MetalDesktopIconUI (Java 2 Platform SE v1.4.2)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalDesktopIconUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.DesktopIconUI
            extended by javax.swing.plaf.basic.BasicDesktopIconUI
                extended by javax.swing.plaf.metal.MetalDesktopIconUI
public class MetalDesktopIconUI
extends BasicDesktopIconUI

Metal desktop icon.

Nested Class Summary
Nested classes inherited from class javax.swing.plaf.basic.BasicDesktopIconUI
BasicDesktopIconUI.MouseInputHandler
Field Summary
Fields inherited from class javax.swing.plaf.basic.BasicDesktopIconUI
desktopIcon, frame
Constructor Summary
MetalDesktopIconUI()
Method Summary
static ComponentUI | createUI(JComponent c) Returns an instance of the UI delegate for the specified component.
Dimension | getMaximumSize(JComponent c) Returns the specified component's maximum size appropriate for the look and feel.
Dimension | getMinimumSize(JComponent c) Returns the specified component's minimum size appropriate for the look and feel.
Dimension | getPreferredSize(JComponent c) Returns the specified component's preferred size appropriate for the look and feel.
protected void | installComponents()
protected void | installDefaults()
protected void | installListeners()
protected void | uninstallComponents()
protected void | uninstallListeners()
Methods inherited from class javax.swing.plaf.basic.BasicDesktopIconUI
createMouseInputListener, deiconize, getInsets, installUI, uninstallDefaults, uninstallUI
Methods inherited from class javax.swing.plaf.ComponentUI
contains, getAccessibleChild, getAccessibleChildrenCount, paint, update
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

MetalDesktopIconUI

public MetalDesktopIconUI()
Method Detail

createUI

public static ComponentUI createUI(JComponent c)
Description copied from class: ComponentUI
Returns an instance of the UI delegate for the specified component. Each subclass must provide its own static createUI method that returns an instance of that UI delegate subclass. If the UI delegate subclass is stateless, it may return an instance that is shared by multiple components. If the UI delegate is stateful, then it should return a new instance per component. The default implementation of this method throws an error, as it should never be invoked.

installDefaults

protected void installDefaults()
Overrides:
installDefaults in class BasicDesktopIconUI

installComponents

protected void installComponents()
Overrides:
installComponents in class BasicDesktopIconUI

uninstallComponents

protected void uninstallComponents()
Overrides:
uninstallComponents in class BasicDesktopIconUI

installListeners

protected void installListeners()
Overrides:
installListeners in class BasicDesktopIconUI

uninstallListeners

protected void uninstallListeners()
Overrides:
uninstallListeners in class BasicDesktopIconUI

getPreferredSize

public Dimension getPreferredSize(JComponent c)
Description copied from class: ComponentUI
Returns the specified component's preferred size appropriate for the look and feel. If null is returned, the preferred size will be calculated by the component's layout manager instead (this is the preferred approach for any component with a specific layout manager installed). The default implementation of this method returns null.

Overrides:
getPreferredSize in class BasicDesktopIconUI

getMinimumSize

public Dimension getMinimumSize(JComponent c)
Description copied from class: ComponentUI
Returns the specified component's minimum size appropriate for the look and feel. If null is returned, the minimum size will be calculated by the component's layout manager instead (this is the preferred approach for any component with a specific layout manager installed). The default implementation of this method invokes getPreferredSize and returns that value.

Overrides:
getMinimumSize in class BasicDesktopIconUI

getMaximumSize

public Dimension getMaximumSize(JComponent c)
Description copied from class: ComponentUI
Returns the specified component's maximum size appropriate for the look and feel. If null is returned, the maximum size will be calculated by the component's layout manager instead (this is the preferred approach for any component with a specific layout manager installed). The default implementation of this method invokes getPreferredSize and returns that value.

Overrides:
getMaximumSize in class BasicDesktopIconUI
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
For further API reference and developer documentation, see Java 2 SDK SE Developer Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.


MetalFileChooserUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalFileChooserUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.FileChooserUI
            extended by javax.swing.plaf.basic.BasicFileChooserUI
                extended by javax.swing.plaf.metal.MetalFileChooserUI
public class MetalFileChooserUI
extends BasicFileChooserUI

Metal L&F implementation of a FileChooser.

Nested Class Summary
protected class | MetalFileChooserUI.DirectoryComboBoxAction Acts when DirectoryComboBox has changed the selected item.
protected class | MetalFileChooserUI.DirectoryComboBoxModel Data model for a type-face selection combo-box.
protected class | MetalFileChooserUI.FileRenderer
protected class | MetalFileChooserUI.FilterComboBoxModel Data model for a type-face selection combo-box.
class | MetalFileChooserUI.FilterComboBoxRenderer Render different type sizes and styles.
protected class | MetalFileChooserUI.SingleClickListener
Nested classes inherited from class javax.swing.plaf.basic.BasicFileChooserUI
BasicFileChooserUI.AcceptAllFileFilter, BasicFileChooserUI.ApproveSelectionAction, BasicFileChooserUI.BasicFileView, BasicFileChooserUI.CancelSelectionAction, BasicFileChooserUI.ChangeToParentDirectoryAction, BasicFileChooserUI.DoubleClickListener, BasicFileChooserUI.GoHomeAction, BasicFileChooserUI.NewFolderAction, BasicFileChooserUI.SelectionListener, BasicFileChooserUI.UpdateAction
Field Summary
Fields inherited from class javax.swing.plaf.basic.BasicFileChooserUI
cancelButtonMnemonic, cancelButtonText, cancelButtonToolTipText, computerIcon, detailsViewIcon, directoryIcon, directoryOpenButtonMnemonic, directoryOpenButtonText, directoryOpenButtonToolTipText, fileIcon, floppyDriveIcon, hardDriveIcon, helpButtonMnemonic, helpButtonText, helpButtonToolTipText, homeFolderIcon, listViewIcon, newFolderIcon, openButtonMnemonic, openButtonText, openButtonToolTipText, saveButtonMnemonic, saveButtonText, saveButtonToolTipText, updateButtonMnemonic, updateButtonText, updateButtonToolTipText, upFolderIcon
Constructor Summary
MetalFileChooserUI(JFileChooser filechooser)
Method Summary
protected void | addControlButtons()
protected ActionMap | createActionMap()
protected JPanel | createDetailsView(JFileChooser fc)
protected MetalFileChooserUI.DirectoryComboBoxModel | createDirectoryComboBoxModel(JFileChooser fc)
protected javax.swing.plaf.metal.MetalFileChooserUI.DirectoryComboBoxRenderer | createDirectoryComboBoxRenderer(JFileChooser fc)
protected MetalFileChooserUI.FilterComboBoxModel | createFilterComboBoxModel()
protected MetalFileChooserUI.FilterComboBoxRenderer | createFilterComboBoxRenderer()
protected JPanel | createList(JFileChooser fc)
ListSelectionListener | createListSelectionListener(JFileChooser fc) Creates a selection listener for the list of files and directories.
PropertyChangeListener | createPropertyChangeListener(JFileChooser fc)
static ComponentUI | createUI(JComponent c) Returns an instance of the UI delegate for the specified component.
void | ensureFileIsVisible(JFileChooser fc, File f)
protected ActionMap | getActionMap()
protected JButton | getApproveButton(JFileChooser fc)
protected JPanel | getBottomPanel()
protected JPanel | getButtonPanel()
String | getDirectoryName()
String | getFileName()
Dimension | getMaximumSize(JComponent c) Returns the maximum size of the JFileChooser.
Dimension | getMinimumSize(JComponent c) Returns the minimum size of the JFileChooser.
Dimension | getPreferredSize(JComponent c) Returns the preferred size of the specified JFileChooser.
void | installComponents(JFileChooser fc)
protected void | installListeners(JFileChooser fc)
protected void | installStrings(JFileChooser fc)
void | installUI(JComponent c) Configures the specified component appropriate for the look and feel.
protected void | removeControlButtons()
void | rescanCurrentDirectory(JFileChooser fc)
void | setDirectoryName(String dirname)
protected void | setDirectorySelected(boolean directorySelected) Property to remember whether a directory is currently selected in the UI.
void | setFileName(String filename)
void | uninstallComponents(JFileChooser fc)
void | uninstallUI(JComponent c) Reverses configuration which was done on the specified component during installUI.
void | valueChanged(ListSelectionEvent e)
Methods inherited from class javax.swing.plaf.basic.BasicFileChooserUI
clearIconCache, createDoubleClickListener, createModel, getAcceptAllFileFilter, getAccessoryPanel, getApproveButtonMnemonic, getApproveButtonText, getApproveButtonToolTipText, getApproveSelectionAction, getCancelSelectionAction, getChangeToParentDirectoryAction, getDialogTitle, getDirectory, getFileChooser, getFileView, getGoHomeAction, getModel, getNewFolderAction, getUpdateAction, installDefaults, installIcons, isDirectorySelected, setDirectory, uninstallDefaults, uninstallIcons, uninstallListeners, uninstallStrings
Methods inherited from class javax.swing.plaf.ComponentUI
contains, getAccessibleChild, getAccessibleChildrenCount, paint, update
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

MetalFileChooserUI

public MetalFileChooserUI(JFileChooser filechooser)
Method Detail

createUI

public static ComponentUI createUI(JComponent c)
Description copied from class: ComponentUI
Returns an instance of the UI delegate for the specified component. Each subclass must provide its own static createUI method that returns an instance of that UI delegate subclass. If the UI delegate subclass is stateless, it may return an instance that is shared by multiple components. If the UI delegate is stateful, then it should return a new instance per component. The default implementation of this method throws an error, as it should never be invoked.

installUI

public void installUI(JComponent c)
Description copied from class: ComponentUI
Configures the specified component appropriate for the look and feel. This method is invoked when the ComponentUI instance is being installed as the UI delegate on the specified component. This method should completely configure the component for the look and feel, including the following:
  1. Install any default property values for color, fonts, borders, icons, opacity, etc. on the component. Whenever possible, property values initialized by the client program should not be overridden.
  2. Install a LayoutManager on the component if necessary.
  3. Create/add any required sub-components to the component.
  4. Create/install event listeners on the component.
  5. Create/install a PropertyChangeListener on the component in order to detect and respond to component property changes appropriately.
  6. Install keyboard UI (mnemonics, traversal, etc.) on the component.
  7. Initialize any appropriate instance data.

Overrides:
installUI in class BasicFileChooserUI

uninstallComponents

public void uninstallComponents(JFileChooser fc)
Overrides:
uninstallComponents in class BasicFileChooserUI

installComponents

public void installComponents(JFileChooser fc)
Overrides:
installComponents in class BasicFileChooserUI

getButtonPanel

protected JPanel getButtonPanel()

getBottomPanel

protected JPanel getBottomPanel()

installStrings

protected void installStrings(JFileChooser fc)
Overrides:
installStrings in class BasicFileChooserUI

installListeners

protected void installListeners(JFileChooser fc)
Overrides:
installListeners in class BasicFileChooserUI

getActionMap

protected ActionMap getActionMap()

createActionMap

protected ActionMap createActionMap()

createList

protected JPanel createList(JFileChooser fc)

createDetailsView

protected JPanel createDetailsView(JFileChooser fc)

createListSelectionListener

public ListSelectionListener createListSelectionListener(JFileChooser fc)
Creates a selection listener for the list of files and directories.

Overrides:
createListSelectionListener in class BasicFileChooserUI
Parameters:
fc - a JFileChooser
Returns:
a ListSelectionListener

uninstallUI

public void uninstallUI(JComponent c)
Description copied from class: ComponentUI
Reverses configuration which was done on the specified component during installUI. This method is invoked when this UIComponent instance is being removed as the UI delegate for the specified component. This method should undo the configuration performed in installUI, being careful to leave the JComponent instance in a clean state (no extraneous listeners, look-and-feel-specific property objects, etc.). This should include the following:
  1. Remove any UI-set borders from the component.
  2. Remove any UI-set layout managers on the component.
  3. Remove any UI-added sub-components from the component.
  4. Remove any UI-added event/property listeners from the component.
  5. Remove any UI-installed keyboard UI from the component.
  6. Nullify any allocated instance data objects to allow for GC.

Overrides:
uninstallUI in class BasicFileChooserUI

getPreferredSize

public Dimension getPreferredSize(JComponent c)
Returns the preferred size of the specified JFileChooser. The preferred size is at least as large, in both height and width, as the preferred size recommended by the file chooser's layout manager.

Overrides:
getPreferredSize in class ComponentUI
Parameters:
c - a JFileChooser
Returns:
a Dimension specifying the preferred width and height of the file chooser
See Also:
JComponent.getPreferredSize(), LayoutManager.preferredLayoutSize(java.awt.Container)

getMinimumSize

public Dimension getMinimumSize(JComponent c)
Returns the minimum size of the JFileChooser.

Overrides:
getMinimumSize in class ComponentUI
Parameters:
c - a JFileChooser
Returns:
a Dimension specifying the minimum width and height of the file chooser
See Also:
JComponent.getMinimumSize(),
LayoutManager.minimumLayoutSize(java.awt.Container),
ComponentUI.getPreferredSize(javax.swing.JComponent)

getMaximumSize

public Dimension getMaximumSize(JComponent c)
Returns the maximum size of the JFileChooser.

Overrides:
getMaximumSize in class ComponentUI
Parameters:
c - a JFileChooser
Returns:
a Dimension specifying the maximum width and height of the file chooser
See Also:
JComponent.getMaximumSize(), LayoutManager2.maximumLayoutSize(java.awt.Container)

createPropertyChangeListener

public PropertyChangeListener createPropertyChangeListener(JFileChooser fc)
Overrides:
createPropertyChangeListener in class BasicFileChooserUI

removeControlButtons

protected void removeControlButtons()

addControlButtons

protected void addControlButtons()

ensureFileIsVisible

public void ensureFileIsVisible(JFileChooser fc,
                                File f)
Overrides:
ensureFileIsVisible in class BasicFileChooserUI

rescanCurrentDirectory

public void rescanCurrentDirectory(JFileChooser fc)
Overrides:
rescanCurrentDirectory in class BasicFileChooserUI

getFileName

public String getFileName()
Overrides:
getFileName in class BasicFileChooserUI

setFileName

public void setFileName(String filename)
Overrides:
setFileName in class BasicFileChooserUI

setDirectorySelected

protected void setDirectorySelected(boolean directorySelected)
Property to remember whether a directory is currently selected in the UI. This is normally called by the UI on a selection event.

Overrides:
setDirectorySelected in class BasicFileChooserUI
Parameters:
directorySelected - if a directory is currently selected.
Since:
1.4

getDirectoryName

public String getDirectoryName()
Overrides:
getDirectoryName in class BasicFileChooserUI

setDirectoryName

public void setDirectoryName(String dirname)
Overrides:
setDirectoryName in class BasicFileChooserUI

createDirectoryComboBoxRenderer

protected javax.swing.plaf.metal.MetalFileChooserUI.DirectoryComboBoxRenderer createDirectoryComboBoxRenderer(JFileChooser fc)

createDirectoryComboBoxModel

protected MetalFileChooserUI.DirectoryComboBoxModel createDirectoryComboBoxModel(JFileChooser fc)

createFilterComboBoxRenderer

protected MetalFileChooserUI.FilterComboBoxRenderer createFilterComboBoxRenderer()

createFilterComboBoxModel

protected MetalFileChooserUI.FilterComboBoxModel createFilterComboBoxModel()

valueChanged

public void valueChanged(ListSelectionEvent e)

getApproveButton

protected JButton getApproveButton(JFileChooser fc)
Overrides:
getApproveButton in class BasicFileChooserUI
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature


MetalFileChooserUI.DirectoryComboBoxAction (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalFileChooserUI.DirectoryComboBoxAction

java.lang.Object
    extended by javax.swing.AbstractAction
        extended by javax.swing.plaf.metal.MetalFileChooserUI.DirectoryComboBoxAction
All Implemented Interfaces:
Action, ActionListener, Cloneable, EventListener, Serializable
Enclosing class:
MetalFileChooserUI
protected class MetalFileChooserUI.DirectoryComboBoxAction
extends AbstractAction

Acts when DirectoryComboBox has changed the selected item.

Field Summary
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SHORT_DESCRIPTION, SMALL_ICON
Constructor Summary
protected MetalFileChooserUI.DirectoryComboBoxAction()
Method Summary
 void actionPerformed(ActionEvent e)
Invoked when an action occurs.
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

MetalFileChooserUI.DirectoryComboBoxAction

protected MetalFileChooserUI.DirectoryComboBoxAction()
Method Detail

actionPerformed

public void actionPerformed(ActionEvent e)
Description copied from interface: ActionListener
Invoked when an action occurs.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MetalFileChooserUI.DirectoryComboBoxModel (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalFileChooserUI.DirectoryComboBoxModel

java.lang.Object
    extended by javax.swing.AbstractListModel
        extended by javax.swing.plaf.metal.MetalFileChooserUI.DirectoryComboBoxModel
All Implemented Interfaces:
ComboBoxModel, ListModel, Serializable
Enclosing class:
MetalFileChooserUI
protected class MetalFileChooserUI.DirectoryComboBoxModel
extends AbstractListModel
implements ComboBoxModel

Data model for a type-face selection combo-box.

Field Summary
Fields inherited from class javax.swing.AbstractListModel
listenerList
Constructor Summary
MetalFileChooserUI.DirectoryComboBoxModel()
Method Summary
int | getDepth(int i)
Object | getElementAt(int index) Returns the value at the specified index.
Object | getSelectedItem() Returns the selected item
int | getSize() Returns the length of the list.
void | setSelectedItem(Object selectedDirectory) Set the selected item.
Methods inherited from class javax.swing.AbstractListModel
addListDataListener, fireContentsChanged, fireIntervalAdded, fireIntervalRemoved, getListDataListeners, getListeners, removeListDataListener
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Methods inherited from interface javax.swing.ListModel
addListDataListener, removeListDataListener

Constructor Detail

MetalFileChooserUI.DirectoryComboBoxModel

public MetalFileChooserUI.DirectoryComboBoxModel()
Method Detail

getDepth

public int getDepth(int i)

setSelectedItem

public void setSelectedItem(Object selectedDirectory)
Description copied from interface: ComboBoxModel
Set the selected item. The implementation of this method should notify all registered ListDataListeners that the contents have changed.

Specified by:
setSelectedItem in interface ComboBoxModel
Parameters:
selectedDirectory - the list object to select or null to clear the selection

getSelectedItem

public Object getSelectedItem()
Description copied from interface: ComboBoxModel
Returns the selected item

Specified by:
getSelectedItem in interface ComboBoxModel
Returns:
The selected item or null if there is no selection

getSize

public int getSize()
Description copied from interface: ListModel
Returns the length of the list.

Specified by:
getSize in interface ListModel
Returns:
the length of the list

getElementAt

public Object getElementAt(int index)
Description copied from interface: ListModel
Returns the value at the specified index.

Specified by:
getElementAt in interface ListModel
Parameters:
index - the requested index
Returns:
the value at index
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MetalFileChooserUI.FileRenderer (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalFileChooserUI.FileRenderer

java.lang.Object
    extended by java.awt.Component
        extended by java.awt.Container
            extended by javax.swing.JComponent
                extended by javax.swing.JLabel
                    extended by javax.swing.DefaultListCellRenderer
                        extended by javax.swing.plaf.metal.MetalFileChooserUI.FileRenderer
All Implemented Interfaces:
Accessible, ImageObserver, ListCellRenderer, MenuContainer, Serializable, SwingConstants
Enclosing class:
MetalFileChooserUI
protected class MetalFileChooserUI.FileRenderer
extends DefaultListCellRenderer

Nested Class Summary
Nested classes inherited from class javax.swing.DefaultListCellRenderer
DefaultListCellRenderer.UIResource
Nested classes inherited from class javax.swing.JLabel
JLabel.AccessibleJLabel
Nested classes inherited from class javax.swing.JComponent
JComponent.AccessibleJComponent
Nested classes inherited from class java.awt.Container
Container.AccessibleAWTContainer
Nested classes inherited from class java.awt.Component
Component.AccessibleAWTComponent, Component.BltBufferStrategy, Component.FlipBufferStrategy
Field Summary
Fields inherited from class javax.swing.DefaultListCellRenderer
noFocusBorder
Fields inherited from class javax.swing.JLabel
labelFor
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
Constructor Summary
protected MetalFileChooserUI.FileRenderer()
Method Summary
 Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
Return a component that has been configured to display the specified value.
Methods inherited from class javax.swing.DefaultListCellRenderer
firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, repaint, repaint, revalidate, validate
Methods inherited from class javax.swing.JLabel
checkHorizontalKey, checkVerticalKey, getAccessibleContext, getDisabledIcon, getDisplayedMnemonic, getDisplayedMnemonicIndex, getHorizontalAlignment, getHorizontalTextPosition, getIcon, getIconTextGap, getLabelFor, getText, getUI, getUIClassID, getVerticalAlignment, getVerticalTextPosition, imageUpdate, paramString, setDisabledIcon, setDisplayedMnemonic, setDisplayedMnemonic, setDisplayedMnemonicIndex, setHorizontalAlignment, setHorizontalTextPosition, setIcon, setIconTextGap, setLabelFor, setText, setUI, setVerticalAlignment, setVerticalTextPosition, updateUI
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addPropertyChangeListener, addPropertyChangeListener, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBorder, getBounds, getClientProperty, getComponentGraphics, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getGraphics, getHeight, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPreferredSize, getPropertyChangeListeners, getPropertyChangeListeners, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isMaximumSizeSet, isMinimumSizeSet, isOpaque, isOptimizedDrawingEnabled, isPaintingTile, isPreferredSizeSet, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removePropertyChangeListener, removePropertyChangeListener, removeVetoableChangeListener, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFont, setForeground, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setFocusCycleRoot, setFocusTraversalKeys, setFocusTraversalPolicy, setLayout, transferFocusBackward, transferFocusDownCycle, validateTree
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getFontMetrics, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMouseWheelListeners, getName, getParent, getPeer, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

MetalFileChooserUI.FileRenderer

protected MetalFileChooserUI.FileRenderer()
Method Detail

getListCellRendererComponent

public Component getListCellRendererComponent(JList list,
                                              Object value,
                                              int index,
                                              boolean isSelected,
                                              boolean cellHasFocus)
Description copied from interface: ListCellRenderer
Return a component that has been configured to display the specified value. That component's paint method is then called to "render" the cell. If it is necessary to compute the dimensions of a list because the list cells do not have a fixed size, this method is called to generate a component on which getPreferredSize can be invoked.

Specified by:
getListCellRendererComponent in interface ListCellRenderer
Overrides:
getListCellRendererComponent in class DefaultListCellRenderer
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MetalFileChooserUI.FilterComboBoxModel (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalFileChooserUI.FilterComboBoxModel

java.lang.Object
    extended by javax.swing.AbstractListModel
        extended by javax.swing.plaf.metal.MetalFileChooserUI.FilterComboBoxModel
All Implemented Interfaces:
ComboBoxModel, EventListener, ListModel, PropertyChangeListener, Serializable
Enclosing class:
MetalFileChooserUI
protected class MetalFileChooserUI.FilterComboBoxModel
extends AbstractListModel
implements ComboBoxModel, PropertyChangeListener

Data model for a type-face selection combo-box.

Field Summary
protected  FileFilter[] filters
Fields inherited from class javax.swing.AbstractListModel
listenerList
Constructor Summary
protected MetalFileChooserUI.FilterComboBoxModel()
Method Summary
Object | getElementAt(int index) Returns the value at the specified index.
Object | getSelectedItem() Returns the selected item
int | getSize() Returns the length of the list.
void | propertyChange(PropertyChangeEvent e) This method gets called when a bound property is changed.
void | setSelectedItem(Object filter) Set the selected item.
Methods inherited from class javax.swing.AbstractListModel
addListDataListener, fireContentsChanged, fireIntervalAdded, fireIntervalRemoved, getListDataListeners, getListeners, removeListDataListener
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Methods inherited from interface javax.swing.ListModel
addListDataListener, removeListDataListener

Field Detail

filters

protected FileFilter[] filters
Constructor Detail

MetalFileChooserUI.FilterComboBoxModel

protected MetalFileChooserUI.FilterComboBoxModel()
Method Detail

propertyChange

public void propertyChange(PropertyChangeEvent e)
Description copied from interface: PropertyChangeListener
This method gets called when a bound property is changed.

Specified by:
propertyChange in interface PropertyChangeListener
Parameters:
e - A PropertyChangeEvent object describing the event source and the property that has changed.

setSelectedItem

public void setSelectedItem(Object filter)
Description copied from interface: ComboBoxModel
Set the selected item. The implementation of this method should notify all registered ListDataListeners that the contents have changed.

Specified by:
setSelectedItem in interface ComboBoxModel
Parameters:
filter - the list object to select or null to clear the selection

getSelectedItem

public Object getSelectedItem()
Description copied from interface: ComboBoxModel
Returns the selected item

Specified by:
getSelectedItem in interface ComboBoxModel
Returns:
The selected item or null if there is no selection

getSize

public int getSize()
Description copied from interface: ListModel
Returns the length of the list.

Specified by:
getSize in interface ListModel
Returns:
the length of the list

getElementAt

public Object getElementAt(int index)
Description copied from interface: ListModel
Returns the value at the specified index.

Specified by:
getElementAt in interface ListModel
Parameters:
index - the requested index
Returns:
the value at index
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MetalFileChooserUI.FilterComboBoxRenderer (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalFileChooserUI.FilterComboBoxRenderer

java.lang.Object
    extended by java.awt.Component
        extended by java.awt.Container
            extended by javax.swing.JComponent
                extended by javax.swing.JLabel
                    extended by javax.swing.DefaultListCellRenderer
                        extended by javax.swing.plaf.metal.MetalFileChooserUI.FilterComboBoxRenderer
All Implemented Interfaces:
Accessible, ImageObserver, ListCellRenderer, MenuContainer, Serializable, SwingConstants
Enclosing class:
MetalFileChooserUI
public class MetalFileChooserUI.FilterComboBoxRenderer
extends DefaultListCellRenderer

Render different type sizes and styles.

Nested Class Summary
Nested classes inherited from class javax.swing.DefaultListCellRenderer
DefaultListCellRenderer.UIResource
Nested classes inherited from class javax.swing.JLabel
JLabel.AccessibleJLabel
Nested classes inherited from class javax.swing.JComponent
JComponent.AccessibleJComponent
Nested classes inherited from class java.awt.Container
Container.AccessibleAWTContainer
Nested classes inherited from class java.awt.Component
Component.AccessibleAWTComponent, Component.BltBufferStrategy, Component.FlipBufferStrategy
Field Summary
Fields inherited from class javax.swing.DefaultListCellRenderer
noFocusBorder
Fields inherited from class javax.swing.JLabel
labelFor
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
Constructor Summary
MetalFileChooserUI.FilterComboBoxRenderer()
Method Summary
 Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
Return a component that has been configured to display the specified value.
Methods inherited from class javax.swing.DefaultListCellRenderer
firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, repaint, repaint, revalidate, validate
Methods inherited from class javax.swing.JLabel
checkHorizontalKey, checkVerticalKey, getAccessibleContext, getDisabledIcon, getDisplayedMnemonic, getDisplayedMnemonicIndex, getHorizontalAlignment, getHorizontalTextPosition, getIcon, getIconTextGap, getLabelFor, getText, getUI, getUIClassID, getVerticalAlignment, getVerticalTextPosition, imageUpdate, paramString, setDisabledIcon, setDisplayedMnemonic, setDisplayedMnemonic, setDisplayedMnemonicIndex, setHorizontalAlignment, setHorizontalTextPosition, setIcon, setIconTextGap, setLabelFor, setText, setUI, setVerticalAlignment, setVerticalTextPosition, updateUI
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addPropertyChangeListener, addPropertyChangeListener, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBorder, getBounds, getClientProperty, getComponentGraphics, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getGraphics, getHeight, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPreferredSize, getPropertyChangeListeners, getPropertyChangeListeners, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isMaximumSizeSet, isMinimumSizeSet, isOpaque, isOptimizedDrawingEnabled, isPaintingTile, isPreferredSizeSet, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removePropertyChangeListener, removePropertyChangeListener, removeVetoableChangeListener, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFont, setForeground, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setFocusCycleRoot, setFocusTraversalKeys, setFocusTraversalPolicy, setLayout, transferFocusBackward, transferFocusDownCycle, validateTree
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getFontMetrics, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMouseWheelListeners, getName, getParent, getPeer, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

MetalFileChooserUI.FilterComboBoxRenderer

public MetalFileChooserUI.FilterComboBoxRenderer()
Method Detail

getListCellRendererComponent

public Component getListCellRendererComponent(JList list,
                                              Object value,
                                              int index,
                                              boolean isSelected,
                                              boolean cellHasFocus)
Description copied from interface: ListCellRenderer
Return a component that has been configured to display the specified value. That component's paint method is then called to "render" the cell. If it is necessary to compute the dimensions of a list because the list cells do not have a fixed size, this method is called to generate a component on which getPreferredSize can be invoked.

Specified by:
getListCellRendererComponent in interface ListCellRenderer
Overrides:
getListCellRendererComponent in class DefaultListCellRenderer
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MetalFileChooserUI.SingleClickListener (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalFileChooserUI.SingleClickListener

java.lang.Object
    extended by java.awt.event.MouseAdapter
        extended by javax.swing.plaf.metal.MetalFileChooserUI.SingleClickListener
All Implemented Interfaces:
EventListener, MouseListener
Enclosing class:
MetalFileChooserUI
protected class MetalFileChooserUI.SingleClickListener
extends MouseAdapter

Constructor Summary
MetalFileChooserUI.SingleClickListener(JList list)
Method Summary
 void mouseClicked(MouseEvent e)
Invoked when the mouse has been clicked on a component.
Methods inherited from class java.awt.event.MouseAdapter
mouseEntered, mouseExited, mousePressed, mouseReleased
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

MetalFileChooserUI.SingleClickListener

public MetalFileChooserUI.SingleClickListener(JList list)
Method Detail

mouseClicked

public void mouseClicked(MouseEvent e)
Description copied from class: MouseAdapter
Invoked when the mouse has been clicked on a component.

Specified by:
mouseClicked in interface MouseListener
Overrides:
mouseClicked in class MouseAdapter
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MetalIconFactory (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalIconFactory

java.lang.Object
    extended by javax.swing.plaf.metal.MetalIconFactory
All Implemented Interfaces:
Serializable
public class MetalIconFactory
extends Object
implements Serializable

Factory object that vends Icons for the JavaTM look and feel (Metal). These icons are used extensively in Metal via the defaults mechanism. While other look and feels often use GIFs for icons, creating icons in code facilitates switching to other themes.

Each method in this class returns either an Icon or null, where null implies that there is no default icon.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Nested Class Summary
static class | MetalIconFactory.FileIcon16 Warning: Serialized objects of this class will not be compatible with future Swing releases.
static class | MetalIconFactory.FolderIcon16 Warning: Serialized objects of this class will not be compatible with future Swing releases.
static class | MetalIconFactory.PaletteCloseIcon Defines an icon for Palette close
static class | MetalIconFactory.TreeControlIcon Warning: Serialized objects of this class will not be compatible with future Swing releases.
static class | MetalIconFactory.TreeFolderIcon Warning: Serialized objects of this class will not be compatible with future Swing releases.
static class | MetalIconFactory.TreeLeafIcon
Field Summary
static boolean | DARK
static boolean | LIGHT
Constructor Summary
MetalIconFactory()
Method Summary
static Icon | getCheckBoxIcon() Returns a checkbox icon.
static Icon | getCheckBoxMenuItemIcon()
static Icon | getFileChooserDetailViewIcon()
static Icon | getFileChooserHomeFolderIcon()
static Icon | getFileChooserListViewIcon()
static Icon | getFileChooserNewFolderIcon()
static Icon | getFileChooserUpFolderIcon()
static Icon | getHorizontalSliderThumbIcon()
static Icon | getInternalFrameAltMaximizeIcon(int size)
static Icon | getInternalFrameCloseIcon(int size)
static Icon | getInternalFrameDefaultMenuIcon()
static Icon | getInternalFrameMaximizeIcon(int size)
static Icon | getInternalFrameMinimizeIcon(int size)
static Icon | getMenuArrowIcon()
static Icon | getMenuItemArrowIcon()
static Icon | getMenuItemCheckIcon() Returns an icon to be used by JCheckBoxMenuItem.
static Icon | getRadioButtonIcon()
static Icon | getRadioButtonMenuItemIcon()
static Icon | getTreeComputerIcon()
static Icon | getTreeControlIcon(boolean isCollapsed)
static Icon | getTreeFloppyDriveIcon()
static Icon | getTreeFolderIcon()
static Icon | getTreeHardDriveIcon()
static Icon | getTreeLeafIcon()
static Icon | getVerticalSliderThumbIcon()
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

DARK

public static final boolean DARK
See Also:
Constant Field Values

LIGHT

public static final boolean LIGHT
See Also:
Constant Field Values
Constructor Detail

MetalIconFactory

public MetalIconFactory()
Method Detail

getFileChooserDetailViewIcon

public static Icon getFileChooserDetailViewIcon()

getFileChooserHomeFolderIcon

public static Icon getFileChooserHomeFolderIcon()

getFileChooserListViewIcon

public static Icon getFileChooserListViewIcon()

getFileChooserNewFolderIcon

public static Icon getFileChooserNewFolderIcon()

getFileChooserUpFolderIcon

public static Icon getFileChooserUpFolderIcon()

getInternalFrameAltMaximizeIcon

public static Icon getInternalFrameAltMaximizeIcon(int size)

getInternalFrameCloseIcon

public static Icon getInternalFrameCloseIcon(int size)

getInternalFrameDefaultMenuIcon

public static Icon getInternalFrameDefaultMenuIcon()

getInternalFrameMaximizeIcon

public static Icon getInternalFrameMaximizeIcon(int size)

getInternalFrameMinimizeIcon

public static Icon getInternalFrameMinimizeIcon(int size)

getRadioButtonIcon

public static Icon getRadioButtonIcon()

getCheckBoxIcon

public static Icon getCheckBoxIcon()
Returns a checkbox icon.

Since:
1.3

getTreeComputerIcon

public static Icon getTreeComputerIcon()

getTreeFloppyDriveIcon

public static Icon getTreeFloppyDriveIcon()

getTreeFolderIcon

public static Icon getTreeFolderIcon()

getTreeHardDriveIcon

public static Icon getTreeHardDriveIcon()

getTreeLeafIcon

public static Icon getTreeLeafIcon()

getTreeControlIcon

public static Icon getTreeControlIcon(boolean isCollapsed)

getMenuArrowIcon

public static Icon getMenuArrowIcon()

getMenuItemCheckIcon

public static Icon getMenuItemCheckIcon()
Returns an icon to be used by JCheckBoxMenuItem.

Returns:
the default icon for check box menu items, or null if no default exists

getMenuItemArrowIcon

public static Icon getMenuItemArrowIcon()

getCheckBoxMenuItemIcon

public static Icon getCheckBoxMenuItemIcon()

getRadioButtonMenuItemIcon

public static Icon getRadioButtonMenuItemIcon()

getHorizontalSliderThumbIcon

public static Icon getHorizontalSliderThumbIcon()

getVerticalSliderThumbIcon

public static Icon getVerticalSliderThumbIcon()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MetalIconFactory.FileIcon16 (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalIconFactory.FileIcon16

java.lang.Object
    extended by javax.swing.plaf.metal.MetalIconFactory.FileIcon16
All Implemented Interfaces:
Icon, Serializable
Direct Known Subclasses:
MetalIconFactory.TreeLeafIcon
Enclosing class:
MetalIconFactory
public static class MetalIconFactory.FileIcon16
extends Object
implements Icon, Serializable

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Constructor Summary
MetalIconFactory.FileIcon16()
Method Summary
int | getAdditionalHeight()
int | getIconHeight() Returns the icon's height.
int | getIconWidth() Returns the icon's width.
int | getShift()
void | paintIcon(Component c, Graphics g, int x, int y) Draw the icon at the specified location.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

MetalIconFactory.FileIcon16

public MetalIconFactory.FileIcon16()
Method Detail

paintIcon

public void paintIcon(Component c,
                      Graphics g,
                      int x,
                      int y)
Description copied from interface: Icon
Draw the icon at the specified location. Icon implementations may use the Component argument to get properties useful for painting, e.g. the foreground or background color.

Specified by:
paintIcon in interface Icon

getShift

public int getShift()

getAdditionalHeight

public int getAdditionalHeight()

getIconWidth

public int getIconWidth()
Description copied from interface: Icon
Returns the icon's width.

Specified by:
getIconWidth in interface Icon
Returns:
an int specifying the fixed width of the icon.

getIconHeight

public int getIconHeight()
Description copied from interface: Icon
Returns the icon's height.

Specified by:
getIconHeight in interface Icon
Returns:
an int specifying the fixed height of the icon.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MetalIconFactory.FolderIcon16 (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalIconFactory.FolderIcon16

java.lang.Object
    extended by javax.swing.plaf.metal.MetalIconFactory.FolderIcon16
All Implemented Interfaces:
Icon, Serializable
Direct Known Subclasses:
MetalIconFactory.TreeFolderIcon
Enclosing class:
MetalIconFactory
public static class MetalIconFactory.FolderIcon16
extends Object
implements Icon, Serializable

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Constructor Summary
MetalIconFactory.FolderIcon16()
Method Summary
int | getAdditionalHeight()
int | getIconHeight() Returns the icon's height.
int | getIconWidth() Returns the icon's width.
int | getShift()
void | paintIcon(Component c, Graphics g, int x, int y) Draw the icon at the specified location.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

MetalIconFactory.FolderIcon16

public MetalIconFactory.FolderIcon16()
Method Detail

paintIcon

public void paintIcon(Component c,
                      Graphics g,
                      int x,
                      int y)
Description copied from interface: Icon
Draw the icon at the specified location. Icon implementations may use the Component argument to get properties useful for painting, e.g. the foreground or background color.

Specified by:
paintIcon in interface Icon

getShift

public int getShift()

getAdditionalHeight

public int getAdditionalHeight()

getIconWidth

public int getIconWidth()
Description copied from interface: Icon
Returns the icon's width.

Specified by:
getIconWidth in interface Icon
Returns:
an int specifying the fixed width of the icon.

getIconHeight

public int getIconHeight()
Description copied from interface: Icon
Returns the icon's height.

Specified by:
getIconHeight in interface Icon
Returns:
an int specifying the fixed height of the icon.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MetalIconFactory.PaletteCloseIcon (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalIconFactory.PaletteCloseIcon

java.lang.Object
    extended by javax.swing.plaf.metal.MetalIconFactory.PaletteCloseIcon
All Implemented Interfaces:
Icon, Serializable, UIResource
Enclosing class:
MetalIconFactory
public static class MetalIconFactory.PaletteCloseIcon
extends Object
implements Icon, UIResource, Serializable

Defines an icon for Palette close

Since:
1.3

Constructor Summary
MetalIconFactory.PaletteCloseIcon()
Method Summary
int | getIconHeight() Returns the icon's height.
int | getIconWidth() Returns the icon's width.
void | paintIcon(Component c, Graphics g, int x, int y) Draw the icon at the specified location.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

MetalIconFactory.PaletteCloseIcon

public MetalIconFactory.PaletteCloseIcon()
Method Detail

paintIcon

public void paintIcon(Component c,
                      Graphics g,
                      int x,
                      int y)
Description copied from interface: Icon
Draw the icon at the specified location. Icon implementations may use the Component argument to get properties useful for painting, e.g. the foreground or background color.

Specified by:
paintIcon in interface Icon

getIconWidth

public int getIconWidth()
Description copied from interface: Icon
Returns the icon's width.

Specified by:
getIconWidth in interface Icon
Returns:
an int specifying the fixed width of the icon.

getIconHeight

public int getIconHeight()
Description copied from interface: Icon
Returns the icon's height.

Specified by:
getIconHeight in interface Icon
Returns:
an int specifying the fixed height of the icon.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MetalIconFactory.TreeControlIcon (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalIconFactory.TreeControlIcon

java.lang.Object
    extended by javax.swing.plaf.metal.MetalIconFactory.TreeControlIcon
All Implemented Interfaces:
Icon, Serializable
Enclosing class:
MetalIconFactory
public static class MetalIconFactory.TreeControlIcon
extends Object
implements Icon, Serializable

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Field Summary
protected  boolean isLight
Constructor Summary
MetalIconFactory.TreeControlIcon(boolean isCollapsed)
Method Summary
int | getIconHeight() Returns the icon's height.
int | getIconWidth() Returns the icon's width.
void | paintIcon(Component c, Graphics g, int x, int y) Draw the icon at the specified location.
void | paintMe(Component c, Graphics g, int x, int y)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

isLight

protected boolean isLight
Constructor Detail

MetalIconFactory.TreeControlIcon

public MetalIconFactory.TreeControlIcon(boolean isCollapsed)
Method Detail

paintIcon

public void paintIcon(Component c,
                      Graphics g,
                      int x,
                      int y)
Description copied from interface: Icon
Draw the icon at the specified location. Icon implementations may use the Component argument to get properties useful for painting, e.g. the foreground or background color.

Specified by:
paintIcon in interface Icon

paintMe

public void paintMe(Component c,
                    Graphics g,
                    int x,
                    int y)

getIconWidth

public int getIconWidth()
Description copied from interface: Icon
Returns the icon's width.

Specified by:
getIconWidth in interface Icon
Returns:
an int specifying the fixed width of the icon.

getIconHeight

public int getIconHeight()
Description copied from interface: Icon
Returns the icon's height.

Specified by:
getIconHeight in interface Icon
Returns:
an int specifying the fixed height of the icon.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MetalIconFactory.TreeFolderIcon (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalIconFactory.TreeFolderIcon

java.lang.Object
    extended by javax.swing.plaf.metal.MetalIconFactory.FolderIcon16
        extended by javax.swing.plaf.metal.MetalIconFactory.TreeFolderIcon
All Implemented Interfaces:
Icon, Serializable
Enclosing class:
MetalIconFactory
public static class MetalIconFactory.TreeFolderIcon
extends MetalIconFactory.FolderIcon16

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Constructor Summary
MetalIconFactory.TreeFolderIcon()
Method Summary
int | getAdditionalHeight()
int | getShift()
Methods inherited from class javax.swing.plaf.metal.MetalIconFactory.FolderIcon16
getIconHeight, getIconWidth, paintIcon
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

MetalIconFactory.TreeFolderIcon

public MetalIconFactory.TreeFolderIcon()
Method Detail

getShift

public int getShift()
Overrides:
getShift in class MetalIconFactory.FolderIcon16

getAdditionalHeight

public int getAdditionalHeight()
Overrides:
getAdditionalHeight in class MetalIconFactory.FolderIcon16
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MetalIconFactory.TreeLeafIcon (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalIconFactory.TreeLeafIcon

java.lang.Object
    extended by javax.swing.plaf.metal.MetalIconFactory.FileIcon16
        extended by javax.swing.plaf.metal.MetalIconFactory.TreeLeafIcon
All Implemented Interfaces:
Icon, Serializable
Enclosing class:
MetalIconFactory
public static class MetalIconFactory.TreeLeafIcon
extends MetalIconFactory.FileIcon16

Constructor Summary
MetalIconFactory.TreeLeafIcon()
Method Summary
int | getAdditionalHeight()
int | getShift()
Methods inherited from class javax.swing.plaf.metal.MetalIconFactory.FileIcon16
getIconHeight, getIconWidth, paintIcon
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

MetalIconFactory.TreeLeafIcon

public MetalIconFactory.TreeLeafIcon()
Method Detail

getShift

public int getShift()
Overrides:
getShift in class MetalIconFactory.FileIcon16

getAdditionalHeight

public int getAdditionalHeight()
Overrides:
getAdditionalHeight in class MetalIconFactory.FileIcon16
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MetalInternalFrameTitlePane (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalInternalFrameTitlePane

java.lang.Object
    extended by java.awt.Component
        extended by java.awt.Container
            extended by javax.swing.JComponent
                extended by javax.swing.plaf.basic.BasicInternalFrameTitlePane
                    extended by javax.swing.plaf.metal.MetalInternalFrameTitlePane
All Implemented Interfaces:
ImageObserver, MenuContainer, Serializable
public class MetalInternalFrameTitlePane
extends BasicInternalFrameTitlePane

Class that manages a JLF title bar

Since:
1.3

Nested Class Summary
Nested classes inherited from class javax.swing.plaf.basic.BasicInternalFrameTitlePane
BasicInternalFrameTitlePane.CloseAction, BasicInternalFrameTitlePane.IconifyAction, BasicInternalFrameTitlePane.MaximizeAction, BasicInternalFrameTitlePane.MoveAction, BasicInternalFrameTitlePane.PropertyChangeHandler, BasicInternalFrameTitlePane.RestoreAction, BasicInternalFrameTitlePane.SizeAction, BasicInternalFrameTitlePane.SystemMenuBar, BasicInternalFrameTitlePane.TitlePaneLayout
Nested classes inherited from class javax.swing.JComponent
JComponent.AccessibleJComponent
Nested classes inherited from class java.awt.Container
Container.AccessibleAWTContainer
Nested classes inherited from class java.awt.Component
Component.AccessibleAWTComponent, Component.BltBufferStrategy, Component.FlipBufferStrategy
Field Summary
protected boolean | isPalette
protected Icon | paletteCloseIcon
protected int | paletteTitleHeight
Fields inherited from class javax.swing.plaf.basic.BasicInternalFrameTitlePane
CLOSE_CMD, closeAction, closeButton, closeIcon, frame, iconButton, iconIcon, ICONIFY_CMD, iconifyAction, maxButton, maxIcon, MAXIMIZE_CMD, maximizeAction, menuBar, minIcon, MOVE_CMD, moveAction, notSelectedTextColor, notSelectedTitleColor, propertyChangeListener, RESTORE_CMD, restoreAction, selectedTextColor, selectedTitleColor, SIZE_CMD, sizeAction, windowMenu
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
Constructor Summary
MetalInternalFrameTitlePane(JInternalFrame f)
Method Summary
void | addNotify() Notifies this component that it now has a parent component.
protected void | addSubComponents() Override the parent's method avoid creating a menu bar.
protected void | addSystemMenuItems(JMenu systemMenu) Override the parent's method to do nothing.
protected void | assembleSystemMenu() Override the parent's method to do nothing.
protected void | createButtons()
protected LayoutManager | createLayout()
protected PropertyChangeListener | createPropertyChangeListener()
protected void | installDefaults()
void | paintComponent(Graphics g) Calls the UI delegate's paint method, if the UI delegate is non-null.
void | paintPalette(Graphics g)
void | setPalette(boolean b)
protected void | showSystemMenu() Override the parent's method to do nothing.
protected void | uninstallDefaults()
Methods inherited from class javax.swing.plaf.basic.BasicInternalFrameTitlePane
createActions, createSystemMenu, createSystemMenuBar, enableActions, getTitle, installListeners, installTitlePane, paintTitleBackground, postClosingEvent, setButtonIcons, uninstallListeners
Methods inherited from class javax.swing.JComponent
addAncestorListener, addPropertyChangeListener, addPropertyChangeListener, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getAccessibleContext, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBorder, getBounds, getClientProperty, getComponentGraphics, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getGraphics, getHeight, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPreferredSize, getPropertyChangeListeners, getPropertyChangeListeners, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getUIClassID, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isMaximumSizeSet, isMinimumSizeSet, isOpaque, isOptimizedDrawingEnabled, isPaintingTile, isPreferredSizeSet, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintImmediately, paintImmediately, paramString, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removePropertyChangeListener, removePropertyChangeListener, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFont, setForeground, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update, updateUI
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setFocusCycleRoot, setFocusTraversalKeys, setFocusTraversalPolicy, setLayout, transferFocusBackward, transferFocusDownCycle, validate, validateTree
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getFontMetrics, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMouseWheelListeners, getName, getParent, getPeer, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

isPalette

protected boolean isPalette

paletteCloseIcon

protected Icon paletteCloseIcon

paletteTitleHeight

protected int paletteTitleHeight
Constructor Detail

MetalInternalFrameTitlePane

public MetalInternalFrameTitlePane(JInternalFrame f)
Method Detail

addNotify

public void addNotify()
Description copied from class: JComponent
Notifies this component that it now has a parent component. When this method is invoked, the chain of parent components is set up with KeyboardAction event listeners.

Overrides:
addNotify in class JComponent
See Also:
JComponent.registerKeyboardAction(java.awt.event.ActionListener, java.lang.String, javax.swing.KeyStroke, int)

installDefaults

protected void installDefaults()
Overrides:
installDefaults in class BasicInternalFrameTitlePane

uninstallDefaults

protected void uninstallDefaults()
Overrides:
uninstallDefaults in class BasicInternalFrameTitlePane

createButtons

protected void createButtons()
Overrides:
createButtons in class BasicInternalFrameTitlePane

assembleSystemMenu

protected void assembleSystemMenu()
Override the parent's method to do nothing. Metal frames do not have system menus.

Overrides:
assembleSystemMenu in class BasicInternalFrameTitlePane

addSystemMenuItems

protected void addSystemMenuItems(JMenu systemMenu)
Override the parent's method to do nothing. Metal frames do not have system menus.

Overrides:
addSystemMenuItems in class BasicInternalFrameTitlePane

showSystemMenu

protected void showSystemMenu()
Override the parent's method to do nothing. Metal frames do not have system menus.

Overrides:
showSystemMenu in class BasicInternalFrameTitlePane

addSubComponents

protected void addSubComponents()
Override the parent's method avoid creating a menu bar. Metal frames do not have system menus.

Overrides:
addSubComponents in class BasicInternalFrameTitlePane

createPropertyChangeListener

protected PropertyChangeListener createPropertyChangeListener()
Overrides:
createPropertyChangeListener in class BasicInternalFrameTitlePane

createLayout

protected LayoutManager createLayout()
Overrides:
createLayout in class BasicInternalFrameTitlePane

paintPalette

public void paintPalette(Graphics g)

paintComponent

public void paintComponent(Graphics g)
Description copied from class: JComponent
Calls the UI delegate's paint method, if the UI delegate is non-null. We pass the delegate a copy of the Graphics object to protect the rest of the paint code from irrevocable changes (for example, Graphics.translate).

If you override this in a subclass you should not make permanent changes to the passed in Graphics. For example, you should not alter the clip Rectangle or modify the transform. If you need to do these operations you may find it easier to create a new Graphics from the passed in Graphics and manipulate it. Further, if you do not invoker super's implementation you must honor the opaque property, that is if this component is opaque, you must completely fill in the background in a non-opaque color. If you do not honor the opaque property you will likely see visual artifacts.

Overrides:
paintComponent in class BasicInternalFrameTitlePane

setPalette

public void setPalette(boolean b)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MetalInternalFrameUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalInternalFrameUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.InternalFrameUI
            extended by javax.swing.plaf.basic.BasicInternalFrameUI
                extended by javax.swing.plaf.metal.MetalInternalFrameUI
public class MetalInternalFrameUI
extends BasicInternalFrameUI

Metal implementation of JInternalFrame.

Nested Class Summary
Nested classes inherited from class javax.swing.plaf.basic.BasicInternalFrameUI
BasicInternalFrameUI.BasicInternalFrameListener, BasicInternalFrameUI.BorderListener, BasicInternalFrameUI.ComponentHandler, BasicInternalFrameUI.GlassPaneDispatcher, BasicInternalFrameUI.InternalFrameLayout, BasicInternalFrameUI.InternalFramePropertyChangeListener
Field Summary
protected static String IS_PALETTE
Fields inherited from class javax.swing.plaf.basic.BasicInternalFrameUI
borderListener, componentListener, eastPane, frame, glassPaneDispatcher, internalFrameLayout, northPane, openMenuKey, propertyChangeListener, southPane, westPane
Constructor Summary
MetalInternalFrameUI(JInternalFrame b)
Method Summary
protected JComponent | createNorthPane(JInternalFrame w)
static ComponentUI | createUI(JComponent c) Returns an instance of the UI delegate for the specified component.
protected void | installKeyboardActions()
protected void | installListeners()
void | installUI(JComponent c) Configures the specified component appropriate for the look and feel.
void | setPalette(boolean isPalette)
protected void | uninstallComponents()
protected void | uninstallKeyboardActions()
protected void | uninstallListeners()
void | uninstallUI(JComponent c) Reverses configuration which was done on the specified component during installUI.
Methods inherited from class javax.swing.plaf.basic.BasicInternalFrameUI
activateFrame, closeFrame, createBorderListener, createComponentListener, createDesktopManager, createEastPane, createGlassPaneDispatcher, createInternalFrameListener, createLayoutManager, createPropertyChangeListener, createSouthPane, createWestPane, deactivateFrame, deiconifyFrame, deinstallMouseHandlers, getDesktopManager, getEastPane, getMaximumSize, getMinimumSize, getNorthPane, getPreferredSize, getSouthPane, getWestPane, iconifyFrame, installComponents, installDefaults, installMouseHandlers, isKeyBindingActive, isKeyBindingRegistered, maximizeFrame, minimizeFrame, replacePane, setEastPane, setKeyBindingActive, setKeyBindingRegistered, setNorthPane, setSouthPane, setupMenuCloseKey, setupMenuOpenKey, setWestPane, uninstallDefaults
Methods inherited from class javax.swing.plaf.ComponentUI
contains, getAccessibleChild, getAccessibleChildrenCount, paint, update
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

IS_PALETTE

protected static String IS_PALETTE
Constructor Detail

MetalInternalFrameUI

public MetalInternalFrameUI(JInternalFrame b)
Method Detail

createUI

public static ComponentUI createUI(JComponent c)
Description copied from class: ComponentUI
Returns an instance of the UI delegate for the specified component. Each subclass must provide its own static createUI method that returns an instance of that UI delegate subclass. If the UI delegate subclass is stateless, it may return an instance that is shared by multiple components. If the UI delegate is stateful, then it should return a new instance per component. The default implementation of this method throws an error, as it should never be invoked.

installUI

public void installUI(JComponent c)
Description copied from class: ComponentUI
Configures the specified component appropriate for the look and feel. This method is invoked when the ComponentUI instance is being installed as the UI delegate on the specified component. This method should completely configure the component for the look and feel, including the following:
  1. Install any default property values for color, fonts, borders, icons, opacity, etc. on the component. Whenever possible, property values initialized by the client program should not be overridden.
  2. Install a LayoutManager on the component if necessary.
  3. Create/add any required sub-components to the component.
  4. Create/install event listeners on the component.
  5. Create/install a PropertyChangeListener on the component in order to detect and respond to component property changes appropriately.
  6. Install keyboard UI (mnemonics, traversal, etc.) on the component.
  7. Initialize any appropriate instance data.

Overrides:
installUI in class BasicInternalFrameUI

uninstallUI

public void uninstallUI(JComponent c)
Description copied from class: ComponentUI
Reverses configuration which was done on the specified component during installUI. This method is invoked when this UIComponent instance is being removed as the UI delegate for the specified component. This method should undo the configuration performed in installUI, being careful to leave the JComponent instance in a clean state (no extraneous listeners, look-and-feel-specific property objects, etc.). This should include the following:
  1. Remove any UI-set borders from the component.
  2. Remove any UI-set layout managers on the component.
  3. Remove any UI-added sub-components from the component.
  4. Remove any UI-added event/property listeners from the component.
  5. Remove any UI-installed keyboard UI from the component.
  6. Nullify any allocated instance data objects to allow for GC.

Overrides:
uninstallUI in class BasicInternalFrameUI

installListeners

protected void installListeners()
Overrides:
installListeners in class BasicInternalFrameUI

uninstallListeners

protected void uninstallListeners()
Overrides:
uninstallListeners in class BasicInternalFrameUI

installKeyboardActions

protected void installKeyboardActions()
Overrides:
installKeyboardActions in class BasicInternalFrameUI

uninstallKeyboardActions

protected void uninstallKeyboardActions()
Overrides:
uninstallKeyboardActions in class BasicInternalFrameUI

uninstallComponents

protected void uninstallComponents()
Overrides:
uninstallComponents in class BasicInternalFrameUI

createNorthPane

protected JComponent createNorthPane(JInternalFrame w)
Overrides:
createNorthPane in class BasicInternalFrameUI

setPalette

public void setPalette(boolean isPalette)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MetalLabelUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalLabelUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.LabelUI
            extended by javax.swing.plaf.basic.BasicLabelUI
                extended by javax.swing.plaf.metal.MetalLabelUI
All Implemented Interfaces:
EventListener, PropertyChangeListener
public class MetalLabelUI
extends BasicLabelUI

A Windows L&F implementation of LabelUI. This implementation is completely static, i.e. there's only one UIView implementation that's shared by all JLabel objects.

Field Summary
protected static MetalLabelUI metalLabelUI
Fields inherited from class javax.swing.plaf.basic.BasicLabelUI
labelUI
Constructor Summary
MetalLabelUI()
Method Summary
static ComponentUI | createUI(JComponent c) Returns an instance of the UI delegate for the specified component.
protected void | paintDisabledText(JLabel l, Graphics g, String s, int textX, int textY) Just paint the text gray (Label.disabledForeground) rather than in the labels foreground color.
Methods inherited from class javax.swing.plaf.basic.BasicLabelUI
getMaximumSize, getMinimumSize, getPreferredSize, installComponents, installDefaults, installKeyboardActions, installListeners, installUI, layoutCL, paint, paintEnabledText, propertyChange, uninstallComponents, uninstallDefaults, uninstallKeyboardActions, uninstallListeners, uninstallUI
Methods inherited from class javax.swing.plaf.ComponentUI
contains, getAccessibleChild, getAccessibleChildrenCount, update
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

metalLabelUI

protected static MetalLabelUI metalLabelUI
Constructor Detail

MetalLabelUI

public MetalLabelUI()
Method Detail

createUI

public static ComponentUI createUI(JComponent c)
Description copied from class: ComponentUI
Returns an instance of the UI delegate for the specified component. Each subclass must provide its own static createUI method that returns an instance of that UI delegate subclass. If the UI delegate subclass is stateless, it may return an instance that is shared by multiple components. If the UI delegate is stateful, then it should return a new instance per component. The default implementation of this method throws an error, as it should never be invoked.

paintDisabledText

protected void paintDisabledText(JLabel l,
                                 Graphics g,
                                 String s,
                                 int textX,
                                 int textY)
Just paint the text gray (Label.disabledForeground) rather than in the labels foreground color.

Overrides:
paintDisabledText in class BasicLabelUI
See Also:
BasicLabelUI.paint(java.awt.Graphics, javax.swing.JComponent), BasicLabelUI.paintEnabledText(javax.swing.JLabel, java.awt.Graphics, java.lang.String, int, int)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MetalLookAndFeel (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalLookAndFeel

java.lang.Object
    extended by javax.swing.LookAndFeel
        extended by javax.swing.plaf.basic.BasicLookAndFeel
            extended by javax.swing.plaf.metal.MetalLookAndFeel
All Implemented Interfaces:
Serializable
public class MetalLookAndFeel
extends BasicLookAndFeel

Implements the Java look and feel (codename: Metal).

For the keyboard keys defined for each component in this look and feel, see Component Keystroke Actions for the Java Look and Feel.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Constructor Summary
MetalLookAndFeel()
Method Summary
protected void | createDefaultTheme()
static ColorUIResource | getAcceleratorForeground()
static ColorUIResource | getAcceleratorSelectedForeground()
static ColorUIResource | getBlack()
static ColorUIResource | getControl()
static ColorUIResource | getControlDarkShadow()
static ColorUIResource | getControlDisabled()
static ColorUIResource | getControlHighlight()
static ColorUIResource | getControlInfo()
static ColorUIResource | getControlShadow()
static ColorUIResource | getControlTextColor()
static FontUIResource | getControlTextFont()
UIDefaults | getDefaults() This method is called once by UIManager.setLookAndFeel to create the look and feel specific defaults table.
String | getDescription() Return a one line description of this look and feel implementation, e.g.
static ColorUIResource | getDesktopColor()
static ColorUIResource | getFocusColor()
static ColorUIResource | getHighlightedTextColor()
String | getID() Return a string that identifies this look and feel.
static ColorUIResource | getInactiveControlTextColor()
static ColorUIResource | getInactiveSystemTextColor()
static ColorUIResource | getMenuBackground()
static ColorUIResource | getMenuDisabledForeground()
static ColorUIResource | getMenuForeground()
static ColorUIResource | getMenuSelectedBackground()
static ColorUIResource | getMenuSelectedForeground()
static FontUIResource | getMenuTextFont()
String | getName() Return a short string that identifies this look and feel, e.g.
static ColorUIResource | getPrimaryControl()
static ColorUIResource | getPrimaryControlDarkShadow()
static ColorUIResource | getPrimaryControlHighlight()
static ColorUIResource | getPrimaryControlInfo()
static ColorUIResource | getPrimaryControlShadow()
static ColorUIResource | getSeparatorBackground()
static ColorUIResource | getSeparatorForeground()
static FontUIResource | getSubTextFont()
boolean | getSupportsWindowDecorations() Returns true if the LookAndFeel returned RootPaneUI instances support providing Window decorations in a JRootPane.
static ColorUIResource | getSystemTextColor()
static FontUIResource | getSystemTextFont()
static ColorUIResource | getTextHighlightColor()
static ColorUIResource | getUserTextColor()
static FontUIResource | getUserTextFont()
static ColorUIResource | getWhite()
static ColorUIResource | getWindowBackground()
static ColorUIResource | getWindowTitleBackground()
static FontUIResource | getWindowTitleFont()
static ColorUIResource | getWindowTitleForeground()
static ColorUIResource | getWindowTitleInactiveBackground()
static ColorUIResource | getWindowTitleInactiveForeground()
protected void | initClassDefaults(UIDefaults table) Creates the mapping from UI class IDs to ComponentUI classes, putting the ID-ComponentUI pairs in the passed-in defaults table.
protected void | initComponentDefaults(UIDefaults table)
protected void | initSystemColorDefaults(UIDefaults table) Load the SystemColors into the defaults table.
boolean | isNativeLookAndFeel() If the underlying platform has a "native" look and feel, and this is an implementation of it, return true.
boolean | isSupportedLookAndFeel() Return true if the underlying platform supports and or permits this look and feel.
void | provideErrorFeedback(Component component) Invoked when the user attempts an invalid operation, such as pasting into an uneditable JTextField that has focus.
static void | setCurrentTheme(MetalTheme theme)
Methods inherited from class javax.swing.plaf.basic.BasicLookAndFeel
createAudioAction, getAudioActionMap, loadSystemColors, playSound
Methods inherited from class javax.swing.LookAndFeel
getDesktopPropertyValue, initialize, installBorder, installColors, installColorsAndFont, loadKeyBindings, makeComponentInputMap, makeIcon, makeInputMap, makeKeyBindings, toString, uninitialize, uninstallBorder
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

MetalLookAndFeel

public MetalLookAndFeel()
Method Detail

getName

public String getName()
Description copied from class: LookAndFeel
Return a short string that identifies this look and feel, e.g. "CDE/Motif". This string should be appropriate for a menu item. Distinct look and feels should have different names, e.g. a subclass of MotifLookAndFeel that changes the way a few components are rendered should be called "CDE/Motif My Way"; something that would be useful to a user trying to select a L&F from a list of names.

Specified by:
getName in class LookAndFeel

getID

public String getID()
Description copied from class: LookAndFeel
Return a string that identifies this look and feel. This string will be used by applications/services that want to recognize well known look and feel implementations. Presently the well known names are "Motif", "Windows", "Mac", "Metal". Note that a LookAndFeel derived from a well known superclass that doesn't make any fundamental changes to the look or feel shouldn't override this method.

Specified by:
getID in class LookAndFeel

getDescription

public String getDescription()
Description copied from class: LookAndFeel
Return a one line description of this look and feel implementation, e.g. "The CDE/Motif Look and Feel". This string is intended for the user, e.g. in the title of a window or in a ToolTip message.

Specified by:
getDescription in class LookAndFeel

isNativeLookAndFeel

public boolean isNativeLookAndFeel()
Description copied from class: LookAndFeel
If the underlying platform has a "native" look and feel, and this is an implementation of it, return true. For example a CDE/Motif look and implementation would return true when the underlying platform was Solaris.

Specified by:
isNativeLookAndFeel in class LookAndFeel

isSupportedLookAndFeel

public boolean isSupportedLookAndFeel()
Description copied from class: LookAndFeel
Return true if the underlying platform supports and or permits this look and feel. This method returns false if the look and feel depends on special resources or legal agreements that aren't defined for the current platform.

Specified by:
isSupportedLookAndFeel in class LookAndFeel
See Also:
UIManager.setLookAndFeel(javax.swing.LookAndFeel)

getSupportsWindowDecorations

public boolean getSupportsWindowDecorations()
Returns true if the LookAndFeel returned RootPaneUI instances support providing Window decorations in a JRootPane.

This implementation returns true, since it does support providing these border and window title pane decorations.

Overrides:
getSupportsWindowDecorations in class LookAndFeel
Returns:
True if the RootPaneUI instances created support client side decorations
Since:
1.4
See Also:
JDialog.setDefaultLookAndFeelDecorated(boolean),
JFrame.setDefaultLookAndFeelDecorated(boolean),
JRootPane.setWindowDecorationStyle(int)

initClassDefaults

protected void initClassDefaults(UIDefaults table)
Creates the mapping from UI class IDs to ComponentUI classes, putting the ID-ComponentUI pairs in the passed-in defaults table. Each JComponent class specifies its own UI class ID string. For example, JButton has the UI class ID "ButtonUI", which this method maps to "javax.swing.plaf.metal.MetalButtonUI".

Overrides:
initClassDefaults in class BasicLookAndFeel
See Also:
BasicLookAndFeel.getDefaults(), JComponent.getUIClassID()

initSystemColorDefaults

protected void initSystemColorDefaults(UIDefaults table)
Load the SystemColors into the defaults table. The keys for SystemColor defaults are the same as the names of the public fields in SystemColor.

Overrides:
initSystemColorDefaults in class BasicLookAndFeel

initComponentDefaults

protected void initComponentDefaults(UIDefaults table)
Overrides:
initComponentDefaults in class BasicLookAndFeel

createDefaultTheme

protected void createDefaultTheme()

getDefaults

public UIDefaults getDefaults()
Description copied from class: LookAndFeel
This method is called once by UIManager.setLookAndFeel to create the look and feel specific defaults table. Other applications, for example an application builder, may also call this method.

Overrides:
getDefaults in class BasicLookAndFeel

provideErrorFeedback

public void provideErrorFeedback(Component component)

Invoked when the user attempts an invalid operation, such as pasting into an uneditable JTextField that has focus.

If the user has enabled visual error indication on the desktop, this method will flash the caption bar of the active window. The user can also set the property awt.visualbell=true to achieve the same results.

Overrides:
provideErrorFeedback in class LookAndFeel
Parameters:
component - Component the error occured in, may be null indicating the error condition is not directly associated with a Component.
See Also:
LookAndFeel.provideErrorFeedback(java.awt.Component)

setCurrentTheme

public static void setCurrentTheme(MetalTheme theme)

getControlTextFont

public static FontUIResource getControlTextFont()

getSystemTextFont

public static FontUIResource getSystemTextFont()

getUserTextFont

public static FontUIResource getUserTextFont()

getMenuTextFont

public static FontUIResource getMenuTextFont()

getWindowTitleFont

public static FontUIResource getWindowTitleFont()

getSubTextFont

public static FontUIResource getSubTextFont()

getDesktopColor

public static ColorUIResource getDesktopColor()

getFocusColor

public static ColorUIResource getFocusColor()

getWhite

public static ColorUIResource getWhite()

getBlack

public static ColorUIResource getBlack()

getControl

public static ColorUIResource getControl()

getControlShadow

public static ColorUIResource getControlShadow()

getControlDarkShadow

public static ColorUIResource getControlDarkShadow()

getControlInfo

public static ColorUIResource getControlInfo()

getControlHighlight

public static ColorUIResource getControlHighlight()

getControlDisabled

public static ColorUIResource getControlDisabled()

getPrimaryControl

public static ColorUIResource getPrimaryControl()

getPrimaryControlShadow

public static ColorUIResource getPrimaryControlShadow()

getPrimaryControlDarkShadow

public static ColorUIResource getPrimaryControlDarkShadow()

getPrimaryControlInfo

public static ColorUIResource getPrimaryControlInfo()

getPrimaryControlHighlight

public static ColorUIResource getPrimaryControlHighlight()

getSystemTextColor

public static ColorUIResource getSystemTextColor()

getControlTextColor

public static ColorUIResource getControlTextColor()

getInactiveControlTextColor

public static ColorUIResource getInactiveControlTextColor()

getInactiveSystemTextColor

public static ColorUIResource getInactiveSystemTextColor()

getUserTextColor

public static ColorUIResource getUserTextColor()

getTextHighlightColor

public static ColorUIResource getTextHighlightColor()

getHighlightedTextColor

public static ColorUIResource getHighlightedTextColor()

getWindowBackground

public static ColorUIResource getWindowBackground()

getWindowTitleBackground

public static ColorUIResource getWindowTitleBackground()

getWindowTitleForeground

public static ColorUIResource getWindowTitleForeground()

getWindowTitleInactiveBackground

public static ColorUIResource getWindowTitleInactiveBackground()

getWindowTitleInactiveForeground

public static ColorUIResource getWindowTitleInactiveForeground()

getMenuBackground

public static ColorUIResource getMenuBackground()

getMenuForeground

public static ColorUIResource getMenuForeground()

getMenuSelectedBackground

public static ColorUIResource getMenuSelectedBackground()

getMenuSelectedForeground

public static ColorUIResource getMenuSelectedForeground()

getMenuDisabledForeground

public static ColorUIResource getMenuDisabledForeground()

getSeparatorBackground

public static ColorUIResource getSeparatorBackground()

getSeparatorForeground

public static ColorUIResource getSeparatorForeground()

getAcceleratorForeground

public static ColorUIResource getAcceleratorForeground()

getAcceleratorSelectedForeground

public static ColorUIResource getAcceleratorSelectedForeground()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MetalPopupMenuSeparatorUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalPopupMenuSeparatorUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.SeparatorUI
            extended by javax.swing.plaf.basic.BasicSeparatorUI
                extended by javax.swing.plaf.metal.MetalSeparatorUI
                    extended by javax.swing.plaf.metal.MetalPopupMenuSeparatorUI
public class MetalPopupMenuSeparatorUI
extends MetalSeparatorUI

A Metal L&F implementation of PopupMenuSeparatorUI. This implementation is a "combined" view/controller.

Field Summary
Fields inherited from class javax.swing.plaf.basic.BasicSeparatorUI
highlight, shadow
Constructor Summary
MetalPopupMenuSeparatorUI()
Method Summary
static ComponentUI | createUI(JComponent c) Returns an instance of the UI delegate for the specified component.
Dimension | getPreferredSize(JComponent c) Returns the specified component's preferred size appropriate for the look and feel.
void | paint(Graphics g, JComponent c) Paints the specified component appropriate for the look and feel.
Methods inherited from class javax.swing.plaf.metal.MetalSeparatorUI
installDefaults
Methods inherited from class javax.swing.plaf.basic.BasicSeparatorUI
getMaximumSize, getMinimumSize, installListeners, installUI, uninstallDefaults, uninstallListeners, uninstallUI
Methods inherited from class javax.swing.plaf.ComponentUI
contains, getAccessibleChild, getAccessibleChildrenCount, update
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

MetalPopupMenuSeparatorUI

public MetalPopupMenuSeparatorUI()
Method Detail

createUI

public static ComponentUI createUI(JComponent c)
Description copied from class: ComponentUI
Returns an instance of the UI delegate for the specified component. Each subclass must provide its own static createUI method that returns an instance of that UI delegate subclass. If the UI delegate subclass is stateless, it may return an instance that is shared by multiple components. If the UI delegate is stateful, then it should return a new instance per component. The default implementation of this method throws an error, as it should never be invoked.

paint

public void paint(Graphics g,
                  JComponent c)
Description copied from class: ComponentUI
Paints the specified component appropriate for the look and feel. This method is invoked from the ComponentUI.update method when the specified component is being painted. Subclasses should override this method and use the specified Graphics object to render the content of the component.

Overrides:
paint in class MetalSeparatorUI

getPreferredSize

public Dimension getPreferredSize(JComponent c)
Description copied from class: ComponentUI
Returns the specified component's preferred size appropriate for the look and feel. If null is returned, the preferred size will be calculated by the component's layout manager instead (this is the preferred approach for any component with a specific layout manager installed). The default implementation of this method returns null.

Overrides:
getPreferredSize in class MetalSeparatorUI
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MetalProgressBarUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalProgressBarUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.ProgressBarUI
            extended by javax.swing.plaf.basic.BasicProgressBarUI
                extended by javax.swing.plaf.metal.MetalProgressBarUI
public class MetalProgressBarUI
extends BasicProgressBarUI

The Metal implementation of ProgressBarUI.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Nested Class Summary
Nested classes inherited from class javax.swing.plaf.basic.BasicProgressBarUI
BasicProgressBarUI.ChangeHandler
Field Summary
Fields inherited from class javax.swing.plaf.basic.BasicProgressBarUI
changeListener, progressBar
Constructor Summary
MetalProgressBarUI()
Method Summary
static ComponentUI | createUI(JComponent c) Returns an instance of the UI delegate for the specified component.
void | paintDeterminate(Graphics g, JComponent c) Draws a bit of special highlighting on the progress bar.
void | paintIndeterminate(Graphics g, JComponent c) Draws a bit of special highlighting on the progress bar and bouncing box.
Methods inherited from class javax.swing.plaf.basic.BasicProgressBarUI
getAmountFull, getAnimationIndex, getBox, getCellLength, getCellSpacing, getMaximumSize, getMinimumSize, getPreferredInnerHorizontal, getPreferredInnerVertical, getPreferredSize, getSelectionBackground, getSelectionForeground, getStringPlacement, incrementAnimationIndex, installDefaults, installListeners, installUI, paint, paintString, setAnimationIndex, setCellLength, setCellSpacing, startAnimationTimer, stopAnimationTimer, uninstallDefaults, uninstallListeners, uninstallUI
Methods inherited from class javax.swing.plaf.ComponentUI
contains, getAccessibleChild, getAccessibleChildrenCount, update
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

MetalProgressBarUI

public MetalProgressBarUI()
Method Detail

createUI

public static ComponentUI createUI(JComponent c)
Description copied from class: ComponentUI
Returns an instance of the UI delegate for the specified component. Each subclass must provide its own static createUI method that returns an instance of that UI delegate subclass. If the UI delegate subclass is stateless, it may return an instance that is shared by multiple components. If the UI delegate is stateful, then it should return a new instance per component. The default implementation of this method throws an error, as it should never be invoked.

paintDeterminate

public void paintDeterminate(Graphics g,
                             JComponent c)
Draws a bit of special highlighting on the progress bar. The core painting is deferred to the BasicProgressBar's paintDeterminate method.

Overrides:
paintDeterminate in class BasicProgressBarUI
See Also:
BasicProgressBarUI.paintIndeterminate(java.awt.Graphics, javax.swing.JComponent)

paintIndeterminate

public void paintIndeterminate(Graphics g,
                               JComponent c)
Draws a bit of special highlighting on the progress bar and bouncing box. The core painting is deferred to the BasicProgressBar's paintIndeterminate method.

Overrides:
paintIndeterminate in class BasicProgressBarUI
See Also:
BasicProgressBarUI.paintDeterminate(java.awt.Graphics, javax.swing.JComponent)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MetalRadioButtonUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalRadioButtonUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.ButtonUI
            extended by javax.swing.plaf.basic.BasicButtonUI
                extended by javax.swing.plaf.basic.BasicToggleButtonUI
                    extended by javax.swing.plaf.basic.BasicRadioButtonUI
                        extended by javax.swing.plaf.metal.MetalRadioButtonUI
Direct Known Subclasses:
MetalCheckBoxUI
public class MetalRadioButtonUI
extends BasicRadioButtonUI

RadioButtonUI implementation for MetalRadioButtonUI

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Field Summary
protected Color | disabledTextColor
protected Color | focusColor
protected Color | selectColor
Fields inherited from class javax.swing.plaf.basic.BasicRadioButtonUI
icon
Fields inherited from class javax.swing.plaf.basic.BasicButtonUI
defaultTextIconGap, defaultTextShiftOffset
Constructor Summary
MetalRadioButtonUI()
Method Summary
static ComponentUI | createUI(JComponent c) Returns an instance of the UI delegate for the specified component.
protected Color | getDisabledTextColor()
protected Color | getFocusColor()
protected Color | getSelectColor()
void | installDefaults(AbstractButton b)
void | paint(Graphics g, JComponent c) paint the radio button
protected void | paintFocus(Graphics g, Rectangle t, Dimension d)
protected void | uninstallDefaults(AbstractButton b)
Methods inherited from class javax.swing.plaf.basic.BasicRadioButtonUI
getDefaultIcon, getPreferredSize, getPropertyPrefix
Methods inherited from class javax.swing.plaf.basic.BasicToggleButtonUI
getTextShiftOffset, paintIcon
Methods inherited from class javax.swing.plaf.basic.BasicButtonUI
clearTextShiftOffset, createButtonListener, getDefaultTextIconGap, getMaximumSize, getMinimumSize, installKeyboardActions, installListeners, installUI, paintButtonPressed, paintFocus, paintIcon, paintText, paintText, setTextShiftOffset, uninstallKeyboardActions, uninstallListeners, uninstallUI
Methods inherited from class javax.swing.plaf.ComponentUI
contains, getAccessibleChild, getAccessibleChildrenCount, update
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

focusColor

protected Color focusColor

selectColor

protected Color selectColor

disabledTextColor

protected Color disabledTextColor
Constructor Detail

MetalRadioButtonUI

public MetalRadioButtonUI()
Method Detail

createUI

public static ComponentUI createUI(JComponent c)
Description copied from class: ComponentUI
Returns an instance of the UI delegate for the specified component. Each subclass must provide its own static createUI method that returns an instance of that UI delegate subclass. If the UI delegate subclass is stateless, it may return an instance that is shared by multiple components. If the UI delegate is stateful, then it should return a new instance per component. The default implementation of this method throws an error, as it should never be invoked.

installDefaults

public void installDefaults(AbstractButton b)
Overrides:
installDefaults in class BasicRadioButtonUI

uninstallDefaults

protected void uninstallDefaults(AbstractButton b)
Overrides:
uninstallDefaults in class BasicRadioButtonUI

getSelectColor

protected Color getSelectColor()

getDisabledTextColor

protected Color getDisabledTextColor()

getFocusColor

protected Color getFocusColor()

paint

public void paint(Graphics g,
                  JComponent c)
Description copied from class: BasicRadioButtonUI
paint the radio button

Overrides:
paint in class BasicRadioButtonUI

paintFocus

protected void paintFocus(Graphics g,
                          Rectangle t,
                          Dimension d)
Overrides:
paintFocus in class BasicRadioButtonUI
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MetalRootPaneUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalRootPaneUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.RootPaneUI
            extended by javax.swing.plaf.basic.BasicRootPaneUI
                extended by javax.swing.plaf.metal.MetalRootPaneUI
All Implemented Interfaces:
EventListener, PropertyChangeListener
public class MetalRootPaneUI
extends BasicRootPaneUI

Provides the metal look and feel implementation of RootPaneUI.

MetalRootPaneUI provides support for the windowDecorationStyle property of JRootPane. MetalRootPaneUI does this by way of installing a custom LayoutManager, a private Component to render the appropriate widgets, and a private Border. The LayoutManager is always installed, regardless of the value of the windowDecorationStyle property, but the Border and Component are only installed/added if the windowDecorationStyle is other than JRootPane.NONE.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Since:
1.4

Constructor Summary
MetalRootPaneUI()
Method Summary
static ComponentUI | createUI(JComponent c) Creates a UI for a JRootPane.
void | installUI(JComponent c) Invokes supers implementation of installUI to install the necessary state onto the passed in JRootPane to render the metal look and feel implementation of RootPaneUI.
void | propertyChange(PropertyChangeEvent e) Invoked when a property changes.
void | uninstallUI(JComponent c) Invokes supers implementation to uninstall any of its state.
Methods inherited from class javax.swing.plaf.basic.BasicRootPaneUI
installComponents, installDefaults, installKeyboardActions, installListeners, uninstallComponents, uninstallDefaults, uninstallKeyboardActions, uninstallListeners
Methods inherited from class javax.swing.plaf.ComponentUI
contains, getAccessibleChild, getAccessibleChildrenCount, getMaximumSize, getMinimumSize, getPreferredSize, paint, update
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

MetalRootPaneUI

public MetalRootPaneUI()
Method Detail

createUI

public static ComponentUI createUI(JComponent c)
Creates a UI for a JRootPane.

Parameters:
c - the JRootPane the RootPaneUI will be created for
Returns:
the RootPaneUI implementation for the passed in JRootPane

installUI

public void installUI(JComponent c)
Invokes supers implementation of installUI to install the necessary state onto the passed in JRootPane to render the metal look and feel implementation of RootPaneUI. If the windowDecorationStyle property of the JRootPane is other than JRootPane.NONE, this will add a custom Component to render the widgets to JRootPane, as well as installing a custom Border and LayoutManager on the JRootPane.

Overrides:
installUI in class BasicRootPaneUI
Parameters:
c - the JRootPane to install state onto

uninstallUI

public void uninstallUI(JComponent c)
Invokes supers implementation to uninstall any of its state. This will also reset the LayoutManager of the JRootPane. If a Component has been added to the JRootPane to render the window decoration style, this method will remove it. Similarly, this will revert the Border and LayoutManager of the JRootPane to what it was before installUI was invoked.

Overrides:
uninstallUI in class BasicRootPaneUI
Parameters:
c - the JRootPane to uninstall state from

propertyChange

public void propertyChange(PropertyChangeEvent e)
Invoked when a property changes. MetalRootPaneUI is primarily interested in events originating from the JRootPane it has been installed on identifying the property windowDecorationStyle. If the windowDecorationStyle has changed to a value other than JRootPane.NONE, this will add a Component to the JRootPane to render the window decorations, as well as installing a Border on the JRootPane. On the other hand, if the windowDecorationStyle has changed to JRootPane.NONE, this will remove the Component that has been added to the JRootPane as well resetting the Border to what it was before installUI was invoked.

Specified by:
propertyChange in interface PropertyChangeListener
Overrides:
propertyChange in class BasicRootPaneUI
Parameters:
e - A PropertyChangeEvent object describing the event source and the property that has changed.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MetalScrollBarUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalScrollBarUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.ScrollBarUI
            extended by javax.swing.plaf.basic.BasicScrollBarUI
                extended by javax.swing.plaf.metal.MetalScrollBarUI
All Implemented Interfaces:
LayoutManager, SwingConstants
public class MetalScrollBarUI
extends BasicScrollBarUI

Implementation of ScrollBarUI for the Metal Look and Feel

Nested Class Summary
Nested classes inherited from class javax.swing.plaf.basic.BasicScrollBarUI
BasicScrollBarUI.ArrowButtonListener, BasicScrollBarUI.ModelListener, BasicScrollBarUI.PropertyChangeHandler, BasicScrollBarUI.ScrollListener, BasicScrollBarUI.TrackListener
Field Summary
protected javax.swing.plaf.metal.MetalBumps | bumps
protected MetalScrollButton | decreaseButton
static String | FREE_STANDING_PROP
protected MetalScrollButton | increaseButton
protected boolean | isFreeStanding
protected int | scrollBarWidth
Fields inherited from class javax.swing.plaf.basic.BasicScrollBarUI
buttonListener, decrButton, DECREASE_HIGHLIGHT, incrButton, INCREASE_HIGHLIGHT, isDragging, maximumThumbSize, minimumThumbSize, modelListener, NO_HIGHLIGHT, propertyChangeListener, scrollbar, scrollListener, scrollTimer, thumbDarkShadowColor, thumbLightShadowColor, thumbRect, trackColor, trackHighlight, trackHighlightColor, trackListener, trackRect
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
Constructor Summary
MetalScrollBarUI()
Method Summary
protected void | configureScrollBarColors()
protected JButton | createDecreaseButton(int orientation) Returns the view that represents the decrease view.
protected JButton | createIncreaseButton(int orientation) Returns the view that represents the increase view.
protected PropertyChangeListener | createPropertyChangeListener()
static ComponentUI | createUI(JComponent c) Returns an instance of the UI delegate for the specified component.
protected Dimension | getMinimumThumbSize() Return the smallest acceptable size for the thumb.
Dimension | getPreferredSize(JComponent c) A vertical scrollbar's preferred width is the maximum of preferred widths of the (non null) increment/decrement buttons, and the minimum width of the thumb.
protected void | installDefaults()
protected void | installListeners()
protected void | paintThumb(Graphics g, JComponent c, Rectangle thumbBounds)
protected void | paintTrack(Graphics g, JComponent c, Rectangle trackBounds)
protected void | setThumbBounds(int x, int y, int width, int height) This is overridden only to increase the invalid area.
Methods inherited from class javax.swing.plaf.basic.BasicScrollBarUI
addLayoutComponent, createArrowButtonListener, createModelListener, createScrollListener, createTrackListener, getMaximumSize, getMaximumThumbSize, getMinimumSize, getThumbBounds, getTrackBounds, installComponents, installKeyboardActions, installUI, layoutContainer, layoutHScrollbar, layoutVScrollbar, minimumLayoutSize, paint, paintDecreaseHighlight, paintIncreaseHighlight, preferredLayoutSize, removeLayoutComponent, scrollByBlock, scrollByUnit, uninstallComponents, uninstallDefaults, uninstallKeyboardActions, uninstallListeners, uninstallUI
Methods inherited from class javax.swing.plaf.ComponentUI
contains, getAccessibleChild, getAccessibleChildrenCount, update
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

bumps

protected javax.swing.plaf.metal.MetalBumps bumps

increaseButton

protected MetalScrollButton increaseButton

decreaseButton

protected MetalScrollButton decreaseButton

scrollBarWidth

protected int scrollBarWidth

FREE_STANDING_PROP

public static final String FREE_STANDING_PROP
See Also:
Constant Field Values

isFreeStanding

protected boolean isFreeStanding
Constructor Detail

MetalScrollBarUI

public MetalScrollBarUI()
Method Detail

createUI

public static ComponentUI createUI(JComponent c)
Description copied from class: ComponentUI
Returns an instance of the UI delegate for the specified component. Each subclass must provide its own static createUI method that returns an instance of that UI delegate subclass. If the UI delegate subclass is stateless, it may return an instance that is shared by multiple components. If the UI delegate is stateful, then it should return a new instance per component. The default implementation of this method throws an error, as it should never be invoked.

installDefaults

protected void installDefaults()
Overrides:
installDefaults in class BasicScrollBarUI

installListeners

protected void installListeners()
Overrides:
installListeners in class BasicScrollBarUI

createPropertyChangeListener

protected PropertyChangeListener createPropertyChangeListener()
Overrides:
createPropertyChangeListener in class BasicScrollBarUI

configureScrollBarColors

protected void configureScrollBarColors()
Overrides:
configureScrollBarColors in class BasicScrollBarUI

getPreferredSize

public Dimension getPreferredSize(JComponent c)
Description copied from class: BasicScrollBarUI
A vertical scrollbar's preferred width is the maximum of preferred widths of the (non null) increment/decrement buttons, and the minimum width of the thumb. The preferred height is the sum of the preferred heights of the same parts. The basis for the preferred size of a horizontal scrollbar is similar.

The preferredSize is only computed once, subsequent calls to this method just return a cached size.

Overrides:
getPreferredSize in class BasicScrollBarUI
Parameters:
c - the JScrollBar that's delegating this method to us
Returns:
the preferred size of a Basic JScrollBar
See Also:
BasicScrollBarUI.getMaximumSize(javax.swing.JComponent), BasicScrollBarUI.getMinimumSize(javax.swing.JComponent)

createDecreaseButton

protected JButton createDecreaseButton(int orientation)
Returns the view that represents the decrease view.

Overrides:
createDecreaseButton in class BasicScrollBarUI

createIncreaseButton

protected JButton createIncreaseButton(int orientation)
Returns the view that represents the increase view.

Overrides:
createIncreaseButton in class BasicScrollBarUI

paintTrack

protected void paintTrack(Graphics g,
                          JComponent c,
                          Rectangle trackBounds)
Overrides:
paintTrack in class BasicScrollBarUI

paintThumb

protected void paintThumb(Graphics g,
                          JComponent c,
                          Rectangle thumbBounds)
Overrides:
paintThumb in class BasicScrollBarUI

getMinimumThumbSize

protected Dimension getMinimumThumbSize()
Description copied from class: BasicScrollBarUI
Return the smallest acceptable size for the thumb. If the scrollbar becomes so small that this size isn't available, the thumb will be hidden.

Warning : the value returned by this method should not be be modified, it's a shared static constant.

Overrides:
getMinimumThumbSize in class BasicScrollBarUI
Returns:
The smallest acceptable size for the thumb.
See Also:
BasicScrollBarUI.getMaximumThumbSize()

setThumbBounds

protected void setThumbBounds(int x,
                              int y,
                              int width,
                              int height)
This is overridden only to increase the invalid area. This ensures that the "Shadow" below the thumb is invalidated

Overrides:
setThumbBounds in class BasicScrollBarUI
See Also:
BasicScrollBarUI.getThumbBounds()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MetalScrollButton (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalScrollButton

java.lang.Object
    extended by java.awt.Component
        extended by java.awt.Container
            extended by javax.swing.JComponent
                extended by javax.swing.AbstractButton
                    extended by javax.swing.JButton
                        extended by javax.swing.plaf.basic.BasicArrowButton
                            extended by javax.swing.plaf.metal.MetalScrollButton
All Implemented Interfaces:
Accessible, ImageObserver, ItemSelectable, MenuContainer, Serializable, SwingConstants
public class MetalScrollButton
extends BasicArrowButton

JButton object for Metal scrollbar arrows.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Nested Class Summary
Nested classes inherited from class javax.swing.JButton
JButton.AccessibleJButton
Nested classes inherited from class javax.swing.AbstractButton
AbstractButton.AccessibleAbstractButton, AbstractButton.ButtonChangeListener
Nested classes inherited from class javax.swing.JComponent
JComponent.AccessibleJComponent
Nested classes inherited from class java.awt.Container
Container.AccessibleAWTContainer
Nested classes inherited from class java.awt.Component
Component.AccessibleAWTComponent, Component.BltBufferStrategy, Component.FlipBufferStrategy
Field Summary
Fields inherited from class javax.swing.plaf.basic.BasicArrowButton
direction
Fields inherited from class javax.swing.AbstractButton
actionListener, BORDER_PAINTED_CHANGED_PROPERTY, changeEvent, changeListener, CONTENT_AREA_FILLED_CHANGED_PROPERTY, DISABLED_ICON_CHANGED_PROPERTY, DISABLED_SELECTED_ICON_CHANGED_PROPERTY, FOCUS_PAINTED_CHANGED_PROPERTY, HORIZONTAL_ALIGNMENT_CHANGED_PROPERTY, HORIZONTAL_TEXT_POSITION_CHANGED_PROPERTY, ICON_CHANGED_PROPERTY, itemListener, MARGIN_CHANGED_PROPERTY, MNEMONIC_CHANGED_PROPERTY, model, MODEL_CHANGED_PROPERTY, PRESSED_ICON_CHANGED_PROPERTY, ROLLOVER_ENABLED_CHANGED_PROPERTY, ROLLOVER_ICON_CHANGED_PROPERTY, ROLLOVER_SELECTED_ICON_CHANGED_PROPERTY, SELECTED_ICON_CHANGED_PROPERTY, TEXT_CHANGED_PROPERTY, VERTICAL_ALIGNMENT_CHANGED_PROPERTY, VERTICAL_TEXT_POSITION_CHANGED_PROPERTY
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
Constructor Summary
MetalScrollButton(int direction, int width, boolean freeStanding)
Method Summary
int | getButtonWidth()
Dimension | getMaximumSize() If the maximum size has been set to a non-null value just returns it.
Dimension | getMinimumSize() If the minimum size has been set to a non-null value just returns it.
Dimension | getPreferredSize() If the preferredSize has been set to a non-null value just returns it.
void | paint(Graphics g) Invoked by Swing to draw components.
void | setFreeStanding(boolean freeStanding)
Methods inherited from class javax.swing.plaf.basic.BasicArrowButton
getDirection, isFocusTraversable, paintTriangle, setDirection
Methods inherited from class javax.swing.JButton
configurePropertiesFromAction, getAccessibleContext, getUIClassID, isDefaultButton, isDefaultCapable, paramString, removeNotify, setDefaultCapable, updateUI
Methods inherited from class javax.swing.AbstractButton
addActionListener, addChangeListener, addItemListener, checkHorizontalKey, checkVerticalKey, createActionListener, createActionPropertyChangeListener, createChangeListener, createItemListener, doClick, doClick, fireActionPerformed, fireItemStateChanged, fireStateChanged, getAction, getActionCommand, getActionListeners, getChangeListeners, getDisabledIcon, getDisabledSelectedIcon, getDisplayedMnemonicIndex, getHorizontalAlignment, getHorizontalTextPosition, getIcon, getIconTextGap, getItemListeners, getLabel, getMargin, getMnemonic, getModel, getMultiClickThreshhold, getPressedIcon, getRolloverIcon, getRolloverSelectedIcon, getSelectedIcon, getSelectedObjects, getText, getUI, getVerticalAlignment, getVerticalTextPosition, imageUpdate, init, isBorderPainted, isContentAreaFilled, isFocusPainted, isRolloverEnabled, isSelected, paintBorder, removeActionListener, removeChangeListener, removeItemListener, setAction, setActionCommand, setBorderPainted, setContentAreaFilled, setDisabledIcon, setDisabledSelectedIcon, setDisplayedMnemonicIndex, setEnabled, setFocusPainted, setHorizontalAlignment, setHorizontalTextPosition, setIcon, setIconTextGap, setLabel, setMargin, setMnemonic, setMnemonic, setModel, setMultiClickThreshhold, setPressedIcon, setRolloverEnabled, setRolloverIcon, setRolloverSelectedIcon, setSelected, setSelectedIcon, setText, setUI, setVerticalAlignment, setVerticalTextPosition
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addPropertyChangeListener, addPropertyChangeListener, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBorder, getBounds, getClientProperty, getComponentGraphics, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getGraphics, getHeight, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getNextFocusableComponent, getPropertyChangeListeners, getPropertyChangeListeners, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isMaximumSizeSet, isMinimumSizeSet, isOpaque, isOptimizedDrawingEnabled, isPaintingTile, isPreferredSizeSet, isRequestFocusEnabled, isValidateRoot, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removePropertyChangeListener, removePropertyChangeListener, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setFont, setForeground, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setFocusCycleRoot, setFocusTraversalKeys, setFocusTraversalPolicy, setLayout, transferFocusBackward, transferFocusDownCycle, validate, validateTree
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getFontMetrics, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMouseWheelListeners, getName, getParent, getPeer, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFontSet, isForegroundSet, isLightweight, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

MetalScrollButton

public MetalScrollButton(int direction,
                         int width,
                         boolean freeStanding)
Method Detail

setFreeStanding

public void setFreeStanding(boolean freeStanding)

paint

public void paint(Graphics g)
Description copied from class: JComponent
Invoked by Swing to draw components. Applications should not invoke paint directly, but should instead use the repaint method to schedule the component for redrawing.

This method actually delegates the work of painting to three protected methods: paintComponent, paintBorder, and paintChildren. They're called in the order listed to ensure that children appear on top of component itself. Generally speaking, the component and its children should not paint in the insets area allocated to the border. Subclasses can just override this method, as always. A subclass that just wants to specialize the UI (look and feel) delegate's paint method should just override paintComponent.

Overrides:
paint in class BasicArrowButton

getPreferredSize

public Dimension getPreferredSize()
Description copied from class: JComponent
If the preferredSize has been set to a non-null value just returns it. If the UI delegate's getPreferredSize method returns a non null value then return that; otherwise defer to the component's layout manager.

Overrides:
getPreferredSize in class BasicArrowButton

getMinimumSize

public Dimension getMinimumSize()
Description copied from class: JComponent
If the minimum size has been set to a non-null value just returns it. If the UI delegate's getMinimumSize method returns a non-null value then return that; otherwise defer to the component's layout manager.

Overrides:
getMinimumSize in class BasicArrowButton

getMaximumSize

public Dimension getMaximumSize()
Description copied from class: JComponent
If the maximum size has been set to a non-null value just returns it. If the UI delegate's getMaximumSize method returns a non-null value then return that; otherwise defer to the component's layout manager.

Overrides:
getMaximumSize in class BasicArrowButton

getButtonWidth

public int getButtonWidth()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MetalScrollPaneUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalScrollPaneUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.ScrollPaneUI
            extended by javax.swing.plaf.basic.BasicScrollPaneUI
                extended by javax.swing.plaf.metal.MetalScrollPaneUI
All Implemented Interfaces:
ScrollPaneConstants
public class MetalScrollPaneUI
extends BasicScrollPaneUI

A Metal L&F implementation of ScrollPaneUI.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Nested Class Summary
Nested classes inherited from class javax.swing.plaf.basic.BasicScrollPaneUI
BasicScrollPaneUI.HSBChangeListener, BasicScrollPaneUI.MouseWheelHandler, BasicScrollPaneUI.PropertyChangeHandler, BasicScrollPaneUI.ViewportChangeHandler, BasicScrollPaneUI.VSBChangeListener
Field Summary
Fields inherited from class javax.swing.plaf.basic.BasicScrollPaneUI
hsbChangeListener, scrollpane, spPropertyChangeListener, viewportChangeListener, vsbChangeListener
Fields inherited from interface javax.swing.ScrollPaneConstants
COLUMN_HEADER, HORIZONTAL_SCROLLBAR, HORIZONTAL_SCROLLBAR_ALWAYS, HORIZONTAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_NEVER, HORIZONTAL_SCROLLBAR_POLICY, LOWER_LEADING_CORNER, LOWER_LEFT_CORNER, LOWER_RIGHT_CORNER, LOWER_TRAILING_CORNER, ROW_HEADER, UPPER_LEADING_CORNER, UPPER_LEFT_CORNER, UPPER_RIGHT_CORNER, UPPER_TRAILING_CORNER, VERTICAL_SCROLLBAR, VERTICAL_SCROLLBAR_ALWAYS, VERTICAL_SCROLLBAR_AS_NEEDED, VERTICAL_SCROLLBAR_NEVER, VERTICAL_SCROLLBAR_POLICY, VIEWPORT
Constructor Summary
MetalScrollPaneUI()
Method Summary
protected PropertyChangeListener | createScrollBarSwapListener()
static ComponentUI | createUI(JComponent x) Returns an instance of the UI delegate for the specified component.
void | installListeners(JScrollPane scrollPane)
void | installUI(JComponent c) Configures the specified component appropriate for the look and feel.
void | uninstallListeners(JScrollPane scrollPane)
void | uninstallUI(JComponent c) Reverses configuration which was done on the specified component during installUI.
Methods inherited from class javax.swing.plaf.basic.BasicScrollPaneUI
createHSBChangeListener, createMouseWheelListener, createPropertyChangeListener, createViewportChangeListener, createVSBChangeListener, getMaximumSize, getMinimumSize, getPreferredSize, installDefaults, installKeyboardActions, paint, syncScrollPaneWithViewport, uninstallDefaults, uninstallKeyboardActions, uninstallListeners, updateColumnHeader, updateRowHeader, updateScrollBarDisplayPolicy, updateViewport
Methods inherited from class javax.swing.plaf.ComponentUI
contains, getAccessibleChild, getAccessibleChildrenCount, update
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

MetalScrollPaneUI

public MetalScrollPaneUI()
Method Detail

createUI

public static ComponentUI createUI(JComponent x)
Description copied from class: ComponentUI
Returns an instance of the UI delegate for the specified component. Each subclass must provide its own static createUI method that returns an instance of that UI delegate subclass. If the UI delegate subclass is stateless, it may return an instance that is shared by multiple components. If the UI delegate is stateful, then it should return a new instance per component. The default implementation of this method throws an error, as it should never be invoked.

installUI

public void installUI(JComponent c)
Description copied from class: ComponentUI
Configures the specified component appropriate for the look and feel. This method is invoked when the ComponentUI instance is being installed as the UI delegate on the specified component. This method should completely configure the component for the look and feel, including the following:
  1. Install any default property values for color, fonts, borders, icons, opacity, etc. on the component. Whenever possible, property values initialized by the client program should not be overridden.
  2. Install a LayoutManager on the component if necessary.
  3. Create/add any required sub-components to the component.
  4. Create/install event listeners on the component.
  5. Create/install a PropertyChangeListener on the component in order to detect and respond to component property changes appropriately.
  6. Install keyboard UI (mnemonics, traversal, etc.) on the component.
  7. Initialize any appropriate instance data.

Overrides:
installUI in class BasicScrollPaneUI

uninstallUI

public void uninstallUI(JComponent c)
Description copied from class: ComponentUI
Reverses configuration which was done on the specified component during installUI. This method is invoked when this UIComponent instance is being removed as the UI delegate for the specified component. This method should undo the configuration performed in installUI, being careful to leave the JComponent instance in a clean state (no extraneous listeners, look-and-feel-specific property objects, etc.). This should include the following:
  1. Remove any UI-set borders from the component.
  2. Remove any UI-set layout managers on the component.
  3. Remove any UI-added sub-components from the component.
  4. Remove any UI-added event/property listeners from the component.
  5. Remove any UI-installed keyboard UI from the component.
  6. Nullify any allocated instance data objects to allow for GC.

Overrides:
uninstallUI in class BasicScrollPaneUI

installListeners

public void installListeners(JScrollPane scrollPane)
Overrides:
installListeners in class BasicScrollPaneUI

uninstallListeners

public void uninstallListeners(JScrollPane scrollPane)

createScrollBarSwapListener

protected PropertyChangeListener createScrollBarSwapListener()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MetalSeparatorUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalSeparatorUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.SeparatorUI
            extended by javax.swing.plaf.basic.BasicSeparatorUI
                extended by javax.swing.plaf.metal.MetalSeparatorUI
Direct Known Subclasses:
MetalPopupMenuSeparatorUI
public class MetalSeparatorUI
extends BasicSeparatorUI

A Metal L&F implementation of SeparatorUI. This implementation is a "combined" view/controller.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Field Summary
Fields inherited from class javax.swing.plaf.basic.BasicSeparatorUI
highlight, shadow
Constructor Summary
MetalSeparatorUI()
Method Summary
static ComponentUI | createUI(JComponent c) Returns an instance of the UI delegate for the specified component.
Dimension | getPreferredSize(JComponent c) Returns the specified component's preferred size appropriate for the look and feel.
protected void | installDefaults(JSeparator s)
void | paint(Graphics g, JComponent c) Paints the specified component appropriate for the look and feel.
Methods inherited from class javax.swing.plaf.basic.BasicSeparatorUI
getMaximumSize, getMinimumSize, installListeners, installUI, uninstallDefaults, uninstallListeners, uninstallUI
Methods inherited from class javax.swing.plaf.ComponentUI
contains, getAccessibleChild, getAccessibleChildrenCount, update
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

MetalSeparatorUI

public MetalSeparatorUI()
Method Detail

createUI

public static ComponentUI createUI(JComponent c)
Description copied from class: ComponentUI
Returns an instance of the UI delegate for the specified component. Each subclass must provide its own static createUI method that returns an instance of that UI delegate subclass. If the UI delegate subclass is stateless, it may return an instance that is shared by multiple components. If the UI delegate is stateful, then it should return a new instance per component. The default implementation of this method throws an error, as it should never be invoked.

installDefaults

protected void installDefaults(JSeparator s)
Overrides:
installDefaults in class BasicSeparatorUI

paint

public void paint(Graphics g,
                  JComponent c)
Description copied from class: ComponentUI
Paints the specified component appropriate for the look and feel. This method is invoked from the ComponentUI.update method when the specified component is being painted. Subclasses should override this method and use the specified Graphics object to render the content of the component.

Overrides:
paint in class BasicSeparatorUI

getPreferredSize

public Dimension getPreferredSize(JComponent c)
Description copied from class: ComponentUI
Returns the specified component's preferred size appropriate for the look and feel. If null is returned, the preferred size will be calculated by the component's layout manager instead (this is the preferred approach for any component with a specific layout manager installed). The default implementation of this method returns null.

Overrides:
getPreferredSize in class BasicSeparatorUI
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MetalSliderUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalSliderUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.SliderUI
            extended by javax.swing.plaf.basic.BasicSliderUI
                extended by javax.swing.plaf.metal.MetalSliderUI
public class MetalSliderUI
extends BasicSliderUI

A Java L&F implementation of SliderUI.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Nested Class Summary
protected  class MetalSliderUI.MetalPropertyListener
Nested classes inherited from class javax.swing.plaf.basic.BasicSliderUI
BasicSliderUI.ActionScroller, BasicSliderUI.ChangeHandler, BasicSliderUI.ComponentHandler, BasicSliderUI.FocusHandler, BasicSliderUI.PropertyChangeHandler, BasicSliderUI.ScrollListener, BasicSliderUI.TrackListener
Field Summary
protected static Color | darkShadowColor
protected boolean | filledSlider
protected static Color | highlightColor
protected static Icon | horizThumbIcon
protected String | SLIDER_FILL
protected static Color | thumbColor
protected int | TICK_BUFFER
protected static int | tickLength
protected static int | trackWidth
protected static Icon | vertThumbIcon
Fields inherited from class javax.swing.plaf.basic.BasicSliderUI
changeListener, componentListener, contentRect, focusInsets, focusListener, focusRect, insetCache, labelRect, leftToRightCache, MAX_SCROLL, MIN_SCROLL, NEGATIVE_SCROLL, POSITIVE_SCROLL, propertyChangeListener, scrollListener, scrollTimer, slider, thumbRect, tickRect, trackBuffer, trackListener, trackRect
Constructor Summary
MetalSliderUI()
Method Summary
protected PropertyChangeListener | createPropertyChangeListener(JSlider slider)
static ComponentUI | createUI(JComponent c) Returns an instance of the UI delegate for the specified component.
protected int | getThumbOverhang() Returns the amount that the thumb goes past the slide bar.
protected Dimension | getThumbSize()
int | getTickLength() Gets the height of the tick area for horizontal sliders and the width of the tick area for vertical sliders.
protected int | getTrackLength() Returns the longer dimension of the slide bar.
protected int | getTrackWidth() Returns the shorter dimension of the track.
void | installUI(JComponent c) Configures the specified component appropriate for the look and feel.
void | paintFocus(Graphics g)
protected void | paintMajorTickForHorizSlider(Graphics g, Rectangle tickBounds, int x)
protected void | paintMajorTickForVertSlider(Graphics g, Rectangle tickBounds, int y)
protected void | paintMinorTickForHorizSlider(Graphics g, Rectangle tickBounds, int x)
protected void | paintMinorTickForVertSlider(Graphics g, Rectangle tickBounds, int y)
void | paintThumb(Graphics g)
void | paintTrack(Graphics g)
protected void | scrollDueToClickInTrack(int dir) This function is called when a mousePressed was detected in the track, not in the thumb.
Methods inherited from class javax.swing.plaf.basic.BasicSliderUI
calculateContentRect, calculateFocusRect, calculateGeometry, calculateLabelRect, calculateThumbLocation, calculateThumbSize, calculateTickRect, calculateTrackBuffer, calculateTrackRect, createChangeListener, createComponentListener, createFocusListener, createScrollListener, createTrackListener, drawInverted, getFocusColor, getHeightOfHighValueLabel, getHeightOfLowValueLabel, getHeightOfTallestLabel, getHighestValueLabel, getHighlightColor, getLowestValueLabel, getMaximumSize, getMinimumHorizontalSize, getMinimumSize, getMinimumVerticalSize, getPreferredHorizontalSize, getPreferredSize, getPreferredVerticalSize, getShadowColor, getWidthOfHighValueLabel, getWidthOfLowValueLabel, getWidthOfWidestLabel, installDefaults, installKeyboardActions, installListeners, paint, paintHorizontalLabel, paintLabels, paintTicks, paintVerticalLabel, recalculateIfInsetsChanged, recalculateIfOrientationChanged, scrollByBlock, scrollByUnit, setThumbLocation, uninstallKeyboardActions, uninstallListeners, uninstallUI, valueForXPosition, valueForYPosition, xPositionForValue, yPositionForValue
Methods inherited from class javax.swing.plaf.ComponentUI
contains, getAccessibleChild, getAccessibleChildrenCount, update
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

TICK_BUFFER

protected final int TICK_BUFFER
See Also:
Constant Field Values

filledSlider

protected boolean filledSlider

thumbColor

protected static Color thumbColor

highlightColor

protected static Color highlightColor

darkShadowColor

protected static Color darkShadowColor

trackWidth

protected static int trackWidth

tickLength

protected static int tickLength

horizThumbIcon

protected static Icon horizThumbIcon

vertThumbIcon

protected static Icon vertThumbIcon

SLIDER_FILL

protected final String SLIDER_FILL
See Also:
Constant Field Values
Constructor Detail

MetalSliderUI

public MetalSliderUI()
Method Detail

createUI

public static ComponentUI createUI(JComponent c)
Description copied from class: ComponentUI
Returns an instance of the UI delegate for the specified component. Each subclass must provide its own static createUI method that returns an instance of that UI delegate subclass. If the UI delegate subclass is stateless, it may return an instance that is shared by multiple components. If the UI delegate is stateful, then it should return a new instance per component. The default implementation of this method throws an error, as it should never be invoked.

installUI

public void installUI(JComponent c)
Description copied from class: ComponentUI
Configures the specified component appropriate for the look and feel. This method is invoked when the ComponentUI instance is being installed as the UI delegate on the specified component. This method should completely configure the component for the look and feel, including the following:
  1. Install any default property values for color, fonts, borders, icons, opacity, etc. on the component. Whenever possible, property values initialized by the client program should not be overridden.
  2. Install a LayoutManager on the component if necessary.
  3. Create/add any required sub-components to the component.
  4. Create/install event listeners on the component.
  5. Create/install a PropertyChangeListener on the component in order to detect and respond to component property changes appropriately.
  6. Install keyboard UI (mnemonics, traversal, etc.) on the component.
  7. Initialize any appropriate instance data.

Overrides:
installUI in class BasicSliderUI

createPropertyChangeListener

protected PropertyChangeListener createPropertyChangeListener(JSlider slider)
Overrides:
createPropertyChangeListener in class BasicSliderUI

paintThumb

public void paintThumb(Graphics g)
Overrides:
paintThumb in class BasicSliderUI

paintTrack

public void paintTrack(Graphics g)
Overrides:
paintTrack in class BasicSliderUI

paintFocus

public void paintFocus(Graphics g)
Overrides:
paintFocus in class BasicSliderUI

getThumbSize

protected Dimension getThumbSize()
Overrides:
getThumbSize in class BasicSliderUI

getTickLength

public int getTickLength()
Gets the height of the tick area for horizontal sliders and the width of the tick area for vertical sliders. BasicSliderUI uses the returned value to determine the tick area rectangle.

Overrides:
getTickLength in class BasicSliderUI

getTrackWidth

protected int getTrackWidth()
Returns the shorter dimension of the track.

getTrackLength

protected int getTrackLength()
Returns the longer dimension of the slide bar. (The slide bar is only the part that runs directly under the thumb)

getThumbOverhang

protected int getThumbOverhang()
Returns the amount that the thumb goes past the slide bar.

scrollDueToClickInTrack

protected void scrollDueToClickInTrack(int dir)
Description copied from class: BasicSliderUI
This function is called when a mousePressed was detected in the track, not in the thumb. The default behavior is to scroll by block. You can override this method to stop it from scrolling or to add additional behavior.

Overrides:
scrollDueToClickInTrack in class BasicSliderUI

paintMinorTickForHorizSlider

protected void paintMinorTickForHorizSlider(Graphics g,
                                            Rectangle tickBounds,
                                            int x)
Overrides:
paintMinorTickForHorizSlider in class BasicSliderUI

paintMajorTickForHorizSlider

protected void paintMajorTickForHorizSlider(Graphics g,
                                            Rectangle tickBounds,
                                            int x)
Overrides:
paintMajorTickForHorizSlider in class BasicSliderUI

paintMinorTickForVertSlider

protected void paintMinorTickForVertSlider(Graphics g,
                                           Rectangle tickBounds,
                                           int y)
Overrides:
paintMinorTickForVertSlider in class BasicSliderUI

paintMajorTickForVertSlider

protected void paintMajorTickForVertSlider(Graphics g,
                                           Rectangle tickBounds,
                                           int y)
Overrides:
paintMajorTickForVertSlider in class BasicSliderUI
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MetalSliderUI.MetalPropertyListener (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalSliderUI.MetalPropertyListener

java.lang.Object
    extended by javax.swing.plaf.basic.BasicSliderUI.PropertyChangeHandler
        extended by javax.swing.plaf.metal.MetalSliderUI.MetalPropertyListener
All Implemented Interfaces:
EventListener, PropertyChangeListener
Enclosing class:
MetalSliderUI
protected class MetalSliderUI.MetalPropertyListener
extends BasicSliderUI.PropertyChangeHandler

Constructor Summary
protected MetalSliderUI.MetalPropertyListener()
Method Summary
 void propertyChange(PropertyChangeEvent e)
This method gets called when a bound property is changed.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

MetalSliderUI.MetalPropertyListener

protected MetalSliderUI.MetalPropertyListener()
Method Detail

propertyChange

public void propertyChange(PropertyChangeEvent e)
Description copied from interface: PropertyChangeListener
This method gets called when a bound property is changed.

Specified by:
propertyChange in interface PropertyChangeListener
Overrides:
propertyChange in class BasicSliderUI.PropertyChangeHandler
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MetalSplitPaneUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalSplitPaneUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.SplitPaneUI
            extended by javax.swing.plaf.basic.BasicSplitPaneUI
                extended by javax.swing.plaf.metal.MetalSplitPaneUI
public class MetalSplitPaneUI
extends BasicSplitPaneUI

Metal split pane.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Nested Class Summary
Nested classes inherited from class javax.swing.plaf.basic.BasicSplitPaneUI
BasicSplitPaneUI.BasicHorizontalLayoutManager, BasicSplitPaneUI.BasicVerticalLayoutManager, BasicSplitPaneUI.FocusHandler, BasicSplitPaneUI.KeyboardDownRightHandler, BasicSplitPaneUI.KeyboardEndHandler, BasicSplitPaneUI.KeyboardHomeHandler, BasicSplitPaneUI.KeyboardResizeToggleHandler, BasicSplitPaneUI.KeyboardUpLeftHandler, BasicSplitPaneUI.PropertyHandler
Field Summary
Fields inherited from class javax.swing.plaf.basic.BasicSplitPaneUI
beginDragDividerLocation, divider, dividerResizeToggleKey, dividerSize, downKey, draggingHW, endKey, focusListener, homeKey, KEYBOARD_DIVIDER_MOVE_OFFSET, keyboardDownRightListener, keyboardEndListener, keyboardHomeListener, keyboardResizeToggleListener, keyboardUpLeftListener, layoutManager, leftKey, NON_CONTINUOUS_DIVIDER, nonContinuousLayoutDivider, propertyChangeListener, rightKey, splitPane, upKey
Constructor Summary
MetalSplitPaneUI()
Method Summary
BasicSplitPaneDivider | createDefaultDivider() Creates the default divider.
static ComponentUI | createUI(JComponent x) Creates a new MetalSplitPaneUI instance
Methods inherited from class javax.swing.plaf.basic.BasicSplitPaneUI
createDefaultNonContinuousLayoutDivider, createFocusListener, createKeyboardDownRightListener, createKeyboardEndListener, createKeyboardHomeListener, createKeyboardResizeToggleListener, createKeyboardUpLeftListener, createPropertyChangeListener, dragDividerTo, finishDraggingTo, finishedPaintingChildren, getDivider, getDividerBorderSize, getDividerLocation, getInsets, getLastDragLocation, getMaximumDividerLocation, getMaximumSize, getMinimumDividerLocation, getMinimumSize, getNonContinuousLayoutDivider, getOrientation, getPreferredSize, getSplitPane, installDefaults, installKeyboardActions, installListeners, installUI, isContinuousLayout, paint, resetLayoutManager, resetToPreferredSizes, setContinuousLayout, setDividerLocation, setLastDragLocation, setNonContinuousLayoutDivider, setNonContinuousLayoutDivider, setOrientation, startDragging, uninstallDefaults, uninstallKeyboardActions, uninstallListeners, uninstallUI
Methods inherited from class javax.swing.plaf.ComponentUI
contains, getAccessibleChild, getAccessibleChildrenCount, update
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

MetalSplitPaneUI

public MetalSplitPaneUI()
Method Detail

createUI

public static ComponentUI createUI(JComponent x)
Creates a new MetalSplitPaneUI instance

createDefaultDivider

public BasicSplitPaneDivider createDefaultDivider()
Creates the default divider.

Overrides:
createDefaultDivider in class BasicSplitPaneUI
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MetalTabbedPaneUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalTabbedPaneUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.TabbedPaneUI
            extended by javax.swing.plaf.basic.BasicTabbedPaneUI
                extended by javax.swing.plaf.metal.MetalTabbedPaneUI
All Implemented Interfaces:
SwingConstants
public class MetalTabbedPaneUI
extends BasicTabbedPaneUI

The Metal subclass of BasicTabbedPaneUI.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Nested Class Summary
 class MetalTabbedPaneUI.TabbedPaneLayout
This inner class is marked "public" due to a compiler bug.
Nested classes inherited from class javax.swing.plaf.basic.BasicTabbedPaneUI
BasicTabbedPaneUI.FocusHandler, BasicTabbedPaneUI.MouseHandler, BasicTabbedPaneUI.PropertyChangeHandler, BasicTabbedPaneUI.TabSelectionHandler
Field Summary
protected int | minTabWidth
protected Color | selectColor
protected Color | selectHighlight
protected Color | tabAreaBackground
Fields inherited from class javax.swing.plaf.basic.BasicTabbedPaneUI
calcRect, contentBorderInsets, darkShadow, downKey, focus, focusListener, highlight, leftKey, lightHighlight, maxTabHeight, maxTabWidth, mouseListener, propertyChangeListener, rects, rightKey, runCount, selectedRun, selectedTabPadInsets, shadow, tabAreaInsets, tabChangeListener, tabInsets, tabPane, tabRunOverlay, tabRuns, textIconGap, upKey
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
Constructor Summary
MetalTabbedPaneUI()
Method Summary
protected int | calculateMaxTabHeight(int tabPlacement)
protected LayoutManager | createLayoutManager() Invoked by installUI to create a layout manager object to manage the JTabbedPane.
static ComponentUI | createUI(JComponent x) Returns an instance of the UI delegate for the specified component.
protected Color | getColorForGap(int currentRun, int x, int y)
protected int | getTabLabelShiftX(int tabPlacement, int tabIndex, boolean isSelected) Overridden to do nothing for the Java L&F.
protected int | getTabLabelShiftY(int tabPlacement, int tabIndex, boolean isSelected) Overridden to do nothing for the Java L&F.
protected int | getTabRunOverlay(int tabPlacement)
protected void | installDefaults()
void | paint(Graphics g, JComponent c) Paints the specified component appropriate for the look and feel.
protected void | paintBottomTabBorder(int tabIndex, Graphics g, int x, int y, int w, int h, int btm, int rght, boolean isSelected)
protected void | paintContentBorderBottomEdge(Graphics g, int tabPlacement, int selectedIndex, int x, int y, int w, int h)
protected void | paintContentBorderLeftEdge(Graphics g, int tabPlacement, int selectedIndex, int x, int y, int w, int h)
protected void | paintContentBorderRightEdge(Graphics g, int tabPlacement, int selectedIndex, int x, int y, int w, int h)
protected void | paintContentBorderTopEdge(Graphics g, int tabPlacement, int selectedIndex, int x, int y, int w, int h)
protected void | paintFocusIndicator(Graphics g, int tabPlacement, Rectangle[] rects, int tabIndex, Rectangle iconRect, Rectangle textRect, boolean isSelected)
protected void | paintHighlightBelowTab()
protected void | paintLeftTabBorder(int tabIndex, Graphics g, int x, int y, int w, int h, int btm, int rght, boolean isSelected)
protected void | paintRightTabBorder(int tabIndex, Graphics g, int x, int y, int w, int h, int btm, int rght, boolean isSelected)
protected void | paintTabBackground(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected)
protected void | paintTabBorder(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) this function draws the border around each tab note that this function does now draw the background of the tab.
protected void | paintTopTabBorder(int tabIndex, Graphics g, int x, int y, int w, int h, int btm, int rght, boolean isSelected)
protected boolean | shouldFillGap(int currentRun, int tabIndex, int x, int y)
protected boolean | shouldPadTabRun(int tabPlacement, int run)
protected boolean | shouldRotateTabRuns(int tabPlacement, int selectedRun)
void | update(Graphics g, JComponent c) Notifies this UI delegate that it's time to paint the specified component.
Methods inherited from class javax.swing.plaf.basic.BasicTabbedPaneUI
assureRectsCreated, calculateMaxTabWidth, calculateTabAreaHeight, calculateTabAreaWidth, calculateTabHeight, calculateTabWidth, createChangeListener, createFocusListener, createMouseListener, createPropertyChangeListener, expandTabRunsArray, getContentBorderInsets, getFontMetrics, getIconForTab, getMaximumSize, getMinimumSize, getNextTabIndex, getNextTabIndexInRun, getNextTabRun, getPreferredSize, getPreviousTabIndex, getPreviousTabIndexInRun, getPreviousTabRun, getRunForTab, getSelectedTabPadInsets, getTabAreaInsets, getTabBounds, getTabBounds, getTabInsets, getTabRunCount, getTabRunIndent, getTabRunOffset, getTextViewForTab, getVisibleComponent, installComponents, installKeyboardActions, installListeners, installUI, lastTabInRun, layoutLabel, navigateSelectedTab, paintContentBorder, paintIcon, paintTab, paintTabArea, paintText, rotateInsets, selectAdjacentRunTab, selectNextTab, selectNextTabInRun, selectPreviousTab, selectPreviousTabInRun, setVisibleComponent, shouldRotateTabRuns, tabForCoordinate, uninstallComponents, uninstallDefaults, uninstallKeyboardActions, uninstallListeners, uninstallUI
Methods inherited from class javax.swing.plaf.ComponentUI
contains, getAccessibleChild, getAccessibleChildrenCount
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

minTabWidth

protected int minTabWidth

tabAreaBackground

protected Color tabAreaBackground

selectColor

protected Color selectColor

selectHighlight

protected Color selectHighlight
Constructor Detail

MetalTabbedPaneUI

public MetalTabbedPaneUI()
Method Detail

createUI

public static ComponentUI createUI(JComponent x)
Description copied from class: ComponentUI
Returns an instance of the UI delegate for the specified component. Each subclass must provide its own static createUI method that returns an instance of that UI delegate subclass. If the UI delegate subclass is stateless, it may return an instance that is shared by multiple components. If the UI delegate is stateful, then it should return a new instance per component. The default implementation of this method throws an error, as it should never be invoked.

createLayoutManager

protected LayoutManager createLayoutManager()
Description copied from class: BasicTabbedPaneUI
Invoked by installUI to create a layout manager object to manage the JTabbedPane.

Overrides:
createLayoutManager in class BasicTabbedPaneUI
Returns:
a layout manager object
See Also:
BasicTabbedPaneUI.TabbedPaneLayout, JTabbedPane.getTabLayoutPolicy()

installDefaults

protected void installDefaults()
Overrides:
installDefaults in class BasicTabbedPaneUI

paintTabBorder

protected void paintTabBorder(Graphics g,
                              int tabPlacement,
                              int tabIndex,
                              int x,
                              int y,
                              int w,
                              int h,
                              boolean isSelected)
Description copied from class: BasicTabbedPaneUI
this function draws the border around each tab note that this function does now draw the background of the tab. that is done elsewhere

Overrides:
paintTabBorder in class BasicTabbedPaneUI

paintTopTabBorder

protected void paintTopTabBorder(int tabIndex,
                                 Graphics g,
                                 int x,
                                 int y,
                                 int w,
                                 int h,
                                 int btm,
                                 int rght,
                                 boolean isSelected)

shouldFillGap

protected boolean shouldFillGap(int currentRun,
                                int tabIndex,
                                int x,
                                int y)

getColorForGap

protected Color getColorForGap(int currentRun,
                               int x,
                               int y)

paintLeftTabBorder

protected void paintLeftTabBorder(int tabIndex,
                                  Graphics g,
                                  int x,
                                  int y,
                                  int w,
                                  int h,
                                  int btm,
                                  int rght,
                                  boolean isSelected)

paintBottomTabBorder

protected void paintBottomTabBorder(int tabIndex,
                                    Graphics g,
                                    int x,
                                    int y,
                                    int w,
                                    int h,
                                    int btm,
                                    int rght,
                                    boolean isSelected)

paintRightTabBorder

protected void paintRightTabBorder(int tabIndex,
                                   Graphics g,
                                   int x,
                                   int y,
                                   int w,
                                   int h,
                                   int btm,
                                   int rght,
                                   boolean isSelected)

update

public void update(Graphics g,
                   JComponent c)
Description copied from class: ComponentUI
Notifies this UI delegate that it's time to paint the specified component. This method is invoked by JComponent when the specified component is being painted. By default this method will fill the specified component with its background color (if its opaque property is true) and then immediately call paint. In general this method need not be overridden by subclasses; all look-and-feel rendering code should reside in the paint method.

Overrides:
update in class ComponentUI
Parameters:
g - the Graphics context in which to paint
c - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.paint(java.awt.Graphics, javax.swing.JComponent), JComponent.paintComponent(java.awt.Graphics)

paintTabBackground

protected void paintTabBackground(Graphics g,
                                  int tabPlacement,
                                  int tabIndex,
                                  int x,
                                  int y,
                                  int w,
                                  int h,
                                  boolean isSelected)
Overrides:
paintTabBackground in class BasicTabbedPaneUI

getTabLabelShiftX

protected int getTabLabelShiftX(int tabPlacement,
                                int tabIndex,
                                boolean isSelected)
Overridden to do nothing for the Java L&F.

Overrides:
getTabLabelShiftX in class BasicTabbedPaneUI

getTabLabelShiftY

protected int getTabLabelShiftY(int tabPlacement,
                                int tabIndex,
                                boolean isSelected)
Overridden to do nothing for the Java L&F.

Overrides:
getTabLabelShiftY in class BasicTabbedPaneUI

paint

public void paint(Graphics g,
                  JComponent c)
Description copied from class: ComponentUI
Paints the specified component appropriate for the look and feel. This method is invoked from the ComponentUI.update method when the specified component is being painted. Subclasses should override this method and use the specified Graphics object to render the content of the component.

Overrides:
paint in class BasicTabbedPaneUI

paintHighlightBelowTab

protected void paintHighlightBelowTab()

paintFocusIndicator

protected void paintFocusIndicator(Graphics g,
                                   int tabPlacement,
                                   Rectangle[] rects,
                                   int tabIndex,
                                   Rectangle iconRect,
                                   Rectangle textRect,
                                   boolean isSelected)
Overrides:
paintFocusIndicator in class BasicTabbedPaneUI

paintContentBorderTopEdge

protected void paintContentBorderTopEdge(Graphics g,
                                         int tabPlacement,
                                         int selectedIndex,
                                         int x,
                                         int y,
                                         int w,
                                         int h)
Overrides:
paintContentBorderTopEdge in class BasicTabbedPaneUI

paintContentBorderBottomEdge

protected void paintContentBorderBottomEdge(Graphics g,
                                            int tabPlacement,
                                            int selectedIndex,
                                            int x,
                                            int y,
                                            int w,
                                            int h)
Overrides:
paintContentBorderBottomEdge in class BasicTabbedPaneUI

paintContentBorderLeftEdge

protected void paintContentBorderLeftEdge(Graphics g,
                                          int tabPlacement,
                                          int selectedIndex,
                                          int x,
                                          int y,
                                          int w,
                                          int h)
Overrides:
paintContentBorderLeftEdge in class BasicTabbedPaneUI

paintContentBorderRightEdge

protected void paintContentBorderRightEdge(Graphics g,
                                           int tabPlacement,
                                           int selectedIndex,
                                           int x,
                                           int y,
                                           int w,
                                           int h)
Overrides:
paintContentBorderRightEdge in class BasicTabbedPaneUI

calculateMaxTabHeight

protected int calculateMaxTabHeight(int tabPlacement)
Overrides:
calculateMaxTabHeight in class BasicTabbedPaneUI

getTabRunOverlay

protected int getTabRunOverlay(int tabPlacement)
Overrides:
getTabRunOverlay in class BasicTabbedPaneUI

shouldRotateTabRuns

protected boolean shouldRotateTabRuns(int tabPlacement,
                                      int selectedRun)

shouldPadTabRun

protected boolean shouldPadTabRun(int tabPlacement,
                                  int run)
Overrides:
shouldPadTabRun in class BasicTabbedPaneUI
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MetalTabbedPaneUI.TabbedPaneLayout (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalTabbedPaneUI.TabbedPaneLayout

java.lang.Object
    extended by javax.swing.plaf.basic.BasicTabbedPaneUI.TabbedPaneLayout
        extended by javax.swing.plaf.metal.MetalTabbedPaneUI.TabbedPaneLayout
All Implemented Interfaces:
LayoutManager
Enclosing class:
MetalTabbedPaneUI
public class MetalTabbedPaneUI.TabbedPaneLayout
extends BasicTabbedPaneUI.TabbedPaneLayout

This inner class is marked "public" due to a compiler bug. This class should be treated as a "protected" inner class. Instantiate it only within subclasses of MetalTabbedPaneUI.

Constructor Summary
MetalTabbedPaneUI.TabbedPaneLayout()
Method Summary
protected void | normalizeTabRuns(int tabPlacement, int tabCount, int start, int max)
protected void | padSelectedTab(int tabPlacement, int selectedIndex)
protected void | rotateTabRuns(int tabPlacement, int selectedRun)
Methods inherited from class javax.swing.plaf.basic.BasicTabbedPaneUI.TabbedPaneLayout
addLayoutComponent, calculateLayoutInfo, calculateSize, calculateTabRects, layoutContainer, minimumLayoutSize, padTabRun, preferredLayoutSize, preferredTabAreaHeight, preferredTabAreaWidth, removeLayoutComponent
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

MetalTabbedPaneUI.TabbedPaneLayout

public MetalTabbedPaneUI.TabbedPaneLayout()
Method Detail

normalizeTabRuns

protected void normalizeTabRuns(int tabPlacement,
                                int tabCount,
                                int start,
                                int max)
Overrides:
normalizeTabRuns in class BasicTabbedPaneUI.TabbedPaneLayout

rotateTabRuns

protected void rotateTabRuns(int tabPlacement,
                             int selectedRun)
Overrides:
rotateTabRuns in class BasicTabbedPaneUI.TabbedPaneLayout

padSelectedTab

protected void padSelectedTab(int tabPlacement,
                              int selectedIndex)
Overrides:
padSelectedTab in class BasicTabbedPaneUI.TabbedPaneLayout
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MetalTextFieldUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalTextFieldUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.TextUI
            extended by javax.swing.plaf.basic.BasicTextUI
                extended by javax.swing.plaf.basic.BasicTextFieldUI
                    extended by javax.swing.plaf.metal.MetalTextFieldUI
All Implemented Interfaces:
ViewFactory
public class MetalTextFieldUI
extends BasicTextFieldUI

Basis of a look and feel for a JTextField.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Nested Class Summary
Nested classes inherited from class javax.swing.plaf.basic.BasicTextUI
BasicTextUI.BasicCaret, BasicTextUI.BasicHighlighter
Constructor Summary
MetalTextFieldUI()
Method Summary
static ComponentUI | createUI(JComponent c) Creates a UI for a JTextField.
void | propertyChange(PropertyChangeEvent evt) This method gets called when a bound property is changed on the associated JTextComponent.
Methods inherited from class javax.swing.plaf.basic.BasicTextFieldUI
create, getPropertyPrefix, installUI
Methods inherited from class javax.swing.plaf.basic.BasicTextUI
create, createCaret, createHighlighter, createKeymap, damageRange, damageRange, getComponent, getEditorKit, getKeymapName, getMaximumSize, getMinimumSize, getNextVisualPositionFrom, getPreferredSize, getRootView, getToolTipText, getVisibleEditorRect, installDefaults, installKeyboardActions, installListeners, modelChanged, modelToView, modelToView, paint, paintBackground, paintSafely, setView, uninstallDefaults, uninstallKeyboardActions, uninstallListeners, uninstallUI, update, viewToModel, viewToModel
Methods inherited from class javax.swing.plaf.ComponentUI
contains, getAccessibleChild, getAccessibleChildrenCount
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

MetalTextFieldUI

public MetalTextFieldUI()
Method Detail

createUI

public static ComponentUI createUI(JComponent c)
Description copied from class: BasicTextFieldUI
Creates a UI for a JTextField.

propertyChange

public void propertyChange(PropertyChangeEvent evt)
This method gets called when a bound property is changed on the associated JTextComponent. This is a hook which UI implementations may change to reflect how the UI displays bound properties of JTextComponent subclasses.

Overrides:
propertyChange in class BasicTextFieldUI
Parameters:
evt - the property change event
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MetalTheme (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalTheme

java.lang.Object
    extended by javax.swing.plaf.metal.MetalTheme
Direct Known Subclasses:
DefaultMetalTheme
public abstract class MetalTheme
extends Object

This interface acts as a generic way to describe the colors used by Metal. Classes which implement this interface can be used to swap the colors in a Metal application.

Constructor Summary
MetalTheme()
Method Summary
void | addCustomEntriesToTable(UIDefaults table)
ColorUIResource | getAcceleratorForeground()
ColorUIResource | getAcceleratorSelectedForeground()
protected ColorUIResource | getBlack()
ColorUIResource | getControl()
ColorUIResource | getControlDarkShadow()
ColorUIResource | getControlDisabled()
ColorUIResource | getControlHighlight()
ColorUIResource | getControlInfo()
ColorUIResource | getControlShadow()
ColorUIResource | getControlTextColor()
abstract FontUIResource | getControlTextFont()
ColorUIResource | getDesktopColor()
ColorUIResource | getFocusColor()
ColorUIResource | getHighlightedTextColor()
ColorUIResource | getInactiveControlTextColor()
ColorUIResource | getInactiveSystemTextColor()
ColorUIResource | getMenuBackground()
ColorUIResource | getMenuDisabledForeground()
ColorUIResource | getMenuForeground()
ColorUIResource | getMenuSelectedBackground()
ColorUIResource | getMenuSelectedForeground()
abstract FontUIResource | getMenuTextFont()
abstract String | getName()
protected abstract ColorUIResource | getPrimary1()
protected abstract ColorUIResource | getPrimary2()
protected abstract ColorUIResource | getPrimary3()
ColorUIResource | getPrimaryControl()
ColorUIResource | getPrimaryControlDarkShadow()
ColorUIResource | getPrimaryControlHighlight()
ColorUIResource | getPrimaryControlInfo()
ColorUIResource | getPrimaryControlShadow()
protected abstract ColorUIResource | getSecondary1()
protected abstract ColorUIResource | getSecondary2()
protected abstract ColorUIResource | getSecondary3()
ColorUIResource | getSeparatorBackground()
ColorUIResource | getSeparatorForeground()
abstract FontUIResource | getSubTextFont()
ColorUIResource | getSystemTextColor() Returns the color used, by default, for the text in labels and titled borders.
abstract FontUIResource | getSystemTextFont()
ColorUIResource | getTextHighlightColor()
ColorUIResource | getUserTextColor()
abstract FontUIResource | getUserTextFont()
protected ColorUIResource | getWhite()
ColorUIResource | getWindowBackground()
ColorUIResource | getWindowTitleBackground()
abstract FontUIResource | getWindowTitleFont()
ColorUIResource | getWindowTitleForeground()
ColorUIResource | getWindowTitleInactiveBackground()
ColorUIResource | getWindowTitleInactiveForeground()
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

MetalTheme

public MetalTheme()
Method Detail

getName

public abstract String getName()

getPrimary1

protected abstract ColorUIResource getPrimary1()

getPrimary2

protected abstract ColorUIResource getPrimary2()

getPrimary3

protected abstract ColorUIResource getPrimary3()

getSecondary1

protected abstract ColorUIResource getSecondary1()

getSecondary2

protected abstract ColorUIResource getSecondary2()

getSecondary3

protected abstract ColorUIResource getSecondary3()

getControlTextFont

public abstract FontUIResource getControlTextFont()

getSystemTextFont

public abstract FontUIResource getSystemTextFont()

getUserTextFont

public abstract FontUIResource getUserTextFont()

getMenuTextFont

public abstract FontUIResource getMenuTextFont()

getWindowTitleFont

public abstract FontUIResource getWindowTitleFont()

getSubTextFont

public abstract FontUIResource getSubTextFont()

getWhite

protected ColorUIResource getWhite()

getBlack

protected ColorUIResource getBlack()

getFocusColor

public ColorUIResource getFocusColor()

getDesktopColor

public ColorUIResource getDesktopColor()

getControl

public ColorUIResource getControl()

getControlShadow

public ColorUIResource getControlShadow()

getControlDarkShadow

public ColorUIResource getControlDarkShadow()

getControlInfo

public ColorUIResource getControlInfo()

getControlHighlight

public ColorUIResource getControlHighlight()

getControlDisabled

public ColorUIResource getControlDisabled()

getPrimaryControl

public ColorUIResource getPrimaryControl()

getPrimaryControlShadow

public ColorUIResource getPrimaryControlShadow()

getPrimaryControlDarkShadow

public ColorUIResource getPrimaryControlDarkShadow()

getPrimaryControlInfo

public ColorUIResource getPrimaryControlInfo()

getPrimaryControlHighlight

public ColorUIResource getPrimaryControlHighlight()

getSystemTextColor

public ColorUIResource getSystemTextColor()
Returns the color used, by default, for the text in labels and titled borders.

getControlTextColor

public ColorUIResource getControlTextColor()

getInactiveControlTextColor

public ColorUIResource getInactiveControlTextColor()

getInactiveSystemTextColor

public ColorUIResource getInactiveSystemTextColor()

getUserTextColor

public ColorUIResource getUserTextColor()

getTextHighlightColor

public ColorUIResource getTextHighlightColor()

getHighlightedTextColor

public ColorUIResource getHighlightedTextColor()

getWindowBackground

public ColorUIResource getWindowBackground()

getWindowTitleBackground

public ColorUIResource getWindowTitleBackground()

getWindowTitleForeground

public ColorUIResource getWindowTitleForeground()

getWindowTitleInactiveBackground

public ColorUIResource getWindowTitleInactiveBackground()

getWindowTitleInactiveForeground

public ColorUIResource getWindowTitleInactiveForeground()

getMenuBackground

public ColorUIResource getMenuBackground()

getMenuForeground

public ColorUIResource getMenuForeground()

getMenuSelectedBackground

public ColorUIResource getMenuSelectedBackground()

getMenuSelectedForeground

public ColorUIResource getMenuSelectedForeground()

getMenuDisabledForeground

public ColorUIResource getMenuDisabledForeground()

getSeparatorBackground

public ColorUIResource getSeparatorBackground()

getSeparatorForeground

public ColorUIResource getSeparatorForeground()

getAcceleratorForeground

public ColorUIResource getAcceleratorForeground()

getAcceleratorSelectedForeground

public ColorUIResource getAcceleratorSelectedForeground()

addCustomEntriesToTable

public void addCustomEntriesToTable(UIDefaults table)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MetalToggleButtonUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalToggleButtonUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.ButtonUI
            extended by javax.swing.plaf.basic.BasicButtonUI
                extended by javax.swing.plaf.basic.BasicToggleButtonUI
                    extended by javax.swing.plaf.metal.MetalToggleButtonUI
public class MetalToggleButtonUI
extends BasicToggleButtonUI

MetalToggleButton implementation

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Field Summary
protected Color | disabledTextColor
protected Color | focusColor
protected Color | selectColor
Fields inherited from class javax.swing.plaf.basic.BasicButtonUI
defaultTextIconGap, defaultTextShiftOffset
Constructor Summary
MetalToggleButtonUI()
Method Summary
static ComponentUI | createUI(JComponent b) Returns an instance of the UI delegate for the specified component.
protected Color | getDisabledTextColor()
protected Color | getFocusColor()
protected Color | getSelectColor()
void | installDefaults(AbstractButton b)
protected void | paintButtonPressed(Graphics g, AbstractButton b)
protected void | paintFocus(Graphics g, AbstractButton b, Rectangle viewRect, Rectangle textRect, Rectangle iconRect)
protected void | paintText(Graphics g, JComponent c, Rectangle textRect, String text) As of Java 2 platform v 1.4 this method should not be used or overriden.
protected void | uninstallDefaults(AbstractButton b)
Methods inherited from class javax.swing.plaf.basic.BasicToggleButtonUI
getPropertyPrefix, getTextShiftOffset, paint, paintIcon
Methods inherited from class javax.swing.plaf.basic.BasicButtonUI
clearTextShiftOffset, createButtonListener, getDefaultTextIconGap, getMaximumSize, getMinimumSize, getPreferredSize, installKeyboardActions, installListeners, installUI, paintIcon, paintText, setTextShiftOffset, uninstallKeyboardActions, uninstallListeners, uninstallUI
Methods inherited from class javax.swing.plaf.ComponentUI
contains, getAccessibleChild, getAccessibleChildrenCount, update
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

focusColor

protected Color focusColor

selectColor

protected Color selectColor

disabledTextColor

protected Color disabledTextColor
Constructor Detail

MetalToggleButtonUI

public MetalToggleButtonUI()
Method Detail

createUI

public static ComponentUI createUI(JComponent b)
Description copied from class: ComponentUI
Returns an instance of the UI delegate for the specified component. Each subclass must provide its own static createUI method that returns an instance of that UI delegate subclass. If the UI delegate subclass is stateless, it may return an instance that is shared by multiple components. If the UI delegate is stateful, then it should return a new instance per component. The default implementation of this method throws an error, as it should never be invoked.

installDefaults

public void installDefaults(AbstractButton b)
Overrides:
installDefaults in class BasicButtonUI

uninstallDefaults

protected void uninstallDefaults(AbstractButton b)
Overrides:
uninstallDefaults in class BasicButtonUI

getSelectColor

protected Color getSelectColor()

getDisabledTextColor

protected Color getDisabledTextColor()

getFocusColor

protected Color getFocusColor()

paintButtonPressed

protected void paintButtonPressed(Graphics g,
                                  AbstractButton b)
Overrides:
paintButtonPressed in class BasicButtonUI

paintText

protected void paintText(Graphics g,
                         JComponent c,
                         Rectangle textRect,
                         String text)
Description copied from class: BasicButtonUI
As of Java 2 platform v 1.4 this method should not be used or overriden. Use the paintText method which takes the AbstractButton argument.

Overrides:
paintText in class BasicButtonUI

paintFocus

protected void paintFocus(Graphics g,
                          AbstractButton b,
                          Rectangle viewRect,
                          Rectangle textRect,
                          Rectangle iconRect)
Overrides:
paintFocus in class BasicButtonUI
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MetalToolBarUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalToolBarUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.ToolBarUI
            extended by javax.swing.plaf.basic.BasicToolBarUI
                extended by javax.swing.plaf.metal.MetalToolBarUI
All Implemented Interfaces:
SwingConstants
public class MetalToolBarUI
extends BasicToolBarUI

A Metal Look and Feel implementation of ToolBarUI. This implementation is a "combined" view/controller.

Nested Class Summary
protected class | MetalToolBarUI.MetalContainerListener
protected class | MetalToolBarUI.MetalDockingListener
protected class | MetalToolBarUI.MetalRolloverListener
Nested classes inherited from class javax.swing.plaf.basic.BasicToolBarUI
BasicToolBarUI.DockingListener, BasicToolBarUI.DragWindow, BasicToolBarUI.FrameListener, BasicToolBarUI.PropertyListener, BasicToolBarUI.ToolBarContListener, BasicToolBarUI.ToolBarFocusListener
Field Summary
protected ContainerListener | contListener This protected field is implemenation specific.
protected PropertyChangeListener | rolloverListener This protected field is implemenation specific.
Fields inherited from class javax.swing.plaf.basic.BasicToolBarUI
constraintBeforeFloating, dockingBorderColor, dockingColor, dockingListener, downKey, dragWindow, floatingBorderColor, floatingColor, focusedCompIndex, leftKey, propertyListener, rightKey, toolBar, toolBarContListener, toolBarFocusListener, upKey
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
Constructor Summary
MetalToolBarUI()
Method Summary
protected ContainerListener | createContainerListener() Creates a container listener that will be added to the JToolBar.
protected MouseInputListener | createDockingListener()
protected Border | createNonRolloverBorder() Creates the non rollover border for toolbar components.
protected Border | createRolloverBorder() Creates a rollover border for toolbar components.
protected PropertyChangeListener | createRolloverListener() Creates a property change listener that will be added to the JToolBar.
static ComponentUI | createUI(JComponent c) Returns an instance of the UI delegate for the specified component.
protected void | installListeners()
void | installUI(JComponent c) Configures the specified component appropriate for the look and feel.
protected void | setBorderToNonRollover(Component c) Sets the border of the component to have a non-rollover border which was created by createNonRolloverBorder.
protected void | setDragOffset(Point p)
protected void | uninstallListeners()
void | uninstallUI(JComponent c) Reverses configuration which was done on the specified component during installUI.
Methods inherited from class javax.swing.plaf.basic.BasicToolBarUI
canDock, createDragWindow, createFloatingFrame, createFloatingWindow, createFrameListener, createPropertyListener, createToolBarContListener, createToolBarFocusListener, dragTo, floatAt, getDockingColor, getFloatingColor, getMaximumSize, getMinimumSize, getPreferredSize, installComponents, installDefaults, installKeyboardActions, installNonRolloverBorders, installNormalBorders, installRolloverBorders, isFloating, isRolloverBorders, navigateFocusedComp, setBorderToNormal, setBorderToRollover, setDockingColor, setFloating, setFloatingColor, setFloatingLocation, setOrientation, setRolloverBorders, uninstallComponents, uninstallDefaults, uninstallKeyboardActions
Methods inherited from class javax.swing.plaf.ComponentUI
contains, getAccessibleChild, getAccessibleChildrenCount, paint, update
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

contListener

protected ContainerListener contListener
This protected field is implemenation specific. Do not access directly or override. Use the create method instead.

See Also:
createContainerListener()

rolloverListener

protected PropertyChangeListener rolloverListener
This protected field is implemenation specific. Do not access directly or override. Use the create method instead.

See Also:
createRolloverListener()
Constructor Detail

MetalToolBarUI

public MetalToolBarUI()
Method Detail

createUI

public static ComponentUI createUI(JComponent c)
Description copied from class: ComponentUI
Returns an instance of the UI delegate for the specified component. Each subclass must provide its own static createUI method that returns an instance of that UI delegate subclass. If the UI delegate subclass is stateless, it may return an instance that is shared by multiple components. If the UI delegate is stateful, then it should return a new instance per component. The default implementation of this method throws an error, as it should never be invoked.

installUI

public void installUI(JComponent c)
Description copied from class: ComponentUI
Configures the specified component appropriate for the look and feel. This method is invoked when the ComponentUI instance is being installed as the UI delegate on the specified component. This method should completely configure the component for the look and feel, including the following:
  1. Install any default property values for color, fonts, borders, icons, opacity, etc. on the component. Whenever possible, property values initialized by the client program should not be overridden.
  2. Install a LayoutManager on the component if necessary.
  3. Create/add any required sub-components to the component.
  4. Create/install event listeners on the component.
  5. Create/install a PropertyChangeListener on the component in order to detect and respond to component property changes appropriately.
  6. Install keyboard UI (mnemonics, traversal, etc.) on the component.
  7. Initialize any appropriate instance data.

Overrides:
installUI in class BasicToolBarUI

uninstallUI

public void uninstallUI(JComponent c)
Description copied from class: ComponentUI
Reverses configuration which was done on the specified component during installUI. This method is invoked when this UIComponent instance is being removed as the UI delegate for the specified component. This method should undo the configuration performed in installUI, being careful to leave the JComponent instance in a clean state (no extraneous listeners, look-and-feel-specific property objects, etc.). This should include the following:
  1. Remove any UI-set borders from the component.
  2. Remove any UI-set layout managers on the component.
  3. Remove any UI-added sub-components from the component.
  4. Remove any UI-added event/property listeners from the component.
  5. Remove any UI-installed keyboard UI from the component.
  6. Nullify any allocated instance data objects to allow for GC.

Overrides:
uninstallUI in class BasicToolBarUI

installListeners

protected void installListeners()
Overrides:
installListeners in class BasicToolBarUI

uninstallListeners

protected void uninstallListeners()
Overrides:
uninstallListeners in class BasicToolBarUI

createRolloverBorder

protected Border createRolloverBorder()
Description copied from class: BasicToolBarUI
Creates a rollover border for toolbar components. The rollover border will be installed if rollover borders are enabled.

Override this method to provide an alternate rollover border.

Overrides:
createRolloverBorder in class BasicToolBarUI

createNonRolloverBorder

protected Border createNonRolloverBorder()
Description copied from class: BasicToolBarUI
Creates the non rollover border for toolbar components. This border will be installed as the border for components added to the toolbar if rollover borders are not enabled.

Override this method to provide an alternate rollover border.

Overrides:
createNonRolloverBorder in class BasicToolBarUI

setBorderToNonRollover

protected void setBorderToNonRollover(Component c)
Description copied from class: BasicToolBarUI
Sets the border of the component to have a non-rollover border which was created by createNonRolloverBorder.

Overrides:
setBorderToNonRollover in class BasicToolBarUI
Parameters:
c - component which will have a non-rollover border installed
See Also:
BasicToolBarUI.createNonRolloverBorder()

createContainerListener

protected ContainerListener createContainerListener()
Creates a container listener that will be added to the JToolBar. If this method returns null then it will not be added to the toolbar.

Returns:
an instance of a ContainerListener or null

createRolloverListener

protected PropertyChangeListener createRolloverListener()
Creates a property change listener that will be added to the JToolBar. If this method returns null then it will not be added to the toolbar.

Returns:
an instance of a PropertyChangeListener or null

createDockingListener

protected MouseInputListener createDockingListener()
Overrides:
createDockingListener in class BasicToolBarUI

setDragOffset

protected void setDragOffset(Point p)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MetalToolBarUI.MetalContainerListener (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalToolBarUI.MetalContainerListener

java.lang.Object
    extended by javax.swing.plaf.basic.BasicToolBarUI.ToolBarContListener
        extended by javax.swing.plaf.metal.MetalToolBarUI.MetalContainerListener
All Implemented Interfaces:
ContainerListener, EventListener
Enclosing class:
MetalToolBarUI
protected class MetalToolBarUI.MetalContainerListener
extends BasicToolBarUI.ToolBarContListener

Constructor Summary
protected MetalToolBarUI.MetalContainerListener()
Methods inherited from class javax.swing.plaf.basic.BasicToolBarUI.ToolBarContListener
componentAdded, componentRemoved
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

MetalToolBarUI.MetalContainerListener

protected MetalToolBarUI.MetalContainerListener()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MetalToolBarUI.MetalDockingListener (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalToolBarUI.MetalDockingListener

java.lang.Object
    extended by javax.swing.plaf.basic.BasicToolBarUI.DockingListener
        extended by javax.swing.plaf.metal.MetalToolBarUI.MetalDockingListener
All Implemented Interfaces:
EventListener, MouseInputListener, MouseListener, MouseMotionListener
Enclosing class:
MetalToolBarUI
protected class MetalToolBarUI.MetalDockingListener
extends BasicToolBarUI.DockingListener

Field Summary
Fields inherited from class javax.swing.plaf.basic.BasicToolBarUI.DockingListener
isDragging, origin, toolBar
Constructor Summary
MetalToolBarUI.MetalDockingListener(JToolBar t)
Method Summary
void | mouseDragged(MouseEvent e) Invoked when a mouse button is pressed on a component and then dragged.
void | mousePressed(MouseEvent e) Invoked when a mouse button has been pressed on a component.
Methods inherited from class javax.swing.plaf.basic.BasicToolBarUI.DockingListener
mouseClicked, mouseEntered, mouseExited, mouseMoved, mouseReleased
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

MetalToolBarUI.MetalDockingListener

public MetalToolBarUI.MetalDockingListener(JToolBar t)
Method Detail

mousePressed

public void mousePressed(MouseEvent e)
Description copied from interface: MouseListener
Invoked when a mouse button has been pressed on a component.

Specified by:
mousePressed in interface MouseListener
Overrides:
mousePressed in class BasicToolBarUI.DockingListener

mouseDragged

public void mouseDragged(MouseEvent e)
Description copied from interface: MouseMotionListener
Invoked when a mouse button is pressed on a component and then dragged. MOUSE_DRAGGED events will continue to be delivered to the component where the drag originated until the mouse button is released (regardless of whether the mouse position is within the bounds of the component).

Due to platform-dependent Drag&Drop implementations, MOUSE_DRAGGED events may not be delivered during a native Drag&Drop operation.

Specified by:
mouseDragged in interface MouseMotionListener
Overrides:
mouseDragged in class BasicToolBarUI.DockingListener
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MetalToolBarUI.MetalRolloverListener (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalToolBarUI.MetalRolloverListener

java.lang.Object
    extended by javax.swing.plaf.basic.BasicToolBarUI.PropertyListener
        extended by javax.swing.plaf.metal.MetalToolBarUI.MetalRolloverListener
All Implemented Interfaces:
EventListener, PropertyChangeListener
Enclosing class:
MetalToolBarUI
protected class MetalToolBarUI.MetalRolloverListener
extends BasicToolBarUI.PropertyListener

Constructor Summary
protected MetalToolBarUI.MetalRolloverListener()
Methods inherited from class javax.swing.plaf.basic.BasicToolBarUI.PropertyListener
propertyChange
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

MetalToolBarUI.MetalRolloverListener

protected MetalToolBarUI.MetalRolloverListener()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MetalToolTipUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalToolTipUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.ToolTipUI
            extended by javax.swing.plaf.basic.BasicToolTipUI
                extended by javax.swing.plaf.metal.MetalToolTipUI
public class MetalToolTipUI
extends BasicToolTipUI

A Metal L&F extension of BasicToolTipUI.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Field Summary
static int padSpaceBetweenStrings
Constructor Summary
MetalToolTipUI()
Method Summary
static ComponentUI | createUI(JComponent c) Returns an instance of the UI delegate for the specified component.
String | getAcceleratorString()
Dimension | getPreferredSize(JComponent c) Returns the specified component's preferred size appropriate for the look and feel.
void | installUI(JComponent c) Configures the specified component appropriate for the look and feel.
protected boolean | isAcceleratorHidden()
void | paint(Graphics g, JComponent c) Paints the specified component appropriate for the look and feel.
void | uninstallUI(JComponent c) Reverses configuration which was done on the specified component during installUI.
Methods inherited from class javax.swing.plaf.basic.BasicToolTipUI
getMaximumSize, getMinimumSize, installDefaults, installListeners, uninstallDefaults, uninstallListeners
Methods inherited from class javax.swing.plaf.ComponentUI
contains, getAccessibleChild, getAccessibleChildrenCount, update
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

padSpaceBetweenStrings

public static final int padSpaceBetweenStrings
See Also:
Constant Field Values
Constructor Detail

MetalToolTipUI

public MetalToolTipUI()
Method Detail

createUI

public static ComponentUI createUI(JComponent c)
Description copied from class: ComponentUI
Returns an instance of the UI delegate for the specified component. Each subclass must provide its own static createUI method that returns an instance of that UI delegate subclass. If the UI delegate subclass is stateless, it may return an instance that is shared by multiple components. If the UI delegate is stateful, then it should return a new instance per component. The default implementation of this method throws an error, as it should never be invoked.

installUI

public void installUI(JComponent c)
Description copied from class: ComponentUI
Configures the specified component appropriate for the look and feel. This method is invoked when the ComponentUI instance is being installed as the UI delegate on the specified component. This method should completely configure the component for the look and feel, including the following:
  1. Install any default property values for color, fonts, borders, icons, opacity, etc. on the component. Whenever possible, property values initialized by the client program should not be overridden.
  2. Install a LayoutManager on the component if necessary.
  3. Create/add any required sub-components to the component.
  4. Create/install event listeners on the component.
  5. Create/install a PropertyChangeListener on the component in order to detect and respond to component property changes appropriately.
  6. Install keyboard UI (mnemonics, traversal, etc.) on the component.
  7. Initialize any appropriate instance data.

Overrides:
installUI in class BasicToolTipUI

uninstallUI

public void uninstallUI(JComponent c)
Description copied from class: ComponentUI
Reverses configuration which was done on the specified component during installUI. This method is invoked when this UIComponent instance is being removed as the UI delegate for the specified component. This method should undo the configuration performed in installUI, being careful to leave the JComponent instance in a clean state (no extraneous listeners, look-and-feel-specific property objects, etc.). This should include the following:
  1. Remove any UI-set borders from the component.
  2. Remove any UI-set layout managers on the component.
  3. Remove any UI-added sub-components from the component.
  4. Remove any UI-added event/property listeners from the component.
  5. Remove any UI-installed keyboard UI from the component.
  6. Nullify any allocated instance data objects to allow for GC.

Overrides:
uninstallUI in class BasicToolTipUI

paint

public void paint(Graphics g,
                  JComponent c)
Description copied from class: ComponentUI
Paints the specified component appropriate for the look and feel. This method is invoked from the ComponentUI.update method when the specified component is being painted. Subclasses should override this method and use the specified Graphics object to render the content of the component.

Overrides:
paint in class BasicToolTipUI

getPreferredSize

public Dimension getPreferredSize(JComponent c)
Description copied from class: ComponentUI
Returns the specified component's preferred size appropriate for the look and feel. If null is returned, the preferred size will be calculated by the component's layout manager instead (this is the preferred approach for any component with a specific layout manager installed). The default implementation of this method returns null.

Overrides:
getPreferredSize in class BasicToolTipUI

isAcceleratorHidden

protected boolean isAcceleratorHidden()

getAcceleratorString

public String getAcceleratorString()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MetalTreeUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.metal
Class MetalTreeUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.TreeUI
            extended by javax.swing.plaf.basic.BasicTreeUI
                extended by javax.swing.plaf.metal.MetalTreeUI
public class MetalTreeUI
extends BasicTreeUI

The metal look and feel implementation of TreeUI.

MetalTreeUI allows for configuring how to visually render the spacing and delineation between nodes. The following hints are supported:

Angled | A line is drawn connecting the child to the parent. For handling of the root node refer to JTree.setRootVisible(boolean) and JTree.setShowsRootHandles(boolean).
Horizontal | A horizontal line is drawn dividing the children of the root node.
None | Do not draw any visual indication between nodes.

As it is typically impratical to obtain the TreeUI from the JTree and cast to an instance of MetalTreeUI you enable this property via the client property JTree.lineStyle. For example, to switch to Horizontal style you would do: tree.putClientProperty("JTree.lineStyle", "Horizontal");

The default is Angled.

Nested Class Summary
Nested classes inherited from class javax.swing.plaf.basic.BasicTreeUI
BasicTreeUI.CellEditorHandler, BasicTreeUI.ComponentHandler, BasicTreeUI.FocusHandler, BasicTreeUI.KeyHandler, BasicTreeUI.MouseHandler, BasicTreeUI.MouseInputHandler, BasicTreeUI.NodeDimensionsHandler, BasicTreeUI.PropertyChangeHandler, BasicTreeUI.SelectionModelPropertyChangeHandler, BasicTreeUI.TreeCancelEditingAction, BasicTreeUI.TreeExpansionHandler, BasicTreeUI.TreeHomeAction, BasicTreeUI.TreeIncrementAction, BasicTreeUI.TreeModelHandler, BasicTreeUI.TreePageAction, BasicTreeUI.TreeSelectionHandler, BasicTreeUI.TreeToggleAction, BasicTreeUI.TreeTraverseAction
Field Summary
Fields inherited from class javax.swing.plaf.basic.BasicTreeUI
cellEditor, collapsedIcon, createdCellEditor, createdRenderer, currentCellRenderer, depthOffset, drawingCache, editingComponent, editingPath, editingRow, editorHasDifferentSize, expandedIcon, largeModel, lastSelectedRow, leftChildIndent, nodeDimensions, preferredMinSize, preferredSize, rendererPane, rightChildIndent, stopEditingInCompleteEditing, totalChildIndent, tree, treeModel, treeSelectionModel, treeState, validCachedPreferredSize
Constructor Summary
MetalTreeUI()
Method Summary
static ComponentUI | createUI(JComponent x) Returns an instance of the UI delegate for the specified component.
protected void | decodeLineStyle(Object lineStyleFlag) this function converts between the string passed into the client property and the internal representation (currently and int)
protected int | getHorizontalLegBuffer() The horizontal element of legs between nodes starts at the right of the left-hand side of the child node by default.
void | installUI(JComponent c) Configures the specified component appropriate for the look and feel.
protected boolean | isLocationInExpandControl(int row, int rowLevel, int mouseX, int mouseY)
void | paint(Graphics g, JComponent c) Paints the specified component appropriate for the look and feel.
protected void | paintHorizontalPartOfLeg(Graphics g, Rectangle clipBounds, Insets insets, Rectangle bounds, TreePath path, int row, boolean isExpanded, boolean hasBeenExpanded, boolean isLeaf) Paints the horizontal part of the leg.
protected void | paintHorizontalSeparators(Graphics g, JComponent c)
protected void | paintVerticalPartOfLeg(Graphics g, Rectangle clipBounds, Insets insets, TreePath path) Paints the vertical part of the leg.
void | uninstallUI(JComponent c) Reverses configuration which was done on the specified component during installUI.
Methods inherited from class javax.swing.plaf.basic.BasicTreeUI
cancelEditing, checkForClickInExpandControl, completeEditing, completeEditing, completeUIInstall, completeUIUninstall, configureLayoutCache, createCellEditorListener, createCellRendererPane, createComponentListener, createDefaultCellEditor, createDefaultCellRenderer, createFocusListener, createKeyListener, createLayoutCache, createMouseListener, createNodeDimensions, createPropertyChangeListener, createSelectionModelPropertyChangeListener, createTreeExpansionListener, createTreeModelListener, createTreeSelectionListener, drawCentered, drawDashedHorizontalLine, drawDashedVerticalLine, ensureRowsAreVisible, getCellEditor, getCellRenderer, getClosestPathForLocation, getCollapsedIcon, getEditingPath, getExpandedIcon, getHashColor, getLastChildPath, getLeftChildIndent, getMaximumSize, getMinimumSize, getModel, getPathBounds, getPathForRow, getPreferredMinSize, getPreferredSize, getPreferredSize, getRightChildIndent, getRowCount, getRowForPath, getRowHeight, getSelectionModel, getShowsRootHandles, getVerticalLegBuffer, handleExpandControlClick, installComponents, installDefaults, installKeyboardActions, installListeners, isEditable, isEditing, isLargeModel, isLeaf, isLocationInExpandControl, isMultiSelectEvent, isRootVisible, isToggleEvent, isToggleSelectionEvent, paintExpandControl, paintHorizontalLine, paintRow, paintVerticalLine, pathWasCollapsed, pathWasExpanded, prepareForUIInstall, prepareForUIUninstall, selectPathForEvent, setCellEditor, setCellRenderer, setCollapsedIcon, setEditable, setExpandedIcon, setHashColor, setLargeModel, setLeftChildIndent, setModel, setPreferredMinSize, setRightChildIndent, setRootVisible, setRowHeight, setSelectionModel, setShowsRootHandles, shouldPaintExpandControl, startEditing, startEditingAtPath, stopEditing, toggleExpandState, uninstallComponents, uninstallDefaults, uninstallKeyboardActions, uninstallListeners, updateCachedPreferredSize, updateCellEditor, updateDepthOffset, updateExpandedDescendants, updateLayoutCacheExpandedNodes, updateRenderer, updateSize
Methods inherited from class javax.swing.plaf.ComponentUI
contains, getAccessibleChild, getAccessibleChildrenCount, update
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

MetalTreeUI

public MetalTreeUI()
Method Detail

createUI

public static ComponentUI createUI(JComponent x)
Description copied from class: ComponentUI
Returns an instance of the UI delegate for the specified component. Each subclass must provide its own static createUI method that returns an instance of that UI delegate subclass. If the UI delegate subclass is stateless, it may return an instance that is shared by multiple components. If the UI delegate is stateful, then it should return a new instance per component. The default implementation of this method throws an error, as it should never be invoked.

getHorizontalLegBuffer

protected int getHorizontalLegBuffer()
Description copied from class: BasicTreeUI
The horizontal element of legs between nodes starts at the right of the left-hand side of the child node by default. This method makes the leg end before that.

Overrides:
getHorizontalLegBuffer in class BasicTreeUI

installUI

public void installUI(JComponent c)
Description copied from class: ComponentUI
Configures the specified component appropriate for the look and feel. This method is invoked when the ComponentUI instance is being installed as the UI delegate on the specified component. This method should completely configure the component for the look and feel, including the following:
  1. Install any default property values for color, fonts, borders, icons, opacity, etc. on the component. Whenever possible, property values initialized by the client program should not be overridden.
  2. Install a LayoutManager on the component if necessary.
  3. Create/add any required sub-components to the component.
  4. Create/install event listeners on the component.
  5. Create/install a PropertyChangeListener on the component in order to detect and respond to component property changes appropriately.
  6. Install keyboard UI (mnemonics, traversal, etc.) on the component.
  7. Initialize any appropriate instance data.

Overrides:
installUI in class BasicTreeUI

uninstallUI

public void uninstallUI(JComponent c)
Description copied from class: ComponentUI
Reverses configuration which was done on the specified component during installUI. This method is invoked when this UIComponent instance is being removed as the UI delegate for the specified component. This method should undo the configuration performed in installUI, being careful to leave the JComponent instance in a clean state (no extraneous listeners, look-and-feel-specific property objects, etc.). This should include the following:
  1. Remove any UI-set borders from the component.
  2. Remove any UI-set layout managers on the component.
  3. Remove any UI-added sub-components from the component.
  4. Remove any UI-added event/property listeners from the component.
  5. Remove any UI-installed keyboard UI from the component.
  6. Nullify any allocated instance data objects to allow for GC.

Overrides:
uninstallUI in class BasicTreeUI

decodeLineStyle

protected void decodeLineStyle(Object lineStyleFlag)
this function converts between the string passed into the client property and the internal representation (currently and int)

isLocationInExpandControl

protected boolean isLocationInExpandControl(int row,
                                            int rowLevel,
                                            int mouseX,
                                            int mouseY)

paint

public void paint(Graphics g,
                  JComponent c)
Description copied from class: ComponentUI
Paints the specified component appropriate for the look and feel. This method is invoked from the ComponentUI.update method when the specified component is being painted. Subclasses should override this method and use the specified Graphics object to render the content of the component.

Overrides:
paint in class BasicTreeUI

paintHorizontalSeparators

protected void paintHorizontalSeparators(Graphics g,
                                         JComponent c)

paintVerticalPartOfLeg

protected void paintVerticalPartOfLeg(Graphics g,
                                      Rectangle clipBounds,
                                      Insets insets,
                                      TreePath path)
Description copied from class: BasicTreeUI
Paints the vertical part of the leg. The receiver should NOT modify clipBounds, insets.

Overrides:
paintVerticalPartOfLeg in class BasicTreeUI

paintHorizontalPartOfLeg

protected void paintHorizontalPartOfLeg(Graphics g,
                                        Rectangle clipBounds,
                                        Insets insets,
                                        Rectangle bounds,
                                        TreePath path,
                                        int row,
                                        boolean isExpanded,
                                        boolean hasBeenExpanded,
                                        boolean isLeaf)
Description copied from class: BasicTreeUI
Paints the horizontal part of the leg. The receiver should NOT modify clipBounds, or insets.

NOTE: parentRow can be -1 if the root is not visible.

Overrides:
paintHorizontalPartOfLeg in class BasicTreeUI
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


javax.swing.plaf.metal (Java 2 Platform SE v1.4.2)

 javax.swing.plaf.metal
Classes
DefaultMetalTheme
MetalBorders
MetalBorders.ButtonBorder
MetalBorders.Flush3DBorder
MetalBorders.InternalFrameBorder
MetalBorders.MenuBarBorder
MetalBorders.MenuItemBorder
MetalBorders.OptionDialogBorder
MetalBorders.PaletteBorder
MetalBorders.PopupMenuBorder
MetalBorders.RolloverButtonBorder
MetalBorders.ScrollPaneBorder
MetalBorders.TableHeaderBorder
MetalBorders.TextFieldBorder
MetalBorders.ToggleButtonBorder
MetalBorders.ToolBarBorder
MetalButtonUI
MetalCheckBoxIcon
MetalCheckBoxUI
MetalComboBoxButton
MetalComboBoxEditor
MetalComboBoxEditor.UIResource
MetalComboBoxIcon
MetalComboBoxUI
MetalDesktopIconUI
MetalFileChooserUI
MetalIconFactory
MetalIconFactory.FileIcon16
MetalIconFactory.FolderIcon16
MetalIconFactory.PaletteCloseIcon
MetalIconFactory.TreeControlIcon
MetalIconFactory.TreeFolderIcon
MetalIconFactory.TreeLeafIcon
MetalInternalFrameTitlePane
MetalInternalFrameUI
MetalLabelUI
MetalLookAndFeel
MetalPopupMenuSeparatorUI
MetalProgressBarUI
MetalRadioButtonUI
MetalRootPaneUI
MetalScrollBarUI
MetalScrollButton
MetalScrollPaneUI
MetalSeparatorUI
MetalSliderUI
MetalSplitPaneUI
MetalTabbedPaneUI
MetalTextFieldUI
MetalTheme
MetalToggleButtonUI
MetalToolBarUI
MetalToolTipUI
MetalTreeUI


javax.swing.plaf.metal (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

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.

See:
Description

Class Summary
DefaultMetalTheme | This class describes the default Metal Theme.
MetalBorders | Factory object that can vend Borders appropriate for the metal L & F.
MetalBorders.ButtonBorder |
MetalBorders.Flush3DBorder |
MetalBorders.InternalFrameBorder |
MetalBorders.MenuBarBorder |
MetalBorders.MenuItemBorder |
MetalBorders.OptionDialogBorder |
MetalBorders.PaletteBorder | Border for a Palette.
MetalBorders.PopupMenuBorder |
MetalBorders.RolloverButtonBorder |
MetalBorders.ScrollPaneBorder |
MetalBorders.TableHeaderBorder | Border for a Table Header
MetalBorders.TextFieldBorder |
MetalBorders.ToggleButtonBorder |
MetalBorders.ToolBarBorder |
MetalButtonUI | MetalButtonUI implementation
MetalCheckBoxIcon | CheckboxIcon implementation for OrganicCheckBoxUI
MetalCheckBoxUI | CheckboxUI implementation for MetalCheckboxUI
MetalComboBoxButton | JButton subclass to help out MetalComboBoxUI
MetalComboBoxEditor | The default editor for Metal editable combo boxes
MetalComboBoxEditor.UIResource | A subclass of BasicComboBoxEditor that implements UIResource.
MetalComboBoxIcon | This utility class draws the horizontal bars which indicate a MetalComboBox
MetalComboBoxUI | Metal UI for JComboBox
MetalDesktopIconUI | Metal desktop icon.
MetalFileChooserUI | Metal L&F implementation of a FileChooser.
MetalIconFactory | Factory object that vends Icons for the JavaTM look and feel (Metal).
MetalIconFactory.FileIcon16 | Warning: Serialized objects of this class will not be compatible with future Swing releases.
MetalIconFactory.FolderIcon16 | Warning: Serialized objects of this class will not be compatible with future Swing releases.
MetalIconFactory.PaletteCloseIcon | Defines an icon for Palette close
MetalIconFactory.TreeControlIcon | Warning: Serialized objects of this class will not be compatible with future Swing releases.
MetalIconFactory.TreeFolderIcon | Warning: Serialized objects of this class will not be compatible with future Swing releases.
MetalIconFactory.TreeLeafIcon |
MetalInternalFrameTitlePane | Class that manages a JLF title bar
MetalInternalFrameUI | Metal implementation of JInternalFrame.
MetalLabelUI | A Windows L&F implementation of LabelUI.
MetalLookAndFeel | Implements the Java look and feel (codename: Metal).
MetalPopupMenuSeparatorUI | A Metal L&F implementation of PopupMenuSeparatorUI.
MetalProgressBarUI | The Metal implementation of ProgressBarUI.
MetalRadioButtonUI | RadioButtonUI implementation for MetalRadioButtonUI
MetalRootPaneUI | Provides the metal look and feel implementation of RootPaneUI.
MetalScrollBarUI | Implementation of ScrollBarUI for the Metal Look and Feel
MetalScrollButton | JButton object for Metal scrollbar arrows.
MetalScrollPaneUI | A Metal L&F implementation of ScrollPaneUI.
MetalSeparatorUI | A Metal L&F implementation of SeparatorUI.
MetalSliderUI | A Java L&F implementation of SliderUI.
MetalSplitPaneUI | Metal split pane.
MetalTabbedPaneUI | The Metal subclass of BasicTabbedPaneUI.
MetalTextFieldUI | Basis of a look and feel for a JTextField.
MetalTheme | This interface acts as a generic way to describe the colors used by Metal.
MetalToggleButtonUI | MetalToggleButton implementation
MetalToolBarUI | A Metal Look and Feel implementation of ToolBarUI.
MetalToolTipUI | A Metal L&F extension of BasicToolTipUI.
MetalTreeUI | The metal look and feel implementation of TreeUI.

Package javax.swing.plaf.metal Description

Provides user interface objects built according to the Java look and feel (once codenamed Metal), which is the default look and feel.

These classes are designed to be used while the corresponding LookAndFeel class has been installed (UIManager.setLookAndFeel(new XXXLookAndFeel())). Using them while a different LookAndFeel is installed may produce unexpected results, including exceptions. Additionally, changing the LookAndFeel maintained by the UIManager without updating the corresponding ComponentUI of any JComponents may also produce unexpected results, such as the wrong colors showing up, and is generally not encouraged.

Note: Most of the Swing API is not thread safe. For details, see Threads and Swing, a section in The Java Tutorial.

Since:
1.2
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


javax.swing.plaf.metal Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package javax.swing.plaf.metal

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class javax.swing.AbstractAction (implements javax.swing.Action, java.lang.Cloneable, java.io.Serializable)
      • class javax.swing.plaf.metal.MetalFileChooserUI.DirectoryComboBoxAction
    • class javax.swing.border.AbstractBorder (implements javax.swing.border.Border, java.io.Serializable)
      • class javax.swing.plaf.metal.MetalBorders.ButtonBorder (implements javax.swing.plaf.UIResource)
        • class javax.swing.plaf.metal.MetalBorders.RolloverButtonBorder
        • class javax.swing.plaf.metal.MetalBorders.ToggleButtonBorder
      • class javax.swing.plaf.metal.MetalBorders.Flush3DBorder (implements javax.swing.plaf.UIResource)
        • class javax.swing.plaf.metal.MetalBorders.TextFieldBorder
      • class javax.swing.plaf.metal.MetalBorders.InternalFrameBorder (implements javax.swing.plaf.UIResource)
      • class javax.swing.plaf.metal.MetalBorders.MenuBarBorder (implements javax.swing.plaf.UIResource)
      • class javax.swing.plaf.metal.MetalBorders.MenuItemBorder (implements javax.swing.plaf.UIResource)
      • class javax.swing.plaf.metal.MetalBorders.OptionDialogBorder (implements javax.swing.plaf.UIResource)
      • class javax.swing.plaf.metal.MetalBorders.PaletteBorder (implements javax.swing.plaf.UIResource)
      • class javax.swing.plaf.metal.MetalBorders.PopupMenuBorder (implements javax.swing.plaf.UIResource)
      • class javax.swing.plaf.metal.MetalBorders.ScrollPaneBorder (implements javax.swing.plaf.UIResource)
      • class javax.swing.plaf.metal.MetalBorders.TableHeaderBorder
      • class javax.swing.plaf.metal.MetalBorders.ToolBarBorder (implements javax.swing.SwingConstants, javax.swing.plaf.UIResource)
    • class javax.swing.AbstractListModel (implements javax.swing.ListModel, java.io.Serializable)
      • class javax.swing.plaf.metal.MetalFileChooserUI.DirectoryComboBoxModel (implements javax.swing.ComboBoxModel)
      • class javax.swing.plaf.metal.MetalFileChooserUI.FilterComboBoxModel (implements javax.swing.ComboBoxModel, java.beans.PropertyChangeListener)
    • class javax.swing.plaf.basic.BasicComboBoxEditor (implements javax.swing.ComboBoxEditor, java.awt.event.FocusListener)
      • class javax.swing.plaf.metal.MetalComboBoxEditor
        • class javax.swing.plaf.metal.MetalComboBoxEditor.UIResource (implements javax.swing.plaf.UIResource)
    • class javax.swing.plaf.basic.BasicComboBoxUI.ComboBoxLayoutManager (implements java.awt.LayoutManager)
      • class javax.swing.plaf.metal.MetalComboBoxUI.MetalComboBoxLayoutManager
    • class javax.swing.plaf.basic.BasicComboBoxUI.PropertyChangeHandler (implements java.beans.PropertyChangeListener)
      • class javax.swing.plaf.metal.MetalComboBoxUI.MetalPropertyChangeListener
    • class javax.swing.plaf.basic.BasicSliderUI.PropertyChangeHandler (implements java.beans.PropertyChangeListener)
      • class javax.swing.plaf.metal.MetalSliderUI.MetalPropertyListener
    • class javax.swing.plaf.basic.BasicTabbedPaneUI.TabbedPaneLayout (implements java.awt.LayoutManager)
      • class javax.swing.plaf.metal.MetalTabbedPaneUI.TabbedPaneLayout
    • class javax.swing.plaf.basic.BasicToolBarUI.DockingListener (implements javax.swing.event.MouseInputListener)
      • class javax.swing.plaf.metal.MetalToolBarUI.MetalDockingListener
    • class javax.swing.plaf.basic.BasicToolBarUI.PropertyListener (implements java.beans.PropertyChangeListener)
      • class javax.swing.plaf.metal.MetalToolBarUI.MetalRolloverListener
    • class javax.swing.plaf.basic.BasicToolBarUI.ToolBarContListener (implements java.awt.event.ContainerListener)
      • class javax.swing.plaf.metal.MetalToolBarUI.MetalContainerListener
    • class java.awt.Component (implements java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable)
      • class java.awt.Container
        • class javax.swing.JComponent (implements java.io.Serializable)
          • class javax.swing.AbstractButton (implements java.awt.ItemSelectable, javax.swing.SwingConstants)
            • class javax.swing.JButton (implements javax.accessibility.Accessible)
              • class javax.swing.plaf.basic.BasicArrowButton (implements javax.swing.SwingConstants)
                • class javax.swing.plaf.metal.MetalScrollButton
              • class javax.swing.plaf.metal.MetalComboBoxButton
          • class javax.swing.plaf.basic.BasicInternalFrameTitlePane
            • class javax.swing.plaf.metal.MetalInternalFrameTitlePane
          • class javax.swing.JLabel (implements javax.accessibility.Accessible, javax.swing.SwingConstants)
            • class javax.swing.DefaultListCellRenderer (implements javax.swing.ListCellRenderer, java.io.Serializable)
              • class javax.swing.plaf.metal.MetalFileChooserUI.FileRenderer
              • class javax.swing.plaf.metal.MetalFileChooserUI.FilterComboBoxRenderer
          • class javax.swing.JPopupMenu (implements javax.accessibility.Accessible, javax.swing.MenuElement)
            • class javax.swing.plaf.basic.BasicComboPopup (implements javax.swing.plaf.basic.ComboPopup)
              • class javax.swing.plaf.metal.MetalComboBoxUI.MetalComboPopup
    • class javax.swing.plaf.ComponentUI
      • class javax.swing.plaf.ButtonUI
        • class javax.swing.plaf.basic.BasicButtonUI
          • class javax.swing.plaf.basic.BasicToggleButtonUI
            • class javax.swing.plaf.basic.BasicRadioButtonUI
              • class javax.swing.plaf.metal.MetalRadioButtonUI
                • class javax.swing.plaf.metal.MetalCheckBoxUI
            • class javax.swing.plaf.metal.MetalToggleButtonUI
          • class javax.swing.plaf.metal.MetalButtonUI
      • class javax.swing.plaf.ComboBoxUI
        • class javax.swing.plaf.basic.BasicComboBoxUI
          • class javax.swing.plaf.metal.MetalComboBoxUI
      • class javax.swing.plaf.DesktopIconUI
        • class javax.swing.plaf.basic.BasicDesktopIconUI
          • class javax.swing.plaf.metal.MetalDesktopIconUI
      • class javax.swing.plaf.FileChooserUI
        • class javax.swing.plaf.basic.BasicFileChooserUI
          • class javax.swing.plaf.metal.MetalFileChooserUI
      • class javax.swing.plaf.InternalFrameUI
        • class javax.swing.plaf.basic.BasicInternalFrameUI
          • class javax.swing.plaf.metal.MetalInternalFrameUI
      • class javax.swing.plaf.LabelUI
        • class javax.swing.plaf.basic.BasicLabelUI (implements java.beans.PropertyChangeListener)
          • class javax.swing.plaf.metal.MetalLabelUI
      • class javax.swing.plaf.ProgressBarUI
        • class javax.swing.plaf.basic.BasicProgressBarUI
          • class javax.swing.plaf.metal.MetalProgressBarUI
      • class javax.swing.plaf.RootPaneUI
        • class javax.swing.plaf.basic.BasicRootPaneUI (implements java.beans.PropertyChangeListener)
          • class javax.swing.plaf.metal.MetalRootPaneUI
      • class javax.swing.plaf.ScrollBarUI
        • class javax.swing.plaf.basic.BasicScrollBarUI (implements java.awt.LayoutManager, javax.swing.SwingConstants)
          • class javax.swing.plaf.metal.MetalScrollBarUI
      • class javax.swing.plaf.ScrollPaneUI
        • class javax.swing.plaf.basic.BasicScrollPaneUI (implements javax.swing.ScrollPaneConstants)
          • class javax.swing.plaf.metal.MetalScrollPaneUI
      • class javax.swing.plaf.SeparatorUI
        • class javax.swing.plaf.basic.BasicSeparatorUI
          • class javax.swing.plaf.metal.MetalSeparatorUI
            • class javax.swing.plaf.metal.MetalPopupMenuSeparatorUI
      • class javax.swing.plaf.SliderUI
        • class javax.swing.plaf.basic.BasicSliderUI
          • class javax.swing.plaf.metal.MetalSliderUI
      • class javax.swing.plaf.SplitPaneUI
        • class javax.swing.plaf.basic.BasicSplitPaneUI
          • class javax.swing.plaf.metal.MetalSplitPaneUI
      • class javax.swing.plaf.TabbedPaneUI
        • class javax.swing.plaf.basic.BasicTabbedPaneUI (implements javax.swing.SwingConstants)
          • class javax.swing.plaf.metal.MetalTabbedPaneUI
      • class javax.swing.plaf.TextUI
        • class javax.swing.plaf.basic.BasicTextUI (implements javax.swing.text.ViewFactory)
          • class javax.swing.plaf.basic.BasicTextFieldUI
            • class javax.swing.plaf.metal.MetalTextFieldUI
      • class javax.swing.plaf.ToolBarUI
        • class javax.swing.plaf.basic.BasicToolBarUI (implements javax.swing.SwingConstants)
          • class javax.swing.plaf.metal.MetalToolBarUI
      • class javax.swing.plaf.ToolTipUI
        • class javax.swing.plaf.basic.BasicToolTipUI
          • class javax.swing.plaf.metal.MetalToolTipUI
      • class javax.swing.plaf.TreeUI
        • class javax.swing.plaf.basic.BasicTreeUI
          • class javax.swing.plaf.metal.MetalTreeUI
    • class javax.swing.LookAndFeel
      • class javax.swing.plaf.basic.BasicLookAndFeel (implements java.io.Serializable)
        • class javax.swing.plaf.metal.MetalLookAndFeel
    • class javax.swing.plaf.metal.MetalBorders
    • class javax.swing.plaf.metal.MetalCheckBoxIcon (implements javax.swing.Icon, java.io.Serializable, javax.swing.plaf.UIResource)
    • class javax.swing.plaf.metal.MetalComboBoxIcon (implements javax.swing.Icon, java.io.Serializable)
    • class javax.swing.plaf.metal.MetalIconFactory (implements java.io.Serializable)
    • class javax.swing.plaf.metal.MetalIconFactory.FileIcon16 (implements javax.swing.Icon, java.io.Serializable)
      • class javax.swing.plaf.metal.MetalIconFactory.TreeLeafIcon
    • class javax.swing.plaf.metal.MetalIconFactory.FolderIcon16 (implements javax.swing.Icon, java.io.Serializable)
      • class javax.swing.plaf.metal.MetalIconFactory.TreeFolderIcon
    • class javax.swing.plaf.metal.MetalIconFactory.PaletteCloseIcon (implements javax.swing.Icon, java.io.Serializable, javax.swing.plaf.UIResource)
    • class javax.swing.plaf.metal.MetalIconFactory.TreeControlIcon (implements javax.swing.Icon, java.io.Serializable)
    • class javax.swing.plaf.metal.MetalTheme
      • class javax.swing.plaf.metal.DefaultMetalTheme
    • class java.awt.event.MouseAdapter (implements java.awt.event.MouseListener)
      • class javax.swing.plaf.metal.MetalFileChooserUI.SingleClickListener
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package javax.swing.plaf.metal (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
javax.swing.plaf.metal

Packages that use javax.swing.plaf.metal
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.

Classes in javax.swing.plaf.metal used by javax.swing.plaf.metal
MetalBorders.ButtonBorder
MetalBorders.Flush3DBorder
MetalComboBoxEditor
The default editor for Metal editable combo boxes
MetalComboBoxUI.MetalComboBoxLayoutManager
This inner class is marked "public" due to a compiler bug.
MetalFileChooserUI.DirectoryComboBoxModel
Data model for a type-face selection combo-box.
MetalFileChooserUI.FilterComboBoxModel
Data model for a type-face selection combo-box.
MetalFileChooserUI.FilterComboBoxRenderer
Render different type sizes and styles.
MetalIconFactory.FileIcon16
Warning: Serialized objects of this class will not be compatible with future Swing releases.
MetalIconFactory.FolderIcon16
Warning: Serialized objects of this class will not be compatible with future Swing releases.
MetalLabelUI
A Windows L&F implementation of LabelUI.
MetalRadioButtonUI
RadioButtonUI implementation for MetalRadioButtonUI
MetalScrollButton
JButton object for Metal scrollbar arrows.
MetalSeparatorUI
A Metal L&F implementation of SeparatorUI.
MetalTheme
This interface acts as a generic way to describe the colors used by Metal.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.DefaultMetalTheme (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.DefaultMetalTheme

No usage of javax.swing.plaf.metal.DefaultMetalTheme

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalBorders (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalBorders

No usage of javax.swing.plaf.metal.MetalBorders

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalBorders.ButtonBorder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalBorders.ButtonBorder

Packages that use MetalBorders.ButtonBorder
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.

Uses of MetalBorders.ButtonBorder in javax.swing.plaf.metal

Subclasses of MetalBorders.ButtonBorder in javax.swing.plaf.metal
static class | MetalBorders.RolloverButtonBorder
static class | MetalBorders.ToggleButtonBorder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalBorders.Flush3DBorder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalBorders.Flush3DBorder

Packages that use MetalBorders.Flush3DBorder
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.

Uses of MetalBorders.Flush3DBorder in javax.swing.plaf.metal

Subclasses of MetalBorders.Flush3DBorder in javax.swing.plaf.metal
static class MetalBorders.TextFieldBorder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalBorders.InternalFrameBorder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalBorders.InternalFrameBorder

No usage of javax.swing.plaf.metal.MetalBorders.InternalFrameBorder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalBorders.MenuBarBorder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalBorders.MenuBarBorder

No usage of javax.swing.plaf.metal.MetalBorders.MenuBarBorder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalBorders.MenuItemBorder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalBorders.MenuItemBorder

No usage of javax.swing.plaf.metal.MetalBorders.MenuItemBorder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalBorders.OptionDialogBorder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalBorders.OptionDialogBorder

No usage of javax.swing.plaf.metal.MetalBorders.OptionDialogBorder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalBorders.PaletteBorder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalBorders.PaletteBorder

No usage of javax.swing.plaf.metal.MetalBorders.PaletteBorder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalBorders.PopupMenuBorder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalBorders.PopupMenuBorder

No usage of javax.swing.plaf.metal.MetalBorders.PopupMenuBorder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalBorders.RolloverButtonBorder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalBorders.RolloverButtonBorder

No usage of javax.swing.plaf.metal.MetalBorders.RolloverButtonBorder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalBorders.ScrollPaneBorder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalBorders.ScrollPaneBorder

No usage of javax.swing.plaf.metal.MetalBorders.ScrollPaneBorder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalBorders.TableHeaderBorder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalBorders.TableHeaderBorder

No usage of javax.swing.plaf.metal.MetalBorders.TableHeaderBorder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalBorders.TextFieldBorder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalBorders.TextFieldBorder

No usage of javax.swing.plaf.metal.MetalBorders.TextFieldBorder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalBorders.ToggleButtonBorder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalBorders.ToggleButtonBorder

No usage of javax.swing.plaf.metal.MetalBorders.ToggleButtonBorder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalBorders.ToolBarBorder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalBorders.ToolBarBorder

No usage of javax.swing.plaf.metal.MetalBorders.ToolBarBorder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalButtonUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalButtonUI

No usage of javax.swing.plaf.metal.MetalButtonUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalCheckBoxIcon (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalCheckBoxIcon

No usage of javax.swing.plaf.metal.MetalCheckBoxIcon

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalCheckBoxUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalCheckBoxUI

No usage of javax.swing.plaf.metal.MetalCheckBoxUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalComboBoxButton (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalComboBoxButton

No usage of javax.swing.plaf.metal.MetalComboBoxButton

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalComboBoxEditor (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalComboBoxEditor

Packages that use MetalComboBoxEditor
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.

Uses of MetalComboBoxEditor in javax.swing.plaf.metal

Subclasses of MetalComboBoxEditor in javax.swing.plaf.metal
static class MetalComboBoxEditor.UIResource
A subclass of BasicComboBoxEditor that implements UIResource.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalComboBoxEditor.UIResource (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalComboBoxEditor.UIResource

No usage of javax.swing.plaf.metal.MetalComboBoxEditor.UIResource

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalComboBoxIcon (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalComboBoxIcon

No usage of javax.swing.plaf.metal.MetalComboBoxIcon

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalComboBoxUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalComboBoxUI

No usage of javax.swing.plaf.metal.MetalComboBoxUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalComboBoxUI.MetalComboBoxLayoutManager (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalComboBoxUI.MetalComboBoxLayoutManager

Packages that use MetalComboBoxUI.MetalComboBoxLayoutManager
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.

Uses of MetalComboBoxUI.MetalComboBoxLayoutManager in javax.swing.plaf.metal

Methods in javax.swing.plaf.metal with parameters of type MetalComboBoxUI.MetalComboBoxLayoutManager
 void MetalComboBoxUI.layoutComboBox(Container parent, MetalComboBoxUI.MetalComboBoxLayoutManager manager)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalComboBoxUI.MetalComboPopup (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalComboBoxUI.MetalComboPopup

No usage of javax.swing.plaf.metal.MetalComboBoxUI.MetalComboPopup

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalComboBoxUI.MetalPropertyChangeListener (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalComboBoxUI.MetalPropertyChangeListener

No usage of javax.swing.plaf.metal.MetalComboBoxUI.MetalPropertyChangeListener

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalDesktopIconUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalDesktopIconUI

No usage of javax.swing.plaf.metal.MetalDesktopIconUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalFileChooserUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalFileChooserUI

No usage of javax.swing.plaf.metal.MetalFileChooserUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalFileChooserUI.DirectoryComboBoxAction (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalFileChooserUI.DirectoryComboBoxAction

No usage of javax.swing.plaf.metal.MetalFileChooserUI.DirectoryComboBoxAction

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalFileChooserUI.DirectoryComboBoxModel (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalFileChooserUI.DirectoryComboBoxModel

Packages that use MetalFileChooserUI.DirectoryComboBoxModel
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.

Uses of MetalFileChooserUI.DirectoryComboBoxModel in javax.swing.plaf.metal

Methods in javax.swing.plaf.metal that return MetalFileChooserUI.DirectoryComboBoxModel
protected  MetalFileChooserUI.DirectoryComboBoxModel MetalFileChooserUI.createDirectoryComboBoxModel(JFileChooser fc)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalFileChooserUI.FileRenderer (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalFileChooserUI.FileRenderer

No usage of javax.swing.plaf.metal.MetalFileChooserUI.FileRenderer

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalFileChooserUI.FilterComboBoxModel (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalFileChooserUI.FilterComboBoxModel

Packages that use MetalFileChooserUI.FilterComboBoxModel
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.

Uses of MetalFileChooserUI.FilterComboBoxModel in javax.swing.plaf.metal

Methods in javax.swing.plaf.metal that return MetalFileChooserUI.FilterComboBoxModel
protected  MetalFileChooserUI.FilterComboBoxModel MetalFileChooserUI.createFilterComboBoxModel()

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalFileChooserUI.FilterComboBoxRenderer (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalFileChooserUI.FilterComboBoxRenderer

Packages that use MetalFileChooserUI.FilterComboBoxRenderer
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.

Uses of MetalFileChooserUI.FilterComboBoxRenderer in javax.swing.plaf.metal

Methods in javax.swing.plaf.metal that return MetalFileChooserUI.FilterComboBoxRenderer
protected  MetalFileChooserUI.FilterComboBoxRenderer MetalFileChooserUI.createFilterComboBoxRenderer()

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalFileChooserUI.SingleClickListener (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalFileChooserUI.SingleClickListener

No usage of javax.swing.plaf.metal.MetalFileChooserUI.SingleClickListener

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalIconFactory (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalIconFactory

No usage of javax.swing.plaf.metal.MetalIconFactory

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalIconFactory.FileIcon16 (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalIconFactory.FileIcon16

Packages that use MetalIconFactory.FileIcon16
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.

Uses of MetalIconFactory.FileIcon16 in javax.swing.plaf.metal

Subclasses of MetalIconFactory.FileIcon16 in javax.swing.plaf.metal
static class MetalIconFactory.TreeLeafIcon

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalIconFactory.FolderIcon16 (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalIconFactory.FolderIcon16

Packages that use MetalIconFactory.FolderIcon16
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.

Uses of MetalIconFactory.FolderIcon16 in javax.swing.plaf.metal

Subclasses of MetalIconFactory.FolderIcon16 in javax.swing.plaf.metal
static class MetalIconFactory.TreeFolderIcon
Warning: Serialized objects of this class will not be compatible with future Swing releases.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalIconFactory.PaletteCloseIcon (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalIconFactory.PaletteCloseIcon

No usage of javax.swing.plaf.metal.MetalIconFactory.PaletteCloseIcon

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalIconFactory.TreeControlIcon (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalIconFactory.TreeControlIcon

No usage of javax.swing.plaf.metal.MetalIconFactory.TreeControlIcon

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalIconFactory.TreeFolderIcon (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalIconFactory.TreeFolderIcon

No usage of javax.swing.plaf.metal.MetalIconFactory.TreeFolderIcon

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalIconFactory.TreeLeafIcon (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalIconFactory.TreeLeafIcon

No usage of javax.swing.plaf.metal.MetalIconFactory.TreeLeafIcon

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalInternalFrameTitlePane (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalInternalFrameTitlePane

No usage of javax.swing.plaf.metal.MetalInternalFrameTitlePane

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalInternalFrameUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalInternalFrameUI

No usage of javax.swing.plaf.metal.MetalInternalFrameUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalLabelUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalLabelUI

Packages that use MetalLabelUI
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.

Uses of MetalLabelUI in javax.swing.plaf.metal

Fields in javax.swing.plaf.metal declared as MetalLabelUI
protected static MetalLabelUI MetalLabelUI.metalLabelUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalLookAndFeel (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalLookAndFeel

No usage of javax.swing.plaf.metal.MetalLookAndFeel

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalPopupMenuSeparatorUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalPopupMenuSeparatorUI

No usage of javax.swing.plaf.metal.MetalPopupMenuSeparatorUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalProgressBarUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalProgressBarUI

No usage of javax.swing.plaf.metal.MetalProgressBarUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalRadioButtonUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalRadioButtonUI

Packages that use MetalRadioButtonUI
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.

Uses of MetalRadioButtonUI in javax.swing.plaf.metal

Subclasses of MetalRadioButtonUI in javax.swing.plaf.metal
 class MetalCheckBoxUI
CheckboxUI implementation for MetalCheckboxUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalRootPaneUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalRootPaneUI

No usage of javax.swing.plaf.metal.MetalRootPaneUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalScrollBarUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalScrollBarUI

No usage of javax.swing.plaf.metal.MetalScrollBarUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalScrollButton (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalScrollButton

Packages that use MetalScrollButton
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.

Uses of MetalScrollButton in javax.swing.plaf.metal

Fields in javax.swing.plaf.metal declared as MetalScrollButton
protected MetalScrollButton | MetalScrollBarUI.increaseButton
protected MetalScrollButton | MetalScrollBarUI.decreaseButton

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalScrollPaneUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalScrollPaneUI

No usage of javax.swing.plaf.metal.MetalScrollPaneUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalSeparatorUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalSeparatorUI

Packages that use MetalSeparatorUI
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.

Uses of MetalSeparatorUI in javax.swing.plaf.metal

Subclasses of MetalSeparatorUI in javax.swing.plaf.metal
 class MetalPopupMenuSeparatorUI
A Metal L&F implementation of PopupMenuSeparatorUI.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalSliderUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalSliderUI

No usage of javax.swing.plaf.metal.MetalSliderUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalSliderUI.MetalPropertyListener (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalSliderUI.MetalPropertyListener

No usage of javax.swing.plaf.metal.MetalSliderUI.MetalPropertyListener

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalSplitPaneUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalSplitPaneUI

No usage of javax.swing.plaf.metal.MetalSplitPaneUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalTabbedPaneUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalTabbedPaneUI

No usage of javax.swing.plaf.metal.MetalTabbedPaneUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalTabbedPaneUI.TabbedPaneLayout (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalTabbedPaneUI.TabbedPaneLayout

No usage of javax.swing.plaf.metal.MetalTabbedPaneUI.TabbedPaneLayout

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalTextFieldUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalTextFieldUI

No usage of javax.swing.plaf.metal.MetalTextFieldUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalTheme (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalTheme

Packages that use MetalTheme
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.

Uses of MetalTheme in javax.swing.plaf.metal

Subclasses of MetalTheme in javax.swing.plaf.metal
 class DefaultMetalTheme
This class describes the default Metal Theme.

Methods in javax.swing.plaf.metal with parameters of type MetalTheme
static void MetalLookAndFeel.setCurrentTheme(MetalTheme theme)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalToggleButtonUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalToggleButtonUI

No usage of javax.swing.plaf.metal.MetalToggleButtonUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalToolBarUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalToolBarUI

No usage of javax.swing.plaf.metal.MetalToolBarUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalToolBarUI.MetalContainerListener (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalToolBarUI.MetalContainerListener

No usage of javax.swing.plaf.metal.MetalToolBarUI.MetalContainerListener

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalToolBarUI.MetalDockingListener (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalToolBarUI.MetalDockingListener

No usage of javax.swing.plaf.metal.MetalToolBarUI.MetalDockingListener

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalToolBarUI.MetalRolloverListener (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalToolBarUI.MetalRolloverListener

No usage of javax.swing.plaf.metal.MetalToolBarUI.MetalRolloverListener

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalToolTipUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalToolTipUI

No usage of javax.swing.plaf.metal.MetalToolTipUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.metal.MetalTreeUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.metal.MetalTreeUI

No usage of javax.swing.plaf.metal.MetalTreeUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


MultiButtonUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.multi
Class MultiButtonUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.ButtonUI
            extended by javax.swing.plaf.multi.MultiButtonUI
public class MultiButtonUI
extends ButtonUI

A multiplexing UI used to combine ButtonUIs.

This file was automatically generated by AutoMulti.

Field Summary
protected  Vector uis
The vector containing the real UIs.
Constructor Summary
MultiButtonUI()
Method Summary
boolean | contains(JComponent a, int b, int c) Invokes the contains method on each UI handled by this object.
static ComponentUI | createUI(JComponent a) Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI.
Accessible | getAccessibleChild(JComponent a, int b) Invokes the getAccessibleChild method on each UI handled by this object.
int | getAccessibleChildrenCount(JComponent a) Invokes the getAccessibleChildrenCount method on each UI handled by this object.
Dimension | getMaximumSize(JComponent a) Invokes the getMaximumSize method on each UI handled by this object.
Dimension | getMinimumSize(JComponent a) Invokes the getMinimumSize method on each UI handled by this object.
Dimension | getPreferredSize(JComponent a) Invokes the getPreferredSize method on each UI handled by this object.
ComponentUI[] | getUIs() Returns the list of UIs associated with this multiplexing UI.
void | installUI(JComponent a) Invokes the installUI method on each UI handled by this object.
void | paint(Graphics a, JComponent b) Invokes the paint method on each UI handled by this object.
void | uninstallUI(JComponent a) Invokes the uninstallUI method on each UI handled by this object.
void | update(Graphics a, JComponent b) Invokes the update method on each UI handled by this object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

uis

protected Vector uis
The vector containing the real UIs. This is populated in the call to createUI, and can be obtained by calling the getUIs method. The first element is guaranteed to be the real UI obtained from the default look and feel.

Constructor Detail

MultiButtonUI

public MultiButtonUI()
Method Detail

getUIs

public ComponentUI[] getUIs()
Returns the list of UIs associated with this multiplexing UI. This allows processing of the UIs by an application aware of multiplexing UIs on components.

contains

public boolean contains(JComponent a,
                        int b,
                        int c)
Invokes the contains method on each UI handled by this object.

Overrides:
contains in class ComponentUI
Parameters:
a - the component where the x,y location is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
b - the x coordinate of the point
c - the y coordinate of the point
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.contains(int, int), Component.contains(int, int)

update

public void update(Graphics a,
                   JComponent b)
Invokes the update method on each UI handled by this object.

Overrides:
update in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.paint(java.awt.Graphics, javax.swing.JComponent), JComponent.paintComponent(java.awt.Graphics)

createUI

public static ComponentUI createUI(JComponent a)
Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI. Otherwise, just returns the UI object obtained from the default LookAndFeel.

installUI

public void installUI(JComponent a)
Invokes the installUI method on each UI handled by this object.

Overrides:
installUI in class ComponentUI
Parameters:
a - the component where this UI delegate is being installed
See Also:
ComponentUI.uninstallUI(javax.swing.JComponent),
JComponent.setUI(javax.swing.plaf.ComponentUI),
JComponent.updateUI()

uninstallUI

public void uninstallUI(JComponent a)
Invokes the uninstallUI method on each UI handled by this object.

Overrides:
uninstallUI in class ComponentUI
Parameters:
a - the component from which this UI delegate is being removed; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.installUI(javax.swing.JComponent), JComponent.updateUI()

paint

public void paint(Graphics a,
                  JComponent b)
Invokes the paint method on each UI handled by this object.

Overrides:
paint in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.update(java.awt.Graphics, javax.swing.JComponent)

getPreferredSize

public Dimension getPreferredSize(JComponent a)
Invokes the getPreferredSize method on each UI handled by this object.

Overrides:
getPreferredSize in class ComponentUI
Parameters:
a - the component whose preferred size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getPreferredSize(), LayoutManager.preferredLayoutSize(java.awt.Container)

getMinimumSize

public Dimension getMinimumSize(JComponent a)
Invokes the getMinimumSize method on each UI handled by this object.

Overrides:
getMinimumSize in class ComponentUI
Parameters:
a - the component whose minimum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMinimumSize(),
LayoutManager.minimumLayoutSize(java.awt.Container),
ComponentUI.getPreferredSize(javax.swing.JComponent)

getMaximumSize

public Dimension getMaximumSize(JComponent a)
Invokes the getMaximumSize method on each UI handled by this object.

Overrides:
getMaximumSize in class ComponentUI
Parameters:
a - the component whose maximum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMaximumSize(), LayoutManager2.maximumLayoutSize(java.awt.Container)

getAccessibleChildrenCount

public int getAccessibleChildrenCount(JComponent a)
Invokes the getAccessibleChildrenCount method on each UI handled by this object.

Overrides:
getAccessibleChildrenCount in class ComponentUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChild(javax.swing.JComponent, int)

getAccessibleChild

public Accessible getAccessibleChild(JComponent a,
                                     int b)
Invokes the getAccessibleChild method on each UI handled by this object.

Overrides:
getAccessibleChild in class ComponentUI
Parameters:
b - zero-based index of child
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChildrenCount(javax.swing.JComponent)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


MultiColorChooserUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.multi
Class MultiColorChooserUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.ColorChooserUI
            extended by javax.swing.plaf.multi.MultiColorChooserUI
public class MultiColorChooserUI
extends ColorChooserUI

A multiplexing UI used to combine ColorChooserUIs.

This file was automatically generated by AutoMulti.

Field Summary
protected  Vector uis
The vector containing the real UIs.
Constructor Summary
MultiColorChooserUI()
Method Summary
boolean | contains(JComponent a, int b, int c) Invokes the contains method on each UI handled by this object.
static ComponentUI | createUI(JComponent a) Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI.
Accessible | getAccessibleChild(JComponent a, int b) Invokes the getAccessibleChild method on each UI handled by this object.
int | getAccessibleChildrenCount(JComponent a) Invokes the getAccessibleChildrenCount method on each UI handled by this object.
Dimension | getMaximumSize(JComponent a) Invokes the getMaximumSize method on each UI handled by this object.
Dimension | getMinimumSize(JComponent a) Invokes the getMinimumSize method on each UI handled by this object.
Dimension | getPreferredSize(JComponent a) Invokes the getPreferredSize method on each UI handled by this object.
ComponentUI[] | getUIs() Returns the list of UIs associated with this multiplexing UI.
void | installUI(JComponent a) Invokes the installUI method on each UI handled by this object.
void | paint(Graphics a, JComponent b) Invokes the paint method on each UI handled by this object.
void | uninstallUI(JComponent a) Invokes the uninstallUI method on each UI handled by this object.
void | update(Graphics a, JComponent b) Invokes the update method on each UI handled by this object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

uis

protected Vector uis
The vector containing the real UIs. This is populated in the call to createUI, and can be obtained by calling the getUIs method. The first element is guaranteed to be the real UI obtained from the default look and feel.

Constructor Detail

MultiColorChooserUI

public MultiColorChooserUI()
Method Detail

getUIs

public ComponentUI[] getUIs()
Returns the list of UIs associated with this multiplexing UI. This allows processing of the UIs by an application aware of multiplexing UIs on components.

contains

public boolean contains(JComponent a,
                        int b,
                        int c)
Invokes the contains method on each UI handled by this object.

Overrides:
contains in class ComponentUI
Parameters:
a - the component where the x,y location is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
b - the x coordinate of the point
c - the y coordinate of the point
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.contains(int, int), Component.contains(int, int)

update

public void update(Graphics a,
                   JComponent b)
Invokes the update method on each UI handled by this object.

Overrides:
update in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.paint(java.awt.Graphics, javax.swing.JComponent), JComponent.paintComponent(java.awt.Graphics)

createUI

public static ComponentUI createUI(JComponent a)
Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI. Otherwise, just returns the UI object obtained from the default LookAndFeel.

installUI

public void installUI(JComponent a)
Invokes the installUI method on each UI handled by this object.

Overrides:
installUI in class ComponentUI
Parameters:
a - the component where this UI delegate is being installed
See Also:
ComponentUI.uninstallUI(javax.swing.JComponent),
JComponent.setUI(javax.swing.plaf.ComponentUI),
JComponent.updateUI()

uninstallUI

public void uninstallUI(JComponent a)
Invokes the uninstallUI method on each UI handled by this object.

Overrides:
uninstallUI in class ComponentUI
Parameters:
a - the component from which this UI delegate is being removed; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.installUI(javax.swing.JComponent), JComponent.updateUI()

paint

public void paint(Graphics a,
                  JComponent b)
Invokes the paint method on each UI handled by this object.

Overrides:
paint in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.update(java.awt.Graphics, javax.swing.JComponent)

getPreferredSize

public Dimension getPreferredSize(JComponent a)
Invokes the getPreferredSize method on each UI handled by this object.

Overrides:
getPreferredSize in class ComponentUI
Parameters:
a - the component whose preferred size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getPreferredSize(), LayoutManager.preferredLayoutSize(java.awt.Container)

getMinimumSize

public Dimension getMinimumSize(JComponent a)
Invokes the getMinimumSize method on each UI handled by this object.

Overrides:
getMinimumSize in class ComponentUI
Parameters:
a - the component whose minimum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMinimumSize(),
LayoutManager.minimumLayoutSize(java.awt.Container),
ComponentUI.getPreferredSize(javax.swing.JComponent)

getMaximumSize

public Dimension getMaximumSize(JComponent a)
Invokes the getMaximumSize method on each UI handled by this object.

Overrides:
getMaximumSize in class ComponentUI
Parameters:
a - the component whose maximum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMaximumSize(), LayoutManager2.maximumLayoutSize(java.awt.Container)

getAccessibleChildrenCount

public int getAccessibleChildrenCount(JComponent a)
Invokes the getAccessibleChildrenCount method on each UI handled by this object.

Overrides:
getAccessibleChildrenCount in class ComponentUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChild(javax.swing.JComponent, int)

getAccessibleChild

public Accessible getAccessibleChild(JComponent a,
                                     int b)
Invokes the getAccessibleChild method on each UI handled by this object.

Overrides:
getAccessibleChild in class ComponentUI
Parameters:
b - zero-based index of child
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChildrenCount(javax.swing.JComponent)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MultiComboBoxUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.multi
Class MultiComboBoxUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.ComboBoxUI
            extended by javax.swing.plaf.multi.MultiComboBoxUI
public class MultiComboBoxUI
extends ComboBoxUI

A multiplexing UI used to combine ComboBoxUIs.

This file was automatically generated by AutoMulti.

Field Summary
protected  Vector uis
The vector containing the real UIs.
Constructor Summary
MultiComboBoxUI()
Method Summary
boolean | contains(JComponent a, int b, int c) Invokes the contains method on each UI handled by this object.
static ComponentUI | createUI(JComponent a) Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI.
Accessible | getAccessibleChild(JComponent a, int b) Invokes the getAccessibleChild method on each UI handled by this object.
int | getAccessibleChildrenCount(JComponent a) Invokes the getAccessibleChildrenCount method on each UI handled by this object.
Dimension | getMaximumSize(JComponent a) Invokes the getMaximumSize method on each UI handled by this object.
Dimension | getMinimumSize(JComponent a) Invokes the getMinimumSize method on each UI handled by this object.
Dimension | getPreferredSize(JComponent a) Invokes the getPreferredSize method on each UI handled by this object.
ComponentUI[] | getUIs() Returns the list of UIs associated with this multiplexing UI.
void | installUI(JComponent a) Invokes the installUI method on each UI handled by this object.
boolean | isFocusTraversable(JComboBox a) Invokes the isFocusTraversable method on each UI handled by this object.
boolean | isPopupVisible(JComboBox a) Invokes the isPopupVisible method on each UI handled by this object.
void | paint(Graphics a, JComponent b) Invokes the paint method on each UI handled by this object.
void | setPopupVisible(JComboBox a, boolean b) Invokes the setPopupVisible method on each UI handled by this object.
void | uninstallUI(JComponent a) Invokes the uninstallUI method on each UI handled by this object.
void | update(Graphics a, JComponent b) Invokes the update method on each UI handled by this object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

uis

protected Vector uis
The vector containing the real UIs. This is populated in the call to createUI, and can be obtained by calling the getUIs method. The first element is guaranteed to be the real UI obtained from the default look and feel.

Constructor Detail

MultiComboBoxUI

public MultiComboBoxUI()
Method Detail

getUIs

public ComponentUI[] getUIs()
Returns the list of UIs associated with this multiplexing UI. This allows processing of the UIs by an application aware of multiplexing UIs on components.

isFocusTraversable

public boolean isFocusTraversable(JComboBox a)
Invokes the isFocusTraversable method on each UI handled by this object.

Specified by:
isFocusTraversable in class ComboBoxUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel

setPopupVisible

public void setPopupVisible(JComboBox a,
                            boolean b)
Invokes the setPopupVisible method on each UI handled by this object.

Specified by:
setPopupVisible in class ComboBoxUI

isPopupVisible

public boolean isPopupVisible(JComboBox a)
Invokes the isPopupVisible method on each UI handled by this object.

Specified by:
isPopupVisible in class ComboBoxUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel

contains

public boolean contains(JComponent a,
                        int b,
                        int c)
Invokes the contains method on each UI handled by this object.

Overrides:
contains in class ComponentUI
Parameters:
a - the component where the x,y location is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
b - the x coordinate of the point
c - the y coordinate of the point
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.contains(int, int), Component.contains(int, int)

update

public void update(Graphics a,
                   JComponent b)
Invokes the update method on each UI handled by this object.

Overrides:
update in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.paint(java.awt.Graphics, javax.swing.JComponent), JComponent.paintComponent(java.awt.Graphics)

createUI

public static ComponentUI createUI(JComponent a)
Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI. Otherwise, just returns the UI object obtained from the default LookAndFeel.

installUI

public void installUI(JComponent a)
Invokes the installUI method on each UI handled by this object.

Overrides:
installUI in class ComponentUI
Parameters:
a - the component where this UI delegate is being installed
See Also:
ComponentUI.uninstallUI(javax.swing.JComponent),
JComponent.setUI(javax.swing.plaf.ComponentUI),
JComponent.updateUI()

uninstallUI

public void uninstallUI(JComponent a)
Invokes the uninstallUI method on each UI handled by this object.

Overrides:
uninstallUI in class ComponentUI
Parameters:
a - the component from which this UI delegate is being removed; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.installUI(javax.swing.JComponent), JComponent.updateUI()

paint

public void paint(Graphics a,
                  JComponent b)
Invokes the paint method on each UI handled by this object.

Overrides:
paint in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.update(java.awt.Graphics, javax.swing.JComponent)

getPreferredSize

public Dimension getPreferredSize(JComponent a)
Invokes the getPreferredSize method on each UI handled by this object.

Overrides:
getPreferredSize in class ComponentUI
Parameters:
a - the component whose preferred size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getPreferredSize(), LayoutManager.preferredLayoutSize(java.awt.Container)

getMinimumSize

public Dimension getMinimumSize(JComponent a)
Invokes the getMinimumSize method on each UI handled by this object.

Overrides:
getMinimumSize in class ComponentUI
Parameters:
a - the component whose minimum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMinimumSize(),
LayoutManager.minimumLayoutSize(java.awt.Container),
ComponentUI.getPreferredSize(javax.swing.JComponent)

getMaximumSize

public Dimension getMaximumSize(JComponent a)
Invokes the getMaximumSize method on each UI handled by this object.

Overrides:
getMaximumSize in class ComponentUI
Parameters:
a - the component whose maximum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMaximumSize(), LayoutManager2.maximumLayoutSize(java.awt.Container)

getAccessibleChildrenCount

public int getAccessibleChildrenCount(JComponent a)
Invokes the getAccessibleChildrenCount method on each UI handled by this object.

Overrides:
getAccessibleChildrenCount in class ComponentUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChild(javax.swing.JComponent, int)

getAccessibleChild

public Accessible getAccessibleChild(JComponent a,
                                     int b)
Invokes the getAccessibleChild method on each UI handled by this object.

Overrides:
getAccessibleChild in class ComponentUI
Parameters:
b - zero-based index of child
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChildrenCount(javax.swing.JComponent)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MultiDesktopIconUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.multi
Class MultiDesktopIconUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.DesktopIconUI
            extended by javax.swing.plaf.multi.MultiDesktopIconUI
public class MultiDesktopIconUI
extends DesktopIconUI

A multiplexing UI used to combine DesktopIconUIs.

This file was automatically generated by AutoMulti.

Field Summary
protected  Vector uis
The vector containing the real UIs.
Constructor Summary
MultiDesktopIconUI()
Method Summary
boolean | contains(JComponent a, int b, int c) Invokes the contains method on each UI handled by this object.
static ComponentUI | createUI(JComponent a) Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI.
Accessible | getAccessibleChild(JComponent a, int b) Invokes the getAccessibleChild method on each UI handled by this object.
int | getAccessibleChildrenCount(JComponent a) Invokes the getAccessibleChildrenCount method on each UI handled by this object.
Dimension | getMaximumSize(JComponent a) Invokes the getMaximumSize method on each UI handled by this object.
Dimension | getMinimumSize(JComponent a) Invokes the getMinimumSize method on each UI handled by this object.
Dimension | getPreferredSize(JComponent a) Invokes the getPreferredSize method on each UI handled by this object.
ComponentUI[] | getUIs() Returns the list of UIs associated with this multiplexing UI.
void | installUI(JComponent a) Invokes the installUI method on each UI handled by this object.
void | paint(Graphics a, JComponent b) Invokes the paint method on each UI handled by this object.
void | uninstallUI(JComponent a) Invokes the uninstallUI method on each UI handled by this object.
void | update(Graphics a, JComponent b) Invokes the update method on each UI handled by this object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

uis

protected Vector uis
The vector containing the real UIs. This is populated in the call to createUI, and can be obtained by calling the getUIs method. The first element is guaranteed to be the real UI obtained from the default look and feel.

Constructor Detail

MultiDesktopIconUI

public MultiDesktopIconUI()
Method Detail

getUIs

public ComponentUI[] getUIs()
Returns the list of UIs associated with this multiplexing UI. This allows processing of the UIs by an application aware of multiplexing UIs on components.

contains

public boolean contains(JComponent a,
                        int b,
                        int c)
Invokes the contains method on each UI handled by this object.

Overrides:
contains in class ComponentUI
Parameters:
a - the component where the x,y location is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
b - the x coordinate of the point
c - the y coordinate of the point
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.contains(int, int), Component.contains(int, int)

update

public void update(Graphics a,
                   JComponent b)
Invokes the update method on each UI handled by this object.

Overrides:
update in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.paint(java.awt.Graphics, javax.swing.JComponent), JComponent.paintComponent(java.awt.Graphics)

createUI

public static ComponentUI createUI(JComponent a)
Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI. Otherwise, just returns the UI object obtained from the default LookAndFeel.

installUI

public void installUI(JComponent a)
Invokes the installUI method on each UI handled by this object.

Overrides:
installUI in class ComponentUI
Parameters:
a - the component where this UI delegate is being installed
See Also:
ComponentUI.uninstallUI(javax.swing.JComponent),
JComponent.setUI(javax.swing.plaf.ComponentUI),
JComponent.updateUI()

uninstallUI

public void uninstallUI(JComponent a)
Invokes the uninstallUI method on each UI handled by this object.

Overrides:
uninstallUI in class ComponentUI
Parameters:
a - the component from which this UI delegate is being removed; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.installUI(javax.swing.JComponent), JComponent.updateUI()

paint

public void paint(Graphics a,
                  JComponent b)
Invokes the paint method on each UI handled by this object.

Overrides:
paint in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.update(java.awt.Graphics, javax.swing.JComponent)

getPreferredSize

public Dimension getPreferredSize(JComponent a)
Invokes the getPreferredSize method on each UI handled by this object.

Overrides:
getPreferredSize in class ComponentUI
Parameters:
a - the component whose preferred size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getPreferredSize(), LayoutManager.preferredLayoutSize(java.awt.Container)

getMinimumSize

public Dimension getMinimumSize(JComponent a)
Invokes the getMinimumSize method on each UI handled by this object.

Overrides:
getMinimumSize in class ComponentUI
Parameters:
a - the component whose minimum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMinimumSize(),
LayoutManager.minimumLayoutSize(java.awt.Container),
ComponentUI.getPreferredSize(javax.swing.JComponent)

getMaximumSize

public Dimension getMaximumSize(JComponent a)
Invokes the getMaximumSize method on each UI handled by this object.

Overrides:
getMaximumSize in class ComponentUI
Parameters:
a - the component whose maximum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMaximumSize(), LayoutManager2.maximumLayoutSize(java.awt.Container)

getAccessibleChildrenCount

public int getAccessibleChildrenCount(JComponent a)
Invokes the getAccessibleChildrenCount method on each UI handled by this object.

Overrides:
getAccessibleChildrenCount in class ComponentUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChild(javax.swing.JComponent, int)

getAccessibleChild

public Accessible getAccessibleChild(JComponent a,
                                     int b)
Invokes the getAccessibleChild method on each UI handled by this object.

Overrides:
getAccessibleChild in class ComponentUI
Parameters:
b - zero-based index of child
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChildrenCount(javax.swing.JComponent)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MultiDesktopPaneUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.multi
Class MultiDesktopPaneUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.DesktopPaneUI
            extended by javax.swing.plaf.multi.MultiDesktopPaneUI
public class MultiDesktopPaneUI
extends DesktopPaneUI

A multiplexing UI used to combine DesktopPaneUIs.

This file was automatically generated by AutoMulti.

Field Summary
protected  Vector uis
The vector containing the real UIs.
Constructor Summary
MultiDesktopPaneUI()
Method Summary
boolean | contains(JComponent a, int b, int c) Invokes the contains method on each UI handled by this object.
static ComponentUI | createUI(JComponent a) Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI.
Accessible | getAccessibleChild(JComponent a, int b) Invokes the getAccessibleChild method on each UI handled by this object.
int | getAccessibleChildrenCount(JComponent a) Invokes the getAccessibleChildrenCount method on each UI handled by this object.
Dimension | getMaximumSize(JComponent a) Invokes the getMaximumSize method on each UI handled by this object.
Dimension | getMinimumSize(JComponent a) Invokes the getMinimumSize method on each UI handled by this object.
Dimension | getPreferredSize(JComponent a) Invokes the getPreferredSize method on each UI handled by this object.
ComponentUI[] | getUIs() Returns the list of UIs associated with this multiplexing UI.
void | installUI(JComponent a) Invokes the installUI method on each UI handled by this object.
void | paint(Graphics a, JComponent b) Invokes the paint method on each UI handled by this object.
void | uninstallUI(JComponent a) Invokes the uninstallUI method on each UI handled by this object.
void | update(Graphics a, JComponent b) Invokes the update method on each UI handled by this object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

uis

protected Vector uis
The vector containing the real UIs. This is populated in the call to createUI, and can be obtained by calling the getUIs method. The first element is guaranteed to be the real UI obtained from the default look and feel.

Constructor Detail

MultiDesktopPaneUI

public MultiDesktopPaneUI()
Method Detail

getUIs

public ComponentUI[] getUIs()
Returns the list of UIs associated with this multiplexing UI. This allows processing of the UIs by an application aware of multiplexing UIs on components.

contains

public boolean contains(JComponent a,
                        int b,
                        int c)
Invokes the contains method on each UI handled by this object.

Overrides:
contains in class ComponentUI
Parameters:
a - the component where the x,y location is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
b - the x coordinate of the point
c - the y coordinate of the point
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.contains(int, int), Component.contains(int, int)

update

public void update(Graphics a,
                   JComponent b)
Invokes the update method on each UI handled by this object.

Overrides:
update in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.paint(java.awt.Graphics, javax.swing.JComponent), JComponent.paintComponent(java.awt.Graphics)

createUI

public static ComponentUI createUI(JComponent a)
Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI. Otherwise, just returns the UI object obtained from the default LookAndFeel.

installUI

public void installUI(JComponent a)
Invokes the installUI method on each UI handled by this object.

Overrides:
installUI in class ComponentUI
Parameters:
a - the component where this UI delegate is being installed
See Also:
ComponentUI.uninstallUI(javax.swing.JComponent),
JComponent.setUI(javax.swing.plaf.ComponentUI),
JComponent.updateUI()

uninstallUI

public void uninstallUI(JComponent a)
Invokes the uninstallUI method on each UI handled by this object.

Overrides:
uninstallUI in class ComponentUI
Parameters:
a - the component from which this UI delegate is being removed; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.installUI(javax.swing.JComponent), JComponent.updateUI()

paint

public void paint(Graphics a,
                  JComponent b)
Invokes the paint method on each UI handled by this object.

Overrides:
paint in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.update(java.awt.Graphics, javax.swing.JComponent)

getPreferredSize

public Dimension getPreferredSize(JComponent a)
Invokes the getPreferredSize method on each UI handled by this object.

Overrides:
getPreferredSize in class ComponentUI
Parameters:
a - the component whose preferred size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getPreferredSize(), LayoutManager.preferredLayoutSize(java.awt.Container)

getMinimumSize

public Dimension getMinimumSize(JComponent a)
Invokes the getMinimumSize method on each UI handled by this object.

Overrides:
getMinimumSize in class ComponentUI
Parameters:
a - the component whose minimum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMinimumSize(),
LayoutManager.minimumLayoutSize(java.awt.Container),
ComponentUI.getPreferredSize(javax.swing.JComponent)

getMaximumSize

public Dimension getMaximumSize(JComponent a)
Invokes the getMaximumSize method on each UI handled by this object.

Overrides:
getMaximumSize in class ComponentUI
Parameters:
a - the component whose maximum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMaximumSize(), LayoutManager2.maximumLayoutSize(java.awt.Container)

getAccessibleChildrenCount

public int getAccessibleChildrenCount(JComponent a)
Invokes the getAccessibleChildrenCount method on each UI handled by this object.

Overrides:
getAccessibleChildrenCount in class ComponentUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChild(javax.swing.JComponent, int)

getAccessibleChild

public Accessible getAccessibleChild(JComponent a,
                                     int b)
Invokes the getAccessibleChild method on each UI handled by this object.

Overrides:
getAccessibleChild in class ComponentUI
Parameters:
b - zero-based index of child
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChildrenCount(javax.swing.JComponent)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MultiFileChooserUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.multi
Class MultiFileChooserUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.FileChooserUI
            extended by javax.swing.plaf.multi.MultiFileChooserUI
public class MultiFileChooserUI
extends FileChooserUI

A multiplexing UI used to combine FileChooserUIs.

This file was automatically generated by AutoMulti.

Field Summary
protected  Vector uis
The vector containing the real UIs.
Constructor Summary
MultiFileChooserUI()
Method Summary
boolean | contains(JComponent a, int b, int c) Invokes the contains method on each UI handled by this object.
static ComponentUI | createUI(JComponent a) Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI.
void | ensureFileIsVisible(JFileChooser a, File b) Invokes the ensureFileIsVisible method on each UI handled by this object.
FileFilter | getAcceptAllFileFilter(JFileChooser a) Invokes the getAcceptAllFileFilter method on each UI handled by this object.
Accessible | getAccessibleChild(JComponent a, int b) Invokes the getAccessibleChild method on each UI handled by this object.
int | getAccessibleChildrenCount(JComponent a) Invokes the getAccessibleChildrenCount method on each UI handled by this object.
String | getApproveButtonText(JFileChooser a) Invokes the getApproveButtonText method on each UI handled by this object.
String | getDialogTitle(JFileChooser a) Invokes the getDialogTitle method on each UI handled by this object.
FileView | getFileView(JFileChooser a) Invokes the getFileView method on each UI handled by this object.
Dimension | getMaximumSize(JComponent a) Invokes the getMaximumSize method on each UI handled by this object.
Dimension | getMinimumSize(JComponent a) Invokes the getMinimumSize method on each UI handled by this object.
Dimension | getPreferredSize(JComponent a) Invokes the getPreferredSize method on each UI handled by this object.
ComponentUI[] | getUIs() Returns the list of UIs associated with this multiplexing UI.
void | installUI(JComponent a) Invokes the installUI method on each UI handled by this object.
void | paint(Graphics a, JComponent b) Invokes the paint method on each UI handled by this object.
void | rescanCurrentDirectory(JFileChooser a) Invokes the rescanCurrentDirectory method on each UI handled by this object.
void | uninstallUI(JComponent a) Invokes the uninstallUI method on each UI handled by this object.
void | update(Graphics a, JComponent b) Invokes the update method on each UI handled by this object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

uis

protected Vector uis
The vector containing the real UIs. This is populated in the call to createUI, and can be obtained by calling the getUIs method. The first element is guaranteed to be the real UI obtained from the default look and feel.

Constructor Detail

MultiFileChooserUI

public MultiFileChooserUI()
Method Detail

getUIs

public ComponentUI[] getUIs()
Returns the list of UIs associated with this multiplexing UI. This allows processing of the UIs by an application aware of multiplexing UIs on components.

getAcceptAllFileFilter

public FileFilter getAcceptAllFileFilter(JFileChooser a)
Invokes the getAcceptAllFileFilter method on each UI handled by this object.

Specified by:
getAcceptAllFileFilter in class FileChooserUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel

getFileView

public FileView getFileView(JFileChooser a)
Invokes the getFileView method on each UI handled by this object.

Specified by:
getFileView in class FileChooserUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel

getApproveButtonText

public String getApproveButtonText(JFileChooser a)
Invokes the getApproveButtonText method on each UI handled by this object.

Specified by:
getApproveButtonText in class FileChooserUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel

getDialogTitle

public String getDialogTitle(JFileChooser a)
Invokes the getDialogTitle method on each UI handled by this object.

Specified by:
getDialogTitle in class FileChooserUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel

rescanCurrentDirectory

public void rescanCurrentDirectory(JFileChooser a)
Invokes the rescanCurrentDirectory method on each UI handled by this object.

Specified by:
rescanCurrentDirectory in class FileChooserUI

ensureFileIsVisible

public void ensureFileIsVisible(JFileChooser a,
                                File b)
Invokes the ensureFileIsVisible method on each UI handled by this object.

Specified by:
ensureFileIsVisible in class FileChooserUI

contains

public boolean contains(JComponent a,
                        int b,
                        int c)
Invokes the contains method on each UI handled by this object.

Overrides:
contains in class ComponentUI
Parameters:
a - the component where the x,y location is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
b - the x coordinate of the point
c - the y coordinate of the point
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.contains(int, int), Component.contains(int, int)

update

public void update(Graphics a,
                   JComponent b)
Invokes the update method on each UI handled by this object.

Overrides:
update in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.paint(java.awt.Graphics, javax.swing.JComponent), JComponent.paintComponent(java.awt.Graphics)

createUI

public static ComponentUI createUI(JComponent a)
Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI. Otherwise, just returns the UI object obtained from the default LookAndFeel.

installUI

public void installUI(JComponent a)
Invokes the installUI method on each UI handled by this object.

Overrides:
installUI in class ComponentUI
Parameters:
a - the component where this UI delegate is being installed
See Also:
ComponentUI.uninstallUI(javax.swing.JComponent),
JComponent.setUI(javax.swing.plaf.ComponentUI),
JComponent.updateUI()

uninstallUI

public void uninstallUI(JComponent a)
Invokes the uninstallUI method on each UI handled by this object.

Overrides:
uninstallUI in class ComponentUI
Parameters:
a - the component from which this UI delegate is being removed; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.installUI(javax.swing.JComponent), JComponent.updateUI()

paint

public void paint(Graphics a,
                  JComponent b)
Invokes the paint method on each UI handled by this object.

Overrides:
paint in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.update(java.awt.Graphics, javax.swing.JComponent)

getPreferredSize

public Dimension getPreferredSize(JComponent a)
Invokes the getPreferredSize method on each UI handled by this object.

Overrides:
getPreferredSize in class ComponentUI
Parameters:
a - the component whose preferred size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getPreferredSize(), LayoutManager.preferredLayoutSize(java.awt.Container)

getMinimumSize

public Dimension getMinimumSize(JComponent a)
Invokes the getMinimumSize method on each UI handled by this object.

Overrides:
getMinimumSize in class ComponentUI
Parameters:
a - the component whose minimum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMinimumSize(),
LayoutManager.minimumLayoutSize(java.awt.Container),
ComponentUI.getPreferredSize(javax.swing.JComponent)

getMaximumSize

public Dimension getMaximumSize(JComponent a)
Invokes the getMaximumSize method on each UI handled by this object.

Overrides:
getMaximumSize in class ComponentUI
Parameters:
a - the component whose maximum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMaximumSize(), LayoutManager2.maximumLayoutSize(java.awt.Container)

getAccessibleChildrenCount

public int getAccessibleChildrenCount(JComponent a)
Invokes the getAccessibleChildrenCount method on each UI handled by this object.

Overrides:
getAccessibleChildrenCount in class ComponentUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChild(javax.swing.JComponent, int)

getAccessibleChild

public Accessible getAccessibleChild(JComponent a,
                                     int b)
Invokes the getAccessibleChild method on each UI handled by this object.

Overrides:
getAccessibleChild in class ComponentUI
Parameters:
b - zero-based index of child
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChildrenCount(javax.swing.JComponent)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MultiInternalFrameUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.multi
Class MultiInternalFrameUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.InternalFrameUI
            extended by javax.swing.plaf.multi.MultiInternalFrameUI
public class MultiInternalFrameUI
extends InternalFrameUI

A multiplexing UI used to combine InternalFrameUIs.

This file was automatically generated by AutoMulti.

Field Summary
protected  Vector uis
The vector containing the real UIs.
Constructor Summary
MultiInternalFrameUI()
Method Summary
boolean | contains(JComponent a, int b, int c) Invokes the contains method on each UI handled by this object.
static ComponentUI | createUI(JComponent a) Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI.
Accessible | getAccessibleChild(JComponent a, int b) Invokes the getAccessibleChild method on each UI handled by this object.
int | getAccessibleChildrenCount(JComponent a) Invokes the getAccessibleChildrenCount method on each UI handled by this object.
Dimension | getMaximumSize(JComponent a) Invokes the getMaximumSize method on each UI handled by this object.
Dimension | getMinimumSize(JComponent a) Invokes the getMinimumSize method on each UI handled by this object.
Dimension | getPreferredSize(JComponent a) Invokes the getPreferredSize method on each UI handled by this object.
ComponentUI[] | getUIs() Returns the list of UIs associated with this multiplexing UI.
void | installUI(JComponent a) Invokes the installUI method on each UI handled by this object.
void | paint(Graphics a, JComponent b) Invokes the paint method on each UI handled by this object.
void | uninstallUI(JComponent a) Invokes the uninstallUI method on each UI handled by this object.
void | update(Graphics a, JComponent b) Invokes the update method on each UI handled by this object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

uis

protected Vector uis
The vector containing the real UIs. This is populated in the call to createUI, and can be obtained by calling the getUIs method. The first element is guaranteed to be the real UI obtained from the default look and feel.

Constructor Detail

MultiInternalFrameUI

public MultiInternalFrameUI()
Method Detail

getUIs

public ComponentUI[] getUIs()
Returns the list of UIs associated with this multiplexing UI. This allows processing of the UIs by an application aware of multiplexing UIs on components.

contains

public boolean contains(JComponent a,
                        int b,
                        int c)
Invokes the contains method on each UI handled by this object.

Overrides:
contains in class ComponentUI
Parameters:
a - the component where the x,y location is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
b - the x coordinate of the point
c - the y coordinate of the point
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.contains(int, int), Component.contains(int, int)

update

public void update(Graphics a,
                   JComponent b)
Invokes the update method on each UI handled by this object.

Overrides:
update in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.paint(java.awt.Graphics, javax.swing.JComponent), JComponent.paintComponent(java.awt.Graphics)

createUI

public static ComponentUI createUI(JComponent a)
Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI. Otherwise, just returns the UI object obtained from the default LookAndFeel.

installUI

public void installUI(JComponent a)
Invokes the installUI method on each UI handled by this object.

Overrides:
installUI in class ComponentUI
Parameters:
a - the component where this UI delegate is being installed
See Also:
ComponentUI.uninstallUI(javax.swing.JComponent),
JComponent.setUI(javax.swing.plaf.ComponentUI),
JComponent.updateUI()

uninstallUI

public void uninstallUI(JComponent a)
Invokes the uninstallUI method on each UI handled by this object.

Overrides:
uninstallUI in class ComponentUI
Parameters:
a - the component from which this UI delegate is being removed; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.installUI(javax.swing.JComponent), JComponent.updateUI()

paint

public void paint(Graphics a,
                  JComponent b)
Invokes the paint method on each UI handled by this object.

Overrides:
paint in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.update(java.awt.Graphics, javax.swing.JComponent)

getPreferredSize

public Dimension getPreferredSize(JComponent a)
Invokes the getPreferredSize method on each UI handled by this object.

Overrides:
getPreferredSize in class ComponentUI
Parameters:
a - the component whose preferred size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getPreferredSize(), LayoutManager.preferredLayoutSize(java.awt.Container)

getMinimumSize

public Dimension getMinimumSize(JComponent a)
Invokes the getMinimumSize method on each UI handled by this object.

Overrides:
getMinimumSize in class ComponentUI
Parameters:
a - the component whose minimum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMinimumSize(),
LayoutManager.minimumLayoutSize(java.awt.Container),
ComponentUI.getPreferredSize(javax.swing.JComponent)

getMaximumSize

public Dimension getMaximumSize(JComponent a)
Invokes the getMaximumSize method on each UI handled by this object.

Overrides:
getMaximumSize in class ComponentUI
Parameters:
a - the component whose maximum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMaximumSize(), LayoutManager2.maximumLayoutSize(java.awt.Container)

getAccessibleChildrenCount

public int getAccessibleChildrenCount(JComponent a)
Invokes the getAccessibleChildrenCount method on each UI handled by this object.

Overrides:
getAccessibleChildrenCount in class ComponentUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChild(javax.swing.JComponent, int)

getAccessibleChild

public Accessible getAccessibleChild(JComponent a,
                                     int b)
Invokes the getAccessibleChild method on each UI handled by this object.

Overrides:
getAccessibleChild in class ComponentUI
Parameters:
b - zero-based index of child
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChildrenCount(javax.swing.JComponent)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MultiLabelUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.multi
Class MultiLabelUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.LabelUI
            extended by javax.swing.plaf.multi.MultiLabelUI
public class MultiLabelUI
extends LabelUI

A multiplexing UI used to combine LabelUIs.

This file was automatically generated by AutoMulti.

Field Summary
protected  Vector uis
The vector containing the real UIs.
Constructor Summary
MultiLabelUI()
Method Summary
boolean | contains(JComponent a, int b, int c) Invokes the contains method on each UI handled by this object.
static ComponentUI | createUI(JComponent a) Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI.
Accessible | getAccessibleChild(JComponent a, int b) Invokes the getAccessibleChild method on each UI handled by this object.
int | getAccessibleChildrenCount(JComponent a) Invokes the getAccessibleChildrenCount method on each UI handled by this object.
Dimension | getMaximumSize(JComponent a) Invokes the getMaximumSize method on each UI handled by this object.
Dimension | getMinimumSize(JComponent a) Invokes the getMinimumSize method on each UI handled by this object.
Dimension | getPreferredSize(JComponent a) Invokes the getPreferredSize method on each UI handled by this object.
ComponentUI[] | getUIs() Returns the list of UIs associated with this multiplexing UI.
void | installUI(JComponent a) Invokes the installUI method on each UI handled by this object.
void | paint(Graphics a, JComponent b) Invokes the paint method on each UI handled by this object.
void | uninstallUI(JComponent a) Invokes the uninstallUI method on each UI handled by this object.
void | update(Graphics a, JComponent b) Invokes the update method on each UI handled by this object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

uis

protected Vector uis
The vector containing the real UIs. This is populated in the call to createUI, and can be obtained by calling the getUIs method. The first element is guaranteed to be the real UI obtained from the default look and feel.

Constructor Detail

MultiLabelUI

public MultiLabelUI()
Method Detail

getUIs

public ComponentUI[] getUIs()
Returns the list of UIs associated with this multiplexing UI. This allows processing of the UIs by an application aware of multiplexing UIs on components.

contains

public boolean contains(JComponent a,
                        int b,
                        int c)
Invokes the contains method on each UI handled by this object.

Overrides:
contains in class ComponentUI
Parameters:
a - the component where the x,y location is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
b - the x coordinate of the point
c - the y coordinate of the point
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.contains(int, int), Component.contains(int, int)

update

public void update(Graphics a,
                   JComponent b)
Invokes the update method on each UI handled by this object.

Overrides:
update in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.paint(java.awt.Graphics, javax.swing.JComponent), JComponent.paintComponent(java.awt.Graphics)

createUI

public static ComponentUI createUI(JComponent a)
Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI. Otherwise, just returns the UI object obtained from the default LookAndFeel.

installUI

public void installUI(JComponent a)
Invokes the installUI method on each UI handled by this object.

Overrides:
installUI in class ComponentUI
Parameters:
a - the component where this UI delegate is being installed
See Also:
ComponentUI.uninstallUI(javax.swing.JComponent),
JComponent.setUI(javax.swing.plaf.ComponentUI),
JComponent.updateUI()

uninstallUI

public void uninstallUI(JComponent a)
Invokes the uninstallUI method on each UI handled by this object.

Overrides:
uninstallUI in class ComponentUI
Parameters:
a - the component from which this UI delegate is being removed; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.installUI(javax.swing.JComponent), JComponent.updateUI()

paint

public void paint(Graphics a,
                  JComponent b)
Invokes the paint method on each UI handled by this object.

Overrides:
paint in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.update(java.awt.Graphics, javax.swing.JComponent)

getPreferredSize

public Dimension getPreferredSize(JComponent a)
Invokes the getPreferredSize method on each UI handled by this object.

Overrides:
getPreferredSize in class ComponentUI
Parameters:
a - the component whose preferred size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getPreferredSize(), LayoutManager.preferredLayoutSize(java.awt.Container)

getMinimumSize

public Dimension getMinimumSize(JComponent a)
Invokes the getMinimumSize method on each UI handled by this object.

Overrides:
getMinimumSize in class ComponentUI
Parameters:
a - the component whose minimum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMinimumSize(),
LayoutManager.minimumLayoutSize(java.awt.Container),
ComponentUI.getPreferredSize(javax.swing.JComponent)

getMaximumSize

public Dimension getMaximumSize(JComponent a)
Invokes the getMaximumSize method on each UI handled by this object.

Overrides:
getMaximumSize in class ComponentUI
Parameters:
a - the component whose maximum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMaximumSize(), LayoutManager2.maximumLayoutSize(java.awt.Container)

getAccessibleChildrenCount

public int getAccessibleChildrenCount(JComponent a)
Invokes the getAccessibleChildrenCount method on each UI handled by this object.

Overrides:
getAccessibleChildrenCount in class ComponentUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChild(javax.swing.JComponent, int)

getAccessibleChild

public Accessible getAccessibleChild(JComponent a,
                                     int b)
Invokes the getAccessibleChild method on each UI handled by this object.

Overrides:
getAccessibleChild in class ComponentUI
Parameters:
b - zero-based index of child
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChildrenCount(javax.swing.JComponent)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MultiListUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.multi
Class MultiListUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.ListUI
            extended by javax.swing.plaf.multi.MultiListUI
public class MultiListUI
extends ListUI

A multiplexing UI used to combine ListUIs.

This file was automatically generated by AutoMulti.

Field Summary
protected  Vector uis
The vector containing the real UIs.
Constructor Summary
MultiListUI()
Method Summary
boolean | contains(JComponent a, int b, int c) Invokes the contains method on each UI handled by this object.
static ComponentUI | createUI(JComponent a) Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI.
Accessible | getAccessibleChild(JComponent a, int b) Invokes the getAccessibleChild method on each UI handled by this object.
int | getAccessibleChildrenCount(JComponent a) Invokes the getAccessibleChildrenCount method on each UI handled by this object.
Rectangle | getCellBounds(JList a, int b, int c) Invokes the getCellBounds method on each UI handled by this object.
Dimension | getMaximumSize(JComponent a) Invokes the getMaximumSize method on each UI handled by this object.
Dimension | getMinimumSize(JComponent a) Invokes the getMinimumSize method on each UI handled by this object.
Dimension | getPreferredSize(JComponent a) Invokes the getPreferredSize method on each UI handled by this object.
ComponentUI[] | getUIs() Returns the list of UIs associated with this multiplexing UI.
Point | indexToLocation(JList a, int b) Invokes the indexToLocation method on each UI handled by this object.
void | installUI(JComponent a) Invokes the installUI method on each UI handled by this object.
int | locationToIndex(JList a, Point b) Invokes the locationToIndex method on each UI handled by this object.
void | paint(Graphics a, JComponent b) Invokes the paint method on each UI handled by this object.
void | uninstallUI(JComponent a) Invokes the uninstallUI method on each UI handled by this object.
void | update(Graphics a, JComponent b) Invokes the update method on each UI handled by this object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

uis

protected Vector uis
The vector containing the real UIs. This is populated in the call to createUI, and can be obtained by calling the getUIs method. The first element is guaranteed to be the real UI obtained from the default look and feel.

Constructor Detail

MultiListUI

public MultiListUI()
Method Detail

getUIs

public ComponentUI[] getUIs()
Returns the list of UIs associated with this multiplexing UI. This allows processing of the UIs by an application aware of multiplexing UIs on components.

locationToIndex

public int locationToIndex(JList a,
                           Point b)
Invokes the locationToIndex method on each UI handled by this object.

Specified by:
locationToIndex in class ListUI
Parameters:
b - The JList relative coordinates of the cell
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel

indexToLocation

public Point indexToLocation(JList a,
                             int b)
Invokes the indexToLocation method on each UI handled by this object.

Specified by:
indexToLocation in class ListUI
Parameters:
b - The index of the JList cell.
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel

getCellBounds

public Rectangle getCellBounds(JList a,
                               int b,
                               int c)
Invokes the getCellBounds method on each UI handled by this object.

Specified by:
getCellBounds in class ListUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel

contains

public boolean contains(JComponent a,
                        int b,
                        int c)
Invokes the contains method on each UI handled by this object.

Overrides:
contains in class ComponentUI
Parameters:
a - the component where the x,y location is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
b - the x coordinate of the point
c - the y coordinate of the point
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.contains(int, int), Component.contains(int, int)

update

public void update(Graphics a,
                   JComponent b)
Invokes the update method on each UI handled by this object.

Overrides:
update in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.paint(java.awt.Graphics, javax.swing.JComponent), JComponent.paintComponent(java.awt.Graphics)

createUI

public static ComponentUI createUI(JComponent a)
Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI. Otherwise, just returns the UI object obtained from the default LookAndFeel.

installUI

public void installUI(JComponent a)
Invokes the installUI method on each UI handled by this object.

Overrides:
installUI in class ComponentUI
Parameters:
a - the component where this UI delegate is being installed
See Also:
ComponentUI.uninstallUI(javax.swing.JComponent),
JComponent.setUI(javax.swing.plaf.ComponentUI),
JComponent.updateUI()

uninstallUI

public void uninstallUI(JComponent a)
Invokes the uninstallUI method on each UI handled by this object.

Overrides:
uninstallUI in class ComponentUI
Parameters:
a - the component from which this UI delegate is being removed; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.installUI(javax.swing.JComponent), JComponent.updateUI()

paint

public void paint(Graphics a,
                  JComponent b)
Invokes the paint method on each UI handled by this object.

Overrides:
paint in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.update(java.awt.Graphics, javax.swing.JComponent)

getPreferredSize

public Dimension getPreferredSize(JComponent a)
Invokes the getPreferredSize method on each UI handled by this object.

Overrides:
getPreferredSize in class ComponentUI
Parameters:
a - the component whose preferred size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getPreferredSize(), LayoutManager.preferredLayoutSize(java.awt.Container)

getMinimumSize

public Dimension getMinimumSize(JComponent a)
Invokes the getMinimumSize method on each UI handled by this object.

Overrides:
getMinimumSize in class ComponentUI
Parameters:
a - the component whose minimum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMinimumSize(),
LayoutManager.minimumLayoutSize(java.awt.Container),
ComponentUI.getPreferredSize(javax.swing.JComponent)

getMaximumSize

public Dimension getMaximumSize(JComponent a)
Invokes the getMaximumSize method on each UI handled by this object.

Overrides:
getMaximumSize in class ComponentUI
Parameters:
a - the component whose maximum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMaximumSize(), LayoutManager2.maximumLayoutSize(java.awt.Container)

getAccessibleChildrenCount

public int getAccessibleChildrenCount(JComponent a)
Invokes the getAccessibleChildrenCount method on each UI handled by this object.

Overrides:
getAccessibleChildrenCount in class ComponentUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChild(javax.swing.JComponent, int)

getAccessibleChild

public Accessible getAccessibleChild(JComponent a,
                                     int b)
Invokes the getAccessibleChild method on each UI handled by this object.

Overrides:
getAccessibleChild in class ComponentUI
Parameters:
b - zero-based index of child
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChildrenCount(javax.swing.JComponent)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MultiLookAndFeel (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.multi
Class MultiLookAndFeel

java.lang.Object
    extended by javax.swing.LookAndFeel
        extended by javax.swing.plaf.multi.MultiLookAndFeel
public class MultiLookAndFeel
extends LookAndFeel

A multiplexing look and feel that allows more than one UI to be associated with a component at the same time. The primary look and feel is called the default look and feel, and the other look and feels are called auxiliary.

For further information, see Using the Multiplexing Look and Feel.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

See Also:
UIManager.addAuxiliaryLookAndFeel(javax.swing.LookAndFeel), javax.swing.plaf.multi

Constructor Summary
MultiLookAndFeel()
Method Summary
static ComponentUI | createUIs(ComponentUI mui, Vector uis, JComponent target) Creates the ComponentUI objects required to present the target component, placing the objects in the uis vector and returning the ComponentUI object that best represents the component's UI.
UIDefaults | getDefaults() Creates, initializes, and returns the look and feel specific defaults.
String | getDescription() Returns a one-line description of this look and feel.
String | getID() Returns a string, suitable for use by applications/services, that identifies this look and feel.
String | getName() Returns a string, suitable for use in menus, that identifies this look and feel.
boolean | isNativeLookAndFeel() Returns false; this look and feel is not native to any platform.
boolean | isSupportedLookAndFeel() Returns true; every platform permits this look and feel.
protected static ComponentUI[] | uisToArray(Vector uis) Creates an array, populates it with UI objects from the passed-in vector, and returns the array.
Methods inherited from class javax.swing.LookAndFeel
getDesktopPropertyValue, getSupportsWindowDecorations, initialize, installBorder, installColors, installColorsAndFont, loadKeyBindings, makeComponentInputMap, makeIcon, makeInputMap, makeKeyBindings, provideErrorFeedback, toString, uninitialize, uninstallBorder
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

MultiLookAndFeel

public MultiLookAndFeel()
Method Detail

getName

public String getName()
Returns a string, suitable for use in menus, that identifies this look and feel.

Specified by:
getName in class LookAndFeel
Returns:
a string such as "Multiplexing Look and Feel"

getID

public String getID()
Returns a string, suitable for use by applications/services, that identifies this look and feel.

Specified by:
getID in class LookAndFeel
Returns:
"Multiplex"

getDescription

public String getDescription()
Returns a one-line description of this look and feel.

Specified by:
getDescription in class LookAndFeel
Returns:
a descriptive string such as "Allows multiple UI instances per component instance"

isNativeLookAndFeel

public boolean isNativeLookAndFeel()
Returns false; this look and feel is not native to any platform.

Specified by:
isNativeLookAndFeel in class LookAndFeel
Returns:
false

isSupportedLookAndFeel

public boolean isSupportedLookAndFeel()
Returns true; every platform permits this look and feel.

Specified by:
isSupportedLookAndFeel in class LookAndFeel
Returns:
true
See Also:
UIManager.setLookAndFeel(javax.swing.LookAndFeel)

getDefaults

public UIDefaults getDefaults()
Creates, initializes, and returns the look and feel specific defaults. For this look and feel, the defaults consist solely of mappings of UI class IDs (such as "ButtonUI") to ComponentUI class names (such as "javax.swing.plaf.multi.MultiButtonUI").

Overrides:
getDefaults in class LookAndFeel
Returns:
an initialized UIDefaults object
See Also:
JComponent.getUIClassID()

createUIs

public static ComponentUI createUIs(ComponentUI mui,
                                    Vector uis,
                                    JComponent target)
Creates the ComponentUI objects required to present the target component, placing the objects in the uis vector and returning the ComponentUI object that best represents the component's UI. This method finds the ComponentUI objects by invoking getDefaults().getUI(target) on each default and auxiliary look and feel currently in use. The first UI object this method adds to the uis vector is for the default look and feel.

This method is invoked by the createUI method of MultiXxxxUI classes.

Parameters:
mui - the ComponentUI object that represents the complete UI for the target component; this should be an instance of one of the MultiXxxxUI classes
uis - a Vector; generally this is the uis field of the mui argument
target - a component whose UI is represented by mui
Returns:
mui if the component has any auxiliary UI objects; otherwise, returns the UI object for the default look and feel or null if the default UI object couldn't be found
See Also:
UIManager.getAuxiliaryLookAndFeels(), UIDefaults.getUI(javax.swing.JComponent), MultiButtonUI.uis, MultiButtonUI.createUI(javax.swing.JComponent)

uisToArray

protected static ComponentUI[] uisToArray(Vector uis)
Creates an array, populates it with UI objects from the passed-in vector, and returns the array. If uis is null, this method returns an array with zero elements. If uis is an empty vector, this method returns null. A run-time error occurs if any objects in the uis vector are not of type ComponentUI.

Parameters:
uis - a vector containing ComponentUI objects
Returns:
an array equivalent to the passed-in vector
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MultiMenuBarUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.multi
Class MultiMenuBarUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.MenuBarUI
            extended by javax.swing.plaf.multi.MultiMenuBarUI
public class MultiMenuBarUI
extends MenuBarUI

A multiplexing UI used to combine MenuBarUIs.

This file was automatically generated by AutoMulti.

Field Summary
protected  Vector uis
The vector containing the real UIs.
Constructor Summary
MultiMenuBarUI()
Method Summary
boolean | contains(JComponent a, int b, int c) Invokes the contains method on each UI handled by this object.
static ComponentUI | createUI(JComponent a) Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI.
Accessible | getAccessibleChild(JComponent a, int b) Invokes the getAccessibleChild method on each UI handled by this object.
int | getAccessibleChildrenCount(JComponent a) Invokes the getAccessibleChildrenCount method on each UI handled by this object.
Dimension | getMaximumSize(JComponent a) Invokes the getMaximumSize method on each UI handled by this object.
Dimension | getMinimumSize(JComponent a) Invokes the getMinimumSize method on each UI handled by this object.
Dimension | getPreferredSize(JComponent a) Invokes the getPreferredSize method on each UI handled by this object.
ComponentUI[] | getUIs() Returns the list of UIs associated with this multiplexing UI.
void | installUI(JComponent a) Invokes the installUI method on each UI handled by this object.
void | paint(Graphics a, JComponent b) Invokes the paint method on each UI handled by this object.
void | uninstallUI(JComponent a) Invokes the uninstallUI method on each UI handled by this object.
void | update(Graphics a, JComponent b) Invokes the update method on each UI handled by this object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

uis

protected Vector uis
The vector containing the real UIs. This is populated in the call to createUI, and can be obtained by calling the getUIs method. The first element is guaranteed to be the real UI obtained from the default look and feel.

Constructor Detail

MultiMenuBarUI

public MultiMenuBarUI()
Method Detail

getUIs

public ComponentUI[] getUIs()
Returns the list of UIs associated with this multiplexing UI. This allows processing of the UIs by an application aware of multiplexing UIs on components.

contains

public boolean contains(JComponent a,
                        int b,
                        int c)
Invokes the contains method on each UI handled by this object.

Overrides:
contains in class ComponentUI
Parameters:
a - the component where the x,y location is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
b - the x coordinate of the point
c - the y coordinate of the point
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.contains(int, int), Component.contains(int, int)

update

public void update(Graphics a,
                   JComponent b)
Invokes the update method on each UI handled by this object.

Overrides:
update in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.paint(java.awt.Graphics, javax.swing.JComponent), JComponent.paintComponent(java.awt.Graphics)

createUI

public static ComponentUI createUI(JComponent a)
Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI. Otherwise, just returns the UI object obtained from the default LookAndFeel.

installUI

public void installUI(JComponent a)
Invokes the installUI method on each UI handled by this object.

Overrides:
installUI in class ComponentUI
Parameters:
a - the component where this UI delegate is being installed
See Also:
ComponentUI.uninstallUI(javax.swing.JComponent),
JComponent.setUI(javax.swing.plaf.ComponentUI),
JComponent.updateUI()

uninstallUI

public void uninstallUI(JComponent a)
Invokes the uninstallUI method on each UI handled by this object.

Overrides:
uninstallUI in class ComponentUI
Parameters:
a - the component from which this UI delegate is being removed; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.installUI(javax.swing.JComponent), JComponent.updateUI()

paint

public void paint(Graphics a,
                  JComponent b)
Invokes the paint method on each UI handled by this object.

Overrides:
paint in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.update(java.awt.Graphics, javax.swing.JComponent)

getPreferredSize

public Dimension getPreferredSize(JComponent a)
Invokes the getPreferredSize method on each UI handled by this object.

Overrides:
getPreferredSize in class ComponentUI
Parameters:
a - the component whose preferred size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getPreferredSize(), LayoutManager.preferredLayoutSize(java.awt.Container)

getMinimumSize

public Dimension getMinimumSize(JComponent a)
Invokes the getMinimumSize method on each UI handled by this object.

Overrides:
getMinimumSize in class ComponentUI
Parameters:
a - the component whose minimum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMinimumSize(),
LayoutManager.minimumLayoutSize(java.awt.Container),
ComponentUI.getPreferredSize(javax.swing.JComponent)

getMaximumSize

public Dimension getMaximumSize(JComponent a)
Invokes the getMaximumSize method on each UI handled by this object.

Overrides:
getMaximumSize in class ComponentUI
Parameters:
a - the component whose maximum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMaximumSize(), LayoutManager2.maximumLayoutSize(java.awt.Container)

getAccessibleChildrenCount

public int getAccessibleChildrenCount(JComponent a)
Invokes the getAccessibleChildrenCount method on each UI handled by this object.

Overrides:
getAccessibleChildrenCount in class ComponentUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChild(javax.swing.JComponent, int)

getAccessibleChild

public Accessible getAccessibleChild(JComponent a,
                                     int b)
Invokes the getAccessibleChild method on each UI handled by this object.

Overrides:
getAccessibleChild in class ComponentUI
Parameters:
b - zero-based index of child
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChildrenCount(javax.swing.JComponent)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MultiMenuItemUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.multi
Class MultiMenuItemUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.ButtonUI
            extended by javax.swing.plaf.MenuItemUI
                extended by javax.swing.plaf.multi.MultiMenuItemUI
public class MultiMenuItemUI
extends MenuItemUI

A multiplexing UI used to combine MenuItemUIs.

This file was automatically generated by AutoMulti.

Field Summary
protected  Vector uis
The vector containing the real UIs.
Constructor Summary
MultiMenuItemUI()
Method Summary
boolean | contains(JComponent a, int b, int c) Invokes the contains method on each UI handled by this object.
static ComponentUI | createUI(JComponent a) Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI.
Accessible | getAccessibleChild(JComponent a, int b) Invokes the getAccessibleChild method on each UI handled by this object.
int | getAccessibleChildrenCount(JComponent a) Invokes the getAccessibleChildrenCount method on each UI handled by this object.
Dimension | getMaximumSize(JComponent a) Invokes the getMaximumSize method on each UI handled by this object.
Dimension | getMinimumSize(JComponent a) Invokes the getMinimumSize method on each UI handled by this object.
Dimension | getPreferredSize(JComponent a) Invokes the getPreferredSize method on each UI handled by this object.
ComponentUI[] | getUIs() Returns the list of UIs associated with this multiplexing UI.
void | installUI(JComponent a) Invokes the installUI method on each UI handled by this object.
void | paint(Graphics a, JComponent b) Invokes the paint method on each UI handled by this object.
void | uninstallUI(JComponent a) Invokes the uninstallUI method on each UI handled by this object.
void | update(Graphics a, JComponent b) Invokes the update method on each UI handled by this object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

uis

protected Vector uis
The vector containing the real UIs. This is populated in the call to createUI, and can be obtained by calling the getUIs method. The first element is guaranteed to be the real UI obtained from the default look and feel.

Constructor Detail

MultiMenuItemUI

public MultiMenuItemUI()
Method Detail

getUIs

public ComponentUI[] getUIs()
Returns the list of UIs associated with this multiplexing UI. This allows processing of the UIs by an application aware of multiplexing UIs on components.

contains

public boolean contains(JComponent a,
                        int b,
                        int c)
Invokes the contains method on each UI handled by this object.

Overrides:
contains in class ComponentUI
Parameters:
a - the component where the x,y location is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
b - the x coordinate of the point
c - the y coordinate of the point
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.contains(int, int), Component.contains(int, int)

update

public void update(Graphics a,
                   JComponent b)
Invokes the update method on each UI handled by this object.

Overrides:
update in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.paint(java.awt.Graphics, javax.swing.JComponent), JComponent.paintComponent(java.awt.Graphics)

createUI

public static ComponentUI createUI(JComponent a)
Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI. Otherwise, just returns the UI object obtained from the default LookAndFeel.

installUI

public void installUI(JComponent a)
Invokes the installUI method on each UI handled by this object.

Overrides:
installUI in class ComponentUI
Parameters:
a - the component where this UI delegate is being installed
See Also:
ComponentUI.uninstallUI(javax.swing.JComponent),
JComponent.setUI(javax.swing.plaf.ComponentUI),
JComponent.updateUI()

uninstallUI

public void uninstallUI(JComponent a)
Invokes the uninstallUI method on each UI handled by this object.

Overrides:
uninstallUI in class ComponentUI
Parameters:
a - the component from which this UI delegate is being removed; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.installUI(javax.swing.JComponent), JComponent.updateUI()

paint

public void paint(Graphics a,
                  JComponent b)
Invokes the paint method on each UI handled by this object.

Overrides:
paint in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.update(java.awt.Graphics, javax.swing.JComponent)

getPreferredSize

public Dimension getPreferredSize(JComponent a)
Invokes the getPreferredSize method on each UI handled by this object.

Overrides:
getPreferredSize in class ComponentUI
Parameters:
a - the component whose preferred size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getPreferredSize(), LayoutManager.preferredLayoutSize(java.awt.Container)

getMinimumSize

public Dimension getMinimumSize(JComponent a)
Invokes the getMinimumSize method on each UI handled by this object.

Overrides:
getMinimumSize in class ComponentUI
Parameters:
a - the component whose minimum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMinimumSize(),
LayoutManager.minimumLayoutSize(java.awt.Container),
ComponentUI.getPreferredSize(javax.swing.JComponent)

getMaximumSize

public Dimension getMaximumSize(JComponent a)
Invokes the getMaximumSize method on each UI handled by this object.

Overrides:
getMaximumSize in class ComponentUI
Parameters:
a - the component whose maximum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMaximumSize(), LayoutManager2.maximumLayoutSize(java.awt.Container)

getAccessibleChildrenCount

public int getAccessibleChildrenCount(JComponent a)
Invokes the getAccessibleChildrenCount method on each UI handled by this object.

Overrides:
getAccessibleChildrenCount in class ComponentUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChild(javax.swing.JComponent, int)

getAccessibleChild

public Accessible getAccessibleChild(JComponent a,
                                     int b)
Invokes the getAccessibleChild method on each UI handled by this object.

Overrides:
getAccessibleChild in class ComponentUI
Parameters:
b - zero-based index of child
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChildrenCount(javax.swing.JComponent)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MultiOptionPaneUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.multi
Class MultiOptionPaneUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.OptionPaneUI
            extended by javax.swing.plaf.multi.MultiOptionPaneUI
public class MultiOptionPaneUI
extends OptionPaneUI

A multiplexing UI used to combine OptionPaneUIs.

This file was automatically generated by AutoMulti.

Field Summary
protected  Vector uis
The vector containing the real UIs.
Constructor Summary
MultiOptionPaneUI()
Method Summary
boolean | contains(JComponent a, int b, int c) Invokes the contains method on each UI handled by this object.
boolean | containsCustomComponents(JOptionPane a) Invokes the containsCustomComponents method on each UI handled by this object.
static ComponentUI | createUI(JComponent a) Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI.
Accessible | getAccessibleChild(JComponent a, int b) Invokes the getAccessibleChild method on each UI handled by this object.
int | getAccessibleChildrenCount(JComponent a) Invokes the getAccessibleChildrenCount method on each UI handled by this object.
Dimension | getMaximumSize(JComponent a) Invokes the getMaximumSize method on each UI handled by this object.
Dimension | getMinimumSize(JComponent a) Invokes the getMinimumSize method on each UI handled by this object.
Dimension | getPreferredSize(JComponent a) Invokes the getPreferredSize method on each UI handled by this object.
ComponentUI[] | getUIs() Returns the list of UIs associated with this multiplexing UI.
void | installUI(JComponent a) Invokes the installUI method on each UI handled by this object.
void | paint(Graphics a, JComponent b) Invokes the paint method on each UI handled by this object.
void | selectInitialValue(JOptionPane a) Invokes the selectInitialValue method on each UI handled by this object.
void | uninstallUI(JComponent a) Invokes the uninstallUI method on each UI handled by this object.
void | update(Graphics a, JComponent b) Invokes the update method on each UI handled by this object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

uis

protected Vector uis
The vector containing the real UIs. This is populated in the call to createUI, and can be obtained by calling the getUIs method. The first element is guaranteed to be the real UI obtained from the default look and feel.

Constructor Detail

MultiOptionPaneUI

public MultiOptionPaneUI()
Method Detail

getUIs

public ComponentUI[] getUIs()
Returns the list of UIs associated with this multiplexing UI. This allows processing of the UIs by an application aware of multiplexing UIs on components.

selectInitialValue

public void selectInitialValue(JOptionPane a)
Invokes the selectInitialValue method on each UI handled by this object.

Specified by:
selectInitialValue in class OptionPaneUI

containsCustomComponents

public boolean containsCustomComponents(JOptionPane a)
Invokes the containsCustomComponents method on each UI handled by this object.

Specified by:
containsCustomComponents in class OptionPaneUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel

contains

public boolean contains(JComponent a,
                        int b,
                        int c)
Invokes the contains method on each UI handled by this object.

Overrides:
contains in class ComponentUI
Parameters:
a - the component where the x,y location is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
b - the x coordinate of the point
c - the y coordinate of the point
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.contains(int, int), Component.contains(int, int)

update

public void update(Graphics a,
                   JComponent b)
Invokes the update method on each UI handled by this object.

Overrides:
update in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.paint(java.awt.Graphics, javax.swing.JComponent), JComponent.paintComponent(java.awt.Graphics)

createUI

public static ComponentUI createUI(JComponent a)
Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI. Otherwise, just returns the UI object obtained from the default LookAndFeel.

installUI

public void installUI(JComponent a)
Invokes the installUI method on each UI handled by this object.

Overrides:
installUI in class ComponentUI
Parameters:
a - the component where this UI delegate is being installed
See Also:
ComponentUI.uninstallUI(javax.swing.JComponent),
JComponent.setUI(javax.swing.plaf.ComponentUI),
JComponent.updateUI()

uninstallUI

public void uninstallUI(JComponent a)
Invokes the uninstallUI method on each UI handled by this object.

Overrides:
uninstallUI in class ComponentUI
Parameters:
a - the component from which this UI delegate is being removed; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.installUI(javax.swing.JComponent), JComponent.updateUI()

paint

public void paint(Graphics a,
                  JComponent b)
Invokes the paint method on each UI handled by this object.

Overrides:
paint in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.update(java.awt.Graphics, javax.swing.JComponent)

getPreferredSize

public Dimension getPreferredSize(JComponent a)
Invokes the getPreferredSize method on each UI handled by this object.

Overrides:
getPreferredSize in class ComponentUI
Parameters:
a - the component whose preferred size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getPreferredSize(), LayoutManager.preferredLayoutSize(java.awt.Container)

getMinimumSize

public Dimension getMinimumSize(JComponent a)
Invokes the getMinimumSize method on each UI handled by this object.

Overrides:
getMinimumSize in class ComponentUI
Parameters:
a - the component whose minimum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMinimumSize(),
LayoutManager.minimumLayoutSize(java.awt.Container),
ComponentUI.getPreferredSize(javax.swing.JComponent)

getMaximumSize

public Dimension getMaximumSize(JComponent a)
Invokes the getMaximumSize method on each UI handled by this object.

Overrides:
getMaximumSize in class ComponentUI
Parameters:
a - the component whose maximum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMaximumSize(), LayoutManager2.maximumLayoutSize(java.awt.Container)

getAccessibleChildrenCount

public int getAccessibleChildrenCount(JComponent a)
Invokes the getAccessibleChildrenCount method on each UI handled by this object.

Overrides:
getAccessibleChildrenCount in class ComponentUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChild(javax.swing.JComponent, int)

getAccessibleChild

public Accessible getAccessibleChild(JComponent a,
                                     int b)
Invokes the getAccessibleChild method on each UI handled by this object.

Overrides:
getAccessibleChild in class ComponentUI
Parameters:
b - zero-based index of child
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChildrenCount(javax.swing.JComponent)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MultiPanelUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.multi
Class MultiPanelUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.PanelUI
            extended by javax.swing.plaf.multi.MultiPanelUI
public class MultiPanelUI
extends PanelUI

A multiplexing UI used to combine PanelUIs.

This file was automatically generated by AutoMulti.

Field Summary
protected  Vector uis
The vector containing the real UIs.
Constructor Summary
MultiPanelUI()
Method Summary
boolean | contains(JComponent a, int b, int c) Invokes the contains method on each UI handled by this object.
static ComponentUI | createUI(JComponent a) Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI.
Accessible | getAccessibleChild(JComponent a, int b) Invokes the getAccessibleChild method on each UI handled by this object.
int | getAccessibleChildrenCount(JComponent a) Invokes the getAccessibleChildrenCount method on each UI handled by this object.
Dimension | getMaximumSize(JComponent a) Invokes the getMaximumSize method on each UI handled by this object.
Dimension | getMinimumSize(JComponent a) Invokes the getMinimumSize method on each UI handled by this object.
Dimension | getPreferredSize(JComponent a) Invokes the getPreferredSize method on each UI handled by this object.
ComponentUI[] | getUIs() Returns the list of UIs associated with this multiplexing UI.
void | installUI(JComponent a) Invokes the installUI method on each UI handled by this object.
void | paint(Graphics a, JComponent b) Invokes the paint method on each UI handled by this object.
void | uninstallUI(JComponent a) Invokes the uninstallUI method on each UI handled by this object.
void | update(Graphics a, JComponent b) Invokes the update method on each UI handled by this object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

uis

protected Vector uis
The vector containing the real UIs. This is populated in the call to createUI, and can be obtained by calling the getUIs method. The first element is guaranteed to be the real UI obtained from the default look and feel.

Constructor Detail

MultiPanelUI

public MultiPanelUI()
Method Detail

getUIs

public ComponentUI[] getUIs()
Returns the list of UIs associated with this multiplexing UI. This allows processing of the UIs by an application aware of multiplexing UIs on components.

contains

public boolean contains(JComponent a,
                        int b,
                        int c)
Invokes the contains method on each UI handled by this object.

Overrides:
contains in class ComponentUI
Parameters:
a - the component where the x,y location is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
b - the x coordinate of the point
c - the y coordinate of the point
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.contains(int, int), Component.contains(int, int)

update

public void update(Graphics a,
                   JComponent b)
Invokes the update method on each UI handled by this object.

Overrides:
update in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.paint(java.awt.Graphics, javax.swing.JComponent), JComponent.paintComponent(java.awt.Graphics)

createUI

public static ComponentUI createUI(JComponent a)
Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI. Otherwise, just returns the UI object obtained from the default LookAndFeel.

installUI

public void installUI(JComponent a)
Invokes the installUI method on each UI handled by this object.

Overrides:
installUI in class ComponentUI
Parameters:
a - the component where this UI delegate is being installed
See Also:
ComponentUI.uninstallUI(javax.swing.JComponent),
JComponent.setUI(javax.swing.plaf.ComponentUI),
JComponent.updateUI()

uninstallUI

public void uninstallUI(JComponent a)
Invokes the uninstallUI method on each UI handled by this object.

Overrides:
uninstallUI in class ComponentUI
Parameters:
a - the component from which this UI delegate is being removed; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.installUI(javax.swing.JComponent), JComponent.updateUI()

paint

public void paint(Graphics a,
                  JComponent b)
Invokes the paint method on each UI handled by this object.

Overrides:
paint in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.update(java.awt.Graphics, javax.swing.JComponent)

getPreferredSize

public Dimension getPreferredSize(JComponent a)
Invokes the getPreferredSize method on each UI handled by this object.

Overrides:
getPreferredSize in class ComponentUI
Parameters:
a - the component whose preferred size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getPreferredSize(), LayoutManager.preferredLayoutSize(java.awt.Container)

getMinimumSize

public Dimension getMinimumSize(JComponent a)
Invokes the getMinimumSize method on each UI handled by this object.

Overrides:
getMinimumSize in class ComponentUI
Parameters:
a - the component whose minimum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMinimumSize(),
LayoutManager.minimumLayoutSize(java.awt.Container),
ComponentUI.getPreferredSize(javax.swing.JComponent)

getMaximumSize

public Dimension getMaximumSize(JComponent a)
Invokes the getMaximumSize method on each UI handled by this object.

Overrides:
getMaximumSize in class ComponentUI
Parameters:
a - the component whose maximum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMaximumSize(), LayoutManager2.maximumLayoutSize(java.awt.Container)

getAccessibleChildrenCount

public int getAccessibleChildrenCount(JComponent a)
Invokes the getAccessibleChildrenCount method on each UI handled by this object.

Overrides:
getAccessibleChildrenCount in class ComponentUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChild(javax.swing.JComponent, int)

getAccessibleChild

public Accessible getAccessibleChild(JComponent a,
                                     int b)
Invokes the getAccessibleChild method on each UI handled by this object.

Overrides:
getAccessibleChild in class ComponentUI
Parameters:
b - zero-based index of child
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChildrenCount(javax.swing.JComponent)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MultiPopupMenuUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.multi
Class MultiPopupMenuUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.PopupMenuUI
            extended by javax.swing.plaf.multi.MultiPopupMenuUI
public class MultiPopupMenuUI
extends PopupMenuUI

A multiplexing UI used to combine PopupMenuUIs.

This file was automatically generated by AutoMulti.

Field Summary
protected  Vector uis
The vector containing the real UIs.
Constructor Summary
MultiPopupMenuUI()
Method Summary
boolean | contains(JComponent a, int b, int c) Invokes the contains method on each UI handled by this object.
static ComponentUI | createUI(JComponent a) Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI.
Accessible | getAccessibleChild(JComponent a, int b) Invokes the getAccessibleChild method on each UI handled by this object.
int | getAccessibleChildrenCount(JComponent a) Invokes the getAccessibleChildrenCount method on each UI handled by this object.
Dimension | getMaximumSize(JComponent a) Invokes the getMaximumSize method on each UI handled by this object.
Dimension | getMinimumSize(JComponent a) Invokes the getMinimumSize method on each UI handled by this object.
Popup | getPopup(JPopupMenu a, int b, int c) Invokes the getPopup method on each UI handled by this object.
Dimension | getPreferredSize(JComponent a) Invokes the getPreferredSize method on each UI handled by this object.
ComponentUI[] | getUIs() Returns the list of UIs associated with this multiplexing UI.
void | installUI(JComponent a) Invokes the installUI method on each UI handled by this object.
boolean | isPopupTrigger(MouseEvent a) Invokes the isPopupTrigger method on each UI handled by this object.
void | paint(Graphics a, JComponent b) Invokes the paint method on each UI handled by this object.
void | uninstallUI(JComponent a) Invokes the uninstallUI method on each UI handled by this object.
void | update(Graphics a, JComponent b) Invokes the update method on each UI handled by this object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

uis

protected Vector uis
The vector containing the real UIs. This is populated in the call to createUI, and can be obtained by calling the getUIs method. The first element is guaranteed to be the real UI obtained from the default look and feel.

Constructor Detail

MultiPopupMenuUI

public MultiPopupMenuUI()
Method Detail

getUIs

public ComponentUI[] getUIs()
Returns the list of UIs associated with this multiplexing UI. This allows processing of the UIs by an application aware of multiplexing UIs on components.

isPopupTrigger

public boolean isPopupTrigger(MouseEvent a)
Invokes the isPopupTrigger method on each UI handled by this object.

Overrides:
isPopupTrigger in class PopupMenuUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel

getPopup

public Popup getPopup(JPopupMenu a,
                      int b,
                      int c)
Invokes the getPopup method on each UI handled by this object.

Overrides:
getPopup in class PopupMenuUI
Parameters:
a - JPopupMenu requesting Popup
b - Screen x location Popup is to be shown at
c - Screen y location Popup is to be shown at.
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel

contains

public boolean contains(JComponent a,
                        int b,
                        int c)
Invokes the contains method on each UI handled by this object.

Overrides:
contains in class ComponentUI
Parameters:
a - the component where the x,y location is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
b - the x coordinate of the point
c - the y coordinate of the point
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.contains(int, int), Component.contains(int, int)

update

public void update(Graphics a,
                   JComponent b)
Invokes the update method on each UI handled by this object.

Overrides:
update in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.paint(java.awt.Graphics, javax.swing.JComponent), JComponent.paintComponent(java.awt.Graphics)

createUI

public static ComponentUI createUI(JComponent a)
Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI. Otherwise, just returns the UI object obtained from the default LookAndFeel.

installUI

public void installUI(JComponent a)
Invokes the installUI method on each UI handled by this object.

Overrides:
installUI in class ComponentUI
Parameters:
a - the component where this UI delegate is being installed
See Also:
ComponentUI.uninstallUI(javax.swing.JComponent),
JComponent.setUI(javax.swing.plaf.ComponentUI),
JComponent.updateUI()

uninstallUI

public void uninstallUI(JComponent a)
Invokes the uninstallUI method on each UI handled by this object.

Overrides:
uninstallUI in class ComponentUI
Parameters:
a - the component from which this UI delegate is being removed; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.installUI(javax.swing.JComponent), JComponent.updateUI()

paint

public void paint(Graphics a,
                  JComponent b)
Invokes the paint method on each UI handled by this object.

Overrides:
paint in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.update(java.awt.Graphics, javax.swing.JComponent)

getPreferredSize

public Dimension getPreferredSize(JComponent a)
Invokes the getPreferredSize method on each UI handled by this object.

Overrides:
getPreferredSize in class ComponentUI
Parameters:
a - the component whose preferred size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getPreferredSize(), LayoutManager.preferredLayoutSize(java.awt.Container)

getMinimumSize

public Dimension getMinimumSize(JComponent a)
Invokes the getMinimumSize method on each UI handled by this object.

Overrides:
getMinimumSize in class ComponentUI
Parameters:
a - the component whose minimum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMinimumSize(),
LayoutManager.minimumLayoutSize(java.awt.Container),
ComponentUI.getPreferredSize(javax.swing.JComponent)

getMaximumSize

public Dimension getMaximumSize(JComponent a)
Invokes the getMaximumSize method on each UI handled by this object.

Overrides:
getMaximumSize in class ComponentUI
Parameters:
a - the component whose maximum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMaximumSize(), LayoutManager2.maximumLayoutSize(java.awt.Container)

getAccessibleChildrenCount

public int getAccessibleChildrenCount(JComponent a)
Invokes the getAccessibleChildrenCount method on each UI handled by this object.

Overrides:
getAccessibleChildrenCount in class ComponentUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChild(javax.swing.JComponent, int)

getAccessibleChild

public Accessible getAccessibleChild(JComponent a,
                                     int b)
Invokes the getAccessibleChild method on each UI handled by this object.

Overrides:
getAccessibleChild in class ComponentUI
Parameters:
b - zero-based index of child
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChildrenCount(javax.swing.JComponent)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MultiProgressBarUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.multi
Class MultiProgressBarUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.ProgressBarUI
            extended by javax.swing.plaf.multi.MultiProgressBarUI
public class MultiProgressBarUI
extends ProgressBarUI

A multiplexing UI used to combine ProgressBarUIs.

This file was automatically generated by AutoMulti.

Field Summary
protected  Vector uis
The vector containing the real UIs.
Constructor Summary
MultiProgressBarUI()
Method Summary
boolean | contains(JComponent a, int b, int c) Invokes the contains method on each UI handled by this object.
static ComponentUI | createUI(JComponent a) Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI.
Accessible | getAccessibleChild(JComponent a, int b) Invokes the getAccessibleChild method on each UI handled by this object.
int | getAccessibleChildrenCount(JComponent a) Invokes the getAccessibleChildrenCount method on each UI handled by this object.
Dimension | getMaximumSize(JComponent a) Invokes the getMaximumSize method on each UI handled by this object.
Dimension | getMinimumSize(JComponent a) Invokes the getMinimumSize method on each UI handled by this object.
Dimension | getPreferredSize(JComponent a) Invokes the getPreferredSize method on each UI handled by this object.
ComponentUI[] | getUIs() Returns the list of UIs associated with this multiplexing UI.
void | installUI(JComponent a) Invokes the installUI method on each UI handled by this object.
void | paint(Graphics a, JComponent b) Invokes the paint method on each UI handled by this object.
void | uninstallUI(JComponent a) Invokes the uninstallUI method on each UI handled by this object.
void | update(Graphics a, JComponent b) Invokes the update method on each UI handled by this object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

uis

protected Vector uis
The vector containing the real UIs. This is populated in the call to createUI, and can be obtained by calling the getUIs method. The first element is guaranteed to be the real UI obtained from the default look and feel.

Constructor Detail

MultiProgressBarUI

public MultiProgressBarUI()
Method Detail

getUIs

public ComponentUI[] getUIs()
Returns the list of UIs associated with this multiplexing UI. This allows processing of the UIs by an application aware of multiplexing UIs on components.

contains

public boolean contains(JComponent a,
                        int b,
                        int c)
Invokes the contains method on each UI handled by this object.

Overrides:
contains in class ComponentUI
Parameters:
a - the component where the x,y location is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
b - the x coordinate of the point
c - the y coordinate of the point
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.contains(int, int), Component.contains(int, int)

update

public void update(Graphics a,
                   JComponent b)
Invokes the update method on each UI handled by this object.

Overrides:
update in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.paint(java.awt.Graphics, javax.swing.JComponent), JComponent.paintComponent(java.awt.Graphics)

createUI

public static ComponentUI createUI(JComponent a)
Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI. Otherwise, just returns the UI object obtained from the default LookAndFeel.

installUI

public void installUI(JComponent a)
Invokes the installUI method on each UI handled by this object.

Overrides:
installUI in class ComponentUI
Parameters:
a - the component where this UI delegate is being installed
See Also:
ComponentUI.uninstallUI(javax.swing.JComponent),
JComponent.setUI(javax.swing.plaf.ComponentUI),
JComponent.updateUI()

uninstallUI

public void uninstallUI(JComponent a)
Invokes the uninstallUI method on each UI handled by this object.

Overrides:
uninstallUI in class ComponentUI
Parameters:
a - the component from which this UI delegate is being removed; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.installUI(javax.swing.JComponent), JComponent.updateUI()

paint

public void paint(Graphics a,
                  JComponent b)
Invokes the paint method on each UI handled by this object.

Overrides:
paint in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.update(java.awt.Graphics, javax.swing.JComponent)

getPreferredSize

public Dimension getPreferredSize(JComponent a)
Invokes the getPreferredSize method on each UI handled by this object.

Overrides:
getPreferredSize in class ComponentUI
Parameters:
a - the component whose preferred size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getPreferredSize(), LayoutManager.preferredLayoutSize(java.awt.Container)

getMinimumSize

public Dimension getMinimumSize(JComponent a)
Invokes the getMinimumSize method on each UI handled by this object.

Overrides:
getMinimumSize in class ComponentUI
Parameters:
a - the component whose minimum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMinimumSize(),
LayoutManager.minimumLayoutSize(java.awt.Container),
ComponentUI.getPreferredSize(javax.swing.JComponent)

getMaximumSize

public Dimension getMaximumSize(JComponent a)
Invokes the getMaximumSize method on each UI handled by this object.

Overrides:
getMaximumSize in class ComponentUI
Parameters:
a - the component whose maximum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMaximumSize(), LayoutManager2.maximumLayoutSize(java.awt.Container)

getAccessibleChildrenCount

public int getAccessibleChildrenCount(JComponent a)
Invokes the getAccessibleChildrenCount method on each UI handled by this object.

Overrides:
getAccessibleChildrenCount in class ComponentUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChild(javax.swing.JComponent, int)

getAccessibleChild

public Accessible getAccessibleChild(JComponent a,
                                     int b)
Invokes the getAccessibleChild method on each UI handled by this object.

Overrides:
getAccessibleChild in class ComponentUI
Parameters:
b - zero-based index of child
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChildrenCount(javax.swing.JComponent)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MultiRootPaneUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.multi
Class MultiRootPaneUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.RootPaneUI
            extended by javax.swing.plaf.multi.MultiRootPaneUI
public class MultiRootPaneUI
extends RootPaneUI

A multiplexing UI used to combine RootPaneUIs.

This file was automatically generated by AutoMulti.

Field Summary
protected  Vector uis
The vector containing the real UIs.
Constructor Summary
MultiRootPaneUI()
Method Summary
boolean | contains(JComponent a, int b, int c) Invokes the contains method on each UI handled by this object.
static ComponentUI | createUI(JComponent a) Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI.
Accessible | getAccessibleChild(JComponent a, int b) Invokes the getAccessibleChild method on each UI handled by this object.
int | getAccessibleChildrenCount(JComponent a) Invokes the getAccessibleChildrenCount method on each UI handled by this object.
Dimension | getMaximumSize(JComponent a) Invokes the getMaximumSize method on each UI handled by this object.
Dimension | getMinimumSize(JComponent a) Invokes the getMinimumSize method on each UI handled by this object.
Dimension | getPreferredSize(JComponent a) Invokes the getPreferredSize method on each UI handled by this object.
ComponentUI[] | getUIs() Returns the list of UIs associated with this multiplexing UI.
void | installUI(JComponent a) Invokes the installUI method on each UI handled by this object.
void | paint(Graphics a, JComponent b) Invokes the paint method on each UI handled by this object.
void | uninstallUI(JComponent a) Invokes the uninstallUI method on each UI handled by this object.
void | update(Graphics a, JComponent b) Invokes the update method on each UI handled by this object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

uis

protected Vector uis
The vector containing the real UIs. This is populated in the call to createUI, and can be obtained by calling the getUIs method. The first element is guaranteed to be the real UI obtained from the default look and feel.

Constructor Detail

MultiRootPaneUI

public MultiRootPaneUI()
Method Detail

getUIs

public ComponentUI[] getUIs()
Returns the list of UIs associated with this multiplexing UI. This allows processing of the UIs by an application aware of multiplexing UIs on components.

contains

public boolean contains(JComponent a,
                        int b,
                        int c)
Invokes the contains method on each UI handled by this object.

Overrides:
contains in class ComponentUI
Parameters:
a - the component where the x,y location is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
b - the x coordinate of the point
c - the y coordinate of the point
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.contains(int, int), Component.contains(int, int)

update

public void update(Graphics a,
                   JComponent b)
Invokes the update method on each UI handled by this object.

Overrides:
update in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.paint(java.awt.Graphics, javax.swing.JComponent), JComponent.paintComponent(java.awt.Graphics)

createUI

public static ComponentUI createUI(JComponent a)
Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI. Otherwise, just returns the UI object obtained from the default LookAndFeel.

installUI

public void installUI(JComponent a)
Invokes the installUI method on each UI handled by this object.

Overrides:
installUI in class ComponentUI
Parameters:
a - the component where this UI delegate is being installed
See Also:
ComponentUI.uninstallUI(javax.swing.JComponent),
JComponent.setUI(javax.swing.plaf.ComponentUI),
JComponent.updateUI()

uninstallUI

public void uninstallUI(JComponent a)
Invokes the uninstallUI method on each UI handled by this object.

Overrides:
uninstallUI in class ComponentUI
Parameters:
a - the component from which this UI delegate is being removed; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.installUI(javax.swing.JComponent), JComponent.updateUI()

paint

public void paint(Graphics a,
                  JComponent b)
Invokes the paint method on each UI handled by this object.

Overrides:
paint in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.update(java.awt.Graphics, javax.swing.JComponent)

getPreferredSize

public Dimension getPreferredSize(JComponent a)
Invokes the getPreferredSize method on each UI handled by this object.

Overrides:
getPreferredSize in class ComponentUI
Parameters:
a - the component whose preferred size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getPreferredSize(), LayoutManager.preferredLayoutSize(java.awt.Container)

getMinimumSize

public Dimension getMinimumSize(JComponent a)
Invokes the getMinimumSize method on each UI handled by this object.

Overrides:
getMinimumSize in class ComponentUI
Parameters:
a - the component whose minimum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMinimumSize(),
LayoutManager.minimumLayoutSize(java.awt.Container),
ComponentUI.getPreferredSize(javax.swing.JComponent)

getMaximumSize

public Dimension getMaximumSize(JComponent a)
Invokes the getMaximumSize method on each UI handled by this object.

Overrides:
getMaximumSize in class ComponentUI
Parameters:
a - the component whose maximum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMaximumSize(), LayoutManager2.maximumLayoutSize(java.awt.Container)

getAccessibleChildrenCount

public int getAccessibleChildrenCount(JComponent a)
Invokes the getAccessibleChildrenCount method on each UI handled by this object.

Overrides:
getAccessibleChildrenCount in class ComponentUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChild(javax.swing.JComponent, int)

getAccessibleChild

public Accessible getAccessibleChild(JComponent a,
                                     int b)
Invokes the getAccessibleChild method on each UI handled by this object.

Overrides:
getAccessibleChild in class ComponentUI
Parameters:
b - zero-based index of child
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChildrenCount(javax.swing.JComponent)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MultiScrollBarUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.multi
Class MultiScrollBarUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.ScrollBarUI
            extended by javax.swing.plaf.multi.MultiScrollBarUI
public class MultiScrollBarUI
extends ScrollBarUI

A multiplexing UI used to combine ScrollBarUIs.

This file was automatically generated by AutoMulti.

Field Summary
protected  Vector uis
The vector containing the real UIs.
Constructor Summary
MultiScrollBarUI()
Method Summary
boolean | contains(JComponent a, int b, int c) Invokes the contains method on each UI handled by this object.
static ComponentUI | createUI(JComponent a) Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI.
Accessible | getAccessibleChild(JComponent a, int b) Invokes the getAccessibleChild method on each UI handled by this object.
int | getAccessibleChildrenCount(JComponent a) Invokes the getAccessibleChildrenCount method on each UI handled by this object.
Dimension | getMaximumSize(JComponent a) Invokes the getMaximumSize method on each UI handled by this object.
Dimension | getMinimumSize(JComponent a) Invokes the getMinimumSize method on each UI handled by this object.
Dimension | getPreferredSize(JComponent a) Invokes the getPreferredSize method on each UI handled by this object.
ComponentUI[] | getUIs() Returns the list of UIs associated with this multiplexing UI.
void | installUI(JComponent a) Invokes the installUI method on each UI handled by this object.
void | paint(Graphics a, JComponent b) Invokes the paint method on each UI handled by this object.
void | uninstallUI(JComponent a) Invokes the uninstallUI method on each UI handled by this object.
void | update(Graphics a, JComponent b) Invokes the update method on each UI handled by this object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

uis

protected Vector uis
The vector containing the real UIs. This is populated in the call to createUI, and can be obtained by calling the getUIs method. The first element is guaranteed to be the real UI obtained from the default look and feel.

Constructor Detail

MultiScrollBarUI

public MultiScrollBarUI()
Method Detail

getUIs

public ComponentUI[] getUIs()
Returns the list of UIs associated with this multiplexing UI. This allows processing of the UIs by an application aware of multiplexing UIs on components.

contains

public boolean contains(JComponent a,
                        int b,
                        int c)
Invokes the contains method on each UI handled by this object.

Overrides:
contains in class ComponentUI
Parameters:
a - the component where the x,y location is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
b - the x coordinate of the point
c - the y coordinate of the point
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.contains(int, int), Component.contains(int, int)

update

public void update(Graphics a,
                   JComponent b)
Invokes the update method on each UI handled by this object.

Overrides:
update in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.paint(java.awt.Graphics, javax.swing.JComponent), JComponent.paintComponent(java.awt.Graphics)

createUI

public static ComponentUI createUI(JComponent a)
Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI. Otherwise, just returns the UI object obtained from the default LookAndFeel.

installUI

public void installUI(JComponent a)
Invokes the installUI method on each UI handled by this object.

Overrides:
installUI in class ComponentUI
Parameters:
a - the component where this UI delegate is being installed
See Also:
ComponentUI.uninstallUI(javax.swing.JComponent),
JComponent.setUI(javax.swing.plaf.ComponentUI),
JComponent.updateUI()

uninstallUI

public void uninstallUI(JComponent a)
Invokes the uninstallUI method on each UI handled by this object.

Overrides:
uninstallUI in class ComponentUI
Parameters:
a - the component from which this UI delegate is being removed; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.installUI(javax.swing.JComponent), JComponent.updateUI()

paint

public void paint(Graphics a,
                  JComponent b)
Invokes the paint method on each UI handled by this object.

Overrides:
paint in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.update(java.awt.Graphics, javax.swing.JComponent)

getPreferredSize

public Dimension getPreferredSize(JComponent a)
Invokes the getPreferredSize method on each UI handled by this object.

Overrides:
getPreferredSize in class ComponentUI
Parameters:
a - the component whose preferred size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getPreferredSize(), LayoutManager.preferredLayoutSize(java.awt.Container)

getMinimumSize

public Dimension getMinimumSize(JComponent a)
Invokes the getMinimumSize method on each UI handled by this object.

Overrides:
getMinimumSize in class ComponentUI
Parameters:
a - the component whose minimum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMinimumSize(),
LayoutManager.minimumLayoutSize(java.awt.Container),
ComponentUI.getPreferredSize(javax.swing.JComponent)

getMaximumSize

public Dimension getMaximumSize(JComponent a)
Invokes the getMaximumSize method on each UI handled by this object.

Overrides:
getMaximumSize in class ComponentUI
Parameters:
a - the component whose maximum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMaximumSize(), LayoutManager2.maximumLayoutSize(java.awt.Container)

getAccessibleChildrenCount

public int getAccessibleChildrenCount(JComponent a)
Invokes the getAccessibleChildrenCount method on each UI handled by this object.

Overrides:
getAccessibleChildrenCount in class ComponentUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChild(javax.swing.JComponent, int)

getAccessibleChild

public Accessible getAccessibleChild(JComponent a,
                                     int b)
Invokes the getAccessibleChild method on each UI handled by this object.

Overrides:
getAccessibleChild in class ComponentUI
Parameters:
b - zero-based index of child
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChildrenCount(javax.swing.JComponent)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MultiScrollPaneUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.multi
Class MultiScrollPaneUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.ScrollPaneUI
            extended by javax.swing.plaf.multi.MultiScrollPaneUI
public class MultiScrollPaneUI
extends ScrollPaneUI

A multiplexing UI used to combine ScrollPaneUIs.

This file was automatically generated by AutoMulti.

Field Summary
protected  Vector uis
The vector containing the real UIs.
Constructor Summary
MultiScrollPaneUI()
Method Summary
boolean | contains(JComponent a, int b, int c) Invokes the contains method on each UI handled by this object.
static ComponentUI | createUI(JComponent a) Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI.
Accessible | getAccessibleChild(JComponent a, int b) Invokes the getAccessibleChild method on each UI handled by this object.
int | getAccessibleChildrenCount(JComponent a) Invokes the getAccessibleChildrenCount method on each UI handled by this object.
Dimension | getMaximumSize(JComponent a) Invokes the getMaximumSize method on each UI handled by this object.
Dimension | getMinimumSize(JComponent a) Invokes the getMinimumSize method on each UI handled by this object.
Dimension | getPreferredSize(JComponent a) Invokes the getPreferredSize method on each UI handled by this object.
ComponentUI[] | getUIs() Returns the list of UIs associated with this multiplexing UI.
void | installUI(JComponent a) Invokes the installUI method on each UI handled by this object.
void | paint(Graphics a, JComponent b) Invokes the paint method on each UI handled by this object.
void | uninstallUI(JComponent a) Invokes the uninstallUI method on each UI handled by this object.
void | update(Graphics a, JComponent b) Invokes the update method on each UI handled by this object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

uis

protected Vector uis
The vector containing the real UIs. This is populated in the call to createUI, and can be obtained by calling the getUIs method. The first element is guaranteed to be the real UI obtained from the default look and feel.

Constructor Detail

MultiScrollPaneUI

public MultiScrollPaneUI()
Method Detail

getUIs

public ComponentUI[] getUIs()
Returns the list of UIs associated with this multiplexing UI. This allows processing of the UIs by an application aware of multiplexing UIs on components.

contains

public boolean contains(JComponent a,
                        int b,
                        int c)
Invokes the contains method on each UI handled by this object.

Overrides:
contains in class ComponentUI
Parameters:
a - the component where the x,y location is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
b - the x coordinate of the point
c - the y coordinate of the point
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.contains(int, int), Component.contains(int, int)

update

public void update(Graphics a,
                   JComponent b)
Invokes the update method on each UI handled by this object.

Overrides:
update in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.paint(java.awt.Graphics, javax.swing.JComponent), JComponent.paintComponent(java.awt.Graphics)

createUI

public static ComponentUI createUI(JComponent a)
Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI. Otherwise, just returns the UI object obtained from the default LookAndFeel.

installUI

public void installUI(JComponent a)
Invokes the installUI method on each UI handled by this object.

Overrides:
installUI in class ComponentUI
Parameters:
a - the component where this UI delegate is being installed
See Also:
ComponentUI.uninstallUI(javax.swing.JComponent),
JComponent.setUI(javax.swing.plaf.ComponentUI),
JComponent.updateUI()

uninstallUI

public void uninstallUI(JComponent a)
Invokes the uninstallUI method on each UI handled by this object.

Overrides:
uninstallUI in class ComponentUI
Parameters:
a - the component from which this UI delegate is being removed; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.installUI(javax.swing.JComponent), JComponent.updateUI()

paint

public void paint(Graphics a,
                  JComponent b)
Invokes the paint method on each UI handled by this object.

Overrides:
paint in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.update(java.awt.Graphics, javax.swing.JComponent)

getPreferredSize

public Dimension getPreferredSize(JComponent a)
Invokes the getPreferredSize method on each UI handled by this object.

Overrides:
getPreferredSize in class ComponentUI
Parameters:
a - the component whose preferred size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getPreferredSize(), LayoutManager.preferredLayoutSize(java.awt.Container)

getMinimumSize

public Dimension getMinimumSize(JComponent a)
Invokes the getMinimumSize method on each UI handled by this object.

Overrides:
getMinimumSize in class ComponentUI
Parameters:
a - the component whose minimum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMinimumSize(),
LayoutManager.minimumLayoutSize(java.awt.Container),
ComponentUI.getPreferredSize(javax.swing.JComponent)

getMaximumSize

public Dimension getMaximumSize(JComponent a)
Invokes the getMaximumSize method on each UI handled by this object.

Overrides:
getMaximumSize in class ComponentUI
Parameters:
a - the component whose maximum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMaximumSize(), LayoutManager2.maximumLayoutSize(java.awt.Container)

getAccessibleChildrenCount

public int getAccessibleChildrenCount(JComponent a)
Invokes the getAccessibleChildrenCount method on each UI handled by this object.

Overrides:
getAccessibleChildrenCount in class ComponentUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChild(javax.swing.JComponent, int)

getAccessibleChild

public Accessible getAccessibleChild(JComponent a,
                                     int b)
Invokes the getAccessibleChild method on each UI handled by this object.

Overrides:
getAccessibleChild in class ComponentUI
Parameters:
b - zero-based index of child
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChildrenCount(javax.swing.JComponent)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MultiSeparatorUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.multi
Class MultiSeparatorUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.SeparatorUI
            extended by javax.swing.plaf.multi.MultiSeparatorUI
public class MultiSeparatorUI
extends SeparatorUI

A multiplexing UI used to combine SeparatorUIs.

This file was automatically generated by AutoMulti.

Field Summary
protected  Vector uis
The vector containing the real UIs.
Constructor Summary
MultiSeparatorUI()
Method Summary
boolean | contains(JComponent a, int b, int c) Invokes the contains method on each UI handled by this object.
static ComponentUI | createUI(JComponent a) Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI.
Accessible | getAccessibleChild(JComponent a, int b) Invokes the getAccessibleChild method on each UI handled by this object.
int | getAccessibleChildrenCount(JComponent a) Invokes the getAccessibleChildrenCount method on each UI handled by this object.
Dimension | getMaximumSize(JComponent a) Invokes the getMaximumSize method on each UI handled by this object.
Dimension | getMinimumSize(JComponent a) Invokes the getMinimumSize method on each UI handled by this object.
Dimension | getPreferredSize(JComponent a) Invokes the getPreferredSize method on each UI handled by this object.
ComponentUI[] | getUIs() Returns the list of UIs associated with this multiplexing UI.
void | installUI(JComponent a) Invokes the installUI method on each UI handled by this object.
void | paint(Graphics a, JComponent b) Invokes the paint method on each UI handled by this object.
void | uninstallUI(JComponent a) Invokes the uninstallUI method on each UI handled by this object.
void | update(Graphics a, JComponent b) Invokes the update method on each UI handled by this object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

uis

protected Vector uis
The vector containing the real UIs. This is populated in the call to createUI, and can be obtained by calling the getUIs method. The first element is guaranteed to be the real UI obtained from the default look and feel.

Constructor Detail

MultiSeparatorUI

public MultiSeparatorUI()
Method Detail

getUIs

public ComponentUI[] getUIs()
Returns the list of UIs associated with this multiplexing UI. This allows processing of the UIs by an application aware of multiplexing UIs on components.

contains

public boolean contains(JComponent a,
                        int b,
                        int c)
Invokes the contains method on each UI handled by this object.

Overrides:
contains in class ComponentUI
Parameters:
a - the component where the x,y location is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
b - the x coordinate of the point
c - the y coordinate of the point
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.contains(int, int), Component.contains(int, int)

update

public void update(Graphics a,
                   JComponent b)
Invokes the update method on each UI handled by this object.

Overrides:
update in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.paint(java.awt.Graphics, javax.swing.JComponent), JComponent.paintComponent(java.awt.Graphics)

createUI

public static ComponentUI createUI(JComponent a)
Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI. Otherwise, just returns the UI object obtained from the default LookAndFeel.

installUI

public void installUI(JComponent a)
Invokes the installUI method on each UI handled by this object.

Overrides:
installUI in class ComponentUI
Parameters:
a - the component where this UI delegate is being installed
See Also:
ComponentUI.uninstallUI(javax.swing.JComponent),
JComponent.setUI(javax.swing.plaf.ComponentUI),
JComponent.updateUI()

uninstallUI

public void uninstallUI(JComponent a)
Invokes the uninstallUI method on each UI handled by this object.

Overrides:
uninstallUI in class ComponentUI
Parameters:
a - the component from which this UI delegate is being removed; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.installUI(javax.swing.JComponent), JComponent.updateUI()

paint

public void paint(Graphics a,
                  JComponent b)
Invokes the paint method on each UI handled by this object.

Overrides:
paint in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.update(java.awt.Graphics, javax.swing.JComponent)

getPreferredSize

public Dimension getPreferredSize(JComponent a)
Invokes the getPreferredSize method on each UI handled by this object.

Overrides:
getPreferredSize in class ComponentUI
Parameters:
a - the component whose preferred size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getPreferredSize(), LayoutManager.preferredLayoutSize(java.awt.Container)

getMinimumSize

public Dimension getMinimumSize(JComponent a)
Invokes the getMinimumSize method on each UI handled by this object.

Overrides:
getMinimumSize in class ComponentUI
Parameters:
a - the component whose minimum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMinimumSize(),
LayoutManager.minimumLayoutSize(java.awt.Container),
ComponentUI.getPreferredSize(javax.swing.JComponent)

getMaximumSize

public Dimension getMaximumSize(JComponent a)
Invokes the getMaximumSize method on each UI handled by this object.

Overrides:
getMaximumSize in class ComponentUI
Parameters:
a - the component whose maximum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMaximumSize(), LayoutManager2.maximumLayoutSize(java.awt.Container)

getAccessibleChildrenCount

public int getAccessibleChildrenCount(JComponent a)
Invokes the getAccessibleChildrenCount method on each UI handled by this object.

Overrides:
getAccessibleChildrenCount in class ComponentUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChild(javax.swing.JComponent, int)

getAccessibleChild

public Accessible getAccessibleChild(JComponent a,
                                     int b)
Invokes the getAccessibleChild method on each UI handled by this object.

Overrides:
getAccessibleChild in class ComponentUI
Parameters:
b - zero-based index of child
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChildrenCount(javax.swing.JComponent)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MultiSliderUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.multi
Class MultiSliderUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.SliderUI
            extended by javax.swing.plaf.multi.MultiSliderUI
public class MultiSliderUI
extends SliderUI

A multiplexing UI used to combine SliderUIs.

This file was automatically generated by AutoMulti.

Field Summary
protected  Vector uis
The vector containing the real UIs.
Constructor Summary
MultiSliderUI()
Method Summary
boolean | contains(JComponent a, int b, int c) Invokes the contains method on each UI handled by this object.
static ComponentUI | createUI(JComponent a) Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI.
Accessible | getAccessibleChild(JComponent a, int b) Invokes the getAccessibleChild method on each UI handled by this object.
int | getAccessibleChildrenCount(JComponent a) Invokes the getAccessibleChildrenCount method on each UI handled by this object.
Dimension | getMaximumSize(JComponent a) Invokes the getMaximumSize method on each UI handled by this object.
Dimension | getMinimumSize(JComponent a) Invokes the getMinimumSize method on each UI handled by this object.
Dimension | getPreferredSize(JComponent a) Invokes the getPreferredSize method on each UI handled by this object.
ComponentUI[] | getUIs() Returns the list of UIs associated with this multiplexing UI.
void | installUI(JComponent a) Invokes the installUI method on each UI handled by this object.
void | paint(Graphics a, JComponent b) Invokes the paint method on each UI handled by this object.
void | uninstallUI(JComponent a) Invokes the uninstallUI method on each UI handled by this object.
void | update(Graphics a, JComponent b) Invokes the update method on each UI handled by this object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

uis

protected Vector uis
The vector containing the real UIs. This is populated in the call to createUI, and can be obtained by calling the getUIs method. The first element is guaranteed to be the real UI obtained from the default look and feel.

Constructor Detail

MultiSliderUI

public MultiSliderUI()
Method Detail

getUIs

public ComponentUI[] getUIs()
Returns the list of UIs associated with this multiplexing UI. This allows processing of the UIs by an application aware of multiplexing UIs on components.

contains

public boolean contains(JComponent a,
                        int b,
                        int c)
Invokes the contains method on each UI handled by this object.

Overrides:
contains in class ComponentUI
Parameters:
a - the component where the x,y location is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
b - the x coordinate of the point
c - the y coordinate of the point
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.contains(int, int), Component.contains(int, int)

update

public void update(Graphics a,
                   JComponent b)
Invokes the update method on each UI handled by this object.

Overrides:
update in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.paint(java.awt.Graphics, javax.swing.JComponent), JComponent.paintComponent(java.awt.Graphics)

createUI

public static ComponentUI createUI(JComponent a)
Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI. Otherwise, just returns the UI object obtained from the default LookAndFeel.

installUI

public void installUI(JComponent a)
Invokes the installUI method on each UI handled by this object.

Overrides:
installUI in class ComponentUI
Parameters:
a - the component where this UI delegate is being installed
See Also:
ComponentUI.uninstallUI(javax.swing.JComponent),
JComponent.setUI(javax.swing.plaf.ComponentUI),
JComponent.updateUI()

uninstallUI

public void uninstallUI(JComponent a)
Invokes the uninstallUI method on each UI handled by this object.

Overrides:
uninstallUI in class ComponentUI
Parameters:
a - the component from which this UI delegate is being removed; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.installUI(javax.swing.JComponent), JComponent.updateUI()

paint

public void paint(Graphics a,
                  JComponent b)
Invokes the paint method on each UI handled by this object.

Overrides:
paint in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.update(java.awt.Graphics, javax.swing.JComponent)

getPreferredSize

public Dimension getPreferredSize(JComponent a)
Invokes the getPreferredSize method on each UI handled by this object.

Overrides:
getPreferredSize in class ComponentUI
Parameters:
a - the component whose preferred size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getPreferredSize(), LayoutManager.preferredLayoutSize(java.awt.Container)

getMinimumSize

public Dimension getMinimumSize(JComponent a)
Invokes the getMinimumSize method on each UI handled by this object.

Overrides:
getMinimumSize in class ComponentUI
Parameters:
a - the component whose minimum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMinimumSize(),
LayoutManager.minimumLayoutSize(java.awt.Container),
ComponentUI.getPreferredSize(javax.swing.JComponent)

getMaximumSize

public Dimension getMaximumSize(JComponent a)
Invokes the getMaximumSize method on each UI handled by this object.

Overrides:
getMaximumSize in class ComponentUI
Parameters:
a - the component whose maximum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMaximumSize(), LayoutManager2.maximumLayoutSize(java.awt.Container)

getAccessibleChildrenCount

public int getAccessibleChildrenCount(JComponent a)
Invokes the getAccessibleChildrenCount method on each UI handled by this object.

Overrides:
getAccessibleChildrenCount in class ComponentUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChild(javax.swing.JComponent, int)

getAccessibleChild

public Accessible getAccessibleChild(JComponent a,
                                     int b)
Invokes the getAccessibleChild method on each UI handled by this object.

Overrides:
getAccessibleChild in class ComponentUI
Parameters:
b - zero-based index of child
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChildrenCount(javax.swing.JComponent)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MultiSpinnerUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.multi
Class MultiSpinnerUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.SpinnerUI
            extended by javax.swing.plaf.multi.MultiSpinnerUI
public class MultiSpinnerUI
extends SpinnerUI

A multiplexing UI used to combine SpinnerUIs.

This file was automatically generated by AutoMulti.

Field Summary
protected  Vector uis
The vector containing the real UIs.
Constructor Summary
MultiSpinnerUI()
Method Summary
boolean | contains(JComponent a, int b, int c) Invokes the contains method on each UI handled by this object.
static ComponentUI | createUI(JComponent a) Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI.
Accessible | getAccessibleChild(JComponent a, int b) Invokes the getAccessibleChild method on each UI handled by this object.
int | getAccessibleChildrenCount(JComponent a) Invokes the getAccessibleChildrenCount method on each UI handled by this object.
Dimension | getMaximumSize(JComponent a) Invokes the getMaximumSize method on each UI handled by this object.
Dimension | getMinimumSize(JComponent a) Invokes the getMinimumSize method on each UI handled by this object.
Dimension | getPreferredSize(JComponent a) Invokes the getPreferredSize method on each UI handled by this object.
ComponentUI[] | getUIs() Returns the list of UIs associated with this multiplexing UI.
void | installUI(JComponent a) Invokes the installUI method on each UI handled by this object.
void | paint(Graphics a, JComponent b) Invokes the paint method on each UI handled by this object.
void | uninstallUI(JComponent a) Invokes the uninstallUI method on each UI handled by this object.
void | update(Graphics a, JComponent b) Invokes the update method on each UI handled by this object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

uis

protected Vector uis
The vector containing the real UIs. This is populated in the call to createUI, and can be obtained by calling the getUIs method. The first element is guaranteed to be the real UI obtained from the default look and feel.

Constructor Detail

MultiSpinnerUI

public MultiSpinnerUI()
Method Detail

getUIs

public ComponentUI[] getUIs()
Returns the list of UIs associated with this multiplexing UI. This allows processing of the UIs by an application aware of multiplexing UIs on components.

contains

public boolean contains(JComponent a,
                        int b,
                        int c)
Invokes the contains method on each UI handled by this object.

Overrides:
contains in class ComponentUI
Parameters:
a - the component where the x,y location is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
b - the x coordinate of the point
c - the y coordinate of the point
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.contains(int, int), Component.contains(int, int)

update

public void update(Graphics a,
                   JComponent b)
Invokes the update method on each UI handled by this object.

Overrides:
update in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.paint(java.awt.Graphics, javax.swing.JComponent), JComponent.paintComponent(java.awt.Graphics)

createUI

public static ComponentUI createUI(JComponent a)
Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI. Otherwise, just returns the UI object obtained from the default LookAndFeel.

installUI

public void installUI(JComponent a)
Invokes the installUI method on each UI handled by this object.

Overrides:
installUI in class ComponentUI
Parameters:
a - the component where this UI delegate is being installed
See Also:
ComponentUI.uninstallUI(javax.swing.JComponent),
JComponent.setUI(javax.swing.plaf.ComponentUI),
JComponent.updateUI()

uninstallUI

public void uninstallUI(JComponent a)
Invokes the uninstallUI method on each UI handled by this object.

Overrides:
uninstallUI in class ComponentUI
Parameters:
a - the component from which this UI delegate is being removed; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.installUI(javax.swing.JComponent), JComponent.updateUI()

paint

public void paint(Graphics a,
                  JComponent b)
Invokes the paint method on each UI handled by this object.

Overrides:
paint in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.update(java.awt.Graphics, javax.swing.JComponent)

getPreferredSize

public Dimension getPreferredSize(JComponent a)
Invokes the getPreferredSize method on each UI handled by this object.

Overrides:
getPreferredSize in class ComponentUI
Parameters:
a - the component whose preferred size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getPreferredSize(), LayoutManager.preferredLayoutSize(java.awt.Container)

getMinimumSize

public Dimension getMinimumSize(JComponent a)
Invokes the getMinimumSize method on each UI handled by this object.

Overrides:
getMinimumSize in class ComponentUI
Parameters:
a - the component whose minimum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMinimumSize(),
LayoutManager.minimumLayoutSize(java.awt.Container),
ComponentUI.getPreferredSize(javax.swing.JComponent)

getMaximumSize

public Dimension getMaximumSize(JComponent a)
Invokes the getMaximumSize method on each UI handled by this object.

Overrides:
getMaximumSize in class ComponentUI
Parameters:
a - the component whose maximum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMaximumSize(), LayoutManager2.maximumLayoutSize(java.awt.Container)

getAccessibleChildrenCount

public int getAccessibleChildrenCount(JComponent a)
Invokes the getAccessibleChildrenCount method on each UI handled by this object.

Overrides:
getAccessibleChildrenCount in class ComponentUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChild(javax.swing.JComponent, int)

getAccessibleChild

public Accessible getAccessibleChild(JComponent a,
                                     int b)
Invokes the getAccessibleChild method on each UI handled by this object.

Overrides:
getAccessibleChild in class ComponentUI
Parameters:
b - zero-based index of child
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChildrenCount(javax.swing.JComponent)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MultiSplitPaneUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.multi
Class MultiSplitPaneUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.SplitPaneUI
            extended by javax.swing.plaf.multi.MultiSplitPaneUI
public class MultiSplitPaneUI
extends SplitPaneUI

A multiplexing UI used to combine SplitPaneUIs.

This file was automatically generated by AutoMulti.

Field Summary
protected  Vector uis
The vector containing the real UIs.
Constructor Summary
MultiSplitPaneUI()
Method Summary
boolean | contains(JComponent a, int b, int c) Invokes the contains method on each UI handled by this object.
static ComponentUI | createUI(JComponent a) Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI.
void | finishedPaintingChildren(JSplitPane a, Graphics b) Invokes the finishedPaintingChildren method on each UI handled by this object.
Accessible | getAccessibleChild(JComponent a, int b) Invokes the getAccessibleChild method on each UI handled by this object.
int | getAccessibleChildrenCount(JComponent a) Invokes the getAccessibleChildrenCount method on each UI handled by this object.
int | getDividerLocation(JSplitPane a) Invokes the getDividerLocation method on each UI handled by this object.
int | getMaximumDividerLocation(JSplitPane a) Invokes the getMaximumDividerLocation method on each UI handled by this object.
Dimension | getMaximumSize(JComponent a) Invokes the getMaximumSize method on each UI handled by this object.
int | getMinimumDividerLocation(JSplitPane a) Invokes the getMinimumDividerLocation method on each UI handled by this object.
Dimension | getMinimumSize(JComponent a) Invokes the getMinimumSize method on each UI handled by this object.
Dimension | getPreferredSize(JComponent a) Invokes the getPreferredSize method on each UI handled by this object.
ComponentUI[] | getUIs() Returns the list of UIs associated with this multiplexing UI.
void | installUI(JComponent a) Invokes the installUI method on each UI handled by this object.
void | paint(Graphics a, JComponent b) Invokes the paint method on each UI handled by this object.
void | resetToPreferredSizes(JSplitPane a) Invokes the resetToPreferredSizes method on each UI handled by this object.
void | setDividerLocation(JSplitPane a, int b) Invokes the setDividerLocation method on each UI handled by this object.
void | uninstallUI(JComponent a) Invokes the uninstallUI method on each UI handled by this object.
void | update(Graphics a, JComponent b) Invokes the update method on each UI handled by this object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

uis

protected Vector uis
The vector containing the real UIs. This is populated in the call to createUI, and can be obtained by calling the getUIs method. The first element is guaranteed to be the real UI obtained from the default look and feel.

Constructor Detail

MultiSplitPaneUI

public MultiSplitPaneUI()
Method Detail

getUIs

public ComponentUI[] getUIs()
Returns the list of UIs associated with this multiplexing UI. This allows processing of the UIs by an application aware of multiplexing UIs on components.

resetToPreferredSizes

public void resetToPreferredSizes(JSplitPane a)
Invokes the resetToPreferredSizes method on each UI handled by this object.

Specified by:
resetToPreferredSizes in class SplitPaneUI

setDividerLocation

public void setDividerLocation(JSplitPane a,
                               int b)
Invokes the setDividerLocation method on each UI handled by this object.

Specified by:
setDividerLocation in class SplitPaneUI

getDividerLocation

public int getDividerLocation(JSplitPane a)
Invokes the getDividerLocation method on each UI handled by this object.

Specified by:
getDividerLocation in class SplitPaneUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel

getMinimumDividerLocation

public int getMinimumDividerLocation(JSplitPane a)
Invokes the getMinimumDividerLocation method on each UI handled by this object.

Specified by:
getMinimumDividerLocation in class SplitPaneUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel

getMaximumDividerLocation

public int getMaximumDividerLocation(JSplitPane a)
Invokes the getMaximumDividerLocation method on each UI handled by this object.

Specified by:
getMaximumDividerLocation in class SplitPaneUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel

finishedPaintingChildren

public void finishedPaintingChildren(JSplitPane a,
                                     Graphics b)
Invokes the finishedPaintingChildren method on each UI handled by this object.

Specified by:
finishedPaintingChildren in class SplitPaneUI

contains

public boolean contains(JComponent a,
                        int b,
                        int c)
Invokes the contains method on each UI handled by this object.

Overrides:
contains in class ComponentUI
Parameters:
a - the component where the x,y location is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
b - the x coordinate of the point
c - the y coordinate of the point
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.contains(int, int), Component.contains(int, int)

update

public void update(Graphics a,
                   JComponent b)
Invokes the update method on each UI handled by this object.

Overrides:
update in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.paint(java.awt.Graphics, javax.swing.JComponent), JComponent.paintComponent(java.awt.Graphics)

createUI

public static ComponentUI createUI(JComponent a)
Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI. Otherwise, just returns the UI object obtained from the default LookAndFeel.

installUI

public void installUI(JComponent a)
Invokes the installUI method on each UI handled by this object.

Overrides:
installUI in class ComponentUI
Parameters:
a - the component where this UI delegate is being installed
See Also:
ComponentUI.uninstallUI(javax.swing.JComponent),
JComponent.setUI(javax.swing.plaf.ComponentUI),
JComponent.updateUI()

uninstallUI

public void uninstallUI(JComponent a)
Invokes the uninstallUI method on each UI handled by this object.

Overrides:
uninstallUI in class ComponentUI
Parameters:
a - the component from which this UI delegate is being removed; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.installUI(javax.swing.JComponent), JComponent.updateUI()

paint

public void paint(Graphics a,
                  JComponent b)
Invokes the paint method on each UI handled by this object.

Overrides:
paint in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.update(java.awt.Graphics, javax.swing.JComponent)

getPreferredSize

public Dimension getPreferredSize(JComponent a)
Invokes the getPreferredSize method on each UI handled by this object.

Overrides:
getPreferredSize in class ComponentUI
Parameters:
a - the component whose preferred size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getPreferredSize(), LayoutManager.preferredLayoutSize(java.awt.Container)

getMinimumSize

public Dimension getMinimumSize(JComponent a)
Invokes the getMinimumSize method on each UI handled by this object.

Overrides:
getMinimumSize in class ComponentUI
Parameters:
a - the component whose minimum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMinimumSize(),
LayoutManager.minimumLayoutSize(java.awt.Container),
ComponentUI.getPreferredSize(javax.swing.JComponent)

getMaximumSize

public Dimension getMaximumSize(JComponent a)
Invokes the getMaximumSize method on each UI handled by this object.

Overrides:
getMaximumSize in class ComponentUI
Parameters:
a - the component whose maximum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMaximumSize(), LayoutManager2.maximumLayoutSize(java.awt.Container)

getAccessibleChildrenCount

public int getAccessibleChildrenCount(JComponent a)
Invokes the getAccessibleChildrenCount method on each UI handled by this object.

Overrides:
getAccessibleChildrenCount in class ComponentUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChild(javax.swing.JComponent, int)

getAccessibleChild

public Accessible getAccessibleChild(JComponent a,
                                     int b)
Invokes the getAccessibleChild method on each UI handled by this object.

Overrides:
getAccessibleChild in class ComponentUI
Parameters:
b - zero-based index of child
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChildrenCount(javax.swing.JComponent)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MultiTabbedPaneUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.multi
Class MultiTabbedPaneUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.TabbedPaneUI
            extended by javax.swing.plaf.multi.MultiTabbedPaneUI
public class MultiTabbedPaneUI
extends TabbedPaneUI

A multiplexing UI used to combine TabbedPaneUIs.

This file was automatically generated by AutoMulti.

Field Summary
protected  Vector uis
The vector containing the real UIs.
Constructor Summary
MultiTabbedPaneUI()
Method Summary
boolean | contains(JComponent a, int b, int c) Invokes the contains method on each UI handled by this object.
static ComponentUI | createUI(JComponent a) Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI.
Accessible | getAccessibleChild(JComponent a, int b) Invokes the getAccessibleChild method on each UI handled by this object.
int | getAccessibleChildrenCount(JComponent a) Invokes the getAccessibleChildrenCount method on each UI handled by this object.
Dimension | getMaximumSize(JComponent a) Invokes the getMaximumSize method on each UI handled by this object.
Dimension | getMinimumSize(JComponent a) Invokes the getMinimumSize method on each UI handled by this object.
Dimension | getPreferredSize(JComponent a) Invokes the getPreferredSize method on each UI handled by this object.
Rectangle | getTabBounds(JTabbedPane a, int b) Invokes the getTabBounds method on each UI handled by this object.
int | getTabRunCount(JTabbedPane a) Invokes the getTabRunCount method on each UI handled by this object.
ComponentUI[] | getUIs() Returns the list of UIs associated with this multiplexing UI.
void | installUI(JComponent a) Invokes the installUI method on each UI handled by this object.
void | paint(Graphics a, JComponent b) Invokes the paint method on each UI handled by this object.
int | tabForCoordinate(JTabbedPane a, int b, int c) Invokes the tabForCoordinate method on each UI handled by this object.
void | uninstallUI(JComponent a) Invokes the uninstallUI method on each UI handled by this object.
void | update(Graphics a, JComponent b) Invokes the update method on each UI handled by this object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

uis

protected Vector uis
The vector containing the real UIs. This is populated in the call to createUI, and can be obtained by calling the getUIs method. The first element is guaranteed to be the real UI obtained from the default look and feel.

Constructor Detail

MultiTabbedPaneUI

public MultiTabbedPaneUI()
Method Detail

getUIs

public ComponentUI[] getUIs()
Returns the list of UIs associated with this multiplexing UI. This allows processing of the UIs by an application aware of multiplexing UIs on components.

tabForCoordinate

public int tabForCoordinate(JTabbedPane a,
                            int b,
                            int c)
Invokes the tabForCoordinate method on each UI handled by this object.

Specified by:
tabForCoordinate in class TabbedPaneUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel

getTabBounds

public Rectangle getTabBounds(JTabbedPane a,
                              int b)
Invokes the getTabBounds method on each UI handled by this object.

Specified by:
getTabBounds in class TabbedPaneUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel

getTabRunCount

public int getTabRunCount(JTabbedPane a)
Invokes the getTabRunCount method on each UI handled by this object.

Specified by:
getTabRunCount in class TabbedPaneUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel

contains

public boolean contains(JComponent a,
                        int b,
                        int c)
Invokes the contains method on each UI handled by this object.

Overrides:
contains in class ComponentUI
Parameters:
a - the component where the x,y location is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
b - the x coordinate of the point
c - the y coordinate of the point
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.contains(int, int), Component.contains(int, int)

update

public void update(Graphics a,
                   JComponent b)
Invokes the update method on each UI handled by this object.

Overrides:
update in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.paint(java.awt.Graphics, javax.swing.JComponent), JComponent.paintComponent(java.awt.Graphics)

createUI

public static ComponentUI createUI(JComponent a)
Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI. Otherwise, just returns the UI object obtained from the default LookAndFeel.

installUI

public void installUI(JComponent a)
Invokes the installUI method on each UI handled by this object.

Overrides:
installUI in class ComponentUI
Parameters:
a - the component where this UI delegate is being installed
See Also:
ComponentUI.uninstallUI(javax.swing.JComponent),
JComponent.setUI(javax.swing.plaf.ComponentUI),
JComponent.updateUI()

uninstallUI

public void uninstallUI(JComponent a)
Invokes the uninstallUI method on each UI handled by this object.

Overrides:
uninstallUI in class ComponentUI
Parameters:
a - the component from which this UI delegate is being removed; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.installUI(javax.swing.JComponent), JComponent.updateUI()

paint

public void paint(Graphics a,
                  JComponent b)
Invokes the paint method on each UI handled by this object.

Overrides:
paint in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.update(java.awt.Graphics, javax.swing.JComponent)

getPreferredSize

public Dimension getPreferredSize(JComponent a)
Invokes the getPreferredSize method on each UI handled by this object.

Overrides:
getPreferredSize in class ComponentUI
Parameters:
a - the component whose preferred size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getPreferredSize(), LayoutManager.preferredLayoutSize(java.awt.Container)

getMinimumSize

public Dimension getMinimumSize(JComponent a)
Invokes the getMinimumSize method on each UI handled by this object.

Overrides:
getMinimumSize in class ComponentUI
Parameters:
a - the component whose minimum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMinimumSize(),
LayoutManager.minimumLayoutSize(java.awt.Container),
ComponentUI.getPreferredSize(javax.swing.JComponent)

getMaximumSize

public Dimension getMaximumSize(JComponent a)
Invokes the getMaximumSize method on each UI handled by this object.

Overrides:
getMaximumSize in class ComponentUI
Parameters:
a - the component whose maximum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMaximumSize(), LayoutManager2.maximumLayoutSize(java.awt.Container)

getAccessibleChildrenCount

public int getAccessibleChildrenCount(JComponent a)
Invokes the getAccessibleChildrenCount method on each UI handled by this object.

Overrides:
getAccessibleChildrenCount in class ComponentUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChild(javax.swing.JComponent, int)

getAccessibleChild

public Accessible getAccessibleChild(JComponent a,
                                     int b)
Invokes the getAccessibleChild method on each UI handled by this object.

Overrides:
getAccessibleChild in class ComponentUI
Parameters:
b - zero-based index of child
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChildrenCount(javax.swing.JComponent)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MultiTableHeaderUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.multi
Class MultiTableHeaderUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.TableHeaderUI
            extended by javax.swing.plaf.multi.MultiTableHeaderUI
public class MultiTableHeaderUI
extends TableHeaderUI

A multiplexing UI used to combine TableHeaderUIs.

This file was automatically generated by AutoMulti.

Field Summary
protected  Vector uis
The vector containing the real UIs.
Constructor Summary
MultiTableHeaderUI()
Method Summary
boolean | contains(JComponent a, int b, int c) Invokes the contains method on each UI handled by this object.
static ComponentUI | createUI(JComponent a) Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI.
Accessible | getAccessibleChild(JComponent a, int b) Invokes the getAccessibleChild method on each UI handled by this object.
int | getAccessibleChildrenCount(JComponent a) Invokes the getAccessibleChildrenCount method on each UI handled by this object.
Dimension | getMaximumSize(JComponent a) Invokes the getMaximumSize method on each UI handled by this object.
Dimension | getMinimumSize(JComponent a) Invokes the getMinimumSize method on each UI handled by this object.
Dimension | getPreferredSize(JComponent a) Invokes the getPreferredSize method on each UI handled by this object.
ComponentUI[] | getUIs() Returns the list of UIs associated with this multiplexing UI.
void | installUI(JComponent a) Invokes the installUI method on each UI handled by this object.
void | paint(Graphics a, JComponent b) Invokes the paint method on each UI handled by this object.
void | uninstallUI(JComponent a) Invokes the uninstallUI method on each UI handled by this object.
void | update(Graphics a, JComponent b) Invokes the update method on each UI handled by this object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

uis

protected Vector uis
The vector containing the real UIs. This is populated in the call to createUI, and can be obtained by calling the getUIs method. The first element is guaranteed to be the real UI obtained from the default look and feel.

Constructor Detail

MultiTableHeaderUI

public MultiTableHeaderUI()
Method Detail

getUIs

public ComponentUI[] getUIs()
Returns the list of UIs associated with this multiplexing UI. This allows processing of the UIs by an application aware of multiplexing UIs on components.

contains

public boolean contains(JComponent a,
                        int b,
                        int c)
Invokes the contains method on each UI handled by this object.

Overrides:
contains in class ComponentUI
Parameters:
a - the component where the x,y location is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
b - the x coordinate of the point
c - the y coordinate of the point
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.contains(int, int), Component.contains(int, int)

update

public void update(Graphics a,
                   JComponent b)
Invokes the update method on each UI handled by this object.

Overrides:
update in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.paint(java.awt.Graphics, javax.swing.JComponent), JComponent.paintComponent(java.awt.Graphics)

createUI

public static ComponentUI createUI(JComponent a)
Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI. Otherwise, just returns the UI object obtained from the default LookAndFeel.

installUI

public void installUI(JComponent a)
Invokes the installUI method on each UI handled by this object.

Overrides:
installUI in class ComponentUI
Parameters:
a - the component where this UI delegate is being installed
See Also:
ComponentUI.uninstallUI(javax.swing.JComponent),
JComponent.setUI(javax.swing.plaf.ComponentUI),
JComponent.updateUI()

uninstallUI

public void uninstallUI(JComponent a)
Invokes the uninstallUI method on each UI handled by this object.

Overrides:
uninstallUI in class ComponentUI
Parameters:
a - the component from which this UI delegate is being removed; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.installUI(javax.swing.JComponent), JComponent.updateUI()

paint

public void paint(Graphics a,
                  JComponent b)
Invokes the paint method on each UI handled by this object.

Overrides:
paint in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.update(java.awt.Graphics, javax.swing.JComponent)

getPreferredSize

public Dimension getPreferredSize(JComponent a)
Invokes the getPreferredSize method on each UI handled by this object.

Overrides:
getPreferredSize in class ComponentUI
Parameters:
a - the component whose preferred size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getPreferredSize(), LayoutManager.preferredLayoutSize(java.awt.Container)

getMinimumSize

public Dimension getMinimumSize(JComponent a)
Invokes the getMinimumSize method on each UI handled by this object.

Overrides:
getMinimumSize in class ComponentUI
Parameters:
a - the component whose minimum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMinimumSize(),
LayoutManager.minimumLayoutSize(java.awt.Container),
ComponentUI.getPreferredSize(javax.swing.JComponent)

getMaximumSize

public Dimension getMaximumSize(JComponent a)
Invokes the getMaximumSize method on each UI handled by this object.

Overrides:
getMaximumSize in class ComponentUI
Parameters:
a - the component whose maximum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMaximumSize(), LayoutManager2.maximumLayoutSize(java.awt.Container)

getAccessibleChildrenCount

public int getAccessibleChildrenCount(JComponent a)
Invokes the getAccessibleChildrenCount method on each UI handled by this object.

Overrides:
getAccessibleChildrenCount in class ComponentUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChild(javax.swing.JComponent, int)

getAccessibleChild

public Accessible getAccessibleChild(JComponent a,
                                     int b)
Invokes the getAccessibleChild method on each UI handled by this object.

Overrides:
getAccessibleChild in class ComponentUI
Parameters:
b - zero-based index of child
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChildrenCount(javax.swing.JComponent)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MultiTableUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.multi
Class MultiTableUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.TableUI
            extended by javax.swing.plaf.multi.MultiTableUI
public class MultiTableUI
extends TableUI

A multiplexing UI used to combine TableUIs.

This file was automatically generated by AutoMulti.

Field Summary
protected  Vector uis
The vector containing the real UIs.
Constructor Summary
MultiTableUI()
Method Summary
boolean | contains(JComponent a, int b, int c) Invokes the contains method on each UI handled by this object.
static ComponentUI | createUI(JComponent a) Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI.
Accessible | getAccessibleChild(JComponent a, int b) Invokes the getAccessibleChild method on each UI handled by this object.
int | getAccessibleChildrenCount(JComponent a) Invokes the getAccessibleChildrenCount method on each UI handled by this object.
Dimension | getMaximumSize(JComponent a) Invokes the getMaximumSize method on each UI handled by this object.
Dimension | getMinimumSize(JComponent a) Invokes the getMinimumSize method on each UI handled by this object.
Dimension | getPreferredSize(JComponent a) Invokes the getPreferredSize method on each UI handled by this object.
ComponentUI[] | getUIs() Returns the list of UIs associated with this multiplexing UI.
void | installUI(JComponent a) Invokes the installUI method on each UI handled by this object.
void | paint(Graphics a, JComponent b) Invokes the paint method on each UI handled by this object.
void | uninstallUI(JComponent a) Invokes the uninstallUI method on each UI handled by this object.
void | update(Graphics a, JComponent b) Invokes the update method on each UI handled by this object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

uis

protected Vector uis
The vector containing the real UIs. This is populated in the call to createUI, and can be obtained by calling the getUIs method. The first element is guaranteed to be the real UI obtained from the default look and feel.

Constructor Detail

MultiTableUI

public MultiTableUI()
Method Detail

getUIs

public ComponentUI[] getUIs()
Returns the list of UIs associated with this multiplexing UI. This allows processing of the UIs by an application aware of multiplexing UIs on components.

contains

public boolean contains(JComponent a,
                        int b,
                        int c)
Invokes the contains method on each UI handled by this object.

Overrides:
contains in class ComponentUI
Parameters:
a - the component where the x,y location is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
b - the x coordinate of the point
c - the y coordinate of the point
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.contains(int, int), Component.contains(int, int)

update

public void update(Graphics a,
                   JComponent b)
Invokes the update method on each UI handled by this object.

Overrides:
update in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.paint(java.awt.Graphics, javax.swing.JComponent), JComponent.paintComponent(java.awt.Graphics)

createUI

public static ComponentUI createUI(JComponent a)
Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI. Otherwise, just returns the UI object obtained from the default LookAndFeel.

installUI

public void installUI(JComponent a)
Invokes the installUI method on each UI handled by this object.

Overrides:
installUI in class ComponentUI
Parameters:
a - the component where this UI delegate is being installed
See Also:
ComponentUI.uninstallUI(javax.swing.JComponent),
JComponent.setUI(javax.swing.plaf.ComponentUI),
JComponent.updateUI()

uninstallUI

public void uninstallUI(JComponent a)
Invokes the uninstallUI method on each UI handled by this object.

Overrides:
uninstallUI in class ComponentUI
Parameters:
a - the component from which this UI delegate is being removed; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.installUI(javax.swing.JComponent), JComponent.updateUI()

paint

public void paint(Graphics a,
                  JComponent b)
Invokes the paint method on each UI handled by this object.

Overrides:
paint in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.update(java.awt.Graphics, javax.swing.JComponent)

getPreferredSize

public Dimension getPreferredSize(JComponent a)
Invokes the getPreferredSize method on each UI handled by this object.

Overrides:
getPreferredSize in class ComponentUI
Parameters:
a - the component whose preferred size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getPreferredSize(), LayoutManager.preferredLayoutSize(java.awt.Container)

getMinimumSize

public Dimension getMinimumSize(JComponent a)
Invokes the getMinimumSize method on each UI handled by this object.

Overrides:
getMinimumSize in class ComponentUI
Parameters:
a - the component whose minimum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMinimumSize(),
LayoutManager.minimumLayoutSize(java.awt.Container),
ComponentUI.getPreferredSize(javax.swing.JComponent)

getMaximumSize

public Dimension getMaximumSize(JComponent a)
Invokes the getMaximumSize method on each UI handled by this object.

Overrides:
getMaximumSize in class ComponentUI
Parameters:
a - the component whose maximum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMaximumSize(), LayoutManager2.maximumLayoutSize(java.awt.Container)

getAccessibleChildrenCount

public int getAccessibleChildrenCount(JComponent a)
Invokes the getAccessibleChildrenCount method on each UI handled by this object.

Overrides:
getAccessibleChildrenCount in class ComponentUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChild(javax.swing.JComponent, int)

getAccessibleChild

public Accessible getAccessibleChild(JComponent a,
                                     int b)
Invokes the getAccessibleChild method on each UI handled by this object.

Overrides:
getAccessibleChild in class ComponentUI
Parameters:
b - zero-based index of child
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChildrenCount(javax.swing.JComponent)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MultiTextUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.multi
Class MultiTextUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.TextUI
            extended by javax.swing.plaf.multi.MultiTextUI
public class MultiTextUI
extends TextUI

A multiplexing UI used to combine TextUIs.

This file was automatically generated by AutoMulti.

Field Summary
protected  Vector uis
The vector containing the real UIs.
Constructor Summary
MultiTextUI()
Method Summary
boolean | contains(JComponent a, int b, int c) Invokes the contains method on each UI handled by this object.
static ComponentUI | createUI(JComponent a) Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI.
void | damageRange(JTextComponent a, int b, int c) Invokes the damageRange method on each UI handled by this object.
void | damageRange(JTextComponent a, int b, int c, Position.Bias d, Position.Bias e) Invokes the damageRange method on each UI handled by this object.
Accessible | getAccessibleChild(JComponent a, int b) Invokes the getAccessibleChild method on each UI handled by this object.
int | getAccessibleChildrenCount(JComponent a) Invokes the getAccessibleChildrenCount method on each UI handled by this object.
EditorKit | getEditorKit(JTextComponent a) Invokes the getEditorKit method on each UI handled by this object.
Dimension | getMaximumSize(JComponent a) Invokes the getMaximumSize method on each UI handled by this object.
Dimension | getMinimumSize(JComponent a) Invokes the getMinimumSize method on each UI handled by this object.
int | getNextVisualPositionFrom(JTextComponent a, int b, Position.Bias c, int d, Position.Bias[] e) Invokes the getNextVisualPositionFrom method on each UI handled by this object.
Dimension | getPreferredSize(JComponent a) Invokes the getPreferredSize method on each UI handled by this object.
View | getRootView(JTextComponent a) Invokes the getRootView method on each UI handled by this object.
String | getToolTipText(JTextComponent a, Point b) Invokes the getToolTipText method on each UI handled by this object.
ComponentUI[] | getUIs() Returns the list of UIs associated with this multiplexing UI.
void | installUI(JComponent a) Invokes the installUI method on each UI handled by this object.
Rectangle | modelToView(JTextComponent a, int b) Invokes the modelToView method on each UI handled by this object.
Rectangle | modelToView(JTextComponent a, int b, Position.Bias c) Invokes the modelToView method on each UI handled by this object.
void | paint(Graphics a, JComponent b) Invokes the paint method on each UI handled by this object.
void | uninstallUI(JComponent a) Invokes the uninstallUI method on each UI handled by this object.
void | update(Graphics a, JComponent b) Invokes the update method on each UI handled by this object.
int | viewToModel(JTextComponent a, Point b) Invokes the viewToModel method on each UI handled by this object.
int | viewToModel(JTextComponent a, Point b, Position.Bias[] c) Invokes the viewToModel method on each UI handled by this object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

uis

protected Vector uis
The vector containing the real UIs. This is populated in the call to createUI, and can be obtained by calling the getUIs method. The first element is guaranteed to be the real UI obtained from the default look and feel.

Constructor Detail

MultiTextUI

public MultiTextUI()
Method Detail

getUIs

public ComponentUI[] getUIs()
Returns the list of UIs associated with this multiplexing UI. This allows processing of the UIs by an application aware of multiplexing UIs on components.

getToolTipText

public String getToolTipText(JTextComponent a,
                             Point b)
Invokes the getToolTipText method on each UI handled by this object.

Overrides:
getToolTipText in class TextUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JTextComponent.getToolTipText(java.awt.event.MouseEvent)

modelToView

public Rectangle modelToView(JTextComponent a,
                             int b)
                      throws BadLocationException
Invokes the modelToView method on each UI handled by this object.

Specified by:
modelToView in class TextUI
Parameters:
b - the local location in the model to translate >= 0
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
Throws:
BadLocationException - if the given position does not represent a valid location in the associated document

modelToView

public Rectangle modelToView(JTextComponent a,
                             int b,
                             Position.Bias c)
                      throws BadLocationException
Invokes the modelToView method on each UI handled by this object.

Specified by:
modelToView in class TextUI
Parameters:
b - the local location in the model to translate >= 0
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
Throws:
BadLocationException - if the given position does not represent a valid location in the associated document

viewToModel

public int viewToModel(JTextComponent a,
                       Point b)
Invokes the viewToModel method on each UI handled by this object.

Specified by:
viewToModel in class TextUI
Parameters:
b - the location in the view to translate. This should be in the same coordinate system as the mouse events.
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel

viewToModel

public int viewToModel(JTextComponent a,
                       Point b,
                       Position.Bias[] c)
Invokes the viewToModel method on each UI handled by this object.

Specified by:
viewToModel in class TextUI
Parameters:
b - the location in the view to translate. This should be in the same coordinate system as the mouse events.
c - filled in by this method to indicate whether the point given is closer to the previous or the next character in the model
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel

getNextVisualPositionFrom

public int getNextVisualPositionFrom(JTextComponent a,
                                     int b,
                                     Position.Bias c,
                                     int d,
                                     Position.Bias[] e)
                              throws BadLocationException
Invokes the getNextVisualPositionFrom method on each UI handled by this object.

Specified by:
getNextVisualPositionFrom in class TextUI
Parameters:
b - the position to convert >= 0
d - the direction from the current position that can be thought of as the arrow keys typically found on a keyboard. This may be SwingConstants.WEST, SwingConstants.EAST, SwingConstants.NORTH, or SwingConstants.SOUTH.
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
Throws:
BadLocationException

damageRange

public void damageRange(JTextComponent a,
                        int b,
                        int c)
Invokes the damageRange method on each UI handled by this object.

Specified by:
damageRange in class TextUI
Parameters:
b - the beginning of the range >= 0
c - the end of the range >= p0

damageRange

public void damageRange(JTextComponent a,
                        int b,
                        int c,
                        Position.Bias d,
                        Position.Bias e)
Invokes the damageRange method on each UI handled by this object.

Specified by:
damageRange in class TextUI
Parameters:
b - the beginning of the range >= 0
c - the end of the range >= p0

getEditorKit

public EditorKit getEditorKit(JTextComponent a)
Invokes the getEditorKit method on each UI handled by this object.

Specified by:
getEditorKit in class TextUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel

getRootView

public View getRootView(JTextComponent a)
Invokes the getRootView method on each UI handled by this object.

Specified by:
getRootView in class TextUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel

contains

public boolean contains(JComponent a,
                        int b,
                        int c)
Invokes the contains method on each UI handled by this object.

Overrides:
contains in class ComponentUI
Parameters:
a - the component where the x,y location is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
b - the x coordinate of the point
c - the y coordinate of the point
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.contains(int, int), Component.contains(int, int)

update

public void update(Graphics a,
                   JComponent b)
Invokes the update method on each UI handled by this object.

Overrides:
update in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.paint(java.awt.Graphics, javax.swing.JComponent), JComponent.paintComponent(java.awt.Graphics)

createUI

public static ComponentUI createUI(JComponent a)
Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI. Otherwise, just returns the UI object obtained from the default LookAndFeel.

installUI

public void installUI(JComponent a)
Invokes the installUI method on each UI handled by this object.

Overrides:
installUI in class ComponentUI
Parameters:
a - the component where this UI delegate is being installed
See Also:
ComponentUI.uninstallUI(javax.swing.JComponent),
JComponent.setUI(javax.swing.plaf.ComponentUI),
JComponent.updateUI()

uninstallUI

public void uninstallUI(JComponent a)
Invokes the uninstallUI method on each UI handled by this object.

Overrides:
uninstallUI in class ComponentUI
Parameters:
a - the component from which this UI delegate is being removed; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.installUI(javax.swing.JComponent), JComponent.updateUI()

paint

public void paint(Graphics a,
                  JComponent b)
Invokes the paint method on each UI handled by this object.

Overrides:
paint in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.update(java.awt.Graphics, javax.swing.JComponent)

getPreferredSize

public Dimension getPreferredSize(JComponent a)
Invokes the getPreferredSize method on each UI handled by this object.

Overrides:
getPreferredSize in class ComponentUI
Parameters:
a - the component whose preferred size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getPreferredSize(), LayoutManager.preferredLayoutSize(java.awt.Container)

getMinimumSize

public Dimension getMinimumSize(JComponent a)
Invokes the getMinimumSize method on each UI handled by this object.

Overrides:
getMinimumSize in class ComponentUI
Parameters:
a - the component whose minimum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMinimumSize(),
LayoutManager.minimumLayoutSize(java.awt.Container),
ComponentUI.getPreferredSize(javax.swing.JComponent)

getMaximumSize

public Dimension getMaximumSize(JComponent a)
Invokes the getMaximumSize method on each UI handled by this object.

Overrides:
getMaximumSize in class ComponentUI
Parameters:
a - the component whose maximum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMaximumSize(), LayoutManager2.maximumLayoutSize(java.awt.Container)

getAccessibleChildrenCount

public int getAccessibleChildrenCount(JComponent a)
Invokes the getAccessibleChildrenCount method on each UI handled by this object.

Overrides:
getAccessibleChildrenCount in class ComponentUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChild(javax.swing.JComponent, int)

getAccessibleChild

public Accessible getAccessibleChild(JComponent a,
                                     int b)
Invokes the getAccessibleChild method on each UI handled by this object.

Overrides:
getAccessibleChild in class ComponentUI
Parameters:
b - zero-based index of child
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChildrenCount(javax.swing.JComponent)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MultiToolBarUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.multi
Class MultiToolBarUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.ToolBarUI
            extended by javax.swing.plaf.multi.MultiToolBarUI
public class MultiToolBarUI
extends ToolBarUI

A multiplexing UI used to combine ToolBarUIs.

This file was automatically generated by AutoMulti.

Field Summary
protected  Vector uis
The vector containing the real UIs.
Constructor Summary
MultiToolBarUI()
Method Summary
boolean | contains(JComponent a, int b, int c) Invokes the contains method on each UI handled by this object.
static ComponentUI | createUI(JComponent a) Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI.
Accessible | getAccessibleChild(JComponent a, int b) Invokes the getAccessibleChild method on each UI handled by this object.
int | getAccessibleChildrenCount(JComponent a) Invokes the getAccessibleChildrenCount method on each UI handled by this object.
Dimension | getMaximumSize(JComponent a) Invokes the getMaximumSize method on each UI handled by this object.
Dimension | getMinimumSize(JComponent a) Invokes the getMinimumSize method on each UI handled by this object.
Dimension | getPreferredSize(JComponent a) Invokes the getPreferredSize method on each UI handled by this object.
ComponentUI[] | getUIs() Returns the list of UIs associated with this multiplexing UI.
void | installUI(JComponent a) Invokes the installUI method on each UI handled by this object.
void | paint(Graphics a, JComponent b) Invokes the paint method on each UI handled by this object.
void | uninstallUI(JComponent a) Invokes the uninstallUI method on each UI handled by this object.
void | update(Graphics a, JComponent b) Invokes the update method on each UI handled by this object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

uis

protected Vector uis
The vector containing the real UIs. This is populated in the call to createUI, and can be obtained by calling the getUIs method. The first element is guaranteed to be the real UI obtained from the default look and feel.

Constructor Detail

MultiToolBarUI

public MultiToolBarUI()
Method Detail

getUIs

public ComponentUI[] getUIs()
Returns the list of UIs associated with this multiplexing UI. This allows processing of the UIs by an application aware of multiplexing UIs on components.

contains

public boolean contains(JComponent a,
                        int b,
                        int c)
Invokes the contains method on each UI handled by this object.

Overrides:
contains in class ComponentUI
Parameters:
a - the component where the x,y location is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
b - the x coordinate of the point
c - the y coordinate of the point
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.contains(int, int), Component.contains(int, int)

update

public void update(Graphics a,
                   JComponent b)
Invokes the update method on each UI handled by this object.

Overrides:
update in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.paint(java.awt.Graphics, javax.swing.JComponent), JComponent.paintComponent(java.awt.Graphics)

createUI

public static ComponentUI createUI(JComponent a)
Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI. Otherwise, just returns the UI object obtained from the default LookAndFeel.

installUI

public void installUI(JComponent a)
Invokes the installUI method on each UI handled by this object.

Overrides:
installUI in class ComponentUI
Parameters:
a - the component where this UI delegate is being installed
See Also:
ComponentUI.uninstallUI(javax.swing.JComponent),
JComponent.setUI(javax.swing.plaf.ComponentUI),
JComponent.updateUI()

uninstallUI

public void uninstallUI(JComponent a)
Invokes the uninstallUI method on each UI handled by this object.

Overrides:
uninstallUI in class ComponentUI
Parameters:
a - the component from which this UI delegate is being removed; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.installUI(javax.swing.JComponent), JComponent.updateUI()

paint

public void paint(Graphics a,
                  JComponent b)
Invokes the paint method on each UI handled by this object.

Overrides:
paint in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.update(java.awt.Graphics, javax.swing.JComponent)

getPreferredSize

public Dimension getPreferredSize(JComponent a)
Invokes the getPreferredSize method on each UI handled by this object.

Overrides:
getPreferredSize in class ComponentUI
Parameters:
a - the component whose preferred size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getPreferredSize(), LayoutManager.preferredLayoutSize(java.awt.Container)

getMinimumSize

public Dimension getMinimumSize(JComponent a)
Invokes the getMinimumSize method on each UI handled by this object.

Overrides:
getMinimumSize in class ComponentUI
Parameters:
a - the component whose minimum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMinimumSize(),
LayoutManager.minimumLayoutSize(java.awt.Container),
ComponentUI.getPreferredSize(javax.swing.JComponent)

getMaximumSize

public Dimension getMaximumSize(JComponent a)
Invokes the getMaximumSize method on each UI handled by this object.

Overrides:
getMaximumSize in class ComponentUI
Parameters:
a - the component whose maximum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMaximumSize(), LayoutManager2.maximumLayoutSize(java.awt.Container)

getAccessibleChildrenCount

public int getAccessibleChildrenCount(JComponent a)
Invokes the getAccessibleChildrenCount method on each UI handled by this object.

Overrides:
getAccessibleChildrenCount in class ComponentUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChild(javax.swing.JComponent, int)

getAccessibleChild

public Accessible getAccessibleChild(JComponent a,
                                     int b)
Invokes the getAccessibleChild method on each UI handled by this object.

Overrides:
getAccessibleChild in class ComponentUI
Parameters:
b - zero-based index of child
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChildrenCount(javax.swing.JComponent)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MultiToolTipUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.multi
Class MultiToolTipUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.ToolTipUI
            extended by javax.swing.plaf.multi.MultiToolTipUI
public class MultiToolTipUI
extends ToolTipUI

A multiplexing UI used to combine ToolTipUIs.

This file was automatically generated by AutoMulti.

Field Summary
protected  Vector uis
The vector containing the real UIs.
Constructor Summary
MultiToolTipUI()
Method Summary
boolean | contains(JComponent a, int b, int c) Invokes the contains method on each UI handled by this object.
static ComponentUI | createUI(JComponent a) Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI.
Accessible | getAccessibleChild(JComponent a, int b) Invokes the getAccessibleChild method on each UI handled by this object.
int | getAccessibleChildrenCount(JComponent a) Invokes the getAccessibleChildrenCount method on each UI handled by this object.
Dimension | getMaximumSize(JComponent a) Invokes the getMaximumSize method on each UI handled by this object.
Dimension | getMinimumSize(JComponent a) Invokes the getMinimumSize method on each UI handled by this object.
Dimension | getPreferredSize(JComponent a) Invokes the getPreferredSize method on each UI handled by this object.
ComponentUI[] | getUIs() Returns the list of UIs associated with this multiplexing UI.
void | installUI(JComponent a) Invokes the installUI method on each UI handled by this object.
void | paint(Graphics a, JComponent b) Invokes the paint method on each UI handled by this object.
void | uninstallUI(JComponent a) Invokes the uninstallUI method on each UI handled by this object.
void | update(Graphics a, JComponent b) Invokes the update method on each UI handled by this object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

uis

protected Vector uis
The vector containing the real UIs. This is populated in the call to createUI, and can be obtained by calling the getUIs method. The first element is guaranteed to be the real UI obtained from the default look and feel.

Constructor Detail

MultiToolTipUI

public MultiToolTipUI()
Method Detail

getUIs

public ComponentUI[] getUIs()
Returns the list of UIs associated with this multiplexing UI. This allows processing of the UIs by an application aware of multiplexing UIs on components.

contains

public boolean contains(JComponent a,
                        int b,
                        int c)
Invokes the contains method on each UI handled by this object.

Overrides:
contains in class ComponentUI
Parameters:
a - the component where the x,y location is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
b - the x coordinate of the point
c - the y coordinate of the point
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.contains(int, int), Component.contains(int, int)

update

public void update(Graphics a,
                   JComponent b)
Invokes the update method on each UI handled by this object.

Overrides:
update in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.paint(java.awt.Graphics, javax.swing.JComponent), JComponent.paintComponent(java.awt.Graphics)

createUI

public static ComponentUI createUI(JComponent a)
Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI. Otherwise, just returns the UI object obtained from the default LookAndFeel.

installUI

public void installUI(JComponent a)
Invokes the installUI method on each UI handled by this object.

Overrides:
installUI in class ComponentUI
Parameters:
a - the component where this UI delegate is being installed
See Also:
ComponentUI.uninstallUI(javax.swing.JComponent),
JComponent.setUI(javax.swing.plaf.ComponentUI),
JComponent.updateUI()

uninstallUI

public void uninstallUI(JComponent a)
Invokes the uninstallUI method on each UI handled by this object.

Overrides:
uninstallUI in class ComponentUI
Parameters:
a - the component from which this UI delegate is being removed; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.installUI(javax.swing.JComponent), JComponent.updateUI()

paint

public void paint(Graphics a,
                  JComponent b)
Invokes the paint method on each UI handled by this object.

Overrides:
paint in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.update(java.awt.Graphics, javax.swing.JComponent)

getPreferredSize

public Dimension getPreferredSize(JComponent a)
Invokes the getPreferredSize method on each UI handled by this object.

Overrides:
getPreferredSize in class ComponentUI
Parameters:
a - the component whose preferred size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getPreferredSize(), LayoutManager.preferredLayoutSize(java.awt.Container)

getMinimumSize

public Dimension getMinimumSize(JComponent a)
Invokes the getMinimumSize method on each UI handled by this object.

Overrides:
getMinimumSize in class ComponentUI
Parameters:
a - the component whose minimum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMinimumSize(),
LayoutManager.minimumLayoutSize(java.awt.Container),
ComponentUI.getPreferredSize(javax.swing.JComponent)

getMaximumSize

public Dimension getMaximumSize(JComponent a)
Invokes the getMaximumSize method on each UI handled by this object.

Overrides:
getMaximumSize in class ComponentUI
Parameters:
a - the component whose maximum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMaximumSize(), LayoutManager2.maximumLayoutSize(java.awt.Container)

getAccessibleChildrenCount

public int getAccessibleChildrenCount(JComponent a)
Invokes the getAccessibleChildrenCount method on each UI handled by this object.

Overrides:
getAccessibleChildrenCount in class ComponentUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChild(javax.swing.JComponent, int)

getAccessibleChild

public Accessible getAccessibleChild(JComponent a,
                                     int b)
Invokes the getAccessibleChild method on each UI handled by this object.

Overrides:
getAccessibleChild in class ComponentUI
Parameters:
b - zero-based index of child
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChildrenCount(javax.swing.JComponent)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MultiTreeUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.multi
Class MultiTreeUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.TreeUI
            extended by javax.swing.plaf.multi.MultiTreeUI
public class MultiTreeUI
extends TreeUI

A multiplexing UI used to combine TreeUIs.

This file was automatically generated by AutoMulti.

Field Summary
protected  Vector uis
The vector containing the real UIs.
Constructor Summary
MultiTreeUI()
Method Summary
void | cancelEditing(JTree a) Invokes the cancelEditing method on each UI handled by this object.
boolean | contains(JComponent a, int b, int c) Invokes the contains method on each UI handled by this object.
static ComponentUI | createUI(JComponent a) Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI.
Accessible | getAccessibleChild(JComponent a, int b) Invokes the getAccessibleChild method on each UI handled by this object.
int | getAccessibleChildrenCount(JComponent a) Invokes the getAccessibleChildrenCount method on each UI handled by this object.
TreePath | getClosestPathForLocation(JTree a, int b, int c) Invokes the getClosestPathForLocation method on each UI handled by this object.
TreePath | getEditingPath(JTree a) Invokes the getEditingPath method on each UI handled by this object.
Dimension | getMaximumSize(JComponent a) Invokes the getMaximumSize method on each UI handled by this object.
Dimension | getMinimumSize(JComponent a) Invokes the getMinimumSize method on each UI handled by this object.
Rectangle | getPathBounds(JTree a, TreePath b) Invokes the getPathBounds method on each UI handled by this object.
TreePath | getPathForRow(JTree a, int b) Invokes the getPathForRow method on each UI handled by this object.
Dimension | getPreferredSize(JComponent a) Invokes the getPreferredSize method on each UI handled by this object.
int | getRowCount(JTree a) Invokes the getRowCount method on each UI handled by this object.
int | getRowForPath(JTree a, TreePath b) Invokes the getRowForPath method on each UI handled by this object.
ComponentUI[] | getUIs() Returns the list of UIs associated with this multiplexing UI.
void | installUI(JComponent a) Invokes the installUI method on each UI handled by this object.
boolean | isEditing(JTree a) Invokes the isEditing method on each UI handled by this object.
void | paint(Graphics a, JComponent b) Invokes the paint method on each UI handled by this object.
void | startEditingAtPath(JTree a, TreePath b) Invokes the startEditingAtPath method on each UI handled by this object.
boolean | stopEditing(JTree a) Invokes the stopEditing method on each UI handled by this object.
void | uninstallUI(JComponent a) Invokes the uninstallUI method on each UI handled by this object.
void | update(Graphics a, JComponent b) Invokes the update method on each UI handled by this object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

uis

protected Vector uis
The vector containing the real UIs. This is populated in the call to createUI, and can be obtained by calling the getUIs method. The first element is guaranteed to be the real UI obtained from the default look and feel.

Constructor Detail

MultiTreeUI

public MultiTreeUI()
Method Detail

getUIs

public ComponentUI[] getUIs()
Returns the list of UIs associated with this multiplexing UI. This allows processing of the UIs by an application aware of multiplexing UIs on components.

getPathBounds

public Rectangle getPathBounds(JTree a,
                               TreePath b)
Invokes the getPathBounds method on each UI handled by this object.

Specified by:
getPathBounds in class TreeUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel

getPathForRow

public TreePath getPathForRow(JTree a,
                              int b)
Invokes the getPathForRow method on each UI handled by this object.

Specified by:
getPathForRow in class TreeUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel

getRowForPath

public int getRowForPath(JTree a,
                         TreePath b)
Invokes the getRowForPath method on each UI handled by this object.

Specified by:
getRowForPath in class TreeUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel

getRowCount

public int getRowCount(JTree a)
Invokes the getRowCount method on each UI handled by this object.

Specified by:
getRowCount in class TreeUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel

getClosestPathForLocation

public TreePath getClosestPathForLocation(JTree a,
                                          int b,
                                          int c)
Invokes the getClosestPathForLocation method on each UI handled by this object.

Specified by:
getClosestPathForLocation in class TreeUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel

isEditing

public boolean isEditing(JTree a)
Invokes the isEditing method on each UI handled by this object.

Specified by:
isEditing in class TreeUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel

stopEditing

public boolean stopEditing(JTree a)
Invokes the stopEditing method on each UI handled by this object.

Specified by:
stopEditing in class TreeUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel

cancelEditing

public void cancelEditing(JTree a)
Invokes the cancelEditing method on each UI handled by this object.

Specified by:
cancelEditing in class TreeUI

startEditingAtPath

public void startEditingAtPath(JTree a,
                               TreePath b)
Invokes the startEditingAtPath method on each UI handled by this object.

Specified by:
startEditingAtPath in class TreeUI

getEditingPath

public TreePath getEditingPath(JTree a)
Invokes the getEditingPath method on each UI handled by this object.

Specified by:
getEditingPath in class TreeUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel

contains

public boolean contains(JComponent a,
                        int b,
                        int c)
Invokes the contains method on each UI handled by this object.

Overrides:
contains in class ComponentUI
Parameters:
a - the component where the x,y location is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
b - the x coordinate of the point
c - the y coordinate of the point
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.contains(int, int), Component.contains(int, int)

update

public void update(Graphics a,
                   JComponent b)
Invokes the update method on each UI handled by this object.

Overrides:
update in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.paint(java.awt.Graphics, javax.swing.JComponent), JComponent.paintComponent(java.awt.Graphics)

createUI

public static ComponentUI createUI(JComponent a)
Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI. Otherwise, just returns the UI object obtained from the default LookAndFeel.

installUI

public void installUI(JComponent a)
Invokes the installUI method on each UI handled by this object.

Overrides:
installUI in class ComponentUI
Parameters:
a - the component where this UI delegate is being installed
See Also:
ComponentUI.uninstallUI(javax.swing.JComponent),
JComponent.setUI(javax.swing.plaf.ComponentUI),
JComponent.updateUI()

uninstallUI

public void uninstallUI(JComponent a)
Invokes the uninstallUI method on each UI handled by this object.

Overrides:
uninstallUI in class ComponentUI
Parameters:
a - the component from which this UI delegate is being removed; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.installUI(javax.swing.JComponent), JComponent.updateUI()

paint

public void paint(Graphics a,
                  JComponent b)
Invokes the paint method on each UI handled by this object.

Overrides:
paint in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.update(java.awt.Graphics, javax.swing.JComponent)

getPreferredSize

public Dimension getPreferredSize(JComponent a)
Invokes the getPreferredSize method on each UI handled by this object.

Overrides:
getPreferredSize in class ComponentUI
Parameters:
a - the component whose preferred size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getPreferredSize(), LayoutManager.preferredLayoutSize(java.awt.Container)

getMinimumSize

public Dimension getMinimumSize(JComponent a)
Invokes the getMinimumSize method on each UI handled by this object.

Overrides:
getMinimumSize in class ComponentUI
Parameters:
a - the component whose minimum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMinimumSize(),
LayoutManager.minimumLayoutSize(java.awt.Container),
ComponentUI.getPreferredSize(javax.swing.JComponent)

getMaximumSize

public Dimension getMaximumSize(JComponent a)
Invokes the getMaximumSize method on each UI handled by this object.

Overrides:
getMaximumSize in class ComponentUI
Parameters:
a - the component whose maximum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMaximumSize(), LayoutManager2.maximumLayoutSize(java.awt.Container)

getAccessibleChildrenCount

public int getAccessibleChildrenCount(JComponent a)
Invokes the getAccessibleChildrenCount method on each UI handled by this object.

Overrides:
getAccessibleChildrenCount in class ComponentUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChild(javax.swing.JComponent, int)

getAccessibleChild

public Accessible getAccessibleChild(JComponent a,
                                     int b)
Invokes the getAccessibleChild method on each UI handled by this object.

Overrides:
getAccessibleChild in class ComponentUI
Parameters:
b - zero-based index of child
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChildrenCount(javax.swing.JComponent)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MultiViewportUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.swing.plaf.multi
Class MultiViewportUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.ViewportUI
            extended by javax.swing.plaf.multi.MultiViewportUI
public class MultiViewportUI
extends ViewportUI

A multiplexing UI used to combine ViewportUIs.

This file was automatically generated by AutoMulti.

Field Summary
protected  Vector uis
The vector containing the real UIs.
Constructor Summary
MultiViewportUI()
Method Summary
boolean | contains(JComponent a, int b, int c) Invokes the contains method on each UI handled by this object.
static ComponentUI | createUI(JComponent a) Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI.
Accessible | getAccessibleChild(JComponent a, int b) Invokes the getAccessibleChild method on each UI handled by this object.
int | getAccessibleChildrenCount(JComponent a) Invokes the getAccessibleChildrenCount method on each UI handled by this object.
Dimension | getMaximumSize(JComponent a) Invokes the getMaximumSize method on each UI handled by this object.
Dimension | getMinimumSize(JComponent a) Invokes the getMinimumSize method on each UI handled by this object.
Dimension | getPreferredSize(JComponent a) Invokes the getPreferredSize method on each UI handled by this object.
ComponentUI[] | getUIs() Returns the list of UIs associated with this multiplexing UI.
void | installUI(JComponent a) Invokes the installUI method on each UI handled by this object.
void | paint(Graphics a, JComponent b) Invokes the paint method on each UI handled by this object.
void | uninstallUI(JComponent a) Invokes the uninstallUI method on each UI handled by this object.
void | update(Graphics a, JComponent b) Invokes the update method on each UI handled by this object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

uis

protected Vector uis
The vector containing the real UIs. This is populated in the call to createUI, and can be obtained by calling the getUIs method. The first element is guaranteed to be the real UI obtained from the default look and feel.

Constructor Detail

MultiViewportUI

public MultiViewportUI()
Method Detail

getUIs

public ComponentUI[] getUIs()
Returns the list of UIs associated with this multiplexing UI. This allows processing of the UIs by an application aware of multiplexing UIs on components.

contains

public boolean contains(JComponent a,
                        int b,
                        int c)
Invokes the contains method on each UI handled by this object.

Overrides:
contains in class ComponentUI
Parameters:
a - the component where the x,y location is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
b - the x coordinate of the point
c - the y coordinate of the point
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.contains(int, int), Component.contains(int, int)

update

public void update(Graphics a,
                   JComponent b)
Invokes the update method on each UI handled by this object.

Overrides:
update in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.paint(java.awt.Graphics, javax.swing.JComponent), JComponent.paintComponent(java.awt.Graphics)

createUI

public static ComponentUI createUI(JComponent a)
Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI. Otherwise, just returns the UI object obtained from the default LookAndFeel.

installUI

public void installUI(JComponent a)
Invokes the installUI method on each UI handled by this object.

Overrides:
installUI in class ComponentUI
Parameters:
a - the component where this UI delegate is being installed
See Also:
ComponentUI.uninstallUI(javax.swing.JComponent),
JComponent.setUI(javax.swing.plaf.ComponentUI),
JComponent.updateUI()

uninstallUI

public void uninstallUI(JComponent a)
Invokes the uninstallUI method on each UI handled by this object.

Overrides:
uninstallUI in class ComponentUI
Parameters:
a - the component from which this UI delegate is being removed; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.installUI(javax.swing.JComponent), JComponent.updateUI()

paint

public void paint(Graphics a,
                  JComponent b)
Invokes the paint method on each UI handled by this object.

Overrides:
paint in class ComponentUI
Parameters:
a - the Graphics context in which to paint
b - the component being painted; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
See Also:
ComponentUI.update(java.awt.Graphics, javax.swing.JComponent)

getPreferredSize

public Dimension getPreferredSize(JComponent a)
Invokes the getPreferredSize method on each UI handled by this object.

Overrides:
getPreferredSize in class ComponentUI
Parameters:
a - the component whose preferred size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getPreferredSize(), LayoutManager.preferredLayoutSize(java.awt.Container)

getMinimumSize

public Dimension getMinimumSize(JComponent a)
Invokes the getMinimumSize method on each UI handled by this object.

Overrides:
getMinimumSize in class ComponentUI
Parameters:
a - the component whose minimum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMinimumSize(),
LayoutManager.minimumLayoutSize(java.awt.Container),
ComponentUI.getPreferredSize(javax.swing.JComponent)

getMaximumSize

public Dimension getMaximumSize(JComponent a)
Invokes the getMaximumSize method on each UI handled by this object.

Overrides:
getMaximumSize in class ComponentUI
Parameters:
a - the component whose maximum size is being queried; this argument is often ignored, but might be used if the UI object is stateless and shared by multiple components
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
JComponent.getMaximumSize(), LayoutManager2.maximumLayoutSize(java.awt.Container)

getAccessibleChildrenCount

public int getAccessibleChildrenCount(JComponent a)
Invokes the getAccessibleChildrenCount method on each UI handled by this object.

Overrides:
getAccessibleChildrenCount in class ComponentUI
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChild(javax.swing.JComponent, int)

getAccessibleChild

public Accessible getAccessibleChild(JComponent a,
                                     int b)
Invokes the getAccessibleChild method on each UI handled by this object.

Overrides:
getAccessibleChild in class ComponentUI
Parameters:
b - zero-based index of child
Returns:
the value obtained from the first UI, which is the UI obtained from the default LookAndFeel
See Also:
ComponentUI.getAccessibleChildrenCount(javax.swing.JComponent)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


javax.swing.plaf.multi (Java 2 Platform SE v1.4.2)

 javax.swing.plaf.multi
Classes
MultiButtonUI
MultiColorChooserUI
MultiComboBoxUI
MultiDesktopIconUI
MultiDesktopPaneUI
MultiFileChooserUI
MultiInternalFrameUI
MultiLabelUI
MultiListUI
MultiLookAndFeel
MultiMenuBarUI
MultiMenuItemUI
MultiOptionPaneUI
MultiPanelUI
MultiPopupMenuUI
MultiProgressBarUI
MultiRootPaneUI
MultiScrollBarUI
MultiScrollPaneUI
MultiSeparatorUI
MultiSliderUI
MultiSpinnerUI
MultiSplitPaneUI
MultiTabbedPaneUI
MultiTableHeaderUI
MultiTableUI
MultiTextUI
MultiToolBarUI
MultiToolTipUI
MultiTreeUI
MultiViewportUI


javax.swing.plaf.multi (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package javax.swing.plaf.multi

Provides user interface objects that combine two or more look and feels.

See:
Description

Class Summary
MultiButtonUI | A multiplexing UI used to combine ButtonUIs.
MultiColorChooserUI | A multiplexing UI used to combine ColorChooserUIs.
MultiComboBoxUI | A multiplexing UI used to combine ComboBoxUIs.
MultiDesktopIconUI | A multiplexing UI used to combine DesktopIconUIs.
MultiDesktopPaneUI | A multiplexing UI used to combine DesktopPaneUIs.
MultiFileChooserUI | A multiplexing UI used to combine FileChooserUIs.
MultiInternalFrameUI | A multiplexing UI used to combine InternalFrameUIs.
MultiLabelUI | A multiplexing UI used to combine LabelUIs.
MultiListUI | A multiplexing UI used to combine ListUIs.
MultiLookAndFeel | A multiplexing look and feel that allows more than one UI to be associated with a component at the same time.
MultiMenuBarUI | A multiplexing UI used to combine MenuBarUIs.
MultiMenuItemUI | A multiplexing UI used to combine MenuItemUIs.
MultiOptionPaneUI | A multiplexing UI used to combine OptionPaneUIs.
MultiPanelUI | A multiplexing UI used to combine PanelUIs.
MultiPopupMenuUI | A multiplexing UI used to combine PopupMenuUIs.
MultiProgressBarUI | A multiplexing UI used to combine ProgressBarUIs.
MultiRootPaneUI | A multiplexing UI used to combine RootPaneUIs.
MultiScrollBarUI | A multiplexing UI used to combine ScrollBarUIs.
MultiScrollPaneUI | A multiplexing UI used to combine ScrollPaneUIs.
MultiSeparatorUI | A multiplexing UI used to combine SeparatorUIs.
MultiSliderUI | A multiplexing UI used to combine SliderUIs.
MultiSpinnerUI | A multiplexing UI used to combine SpinnerUIs.
MultiSplitPaneUI | A multiplexing UI used to combine SplitPaneUIs.
MultiTabbedPaneUI | A multiplexing UI used to combine TabbedPaneUIs.
MultiTableHeaderUI | A multiplexing UI used to combine TableHeaderUIs.
MultiTableUI | A multiplexing UI used to combine TableUIs.
MultiTextUI | A multiplexing UI used to combine TextUIs.
MultiToolBarUI | A multiplexing UI used to combine ToolBarUIs.
MultiToolTipUI | A multiplexing UI used to combine ToolTipUIs.
MultiTreeUI | A multiplexing UI used to combine TreeUIs.
MultiViewportUI | A multiplexing UI used to combine ViewportUIs.

Package javax.swing.plaf.multi Description

Provides user interface objects that combine two or more look and feels. When a component asks for its UI, this look and feel returns a multiplexing UI that handles all communications with both the default look and feel and one or more auxiliary look and feels. For example, if a user combines an auxiliary audio look and feel with the Motif look and feel, the JButton.getUI method would return an instance of MultiButtonUI, which would handle both a MotifButtonUI and an AudioButtonUI.

For more information, see Using the Multiplexing Look and Feel.

Note: Most of the Swing API is not thread safe. For details, see Threads and Swing, a section in The Java Tutorial.

Since:
1.2
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


javax.swing.plaf.multi Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package javax.swing.plaf.multi

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class javax.swing.plaf.ComponentUI
      • class javax.swing.plaf.ButtonUI
        • class javax.swing.plaf.MenuItemUI
          • class javax.swing.plaf.multi.MultiMenuItemUI
        • class javax.swing.plaf.multi.MultiButtonUI
      • class javax.swing.plaf.ColorChooserUI
        • class javax.swing.plaf.multi.MultiColorChooserUI
      • class javax.swing.plaf.ComboBoxUI
        • class javax.swing.plaf.multi.MultiComboBoxUI
      • class javax.swing.plaf.DesktopIconUI
        • class javax.swing.plaf.multi.MultiDesktopIconUI
      • class javax.swing.plaf.DesktopPaneUI
        • class javax.swing.plaf.multi.MultiDesktopPaneUI
      • class javax.swing.plaf.FileChooserUI
        • class javax.swing.plaf.multi.MultiFileChooserUI
      • class javax.swing.plaf.InternalFrameUI
        • class javax.swing.plaf.multi.MultiInternalFrameUI
      • class javax.swing.plaf.LabelUI
        • class javax.swing.plaf.multi.MultiLabelUI
      • class javax.swing.plaf.ListUI
        • class javax.swing.plaf.multi.MultiListUI
      • class javax.swing.plaf.MenuBarUI
        • class javax.swing.plaf.multi.MultiMenuBarUI
      • class javax.swing.plaf.OptionPaneUI
        • class javax.swing.plaf.multi.MultiOptionPaneUI
      • class javax.swing.plaf.PanelUI
        • class javax.swing.plaf.multi.MultiPanelUI
      • class javax.swing.plaf.PopupMenuUI
        • class javax.swing.plaf.multi.MultiPopupMenuUI
      • class javax.swing.plaf.ProgressBarUI
        • class javax.swing.plaf.multi.MultiProgressBarUI
      • class javax.swing.plaf.RootPaneUI
        • class javax.swing.plaf.multi.MultiRootPaneUI
      • class javax.swing.plaf.ScrollBarUI
        • class javax.swing.plaf.multi.MultiScrollBarUI
      • class javax.swing.plaf.ScrollPaneUI
        • class javax.swing.plaf.multi.MultiScrollPaneUI
      • class javax.swing.plaf.SeparatorUI
        • class javax.swing.plaf.multi.MultiSeparatorUI
      • class javax.swing.plaf.SliderUI
        • class javax.swing.plaf.multi.MultiSliderUI
      • class javax.swing.plaf.SpinnerUI
        • class javax.swing.plaf.multi.MultiSpinnerUI
      • class javax.swing.plaf.SplitPaneUI
        • class javax.swing.plaf.multi.MultiSplitPaneUI
      • class javax.swing.plaf.TabbedPaneUI
        • class javax.swing.plaf.multi.MultiTabbedPaneUI
      • class javax.swing.plaf.TableHeaderUI
        • class javax.swing.plaf.multi.MultiTableHeaderUI
      • class javax.swing.plaf.TableUI
        • class javax.swing.plaf.multi.MultiTableUI
      • class javax.swing.plaf.TextUI
        • class javax.swing.plaf.multi.MultiTextUI
      • class javax.swing.plaf.ToolBarUI
        • class javax.swing.plaf.multi.MultiToolBarUI
      • class javax.swing.plaf.ToolTipUI
        • class javax.swing.plaf.multi.MultiToolTipUI
      • class javax.swing.plaf.TreeUI
        • class javax.swing.plaf.multi.MultiTreeUI
      • class javax.swing.plaf.ViewportUI
        • class javax.swing.plaf.multi.MultiViewportUI
    • class javax.swing.LookAndFeel
      • class javax.swing.plaf.multi.MultiLookAndFeel
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package javax.swing.plaf.multi (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
javax.swing.plaf.multi

No usage of javax.swing.plaf.multi

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.multi.MultiButtonUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.multi.MultiButtonUI

No usage of javax.swing.plaf.multi.MultiButtonUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.multi.MultiColorChooserUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.multi.MultiColorChooserUI

No usage of javax.swing.plaf.multi.MultiColorChooserUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.multi.MultiComboBoxUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.multi.MultiComboBoxUI

No usage of javax.swing.plaf.multi.MultiComboBoxUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.multi.MultiDesktopIconUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.multi.MultiDesktopIconUI

No usage of javax.swing.plaf.multi.MultiDesktopIconUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.multi.MultiDesktopPaneUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.multi.MultiDesktopPaneUI

No usage of javax.swing.plaf.multi.MultiDesktopPaneUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.multi.MultiFileChooserUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.multi.MultiFileChooserUI

No usage of javax.swing.plaf.multi.MultiFileChooserUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.multi.MultiInternalFrameUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.multi.MultiInternalFrameUI

No usage of javax.swing.plaf.multi.MultiInternalFrameUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.multi.MultiLabelUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.multi.MultiLabelUI

No usage of javax.swing.plaf.multi.MultiLabelUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.multi.MultiListUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.multi.MultiListUI

No usage of javax.swing.plaf.multi.MultiListUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.multi.MultiLookAndFeel (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.multi.MultiLookAndFeel

No usage of javax.swing.plaf.multi.MultiLookAndFeel

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.multi.MultiMenuBarUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.multi.MultiMenuBarUI

No usage of javax.swing.plaf.multi.MultiMenuBarUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.multi.MultiMenuItemUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.multi.MultiMenuItemUI

No usage of javax.swing.plaf.multi.MultiMenuItemUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.multi.MultiOptionPaneUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.multi.MultiOptionPaneUI

No usage of javax.swing.plaf.multi.MultiOptionPaneUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.multi.MultiPanelUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.multi.MultiPanelUI

No usage of javax.swing.plaf.multi.MultiPanelUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.multi.MultiPopupMenuUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.multi.MultiPopupMenuUI

No usage of javax.swing.plaf.multi.MultiPopupMenuUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.multi.MultiProgressBarUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.multi.MultiProgressBarUI

No usage of javax.swing.plaf.multi.MultiProgressBarUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.multi.MultiRootPaneUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.multi.MultiRootPaneUI

No usage of javax.swing.plaf.multi.MultiRootPaneUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.multi.MultiScrollBarUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.multi.MultiScrollBarUI

No usage of javax.swing.plaf.multi.MultiScrollBarUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.multi.MultiScrollPaneUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.multi.MultiScrollPaneUI

No usage of javax.swing.plaf.multi.MultiScrollPaneUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.multi.MultiSeparatorUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.multi.MultiSeparatorUI

No usage of javax.swing.plaf.multi.MultiSeparatorUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.multi.MultiSliderUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.multi.MultiSliderUI

No usage of javax.swing.plaf.multi.MultiSliderUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.multi.MultiSpinnerUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.multi.MultiSpinnerUI

No usage of javax.swing.plaf.multi.MultiSpinnerUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.multi.MultiSplitPaneUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.multi.MultiSplitPaneUI

No usage of javax.swing.plaf.multi.MultiSplitPaneUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.multi.MultiTabbedPaneUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.multi.MultiTabbedPaneUI

No usage of javax.swing.plaf.multi.MultiTabbedPaneUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.multi.MultiTableHeaderUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.multi.MultiTableHeaderUI

No usage of javax.swing.plaf.multi.MultiTableHeaderUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.multi.MultiTableUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.multi.MultiTableUI

No usage of javax.swing.plaf.multi.MultiTableUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.multi.MultiTextUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.multi.MultiTextUI

No usage of javax.swing.plaf.multi.MultiTextUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.multi.MultiToolBarUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.multi.MultiToolBarUI

No usage of javax.swing.plaf.multi.MultiToolBarUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.multi.MultiToolTipUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.multi.MultiToolTipUI

No usage of javax.swing.plaf.multi.MultiToolTipUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.multi.MultiTreeUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.multi.MultiTreeUI

No usage of javax.swing.plaf.multi.MultiTreeUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.plaf.multi.MultiViewportUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.plaf.multi.MultiViewportUI

No usage of javax.swing.plaf.multi.MultiViewportUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


 Using the Multiplexing Look and Feel

This document is based on an article originally published in The Swing Connection.

The Multiplexing look and feel lets you supplement an ordinary look and feel (called the default look and feel) with one or more auxiliary look and feels. For example, you could simultaneously provide text-to-speech and Braille outputs, in addition to the ordinary visual output that a Swing-based application generates, by adding two auxiliary look and feels (one for text-to-speech, the other for Braille) to the default look and feel. The default look and feel can be any ordinary look and feel -- the Java or Windows look and feel, for example -- and requires no modifications to work with auxiliary look and feels.

This document has the following sections:

  • Overview
  • How to Use Auxiliary Look and Feels
  • Tips for Writing an Auxiliary Look and Feel
    • Dos and Don'ts
    • Extending UIDefaults
    • Examining Other UI Objects
  • How the Multiplexing Look and Feel is Implemented
  • How to Provide a Custom Multiplexing Look and Feel

Before reading further, you should be familiar with the concept of pluggable look and feels. For basic information, see Choosing the Look and Feel, a section in The Java Tutorial. For architectural details, you can read Pluggable look-and-feel architecture, a section within a Swing Connection article.

Overview

The classes in the javax.swing.plaf.multi package implement a multiplexing look and feel. A multiplexing look and feel transparently creates -- and simultaneously supports -- UI objects from several different look and feels in response to a component requesting its UI object (with the getUI method).

Without a multiplexing look and feel, a developer who wanted to enhance a particular look and feel would need to extend the classes supporting that look and feel. For example, to add text-to-speech support to the Java look and feel without using a multiplexing look and feel, the developer would need to create a group of classes that extend those of the Java look and feel, and add text-to-speech support to the new classes. If the developer also wanted to add text-to-speech support to other look and feels, such as Motif or Windows, the developers would need to create subclasses of those classes as well.

This approach has at least two shortcomings:

  • First, each subclass must use what is essentially a copy of the same code, potentially creating a difficult support situation for the developer.
  • Second, and more significantly for the end user, some application developers might force a particular look and feel to be used. When this approach is used, the end user can't even use the enhanced look and feel.

A multiplexing look and feel both these problems simultaneously because it allows multiple look and feels to be combined. The first problem (having to use what amounts to a second copy of the same code) is solved because the developer can create a specialized look and feel that can then be combined with other look and feels.

The second problem (having to force the use of a particular look and feel) is solved because a specialized look and feel can be used with whatever default look and feel the application may have locked in place.

The default multiplexing look and feel implementation, represented by the MultiLookAndFeel class in the javax.swing.plaf.multi package, is called (unsurprisingly) the Multiplexing look and feel.

How to Use Auxiliary Look and Feels

It's easy to use auxiliary look and feels with Swing. To instruct Swing to use the Multiplexing look and feel, all an application has to do is modify the $JDKHOME/lib/swing.properties file to include a definition of the swing.auxiliarylaf property. Swing treats the swing.auxiliarylaf property as a comma-separated list of LookAndFeel subclasses that specify what auxiliary look and feels should be used in addition to the default look and feel. If at least one valid LookAndFeel subclass is specified in the swing.auxiliarylaf property, Swing automatically uses the Multiplexing look and feel to load and support the default and auxiliary look and feels.

For example, let's assume that an application makes use of a look and feel that supports text-to-speech feedback, and also uses an look and feel that adds support for a device that emits perfume. Let's assume that the text-to-speech look and feel is named com.myco.TextTalkerLookAndFeel, and the look and feel that adds support for perfume is named com.smellco.OlfactoryLookAndFeel.

To tell Swing to use both these look and feels -- and to use a default look and feel at the same time -- your application could simply add the following line to the $JDKHOME/lib/swing.properties file:

    swing.auxiliarylaf=com.myco.TextTalkerLookAndFeel,
        com.smellco.OlfactoryLookAndFeel

This statement tells Swing to obtain a component's UI from the Multiplexing look and feel automatically, instead of obtaining it directly from the default look and feel. The resulting multiplexing UI is a small delegate that obtains and maintains UIs from the default and auxiliary look and feels. As a result, when a method is invoked in a multiplexing UI object, the multiplexing UI invokes the same method on each of the UIs obtained from the default and auxiliary look and feels.

Tips for Writing an Auxiliary Look and Feel

An auxiliary look and feel is like any other look and feel, except that it doesn't have to provide the complete support that a default look and feel must. For example, an auxiliary look and feel that supports just text-to-speech feedback doesn't need to provide any code for painting. Also, it might not need to support all components -- JSeparators, for example, might be ignored.

Auxiliary look and feels tend to be simple, so developing one can be easier than developing a visual look and feel. The developer can concentrate solely on providing the specialized functionality.

Because the primary purpose of an auxiliary look and feel is to enhance the default look and feel, auxiliary look and feels tend be nonvisual. Since an auxiliary look and feel is a genuine look and feel, however, there is nothing to prevent it from rendering information on the display.

Just like for any other look and feel, you implement an auxiliary look and feel by writing a subclass of javax.swing.LookAndFeel and creating subclasses of the FooUI classes defined in the javax.swing.plaf package.

Dos and Don'ts

The following paragraphs provide some general recommendations for developing auxiliary look and feels.

Use the installUI method to perform all initialization, and the uninstallUI method to perform all cleanup.

    The installUI and uninstallUI methods are invoked when a component's look and feel is set. The installUI method gives the new UI object a chance to add listeners on the component and its data model. Similarly, the uninstallUI method lets the previous UI object remove its listeners.

Don't extend visual look and feels.

    We recommended that you don't implement UI classes of an auxiliary look and feel as subclasses of the UI classes of a visual look and feel. Why not? Because they might accidentally inherit code that installs listeners on a component object or renders the component on the display. As a result, your auxiliary look and feel would compete with the default look and feel rather than cooperating with it.

    Instead, we recommend that the UI classes of an auxiliary look and feel directly extend the abstract UI classes in the javax.swing.plaf package. By using this strategy, the developer of an auxiliary look and feel can avoid competing with the default look and feel.

Override all UI-specific methods your UI classes inherit.

    We recommend that each UI class of an auxiliary look and feel override the methods defined in the javax.swing.plaf UI classes it descends from The reasons for this recommendation are similar to those for not extending a visual look and feel. For example, the ComponentUI class, from which all UI classes descend, provides a default implementation for the update method. This default implementation paints on the display if the component is opaque. If a UI class from a non-visual auxiliary look and feel does not override this method, all opaque components appear as blank areas on the screen!

Extending UIDefaults

In many cases, you might want an auxiliary look and feel to be "incomplete." That is, you might not need to support the complete set of components. For example, an auxiliary look and feel might choose to provide a ButtonUI subclass but no LabelUI subclass. This option is allowed, and the multiplexing look and feel gracefully handles such situations.

By default, however, Swing issues an error message when it asks a look and feel for a UI object and the look and feel does not support that UI. This message can be annoying, especially to auxiliary look-and-feel developers who don't want to support a particular component.

Fortunately, you can prevent this error message by creating a subclass of the UIDefaults class and returning an instance of it from the getDefaults method of your LookAndFeel class. For example:

public class MyAuxLookAndFeel
              extends LookAndFeel {
...
public UIDefaults getDefaults() {
UIDefaults table =
new MyAuxUIDefaults();
Object[] uiDefaults = {
"ButtonUI", "MyAuxButtonUI",
...
}
table.putDefaults(uiDefaults);
return table;
}
}

class MyAuxUIDefaults extends UIDefaults {
protected void getUIError(String msg) {
//System.err.println
//   ("An
              annoying message!");
}
}

In the preceding example, an auxiliary look and feel named MyAux creates a UIDefaults subclass that overrides the getUIError method. The getUIError method is the method that is invoked when Swing cannot find a UI object in a look and feel. By merely doing nothing in this method, you can avoid the error message.

Examining Other UI Objects

In rare instances, a UI object from an auxiliary look and feel may be interested in the default UI object used by the component. In these cases, the UI object from auxiliary look and feel can obtain the UI from a component by calling its getUI method. The returned UI is an instance of one of the multiplexing look and feel UI classes (for example, MultiButtonUI). The UI object from the auxiliary look and feel can call the getUIs method of the returned object to obtain an array containing a complete list of all UI objects handled by the multiplexing UI. The first element is guaranteed to be the UI created from the default look and feel.

How the Multiplexing Look and Feel Is Implemented

The Multiplexing look and feel (represented by javax.swing.plaf.multi.MultiLookAndFeel) is meant to be transparent to all developers and users. It should "just work" -- and it is used only when the user tells Swing to use an auxiliary look and feel.

When the Multiplexing look and feel is in use, the type of the UI object associated with each component depends on whether any of the auxiliary look and feels currently in use support the component. If so, the component's UI object is an instance of a multiplexing UI. If only the default look and feel supports the component, then the component gets a UI object from the default look and feel, just as if no auxiliary look and feels were installed.

A multiplexing UI object obtains and maintains UI objects from the default and auxiliary look and feels, referring to these UIs in the following manner:

  • The UI object from the default look and feel is always the first to be created. After that, a UI object is created from each auxiliary look and feel in the order they are specified in the swing.auxiliarylaf property.

  • When a method that requests information from a UI object is invoked, the multiplexing UI object invokes the method on all the UI objects, but returns only the results from the UI for the default look and feel. For example, when the getPreferredSize method is invoked on a multiplexing UI, the UI returns only the results of invoking getPreferredSize on the UI obtained from the default look and feel. The getPreferredSize method is also invoked on the UI object for each auxiliary look and feel, but the return values are ignored.

  • When a method that does not request information from the UI object is invoked, the multiplexing UI object invokes that method on all UIs -- on the UI object obtained from the default look and feel and on all the UIs obtained from the auxiliary look and feels, as well. For example, invoking the installUI method on a multiplexing UI causes the multiplexing UI to invoke installUI on the UI obtained from the default look and feel and the UIs obtained from the auxiliary factories.

In all cases, the UI object obtained from the default look and feel is acted upon first, and then the auxiliary look and feels are acted upon in the order they are specified in the swing.auxiliarylaf property.

How to Provide a Custom Multiplexing Look and Feel

While we hope the behavior of the Multiplexing look and feel is flexible enough not to require an alternative multiplexing look and feel, Swing allows the user to specify another multiplexing look and feel to use.

To do that, all the user has to do is modify the $JDKHOME/lib/swing.properties file to include a definition of the swing.plaf.multiplexinglaf property. Swing then treats the swing.plaf.multiplexinglaf property as a LookAndFeel subclass that supports multiplexing.

For example, if a user has a multiplexing look and feel represented by com.myco.SuperMultiLookAndFeel that is a better match for their needs than the Multiplexing look and feel (javax.swing.plaf.multi.MultiLookAndFeel), the user could include the following line in $JDKHOME/lib/swing.properties:

swing.plaf.multiplexinglaf = com.myco.SuperMultiLookAndFeel

This statement instructs Swing to use com.myco.SuperMultiLookAndFeel instead of javax.swing.plaf.multi.MultiLookAndFeel. But if you use this kind of statement, be careful, because the suppliers of auxiliary look and feels will most likely have developed and tested against our Multiplexing look and feel.


AbstractTableModel (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.swing.table
Class AbstractTableModel

java.lang.Object
    extended by javax.swing.table.AbstractTableModel
All Implemented Interfaces:
Serializable, TableModel
Direct Known Subclasses:
DefaultTableModel
public abstract class AbstractTableModel
extends Object
implements TableModel, Serializable

This abstract class provides default implementations for most of the methods in the TableModel interface. It takes care of the management of listeners and provides some conveniences for generating TableModelEvents and dispatching them to the listeners. To create a concrete TableModel as a subclass of AbstractTableModel you need only provide implementations for the following three methods:

  public int getRowCount();
  public int getColumnCount();
  public Object getValueAt(int row, int column);

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Field Summary
protected  EventListenerList listenerList
List of listeners
Constructor Summary
AbstractTableModel()
Method Summary
void | addTableModelListener(TableModelListener l) Adds a listener to the list that's notified each time a change to the data model occurs.
int | findColumn(String columnName) Returns a column given its name.
void | fireTableCellUpdated(int row, int column) Notifies all listeners that the value of the cell at [row, column] has been updated.
void | fireTableChanged(TableModelEvent e) Forwards the given notification event to all TableModelListeners that registered themselves as listeners for this table model.
void | fireTableDataChanged() Notifies all listeners that all cell values in the table's rows may have changed.
void | fireTableRowsDeleted(int firstRow, int lastRow) Notifies all listeners that rows in the range [firstRow, lastRow], inclusive, have been deleted.
void | fireTableRowsInserted(int firstRow, int lastRow) Notifies all listeners that rows in the range [firstRow, lastRow], inclusive, have been inserted.
void | fireTableRowsUpdated(int firstRow, int lastRow) Notifies all listeners that rows in the range [firstRow, lastRow], inclusive, have been updated.
void | fireTableStructureChanged() Notifies all listeners that the table's structure has changed.
Class | getColumnClass(int columnIndex) Returns Object.class regardless of columnIndex.
String | getColumnName(int column) Returns a default name for the column using spreadsheet conventions: A, B, C, ...
EventListener[] | getListeners(Class listenerType) Returns an array of all the objects currently registered as FooListeners upon this AbstractTableModel.
TableModelListener[] | getTableModelListeners() Returns an array of all the table model listeners registered on this model.
boolean | isCellEditable(int rowIndex, int columnIndex) Returns false.
void | removeTableModelListener(TableModelListener l) Removes a listener from the list that's notified each time a change to the data model occurs.
void | setValueAt(Object aValue, int rowIndex, int columnIndex) This empty implementation is provided so users don't have to implement this method if their data model is not editable.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Methods inherited from interface javax.swing.table.TableModel
getColumnCount, getRowCount, getValueAt

Field Detail

listenerList

protected EventListenerList listenerList
List of listeners

Constructor Detail

AbstractTableModel

public AbstractTableModel()
Method Detail

getColumnName

public String getColumnName(int column)
Returns a default name for the column using spreadsheet conventions: A, B, C, ... Z, AA, AB, etc. If column cannot be found, returns an empty string.

Specified by:
getColumnName in interface TableModel
Parameters:
column - the column being queried
Returns:
a string containing the default name of column

findColumn

public int findColumn(String columnName)
Returns a column given its name. Implementation is naive so this should be overridden if this method is to be called often. This method is not in the TableModel interface and is not used by the JTable.

Parameters:
columnName - string containing name of column to be located
Returns:
the column with columnName, or -1 if not found

getColumnClass

public Class getColumnClass(int columnIndex)
Returns Object.class regardless of columnIndex.

Specified by:
getColumnClass in interface TableModel
Parameters:
columnIndex - the column being queried
Returns:
the Object.class

isCellEditable

public boolean isCellEditable(int rowIndex,
                              int columnIndex)
Returns false. This is the default implementation for all cells.

Specified by:
isCellEditable in interface TableModel
Parameters:
rowIndex - the row being queried
columnIndex - the column being queried
Returns:
false
See Also:
TableModel.setValueAt(java.lang.Object, int, int)

setValueAt

public void setValueAt(Object aValue,
                       int rowIndex,
                       int columnIndex)
This empty implementation is provided so users don't have to implement this method if their data model is not editable.

Specified by:
setValueAt in interface TableModel
Parameters:
aValue - value to assign to cell
rowIndex - row of cell
columnIndex - column of cell
See Also:
TableModel.getValueAt(int, int), TableModel.isCellEditable(int, int)

addTableModelListener

public void addTableModelListener(TableModelListener l)
Adds a listener to the list that's notified each time a change to the data model occurs.

Specified by:
addTableModelListener in interface TableModel
Parameters:
l - the TableModelListener

removeTableModelListener

public void removeTableModelListener(TableModelListener l)
Removes a listener from the list that's notified each time a change to the data model occurs.

Specified by:
removeTableModelListener in interface TableModel
Parameters:
l - the TableModelListener

getTableModelListeners

public TableModelListener[] getTableModelListeners()
Returns an array of all the table model listeners registered on this model.

Returns:
all of this model's TableModelListeners or an empty array if no table model listeners are currently registered
Since:
1.4
See Also:
addTableModelListener(javax.swing.event.TableModelListener), removeTableModelListener(javax.swing.event.TableModelListener)

fireTableDataChanged

public void fireTableDataChanged()
Notifies all listeners that all cell values in the table's rows may have changed. The number of rows may also have changed and the JTable should redraw the table from scratch. The structure of the table (as in the order of the columns) is assumed to be the same.

See Also:
TableModelEvent, EventListenerList, JTable.tableChanged(TableModelEvent)

fireTableStructureChanged

public void fireTableStructureChanged()
Notifies all listeners that the table's structure has changed. The number of columns in the table, and the names and types of the new columns may be different from the previous state. If the JTable receives this event and its autoCreateColumnsFromModel flag is set it discards any table columns that it had and reallocates default columns in the order they appear in the model. This is the same as calling setModel(TableModel) on the JTable.

See Also:
TableModelEvent, EventListenerList

fireTableRowsInserted

public void fireTableRowsInserted(int firstRow,
                                  int lastRow)
Notifies all listeners that rows in the range [firstRow, lastRow], inclusive, have been inserted.

Parameters:
firstRow - the first row
lastRow - the last row
See Also:
TableModelEvent, EventListenerList

fireTableRowsUpdated

public void fireTableRowsUpdated(int firstRow,
                                 int lastRow)
Notifies all listeners that rows in the range [firstRow, lastRow], inclusive, have been updated.

Parameters:
firstRow - the first row
lastRow - the last row
See Also:
TableModelEvent, EventListenerList

fireTableRowsDeleted

public void fireTableRowsDeleted(int firstRow,
                                 int lastRow)
Notifies all listeners that rows in the range [firstRow, lastRow], inclusive, have been deleted.

Parameters:
firstRow - the first row
lastRow - the last row
See Also:
TableModelEvent, EventListenerList

fireTableCellUpdated

public void fireTableCellUpdated(int row,
                                 int column)
Notifies all listeners that the value of the cell at [row, column] has been updated.

Parameters:
row - row of cell which has been updated
column - column of cell which has been updated
See Also:
TableModelEvent, EventListenerList

fireTableChanged

public void fireTableChanged(TableModelEvent e)
Forwards the given notification event to all TableModelListeners that registered themselves as listeners for this table model.

Parameters:
e - the event to be forwarded
See Also:
addTableModelListener(javax.swing.event.TableModelListener), TableModelEvent, EventListenerList

getListeners

public EventListener[] getListeners(Class listenerType)
Returns an array of all the objects currently registered as FooListeners upon this AbstractTableModel. FooListeners are registered using the addFooListener method.

You can specify the listenerType argument with a class literal, such as FooListener.class. For example, you can query a model m for its table model listeners with the following code:

TableModelListener[] tmls = (TableModelListener[])(m.getListeners(TableModelListener.class));
If no such listeners exist, this method returns an empty array.

Parameters:
listenerType - the type of listeners requested; this parameter should specify an interface that descends from java.util.EventListener
Returns:
an array of all objects registered as FooListeners on this component, or an empty array if no such listeners have been added
Throws:
ClassCastException - if listenerType doesn't specify a class or interface that implements java.util.EventListener
Since:
1.3
See Also:
getTableModelListeners()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


DefaultTableCellRenderer (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.table
Class DefaultTableCellRenderer

java.lang.Object
    extended by java.awt.Component
        extended by java.awt.Container
            extended by javax.swing.JComponent
                extended by javax.swing.JLabel
                    extended by javax.swing.table.DefaultTableCellRenderer
All Implemented Interfaces:
Accessible, ImageObserver, MenuContainer, Serializable, SwingConstants, TableCellRenderer
Direct Known Subclasses:
DefaultTableCellRenderer.UIResource
public class DefaultTableCellRenderer
extends JLabel
implements TableCellRenderer, Serializable

The standard class for rendering (displaying) individual cells in a JTable.

Implementation Note: This class inherits from JLabel, a standard component class. However JTable employs a unique mechanism for rendering its cells and therefore requires some slightly modified behavior from its cell renderer. The table class defines a single cell renderer and uses it as a as a rubber-stamp for rendering all cells in the table; it renders the first cell, changes the contents of that cell renderer, shifts the origin to the new location, re-draws it, and so on. The standard JLabel component was not designed to be used this way and we want to avoid triggering a revalidate each time the cell is drawn. This would greatly decrease performance because the revalidate message would be passed up the hierarchy of the container to determine whether any other components would be affected. So this class overrides the validate, revalidate, repaint, and firePropertyChange methods to be no-ops. If you write your own renderer, please keep this performance consideration in mind.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

See Also:
JTable

Nested Class Summary
static class DefaultTableCellRenderer.UIResource
A subclass of DefaultTableCellRenderer that implements UIResource.
Nested classes inherited from class javax.swing.JLabel
JLabel.AccessibleJLabel
Nested classes inherited from class javax.swing.JComponent
JComponent.AccessibleJComponent
Nested classes inherited from class java.awt.Container
Container.AccessibleAWTContainer
Nested classes inherited from class java.awt.Component
Component.AccessibleAWTComponent, Component.BltBufferStrategy, Component.FlipBufferStrategy
Field Summary
protected static Border noFocusBorder
Fields inherited from class javax.swing.JLabel
labelFor
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
Constructor Summary
DefaultTableCellRenderer()
Creates a default table cell renderer.
Method Summary
void | firePropertyChange(String propertyName, boolean oldValue, boolean newValue) Overridden for performance reasons.
protected void | firePropertyChange(String propertyName, Object oldValue, Object newValue) Overridden for performance reasons.
Component | getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) Returns the default table cell renderer.
boolean | isOpaque() Overridden for performance reasons.
void | repaint(long tm, int x, int y, int width, int height) Overridden for performance reasons.
void | repaint(Rectangle r) Overridden for performance reasons.
void | revalidate() Overridden for performance reasons.
void | setBackground(Color c) Overrides JComponent.setBackground to assign the unselected-background color to the specified color.
void | setForeground(Color c) Overrides JComponent.setForeground to assign the unselected-foreground color to the specified color.
protected void | setValue(Object value) Sets the String object for the cell being rendered to value.
void | updateUI() Notification from the UIManager that the look and feel [L&F] has changed.
void | validate() Overridden for performance reasons.
Methods inherited from class javax.swing.JLabel
checkHorizontalKey, checkVerticalKey, getAccessibleContext, getDisabledIcon, getDisplayedMnemonic, getDisplayedMnemonicIndex, getHorizontalAlignment, getHorizontalTextPosition, getIcon, getIconTextGap, getLabelFor, getText, getUI, getUIClassID, getVerticalAlignment, getVerticalTextPosition, imageUpdate, paramString, setDisabledIcon, setDisplayedMnemonic, setDisplayedMnemonic, setDisplayedMnemonicIndex, setHorizontalAlignment, setHorizontalTextPosition, setIcon, setIconTextGap, setLabelFor, setText, setUI, setVerticalAlignment, setVerticalTextPosition
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addPropertyChangeListener, addPropertyChangeListener, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBorder, getBounds, getClientProperty, getComponentGraphics, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getGraphics, getHeight, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPreferredSize, getPropertyChangeListeners, getPropertyChangeListeners, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isMaximumSizeSet, isMinimumSizeSet, isOptimizedDrawingEnabled, isPaintingTile, isPreferredSizeSet, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removePropertyChangeListener, removePropertyChangeListener, removeVetoableChangeListener, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBorder, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFont, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setFocusCycleRoot, setFocusTraversalKeys, setFocusTraversalPolicy, setLayout, transferFocusBackward, transferFocusDownCycle, validateTree
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getFontMetrics, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMouseWheelListeners, getName, getParent, getPeer, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

noFocusBorder

protected static Border noFocusBorder
Constructor Detail

DefaultTableCellRenderer

public DefaultTableCellRenderer()
Creates a default table cell renderer.

Method Detail

setForeground

public void setForeground(Color c)
Overrides JComponent.setForeground to assign the unselected-foreground color to the specified color.

Overrides:
setForeground in class JComponent
Parameters:
c - set the foreground color to this value
See Also:
Component.getForeground()

setBackground

public void setBackground(Color c)
Overrides JComponent.setBackground to assign the unselected-background color to the specified color.

Overrides:
setBackground in class JComponent
Parameters:
c - set the background color to this value
See Also:
Component.getBackground()

updateUI

public void updateUI()
Notification from the UIManager that the look and feel [L&F] has changed. Replaces the current UI object with the latest version from the UIManager.

Overrides:
updateUI in class JLabel
See Also:
JComponent.updateUI()

getTableCellRendererComponent

public Component getTableCellRendererComponent(JTable table,
                                               Object value,
                                               boolean isSelected,
                                               boolean hasFocus,
                                               int row,
                                               int column)
Returns the default table cell renderer.

Specified by:
getTableCellRendererComponent in interface TableCellRenderer
Parameters:
table - the JTable
value - the value to assign to the cell at [row, column]
isSelected - true if cell is selected
hasFocus - true if cell has focus
row - the row of the cell to render
column - the column of the cell to render
Returns:
the default table cell renderer

isOpaque

public boolean isOpaque()
Overridden for performance reasons. See the Implementation Note for more information.

Overrides:
isOpaque in class JComponent
Returns:
true if this component is completely opaque
See Also:
JComponent.setOpaque(boolean)

validate

public void validate()
Overridden for performance reasons. See the Implementation Note for more information.

Overrides:
validate in class Container
See Also:
Container.add(java.awt.Component),
Component.invalidate(),
JComponent.revalidate()

revalidate

public void revalidate()
Overridden for performance reasons. See the Implementation Note for more information.

Overrides:
revalidate in class JComponent
See Also:
Component.invalidate(),
Container.validate(),
JComponent.isValidateRoot(),
RepaintManager.addInvalidComponent(javax.swing.JComponent)

repaint

public void repaint(long tm,
                    int x,
                    int y,
                    int width,
                    int height)
Overridden for performance reasons. See the Implementation Note for more information.

Overrides:
repaint in class JComponent
Parameters:
tm - this parameter is not used
x - the x value of the dirty region
y - the y value of the dirty region
width - the width of the dirty region
height - the height of the dirty region
See Also:
Component.isShowing(), RepaintManager.addDirtyRegion(javax.swing.JComponent, int, int, int, int)

repaint

public void repaint(Rectangle r)
Overridden for performance reasons. See the Implementation Note for more information.

Overrides:
repaint in class JComponent
Parameters:
r - a Rectangle containing the dirty region
See Also:
Component.isShowing(), RepaintManager.addDirtyRegion(javax.swing.JComponent, int, int, int, int)

firePropertyChange

protected void firePropertyChange(String propertyName,
                                  Object oldValue,
                                  Object newValue)
Overridden for performance reasons. See the Implementation Note for more information.

Overrides:
firePropertyChange in class JComponent
Parameters:
propertyName - the programmatic name of the property that was changed
oldValue - the old value of the property (as an Object)
newValue - the new value of the property (as an Object)
See Also:
PropertyChangeSupport

firePropertyChange

public void firePropertyChange(String propertyName,
                               boolean oldValue,
                               boolean newValue)
Overridden for performance reasons. See the Implementation Note for more information.

Overrides:
firePropertyChange in class JComponent
Parameters:
propertyName - the programmatic name of the property that was changed
oldValue - the old value of the property (as a boolean)
newValue - the new value of the property (as a boolean)
See Also:
JComponent.firePropertyChange(java.lang.String, java.lang.Object, java.lang.Object)

setValue

protected void setValue(Object value)
Sets the String object for the cell being rendered to value.

Parameters:
value - the string value for this cell; if value is null it sets the text value to an empty string
See Also:
JLabel.setText(java.lang.String)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DefaultTableCellRenderer.UIResource (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.table
Class DefaultTableCellRenderer.UIResource

java.lang.Object
    extended by java.awt.Component
        extended by java.awt.Container
            extended by javax.swing.JComponent
                extended by javax.swing.JLabel
                    extended by javax.swing.table.DefaultTableCellRenderer
                        extended by javax.swing.table.DefaultTableCellRenderer.UIResource
All Implemented Interfaces:
Accessible, ImageObserver, MenuContainer, Serializable, SwingConstants, TableCellRenderer, UIResource
Enclosing class:
DefaultTableCellRenderer
public static class DefaultTableCellRenderer.UIResource
extends DefaultTableCellRenderer
implements UIResource

A subclass of DefaultTableCellRenderer that implements UIResource. DefaultTableCellRenderer doesn't implement UIResource directly so that applications can safely override the cellRenderer property with DefaultTableCellRenderer subclasses.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Nested Class Summary
Nested classes inherited from class javax.swing.table.DefaultTableCellRenderer
DefaultTableCellRenderer.UIResource
Nested classes inherited from class javax.swing.JLabel
JLabel.AccessibleJLabel
Nested classes inherited from class javax.swing.JComponent
JComponent.AccessibleJComponent
Nested classes inherited from class java.awt.Container
Container.AccessibleAWTContainer
Nested classes inherited from class java.awt.Component
Component.AccessibleAWTComponent, Component.BltBufferStrategy, Component.FlipBufferStrategy
Field Summary
Fields inherited from class javax.swing.table.DefaultTableCellRenderer
noFocusBorder
Fields inherited from class javax.swing.JLabel
labelFor
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
Constructor Summary
DefaultTableCellRenderer.UIResource()
Methods inherited from class javax.swing.table.DefaultTableCellRenderer
firePropertyChange, firePropertyChange, getTableCellRendererComponent, isOpaque, repaint, repaint, revalidate, setBackground, setForeground, setValue, updateUI, validate
Methods inherited from class javax.swing.JLabel
checkHorizontalKey, checkVerticalKey, getAccessibleContext, getDisabledIcon, getDisplayedMnemonic, getDisplayedMnemonicIndex, getHorizontalAlignment, getHorizontalTextPosition, getIcon, getIconTextGap, getLabelFor, getText, getUI, getUIClassID, getVerticalAlignment, getVerticalTextPosition, imageUpdate, paramString, setDisabledIcon, setDisplayedMnemonic, setDisplayedMnemonic, setDisplayedMnemonicIndex, setHorizontalAlignment, setHorizontalTextPosition, setIcon, setIconTextGap, setLabelFor, setText, setUI, setVerticalAlignment, setVerticalTextPosition
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addPropertyChangeListener, addPropertyChangeListener, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBorder, getBounds, getClientProperty, getComponentGraphics, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getGraphics, getHeight, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPreferredSize, getPropertyChangeListeners, getPropertyChangeListeners, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isMaximumSizeSet, isMinimumSizeSet, isOptimizedDrawingEnabled, isPaintingTile, isPreferredSizeSet, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removePropertyChangeListener, removePropertyChangeListener, removeVetoableChangeListener, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBorder, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFont, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setFocusCycleRoot, setFocusTraversalKeys, setFocusTraversalPolicy, setLayout, transferFocusBackward, transferFocusDownCycle, validateTree
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getFontMetrics, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMouseWheelListeners, getName, getParent, getPeer, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

DefaultTableCellRenderer.UIResource

public DefaultTableCellRenderer.UIResource()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DefaultTableColumnModel (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.table
Class DefaultTableColumnModel

java.lang.Object
    extended by javax.swing.table.DefaultTableColumnModel
All Implemented Interfaces:
EventListener, ListSelectionListener, PropertyChangeListener, Serializable, TableColumnModel
public class DefaultTableColumnModel
extends Object
implements TableColumnModel, PropertyChangeListener, ListSelectionListener, Serializable

The standard column-handler for a JTable.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

See Also:
JTable

Field Summary
protected ChangeEvent | changeEvent Change event (only one needed)
protected int | columnMargin Width margin between each column
protected boolean | columnSelectionAllowed Column selection allowed in this column model
protected EventListenerList | listenerList List of TableColumnModelListener
protected ListSelectionModel | selectionModel Model for keeping track of column selections
protected Vector | tableColumns Array of TableColumn objects in this model
protected int | totalColumnWidth A local cache of the combined width of all columns
Constructor Summary
DefaultTableColumnModel()
Creates a default table column model.
Method Summary
void | addColumn(TableColumn aColumn) Appends aColumn to the end of the tableColumns array.
void | addColumnModelListener(TableColumnModelListener x) Adds a listener for table column model events.
protected ListSelectionModel | createSelectionModel() Creates a new default list selection model.
protected void | fireColumnAdded(TableColumnModelEvent e) Notifies all listeners that have registered interest for notification on this event type.
protected void | fireColumnMarginChanged() Notifies all listeners that have registered interest for notification on this event type.
protected void | fireColumnMoved(TableColumnModelEvent e) Notifies all listeners that have registered interest for notification on this event type.
protected void | fireColumnRemoved(TableColumnModelEvent e) Notifies all listeners that have registered interest for notification on this event type.
protected void | fireColumnSelectionChanged(ListSelectionEvent e) Notifies all listeners that have registered interest for notification on this event type.
TableColumn | getColumn(int columnIndex) Returns the TableColumn object for the column at columnIndex.
int | getColumnCount() Returns the number of columns in the tableColumns array.
int | getColumnIndex(Object identifier) Returns the index of the first column in the tableColumns array whose identifier is equal to identifier, when compared using equals.
int | getColumnIndexAtX(int x) Returns the index of the column that lies at position x, or -1 if no column covers this point.
int | getColumnMargin() Returns the width margin for TableColumn.
TableColumnModelListener[] | getColumnModelListeners() Returns an array of all the column model listeners registered on this model.
Enumeration | getColumns() Returns an Enumeration of all the columns in the model.
boolean | getColumnSelectionAllowed() Returns true if column selection is allowed, otherwise false.
EventListener[] | getListeners(Class listenerType) Returns an array of all the objects currently registered as FooListeners upon this model.
int | getSelectedColumnCount() Returns the number of columns selected.
int[] | getSelectedColumns() Returns an array of selected columns.
ListSelectionModel | getSelectionModel() Returns the ListSelectionModel that is used to maintain column selection state.
int | getTotalColumnWidth() Returns the total combined width of all columns.
void | moveColumn(int columnIndex, int newIndex) Moves the column and heading at columnIndex to newIndex.
void | propertyChange(PropertyChangeEvent evt) Property Change Listener change method.
protected void | recalcWidthCache() Recalculates the total combined width of all columns.
void | removeColumn(TableColumn column) Deletes the column from the tableColumns array.
void | removeColumnModelListener(TableColumnModelListener x) Removes a listener for table column model events.
void | setColumnMargin(int newMargin) Sets the column margin to newMargin.
void | setColumnSelectionAllowed(boolean flag) Sets whether column selection is allowed.
void | setSelectionModel(ListSelectionModel newModel) Sets the selection model for this TableColumnModel to newModel and registers for listener notifications from the new selection model.
void | valueChanged(ListSelectionEvent e) A ListSelectionListener that forwards ListSelectionEvents when there is a column selection change.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

tableColumns

protected Vector tableColumns
Array of TableColumn objects in this model

selectionModel

protected ListSelectionModel selectionModel
Model for keeping track of column selections

columnMargin

protected int columnMargin
Width margin between each column

listenerList

protected EventListenerList listenerList
List of TableColumnModelListener

changeEvent

protected transient ChangeEvent changeEvent
Change event (only one needed)

columnSelectionAllowed

protected boolean columnSelectionAllowed
Column selection allowed in this column model

totalColumnWidth

protected int totalColumnWidth
A local cache of the combined width of all columns

Constructor Detail

DefaultTableColumnModel

public DefaultTableColumnModel()
Creates a default table column model.

Method Detail

addColumn

public void addColumn(TableColumn aColumn)
Appends aColumn to the end of the tableColumns array. This method also posts the columnAdded event to its listeners.

Specified by:
addColumn in interface TableColumnModel
Parameters:
aColumn - the TableColumn to be added
Throws:
IllegalArgumentException - if aColumn is null
See Also:
removeColumn(javax.swing.table.TableColumn)

removeColumn

public void removeColumn(TableColumn column)
Deletes the column from the tableColumns array. This method will do nothing if column is not in the table's columns list. tile is called to resize both the header and table views. This method also posts a columnRemoved event to its listeners.

Specified by:
removeColumn in interface TableColumnModel
Parameters:
column - the TableColumn to be removed
See Also:
addColumn(javax.swing.table.TableColumn)

moveColumn

public void moveColumn(int columnIndex,
                       int newIndex)
Moves the column and heading at columnIndex to newIndex. The old column at columnIndex will now be found at newIndex. The column that used to be at newIndex is shifted left or right to make room. This will not move any columns if columnIndex equals newIndex. This method also posts a columnMoved event to its listeners.

Specified by:
moveColumn in interface TableColumnModel
Parameters:
columnIndex - the index of column to be moved
newIndex - new index to move the column
Throws:
IllegalArgumentException - if column or newIndex are not in the valid range

setColumnMargin

public void setColumnMargin(int newMargin)
Sets the column margin to newMargin. This method also posts a columnMarginChanged event to its listeners.

Specified by:
setColumnMargin in interface TableColumnModel
Parameters:
newMargin - the new margin width, in pixels
See Also:
getColumnMargin(), getTotalColumnWidth()

getColumnCount

public int getColumnCount()
Returns the number of columns in the tableColumns array.

Specified by:
getColumnCount in interface TableColumnModel
Returns:
the number of columns in the tableColumns array
See Also:
getColumns()

getColumns

public Enumeration getColumns()
Returns an Enumeration of all the columns in the model.

Specified by:
getColumns in interface TableColumnModel
Returns:
an Enumeration of the columns in the model

getColumnIndex

public int getColumnIndex(Object identifier)
Returns the index of the first column in the tableColumns array whose identifier is equal to identifier, when compared using equals.

Specified by:
getColumnIndex in interface TableColumnModel
Parameters:
identifier - the identifier object
Returns:
the index of the first column in the tableColumns array whose identifier is equal to identifier
Throws:
IllegalArgumentException - if identifier is null, or if no TableColumn has this identifier
See Also:
getColumn(int)

getColumn

public TableColumn getColumn(int columnIndex)
Returns the TableColumn object for the column at columnIndex.

Specified by:
getColumn in interface TableColumnModel
Parameters:
columnIndex - the index of the column desired
Returns:
the TableColumn object for the column at columnIndex

getColumnMargin

public int getColumnMargin()
Returns the width margin for TableColumn. The default columnMargin is 1.

Specified by:
getColumnMargin in interface TableColumnModel
Returns:
the maximum width for the TableColumn
See Also:
setColumnMargin(int)

getColumnIndexAtX

public int getColumnIndexAtX(int x)
Returns the index of the column that lies at position x, or -1 if no column covers this point. In keeping with Swing's separable model architecture, a TableColumnModel does not know how the table columns actually appear on screen. The visual presentation of the columns is the responsibility of the view/controller object using this model (typically JTable). The view/controller need not display the columns sequentially from left to right. For example, columns could be displayed from right to left to accomodate a locale preference or some columns might be hidden at the request of the user. Because the model does not know how the columns are laid out on screen, the given xPosition should not be considered to be a coordinate in 2D graphics space. Instead, it should be considered to be a width from the start of the first column in the model. If the column index for a given X coordinate in 2D space is required, JTable.columnAtPoint can be used instead.

Specified by:
getColumnIndexAtX in interface TableColumnModel
Parameters:
x - the horizontal location of interest
Returns:
the index of the column or -1 if no column is found
See Also:
JTable.columnAtPoint(java.awt.Point)

getTotalColumnWidth

public int getTotalColumnWidth()
Returns the total combined width of all columns.

Specified by:
getTotalColumnWidth in interface TableColumnModel
Returns:
the totalColumnWidth property

setSelectionModel

public void setSelectionModel(ListSelectionModel newModel)
Sets the selection model for this TableColumnModel to newModel and registers for listener notifications from the new selection model. If newModel is null, an exception is thrown.

Specified by:
setSelectionModel in interface TableColumnModel
Parameters:
newModel - the new selection model
Throws:
IllegalArgumentException - if newModel is null
See Also:
getSelectionModel()

getSelectionModel

public ListSelectionModel getSelectionModel()
Returns the ListSelectionModel that is used to maintain column selection state.

Specified by:
getSelectionModel in interface TableColumnModel
Returns:
the object that provides column selection state. Or null if row selection is not allowed.
See Also:
setSelectionModel(javax.swing.ListSelectionModel)

setColumnSelectionAllowed

public void setColumnSelectionAllowed(boolean flag)
Sets whether column selection is allowed. The default is false.

Specified by:
setColumnSelectionAllowed in interface TableColumnModel
Parameters:
flag - true if column selection will be allowed, false otherwise
See Also:
TableColumnModel.getColumnSelectionAllowed()

getColumnSelectionAllowed

public boolean getColumnSelectionAllowed()
Returns true if column selection is allowed, otherwise false. The default is false.

Specified by:
getColumnSelectionAllowed in interface TableColumnModel
Returns:
the columnSelectionAllowed property
See Also:
TableColumnModel.setColumnSelectionAllowed(boolean)

getSelectedColumns

public int[] getSelectedColumns()
Returns an array of selected columns. If selectionModel is null, returns an empty array.

Specified by:
getSelectedColumns in interface TableColumnModel
Returns:
an array of selected columns or an empty array if nothing is selected or the selectionModel is null

getSelectedColumnCount

public int getSelectedColumnCount()
Returns the number of columns selected.

Specified by:
getSelectedColumnCount in interface TableColumnModel
Returns:
the number of columns selected

addColumnModelListener

public void addColumnModelListener(TableColumnModelListener x)
Adds a listener for table column model events.

Specified by:
addColumnModelListener in interface TableColumnModel
Parameters:
x - a TableColumnModelListener object

removeColumnModelListener

public void removeColumnModelListener(TableColumnModelListener x)
Removes a listener for table column model events.

Specified by:
removeColumnModelListener in interface TableColumnModel
Parameters:
x - a TableColumnModelListener object

getColumnModelListeners

public TableColumnModelListener[] getColumnModelListeners()
Returns an array of all the column model listeners registered on this model.

Returns:
all of this default table column model's ColumnModelListeners or an empty array if no column model listeners are currently registered
Since:
1.4
See Also:
addColumnModelListener(javax.swing.event.TableColumnModelListener), removeColumnModelListener(javax.swing.event.TableColumnModelListener)

fireColumnAdded

protected void fireColumnAdded(TableColumnModelEvent e)
Notifies all listeners that have registered interest for notification on this event type. The event instance is lazily created using the parameters passed into the fire method.

Parameters:
e - the event received
See Also:
EventListenerList

fireColumnRemoved

protected void fireColumnRemoved(TableColumnModelEvent e)
Notifies all listeners that have registered interest for notification on this event type. The event instance is lazily created using the parameters passed into the fire method.

Parameters:
e - the event received
See Also:
EventListenerList

fireColumnMoved

protected void fireColumnMoved(TableColumnModelEvent e)
Notifies all listeners that have registered interest for notification on this event type. The event instance is lazily created using the parameters passed into the fire method.

Parameters:
e - the event received
See Also:
EventListenerList

fireColumnSelectionChanged

protected void fireColumnSelectionChanged(ListSelectionEvent e)
Notifies all listeners that have registered interest for notification on this event type. The event instance is lazily created using the parameters passed into the fire method.

Parameters:
e - the event received
See Also:
EventListenerList

fireColumnMarginChanged

protected void fireColumnMarginChanged()
Notifies all listeners that have registered interest for notification on this event type. The event instance is lazily created using the parameters passed into the fire method.

See Also:
EventListenerList

getListeners

public EventListener[] getListeners(Class listenerType)
Returns an array of all the objects currently registered as FooListeners upon this model. FooListeners are registered using the addFooListener method.

You can specify the listenerType argument with a class literal, such as FooListener.class. For example, you can query a DefaultTableColumnModel m for its column model listeners with the following code:

ColumnModelListener[] cmls = (ColumnModelListener[])(m.getListeners(ColumnModelListener.class));
If no such listeners exist, this method returns an empty array.

Parameters:
listenerType - the type of listeners requested; this parameter should specify an interface that descends from java.util.EventListener
Returns:
an array of all objects registered as FooListeners on this model, or an empty array if no such listeners have been added
Throws:
ClassCastException - if listenerType doesn't specify a class or interface that implements java.util.EventListener
Since:
1.3
See Also:
getColumnModelListeners()

propertyChange

public void propertyChange(PropertyChangeEvent evt)
Property Change Listener change method. Used to track changes to the column width or preferred column width.

Specified by:
propertyChange in interface PropertyChangeListener
Parameters:
evt - PropertyChangeEvent

valueChanged

public void valueChanged(ListSelectionEvent e)
A ListSelectionListener that forwards ListSelectionEvents when there is a column selection change.

Specified by:
valueChanged in interface ListSelectionListener
Parameters:
e - the change event

createSelectionModel

protected ListSelectionModel createSelectionModel()
Creates a new default list selection model.

recalcWidthCache

protected void recalcWidthCache()
Recalculates the total combined width of all columns. Updates the totalColumnWidth property.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DefaultTableModel (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.table
Class DefaultTableModel

java.lang.Object
    extended by javax.swing.table.AbstractTableModel
        extended by javax.swing.table.DefaultTableModel
All Implemented Interfaces:
Serializable, TableModel
public class DefaultTableModel
extends AbstractTableModel
implements Serializable

This is an implementation of TableModel that uses a Vector of Vectors to store the cell value objects.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

See Also:
TableModel, getDataVector()

Field Summary
protected Vector | columnIdentifiers The Vector of column identifiers.
protected Vector | dataVector The Vector of Vectors of Object values.
Fields inherited from class javax.swing.table.AbstractTableModel
listenerList
Constructor Summary
DefaultTableModel()
Constructs a default DefaultTableModel which is a table of zero columns and zero rows.
DefaultTableModel(int rowCount, int columnCount)
Constructs a DefaultTableModel with rowCount and columnCount of null object values.
DefaultTableModel(Object[][] data, Object[] columnNames)
Constructs a DefaultTableModel and initializes the table by passing data and columnNames to the setDataVector method.
DefaultTableModel(Object[] columnNames, int rowCount)
Constructs a DefaultTableModel with as many columns as there are elements in columnNames and rowCount of null object values.
DefaultTableModel(Vector columnNames, int rowCount)
Constructs a DefaultTableModel with as many columns as there are elements in columnNames and rowCount of null object values.
DefaultTableModel(Vector data, Vector columnNames)
Constructs a DefaultTableModel and initializes the table by passing data and columnNames to the setDataVector method.
Method Summary
void | addColumn(Object columnName) Adds a column to the model.
void | addColumn(Object columnName, Object[] columnData) Adds a column to the model.
void | addColumn(Object columnName, Vector columnData) Adds a column to the model.
void | addRow(Object[] rowData) Adds a row to the end of the model.
void | addRow(Vector rowData) Adds a row to the end of the model.
protected static Vector | convertToVector(Object[] anArray) Returns a vector that contains the same objects as the array.
protected static Vector | convertToVector(Object[][] anArray) Returns a vector of vectors that contains the same objects as the array.
int | getColumnCount() Returns the number of columns in this data table.
String | getColumnName(int column) Returns the column name.
Vector | getDataVector() Returns the Vector of Vectors that contains the table's data values.
int | getRowCount() Returns the number of rows in this data table.
Object | getValueAt(int row, int column) Returns an attribute value for the cell at row and column.
void | insertRow(int row, Object[] rowData) Inserts a row at row in the model.
void | insertRow(int row, Vector rowData) Inserts a row at row in the model.
boolean | isCellEditable(int row, int column) Returns true regardless of parameter values.
void | moveRow(int start, int end, int to) Moves one or more rows from the inlcusive range start to end to the to position in the model.
void | newDataAvailable(TableModelEvent event) Equivalent to fireTableChanged.
void | newRowsAdded(TableModelEvent e) Ensures that the new rows have the correct number of columns.
void | removeRow(int row) Removes the row at row from the model.
void | rowsRemoved(TableModelEvent event) Equivalent to fireTableChanged.
void | setColumnCount(int columnCount) Sets the number of columns in the model.
void | setColumnIdentifiers(Object[] newIdentifiers) Replaces the column identifiers in the model.
void | setColumnIdentifiers(Vector columnIdentifiers) Replaces the column identifiers in the model.
void | setDataVector(Object[][] dataVector, Object[] columnIdentifiers) Replaces the value in the dataVector instance variable with the values in the array dataVector.
void | setDataVector(Vector dataVector, Vector columnIdentifiers) Replaces the current dataVector instance variable with the new Vector of rows, dataVector.
void | setNumRows(int rowCount) Obsolete as of Java 2 platform v1.3.
void | setRowCount(int rowCount) Sets the number of rows in the model.
void | setValueAt(Object aValue, int row, int column) Sets the object value for the cell at column and row.
Methods inherited from class javax.swing.table.AbstractTableModel
addTableModelListener, findColumn, fireTableCellUpdated, fireTableChanged, fireTableDataChanged, fireTableRowsDeleted, fireTableRowsInserted, fireTableRowsUpdated, fireTableStructureChanged, getColumnClass, getListeners, getTableModelListeners, removeTableModelListener
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

dataVector

protected Vector dataVector
The Vector of Vectors of Object values.

columnIdentifiers

protected Vector columnIdentifiers
The Vector of column identifiers.

Constructor Detail

DefaultTableModel

public DefaultTableModel()
Constructs a default DefaultTableModel which is a table of zero columns and zero rows.

DefaultTableModel

public DefaultTableModel(int rowCount,
                         int columnCount)
Constructs a DefaultTableModel with rowCount and columnCount of null object values.

Parameters:
rowCount - the number of rows the table holds
columnCount - the number of columns the table holds
See Also:
setValueAt(java.lang.Object, int, int)

DefaultTableModel

public DefaultTableModel(Vector columnNames,
                         int rowCount)
Constructs a DefaultTableModel with as many columns as there are elements in columnNames and rowCount of null object values. Each column's name will be taken from the columnNames vector.

Parameters:
columnNames - vector containing the names of the new columns; if this is null then the model has no columns
rowCount - the number of rows the table holds
See Also:
setDataVector(java.util.Vector, java.util.Vector), setValueAt(java.lang.Object, int, int)

DefaultTableModel

public DefaultTableModel(Object[] columnNames,
                         int rowCount)
Constructs a DefaultTableModel with as many columns as there are elements in columnNames and rowCount of null object values. Each column's name will be taken from the columnNames array.

Parameters:
columnNames - array containing the names of the new columns; if this is null then the model has no columns
rowCount - the number of rows the table holds
See Also:
setDataVector(java.util.Vector, java.util.Vector), setValueAt(java.lang.Object, int, int)

DefaultTableModel

public DefaultTableModel(Vector data,
                         Vector columnNames)
Constructs a DefaultTableModel and initializes the table by passing data and columnNames to the setDataVector method.

Parameters:
data - the data of the table
columnNames - vector containing the names of the new columns
See Also:
getDataVector(), setDataVector(java.util.Vector, java.util.Vector)

DefaultTableModel

public DefaultTableModel(Object[][] data,
                         Object[] columnNames)
Constructs a DefaultTableModel and initializes the table by passing data and columnNames to the setDataVector method. The first index in the Object[][] array is the row index and the second is the column index.

Parameters:
data - the data of the table
columnNames - the names of the columns
See Also:
getDataVector(), setDataVector(java.util.Vector, java.util.Vector)
Method Detail

getDataVector

public Vector getDataVector()
Returns the Vector of Vectors that contains the table's data values. The vectors contained in the outer vector are each a single row of values. In other words, to get to the cell at row 1, column 5:

((Vector)getDataVector().elementAt(1)).elementAt(5);

Returns:
the vector of vectors containing the tables data values
See Also:
newDataAvailable(javax.swing.event.TableModelEvent),
newRowsAdded(javax.swing.event.TableModelEvent),
setDataVector(java.util.Vector, java.util.Vector)

setDataVector

public void setDataVector(Vector dataVector,
                          Vector columnIdentifiers)
Replaces the current dataVector instance variable with the new Vector of rows, dataVector. columnIdentifiers are the names of the new columns. The first name in columnIdentifiers is mapped to column 0 in dataVector. Each row in dataVector is adjusted to match the number of columns in columnIdentifiers either by truncating the Vector if it is too long, or adding null values if it is too short.

Note that passing in a null value for dataVector results in unspecified behavior, an possibly an exception.

Parameters:
dataVector - the new data vector
columnIdentifiers - the names of the columns
See Also:
getDataVector()

setDataVector

public void setDataVector(Object[][] dataVector,
                          Object[] columnIdentifiers)
Replaces the value in the dataVector instance variable with the values in the array dataVector. The first index in the Object[][] array is the row index and the second is the column index. columnIdentifiers are the names of the new columns.

Parameters:
dataVector - the new data vector
columnIdentifiers - the names of the columns
See Also:
setDataVector(Vector, Vector)

newDataAvailable

public void newDataAvailable(TableModelEvent event)
Equivalent to fireTableChanged.

Parameters:
event - the change event

newRowsAdded

public void newRowsAdded(TableModelEvent e)
Ensures that the new rows have the correct number of columns. This is accomplished by using the setSize method in Vector which truncates vectors which are too long, and appends nulls if they are too short. This method also sends out a tableChanged notification message to all the listeners.

Parameters:
e - this TableModelEvent describes where the rows were added. If null it assumes all the rows were newly added
See Also:
getDataVector()

rowsRemoved

public void rowsRemoved(TableModelEvent event)
Equivalent to fireTableChanged.

Parameters:
event - the change event

setNumRows

public void setNumRows(int rowCount)
Obsolete as of Java 2 platform v1.3. Please use setRowCount instead.

setRowCount

public void setRowCount(int rowCount)
Sets the number of rows in the model. If the new size is greater than the current size, new rows are added to the end of the model If the new size is less than the current size, all rows at index rowCount and greater are discarded.

See Also:
setColumnCount(int)

addRow

public void addRow(Vector rowData)
Adds a row to the end of the model. The new row will contain null values unless rowData is specified. Notification of the row being added will be generated.

Parameters:
rowData - optional data of the row being added

addRow

public void addRow(Object[] rowData)
Adds a row to the end of the model. The new row will contain null values unless rowData is specified. Notification of the row being added will be generated.

Parameters:
rowData - optional data of the row being added

insertRow

public void insertRow(int row,
                      Vector rowData)
Inserts a row at row in the model. The new row will contain null values unless rowData is specified. Notification of the row being added will be generated.

Parameters:
row - the row index of the row to be inserted
rowData - optional data of the row being added
Throws:
ArrayIndexOutOfBoundsException - if the row was invalid

insertRow

public void insertRow(int row,
                      Object[] rowData)
Inserts a row at row in the model. The new row will contain null values unless rowData is specified. Notification of the row being added will be generated.

Parameters:
row - the row index of the row to be inserted
rowData - optional data of the row being added
Throws:
ArrayIndexOutOfBoundsException - if the row was invalid

moveRow

public void moveRow(int start,
                    int end,
                    int to)
Moves one or more rows from the inlcusive range start to end to the to position in the model. After the move, the row that was at index start will be at index to. This method will send a tableChanged notification message to all the listeners.

  Examples of moves:

  1. moveRow(1,3,5);
          a|B|C|D|e|f|g|h|i|j|k   - before
          a|e|f|g|h|B|C|D|i|j|k   - after

  2. moveRow(6,7,1);
          a|b|c|d|e|f|G|H|i|j|k   - before
          a|G|H|b|c|d|e|f|i|j|k   - after

Parameters:
start - the starting row index to be moved
end - the ending row index to be moved
to - the destination of the rows to be moved
Throws:
ArrayIndexOutOfBoundsException - if any of the elements would be moved out of the table's range

removeRow

public void removeRow(int row)
Removes the row at row from the model. Notification of the row being removed will be sent to all the listeners.

Parameters:
row - the row index of the row to be removed
Throws:
ArrayIndexOutOfBoundsException - if the row was invalid

setColumnIdentifiers

public void setColumnIdentifiers(Vector columnIdentifiers)
Replaces the column identifiers in the model. If the number of newIdentifiers is greater than the current number of columns, new columns are added to the end of each row in the model. If the number of newIdentifiers is less than the current number of columns, all the extra columns at the end of a row are discarded.

Parameters:
columnIdentifiers - vector of column identifiers. If null, set the model to zero columns
See Also:
setNumRows(int)

setColumnIdentifiers

public void setColumnIdentifiers(Object[] newIdentifiers)
Replaces the column identifiers in the model. If the number of newIdentifiers is greater than the current number of columns, new columns are added to the end of each row in the model. If the number of newIdentifiers is less than the current number of columns, all the extra columns at the end of a row are discarded.

Parameters:
newIdentifiers - array of column identifiers. If null, set the model to zero columns
See Also:
setNumRows(int)

setColumnCount

public void setColumnCount(int columnCount)
Sets the number of columns in the model. If the new size is greater than the current size, new columns are added to the end of the model with null cell values. If the new size is less than the current size, all columns at index columnCount and greater are discarded.

Parameters:
columnCount - the new number of columns in the model
See Also:
setColumnCount(int)

addColumn

public void addColumn(Object columnName)
Adds a column to the model. The new column will have the identifier columnName, which may be null. This method will send a tableChanged notification message to all the listeners. This method is a cover for addColumn(Object, Vector) which uses null as the data vector.

Parameters:
columnName - the identifier of the column being added

addColumn

public void addColumn(Object columnName,
                      Vector columnData)
Adds a column to the model. The new column will have the identifier columnName, which may be null. columnData is the optional vector of data for the column. If it is null the column is filled with null values. Otherwise, the new data will be added to model starting with the first element going to row 0, etc. This method will send a tableChanged notification message to all the listeners.

Parameters:
columnName - the identifier of the column being added
columnData - optional data of the column being added

addColumn

public void addColumn(Object columnName,
                      Object[] columnData)
Adds a column to the model. The new column will have the identifier columnName. columnData is the optional array of data for the column. If it is null the column is filled with null values. Otherwise, the new data will be added to model starting with the first element going to row 0, etc. This method will send a tableChanged notification message to all the listeners.

See Also:
addColumn(Object, Vector)

getRowCount

public int getRowCount()
Returns the number of rows in this data table.

Specified by:
getRowCount in interface TableModel
Returns:
the number of rows in the model
See Also:
TableModel.getColumnCount()

getColumnCount

public int getColumnCount()
Returns the number of columns in this data table.

Specified by:
getColumnCount in interface TableModel
Returns:
the number of columns in the model
See Also:
TableModel.getRowCount()

getColumnName

public String getColumnName(int column)
Returns the column name.

Specified by:
getColumnName in interface TableModel
Overrides:
getColumnName in class AbstractTableModel
Parameters:
column - the column being queried
Returns:
a name for this column using the string value of the appropriate member in columnIdentifiers. If columnIdentifiers does not have an entry for this index, returns the default name provided by the superclass

isCellEditable

public boolean isCellEditable(int row,
                              int column)
Returns true regardless of parameter values.

Specified by:
isCellEditable in interface TableModel
Overrides:
isCellEditable in class AbstractTableModel
Parameters:
row - the row whose value is to be queried
column - the column whose value is to be queried
Returns:
true
See Also:
setValueAt(java.lang.Object, int, int)

getValueAt

public Object getValueAt(int row,
                         int column)
Returns an attribute value for the cell at row and column.

Specified by:
getValueAt in interface TableModel
Parameters:
row - the row whose value is to be queried
column - the column whose value is to be queried
Returns:
the value Object at the specified cell
Throws:
ArrayIndexOutOfBoundsException - if an invalid row or column was given

setValueAt

public void setValueAt(Object aValue,
                       int row,
                       int column)
Sets the object value for the cell at column and row. aValue is the new value. This method will generate a tableChanged notification.

Specified by:
setValueAt in interface TableModel
Overrides:
setValueAt in class AbstractTableModel
Parameters:
aValue - the new value; this can be null
row - the row whose value is to be changed
column - the column whose value is to be changed
Throws:
ArrayIndexOutOfBoundsException - if an invalid row or column was given

convertToVector

protected static Vector convertToVector(Object[] anArray)
Returns a vector that contains the same objects as the array.

Parameters:
anArray - the array to be converted
Returns:
the new vector; if anArray is null, returns null

convertToVector

protected static Vector convertToVector(Object[][] anArray)
Returns a vector of vectors that contains the same objects as the array.

Parameters:
anArray - the double array to be converted
Returns:
the new vector of vectors; if anArray is null, returns null
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


JTableHeader (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.table
Class JTableHeader

java.lang.Object
    extended by java.awt.Component
        extended by java.awt.Container
            extended by javax.swing.JComponent
                extended by javax.swing.table.JTableHeader
All Implemented Interfaces:
Accessible, EventListener, ImageObserver, MenuContainer, Serializable, TableColumnModelListener
public class JTableHeader
extends JComponent
implements TableColumnModelListener, Accessible

This is the object which manages the header of the JTable.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

See Also:
JTable

Nested Class Summary
protected  class JTableHeader.AccessibleJTableHeader
This class implements accessibility support for the JTableHeader class.
Nested classes inherited from class javax.swing.JComponent
JComponent.AccessibleJComponent
Nested classes inherited from class java.awt.Container
Container.AccessibleAWTContainer
Nested classes inherited from class java.awt.Component
Component.AccessibleAWTComponent, Component.BltBufferStrategy, Component.FlipBufferStrategy
Field Summary
protected TableColumnModel | columnModel The TableColumnModel of the table header.
protected TableColumn | draggedColumn The index of the column being dragged.
protected int | draggedDistance The distance from its original position the column has been dragged.
protected boolean | reorderingAllowed If true, reordering of columns are allowed by the user; the default is true.
protected boolean | resizingAllowed If true, resizing of columns are allowed by the user; the default is true.
protected TableColumn | resizingColumn The index of the column being resized.
protected JTable | table The table for which this object is the header; the default is null.
protected boolean | updateTableInRealTime Obsolete as of Java 2 platform v1.3.
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
Constructor Summary
JTableHeader()
Constructs a JTableHeader with a default TableColumnModel.
JTableHeader(TableColumnModel cm)
Constructs a JTableHeader which is initialized with cm as the column model.
Method Summary
void | columnAdded(TableColumnModelEvent e) Invoked when a column is added to the table column model.
int | columnAtPoint(Point point) Returns the index of the column that point lies in, or -1 if it lies out of bounds.
void | columnMarginChanged(ChangeEvent e) Invoked when a column is moved due to a margin change.
void | columnMoved(TableColumnModelEvent e) Invoked when a column is repositioned.
void | columnRemoved(TableColumnModelEvent e) Invoked when a column is removed from the table column model.
void | columnSelectionChanged(ListSelectionEvent e) Invoked when the selection model of the TableColumnModel is changed.
protected TableColumnModel | createDefaultColumnModel() Returns the default column model object which is a DefaultTableColumnModel.
protected TableCellRenderer | createDefaultRenderer() Returns a default renderer to be used when no header renderer is defined by a TableColumn.
AccessibleContext | getAccessibleContext() Gets the AccessibleContext associated with this JTableHeader.
TableColumnModel | getColumnModel() Returns the TableColumnModel that contains all column information of this table header.
TableCellRenderer | getDefaultRenderer() Returns the default renderer used when no headerRenderer is defined by a TableColumn.
TableColumn | getDraggedColumn() Returns the the dragged column, if and only if, a drag is in process, otherwise returns null.
int | getDraggedDistance() Returns the column's horizontal distance from its original position, if and only if, a drag is in process.
Rectangle | getHeaderRect(int column) Returns the rectangle containing the header tile at column.
boolean | getReorderingAllowed() Returns true if the user is allowed to rearrange columns by dragging their headers, false otherwise.
boolean | getResizingAllowed() Returns true if the user is allowed to resize columns by dragging between their headers, false otherwise.
TableColumn | getResizingColumn() Returns the resizing column.
JTable | getTable() Returns the table associated with this header.
String | getToolTipText(MouseEvent event) Allows the renderer's tips to be used if there is text set.
TableHeaderUI | getUI() Returns the look and feel (L&F) object that renders this component.
String | getUIClassID() Returns the suffix used to construct the name of the look and feel (L&F) class used to render this component.
boolean | getUpdateTableInRealTime() Obsolete as of Java 2 platform v1.3.
protected void | initializeLocalVars() Initializes the local variables and properties with default values.
protected String | paramString() Returns a string representation of this JTableHeader.
void | resizeAndRepaint() Sizes the header and marks it as needing display.
void | setColumnModel(TableColumnModel columnModel) Sets the column model for this table to newModel and registers for listener notifications from the new column model.
void | setDefaultRenderer(TableCellRenderer defaultRenderer) Sets the default renderer to be used when no headerRenderer is defined by a TableColumn.
void | setDraggedColumn(TableColumn aColumn) Sets the header's draggedColumn to aColumn.
void | setDraggedDistance(int distance) Sets the header's draggedDistance to distance.
void | setReorderingAllowed(boolean reorderingAllowed) Sets whether the user can drag column headers to reorder columns.
void | setResizingAllowed(boolean resizingAllowed) Sets whether the user can resize columns by dragging between headers.
void | setResizingColumn(TableColumn aColumn) Sets the header's resizingColumn to aColumn.
void | setTable(JTable table) Sets the table associated with this header.
void | setUI(TableHeaderUI ui) Sets the look and feel (L&F) object that renders this component.
void | setUpdateTableInRealTime(boolean flag) Obsolete as of Java 2 platform v1.3.
void | updateUI() Notification from the UIManager that the look and feel (L&F) has changed.
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addPropertyChangeListener, addPropertyChangeListener, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBorder, getBounds, getClientProperty, getComponentGraphics, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getGraphics, getHeight, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPreferredSize, getPropertyChangeListeners, getPropertyChangeListeners, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isMaximumSizeSet, isMinimumSizeSet, isOpaque, isOptimizedDrawingEnabled, isPaintingTile, isPreferredSizeSet, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removePropertyChangeListener, removePropertyChangeListener, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFont, setForeground, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setFocusCycleRoot, setFocusTraversalKeys, setFocusTraversalPolicy, setLayout, transferFocusBackward, transferFocusDownCycle, validate, validateTree
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getFontMetrics, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMouseWheelListeners, getName, getParent, getPeer, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

table

protected JTable table
The table for which this object is the header; the default is null.

columnModel

protected TableColumnModel columnModel
The TableColumnModel of the table header.

reorderingAllowed

protected boolean reorderingAllowed
If true, reordering of columns are allowed by the user; the default is true.

resizingAllowed

protected boolean resizingAllowed
If true, resizing of columns are allowed by the user; the default is true.

updateTableInRealTime

protected boolean updateTableInRealTime
Obsolete as of Java 2 platform v1.3. Real time repaints, in response to column dragging or resizing, are now unconditional.

resizingColumn

protected transient TableColumn resizingColumn
The index of the column being resized. null if not resizing.

draggedColumn

protected transient TableColumn draggedColumn
The index of the column being dragged. null if not dragging.

draggedDistance

protected transient int draggedDistance
The distance from its original position the column has been dragged.

Constructor Detail

JTableHeader

public JTableHeader()
Constructs a JTableHeader with a default TableColumnModel.

See Also:
createDefaultColumnModel()

JTableHeader

public JTableHeader(TableColumnModel cm)
Constructs a JTableHeader which is initialized with cm as the column model. If cm is null this method will initialize the table header with a default TableColumnModel.

Parameters:
cm - the column model for the table
See Also:
createDefaultColumnModel()
Method Detail

setTable

public void setTable(JTable table)
Sets the table associated with this header.

Parameters:
table - the new table

getTable

public JTable getTable()
Returns the table associated with this header.

Returns:
the table property

setReorderingAllowed

public void setReorderingAllowed(boolean reorderingAllowed)
Sets whether the user can drag column headers to reorder columns.

Parameters:
reorderingAllowed - true if the table view should allow reordering; otherwise false
See Also:
getReorderingAllowed()

getReorderingAllowed

public boolean getReorderingAllowed()
Returns true if the user is allowed to rearrange columns by dragging their headers, false otherwise. The default is true. You can rearrange columns programmatically regardless of this setting.

Returns:
the reorderingAllowed property
See Also:
setReorderingAllowed(boolean)

setResizingAllowed

public void setResizingAllowed(boolean resizingAllowed)
Sets whether the user can resize columns by dragging between headers.

Parameters:
resizingAllowed - true if table view should allow resizing
See Also:
getResizingAllowed()

getResizingAllowed

public boolean getResizingAllowed()
Returns true if the user is allowed to resize columns by dragging between their headers, false otherwise. The default is true. You can resize columns programmatically regardless of this setting.

Returns:
the resizingAllowed property
See Also:
setResizingAllowed(boolean)

getDraggedColumn

public TableColumn getDraggedColumn()
Returns the the dragged column, if and only if, a drag is in process, otherwise returns null.

Returns:
the dragged column, if a drag is in process, otherwise returns null
See Also:
getDraggedDistance()

getDraggedDistance

public int getDraggedDistance()
Returns the column's horizontal distance from its original position, if and only if, a drag is in process. Otherwise, the the return value is meaningless.

Returns:
the column's horizontal distance from its original position, if a drag is in process, otherwise the return value is meaningless
See Also:
getDraggedColumn()

getResizingColumn

public TableColumn getResizingColumn()
Returns the resizing column. If no column is being resized this method returns null.

Returns:
the resizing column, if a resize is in process, otherwise returns null

setUpdateTableInRealTime

public void setUpdateTableInRealTime(boolean flag)
Obsolete as of Java 2 platform v1.3. Real time repaints, in response to column dragging or resizing, are now unconditional.

getUpdateTableInRealTime

public boolean getUpdateTableInRealTime()
Obsolete as of Java 2 platform v1.3. Real time repaints, in response to column dragging or resizing, are now unconditional.

setDefaultRenderer

public void setDefaultRenderer(TableCellRenderer defaultRenderer)
Sets the default renderer to be used when no headerRenderer is defined by a TableColumn.

Parameters:
defaultRenderer - the default renderer

getDefaultRenderer

public TableCellRenderer getDefaultRenderer()
Returns the default renderer used when no headerRenderer is defined by a TableColumn.

Returns:
the default renderer

columnAtPoint

public int columnAtPoint(Point point)
Returns the index of the column that point lies in, or -1 if it lies out of bounds.

Returns:
the index of the column that point lies in, or -1 if it lies out of bounds

getHeaderRect

public Rectangle getHeaderRect(int column)
Returns the rectangle containing the header tile at column. When the column parameter is out of bounds this method uses the same conventions as the JTable method getCellRect.

Returns:
the rectangle containing the header tile at column
See Also:
JTable.getCellRect(int, int, boolean)

getToolTipText

public String getToolTipText(MouseEvent event)
Allows the renderer's tips to be used if there is text set.

Overrides:
getToolTipText in class JComponent
Parameters:
event - the location of the event identifies the proper renderer and, therefore, the proper tip
Returns:
the tool tip for this component

getUI

public TableHeaderUI getUI()
Returns the look and feel (L&F) object that renders this component.

Returns:
the TableHeaderUI object that renders this component

setUI

public void setUI(TableHeaderUI ui)
Sets the look and feel (L&F) object that renders this component.

Parameters:
ui - the TableHeaderUI L&F object
See Also:
UIDefaults.getUI(javax.swing.JComponent)

updateUI

public void updateUI()
Notification from the UIManager that the look and feel (L&F) has changed. Replaces the current UI object with the latest version from the UIManager.

Overrides:
updateUI in class JComponent
See Also:
JComponent.updateUI()

getUIClassID

public String getUIClassID()
Returns the suffix used to construct the name of the look and feel (L&F) class used to render this component.

Overrides:
getUIClassID in class JComponent
Returns:
the string "TableHeaderUI"
See Also:
JComponent.getUIClassID(), UIDefaults.getUI(javax.swing.JComponent)

setColumnModel

public void setColumnModel(TableColumnModel columnModel)
Sets the column model for this table to newModel and registers for listener notifications from the new column model.

Parameters:
columnModel - the new data source for this table
Throws:
IllegalArgumentException - if newModel is null
See Also:
getColumnModel()

getColumnModel

public TableColumnModel getColumnModel()
Returns the TableColumnModel that contains all column information of this table header.

Returns:
the columnModel property
See Also:
setColumnModel(javax.swing.table.TableColumnModel)

columnAdded

public void columnAdded(TableColumnModelEvent e)
Invoked when a column is added to the table column model.

Application code will not use these methods explicitly, they are used internally by JTable.

Specified by:
columnAdded in interface TableColumnModelListener
Parameters:
e - the event received
See Also:
TableColumnModelListener

columnRemoved

public void columnRemoved(TableColumnModelEvent e)
Invoked when a column is removed from the table column model.

Application code will not use these methods explicitly, they are used internally by JTable.

Specified by:
columnRemoved in interface TableColumnModelListener
Parameters:
e - the event received
See Also:
TableColumnModelListener

columnMoved

public void columnMoved(TableColumnModelEvent e)
Invoked when a column is repositioned.

Application code will not use these methods explicitly, they are used internally by JTable.

Specified by:
columnMoved in interface TableColumnModelListener
Parameters:
e - the event received
See Also:
TableColumnModelListener

columnMarginChanged

public void columnMarginChanged(ChangeEvent e)
Invoked when a column is moved due to a margin change.

Application code will not use these methods explicitly, they are used internally by JTable.

Specified by:
columnMarginChanged in interface TableColumnModelListener
Parameters:
e - the event received
See Also:
TableColumnModelListener

columnSelectionChanged

public void columnSelectionChanged(ListSelectionEvent e)
Invoked when the selection model of the TableColumnModel is changed. This method currently has no effect (the header is not redrawn).

Application code will not use these methods explicitly, they are used internally by JTable.

Specified by:
columnSelectionChanged in interface TableColumnModelListener
Parameters:
e - the event received
See Also:
TableColumnModelListener

createDefaultColumnModel

protected TableColumnModel createDefaultColumnModel()
Returns the default column model object which is a DefaultTableColumnModel. A subclass can override this method to return a different column model object

Returns:
the default column model object

createDefaultRenderer

protected TableCellRenderer createDefaultRenderer()
Returns a default renderer to be used when no header renderer is defined by a TableColumn.

Returns:
the default table column renderer

initializeLocalVars

protected void initializeLocalVars()
Initializes the local variables and properties with default values. Used by the constructor methods.

resizeAndRepaint

public void resizeAndRepaint()
Sizes the header and marks it as needing display. Equivalent to revalidate followed by repaint.

setDraggedColumn

public void setDraggedColumn(TableColumn aColumn)
Sets the header's draggedColumn to aColumn.

Application code will not use this method explicitly, it is used internally by the column dragging mechanism.

Parameters:
aColumn - the column being dragged, or null if no column is being dragged

setDraggedDistance

public void setDraggedDistance(int distance)
Sets the header's draggedDistance to distance.

Parameters:
distance - the distance dragged

setResizingColumn

public void setResizingColumn(TableColumn aColumn)
Sets the header's resizingColumn to aColumn.

Application code will not use this method explicitly, it is used internally by the column sizing mechanism.

Parameters:
aColumn - the column being resized, or null if no column is being resized

paramString

protected String paramString()
Returns a string representation of this JTableHeader. This method is intended to be used only for debugging purposes, and the content and format of the returned string may vary between implementations. The returned string may be empty but may not be null.

Overriding paramString to provide information about the specific new aspects of the JFC components.

Overrides:
paramString in class JComponent
Returns:
a string representation of this JTableHeader

getAccessibleContext

public AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JTableHeader. For JTableHeaders, the AccessibleContext takes the form of an AccessibleJTableHeader. A new AccessibleJTableHeader instance is created if necessary.

Specified by:
getAccessibleContext in interface Accessible
Overrides:
getAccessibleContext in class JComponent
Returns:
an AccessibleJTableHeader that serves as the AccessibleContext of this JTableHeader
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


JTableHeader.AccessibleJTableHeader (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.table
Class JTableHeader.AccessibleJTableHeader

java.lang.Object
    extended by javax.accessibility.AccessibleContext
        extended by java.awt.Component.AccessibleAWTComponent
            extended by java.awt.Container.AccessibleAWTContainer
                extended by javax.swing.JComponent.AccessibleJComponent
                    extended by javax.swing.table.JTableHeader.AccessibleJTableHeader
All Implemented Interfaces:
AccessibleComponent, AccessibleExtendedComponent, Serializable
Enclosing class:
JTableHeader
protected class JTableHeader.AccessibleJTableHeader
extends JComponent.AccessibleJComponent

This class implements accessibility support for the JTableHeader class. It provides an implementation of the Java Accessibility API appropriate to table header user-interface elements.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Nested Class Summary
protected  class JTableHeader.AccessibleJTableHeader.AccessibleJTableHeaderEntry
This class provides an implementation of the Java Accessibility API appropropriate for JTableHeader entries.
Nested classes inherited from class javax.swing.JComponent.AccessibleJComponent
JComponent.AccessibleJComponent.AccessibleContainerHandler, JComponent.AccessibleJComponent.AccessibleFocusHandler
Nested classes inherited from class java.awt.Component.AccessibleAWTComponent
Component.AccessibleAWTComponent.AccessibleAWTComponentHandler, Component.AccessibleAWTComponent.AccessibleAWTFocusHandler
Field Summary
Fields inherited from class javax.swing.JComponent.AccessibleJComponent
accessibleContainerHandler, accessibleFocusHandler
Fields inherited from class java.awt.Component.AccessibleAWTComponent
accessibleAWTComponentHandler, accessibleAWTFocusHandler
Fields inherited from class javax.accessibility.AccessibleContext
ACCESSIBLE_ACTION_PROPERTY, ACCESSIBLE_ACTIVE_DESCENDANT_PROPERTY, ACCESSIBLE_CARET_PROPERTY, ACCESSIBLE_CHILD_PROPERTY, ACCESSIBLE_DESCRIPTION_PROPERTY, ACCESSIBLE_HYPERTEXT_OFFSET, ACCESSIBLE_NAME_PROPERTY, ACCESSIBLE_SELECTION_PROPERTY, ACCESSIBLE_STATE_PROPERTY, ACCESSIBLE_TABLE_CAPTION_CHANGED, ACCESSIBLE_TABLE_COLUMN_DESCRIPTION_CHANGED, ACCESSIBLE_TABLE_COLUMN_HEADER_CHANGED, ACCESSIBLE_TABLE_MODEL_CHANGED, ACCESSIBLE_TABLE_ROW_DESCRIPTION_CHANGED, ACCESSIBLE_TABLE_ROW_HEADER_CHANGED, ACCESSIBLE_TABLE_SUMMARY_CHANGED, ACCESSIBLE_TEXT_PROPERTY, ACCESSIBLE_VALUE_PROPERTY, ACCESSIBLE_VISIBLE_DATA_PROPERTY, accessibleDescription, accessibleName, accessibleParent
Constructor Summary
protected JTableHeader.AccessibleJTableHeader()
Method Summary
Accessible | getAccessibleAt(Point p) Returns the Accessible child, if one exists, contained at the local coordinate Point.
Accessible | getAccessibleChild(int i) Return the nth Accessible child of the object.
int | getAccessibleChildrenCount() Returns the number of accessible children in the object.
AccessibleRole | getAccessibleRole() Get the role of this object.
Methods inherited from class javax.swing.JComponent.AccessibleJComponent
addPropertyChangeListener, getAccessibleDescription, getAccessibleKeyBinding, getAccessibleName, getAccessibleStateSet, getBorderTitle, getTitledBorderText, getToolTipText, removePropertyChangeListener
Methods inherited from class java.awt.Component.AccessibleAWTComponent
addFocusListener, contains, getAccessibleComponent, getAccessibleIndexInParent, getAccessibleParent, getBackground, getBounds, getCursor, getFont, getFontMetrics, getForeground, getLocale, getLocation, getLocationOnScreen, getSize, isEnabled, isFocusTraversable, isShowing, isVisible, removeFocusListener, requestFocus, setBackground, setBounds, setCursor, setEnabled, setFont, setForeground, setLocation, setSize, setVisible
Methods inherited from class javax.accessibility.AccessibleContext
firePropertyChange, getAccessibleAction, getAccessibleEditableText, getAccessibleIcon, getAccessibleRelationSet, getAccessibleSelection, getAccessibleTable, getAccessibleText, getAccessibleValue, setAccessibleDescription, setAccessibleName, setAccessibleParent
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Methods inherited from interface javax.accessibility.AccessibleComponent
addFocusListener, contains, getBackground, getBounds, getCursor, getFont, getFontMetrics, getForeground, getLocation, getLocationOnScreen, getSize, isEnabled, isFocusTraversable, isShowing, isVisible, removeFocusListener, requestFocus, setBackground, setBounds, setCursor, setEnabled, setFont, setForeground, setLocation, setSize, setVisible

Constructor Detail

JTableHeader.AccessibleJTableHeader

protected JTableHeader.AccessibleJTableHeader()
Method Detail

getAccessibleRole

public AccessibleRole getAccessibleRole()
Get the role of this object.

Overrides:
getAccessibleRole in class JComponent.AccessibleJComponent
Returns:
an instance of AccessibleRole describing the role of the object
See Also:
AccessibleRole

getAccessibleAt

public Accessible getAccessibleAt(Point p)
Returns the Accessible child, if one exists, contained at the local coordinate Point.

Specified by:
getAccessibleAt in interface AccessibleComponent
Overrides:
getAccessibleAt in class Container.AccessibleAWTContainer
Parameters:
p - The point defining the top-left corner of the Accessible, given in the coordinate space of the object's parent.
Returns:
the Accessible, if it exists, at the specified location; else null

getAccessibleChildrenCount

public int getAccessibleChildrenCount()
Returns the number of accessible children in the object. If all of the children of this object implement Accessible, than this method should return the number of children of this object.

Overrides:
getAccessibleChildrenCount in class JComponent.AccessibleJComponent
Returns:
the number of accessible children in the object.

getAccessibleChild

public Accessible getAccessibleChild(int i)
Return the nth Accessible child of the object.

Overrides:
getAccessibleChild in class JComponent.AccessibleJComponent
Parameters:
i - zero-based index of child
Returns:
the nth Accessible child of the object
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


JTableHeader.AccessibleJTableHeader.AccessibleJTableHeaderEntry (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.table
Class JTableHeader.AccessibleJTableHeader.AccessibleJTableHeaderEntry

java.lang.Object
    extended by javax.accessibility.AccessibleContext
        extended by javax.swing.table.JTableHeader.AccessibleJTableHeader.AccessibleJTableHeaderEntry
All Implemented Interfaces:
Accessible, AccessibleComponent
Enclosing class:
JTableHeader.AccessibleJTableHeader
protected class JTableHeader.AccessibleJTableHeader.AccessibleJTableHeaderEntry
extends AccessibleContext
implements Accessible, AccessibleComponent

This class provides an implementation of the Java Accessibility API appropropriate for JTableHeader entries.

Field Summary
Fields inherited from class javax.accessibility.AccessibleContext
ACCESSIBLE_ACTION_PROPERTY, ACCESSIBLE_ACTIVE_DESCENDANT_PROPERTY, ACCESSIBLE_CARET_PROPERTY, ACCESSIBLE_CHILD_PROPERTY, ACCESSIBLE_DESCRIPTION_PROPERTY, ACCESSIBLE_HYPERTEXT_OFFSET, ACCESSIBLE_NAME_PROPERTY, ACCESSIBLE_SELECTION_PROPERTY, ACCESSIBLE_STATE_PROPERTY, ACCESSIBLE_TABLE_CAPTION_CHANGED, ACCESSIBLE_TABLE_COLUMN_DESCRIPTION_CHANGED, ACCESSIBLE_TABLE_COLUMN_HEADER_CHANGED, ACCESSIBLE_TABLE_MODEL_CHANGED, ACCESSIBLE_TABLE_ROW_DESCRIPTION_CHANGED, ACCESSIBLE_TABLE_ROW_HEADER_CHANGED, ACCESSIBLE_TABLE_SUMMARY_CHANGED, ACCESSIBLE_TEXT_PROPERTY, ACCESSIBLE_VALUE_PROPERTY, ACCESSIBLE_VISIBLE_DATA_PROPERTY, accessibleDescription, accessibleName, accessibleParent
Constructor Summary
JTableHeader.AccessibleJTableHeader.AccessibleJTableHeaderEntry(int c, JTableHeader p, JTable t)
Constructs an AccessiblJTableHeaaderEntry
Method Summary
void | addFocusListener(FocusListener l) Adds the specified focus listener to receive focus events from this component.
void | addPropertyChangeListener(PropertyChangeListener l) Adds a PropertyChangeListener to the listener list.
boolean | contains(Point p) Checks whether the specified point is within this object's bounds, where the point's x and y coordinates are defined to be relative to the coordinate system of the object.
AccessibleAction | getAccessibleAction() Gets the AccessibleAction associated with this object that supports one or more actions.
Accessible | getAccessibleAt(Point p) Returns the Accessible child, if one exists, contained at the local coordinate Point.
Accessible | getAccessibleChild(int i) Returns the specified Accessible child of the object.
int | getAccessibleChildrenCount() Returns the number of accessible children of the object.
AccessibleComponent | getAccessibleComponent() Get the AccessibleComponent associated with this object.
AccessibleContext | getAccessibleContext() Get the AccessibleContext associated with this object.
String | getAccessibleDescription() Gets the accessibleDescription property of this object.
int | getAccessibleIndexInParent() Gets the 0-based index of this object in its accessible parent.
String | getAccessibleName() Gets the accessibleName property of this object.
AccessibleRole | getAccessibleRole() Gets the role of this object.
AccessibleSelection | getAccessibleSelection() Gets the AccessibleSelection associated with this object which allows its Accessible children to be selected.
AccessibleStateSet | getAccessibleStateSet() Gets the state set of this object.
AccessibleText | getAccessibleText() Gets the AccessibleText associated with this object presenting text on the display.
AccessibleValue | getAccessibleValue() Gets the AccessibleValue associated with this object that supports a Numerical value.
Color | getBackground() Gets the background color of this object.
Rectangle | getBounds() Gets the bounds of this object in the form of a Rectangle object.
Cursor | getCursor() Gets the Cursor of this object.
Font | getFont() Gets the Font of this object.
FontMetrics | getFontMetrics(Font f) Gets the FontMetrics of this object.
Color | getForeground() Gets the foreground color of this object.
Locale | getLocale() Gets the locale of the component.
Point | getLocation() Gets the location of the object relative to the parent in the form of a point specifying the object's top-left corner in the screen's coordinate space.
Point | getLocationOnScreen() Returns the location of the object on the screen.
Dimension | getSize() Returns the size of this object in the form of a Dimension object.
boolean | isEnabled() Determines if the object is enabled.
boolean | isFocusTraversable() Returns whether this object can accept focus or not.
boolean | isShowing() Determines if the object is showing.
boolean | isVisible() Determines if the object is visible.
void | removeFocusListener(FocusListener l) Removes the specified focus listener so it no longer receives focus events from this component.
void | removePropertyChangeListener(PropertyChangeListener l) Removes a PropertyChangeListener from the listener list.
void | requestFocus() Requests focus for this object.
void | setAccessibleDescription(String s) Sets the accessible description of this object.
void | setAccessibleName(String s) Sets the localized accessible name of this object.
void | setBackground(Color c) Sets the background color of this object.
void | setBounds(Rectangle r) Sets the bounds of this object in the form of a Rectangle object.
void | setCursor(Cursor c) Sets the Cursor of this object.
void | setEnabled(boolean b) Sets the enabled state of the object.
void | setFont(Font f) Sets the Font of this object.
void | setForeground(Color c) Sets the foreground color of this object.
void | setLocation(Point p) Sets the location of the object relative to the parent.
void | setSize(Dimension d) Resizes this object so that it has width and height.
void | setVisible(boolean b) Sets the visible state of the object.
Methods inherited from class javax.accessibility.AccessibleContext
firePropertyChange, getAccessibleEditableText, getAccessibleIcon, getAccessibleParent, getAccessibleRelationSet, getAccessibleTable, setAccessibleParent
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

JTableHeader.AccessibleJTableHeader.AccessibleJTableHeaderEntry

public JTableHeader.AccessibleJTableHeader.AccessibleJTableHeaderEntry(int c,
                                                                       JTableHeader p,
                                                                       JTable t)
Constructs an AccessiblJTableHeaaderEntry

Method Detail

getAccessibleContext

public AccessibleContext getAccessibleContext()
Get the AccessibleContext associated with this object. In the implementation of the Java Accessibility API for this class, returns this object, which serves as its own AccessibleContext.

Specified by:
getAccessibleContext in interface Accessible
Returns:
this object

getAccessibleName

public String getAccessibleName()
Description copied from class: AccessibleContext
Gets the accessibleName property of this object. The accessibleName property of an object is a localized String that designates the purpose of the object. For example, the accessibleName property of a label or button might be the text of the label or button itself. In the case of an object that doesn't display its name, the accessibleName should still be set. For example, in the case of a text field used to enter the name of a city, the accessibleName for the en_US locale could be 'city.'

Overrides:
getAccessibleName in class AccessibleContext
Returns:
the localized name of the object; null if this object does not have a name
See Also:
AccessibleContext.setAccessibleName(java.lang.String)

setAccessibleName

public void setAccessibleName(String s)
Description copied from class: AccessibleContext
Sets the localized accessible name of this object. Changing the name will cause a PropertyChangeEvent to be fired for the ACCESSIBLE_NAME_PROPERTY property.

Overrides:
setAccessibleName in class AccessibleContext
Parameters:
s - the new localized name of the object.
See Also:
AccessibleContext.getAccessibleName(), AccessibleContext.addPropertyChangeListener(java.beans.PropertyChangeListener)

getAccessibleDescription

public String getAccessibleDescription()
Description copied from class: AccessibleContext
Gets the accessibleDescription property of this object. The accessibleDescription property of this object is a short localized phrase describing the purpose of the object. For example, in the case of a 'Cancel' button, the accessibleDescription could be 'Ignore changes and close dialog box.'

Overrides:
getAccessibleDescription in class AccessibleContext
Returns:
the localized description of the object; null if this object does not have a description
See Also:
AccessibleContext.setAccessibleDescription(java.lang.String)

setAccessibleDescription

public void setAccessibleDescription(String s)
Description copied from class: AccessibleContext
Sets the accessible description of this object. Changing the name will cause a PropertyChangeEvent to be fired for the ACCESSIBLE_DESCRIPTION_PROPERTY property.

Overrides:
setAccessibleDescription in class AccessibleContext
Parameters:
s - the new localized description of the object
See Also:
AccessibleContext.setAccessibleName(java.lang.String), AccessibleContext.addPropertyChangeListener(java.beans.PropertyChangeListener)

getAccessibleRole

public AccessibleRole getAccessibleRole()
Description copied from class: AccessibleContext
Gets the role of this object. The role of the object is the generic purpose or use of the class of this object. For example, the role of a push button is AccessibleRole.PUSH_BUTTON. The roles in AccessibleRole are provided so component developers can pick from a set of predefined roles. This enables assistive technologies to provide a consistent interface to various tweaked subclasses of components (e.g., use AccessibleRole.PUSH_BUTTON for all components that act like a push button) as well as distinguish between sublasses that behave differently (e.g., AccessibleRole.CHECK_BOX for check boxes and AccessibleRole.RADIO_BUTTON for radio buttons).

Note that the AccessibleRole class is also extensible, so custom component developers can define their own AccessibleRole's if the set of predefined roles is inadequate.

Specified by:
getAccessibleRole in class AccessibleContext
Returns:
an instance of AccessibleRole describing the role of the object
See Also:
AccessibleRole

getAccessibleStateSet

public AccessibleStateSet getAccessibleStateSet()
Description copied from class: AccessibleContext
Gets the state set of this object. The AccessibleStateSet of an object is composed of a set of unique AccessibleStates. A change in the AccessibleStateSet of an object will cause a PropertyChangeEvent to be fired for the ACCESSIBLE_STATE_PROPERTY property.

Specified by:
getAccessibleStateSet in class AccessibleContext
Returns:
an instance of AccessibleStateSet containing the current state set of the object
See Also:
AccessibleStateSet, AccessibleState, AccessibleContext.addPropertyChangeListener(java.beans.PropertyChangeListener)

getAccessibleIndexInParent

public int getAccessibleIndexInParent()
Description copied from class: AccessibleContext
Gets the 0-based index of this object in its accessible parent.

Specified by:
getAccessibleIndexInParent in class AccessibleContext
Returns:
the 0-based index of this object in its parent; -1 if this object does not have an accessible parent.
See Also:
AccessibleContext.getAccessibleParent(),
AccessibleContext.getAccessibleChildrenCount(),
AccessibleContext.getAccessibleChild(int)

getAccessibleChildrenCount

public int getAccessibleChildrenCount()
Description copied from class: AccessibleContext
Returns the number of accessible children of the object.

Specified by:
getAccessibleChildrenCount in class AccessibleContext
Returns:
the number of accessible children of the object.

getAccessibleChild

public Accessible getAccessibleChild(int i)
Description copied from class: AccessibleContext
Returns the specified Accessible child of the object. The Accessible children of an Accessible object are zero-based, so the first child of an Accessible child is at index 0, the second child is at index 1, and so on.

Specified by:
getAccessibleChild in class AccessibleContext
Parameters:
i - zero-based index of child
Returns:
the Accessible child of the object
See Also:
AccessibleContext.getAccessibleChildrenCount()

getLocale

public Locale getLocale()
Description copied from class: AccessibleContext
Gets the locale of the component. If the component does not have a locale, then the locale of its parent is returned.

Specified by:
getLocale in class AccessibleContext
Returns:
this component's locale. If this component does not have a locale, the locale of its parent is returned.

addPropertyChangeListener

public void addPropertyChangeListener(PropertyChangeListener l)
Description copied from class: AccessibleContext
Adds a PropertyChangeListener to the listener list. The listener is registered for all Accessible properties and will be called when those properties change.

Overrides:
addPropertyChangeListener in class AccessibleContext
Parameters:
l - The PropertyChangeListener to be added
See Also:
AccessibleContext.ACCESSIBLE_NAME_PROPERTY, AccessibleContext.ACCESSIBLE_DESCRIPTION_PROPERTY, AccessibleContext.ACCESSIBLE_STATE_PROPERTY, AccessibleContext.ACCESSIBLE_VALUE_PROPERTY, AccessibleContext.ACCESSIBLE_SELECTION_PROPERTY, AccessibleContext.ACCESSIBLE_TEXT_PROPERTY, AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY

removePropertyChangeListener

public void removePropertyChangeListener(PropertyChangeListener l)
Description copied from class: AccessibleContext
Removes a PropertyChangeListener from the listener list. This removes a PropertyChangeListener that was registered for all properties.

Overrides:
removePropertyChangeListener in class AccessibleContext
Parameters:
l - The PropertyChangeListener to be removed

getAccessibleAction

public AccessibleAction getAccessibleAction()
Description copied from class: AccessibleContext
Gets the AccessibleAction associated with this object that supports one or more actions.

Overrides:
getAccessibleAction in class AccessibleContext
Returns:
AccessibleAction if supported by object; else return null
See Also:
AccessibleAction

getAccessibleComponent

public AccessibleComponent getAccessibleComponent()
Get the AccessibleComponent associated with this object. In the implementation of the Java Accessibility API for this class, return this object, which is responsible for implementing the AccessibleComponent interface on behalf of itself.

Overrides:
getAccessibleComponent in class AccessibleContext
Returns:
this object
See Also:
AccessibleComponent

getAccessibleSelection

public AccessibleSelection getAccessibleSelection()
Description copied from class: AccessibleContext
Gets the AccessibleSelection associated with this object which allows its Accessible children to be selected.

Overrides:
getAccessibleSelection in class AccessibleContext
Returns:
AccessibleSelection if supported by object; else return null
See Also:
AccessibleSelection

getAccessibleText

public AccessibleText getAccessibleText()
Description copied from class: AccessibleContext
Gets the AccessibleText associated with this object presenting text on the display.

Overrides:
getAccessibleText in class AccessibleContext
Returns:
AccessibleText if supported by object; else return null
See Also:
AccessibleText

getAccessibleValue

public AccessibleValue getAccessibleValue()
Description copied from class: AccessibleContext
Gets the AccessibleValue associated with this object that supports a Numerical value.

Overrides:
getAccessibleValue in class AccessibleContext
Returns:
AccessibleValue if supported by object; else return null
See Also:
AccessibleValue

getBackground

public Color getBackground()
Description copied from interface: AccessibleComponent
Gets the background color of this object.

Specified by:
getBackground in interface AccessibleComponent
Returns:
the background color, if supported, of the object; otherwise, null
See Also:
AccessibleComponent.setBackground(java.awt.Color)

setBackground

public void setBackground(Color c)
Description copied from interface: AccessibleComponent
Sets the background color of this object.

Specified by:
setBackground in interface AccessibleComponent
Parameters:
c - the new Color for the background
See Also:
AccessibleComponent.setBackground(java.awt.Color)

getForeground

public Color getForeground()
Description copied from interface: AccessibleComponent
Gets the foreground color of this object.

Specified by:
getForeground in interface AccessibleComponent
Returns:
the foreground color, if supported, of the object; otherwise, null
See Also:
AccessibleComponent.setForeground(java.awt.Color)

setForeground

public void setForeground(Color c)
Description copied from interface: AccessibleComponent
Sets the foreground color of this object.

Specified by:
setForeground in interface AccessibleComponent
Parameters:
c - the new Color for the foreground
See Also:
AccessibleComponent.getForeground()

getCursor

public Cursor getCursor()
Description copied from interface: AccessibleComponent
Gets the Cursor of this object.

Specified by:
getCursor in interface AccessibleComponent
Returns:
the Cursor, if supported, of the object; otherwise, null
See Also:
AccessibleComponent.setCursor(java.awt.Cursor)

setCursor

public void setCursor(Cursor c)
Description copied from interface: AccessibleComponent
Sets the Cursor of this object.

Specified by:
setCursor in interface AccessibleComponent
Parameters:
c - the new Cursor for the object
See Also:
AccessibleComponent.getCursor()

getFont

public Font getFont()
Description copied from interface: AccessibleComponent
Gets the Font of this object.

Specified by:
getFont in interface AccessibleComponent
Returns:
the Font,if supported, for the object; otherwise, null
See Also:
AccessibleComponent.setFont(java.awt.Font)

setFont

public void setFont(Font f)
Description copied from interface: AccessibleComponent
Sets the Font of this object.

Specified by:
setFont in interface AccessibleComponent
Parameters:
f - the new Font for the object
See Also:
AccessibleComponent.getFont()

getFontMetrics

public FontMetrics getFontMetrics(Font f)
Description copied from interface: AccessibleComponent
Gets the FontMetrics of this object.

Specified by:
getFontMetrics in interface AccessibleComponent
Parameters:
f - the Font
Returns:
the FontMetrics, if supported, the object; otherwise, null
See Also:
AccessibleComponent.getFont()

isEnabled

public boolean isEnabled()
Description copied from interface: AccessibleComponent
Determines if the object is enabled. Objects that are enabled will also have the AccessibleState.ENABLED state set in their AccessibleStateSets.

Specified by:
isEnabled in interface AccessibleComponent
Returns:
true if object is enabled; otherwise, false
See Also:
AccessibleComponent.setEnabled(boolean), AccessibleContext.getAccessibleStateSet(), AccessibleState.ENABLED, AccessibleStateSet

setEnabled

public void setEnabled(boolean b)
Description copied from interface: AccessibleComponent
Sets the enabled state of the object.

Specified by:
setEnabled in interface AccessibleComponent
Parameters:
b - if true, enables this object; otherwise, disables it
See Also:
AccessibleComponent.isEnabled()

isVisible

public boolean isVisible()
Description copied from interface: AccessibleComponent
Determines if the object is visible. Note: this means that the object intends to be visible; however, it may not be showing on the screen because one of the objects that this object is contained by is currently not visible. To determine if an object is showing on the screen, use isShowing().

Objects that are visible will also have the AccessibleState.VISIBLE state set in their AccessibleStateSets.

Specified by:
isVisible in interface AccessibleComponent
Returns:
true if object is visible; otherwise, false
See Also:
AccessibleComponent.setVisible(boolean), AccessibleContext.getAccessibleStateSet(), AccessibleState.VISIBLE, AccessibleStateSet

setVisible

public void setVisible(boolean b)
Description copied from interface: AccessibleComponent
Sets the visible state of the object.

Specified by:
setVisible in interface AccessibleComponent
Parameters:
b - if true, shows this object; otherwise, hides it
See Also:
AccessibleComponent.isVisible()

isShowing

public boolean isShowing()
Description copied from interface: AccessibleComponent
Determines if the object is showing. This is determined by checking the visibility of the object and its ancestors. Note: this will return true even if the object is obscured by another (for example, it is underneath a menu that was pulled down).

Specified by:
isShowing in interface AccessibleComponent
Returns:
true if object is showing; otherwise, false

contains

public boolean contains(Point p)
Description copied from interface: AccessibleComponent
Checks whether the specified point is within this object's bounds, where the point's x and y coordinates are defined to be relative to the coordinate system of the object.

Specified by:
contains in interface AccessibleComponent
Parameters:
p - the Point relative to the coordinate system of the object
Returns:
true if object contains Point; otherwise false
See Also:
AccessibleComponent.getBounds()

getLocationOnScreen

public Point getLocationOnScreen()
Description copied from interface: AccessibleComponent
Returns the location of the object on the screen.

Specified by:
getLocationOnScreen in interface AccessibleComponent
Returns:
the location of the object on screen; null if this object is not on the screen
See Also:
AccessibleComponent.getBounds(), AccessibleComponent.getLocation()

getLocation

public Point getLocation()
Description copied from interface: AccessibleComponent
Gets the location of the object relative to the parent in the form of a point specifying the object's top-left corner in the screen's coordinate space.

Specified by:
getLocation in interface AccessibleComponent
Returns:
An instance of Point representing the top-left corner of the object's bounds in the coordinate space of the screen; null if this object or its parent are not on the screen
See Also:
AccessibleComponent.getBounds(), AccessibleComponent.getLocationOnScreen()

setLocation

public void setLocation(Point p)
Description copied from interface: AccessibleComponent
Sets the location of the object relative to the parent.

Specified by:
setLocation in interface AccessibleComponent
Parameters:
p - the new position for the top-left corner
See Also:
AccessibleComponent.getLocation()

getBounds

public Rectangle getBounds()
Description copied from interface: AccessibleComponent
Gets the bounds of this object in the form of a Rectangle object. The bounds specify this object's width, height, and location relative to its parent.

Specified by:
getBounds in interface AccessibleComponent
Returns:
A rectangle indicating this component's bounds; null if this object is not on the screen.
See Also:
AccessibleComponent.contains(java.awt.Point)

setBounds

public void setBounds(Rectangle r)
Description copied from interface: AccessibleComponent
Sets the bounds of this object in the form of a Rectangle object. The bounds specify this object's width, height, and location relative to its parent.

Specified by:
setBounds in interface AccessibleComponent
Parameters:
r - rectangle indicating this component's bounds
See Also:
AccessibleComponent.getBounds()

getSize

public Dimension getSize()
Description copied from interface: AccessibleComponent
Returns the size of this object in the form of a Dimension object. The height field of the Dimension object contains this object's height, and the width field of the Dimension object contains this object's width.

Specified by:
getSize in interface AccessibleComponent
Returns:
A Dimension object that indicates the size of this component; null if this object is not on the screen
See Also:
AccessibleComponent.setSize(java.awt.Dimension)

setSize

public void setSize(Dimension d)
Description copied from interface: AccessibleComponent
Resizes this object so that it has width and height.

Specified by:
setSize in interface AccessibleComponent
Parameters:
d - The dimension specifying the new size of the object.
See Also:
AccessibleComponent.getSize()

getAccessibleAt

public Accessible getAccessibleAt(Point p)
Description copied from interface: AccessibleComponent
Returns the Accessible child, if one exists, contained at the local coordinate Point.

Specified by:
getAccessibleAt in interface AccessibleComponent
Parameters:
p - The point relative to the coordinate system of this object.
Returns:
the Accessible, if it exists, at the specified location; otherwise null

isFocusTraversable

public boolean isFocusTraversable()
Description copied from interface: AccessibleComponent
Returns whether this object can accept focus or not. Objects that can accept focus will also have the AccessibleState.FOCUSABLE state set in their AccessibleStateSets.

Specified by:
isFocusTraversable in interface AccessibleComponent
Returns:
true if object can accept focus; otherwise false
See Also:
AccessibleContext.getAccessibleStateSet(), AccessibleState.FOCUSABLE, AccessibleState.FOCUSED, AccessibleStateSet

requestFocus

public void requestFocus()
Description copied from interface: AccessibleComponent
Requests focus for this object. If this object cannot accept focus, nothing will happen. Otherwise, the object will attempt to take focus.

Specified by:
requestFocus in interface AccessibleComponent
See Also:
AccessibleComponent.isFocusTraversable()

addFocusListener

public void addFocusListener(FocusListener l)
Description copied from interface: AccessibleComponent
Adds the specified focus listener to receive focus events from this component.

Specified by:
addFocusListener in interface AccessibleComponent
Parameters:
l - the focus listener
See Also:
AccessibleComponent.removeFocusListener(java.awt.event.FocusListener)

removeFocusListener

public void removeFocusListener(FocusListener l)
Description copied from interface: AccessibleComponent
Removes the specified focus listener so it no longer receives focus events from this component.

Specified by:
removeFocusListener in interface AccessibleComponent
Parameters:
l - the focus listener
See Also:
AccessibleComponent.addFocusListener(java.awt.event.FocusListener)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


javax.swing.table (Java 2 Platform SE v1.4.2)

 javax.swing.table
Interfaces
TableCellEditor
TableCellRenderer
TableColumnModel
TableModel
Classes
AbstractTableModel
DefaultTableCellRenderer
DefaultTableCellRenderer.UIResource
DefaultTableColumnModel
DefaultTableModel
JTableHeader
TableColumn


javax.swing.table (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package javax.swing.table

Provides classes and interfaces for dealing with javax.swing.JTable.

See:
Description

Interface Summary
TableCellEditor | 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 | This interface defines the method required by any object that would like to be a renderer for cells in a JTable.
TableColumnModel | Defines the requirements for a table column model object suitable for use with JTable.
TableModel | The TableModel interface specifies the methods the JTable will use to interrogate a tabular data model.

Class Summary
AbstractTableModel | This abstract class provides default implementations for most of the methods in the TableModel interface.
DefaultTableCellRenderer | The standard class for rendering (displaying) individual cells in a JTable.
DefaultTableCellRenderer.UIResource | A subclass of DefaultTableCellRenderer that implements UIResource.
DefaultTableColumnModel | The standard column-handler for a JTable.
DefaultTableModel | This is an implementation of TableModel that uses a Vector of Vectors to store the cell value objects.
JTableHeader | This is the object which manages the header of the JTable.
TableColumn | A TableColumn represents all the attributes of a column in a JTable, such as width, resizibility, minimum and maximum width.

Package javax.swing.table Description

Provides classes and interfaces for dealing with javax.swing.JTable. JTable is Swing's grid or tabular view for constructing user interfaces for tabular data structures inside an application. Use this package if you want control over how tables are constructed, updated, and rendered, as well as how data associated with the tables are viewed and managed.

Note: Most of the Swing API is not thread safe. For details, see Threads and Swing, a section in The Java Tutorial.

Related Documentation

For overviews, tutorials, examples, guides, and tool documentation, please see:
  • How to Use Tables, a section in The Java Tutorial

Since:
1.2
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


javax.swing.table Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package javax.swing.table

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class javax.swing.table.AbstractTableModel (implements java.io.Serializable, javax.swing.table.TableModel)
      • class javax.swing.table.DefaultTableModel (implements java.io.Serializable)
    • class javax.accessibility.AccessibleContext
      • class java.awt.Component.AccessibleAWTComponent (implements javax.accessibility.AccessibleComponent, java.io.Serializable)
        • class java.awt.Container.AccessibleAWTContainer
          • class javax.swing.JComponent.AccessibleJComponent (implements javax.accessibility.AccessibleExtendedComponent)
            • class javax.swing.table.JTableHeader.AccessibleJTableHeader
      • class javax.swing.table.JTableHeader.AccessibleJTableHeader.AccessibleJTableHeaderEntry (implements javax.accessibility.Accessible, javax.accessibility.AccessibleComponent)
    • class java.awt.Component (implements java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable)
      • class java.awt.Container
        • class javax.swing.JComponent (implements java.io.Serializable)
          • class javax.swing.JLabel (implements javax.accessibility.Accessible, javax.swing.SwingConstants)
            • class javax.swing.table.DefaultTableCellRenderer (implements java.io.Serializable, javax.swing.table.TableCellRenderer)
              • class javax.swing.table.DefaultTableCellRenderer.UIResource (implements javax.swing.plaf.UIResource)
          • class javax.swing.table.JTableHeader (implements javax.accessibility.Accessible, javax.swing.event.TableColumnModelListener)
    • class javax.swing.table.DefaultTableColumnModel (implements javax.swing.event.ListSelectionListener, java.beans.PropertyChangeListener, java.io.Serializable, javax.swing.table.TableColumnModel)
    • class javax.swing.table.TableColumn (implements java.io.Serializable)

Interface Hierarchy

  • interface javax.swing.CellEditor
    • interface javax.swing.table.TableCellEditor
  • interface javax.swing.table.TableCellRenderer
  • interface javax.swing.table.TableColumnModel
  • interface javax.swing.table.TableModel
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package javax.swing.table (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
javax.swing.table

Packages that use javax.swing.table
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.event | Provides for events fired by Swing components.
javax.swing.plaf.basic | Provides user interface objects built according to the Basic look and feel.
javax.swing.table | Provides classes and interfaces for dealing with javax.swing.JTable.

Classes in javax.swing.table used by javax.swing
JTableHeader
This is the object which manages the header of the JTable.
TableCellEditor
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
This interface defines the method required by any object that would like to be a renderer for cells in a JTable.
TableColumn
A TableColumn represents all the attributes of a column in a JTable, such as width, resizibility, minimum and maximum width.
TableColumnModel
Defines the requirements for a table column model object suitable for use with JTable.
TableModel
The TableModel interface specifies the methods the JTable will use to interrogate a tabular data model.

Classes in javax.swing.table used by javax.swing.event
TableColumnModel
Defines the requirements for a table column model object suitable for use with JTable.
TableModel
The TableModel interface specifies the methods the JTable will use to interrogate a tabular data model.

Classes in javax.swing.table used by javax.swing.plaf.basic
JTableHeader
This is the object which manages the header of the JTable.

Classes in javax.swing.table used by javax.swing.table
AbstractTableModel
This abstract class provides default implementations for most of the methods in the TableModel interface.
DefaultTableCellRenderer
The standard class for rendering (displaying) individual cells in a JTable.
JTableHeader
This is the object which manages the header of the JTable.
TableCellEditor
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
This interface defines the method required by any object that would like to be a renderer for cells in a JTable.
TableColumn
A TableColumn represents all the attributes of a column in a JTable, such as width, resizibility, minimum and maximum width.
TableColumnModel
Defines the requirements for a table column model object suitable for use with JTable.
TableModel
The TableModel interface specifies the methods the JTable will use to interrogate a tabular data model.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


TableCellEditor (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.swing.table
Interface TableCellEditor

All Superinterfaces:
CellEditor
All Known Implementing Classes:
DefaultCellEditor
public interface TableCellEditor
extends CellEditor

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.

Method Summary
 Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
Sets an initial value for the editor.
Methods inherited from interface javax.swing.CellEditor
addCellEditorListener, cancelCellEditing, getCellEditorValue, isCellEditable, removeCellEditorListener, shouldSelectCell, stopCellEditing

Method Detail

getTableCellEditorComponent

public Component getTableCellEditorComponent(JTable table,
                                             Object value,
                                             boolean isSelected,
                                             int row,
                                             int column)
Sets an initial value for the editor. This will cause the editor to stopEditing and lose any partially edited value if the editor is editing when this method is called.

Returns the component that should be added to the client's Component hierarchy. Once installed in the client's hierarchy this component will then be able to draw and receive user input.

Parameters:
table - the JTable that is asking the editor to edit; can be null
value - the value of the cell to be edited; it is up to the specific editor to interpret and draw the value. For example, if value is the string "true", it could be rendered as a string or it could be rendered as a check box that is checked. null is a valid value
isSelected - true if the cell is to be rendered with highlighting
row - the row of the cell being edited
column - the column of the cell being edited
Returns:
the component for editing
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


TableCellRenderer (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.table
Interface TableCellRenderer

All Known Implementing Classes:
DefaultTableCellRenderer
public interface TableCellRenderer

This interface defines the method required by any object that would like to be a renderer for cells in a JTable.

Method Summary
 Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
Returns the component used for drawing the cell.

Method Detail

getTableCellRendererComponent

public Component getTableCellRendererComponent(JTable table,
                                               Object value,
                                               boolean isSelected,
                                               boolean hasFocus,
                                               int row,
                                               int column)
Returns the component used for drawing the cell. This method is used to configure the renderer appropriately before drawing.

Parameters:
table - the JTable that is asking the renderer to draw; can be null
value - the value of the cell to be rendered. It is up to the specific renderer to interpret and draw the value. For example, if value is the string "true", it could be rendered as a string or it could be rendered as a check box that is checked. null is a valid value
isSelected - true if the cell is to be rendered with the selection highlighted; otherwise false
hasFocus - if true, render cell appropriately. For example, put a special border on the cell, if the cell can be edited, render in the color used to indicate editing
row - the row index of the cell being drawn. When drawing the header, the value of row is -1
column - the column index of the cell being drawn
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TableColumn (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.swing.table
Class TableColumn

java.lang.Object
    extended by javax.swing.table.TableColumn
All Implemented Interfaces:
Serializable
public class TableColumn
extends Object
implements Serializable

A TableColumn represents all the attributes of a column in a JTable, such as width, resizibility, minimum and maximum width. In addition, the TableColumn provides slots for a renderer and an editor that can be used to display and edit the values in this column.

It is also possible to specify renderers and editors on a per type basis rather than a per column basis - see the setDefaultRenderer method in the JTable class. This default mechanism is only used when the renderer (or editor) in the TableColumn is null.

The TableColumn stores the link between the columns in the JTable and the columns in the TableModel. The modelIndex is the column in the TableModel, which will be queried for the data values for the cells in this column. As the column moves around in the view this modelIndex does not change.

Note: Some implementations may assume that all TableColumnModels are unique, therefore we would recommend that the same TableColumn instance not be added more than once to a TableColumnModel. To show TableColumns with the same column of data from the model, create a new instance with the same modelIndex.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

See Also:
TableColumnModel,
DefaultTableColumnModel,
JTableHeader.getDefaultRenderer(),
JTable.getDefaultRenderer(Class),
JTable.getDefaultEditor(Class),
JTable.getCellRenderer(int, int),
JTable.getCellEditor(int, int)

Field Summary
static String | CELL_RENDERER_PROPERTY Obsolete as of Java 2 platform v1.3.
protected TableCellEditor | cellEditor The editor used to edit the data cells of the column.
protected TableCellRenderer | cellRenderer The renderer used to draw the data cells of the column.
static String | COLUMN_WIDTH_PROPERTY Obsolete as of Java 2 platform v1.3.
static String | HEADER_RENDERER_PROPERTY Obsolete as of Java 2 platform v1.3.
static String | HEADER_VALUE_PROPERTY Obsolete as of Java 2 platform v1.3.
protected TableCellRenderer | headerRenderer The renderer used to draw the header of the column.
protected Object | headerValue The header value of the column.
protected Object | identifier This object is not used internally by the drawing machinery of the JTable; identifiers may be set in the TableColumn as as an optional way to tag and locate table columns.
protected boolean | isResizable If true, the user is allowed to resize the column; the default is true.
protected int | maxWidth The maximum width of the column.
protected int | minWidth The minimum width of the column.
protected int | modelIndex The index of the column in the model which is to be displayed by this TableColumn.
protected int | resizedPostingDisableCount Deprecated. as of Java 2 platform v1.3
protected int | width The width of the column.
Constructor Summary
TableColumn()
Cover method, using a default model index of 0, default width of 75, a null renderer and a null editor.
TableColumn(int modelIndex)
Cover method, using a default width of 75, a null renderer and a null editor.
TableColumn(int modelIndex, int width)
Cover method, using a null renderer and a null editor.
TableColumn(int modelIndex, int width, TableCellRenderer cellRenderer, TableCellEditor cellEditor)
Creates and initializes an instance of TableColumn with modelIndex.
Method Summary
 void addPropertyChangeListener(PropertyChangeListener listener)
Adds a PropertyChangeListener to the listener list.
protected  TableCellRenderer createDefaultHeaderRenderer()
As of Java 2 platform v1.3, this method is not called by the TableColumn constructor.
 void disableResizedPosting()
Deprecated. as of Java 2 platform v1.3
 void enableResizedPosting()
Deprecated. as of Java 2 platform v1.3
 TableCellEditor getCellEditor()
Returns the TableCellEditor used by the JTable to edit values for this column.
 TableCellRenderer getCellRenderer()
Returns the TableCellRenderer used by the JTable to draw values for this column.
 TableCellRenderer getHeaderRenderer()
Returns the TableCellRenderer used to draw the header of the TableColumn.
 Object getHeaderValue()
Returns the Object used as the value for the header renderer.
 Object getIdentifier()
Returns the identifier object for this column.
 int getMaxWidth()
Returns the maximum width for the TableColumn.
 int getMinWidth()
Returns the minimum width for the TableColumn.
 int getModelIndex()
Returns the model index for this column.
 int getPreferredWidth()
Returns the preferred width of the TableColumn.
 PropertyChangeListener[] getPropertyChangeListeners()
Returns an array of all the PropertyChangeListeners added to this TableColumn with addPropertyChangeListener().
 boolean getResizable()
Returns true if the user is allowed to resize the TableColumn's width, false otherwise.
 int getWidth()
Returns the width of the TableColumn.
 void removePropertyChangeListener(PropertyChangeListener listener)
Removes a PropertyChangeListener from the listener list.
 void setCellEditor(TableCellEditor cellEditor)
Sets the editor to used by when a cell in this column is edited.
 void setCellRenderer(TableCellRenderer cellRenderer)
Sets the TableCellRenderer used by JTable to draw individual values for this column.
 void setHeaderRenderer(TableCellRenderer headerRenderer)
Sets the TableCellRenderer used to draw the TableColumn's header to headerRenderer.
 void setHeaderValue(Object headerValue)
Sets the Object whose string representation will be used as the value for the headerRenderer.
 void setIdentifier(Object identifier)
Sets the TableColumn's identifier to anIdentifier.
 void setMaxWidth(int maxWidth)
Sets the TableColumn's maximum width to maxWidth; also adjusts the width and preferred width if they are greater than this value.
 void setMinWidth(int minWidth)
Sets the TableColumn's minimum width to minWidth; also adjusts the current width and preferred width if they are less than this value.
 void setModelIndex(int modelIndex)
Sets the model index for this column.
 void setPreferredWidth(int preferredWidth)
Sets this column's preferred width to preferredWidth.
 void setResizable(boolean isResizable)
Sets whether this column can be resized.
 void setWidth(int width)
This method should not be used to set the widths of columns in the JTable, use setPreferredWidth instead.
 void sizeWidthToFit()
Resizes the TableColumn to fit the width of its header cell.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

COLUMN_WIDTH_PROPERTY

public static final String COLUMN_WIDTH_PROPERTY
Obsolete as of Java 2 platform v1.3. Please use string literals to identify properties.

See Also:
Constant Field Values

HEADER_VALUE_PROPERTY

public static final String HEADER_VALUE_PROPERTY
Obsolete as of Java 2 platform v1.3. Please use string literals to identify properties.

See Also:
Constant Field Values

HEADER_RENDERER_PROPERTY

public static final String HEADER_RENDERER_PROPERTY
Obsolete as of Java 2 platform v1.3. Please use string literals to identify properties.

See Also:
Constant Field Values

CELL_RENDERER_PROPERTY

public static final String CELL_RENDERER_PROPERTY
Obsolete as of Java 2 platform v1.3. Please use string literals to identify properties.

See Also:
Constant Field Values

modelIndex

protected int modelIndex
The index of the column in the model which is to be displayed by this TableColumn. As columns are moved around in the view modelIndex remains constant.

identifier

protected Object identifier
This object is not used internally by the drawing machinery of the JTable; identifiers may be set in the TableColumn as as an optional way to tag and locate table columns. The table package does not modify or invoke any methods in these identifier objects other than the equals method which is used in the getColumnIndex() method in the DefaultTableColumnModel.

width

protected int width
The width of the column.

minWidth

protected int minWidth
The minimum width of the column.

maxWidth

protected int maxWidth
The maximum width of the column.

headerRenderer

protected TableCellRenderer headerRenderer
The renderer used to draw the header of the column.

headerValue

protected Object headerValue
The header value of the column.

cellRenderer

protected TableCellRenderer cellRenderer
The renderer used to draw the data cells of the column.

cellEditor

protected TableCellEditor cellEditor
The editor used to edit the data cells of the column.

isResizable

protected boolean isResizable
If true, the user is allowed to resize the column; the default is true.

resizedPostingDisableCount

protected transient int resizedPostingDisableCount
Deprecated. as of Java 2 platform v1.3

This field was not used in previous releases and there are currently no plans to support it in the future.

Constructor Detail

TableColumn

public TableColumn()
Cover method, using a default model index of 0, default width of 75, a null renderer and a null editor. This method is intended for serialization.

See Also:
TableColumn(int, int, TableCellRenderer, TableCellEditor)

TableColumn

public TableColumn(int modelIndex)
Cover method, using a default width of 75, a null renderer and a null editor.

See Also:
TableColumn(int, int, TableCellRenderer, TableCellEditor)

TableColumn

public TableColumn(int modelIndex,
                   int width)
Cover method, using a null renderer and a null editor.

See Also:
TableColumn(int, int, TableCellRenderer, TableCellEditor)

TableColumn

public TableColumn(int modelIndex,
                   int width,
                   TableCellRenderer cellRenderer,
                   TableCellEditor cellEditor)
Creates and initializes an instance of TableColumn with modelIndex. All TableColumn constructors delegate to this one. The modelIndex is the index of the column in the model which will supply the data for this column in the table. The modelIndex does not change as the columns are reordered in the view. The width parameter is used to set both the preferredWidth for this column and the initial width. The renderer and editor are the objects used respectively to render and edit values in this column. When these are null, default values, provided by the getDefaultRenderer and getDefaultEditor methods in the JTable class are used to provide defaults based on the type of the data in this column. This column-centric rendering strategy can be circumvented by overriding the getCellRenderer methods in the JTable.

See Also:
JTable.getDefaultRenderer(Class),
JTable.getDefaultEditor(Class),
JTable.getCellRenderer(int, int),
JTable.getCellEditor(int, int)
Method Detail

setModelIndex

public void setModelIndex(int modelIndex)
Sets the model index for this column. The model index is the index of the column in the model that will be displayed by this TableColumn. As the TableColumn is moved around in the view the model index remains constant.

Parameters:
modelIndex - the new modelIndex

getModelIndex

public int getModelIndex()
Returns the model index for this column.

Returns:
the modelIndex property

setIdentifier

public void setIdentifier(Object identifier)
Sets the TableColumn's identifier to anIdentifier.

Note: identifiers are not used by the JTable, they are purely a convenience for the external tagging and location of columns.

Parameters:
identifier - an identifier for this column
See Also:
getIdentifier()

getIdentifier

public Object getIdentifier()
Returns the identifier object for this column. Note identifiers are not used by JTable, they are purely a convenience for external use. If the identifier is null, getIdentifier() returns getHeaderValue as a default.

Returns:
the identifier property
See Also:
setIdentifier(java.lang.Object)

setHeaderValue

public void setHeaderValue(Object headerValue)
Sets the Object whose string representation will be used as the value for the headerRenderer. When the TableColumn is created, the default headerValue is null.

Parameters:
headerValue - the new headerValue
See Also:
getHeaderValue()

getHeaderValue

public Object getHeaderValue()
Returns the Object used as the value for the header renderer.

Returns:
the headerValue property
See Also:
setHeaderValue(java.lang.Object)

setHeaderRenderer

public void setHeaderRenderer(TableCellRenderer headerRenderer)
Sets the TableCellRenderer used to draw the TableColumn's header to headerRenderer.

Parameters:
headerRenderer - the new headerRenderer
See Also:
getHeaderRenderer()

getHeaderRenderer

public TableCellRenderer getHeaderRenderer()
Returns the TableCellRenderer used to draw the header of the TableColumn. When the headerRenderer is null, the JTableHeader uses its defaultRenderer. The default value for a headerRenderer is null.

Returns:
the headerRenderer property
See Also:
setHeaderRenderer(javax.swing.table.TableCellRenderer),
setHeaderValue(java.lang.Object),
JTableHeader.getDefaultRenderer()

setCellRenderer

public void setCellRenderer(TableCellRenderer cellRenderer)
Sets the TableCellRenderer used by JTable to draw individual values for this column.

Parameters:
cellRenderer - the new cellRenderer
See Also:
getCellRenderer()

getCellRenderer

public TableCellRenderer getCellRenderer()
Returns the TableCellRenderer used by the JTable to draw values for this column. The cellRenderer of the column not only controls the visual look for the column, but is also used to interpret the value object supplied by the TableModel. When the cellRenderer is null, the JTable uses a default renderer based on the class of the cells in that column. The default value for a cellRenderer is null.

Returns:
the cellRenderer property
See Also:
setCellRenderer(javax.swing.table.TableCellRenderer), JTable.setDefaultRenderer(java.lang.Class, javax.swing.table.TableCellRenderer)

setCellEditor

public void setCellEditor(TableCellEditor cellEditor)
Sets the editor to used by when a cell in this column is edited.

Parameters:
cellEditor - the new cellEditor
See Also:
getCellEditor()

getCellEditor

public TableCellEditor getCellEditor()
Returns the TableCellEditor used by the JTable to edit values for this column. When the cellEditor is null, the JTable uses a default editor based on the class of the cells in that column. The default value for a cellEditor is null.

Returns:
the cellEditor property
See Also:
setCellEditor(javax.swing.table.TableCellEditor), JTable.setDefaultEditor(java.lang.Class, javax.swing.table.TableCellEditor)

setWidth

public void setWidth(int width)
This method should not be used to set the widths of columns in the JTable, use setPreferredWidth instead. Like a layout manager in the AWT, the JTable adjusts a column's width automatically whenever the table itself changes size, or a column's preferred width is changed. Setting widths programmatically therefore has no long term effect.

This method sets this column's width to width. If width exceeds the minimum or maximum width, it is adjusted to the appropriate limiting value.

Parameters:
width - the new width
See Also:
getWidth(), setMinWidth(int), setMaxWidth(int), setPreferredWidth(int), JTable.sizeColumnsToFit(int)

getWidth

public int getWidth()
Returns the width of the TableColumn. The default width is 75.

Returns:
the width property
See Also:
setWidth(int)

setPreferredWidth

public void setPreferredWidth(int preferredWidth)
Sets this column's preferred width to preferredWidth. If preferredWidth exceeds the minimum or maximum width, it is adjusted to the appropriate limiting value.

For details on how the widths of columns in the JTable (and JTableHeader) are calculated from the preferredWidth, see the sizeColumnsToFit method in JTable.

Parameters:
preferredWidth - the new preferred width
See Also:
getPreferredWidth(), JTable.sizeColumnsToFit(int)

getPreferredWidth

public int getPreferredWidth()
Returns the preferred width of the TableColumn. The default preferred width is 75.

Returns:
the preferredWidth property
See Also:
setPreferredWidth(int)

setMinWidth

public void setMinWidth(int minWidth)
Sets the TableColumn's minimum width to minWidth; also adjusts the current width and preferred width if they are less than this value.

Parameters:
minWidth - the new minimum width
See Also:
getMinWidth(), setPreferredWidth(int), setMaxWidth(int)

getMinWidth

public int getMinWidth()
Returns the minimum width for the TableColumn. The TableColumn's width can't be made less than this either by the user or programmatically. The default minWidth is 15.

Returns:
the minWidth property
See Also:
setMinWidth(int)

setMaxWidth

public void setMaxWidth(int maxWidth)
Sets the TableColumn's maximum width to maxWidth; also adjusts the width and preferred width if they are greater than this value.

Parameters:
maxWidth - the new maximum width
See Also:
getMaxWidth(), setPreferredWidth(int), setMinWidth(int)

getMaxWidth

public int getMaxWidth()
Returns the maximum width for the TableColumn. The TableColumn's width can't be made larger than this either by the user or programmatically. The default maxWidth is Integer.MAX_VALUE.

Returns:
the maxWidth property
See Also:
setMaxWidth(int)

setResizable

public void setResizable(boolean isResizable)
Sets whether this column can be resized.

Parameters:
isResizable - if true, resizing is allowed; otherwise false
See Also:
getResizable()

getResizable

public boolean getResizable()
Returns true if the user is allowed to resize the TableColumn's width, false otherwise. You can change the width programmatically regardless of this setting. The default is true.

Returns:
the isResizable property
See Also:
setResizable(boolean)

sizeWidthToFit

public void sizeWidthToFit()
Resizes the TableColumn to fit the width of its header cell. This method does nothing if the header renderer is null (the default case). Otherwise, it sets the minimum, maximum and preferred widths of this column to the widths of the minimum, maximum and preferred sizes of the Component delivered by the header renderer. The transient "width" property of this TableColumn is also set to the preferred width. Note this method is not used internally by the table package.

See Also:
setPreferredWidth(int)

disableResizedPosting

public void disableResizedPosting()
Deprecated. as of Java 2 platform v1.3

This field was not used in previous releases and there are currently no plans to support it in the future.

enableResizedPosting

public void enableResizedPosting()
Deprecated. as of Java 2 platform v1.3

This field was not used in previous releases and there are currently no plans to support it in the future.

addPropertyChangeListener

public void addPropertyChangeListener(PropertyChangeListener listener)
Adds a PropertyChangeListener to the listener list. The listener is registered for all properties.

A PropertyChangeEvent will get fired in response to an explicit call to setFont, setBackground, or setForeground on the current component. Note that if the current component is inheriting its foreground, background, or font from its container, then no event will be fired in response to a change in the inherited property.

Parameters:
listener - the listener to be added

removePropertyChangeListener

public void removePropertyChangeListener(PropertyChangeListener listener)
Removes a PropertyChangeListener from the listener list. The PropertyChangeListener to be removed was registered for all properties.

Parameters:
listener - the listener to be removed

getPropertyChangeListeners

public PropertyChangeListener[] getPropertyChangeListeners()
Returns an array of all the PropertyChangeListeners added to this TableColumn with addPropertyChangeListener().

Returns:
all of the PropertyChangeListeners added or an empty array if no listeners have been added
Since:
1.4

createDefaultHeaderRenderer

protected TableCellRenderer createDefaultHeaderRenderer()
As of Java 2 platform v1.3, this method is not called by the TableColumn constructor. Previously this method was used by the TableColumn to create a default header renderer. As of Java 2 platform v1.3, the default header renderer is null. JTableHeader now provides its own shared default renderer, just as the JTable does for its cell renderers.

Returns:
the default header renderer
See Also:
JTableHeader.createDefaultRenderer()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


TableColumnModel (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.table
Interface TableColumnModel

All Known Implementing Classes:
DefaultTableColumnModel
public interface TableColumnModel

Defines the requirements for a table column model object suitable for use with JTable.

See Also:
DefaultTableColumnModel

Method Summary
void | addColumn(TableColumn aColumn) Appends aColumn to the end of the tableColumns array.
void | addColumnModelListener(TableColumnModelListener x) Adds a listener for table column model events.
TableColumn | getColumn(int columnIndex) Returns the TableColumn object for the column at columnIndex.
int | getColumnCount() Returns the number of columns in the model.
int | getColumnIndex(Object columnIdentifier) Returns the index of the first column in the table whose identifier is equal to identifier, when compared using equals.
int | getColumnIndexAtX(int xPosition) Returns the index of the column that lies on the horizontal point, xPosition; or -1 if it lies outside the any of the column's bounds.
int | getColumnMargin() Returns the width between the cells in each column.
Enumeration | getColumns() Returns an Enumeration of all the columns in the model.
boolean | getColumnSelectionAllowed() Returns true if columns may be selected.
int | getSelectedColumnCount() Returns the number of selected columns.
int[] | getSelectedColumns() Returns an array of indicies of all selected columns.
ListSelectionModel | getSelectionModel() Returns the current selection model.
int | getTotalColumnWidth() Returns the total width of all the columns.
void | moveColumn(int columnIndex, int newIndex) Moves the column and its header at columnIndex to newIndex.
void | removeColumn(TableColumn column) Deletes the TableColumn column from the tableColumns array.
void | removeColumnModelListener(TableColumnModelListener x) Removes a listener for table column model events.
void | setColumnMargin(int newMargin) Sets the TableColumn's column margin to newMargin.
void | setColumnSelectionAllowed(boolean flag) Sets whether the columns in this model may be selected.
void | setSelectionModel(ListSelectionModel newModel) Sets the selection model.

Method Detail

addColumn

public void addColumn(TableColumn aColumn)
Appends aColumn to the end of the tableColumns array. This method posts a columnAdded event to its listeners.

Parameters:
aColumn - the TableColumn to be added
See Also:
removeColumn(javax.swing.table.TableColumn)

removeColumn

public void removeColumn(TableColumn column)
Deletes the TableColumn column from the tableColumns array. This method will do nothing if column is not in the table's column list. This method posts a columnRemoved event to its listeners.

Parameters:
column - the TableColumn to be removed
See Also:
addColumn(javax.swing.table.TableColumn)

moveColumn

public void moveColumn(int columnIndex,
                       int newIndex)
Moves the column and its header at columnIndex to newIndex. The old column at columnIndex will now be found at newIndex. The column that used to be at newIndex is shifted left or right to make room. This will not move any columns if columnIndex equals newIndex. This method posts a columnMoved event to its listeners.

Parameters:
columnIndex - the index of column to be moved
newIndex - index of the column's new location
Throws:
IllegalArgumentException - if columnIndex or newIndex are not in the valid range

setColumnMargin

public void setColumnMargin(int newMargin)
Sets the TableColumn's column margin to newMargin. This method posts a columnMarginChanged event to its listeners.

Parameters:
newMargin - the width, in pixels, of the new column margins
See Also:
getColumnMargin()

getColumnCount

public int getColumnCount()
Returns the number of columns in the model.

Returns:
the number of columns in the model

getColumns

public Enumeration getColumns()
Returns an Enumeration of all the columns in the model.

Returns:
an Enumeration of all the columns in the model

getColumnIndex

public int getColumnIndex(Object columnIdentifier)
Returns the index of the first column in the table whose identifier is equal to identifier, when compared using equals.

Parameters:
columnIdentifier - the identifier object
Returns:
the index of the first table column whose identifier is equal to identifier
Throws:
IllegalArgumentException - if identifier is null, or no TableColumn has this identifier
See Also:
getColumn(int)

getColumn

public TableColumn getColumn(int columnIndex)
Returns the TableColumn object for the column at columnIndex.

Parameters:
columnIndex - the index of the desired column
Returns:
the TableColumn object for the column at columnIndex

getColumnMargin

public int getColumnMargin()
Returns the width between the cells in each column.

Returns:
the margin, in pixels, between the cells

getColumnIndexAtX

public int getColumnIndexAtX(int xPosition)
Returns the index of the column that lies on the horizontal point, xPosition; or -1 if it lies outside the any of the column's bounds. In keeping with Swing's separable model architecture, a TableColumnModel does not know how the table columns actually appear on screen. The visual presentation of the columns is the responsibility of the view/controller object using this model (typically JTable). The view/controller need not display the columns sequentially from left to right. For example, columns could be displayed from right to left to accomodate a locale preference or some columns might be hidden at the request of the user. Because the model does not know how the columns are laid out on screen, the given xPosition should not be considered to be a coordinate in 2D graphics space. Instead, it should be considered to be a width from the start of the first column in the model. If the column index for a given X coordinate in 2D space is required, JTable.columnAtPoint can be used instead.

Returns:
the index of the column; or -1 if no column is found
See Also:
JTable.columnAtPoint(java.awt.Point)

getTotalColumnWidth

public int getTotalColumnWidth()
Returns the total width of all the columns.

Returns:
the total computed width of all columns

setColumnSelectionAllowed

public void setColumnSelectionAllowed(boolean flag)
Sets whether the columns in this model may be selected.

Parameters:
flag - true if columns may be selected; otherwise false
See Also:
getColumnSelectionAllowed()

getColumnSelectionAllowed

public boolean getColumnSelectionAllowed()
Returns true if columns may be selected.

Returns:
true if columns may be selected
See Also:
setColumnSelectionAllowed(boolean)

getSelectedColumns

public int[] getSelectedColumns()
Returns an array of indicies of all selected columns.

Returns:
an array of integers containing the indicies of all selected columns; or an empty array if nothing is selected

getSelectedColumnCount

public int getSelectedColumnCount()
Returns the number of selected columns.

Returns:
the number of selected columns; or 0 if no columns are selected

setSelectionModel

public void setSelectionModel(ListSelectionModel newModel)
Sets the selection model.

Parameters:
newModel - a ListSelectionModel object
See Also:
getSelectionModel()

getSelectionModel

public ListSelectionModel getSelectionModel()
Returns the current selection model.

Returns:
a ListSelectionModel object
See Also:
setSelectionModel(javax.swing.ListSelectionModel)

addColumnModelListener

public void addColumnModelListener(TableColumnModelListener x)
Adds a listener for table column model events.

Parameters:
x - a TableColumnModelListener object

removeColumnModelListener

public void removeColumnModelListener(TableColumnModelListener x)
Removes a listener for table column model events.

Parameters:
x - a TableColumnModelListener object
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TableModel (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.swing.table
Interface TableModel

All Known Implementing Classes:
AbstractTableModel
public interface TableModel

The TableModel interface specifies the methods the JTable will use to interrogate a tabular data model.

The JTable can be set up to display any data model which implements the TableModel interface with a couple of lines of code:

      TableModel myData = new MyTableModel();
      JTable table = new JTable(myData);

For further documentation, see Creating a Table Model in The Java Tutorial.

See Also:
JTable

Method Summary
void | addTableModelListener(TableModelListener l) Adds a listener to the list that is notified each time a change to the data model occurs.
Class | getColumnClass(int columnIndex) Returns the most specific superclass for all the cell values in the column.
int | getColumnCount() Returns the number of columns in the model.
String | getColumnName(int columnIndex) Returns the name of the column at columnIndex.
int | getRowCount() Returns the number of rows in the model.
Object | getValueAt(int rowIndex, int columnIndex) Returns the value for the cell at columnIndex and rowIndex.
boolean | isCellEditable(int rowIndex, int columnIndex) Returns true if the cell at rowIndex and columnIndex is editable.
void | removeTableModelListener(TableModelListener l) Removes a listener from the list that is notified each time a change to the data model occurs.
void | setValueAt(Object aValue, int rowIndex, int columnIndex) Sets the value in the cell at columnIndex and rowIndex to aValue.

Method Detail

getRowCount

public int getRowCount()
Returns the number of rows in the model. A JTable uses this method to determine how many rows it should display. This method should be quick, as it is called frequently during rendering.

Returns:
the number of rows in the model
See Also:
getColumnCount()

getColumnCount

public int getColumnCount()
Returns the number of columns in the model. A JTable uses this method to determine how many columns it should create and display by default.

Returns:
the number of columns in the model
See Also:
getRowCount()

getColumnName

public String getColumnName(int columnIndex)
Returns the name of the column at columnIndex. This is used to initialize the table's column header name. Note: this name does not need to be unique; two columns in a table can have the same name.

Parameters:
columnIndex - the index of the column
Returns:
the name of the column

getColumnClass

public Class getColumnClass(int columnIndex)
Returns the most specific superclass for all the cell values in the column. This is used by the JTable to set up a default renderer and editor for the column.

Parameters:
columnIndex - the index of the column
Returns:
the common ancestor class of the object values in the model.

isCellEditable

public boolean isCellEditable(int rowIndex,
                              int columnIndex)
Returns true if the cell at rowIndex and columnIndex is editable. Otherwise, setValueAt on the cell will not change the value of that cell.

Parameters:
rowIndex - the row whose value to be queried
columnIndex - the column whose value to be queried
Returns:
true if the cell is editable
See Also:
setValueAt(java.lang.Object, int, int)

getValueAt

public Object getValueAt(int rowIndex,
                         int columnIndex)
Returns the value for the cell at columnIndex and rowIndex.

Parameters:
rowIndex - the row whose value is to be queried
columnIndex - the column whose value is to be queried
Returns:
the value Object at the specified cell

setValueAt

public void setValueAt(Object aValue,
                       int rowIndex,
                       int columnIndex)
Sets the value in the cell at columnIndex and rowIndex to aValue.

Parameters:
aValue - the new value
rowIndex - the row whose value is to be changed
columnIndex - the column whose value is to be changed
See Also:
getValueAt(int, int), isCellEditable(int, int)

addTableModelListener

public void addTableModelListener(TableModelListener l)
Adds a listener to the list that is notified each time a change to the data model occurs.

Parameters:
l - the TableModelListener

removeTableModelListener

public void removeTableModelListener(TableModelListener l)
Removes a listener from the list that is notified each time a change to the data model occurs.

Parameters:
l - the TableModelListener
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Uses of Class javax.swing.table.AbstractTableModel (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.table.AbstractTableModel

Packages that use AbstractTableModel
javax.swing.table Provides classes and interfaces for dealing with javax.swing.JTable.

Uses of AbstractTableModel in javax.swing.table

Subclasses of AbstractTableModel in javax.swing.table
 class DefaultTableModel
This is an implementation of TableModel that uses a Vector of Vectors to store the cell value objects.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.table.DefaultTableCellRenderer (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.table.DefaultTableCellRenderer

Packages that use DefaultTableCellRenderer
javax.swing.table Provides classes and interfaces for dealing with javax.swing.JTable.

Uses of DefaultTableCellRenderer in javax.swing.table

Subclasses of DefaultTableCellRenderer in javax.swing.table
static class DefaultTableCellRenderer.UIResource
A subclass of DefaultTableCellRenderer that implements UIResource.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.table.DefaultTableCellRenderer.UIResource (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.table.DefaultTableCellRenderer.UIResource

No usage of javax.swing.table.DefaultTableCellRenderer.UIResource

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.table.DefaultTableColumnModel (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.table.DefaultTableColumnModel

No usage of javax.swing.table.DefaultTableColumnModel

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.table.DefaultTableModel (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.table.DefaultTableModel

No usage of javax.swing.table.DefaultTableModel

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.table.JTableHeader (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.table.JTableHeader

Packages that use JTableHeader
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.plaf.basic | Provides user interface objects built according to the Basic look and feel.
javax.swing.table | Provides classes and interfaces for dealing with javax.swing.JTable.

Uses of JTableHeader in javax.swing

Fields in javax.swing declared as JTableHeader
protected  JTableHeader JTable.tableHeader
The TableHeader working with the table.

Methods in javax.swing that return JTableHeader
JTableHeader | JTable.getTableHeader() Returns the tableHeader used by this JTable.
protected JTableHeader | JTable.createDefaultTableHeader() Returns the default table header object, which is a JTableHeader.

Methods in javax.swing with parameters of type JTableHeader
 void JTable.setTableHeader(JTableHeader tableHeader)
Sets the tableHeader working with this JTable to newHeader.

Uses of JTableHeader in javax.swing.plaf.basic

Fields in javax.swing.plaf.basic declared as JTableHeader
protected  JTableHeader BasicTableHeaderUI.header
The JTableHeader that is delegating the painting to this UI.

Uses of JTableHeader in javax.swing.table

Constructors in javax.swing.table with parameters of type JTableHeader
JTableHeader.AccessibleJTableHeader.AccessibleJTableHeaderEntry(int c, JTableHeader p, JTable t)
Constructs an AccessiblJTableHeaaderEntry

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.table.JTableHeader.AccessibleJTableHeader (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.table.JTableHeader.AccessibleJTableHeader

No usage of javax.swing.table.JTableHeader.AccessibleJTableHeader

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.table.JTableHeader.AccessibleJTableHeader.AccessibleJTableHeaderEntry (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.table.JTableHeader.AccessibleJTableHeader.AccessibleJTableHeaderEntry

No usage of javax.swing.table.JTableHeader.AccessibleJTableHeader.AccessibleJTableHeaderEntry

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.swing.table.TableCellEditor (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.swing.table.TableCellEditor

Packages that use TableCellEditor
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.table | Provides classes and interfaces for dealing with javax.swing.JTable.

Uses of TableCellEditor in javax.swing

Classes in javax.swing that implement TableCellEditor
 class DefaultCellEditor
The default editor for table and tree cells.

Fields in javax.swing declared as TableCellEditor
protected  TableCellEditor JTable.cellEditor
The object that overwrites the screen real estate occupied by the current cell and allows the user to change its contents.

Methods in javax.swing that return TableCellEditor
TableCellEditor | JTable.getDefaultEditor(Class columnClass) Returns the editor to be used when no editor has been set in a TableColumn.
TableCellEditor | JTable.getCellEditor() Returns the cell editor.
TableCellEditor | JTable.getCellEditor(int row, int column) Returns an appropriate editor for the cell specified by row and column.

Methods in javax.swing with parameters of type TableCellEditor
void | JTable.setDefaultEditor(Class columnClass, TableCellEditor editor) Sets a default cell editor to be used if no editor has been set in a TableColumn.
void | JTable.setCellEditor(TableCellEditor anEditor) Sets the cellEditor variable.
Component | JTable.prepareEditor(TableCellEditor editor, int row, int column) Prepares the editor by querying the data model for the value and selection state of the cell at row, column.

Uses of TableCellEditor in javax.swing.table

Fields in javax.swing.table declared as TableCellEditor
protected  TableCellEditor TableColumn.cellEditor
The editor used to edit the data cells of the column.

Methods in javax.swing.table that return TableCellEditor
 TableCellEditor TableColumn.getCellEditor()
Returns the TableCellEditor used by the JTable to edit values for this column.

Methods in javax.swing.table with parameters of type TableCellEditor
 void TableColumn.setCellEditor(TableCellEditor cellEditor)
Sets the editor to used by when a cell in this column is edited.

Constructors in javax.swing.table with parameters of type TableCellEditor
TableColumn(int modelIndex, int width, TableCellRenderer cellRenderer, TableCellEditor cellEditor)
Creates and initializes an instance of TableColumn with modelIndex.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.swing.table.TableCellRenderer (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.swing.table.TableCellRenderer

Packages that use TableCellRenderer
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.table | Provides classes and interfaces for dealing with javax.swing.JTable.

Uses of TableCellRenderer in javax.swing

Methods in javax.swing that return TableCellRenderer
TableCellRenderer | JTable.getDefaultRenderer(Class columnClass) Returns the cell renderer to be used when no renderer has been set in a TableColumn.
TableCellRenderer | JTable.getCellRenderer(int row, int column) Returns an appropriate renderer for the cell specified by this row and column.

Methods in javax.swing with parameters of type TableCellRenderer
void | JTable.setDefaultRenderer(Class columnClass, TableCellRenderer renderer) Sets a default cell renderer to be used if no renderer has been set in a TableColumn.
Component | JTable.prepareRenderer(TableCellRenderer renderer, int row, int column) Prepares the renderer by querying the data model for the value and selection state of the cell at row, column.

Uses of TableCellRenderer in javax.swing.table

Classes in javax.swing.table that implement TableCellRenderer
class | DefaultTableCellRenderer The standard class for rendering (displaying) individual cells in a JTable.
static class | DefaultTableCellRenderer.UIResource A subclass of DefaultTableCellRenderer that implements UIResource.

Fields in javax.swing.table declared as TableCellRenderer
protected TableCellRenderer | TableColumn.headerRenderer The renderer used to draw the header of the column.
protected TableCellRenderer | TableColumn.cellRenderer The renderer used to draw the data cells of the column.

Methods in javax.swing.table that return TableCellRenderer
TableCellRenderer | TableColumn.getHeaderRenderer() Returns the TableCellRenderer used to draw the header of the TableColumn.
TableCellRenderer | TableColumn.getCellRenderer() Returns the TableCellRenderer used by the JTable to draw values for this column.
protected TableCellRenderer | TableColumn.createDefaultHeaderRenderer() As of Java 2 platform v1.3, this method is not called by the TableColumn constructor.
TableCellRenderer | JTableHeader.getDefaultRenderer() Returns the default renderer used when no headerRenderer is defined by a TableColumn.
protected TableCellRenderer | JTableHeader.createDefaultRenderer() Returns a default renderer to be used when no header renderer is defined by a TableColumn.

Methods in javax.swing.table with parameters of type TableCellRenderer
void | TableColumn.setHeaderRenderer(TableCellRenderer headerRenderer) Sets the TableCellRenderer used to draw the TableColumn's header to headerRenderer.
void | TableColumn.setCellRenderer(TableCellRenderer cellRenderer) Sets the TableCellRenderer used by JTable to draw individual values for this column.
void | JTableHeader.setDefaultRenderer(TableCellRenderer defaultRenderer) Sets the default renderer to be used when no headerRenderer is defined by a TableColumn.

Constructors in javax.swing.table with parameters of type TableCellRenderer
TableColumn(int modelIndex, int width, TableCellRenderer cellRenderer, TableCellEditor cellEditor)
Creates and initializes an instance of TableColumn with modelIndex.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.table.TableColumn (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.table.TableColumn

Packages that use TableColumn
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.table | Provides classes and interfaces for dealing with javax.swing.JTable.

Uses of TableColumn in javax.swing

Methods in javax.swing that return TableColumn
 TableColumn JTable.getColumn(Object identifier)
Returns the TableColumn object for the column in the table whose identifier is equal to identifier, when compared using equals.

Methods in javax.swing with parameters of type TableColumn
void | JTable.addColumn(TableColumn aColumn) Appends aColumn to the end of the array of columns held by this JTable's column model.
void | JTable.removeColumn(TableColumn aColumn) Removes aColumn from this JTable's array of columns.

Uses of TableColumn in javax.swing.table

Fields in javax.swing.table declared as TableColumn
protected TableColumn | JTableHeader.resizingColumn The index of the column being resized.
protected TableColumn | JTableHeader.draggedColumn The index of the column being dragged.

Methods in javax.swing.table that return TableColumn
TableColumn | DefaultTableColumnModel.getColumn(int columnIndex) Returns the TableColumn object for the column at columnIndex.
TableColumn | TableColumnModel.getColumn(int columnIndex) Returns the TableColumn object for the column at columnIndex.
TableColumn | JTableHeader.getDraggedColumn() Returns the the dragged column, if and only if, a drag is in process, otherwise returns null.
TableColumn | JTableHeader.getResizingColumn() Returns the resizing column.

Methods in javax.swing.table with parameters of type TableColumn
void | DefaultTableColumnModel.addColumn(TableColumn aColumn) Appends aColumn to the end of the tableColumns array.
void | DefaultTableColumnModel.removeColumn(TableColumn column) Deletes the column from the tableColumns array.
void | TableColumnModel.addColumn(TableColumn aColumn) Appends aColumn to the end of the tableColumns array.
void | TableColumnModel.removeColumn(TableColumn column) Deletes the TableColumn column from the tableColumns array.
void | JTableHeader.setDraggedColumn(TableColumn aColumn) Sets the header's draggedColumn to aColumn.
void | JTableHeader.setResizingColumn(TableColumn aColumn) Sets the header's resizingColumn to aColumn.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.swing.table.TableColumnModel (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.swing.table.TableColumnModel

Packages that use TableColumnModel
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.event | Provides for events fired by Swing components.
javax.swing.table | Provides classes and interfaces for dealing with javax.swing.JTable.

Uses of TableColumnModel in javax.swing

Fields in javax.swing declared as TableColumnModel
protected  TableColumnModel JTable.columnModel
The TableColumnModel of the table.

Methods in javax.swing that return TableColumnModel
TableColumnModel | JTable.getColumnModel() Returns the TableColumnModel that contains all column information of this table.
protected TableColumnModel | JTable.createDefaultColumnModel() Returns the default column model object, which is a DefaultTableColumnModel.

Methods in javax.swing with parameters of type TableColumnModel
 void JTable.setColumnModel(TableColumnModel columnModel)
Sets the column model for this table to newModel and registers for listener notifications from the new column model.

Constructors in javax.swing with parameters of type TableColumnModel
JTable(TableModel dm, TableColumnModel cm)
Constructs a JTable that is initialized with dm as the data model, cm as the column model, and a default selection model.
JTable(TableModel dm, TableColumnModel cm, ListSelectionModel sm)
Constructs a JTable that is initialized with dm as the data model, cm as the column model, and sm as the selection model.

Uses of TableColumnModel in javax.swing.event

Constructors in javax.swing.event with parameters of type TableColumnModel
TableColumnModelEvent(TableColumnModel source, int from, int to)
Constructs a TableColumnModelEvent object.

Uses of TableColumnModel in javax.swing.table

Classes in javax.swing.table that implement TableColumnModel
 class DefaultTableColumnModel
The standard column-handler for a JTable.

Fields in javax.swing.table declared as TableColumnModel
protected  TableColumnModel JTableHeader.columnModel
The TableColumnModel of the table header.

Methods in javax.swing.table that return TableColumnModel
TableColumnModel | JTableHeader.getColumnModel() Returns the TableColumnModel that contains all column information of this table header.
protected TableColumnModel | JTableHeader.createDefaultColumnModel() Returns the default column model object which is a DefaultTableColumnModel.

Methods in javax.swing.table with parameters of type TableColumnModel
 void JTableHeader.setColumnModel(TableColumnModel columnModel)
Sets the column model for this table to newModel and registers for listener notifications from the new column model.

Constructors in javax.swing.table with parameters of type TableColumnModel
JTableHeader(TableColumnModel cm)
Constructs a JTableHeader which is initialized with cm as the column model.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.swing.table.TableModel (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.swing.table.TableModel

Packages that use TableModel
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.event | Provides for events fired by Swing components.
javax.swing.table | Provides classes and interfaces for dealing with javax.swing.JTable.

Uses of TableModel in javax.swing

Fields in javax.swing declared as TableModel
protected  TableModel JTable.dataModel
The TableModel of the table.

Methods in javax.swing that return TableModel
TableModel | JTable.getModel() Returns the TableModel that provides the data displayed by this JTable.
protected TableModel | JTable.createDefaultDataModel() Returns the default table model object, which is a DefaultTableModel.

Methods in javax.swing with parameters of type TableModel
 void JTable.setModel(TableModel dataModel)
Sets the data model for this table to newModel and registers with it for listener notifications from the new data model.

Constructors in javax.swing with parameters of type TableModel
JTable(TableModel dm)
Constructs a JTable that is initialized with dm as the data model, a default column model, and a default selection model.
JTable(TableModel dm, TableColumnModel cm)
Constructs a JTable that is initialized with dm as the data model, cm as the column model, and a default selection model.
JTable(TableModel dm, TableColumnModel cm, ListSelectionModel sm)
Constructs a JTable that is initialized with dm as the data model, cm as the column model, and sm as the selection model.

Uses of TableModel in javax.swing.event

Constructors in javax.swing.event with parameters of type TableModel
TableModelEvent(TableModel source)
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 source, int row)
This row of data has been updated.
TableModelEvent(TableModel source, int firstRow, int lastRow)
The data in rows [firstRow, lastRow] have been updated.
TableModelEvent(TableModel source, int firstRow, int lastRow, int column)
The cells in column column in the range [firstRow, lastRow] have been updated.
TableModelEvent(TableModel source, int firstRow, int lastRow, int column, int type)
The cells from (firstRow, column) to (lastRow, column) have been changed.

Uses of TableModel in javax.swing.table

Classes in javax.swing.table that implement TableModel
class | AbstractTableModel This abstract class provides default implementations for most of the methods in the TableModel interface.
class | DefaultTableModel This is an implementation of TableModel that uses a Vector of Vectors to store the cell value objects.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


AbstractDocument (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class AbstractDocument

java.lang.Object
    extended by javax.swing.text.AbstractDocument
All Implemented Interfaces:
Document, Serializable
Direct Known Subclasses:
DefaultStyledDocument, PlainDocument
public abstract class AbstractDocument
extends Object
implements Document, Serializable

An implementation of the document interface to serve as a basis for implementing various kinds of documents. At this level there is very little policy, so there is a corresponding increase in difficulty of use.

This class implements a locking mechanism for the document. It allows multiple readers or one writer, and writers must wait until all observers of the document have been notified of a previous change before beginning another mutation to the document. The read lock is acquired and released using the render method. A write lock is aquired by the methods that mutate the document, and are held for the duration of the method call. Notification is done on the thread that produced the mutation, and the thread has full read access to the document for the duration of the notification, but other readers are kept out until the notification has finished. The notification is a beans event notification which does not allow any further mutations until all listeners have been notified.

Any models subclassed from this class and used in conjunction with a text component that has a look and feel implementation that is derived from BasicTextUI may be safely updated asynchronously, because all access to the View hierarchy is serialized by BasicTextUI if the document is of type AbstractDocument. The locking assumes that an independant thread will access the View hierarchy only from the DocumentListener methods, and that there will be only one event thread active at a time.

If concurrency support is desired, there are the following additional implications. The code path for any DocumentListener implementation and any UndoListener implementation must be threadsafe, and not access the component lock if trying to be safe from deadlocks. The repaint and revalidate methods on JComponent are safe.

AbstractDocument models an implied break at the end of the document. Among other things this allows you to position the caret after the last character. As a result of this, getLength returns one less than the length of the Content. If you create your own Content, be sure and initialize it to have an additional character. Refer to StringContent and GapContent for examples of this. Another implication of this is that Elements that model the implied end character will have an endOffset == (getLength() + 1). For example, in DefaultStyledDocument getParagraphElement(getLength()).getEndOffset() == getLength() + 1 .

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Nested Class Summary
class | AbstractDocument.AbstractElement Implements the abstract part of an element.
static interface | AbstractDocument.AttributeContext An interface that can be used to allow MutableAttributeSet implementations to use pluggable attribute compression techniques.
class | AbstractDocument.BranchElement Implements a composite element that contains other elements.
static interface | AbstractDocument.Content Interface to describe a sequence of character content that can be edited.
class | AbstractDocument.DefaultDocumentEvent Stores document changes as the document is being modified.
static class | AbstractDocument.ElementEdit An implementation of ElementChange that can be added to the document event.
class | AbstractDocument.LeafElement Implements an element that directly represents content of some kind.
Field Summary
protected static String | BAD_LOCATION Error message to indicate a bad location.
static String | BidiElementName Name of elements used to hold a unidirectional run
static String | ContentElementName Name of elements used to represent content
static String | ElementNameAttribute Name of the attribute used to specify element names.
protected EventListenerList | listenerList The event listener list for the document.
static String | ParagraphElementName Name of elements used to represent paragraphs
static String | SectionElementName Name of elements used to hold sections (lines/paragraphs).
Fields inherited from interface javax.swing.text.Document
StreamDescriptionProperty, TitleProperty
Constructor Summary
protected | AbstractDocument(AbstractDocument.Content data) Constructs a new AbstractDocument, wrapped around some specified content storage mechanism.
protected | AbstractDocument(AbstractDocument.Content data, AbstractDocument.AttributeContext context) Constructs a new AbstractDocument, wrapped around some specified content storage mechanism.
Method Summary
void | addDocumentListener(DocumentListener listener) Adds a document listener for notification of any changes.
void | addUndoableEditListener(UndoableEditListener listener) Adds an undo listener for notification of any changes.
protected Element | createBranchElement(Element parent, AttributeSet a) Creates a document branch element, that can contain other elements.
protected Element | createLeafElement(Element parent, AttributeSet a, int p0, int p1) Creates a document leaf element.
Position | createPosition(int offs) Returns a position that will track change as the document is altered.
void | dump(PrintStream out) Gives a diagnostic dump.
protected void | fireChangedUpdate(DocumentEvent e) Notifies all listeners that have registered interest for notification on this event type.
protected void | fireInsertUpdate(DocumentEvent e) Notifies all listeners that have registered interest for notification on this event type.
protected void | fireRemoveUpdate(DocumentEvent e) Notifies all listeners that have registered interest for notification on this event type.
protected void | fireUndoableEditUpdate(UndoableEditEvent e) Notifies all listeners that have registered interest for notification on this event type.
int | getAsynchronousLoadPriority() Gets the asynchronous loading priority.
protected AbstractDocument.AttributeContext | getAttributeContext() Fetches the context for managing attributes.
Element | getBidiRootElement() Returns the root element of the bidirectional structure for this document.
protected AbstractDocument.Content | getContent() Gets the content for the document.
protected Thread | getCurrentWriter() Fetches the current writing thread if there is one.
abstract Element | getDefaultRootElement() Returns the root element that views should be based upon unless some other mechanism for assigning views to element structures is provided.
DocumentFilter | getDocumentFilter() Returns the DocumentFilter that is responsible for filtering of insertion/removal.
DocumentListener[] | getDocumentListeners() Returns an array of all the document listeners registered on this document.
Dictionary | getDocumentProperties() Supports managing a set of properties.
Position | getEndPosition() Returns a position that represents the end of the document.
int | getLength() Returns the length of the data.
EventListener[] | getListeners(Class listenerType) Returns an array of all the objects currently registered as FooListeners upon this document.
abstract Element | getParagraphElement(int pos) Get the paragraph element containing the given position.
Object | getProperty(Object key) A convenience method for looking up a property value.
Element[] | getRootElements() Gets all root elements defined.
Position | getStartPosition() Returns a position that represents the start of the document.
String | getText(int offset, int length) Gets a sequence of text from the document.
void | getText(int offset, int length, Segment txt) Fetches the text contained within the given portion of the document.
UndoableEditListener[] | getUndoableEditListeners() Returns an array of all the undoable edit listeners registered on this document.
void | insertString(int offs, String str, AttributeSet a) Inserts some content into the document.
protected void | insertUpdate(AbstractDocument.DefaultDocumentEvent chng, AttributeSet attr) Updates document structure as a result of text insertion.
protected void | postRemoveUpdate(AbstractDocument.DefaultDocumentEvent chng) Updates any document structure as a result of text removal.
void | putProperty(Object key, Object value) A convenience method for storing up a property value.
void | readLock() Acquires a lock to begin reading some state from the document.
void | readUnlock() Does a read unlock.
void | remove(int offs, int len) Removes some content from the document.
void | removeDocumentListener(DocumentListener listener) Removes a document listener.
void | removeUndoableEditListener(UndoableEditListener listener) Removes an undo listener.
protected void | removeUpdate(AbstractDocument.DefaultDocumentEvent chng) Updates any document structure as a result of text removal.
void | render(Runnable r) This allows the model to be safely rendered in the presence of currency, if the model supports being updated asynchronously.
void | replace(int offset, int length, String text, AttributeSet attrs) Deletes the region of text from offset to offset + length, and replaces it with text.
void | setAsynchronousLoadPriority(int p) Sets the asynchronous loading priority.
void | setDocumentFilter(DocumentFilter filter) Sets the DocumentFilter.
void | setDocumentProperties(Dictionary x) Replaces the document properties dictionary for this document.
protected void | writeLock() Acquires a lock to begin mutating the document this lock protects.
protected void | writeUnlock() Releases a write lock previously obtained via writeLock.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

listenerList

protected EventListenerList listenerList
The event listener list for the document.

BAD_LOCATION

protected static final String BAD_LOCATION
Error message to indicate a bad location.

See Also:
Constant Field Values

ParagraphElementName

public static final String ParagraphElementName
Name of elements used to represent paragraphs

See Also:
Constant Field Values

ContentElementName

public static final String ContentElementName
Name of elements used to represent content

See Also:
Constant Field Values

SectionElementName

public static final String SectionElementName
Name of elements used to hold sections (lines/paragraphs).

See Also:
Constant Field Values

BidiElementName

public static final String BidiElementName
Name of elements used to hold a unidirectional run

See Also:
Constant Field Values

ElementNameAttribute

public static final String ElementNameAttribute
Name of the attribute used to specify element names.

See Also:
Constant Field Values
Constructor Detail

AbstractDocument

protected AbstractDocument(AbstractDocument.Content data)
Constructs a new AbstractDocument, wrapped around some specified content storage mechanism.

Parameters:
data - the content

AbstractDocument

protected AbstractDocument(AbstractDocument.Content data,
                           AbstractDocument.AttributeContext context)
Constructs a new AbstractDocument, wrapped around some specified content storage mechanism.

Parameters:
data - the content
context - the attribute context
Method Detail

getDocumentProperties

public Dictionary getDocumentProperties()
Supports managing a set of properties. Callers can use the documentProperties dictionary to annotate the document with document-wide properties.

Returns:
a non-null Dictionary
See Also:
setDocumentProperties(java.util.Dictionary)

setDocumentProperties

public void setDocumentProperties(Dictionary x)
Replaces the document properties dictionary for this document.

Parameters:
x - the new dictionary
See Also:
getDocumentProperties()

fireInsertUpdate

protected void fireInsertUpdate(DocumentEvent e)
Notifies all listeners that have registered interest for notification on this event type. The event instance is lazily created using the parameters passed into the fire method.

Parameters:
e - the event
See Also:
EventListenerList

fireChangedUpdate

protected void fireChangedUpdate(DocumentEvent e)
Notifies all listeners that have registered interest for notification on this event type. The event instance is lazily created using the parameters passed into the fire method.

Parameters:
e - the event
See Also:
EventListenerList

fireRemoveUpdate

protected void fireRemoveUpdate(DocumentEvent e)
Notifies all listeners that have registered interest for notification on this event type. The event instance is lazily created using the parameters passed into the fire method.

Parameters:
e - the event
See Also:
EventListenerList

fireUndoableEditUpdate

protected void fireUndoableEditUpdate(UndoableEditEvent e)
Notifies all listeners that have registered interest for notification on this event type. The event instance is lazily created using the parameters passed into the fire method.

Parameters:
e - the event
See Also:
EventListenerList

getListeners

public EventListener[] getListeners(Class listenerType)
Returns an array of all the objects currently registered as FooListeners upon this document. FooListeners are registered using the addFooListener method.

You can specify the listenerType argument with a class literal, such as FooListener.class. For example, you can query a document d for its document listeners with the following code:

DocumentListener[] mls = (DocumentListener[])(d.getListeners(DocumentListener.class));
If no such listeners exist, this method returns an empty array.

Parameters:
listenerType - the type of listeners requested; this parameter should specify an interface that descends from java.util.EventListener
Returns:
an array of all objects registered as FooListeners on this component, or an empty array if no such listeners have been added
Throws:
ClassCastException - if listenerType doesn't specify a class or interface that implements java.util.EventListener
Since:
1.3
See Also:
getDocumentListeners(), getUndoableEditListeners()

getAsynchronousLoadPriority

public int getAsynchronousLoadPriority()
Gets the asynchronous loading priority. If less than zero, the document should not be loaded asynchronously.

Returns:
the asynchronous loading priority, or -1 if the document should not be loaded asynchronously

setAsynchronousLoadPriority

public void setAsynchronousLoadPriority(int p)
Sets the asynchronous loading priority.

Parameters:
p - the new asynchronous loading priority; a value less than zero indicates that the document should not be loaded asynchronously

setDocumentFilter

public void setDocumentFilter(DocumentFilter filter)
Sets the DocumentFilter. The DocumentFilter is passed insert and remove to conditionally allow inserting/deleting of the text. A null value indicates that no filtering will occur.

Parameters:
filter - the DocumentFilter used to constrain text
Since:
1.4
See Also:
getDocumentFilter()

getDocumentFilter

public DocumentFilter getDocumentFilter()
Returns the DocumentFilter that is responsible for filtering of insertion/removal. A null return value implies no filtering is to occur.

Returns:
the DocumentFilter
Since:
1.4
See Also:
setDocumentFilter(javax.swing.text.DocumentFilter)

render

public void render(Runnable r)
This allows the model to be safely rendered in the presence of currency, if the model supports being updated asynchronously. The given runnable will be executed in a way that allows it to safely read the model with no changes while the runnable is being executed. The runnable itself may not make any mutations.

This is implemented to aquire a read lock for the duration of the runnables execution. There may be multiple runnables executing at the same time, and all writers will be blocked while there are active rendering runnables. If the runnable throws an exception, its lock will be safely released. There is no protection against a runnable that never exits, which will effectively leave the document locked for it's lifetime.

If the given runnable attempts to make any mutations in this implementation, a deadlock will occur. There is no tracking of individual rendering threads to enable detecting this situation, but a subclass could incur the overhead of tracking them and throwing an error.

This method is thread safe, although most Swing methods are not. Please see Threads and Swing for more information.

Specified by:
render in interface Document
Parameters:
r - the renderer to execute

getLength

public int getLength()
Returns the length of the data. This is the number of characters of content that represents the users data.

Specified by:
getLength in interface Document
Returns:
the length >= 0
See Also:
Document.getLength()

addDocumentListener

public void addDocumentListener(DocumentListener listener)
Adds a document listener for notification of any changes.

Specified by:
addDocumentListener in interface Document
Parameters:
listener - the DocumentListener to add
See Also:
Document.addDocumentListener(javax.swing.event.DocumentListener)

removeDocumentListener

public void removeDocumentListener(DocumentListener listener)
Removes a document listener.

Specified by:
removeDocumentListener in interface Document
Parameters:
listener - the DocumentListener to remove
See Also:
Document.removeDocumentListener(javax.swing.event.DocumentListener)

getDocumentListeners

public DocumentListener[] getDocumentListeners()
Returns an array of all the document listeners registered on this document.

Returns:
all of this document's DocumentListeners or an empty array if no document listeners are currently registered
Since:
1.4
See Also:
addDocumentListener(javax.swing.event.DocumentListener), removeDocumentListener(javax.swing.event.DocumentListener)

addUndoableEditListener

public void addUndoableEditListener(UndoableEditListener listener)
Adds an undo listener for notification of any changes. Undo/Redo operations performed on the UndoableEdit will cause the appropriate DocumentEvent to be fired to keep the view(s) in sync with the model.

Specified by:
addUndoableEditListener in interface Document
Parameters:
listener - the UndoableEditListener to add
See Also:
Document.addUndoableEditListener(javax.swing.event.UndoableEditListener)

removeUndoableEditListener

public void removeUndoableEditListener(UndoableEditListener listener)
Removes an undo listener.

Specified by:
removeUndoableEditListener in interface Document
Parameters:
listener - the UndoableEditListener to remove
See Also:
Document.removeDocumentListener(javax.swing.event.DocumentListener)

getUndoableEditListeners

public UndoableEditListener[] getUndoableEditListeners()
Returns an array of all the undoable edit listeners registered on this document.

Returns:
all of this document's UndoableEditListeners or an empty array if no undoable edit listeners are currently registered
Since:
1.4
See Also:
addUndoableEditListener(javax.swing.event.UndoableEditListener), removeUndoableEditListener(javax.swing.event.UndoableEditListener)

getProperty

public final Object getProperty(Object key)
A convenience method for looking up a property value. It is equivalent to:
 getDocumentProperties().get(key);

Specified by:
getProperty in interface Document
Parameters:
key - the non-null property key
Returns:
the value of this property or null
See Also:
getDocumentProperties()

putProperty

public final void putProperty(Object key,
                              Object value)
A convenience method for storing up a property value. It is equivalent to:
 getDocumentProperties().put(key, value);
If value is null this method will remove the property.

Specified by:
putProperty in interface Document
Parameters:
key - the non-null key
value - the property value
See Also:
getDocumentProperties()

remove

public void remove(int offs,
                   int len)
            throws BadLocationException
Removes some content from the document. Removing content causes a write lock to be held while the actual changes are taking place. Observers are notified of the change on the thread that called this method.

This method is thread safe, although most Swing methods are not. Please see Threads and Swing for more information.

Specified by:
remove in interface Document
Parameters:
offs - the starting offset >= 0
len - the number of characters to remove >= 0
Throws:
BadLocationException - the given remove position is not a valid position within the document
See Also:
Document.remove(int, int)

replace

public void replace(int offset,
                    int length,
                    String text,
                    AttributeSet attrs)
             throws BadLocationException
Deletes the region of text from offset to offset + length, and replaces it with text. It is up to the implementation as to how this is implemented, some implementations may treat this as two distinct operations: a remove followed by an insert, others may treat the replace as one atomic operation.

Parameters:
offset - index of child element
length - length of text to delete, may be 0 indicating don't delete anything
text - text to insert, null indicates no text to insert
attrs - AttributeSet indicating attributes of inserted text, null is legal, and typically treated as an empty attributeset, but exact interpretation is left to the subclass
Throws:
BadLocationException - the given position is not a valid position within the document
Since:
1.4

insertString

public void insertString(int offs,
                         String str,
                         AttributeSet a)
                  throws BadLocationException
Inserts some content into the document. Inserting content causes a write lock to be held while the actual changes are taking place, followed by notification to the observers on the thread that grabbed the write lock.

This method is thread safe, although most Swing methods are not. Please see Threads and Swing for more information.

Specified by:
insertString in interface Document
Parameters:
offs - the starting offset >= 0
str - the string to insert; does nothing with null/empty strings
a - the attributes for the inserted content
Throws:
BadLocationException - the given insert position is not a valid position within the document
See Also:
Document.insertString(int, java.lang.String, javax.swing.text.AttributeSet)

getText

public String getText(int offset,
                      int length)
               throws BadLocationException
Gets a sequence of text from the document.

Specified by:
getText in interface Document
Parameters:
offset - the starting offset >= 0
length - the number of characters to retrieve >= 0
Returns:
the text
Throws:
BadLocationException - the range given includes a position that is not a valid position within the document
See Also:
Document.getText(int, int)

getText

public void getText(int offset,
                    int length,
                    Segment txt)
             throws BadLocationException
Fetches the text contained within the given portion of the document.

If the partialReturn property on the txt parameter is false, the data returned in the Segment will be the entire length requested and may or may not be a copy depending upon how the data was stored. If the partialReturn property is true, only the amount of text that can be returned without creating a copy is returned. Using partial returns will give better performance for situations where large parts of the document are being scanned. The following is an example of using the partial return to access the entire document:

   int nleft = doc.getDocumentLength();
   Segment text = new Segment();
   int offs = 0;
   text.setPartialReturn(true);
   while (nleft > 0) {
       doc.getText(offs, nleft, text);
       // do something with text
       nleft -= text.count;
       offs += text.count;
   }

Specified by:
getText in interface Document
Parameters:
offset - the starting offset >= 0
length - the number of characters to retrieve >= 0
txt - the Segment object to retrieve the text into
Throws:
BadLocationException - the range given includes a position that is not a valid position within the document

createPosition

public Position createPosition(int offs)
                        throws BadLocationException
Returns a position that will track change as the document is altered.

This method is thread safe, although most Swing methods are not. Please see Threads and Swing for more information.

Specified by:
createPosition in interface Document
Parameters:
offs - the position in the model >= 0
Returns:
the position
Throws:
BadLocationException - if the given position does not represent a valid location in the associated document
See Also:
Document.createPosition(int)

getStartPosition

public final Position getStartPosition()
Returns a position that represents the start of the document. The position returned can be counted on to track change and stay located at the beginning of the document.

Specified by:
getStartPosition in interface Document
Returns:
the position

getEndPosition

public final Position getEndPosition()
Returns a position that represents the end of the document. The position returned can be counted on to track change and stay located at the end of the document.

Specified by:
getEndPosition in interface Document
Returns:
the position

getRootElements

public Element[] getRootElements()
Gets all root elements defined. Typically, there will only be one so the default implementation is to return the default root element.

Specified by:
getRootElements in interface Document
Returns:
the root element

getDefaultRootElement

public abstract Element getDefaultRootElement()
Returns the root element that views should be based upon unless some other mechanism for assigning views to element structures is provided.

Specified by:
getDefaultRootElement in interface Document
Returns:
the root element
See Also:
Document.getDefaultRootElement()

getBidiRootElement

public Element getBidiRootElement()
Returns the root element of the bidirectional structure for this document. Its children represent character runs with a given Unicode bidi level.

getParagraphElement

public abstract Element getParagraphElement(int pos)
Get the paragraph element containing the given position. Sub-classes must define for themselves what exactly constitutes a paragraph. They should keep in mind however that a paragraph should at least be the unit of text over which to run the Unicode bidirectional algorithm.

Parameters:
pos - the starting offset >= 0
Returns:
the element

getAttributeContext

protected final AbstractDocument.AttributeContext getAttributeContext()
Fetches the context for managing attributes. This method effectively establishes the strategy used for compressing AttributeSet information.

Returns:
the context

insertUpdate

protected void insertUpdate(AbstractDocument.DefaultDocumentEvent chng,
                            AttributeSet attr)
Updates document structure as a result of text insertion. This will happen within a write lock. If a subclass of this class reimplements this method, it should delegate to the superclass as well.

Parameters:
chng - a description of the change
attr - the attributes for the change

removeUpdate

protected void removeUpdate(AbstractDocument.DefaultDocumentEvent chng)
Updates any document structure as a result of text removal. This method is called before the text is actually removed from the Content. This will happen within a write lock. If a subclass of this class reimplements this method, it should delegate to the superclass as well.

Parameters:
chng - a description of the change

postRemoveUpdate

protected void postRemoveUpdate(AbstractDocument.DefaultDocumentEvent chng)
Updates any document structure as a result of text removal. This method is called after the text has been removed from the Content. This will happen within a write lock. If a subclass of this class reimplements this method, it should delegate to the superclass as well.

Parameters:
chng - a description of the change

dump

public void dump(PrintStream out)
Gives a diagnostic dump.

Parameters:
out - the output stream

getContent

protected final AbstractDocument.Content getContent()
Gets the content for the document.

Returns:
the content

createLeafElement

protected Element createLeafElement(Element parent,
                                    AttributeSet a,
                                    int p0,
                                    int p1)
Creates a document leaf element. Hook through which elements are created to represent the document structure. Because this implementation keeps structure and content separate, elements grow automatically when content is extended so splits of existing elements follow. The document itself gets to decide how to generate elements to give flexibility in the type of elements used.

Parameters:
parent - the parent element
a - the attributes for the element
p0 - the beginning of the range >= 0
p1 - the end of the range >= p0
Returns:
the new element

createBranchElement

protected Element createBranchElement(Element parent,
                                      AttributeSet a)
Creates a document branch element, that can contain other elements.

Parameters:
parent - the parent element
a - the attributes
Returns:
the element

getCurrentWriter

protected final Thread getCurrentWriter()
Fetches the current writing thread if there is one. This can be used to distinguish whether a method is being called as part of an existing modification or if a lock needs to be acquired and a new transaction started.

Returns:
the thread actively modifying the document or null if there are no modifications in progress

writeLock

protected final void writeLock()
Acquires a lock to begin mutating the document this lock protects. There can be no writing, notification of changes, or reading going on in order to gain the lock. Additionally a thread is allowed to gain more than one writeLock, as long as it doesn't attempt to gain additional writeLocks from within document notification. Attempting to gain a writeLock from within a DocumentListener notification will result in an IllegalStateException. The ability to obtain more than one writeLock per thread allows subclasses to gain a writeLock, perform a number of operations, then release the lock.

Calls to writeLock must be balanced with calls to writeUnlock, else the Document will be left in a locked state so that no reading or writing can be done.

Throws:
IllegalStateException - thrown on illegal lock attempt. If the document is implemented properly, this can only happen if a document listener attempts to mutate the document. This situation violates the bean event model where order of delivery is not guaranteed and all listeners should be notified before further mutations are allowed.

writeUnlock

protected final void writeUnlock()
Releases a write lock previously obtained via writeLock. After decrementing the lock count if there are no oustanding locks this will allow a new writer, or readers.

See Also:
writeLock()

readLock

public final void readLock()
Acquires a lock to begin reading some state from the document. There can be multiple readers at the same time. Writing blocks the readers until notification of the change to the listeners has been completed. This method should be used very carefully to avoid unintended compromise of the document. It should always be balanced with a readUnlock.

See Also:
readUnlock()

readUnlock

public final void readUnlock()
Does a read unlock. This signals that one of the readers is done. If there are no more readers then writing can begin again. This should be balanced with a readLock, and should occur in a finally statement so that the balance is guaranteed. The following is an example.

     readLock();
     try {
         // do something
     } finally {
         readUnlock();
     }

See Also:
readLock()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


AbstractDocument.AbstractElement (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class AbstractDocument.AbstractElement

java.lang.Object
    extended by javax.swing.text.AbstractDocument.AbstractElement
All Implemented Interfaces:
AttributeSet, Element, MutableAttributeSet, Serializable, TreeNode
Direct Known Subclasses:
AbstractDocument.BranchElement, AbstractDocument.LeafElement
Enclosing class:
AbstractDocument
public abstract class AbstractDocument.AbstractElement
extends Object
implements Element, MutableAttributeSet, Serializable, TreeNode

Implements the abstract part of an element. By default elements support attributes by having a field that represents the immutable part of the current attribute set for the element. The element itself implements MutableAttributeSet which can be used to modify the set by fetching a new immutable set. The immutable sets are provided by the AttributeContext associated with the document.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Nested Class Summary
Nested classes inherited from class javax.swing.text.AttributeSet
AttributeSet.CharacterAttribute, AttributeSet.ColorAttribute, AttributeSet.FontAttribute, AttributeSet.ParagraphAttribute
Field Summary
Fields inherited from interface javax.swing.text.AttributeSet
NameAttribute, ResolveAttribute
Constructor Summary
AbstractDocument.AbstractElement(Element parent, AttributeSet a)
Creates a new AbstractElement.
Method Summary
void | addAttribute(Object name, Object value) Adds an attribute to the element.
void | addAttributes(AttributeSet attr) Adds a set of attributes to the element.
abstract Enumeration | children() Returns the children of the receiver as an Enumeration.
boolean | containsAttribute(Object name, Object value) Checks whether a given attribute name/value is defined.
boolean | containsAttributes(AttributeSet attrs) Checks whether the element contains all the attributes.
AttributeSet | copyAttributes() Copies a set of attributes.
void | dump(PrintStream psOut, int indentAmount) Dumps a debugging representation of the element hierarchy.
abstract boolean | getAllowsChildren() Returns true if the receiver allows children.
Object | getAttribute(Object attrName) Gets the value of an attribute.
int | getAttributeCount() Gets the number of attributes that are defined.
Enumeration | getAttributeNames() Gets the names of all attributes.
AttributeSet | getAttributes() Gets the attributes for the element.
TreeNode | getChildAt(int childIndex) Returns the child TreeNode at index childIndex.
int | getChildCount() Returns the number of children TreeNode's receiver contains.
Document | getDocument() Retrieves the underlying model.
abstract Element | getElement(int index) Gets a child element.
abstract int | getElementCount() Gets the number of children for the element.
abstract int | getElementIndex(int offset) Gets the child element index closest to the given model offset.
abstract int | getEndOffset() Gets the ending offset in the model for the element.
int | getIndex(TreeNode node) Returns the index of node in the receivers children.
String | getName() Gets the name of the element.
TreeNode | getParent() Returns the parent TreeNode of the receiver.
Element | getParentElement() Gets the parent of the element.
AttributeSet | getResolveParent() Gets the resolving parent.
abstract int | getStartOffset() Gets the starting offset in the model for the element.
boolean | isDefined(Object attrName) Checks whether a given attribute is defined.
boolean | isEqual(AttributeSet attr) Checks whether two attribute sets are equal.
abstract boolean | isLeaf() Checks whether the element is a leaf.
void | removeAttribute(Object name) Removes an attribute from the set.
void | removeAttributes(AttributeSet attrs) Removes a set of attributes for the element.
void | removeAttributes(Enumeration names) Removes a set of attributes for the element.
void | setResolveParent(AttributeSet parent) Sets the resolving parent.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

AbstractDocument.AbstractElement

public AbstractDocument.AbstractElement(Element parent,
                                        AttributeSet a)
Creates a new AbstractElement.

Parameters:
parent - the parent element
a - the attributes for the element
Method Detail

dump

public void dump(PrintStream psOut,
                 int indentAmount)
Dumps a debugging representation of the element hierarchy.

Parameters:
psOut - the output stream
indentAmount - the indentation level >= 0

getAttributeCount

public int getAttributeCount()
Gets the number of attributes that are defined.

Specified by:
getAttributeCount in interface AttributeSet
Returns:
the number of attributes >= 0
See Also:
AttributeSet.getAttributeCount()

isDefined

public boolean isDefined(Object attrName)
Checks whether a given attribute is defined.

Specified by:
isDefined in interface AttributeSet
Parameters:
attrName - the non-null attribute name
Returns:
true if the attribute is defined
See Also:
AttributeSet.isDefined(java.lang.Object)

isEqual

public boolean isEqual(AttributeSet attr)
Checks whether two attribute sets are equal.

Specified by:
isEqual in interface AttributeSet
Parameters:
attr - the attribute set to check against
Returns:
true if the same
See Also:
AttributeSet.isEqual(javax.swing.text.AttributeSet)

copyAttributes

public AttributeSet copyAttributes()
Copies a set of attributes.

Specified by:
copyAttributes in interface AttributeSet
Returns:
the copy
See Also:
AttributeSet.copyAttributes()

getAttribute

public Object getAttribute(Object attrName)
Gets the value of an attribute.

Specified by:
getAttribute in interface AttributeSet
Parameters:
attrName - the non-null attribute name
Returns:
the attribute value
See Also:
AttributeSet.getAttribute(java.lang.Object)

getAttributeNames

public Enumeration getAttributeNames()
Gets the names of all attributes.

Specified by:
getAttributeNames in interface AttributeSet
Returns:
the attribute names as an enumeration
See Also:
AttributeSet.getAttributeNames()

containsAttribute

public boolean containsAttribute(Object name,
                                 Object value)
Checks whether a given attribute name/value is defined.

Specified by:
containsAttribute in interface AttributeSet
Parameters:
name - the non-null attribute name
value - the attribute value
Returns:
true if the name/value is defined
See Also:
AttributeSet.containsAttribute(java.lang.Object, java.lang.Object)

containsAttributes

public boolean containsAttributes(AttributeSet attrs)
Checks whether the element contains all the attributes.

Specified by:
containsAttributes in interface AttributeSet
Parameters:
attrs - the attributes to check
Returns:
true if the element contains all the attributes
See Also:
AttributeSet.containsAttributes(javax.swing.text.AttributeSet)

getResolveParent

public AttributeSet getResolveParent()
Gets the resolving parent. If not overridden, the resolving parent defaults to the parent element.

Specified by:
getResolveParent in interface AttributeSet
Returns:
the attributes from the parent, null if none
See Also:
AttributeSet.getResolveParent()

addAttribute

public void addAttribute(Object name,
                         Object value)
Adds an attribute to the element.

Specified by:
addAttribute in interface MutableAttributeSet
Parameters:
name - the non-null attribute name
value - the attribute value
See Also:
MutableAttributeSet.addAttribute(java.lang.Object, java.lang.Object)

addAttributes

public void addAttributes(AttributeSet attr)
Adds a set of attributes to the element.

Specified by:
addAttributes in interface MutableAttributeSet
Parameters:
attr - the attributes to add
See Also:
MutableAttributeSet.addAttribute(java.lang.Object, java.lang.Object)

removeAttribute

public void removeAttribute(Object name)
Removes an attribute from the set.

Specified by:
removeAttribute in interface MutableAttributeSet
Parameters:
name - the non-null attribute name
See Also:
MutableAttributeSet.removeAttribute(java.lang.Object)

removeAttributes

public void removeAttributes(Enumeration names)
Removes a set of attributes for the element.

Specified by:
removeAttributes in interface MutableAttributeSet
Parameters:
names - the attribute names
See Also:
MutableAttributeSet.removeAttributes(java.util.Enumeration)

removeAttributes

public void removeAttributes(AttributeSet attrs)
Removes a set of attributes for the element.

Specified by:
removeAttributes in interface MutableAttributeSet
Parameters:
attrs - the attributes
See Also:
MutableAttributeSet.removeAttributes(java.util.Enumeration)

setResolveParent

public void setResolveParent(AttributeSet parent)
Sets the resolving parent.

Specified by:
setResolveParent in interface MutableAttributeSet
Parameters:
parent - the parent, null if none
See Also:
MutableAttributeSet.setResolveParent(javax.swing.text.AttributeSet)

getDocument

public Document getDocument()
Retrieves the underlying model.

Specified by:
getDocument in interface Element
Returns:
the model

getParentElement

public Element getParentElement()
Gets the parent of the element.

Specified by:
getParentElement in interface Element
Returns:
the parent

getAttributes

public AttributeSet getAttributes()
Gets the attributes for the element.

Specified by:
getAttributes in interface Element
Returns:
the attribute set

getName

public String getName()
Gets the name of the element.

Specified by:
getName in interface Element
Returns:
the name, null if none

getStartOffset

public abstract int getStartOffset()
Gets the starting offset in the model for the element.

Specified by:
getStartOffset in interface Element
Returns:
the offset >= 0
See Also:
Document, AbstractDocument

getEndOffset

public abstract int getEndOffset()
Gets the ending offset in the model for the element.

Specified by:
getEndOffset in interface Element
Returns:
the offset >= 0
See Also:
Document, AbstractDocument

getElement

public abstract Element getElement(int index)
Gets a child element.

Specified by:
getElement in interface Element
Parameters:
index - the child index, >= 0 && < getElementCount()
Returns:
the child element

getElementCount

public abstract int getElementCount()
Gets the number of children for the element.

Specified by:
getElementCount in interface Element
Returns:
the number of children >= 0

getElementIndex

public abstract int getElementIndex(int offset)
Gets the child element index closest to the given model offset.

Specified by:
getElementIndex in interface Element
Parameters:
offset - the offset >= 0
Returns:
the element index >= 0

isLeaf

public abstract boolean isLeaf()
Checks whether the element is a leaf.

Specified by:
isLeaf in interface Element
Returns:
true if a leaf

getChildAt

public TreeNode getChildAt(int childIndex)
Returns the child TreeNode at index childIndex.

Specified by:
getChildAt in interface TreeNode

getChildCount

public int getChildCount()
Returns the number of children TreeNode's receiver contains.

Specified by:
getChildCount in interface TreeNode
Returns:
the number of children TreeNodews's receiver contains

getParent

public TreeNode getParent()
Returns the parent TreeNode of the receiver.

Specified by:
getParent in interface TreeNode
Returns:
the parent TreeNode of the receiver

getIndex

public int getIndex(TreeNode node)
Returns the index of node in the receivers children. If the receiver does not contain node, -1 will be returned.

Specified by:
getIndex in interface TreeNode
Parameters:
node - the location of interest
Returns:
the index of node in the receiver's children, or -1 if absent

getAllowsChildren

public abstract boolean getAllowsChildren()
Returns true if the receiver allows children.

Specified by:
getAllowsChildren in interface TreeNode
Returns:
true if the receiver allows children, otherwise false

children

public abstract Enumeration children()
Returns the children of the receiver as an Enumeration.

Specified by:
children in interface TreeNode
Returns:
the children of the receiver as an Enumeration
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


AbstractDocument.AttributeContext (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Interface AbstractDocument.AttributeContext

All Known Implementing Classes:
StyleContext
Enclosing interface:
AbstractDocument
public static interface AbstractDocument.AttributeContext

An interface that can be used to allow MutableAttributeSet implementations to use pluggable attribute compression techniques. Each mutation of the attribute set can be used to exchange a previous AttributeSet instance with another, preserving the possibility of the AttributeSet remaining immutable. An implementation is provided by the StyleContext class. The Element implementations provided by this class use this interface to provide their MutableAttributeSet implementations, so that different AttributeSet compression techniques can be employed. The method getAttributeContext should be implemented to return the object responsible for implementing the desired compression technique.

See Also:
StyleContext

Method Summary
AttributeSet | addAttribute(AttributeSet old, Object name, Object value) Adds an attribute to the given set, and returns the new representative set.
AttributeSet | addAttributes(AttributeSet old, AttributeSet attr) Adds a set of attributes to the element.
AttributeSet | getEmptySet() Fetches an empty AttributeSet.
void | reclaim(AttributeSet a) Reclaims an attribute set.
AttributeSet | removeAttribute(AttributeSet old, Object name) Removes an attribute from the set.
AttributeSet | removeAttributes(AttributeSet old, AttributeSet attrs) Removes a set of attributes for the element.
AttributeSet | removeAttributes(AttributeSet old, Enumeration names) Removes a set of attributes for the element.

Method Detail

addAttribute

public AttributeSet addAttribute(AttributeSet old,
                                 Object name,
                                 Object value)
Adds an attribute to the given set, and returns the new representative set.

Parameters:
old - the old attribute set
name - the non-null attribute name
value - the attribute value
Returns:
the updated attribute set
See Also:
MutableAttributeSet.addAttribute(java.lang.Object, java.lang.Object)

addAttributes

public AttributeSet addAttributes(AttributeSet old,
                                  AttributeSet attr)
Adds a set of attributes to the element.

Parameters:
old - the old attribute set
attr - the attributes to add
Returns:
the updated attribute set
See Also:
MutableAttributeSet.addAttribute(java.lang.Object, java.lang.Object)

removeAttribute

public AttributeSet removeAttribute(AttributeSet old,
                                    Object name)
Removes an attribute from the set.

Parameters:
old - the old attribute set
name - the non-null attribute name
Returns:
the updated attribute set
See Also:
MutableAttributeSet.removeAttribute(java.lang.Object)

removeAttributes

public AttributeSet removeAttributes(AttributeSet old,
                                     Enumeration names)
Removes a set of attributes for the element.

Parameters:
old - the old attribute set
names - the attribute names
Returns:
the updated attribute set
See Also:
MutableAttributeSet.removeAttributes(java.util.Enumeration)

removeAttributes

public AttributeSet removeAttributes(AttributeSet old,
                                     AttributeSet attrs)
Removes a set of attributes for the element.

Parameters:
old - the old attribute set
attrs - the attributes
Returns:
the updated attribute set
See Also:
MutableAttributeSet.removeAttributes(java.util.Enumeration)

getEmptySet

public AttributeSet getEmptySet()
Fetches an empty AttributeSet.

Returns:
the attribute set

reclaim

public void reclaim(AttributeSet a)
Reclaims an attribute set. This is a way for a MutableAttributeSet to mark that it no longer need a particular immutable set. This is only necessary in 1.1 where there are no weak references. A 1.1 implementation would call this in its finalize method.

Parameters:
a - the attribute set to reclaim
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


AbstractDocument.BranchElement (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class AbstractDocument.BranchElement

java.lang.Object
    extended by javax.swing.text.AbstractDocument.AbstractElement
        extended by javax.swing.text.AbstractDocument.BranchElement
All Implemented Interfaces:
AttributeSet, Element, MutableAttributeSet, Serializable, TreeNode
Direct Known Subclasses:
DefaultStyledDocument.SectionElement, HTMLDocument.BlockElement
Enclosing class:
AbstractDocument
public class AbstractDocument.BranchElement
extends AbstractDocument.AbstractElement

Implements a composite element that contains other elements.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Nested Class Summary
Nested classes inherited from class javax.swing.text.AttributeSet
AttributeSet.CharacterAttribute, AttributeSet.ColorAttribute, AttributeSet.FontAttribute, AttributeSet.ParagraphAttribute
Field Summary
Fields inherited from interface javax.swing.text.AttributeSet
NameAttribute, ResolveAttribute
Constructor Summary
AbstractDocument.BranchElement(Element parent, AttributeSet a)
Constructs a composite element that initially contains no children.
Method Summary
Enumeration | children() Returns the children of the receiver as an Enumeration.
boolean | getAllowsChildren() Returns true if the receiver allows children.
Element | getElement(int index) Gets a child element.
int | getElementCount() Gets the number of children for the element.
int | getElementIndex(int offset) Gets the child element index closest to the given model offset.
int | getEndOffset() Gets the ending offset in the model for the element.
String | getName() Gets the element name.
int | getStartOffset() Gets the starting offset in the model for the element.
boolean | isLeaf() Checks whether the element is a leaf.
Element | positionToElement(int pos) Gets the child element that contains the given model position.
void | replace(int offset, int length, Element[] elems) Replaces content with a new set of elements.
String | toString() Converts the element to a string.
Methods inherited from class javax.swing.text.AbstractDocument.AbstractElement
addAttribute, addAttributes, containsAttribute, containsAttributes, copyAttributes, dump, getAttribute, getAttributeCount, getAttributeNames, getAttributes, getChildAt, getChildCount, getDocument, getIndex, getParent, getParentElement, getResolveParent, isDefined, isEqual, removeAttribute, removeAttributes, removeAttributes, setResolveParent
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

AbstractDocument.BranchElement

public AbstractDocument.BranchElement(Element parent,
                                      AttributeSet a)
Constructs a composite element that initially contains no children.

Parameters:
parent - The parent element
a - the attributes for the element
Method Detail

positionToElement

public Element positionToElement(int pos)
Gets the child element that contains the given model position.

Parameters:
pos - the position >= 0
Returns:
the element, null if none

replace

public void replace(int offset,
                    int length,
                    Element[] elems)
Replaces content with a new set of elements.

Parameters:
offset - the starting offset >= 0
length - the length to replace >= 0
elems - the new elements

toString

public String toString()
Converts the element to a string.

Overrides:
toString in class Object
Returns:
the string

getName

public String getName()
Gets the element name.

Specified by:
getName in interface Element
Overrides:
getName in class AbstractDocument.AbstractElement
Returns:
the element name

getStartOffset

public int getStartOffset()
Gets the starting offset in the model for the element.

Specified by:
getStartOffset in interface Element
Specified by:
getStartOffset in class AbstractDocument.AbstractElement
Returns:
the offset >= 0

getEndOffset

public int getEndOffset()
Gets the ending offset in the model for the element.

Specified by:
getEndOffset in interface Element
Specified by:
getEndOffset in class AbstractDocument.AbstractElement
Returns:
the offset >= 0

getElement

public Element getElement(int index)
Gets a child element.

Specified by:
getElement in interface Element
Specified by:
getElement in class AbstractDocument.AbstractElement
Parameters:
index - the child index, >= 0 && < getElementCount()
Returns:
the child element, null if none

getElementCount

public int getElementCount()
Gets the number of children for the element.

Specified by:
getElementCount in interface Element
Specified by:
getElementCount in class AbstractDocument.AbstractElement
Returns:
the number of children >= 0

getElementIndex

public int getElementIndex(int offset)
Gets the child element index closest to the given model offset.

Specified by:
getElementIndex in interface Element
Specified by:
getElementIndex in class AbstractDocument.AbstractElement
Parameters:
offset - the offset >= 0
Returns:
the element index >= 0

isLeaf

public boolean isLeaf()
Checks whether the element is a leaf.

Specified by:
isLeaf in interface Element
Specified by:
isLeaf in class AbstractDocument.AbstractElement
Returns:
true if a leaf

getAllowsChildren

public boolean getAllowsChildren()
Returns true if the receiver allows children.

Specified by:
getAllowsChildren in interface TreeNode
Specified by:
getAllowsChildren in class AbstractDocument.AbstractElement
Returns:
true if the receiver allows children, otherwise false

children

public Enumeration children()
Returns the children of the receiver as an Enumeration.

Specified by:
children in interface TreeNode
Specified by:
children in class AbstractDocument.AbstractElement
Returns:
the children of the receiver
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


AbstractDocument.Content (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Interface AbstractDocument.Content

All Known Implementing Classes:
GapContent, StringContent
Enclosing interface:
AbstractDocument
public static interface AbstractDocument.Content

Interface to describe a sequence of character content that can be edited. Implementations may or may not support a history mechanism which will be reflected by whether or not mutations return an UndoableEdit implementation.

See Also:
AbstractDocument

Method Summary
Position | createPosition(int offset) Creates a position within the content that will track change as the content is mutated.
void | getChars(int where, int len, Segment txt) Gets a sequence of characters and copies them into a Segment.
String | getString(int where, int len) Fetches a string of characters contained in the sequence.
UndoableEdit | insertString(int where, String str) Inserts a string of characters into the sequence.
int | length() Current length of the sequence of character content.
UndoableEdit | remove(int where, int nitems) Removes some portion of the sequence.

Method Detail

createPosition

public Position createPosition(int offset)
                        throws BadLocationException
Creates a position within the content that will track change as the content is mutated.

Parameters:
offset - the offset in the content >= 0
Returns:
a Position
Throws:
BadLocationException - for an invalid offset

length

public int length()
Current length of the sequence of character content.

Returns:
the length >= 0

insertString

public UndoableEdit insertString(int where,
                                 String str)
                          throws BadLocationException
Inserts a string of characters into the sequence.

Parameters:
where - offset into the sequence to make the insertion >= 0
str - string to insert
Returns:
if the implementation supports a history mechanism, a reference to an Edit implementation will be returned, otherwise returns null
Throws:
BadLocationException - thrown if the area covered by the arguments is not contained in the character sequence

remove

public UndoableEdit remove(int where,
                           int nitems)
                    throws BadLocationException
Removes some portion of the sequence.

Parameters:
where - The offset into the sequence to make the insertion >= 0.
nitems - The number of items in the sequence to remove >= 0.
Returns:
If the implementation supports a history mechansim, a reference to an Edit implementation will be returned, otherwise null.
Throws:
BadLocationException - Thrown if the area covered by the arguments is not contained in the character sequence.

getString

public String getString(int where,
                        int len)
                 throws BadLocationException
Fetches a string of characters contained in the sequence.

Parameters:
where - Offset into the sequence to fetch >= 0.
len - number of characters to copy >= 0.
Returns:
the string
Throws:
BadLocationException - Thrown if the area covered by the arguments is not contained in the character sequence.

getChars

public void getChars(int where,
                     int len,
                     Segment txt)
              throws BadLocationException
Gets a sequence of characters and copies them into a Segment.

Parameters:
where - the starting offset >= 0
len - the number of characters >= 0
txt - the target location to copy into
Throws:
BadLocationException - Thrown if the area covered by the arguments is not contained in the character sequence.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


AbstractDocument.DefaultDocumentEvent (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class AbstractDocument.DefaultDocumentEvent

java.lang.Object
    extended by javax.swing.undo.AbstractUndoableEdit
        extended by javax.swing.undo.CompoundEdit
            extended by javax.swing.text.AbstractDocument.DefaultDocumentEvent
All Implemented Interfaces:
DocumentEvent, Serializable, UndoableEdit
Enclosing class:
AbstractDocument
public class AbstractDocument.DefaultDocumentEvent
extends CompoundEdit
implements DocumentEvent

Stores document changes as the document is being modified. Can subsequently be used for change notification when done with the document modification transaction. This is used by the AbstractDocument class and its extensions for broadcasting change information to the document listeners.

Nested Class Summary
Nested classes inherited from class javax.swing.event.DocumentEvent
DocumentEvent.ElementChange, DocumentEvent.EventType
Field Summary
Fields inherited from class javax.swing.undo.CompoundEdit
edits
Fields inherited from class javax.swing.undo.AbstractUndoableEdit
RedoName, UndoName
Constructor Summary
AbstractDocument.DefaultDocumentEvent(int offs, int len, DocumentEvent.EventType type)
Constructs a change record.
Method Summary
boolean | addEdit(UndoableEdit anEdit) Adds a document edit.
DocumentEvent.ElementChange | getChange(Element elem) Gets the changes for an element.
Document | getDocument() Gets the document that sourced the change event.
int | getLength() Returns the length of the change.
int | getOffset() Returns the offset within the document of the start of the change.
String | getPresentationName() Provides a localized, human readable description of this edit suitable for use in, say, a change log.
String | getRedoPresentationName() Provides a localized, human readable description of the redoable form of this edit, e.g.
DocumentEvent.EventType | getType() Returns the type of event.
String | getUndoPresentationName() Provides a localized, human readable description of the undoable form of this edit, e.g.
boolean | isSignificant() DefaultDocument events are significant.
void | redo() Redoes a change.
String | toString() Returns a string description of the change event.
void | undo() Undoes a change.
Methods inherited from class javax.swing.undo.CompoundEdit
canRedo, canUndo, die, end, isInProgress, lastEdit
Methods inherited from class javax.swing.undo.AbstractUndoableEdit
replaceEdit
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

AbstractDocument.DefaultDocumentEvent

public AbstractDocument.DefaultDocumentEvent(int offs,
                                             int len,
                                             DocumentEvent.EventType type)
Constructs a change record.

Parameters:
offs - the offset into the document of the change >= 0
len - the length of the change >= 0
type - the type of event (DocumentEvent.EventType)
Method Detail

toString

public String toString()
Returns a string description of the change event.

Overrides:
toString in class CompoundEdit
Returns:
a string

addEdit

public boolean addEdit(UndoableEdit anEdit)
Adds a document edit. If the number of edits crosses a threshold, this switches on a hashtable lookup for ElementChange implementations since access of these needs to be relatively quick.

Specified by:
addEdit in interface UndoableEdit
Overrides:
addEdit in class CompoundEdit
Parameters:
anEdit - a document edit record
Returns:
true if the edit was added

redo

public void redo()
          throws CannotRedoException
Redoes a change.

Specified by:
redo in interface UndoableEdit
Overrides:
redo in class CompoundEdit
Throws:
CannotRedoException - if the change cannot be redone

undo

public void undo()
          throws CannotUndoException
Undoes a change.

Specified by:
undo in interface UndoableEdit
Overrides:
undo in class CompoundEdit
Throws:
CannotUndoException - if the change cannot be undone

isSignificant

public boolean isSignificant()
DefaultDocument events are significant. If you wish to aggregate DefaultDocumentEvents to present them as a single edit to the user place them into a CompoundEdit.

Specified by:
isSignificant in interface UndoableEdit
Overrides:
isSignificant in class CompoundEdit
Returns:
whether the event is significant for edit undo purposes

getPresentationName

public String getPresentationName()
Provides a localized, human readable description of this edit suitable for use in, say, a change log.

Specified by:
getPresentationName in interface UndoableEdit
Overrides:
getPresentationName in class CompoundEdit
Returns:
the description

getUndoPresentationName

public String getUndoPresentationName()
Provides a localized, human readable description of the undoable form of this edit, e.g. for use as an Undo menu item. Typically derived from getDescription();

Specified by:
getUndoPresentationName in interface UndoableEdit
Overrides:
getUndoPresentationName in class CompoundEdit
Returns:
the description

getRedoPresentationName

public String getRedoPresentationName()
Provides a localized, human readable description of the redoable form of this edit, e.g. for use as a Redo menu item. Typically derived from getPresentationName();

Specified by:
getRedoPresentationName in interface UndoableEdit
Overrides:
getRedoPresentationName in class CompoundEdit
Returns:
the description

getType

public DocumentEvent.EventType getType()
Returns the type of event.

Specified by:
getType in interface DocumentEvent
Returns:
the event type as a DocumentEvent.EventType
See Also:
DocumentEvent.getType()

getOffset

public int getOffset()
Returns the offset within the document of the start of the change.

Specified by:
getOffset in interface DocumentEvent
Returns:
the offset >= 0
See Also:
DocumentEvent.getOffset()

getLength

public int getLength()
Returns the length of the change.

Specified by:
getLength in interface DocumentEvent
Returns:
the length >= 0
See Also:
DocumentEvent.getLength()

getDocument

public Document getDocument()
Gets the document that sourced the change event.

Specified by:
getDocument in interface DocumentEvent
Returns:
the document
See Also:
DocumentEvent.getDocument()

getChange

public DocumentEvent.ElementChange getChange(Element elem)
Gets the changes for an element.

Specified by:
getChange in interface DocumentEvent
Parameters:
elem - the element
Returns:
the changes
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


AbstractDocument.ElementEdit (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class AbstractDocument.ElementEdit

java.lang.Object
    extended by javax.swing.undo.AbstractUndoableEdit
        extended by javax.swing.text.AbstractDocument.ElementEdit
All Implemented Interfaces:
DocumentEvent.ElementChange, Serializable, UndoableEdit
Enclosing class:
AbstractDocument
public static class AbstractDocument.ElementEdit
extends AbstractUndoableEdit
implements DocumentEvent.ElementChange

An implementation of ElementChange that can be added to the document event.

Field Summary
Fields inherited from class javax.swing.undo.AbstractUndoableEdit
RedoName, UndoName
Constructor Summary
AbstractDocument.ElementEdit(Element e, int index, Element[] removed, Element[] added)
Constructs an edit record.
Method Summary
Element[] | getChildrenAdded() Gets a list of children that were added.
Element[] | getChildrenRemoved() Gets a list of children that were removed.
Element | getElement() Returns the underlying element.
int | getIndex() Returns the index into the list of elements.
void | redo() Redoes a change.
void | undo() Undoes a change.
Methods inherited from class javax.swing.undo.AbstractUndoableEdit
addEdit, canRedo, canUndo, die, getPresentationName, getRedoPresentationName, getUndoPresentationName, isSignificant, replaceEdit, toString
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

AbstractDocument.ElementEdit

public AbstractDocument.ElementEdit(Element e,
                                    int index,
                                    Element[] removed,
                                    Element[] added)
Constructs an edit record. This does not modify the element so it can safely be used to catch up a view to the current model state for views that just attached to a model.

Parameters:
e - the element
index - the index into the model >= 0
removed - a set of elements that were removed
added - a set of elements that were added
Method Detail

getElement

public Element getElement()
Returns the underlying element.

Specified by:
getElement in interface DocumentEvent.ElementChange
Returns:
the element

getIndex

public int getIndex()
Returns the index into the list of elements.

Specified by:
getIndex in interface DocumentEvent.ElementChange
Returns:
the index >= 0

getChildrenRemoved

public Element[] getChildrenRemoved()
Gets a list of children that were removed.

Specified by:
getChildrenRemoved in interface DocumentEvent.ElementChange
Returns:
the list

getChildrenAdded

public Element[] getChildrenAdded()
Gets a list of children that were added.

Specified by:
getChildrenAdded in interface DocumentEvent.ElementChange
Returns:
the list

redo

public void redo()
          throws CannotRedoException
Redoes a change.

Specified by:
redo in interface UndoableEdit
Overrides:
redo in class AbstractUndoableEdit
Throws:
CannotRedoException - if the change cannot be redone
See Also:
AbstractUndoableEdit.canRedo()

undo

public void undo()
          throws CannotUndoException
Undoes a change.

Specified by:
undo in interface UndoableEdit
Overrides:
undo in class AbstractUndoableEdit
Throws:
CannotUndoException - if the change cannot be undone
See Also:
AbstractUndoableEdit.canUndo()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


AbstractDocument.LeafElement (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class AbstractDocument.LeafElement

java.lang.Object
    extended by javax.swing.text.AbstractDocument.AbstractElement
        extended by javax.swing.text.AbstractDocument.LeafElement
All Implemented Interfaces:
AttributeSet, Element, MutableAttributeSet, Serializable, TreeNode
Direct Known Subclasses:
HTMLDocument.RunElement
Enclosing class:
AbstractDocument
public class AbstractDocument.LeafElement
extends AbstractDocument.AbstractElement

Implements an element that directly represents content of some kind.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

See Also:
Element

Nested Class Summary
Nested classes inherited from class javax.swing.text.AttributeSet
AttributeSet.CharacterAttribute, AttributeSet.ColorAttribute, AttributeSet.FontAttribute, AttributeSet.ParagraphAttribute
Field Summary
Fields inherited from interface javax.swing.text.AttributeSet
NameAttribute, ResolveAttribute
Constructor Summary
AbstractDocument.LeafElement(Element parent, AttributeSet a, int offs0, int offs1)
Constructs an element that represents content within the document (has no children).
Method Summary
Enumeration | children() Returns the children of the receiver as an Enumeration.
boolean | getAllowsChildren() Returns true if the receiver allows children.
Element | getElement(int index) Gets a child element.
int | getElementCount() Returns the number of child elements.
int | getElementIndex(int pos) Gets the child element index closest to the given model offset.
int | getEndOffset() Gets the ending offset in the model for the element.
String | getName() Gets the element name.
int | getStartOffset() Gets the starting offset in the model for the element.
boolean | isLeaf() Checks whether the element is a leaf.
String | toString() Converts the element to a string.
Methods inherited from class javax.swing.text.AbstractDocument.AbstractElement
addAttribute, addAttributes, containsAttribute, containsAttributes, copyAttributes, dump, getAttribute, getAttributeCount, getAttributeNames, getAttributes, getChildAt, getChildCount, getDocument, getIndex, getParent, getParentElement, getResolveParent, isDefined, isEqual, removeAttribute, removeAttributes, removeAttributes, setResolveParent
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

AbstractDocument.LeafElement

public AbstractDocument.LeafElement(Element parent,
                                    AttributeSet a,
                                    int offs0,
                                    int offs1)
Constructs an element that represents content within the document (has no children).

Parameters:
parent - The parent element
a - The element attributes
offs0 - The start offset >= 0
offs1 - The end offset >= offs0
Method Detail

toString

public String toString()
Converts the element to a string.

Overrides:
toString in class Object
Returns:
the string

getStartOffset

public int getStartOffset()
Gets the starting offset in the model for the element.

Specified by:
getStartOffset in interface Element
Specified by:
getStartOffset in class AbstractDocument.AbstractElement
Returns:
the offset >= 0

getEndOffset

public int getEndOffset()
Gets the ending offset in the model for the element.

Specified by:
getEndOffset in interface Element
Specified by:
getEndOffset in class AbstractDocument.AbstractElement
Returns:
the offset >= 0

getName

public String getName()
Gets the element name.

Specified by:
getName in interface Element
Overrides:
getName in class AbstractDocument.AbstractElement
Returns:
the name

getElementIndex

public int getElementIndex(int pos)
Gets the child element index closest to the given model offset.

Specified by:
getElementIndex in interface Element
Specified by:
getElementIndex in class AbstractDocument.AbstractElement
Parameters:
pos - the offset >= 0
Returns:
the element index >= 0

getElement

public Element getElement(int index)
Gets a child element.

Specified by:
getElement in interface Element
Specified by:
getElement in class AbstractDocument.AbstractElement
Parameters:
index - the child index, >= 0 && < getElementCount()
Returns:
the child element

getElementCount

public int getElementCount()
Returns the number of child elements.

Specified by:
getElementCount in interface Element
Specified by:
getElementCount in class AbstractDocument.AbstractElement
Returns:
the number of children >= 0

isLeaf

public boolean isLeaf()
Checks whether the element is a leaf.

Specified by:
isLeaf in interface Element
Specified by:
isLeaf in class AbstractDocument.AbstractElement
Returns:
true if a leaf

getAllowsChildren

public boolean getAllowsChildren()
Returns true if the receiver allows children.

Specified by:
getAllowsChildren in interface TreeNode
Specified by:
getAllowsChildren in class AbstractDocument.AbstractElement
Returns:
true if the receiver allows children, otherwise false

children

public Enumeration children()
Returns the children of the receiver as an Enumeration.

Specified by:
children in interface TreeNode
Specified by:
children in class AbstractDocument.AbstractElement
Returns:
the children of the receiver
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


AbstractWriter (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class AbstractWriter

java.lang.Object
    extended by javax.swing.text.AbstractWriter
Direct Known Subclasses:
HTMLWriter, MinimalHTMLWriter
public abstract class AbstractWriter
extends Object

AbstractWriter is an abstract class that actually does the work of writing out the element tree including the attributes. In terms of how much is written out per line, the writer defaults to 100. But this value can be set by subclasses.

Field Summary
protected static char NEWLINE
How the text packages models newlines.
Constructor Summary
protected | AbstractWriter(Writer w, Document doc) Creates a new AbstractWriter.
protected | AbstractWriter(Writer w, Document doc, int pos, int len) Creates a new AbstractWriter.
protected | AbstractWriter(Writer w, Element root) Creates a new AbstractWriter.
protected | AbstractWriter(Writer w, Element root, int pos, int len) Creates a new AbstractWriter.
Method Summary
protected void | decrIndent() Decrements the indent level.
protected boolean | getCanWrapLines() Returns whether or not the lines can be wrapped.
protected int | getCurrentLineLength() Returns the current line length.
protected Document | getDocument() Fetches the document.
protected ElementIterator | getElementIterator() Fetches the ElementIterator.
int | getEndOffset() Returns the last offset to be output.
protected int | getIndentLevel() Returns the current indentation level.
protected int | getIndentSpace() Returns the amount of space to indent.
protected int | getLineLength() Returns the maximum line length.
String | getLineSeparator() Returns the string used to represent newlines.
int | getStartOffset() Returns the first offset to be output.
protected String | getText(Element elem) Returns the text associated with the element.
protected Writer | getWriter() Returns the Writer that is used to output the content.
protected void | incrIndent() Increments the indent level.
protected void | indent() Does indentation.
protected boolean | inRange(Element next) This method determines whether the current element is in the range specified.
protected boolean | isLineEmpty() Returns true if the current line should be considered empty.
protected void | output(char[] content, int start, int length) The last stop in writing out content.
protected void | setCanWrapLines(boolean newValue) Sets whether or not lines can be wrapped.
protected void | setCurrentLineLength(int length) Sets the current line length.
protected void | setIndentSpace(int space) Enables subclasses to specify how many spaces an indent maps to.
protected void | setLineLength(int l) Enables subclasses to set the number of characters they want written per line.
void | setLineSeparator(String value) Sets the String used to reprsent newlines.
protected void | text(Element elem) Writes out text.
protected abstract void | write() This abstract method needs to be implemented by subclasses.
protected void | write(char ch) Writes out a character.
protected void | write(char[] chars, int startIndex, int length) All write methods call into this one.
protected void | write(String content) Writes out a string.
protected void | writeAttributes(AttributeSet attr) Writes out the set of attributes as " =" pairs.
protected void | writeLineSeparator() Writes the line separator.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

NEWLINE

protected static final char NEWLINE
How the text packages models newlines.

See Also:
getLineSeparator(), Constant Field Values
Constructor Detail

AbstractWriter

protected AbstractWriter(Writer w,
                         Document doc)
Creates a new AbstractWriter. Initializes the ElementIterator with the default root of the document.

Parameters:
w - a Writer.
doc - a Document

AbstractWriter

protected AbstractWriter(Writer w,
                         Document doc,
                         int pos,
                         int len)
Creates a new AbstractWriter. Initializes the ElementIterator with the element passed in.

Parameters:
w - a Writer
doc - an Element
pos - The location in the document to fetch the content.
len - The amount to write out.

AbstractWriter

protected AbstractWriter(Writer w,
                         Element root)
Creates a new AbstractWriter. Initializes the ElementIterator with the element passed in.

Parameters:
w - a Writer
root - an Element

AbstractWriter

protected AbstractWriter(Writer w,
                         Element root,
                         int pos,
                         int len)
Creates a new AbstractWriter. Initializes the ElementIterator with the element passed in.

Parameters:
w - a Writer
root - an Element
pos - The location in the document to fetch the content.
len - The amount to write out.
Method Detail

getStartOffset

public int getStartOffset()
Returns the first offset to be output.

Since:
1.3

getEndOffset

public int getEndOffset()
Returns the last offset to be output.

Since:
1.3

getElementIterator

protected ElementIterator getElementIterator()
Fetches the ElementIterator.

Returns:
the ElementIterator.

getWriter

protected Writer getWriter()
Returns the Writer that is used to output the content.

Since:
1.3

getDocument

protected Document getDocument()
Fetches the document.

Returns:
the Document.

inRange

protected boolean inRange(Element next)
This method determines whether the current element is in the range specified. When no range is specified, the range is initialized to be the entire document. inRange() returns true if the range specified intersects with the element's range.

Parameters:
next - an Element.
Returns:
boolean that indicates whether the element is in the range.

write

protected abstract void write()
                       throws IOException,
                              BadLocationException
This abstract method needs to be implemented by subclasses. Its responsibility is to iterate over the elements and use the write() methods to generate output in the desired format.

Throws:
IOException
BadLocationException

getText

protected String getText(Element elem)
                  throws BadLocationException
Returns the text associated with the element. The assumption here is that the element is a leaf element. Throws a BadLocationException when encountered.

Parameters:
elem - an Element
Returns:
the text as a String
Throws:
BadLocationException - if pos represents an invalid location within the document

text

protected void text(Element elem)
             throws BadLocationException,
                    IOException
Writes out text. If a range is specified when the constructor is invoked, then only the appropriate range of text is written out.

Parameters:
elem - an Element.
Throws:
IOException - on any I/O error
BadLocationException - if pos represents an invalid location within the document.

setLineLength

protected void setLineLength(int l)
Enables subclasses to set the number of characters they want written per line. The default is 100.

Parameters:
l - the maximum line length.

getLineLength

protected int getLineLength()
Returns the maximum line length.

Since:
1.3

setCurrentLineLength

protected void setCurrentLineLength(int length)
Sets the current line length.

Since:
1.3.

getCurrentLineLength

protected int getCurrentLineLength()
Returns the current line length.

Since:
1.3.

isLineEmpty

protected boolean isLineEmpty()
Returns true if the current line should be considered empty. This is true when getCurrentLineLength == 0 || indent has been invoked on an empty line.

Since:
1.3

setCanWrapLines

protected void setCanWrapLines(boolean newValue)
Sets whether or not lines can be wrapped. This can be toggled during the writing of lines. For example, outputting HTML might set this to false when outputting a quoted string.

Since:
1.3

getCanWrapLines

protected boolean getCanWrapLines()
Returns whether or not the lines can be wrapped. If this is false no lineSeparator's will be output.

Since:
1.3

setIndentSpace

protected void setIndentSpace(int space)
Enables subclasses to specify how many spaces an indent maps to. When indentation takes place, the indent level is multiplied by this mapping. The default is 2.

Parameters:
space - an int representing the space to indent mapping.

getIndentSpace

protected int getIndentSpace()
Returns the amount of space to indent.

Since:
1.3

setLineSeparator

public void setLineSeparator(String value)
Sets the String used to reprsent newlines. This is initialized in the constructor from either the Document, or the System property line.separator.

Since:
1.3

getLineSeparator

public String getLineSeparator()
Returns the string used to represent newlines.

Since:
1.3

incrIndent

protected void incrIndent()
Increments the indent level. If indenting would cause getIndentSpace() *getIndentLevel() to be > than getLineLength() this will not cause an indent.

decrIndent

protected void decrIndent()
Decrements the indent level.

getIndentLevel

protected int getIndentLevel()
Returns the current indentation level. That is, the number of times incrIndent has been invoked minus the number of times decrIndent has been invoked.

Since:
1.3

indent

protected void indent()
               throws IOException
Does indentation. The number of spaces written out is indent level times the space to map mapping. If the current line is empty, this will not make it so that the current line is still considered empty.

Throws:
IOException - on any I/O error

write

protected void write(char ch)
              throws IOException
Writes out a character. This is implemented to invoke the write method that takes a char[].

Parameters:
ch - a char.
Throws:
IOException - on any I/O error

write

protected void write(String content)
              throws IOException
Writes out a string. This is implemented to invoke the write method that takes a char[].

Parameters:
content - a String.
Throws:
IOException - on any I/O error

writeLineSeparator

protected void writeLineSeparator()
                           throws IOException
Writes the line separator. This invokes output directly as well as setting the lineLength to 0.

Throws:
IOException
Since:
1.3

write

protected void write(char[] chars,
                     int startIndex,
                     int length)
              throws IOException
All write methods call into this one. If getCanWrapLines() returns false, this will call output with each sequence of chars that doesn't contain a NEWLINE, followed by a call to writeLineSeparator. On the other hand, if getCanWrapLines() returns true, this will split the string, as necessary, so getLineLength is honored. The only exception is if the current string contains no whitespace, and won't fit in which case the line length will exceed getLineLength.

Throws:
IOException
Since:
1.3

writeAttributes

protected void writeAttributes(AttributeSet attr)
                        throws IOException
Writes out the set of attributes as " =" pairs. It throws an IOException when encountered.

Parameters:
attr - an AttributeSet.
Throws:
IOException - on any I/O error

output

protected void output(char[] content,
                      int start,
                      int length)
               throws IOException
The last stop in writing out content. All the write methods eventually make it to this method, which invokes write on the Writer.

This method also updates the line length based on length. If this is invoked to output a newline, the current line length will need to be reset as will no longer be valid. If it is up to the caller to do this. Use writeLineSeparator to write out a newline, which will property update the current line length.

Throws:
IOException
Since:
1.3
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


AsyncBoxView (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class AsyncBoxView

java.lang.Object
    extended by javax.swing.text.View
        extended by javax.swing.text.AsyncBoxView
All Implemented Interfaces:
SwingConstants
public class AsyncBoxView
extends View

A box that does layout asynchronously. This is useful to keep the GUI event thread moving by not doing any layout on it. The layout is done on a granularity of operations on the child views. After each child view is accessed for some part of layout (a potentially time consuming operation) the remaining tasks can be abandoned or a new higher priority task (i.e. to service a synchronous request or a visible area) can be taken on.

While the child view is being accessed a read lock is aquired on the associated document so that the model is stable while being accessed.

Since:
1.3

Nested Class Summary
class | AsyncBoxView.ChildLocator A class to manage the effective position of the child views in a localized area while changes are being made around the localized area.
class | AsyncBoxView.ChildState A record representing the layout state of a child view.
Field Summary
protected  AsyncBoxView.ChildLocator locator
Object that manages the offsets of the children.
Fields inherited from class javax.swing.text.View
BadBreakWeight, ExcellentBreakWeight, ForcedBreakWeight, GoodBreakWeight, X_AXIS, Y_AXIS
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
Constructor Summary
AsyncBoxView(Element elem, int axis)
Construct a box view that does asynchronous layout.
Method Summary
protected AsyncBoxView.ChildState | createChildState(View v) New ChildState records are created through this method to allow subclasses the extend the ChildState records to do/hold more
protected void | flushRequirementChanges() Publish the changes in preferences upward to the parent view.
float | getBottomInset() Get the bottom part of the margin around the view.
Shape | getChildAllocation(int index, Shape a) Fetches the allocation for the given child view.
protected AsyncBoxView.ChildState | getChildState(int index) Fetch the object representing the layout state of of the child at the given index.
protected boolean | getEstimatedMajorSpan() Is the major span currently estimated?
protected float | getInsetSpan(int axis) Fetch the span along an axis that is taken up by the insets.
protected LayoutQueue | getLayoutQueue() Fetch the queue to use for layout.
float | getLeftInset() Get the left part of the margin around the view.
int | getMajorAxis() Fetch the major axis (the axis the children are tiled along).
float | getMaximumSpan(int axis) Determines the maximum span for this view along an axis.
float | getMinimumSpan(int axis) Determines the minimum span for this view along an axis.
int | getMinorAxis() Fetch the minor axis (the axis orthoginal to the tiled axis).
int | getNextVisualPositionFrom(int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet) Provides a way to determine the next visually represented model location that one might place a caret.
float | getPreferredSpan(int axis) Determines the preferred span for this view along an axis.
float | getRightInset() Get the right part of the margin around the view.
float | getTopInset() Get the top part of the margin around the view.
View | getView(int n) Gets the nth child view.
int | getViewCount() Returns the number of views in this view.
int | getViewIndex(int pos, Position.Bias b) Returns the child view index representing the given position in the model.
protected int | getViewIndexAtPosition(int pos, Position.Bias b) Fetches the child view index representing the given position in the model.
protected void | loadChildren(ViewFactory f) Loads all of the children to initialize the view.
protected void | majorRequirementChange(AsyncBoxView.ChildState cs, float delta) Requirements changed along the major axis.
protected void | minorRequirementChange(AsyncBoxView.ChildState cs) Requirements changed along the minor axis.
Shape | modelToView(int pos, Shape a, Position.Bias b) Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
void | paint(Graphics g, Shape alloc) Render the view using the given allocation and rendering surface.
void | preferenceChanged(View child, boolean width, boolean height) Child views can call this on the parent to indicate that the preference has changed and should be reconsidered for layout.
void | replace(int offset, int length, View[] views) Calls the superclass to update the child views, and updates the status records for the children.
void | setBottomInset(float i) Set the bottom part of the margin around the view.
protected void | setEstimatedMajorSpan(boolean isEstimated) Set the estimatedMajorSpan property that determines if the major span should be treated as being estimated.
void | setLeftInset(float i) Set the left part of the margin around the view.
void | setParent(View parent) Sets the parent of the view.
void | setRightInset(float i) Set the right part of the margin around the view.
void | setSize(float width, float height) Sets the size of the view.
void | setTopInset(float i) Set the top part of the margin around the view.
protected void | updateLayout(DocumentEvent.ElementChange ec, DocumentEvent e, Shape a) Update the layout in response to receiving notification of change from the model.
int | viewToModel(float x, float y, Shape a, Position.Bias[] biasReturn) Provides a mapping from the view coordinate space to the logical coordinate space of the model.
Methods inherited from class javax.swing.text.View
append, breakView, changedUpdate, createFragment, forwardUpdate, forwardUpdateToView, getAlignment, getAttributes, getBreakWeight, getContainer, getDocument, getElement, getEndOffset, getGraphics, getParent, getResizeWeight, getStartOffset, getToolTipText, getViewFactory, getViewIndex, insert, insertUpdate, isVisible, modelToView, modelToView, remove, removeAll, removeUpdate, updateChildren, viewToModel
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

locator

protected AsyncBoxView.ChildLocator locator
Object that manages the offsets of the children. All locking for management of child locations is on this object.

Constructor Detail

AsyncBoxView

public AsyncBoxView(Element elem,
                    int axis)
Construct a box view that does asynchronous layout.

Parameters:
elem - the element of the model to represent
axis - the axis to tile along. This can be either X_AXIS or Y_AXIS.
Method Detail

getMajorAxis

public int getMajorAxis()
Fetch the major axis (the axis the children are tiled along). This will have a value of either X_AXIS or Y_AXIS.

getMinorAxis

public int getMinorAxis()
Fetch the minor axis (the axis orthoginal to the tiled axis). This will have a value of either X_AXIS or Y_AXIS.

getTopInset

public float getTopInset()
Get the top part of the margin around the view.

setTopInset

public void setTopInset(float i)
Set the top part of the margin around the view.

Parameters:
i - the value of the inset

getBottomInset

public float getBottomInset()
Get the bottom part of the margin around the view.

setBottomInset

public void setBottomInset(float i)
Set the bottom part of the margin around the view.

Parameters:
i - the value of the inset

getLeftInset

public float getLeftInset()
Get the left part of the margin around the view.

setLeftInset

public void setLeftInset(float i)
Set the left part of the margin around the view.

Parameters:
i - the value of the inset

getRightInset

public float getRightInset()
Get the right part of the margin around the view.

setRightInset

public void setRightInset(float i)
Set the right part of the margin around the view.

Parameters:
i - the value of the inset

getInsetSpan

protected float getInsetSpan(int axis)
Fetch the span along an axis that is taken up by the insets.

Parameters:
axis - the axis to determine the total insets along, either X_AXIS or Y_AXIS.
Since:
1.4

setEstimatedMajorSpan

protected void setEstimatedMajorSpan(boolean isEstimated)
Set the estimatedMajorSpan property that determines if the major span should be treated as being estimated. If this property is true, the value of setSize along the major axis will change the requirements along the major axis and incremental changes will be ignored until all of the children have been updated (which will cause the property to automatically be set to false). If the property is false the value of the majorSpan will be considered to be accurate and incremental changes will be added into the total as they are calculated.

Since:
1.4

getEstimatedMajorSpan

protected boolean getEstimatedMajorSpan()
Is the major span currently estimated?

Since:
1.4

getChildState

protected AsyncBoxView.ChildState getChildState(int index)
Fetch the object representing the layout state of of the child at the given index.

Parameters:
index - the child index. This should be a value >= 0 and < getViewCount().

getLayoutQueue

protected LayoutQueue getLayoutQueue()
Fetch the queue to use for layout.

createChildState

protected AsyncBoxView.ChildState createChildState(View v)
New ChildState records are created through this method to allow subclasses the extend the ChildState records to do/hold more

majorRequirementChange

protected void majorRequirementChange(AsyncBoxView.ChildState cs,
                                      float delta)
Requirements changed along the major axis. This is called by the thread doing layout for the given ChildState object when it has completed fetching the child views new preferences. Typically this would be the layout thread, but might be the event thread if it is trying to update something immediately (such as to perform a model/view translation).

This is implemented to mark the major axis as having changed so that a future check to see if the requirements need to be published to the parent view will consider the major axis. If the span along the major axis is not estimated, it is updated by the given delta to reflect the incremental change. The delta is ignored if the major span is estimated.

minorRequirementChange

protected void minorRequirementChange(AsyncBoxView.ChildState cs)
Requirements changed along the minor axis. This is called by the thread doing layout for the given ChildState object when it has completed fetching the child views new preferences. Typically this would be the layout thread, but might be the GUI thread if it is trying to update something immediately (such as to perform a model/view translation).

flushRequirementChanges

protected void flushRequirementChanges()
Publish the changes in preferences upward to the parent view. This is normally called by the layout thread.

replace

public void replace(int offset,
                    int length,
                    View[] views)
Calls the superclass to update the child views, and updates the status records for the children. This is expected to be called while a write lock is held on the model so that interaction with the layout thread will not happen (i.e. the layout thread acquires a read lock before doing anything).

Overrides:
replace in class View
Parameters:
offset - the starting offset into the child views >= 0
length - the number of existing views to replace >= 0
views - the child views to insert

loadChildren

protected void loadChildren(ViewFactory f)
Loads all of the children to initialize the view. This is called by the setParent method. Subclasses can reimplement this to initialize their child views in a different manner. The default implementation creates a child view for each child element.

Normally a write-lock is held on the Document while the children are being changed, which keeps the rendering and layout threads safe. The exception to this is when the view is initialized to represent an existing element (via this method), so it is synchronized to exclude preferenceChanged while we are initializing.

Parameters:
f - the view factory
See Also:
setParent(javax.swing.text.View)

getViewIndexAtPosition

protected int getViewIndexAtPosition(int pos,
                                     Position.Bias b)
Fetches the child view index representing the given position in the model. This is implemented to fetch the view in the case where there is a child view for each child element.

Parameters:
pos - the position >= 0
Returns:
index of the view representing the given position, or -1 if no view represents that position

updateLayout

protected void updateLayout(DocumentEvent.ElementChange ec,
                            DocumentEvent e,
                            Shape a)
Update the layout in response to receiving notification of change from the model. This is implemented to note the change on the ChildLocator so that offsets of the children will be correctly computed.

Overrides:
updateLayout in class View
Parameters:
ec - changes to the element this view is responsible for (may be null if there were no changes).
e - the change information from the associated document
a - the current allocation of the view
See Also:
View.insertUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory),
View.removeUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory),
View.changedUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory)

setParent

public void setParent(View parent)
Sets the parent of the view. This is reimplemented to provide the superclass behavior as well as calling the loadChildren method if this view does not already have children. The children should not be loaded in the constructor because the act of setting the parent may cause them to try to search up the hierarchy (to get the hosting Container for example). If this view has children (the view is being moved from one place in the view hierarchy to another), the loadChildren method will not be called.

Overrides:
setParent in class View
Parameters:
parent - the parent of the view, null if none

preferenceChanged

public void preferenceChanged(View child,
                              boolean width,
                              boolean height)
Child views can call this on the parent to indicate that the preference has changed and should be reconsidered for layout. This is reimplemented to queue new work on the layout thread. This method gets messaged from multiple threads via the children.

Overrides:
preferenceChanged in class View
Parameters:
child - the child view
width - true if the width preference has changed
height - true if the height preference has changed
See Also:
JComponent.revalidate()

setSize

public void setSize(float width,
                    float height)
Sets the size of the view. This should cause layout of the view if the view caches any layout information.

Since the major axis is updated asynchronously and should be the sum of the tiled children the call is ignored for the major axis. Since the minor axis is flexible, work is queued to resize the children if the minor span changes.

Overrides:
setSize in class View
Parameters:
width - the width >= 0
height - the height >= 0

paint

public void paint(Graphics g,
                  Shape alloc)
Render the view using the given allocation and rendering surface.

This is implemented to determine whether or not the desired region to be rendered (i.e. the unclipped area) is up to date or not. If up-to-date the children are rendered. If not up-to-date, a task to build the desired area is placed on the layout queue as a high priority task. This keeps by event thread moving by rendering if ready, and postponing until a later time if not ready (since paint requests can be rescheduled).

Specified by:
paint in class View
Parameters:
g - the rendering surface to use
alloc - the allocated region to render into
See Also:
View.paint(java.awt.Graphics, java.awt.Shape)

getPreferredSpan

public float getPreferredSpan(int axis)
Determines the preferred span for this view along an axis.

Specified by:
getPreferredSpan in class View
Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
Returns:
the span the view would like to be rendered into >= 0. Typically the view is told to render into the span that is returned, although there is no guarantee. The parent may choose to resize or break the view.
Throws:
IllegalArgumentException - for an invalid axis type
See Also:
View.getPreferredSpan(int)

getMinimumSpan

public float getMinimumSpan(int axis)
Determines the minimum span for this view along an axis.

Overrides:
getMinimumSpan in class View
Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
Returns:
the span the view would like to be rendered into >= 0. Typically the view is told to render into the span that is returned, although there is no guarantee. The parent may choose to resize or break the view.
Throws:
IllegalArgumentException - for an invalid axis type
See Also:
View.getPreferredSpan(int)

getMaximumSpan

public float getMaximumSpan(int axis)
Determines the maximum span for this view along an axis.

Overrides:
getMaximumSpan in class View
Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
Returns:
the span the view would like to be rendered into >= 0. Typically the view is told to render into the span that is returned, although there is no guarantee. The parent may choose to resize or break the view.
Throws:
IllegalArgumentException - for an invalid axis type
See Also:
View.getPreferredSpan(int)

getViewCount

public int getViewCount()
Returns the number of views in this view. Since the default is to not be a composite view this returns 0.

Overrides:
getViewCount in class View
Returns:
the number of views >= 0
See Also:
View.getViewCount()

getView

public View getView(int n)
Gets the nth child view. Since there are no children by default, this returns null.

Overrides:
getView in class View
Parameters:
n - the number of the view to get, >= 0 && < getViewCount()
Returns:
the view

getChildAllocation

public Shape getChildAllocation(int index,
                                Shape a)
Fetches the allocation for the given child view. This enables finding out where various views are located, without assuming the views store their location. This returns null since the default is to not have any child views.

Overrides:
getChildAllocation in class View
Parameters:
index - the index of the child, >= 0 && < getViewCount()
a - the allocation to this view.
Returns:
the allocation to the child

getViewIndex

public int getViewIndex(int pos,
                        Position.Bias b)
Returns the child view index representing the given position in the model. By default a view has no children so this is implemented to return -1 to indicate there is no valid child index for any position.

Overrides:
getViewIndex in class View
Parameters:
pos - the position >= 0
Returns:
index of the view representing the given position, or -1 if no view represents that position
Since:
1.3

modelToView

public Shape modelToView(int pos,
                         Shape a,
                         Position.Bias b)
                  throws BadLocationException
Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.

Specified by:
modelToView in class View
Parameters:
pos - the position to convert >= 0
a - the allocated region to render into
b - the bias toward the previous character or the next character represented by the offset, in case the position is a boundary of two views.
Returns:
the bounding box of the given position is returned
Throws:
BadLocationException - if the given position does not represent a valid location in the associated document
IllegalArgumentException - for an invalid bias argument
See Also:
View.viewToModel(float, float, java.awt.Shape, javax.swing.text.Position.Bias[])

viewToModel

public int viewToModel(float x,
                       float y,
                       Shape a,
                       Position.Bias[] biasReturn)
Provides a mapping from the view coordinate space to the logical coordinate space of the model. The biasReturn argument will be filled in to indicate that the point given is closer to the next character in the model or the previous character in the model.

This is expected to be called by the GUI thread, holding a read-lock on the associated model. It is implemented to locate the child view and determine it's allocation with a lock on the ChildLocator object, and to call viewToModel on the child view with a lock on the ChildState object to avoid interaction with the layout thread.

Specified by:
viewToModel in class View
Parameters:
x - the X coordinate >= 0
y - the Y coordinate >= 0
a - the allocated region to render into
Returns:
the location within the model that best represents the given point in the view >= 0. The biasReturn argument will be filled in to indicate that the point given is closer to the next character in the model or the previous character in the model.

getNextVisualPositionFrom

public int getNextVisualPositionFrom(int pos,
                                     Position.Bias b,
                                     Shape a,
                                     int direction,
                                     Position.Bias[] biasRet)
                              throws BadLocationException
Provides a way to determine the next visually represented model location that one might place a caret. Some views may not be visible, they might not be in the same order found in the model, or they just might not allow access to some of the locations in the model.

Overrides:
getNextVisualPositionFrom in class View
Parameters:
pos - the position to convert >= 0
a - the allocated region to render into
direction - the direction from the current position that can be thought of as the arrow keys typically found on a keyboard; this may be one of the following:
    SwingConstants.WEST SwingConstants.EAST SwingConstants.NORTH SwingConstants.SOUTH
biasRet - an array contain the bias that was checked
Returns:
the location within the model that best represents the next location visual position
Throws:
BadLocationException
IllegalArgumentException - if direction is invalid
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


AsyncBoxView.ChildLocator (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class AsyncBoxView.ChildLocator

java.lang.Object
    extended by javax.swing.text.AsyncBoxView.ChildLocator
Enclosing class:
AsyncBoxView
public class AsyncBoxView.ChildLocator
extends Object

A class to manage the effective position of the child views in a localized area while changes are being made around the localized area. The AsyncBoxView may be continuously changing, but the visible area needs to remain fairly stable until the layout thread decides to publish an update to the parent.

Field Summary
protected Rectangle | childAlloc A shape to use for the child allocation to avoid creating a lot of garbage.
protected Rectangle | lastAlloc The last seen allocation (for repainting when changes are flushed upward).
protected AsyncBoxView.ChildState | lastValidOffset The location of the last offset calculation that is valid.
Constructor Summary
AsyncBoxView.ChildLocator()
construct a child locator.
Method Summary
void | childChanged(AsyncBoxView.ChildState cs) Notification that a child changed.
protected Shape | getChildAllocation(int index) Fetch the allocation to use for a child view.
Shape | getChildAllocation(int index, Shape a) Fetch the allocation to use for a child view.
int | getViewIndexAtPoint(float x, float y, Shape a) Fetches the child view index at the given point.
protected int | getViewIndexAtVisualOffset(float targetOffset) Locate the view responsible for an offset into the box along the major axis.
void | paintChildren(Graphics g) Paint the children that intersect the clip area.
protected void | setAllocation(Shape a) Copy the currently allocated shape into the Rectangle used to store the current allocation.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

lastValidOffset

protected AsyncBoxView.ChildState lastValidOffset
The location of the last offset calculation that is valid.

lastAlloc

protected Rectangle lastAlloc
The last seen allocation (for repainting when changes are flushed upward).

childAlloc

protected Rectangle childAlloc
A shape to use for the child allocation to avoid creating a lot of garbage.

Constructor Detail

AsyncBoxView.ChildLocator

public AsyncBoxView.ChildLocator()
construct a child locator.

Method Detail

childChanged

public void childChanged(AsyncBoxView.ChildState cs)
Notification that a child changed. This can effect whether or not new offset calculations are needed. This is called by a ChildState object that has changed it's major span. This can therefore be called by multiple threads.

paintChildren

public void paintChildren(Graphics g)
Paint the children that intersect the clip area.

getChildAllocation

public Shape getChildAllocation(int index,
                                Shape a)
Fetch the allocation to use for a child view. This will update the offsets for all children not yet updated before the given index.

getViewIndexAtPoint

public int getViewIndexAtPoint(float x,
                               float y,
                               Shape a)
Fetches the child view index at the given point. This is called by the various View methods that need to calculate which child to forward a message to. This should be called by a block synchronized on this object, and would typically be followed with one or more calls to getChildAllocation that should also be in the synchronized block.

Parameters:
x - the X coordinate >= 0
y - the Y coordinate >= 0
a - the allocation to the View
Returns:
the nearest child index

getChildAllocation

protected Shape getChildAllocation(int index)
Fetch the allocation to use for a child view. This does not update the offsets in the ChildState records.

setAllocation

protected void setAllocation(Shape a)
Copy the currently allocated shape into the Rectangle used to store the current allocation. This would be a floating point rectangle in a Java2D-specific implmentation.

getViewIndexAtVisualOffset

protected int getViewIndexAtVisualOffset(float targetOffset)
Locate the view responsible for an offset into the box along the major axis. Make sure that offsets are set on the ChildState objects up to the given target span past the desired offset.

Returns:
index of the view representing the given visual location (targetOffset), or -1 if no view represents that location
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


AsyncBoxView.ChildState (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class AsyncBoxView.ChildState

java.lang.Object
    extended by javax.swing.text.AsyncBoxView.ChildState
All Implemented Interfaces:
Runnable
Enclosing class:
AsyncBoxView
public class AsyncBoxView.ChildState
extends Object
implements Runnable

A record representing the layout state of a child view. It is runnable as a task on another thread. All access to the child view that is based upon a read-lock on the model should synchronize on this object (i.e. The layout thread and the GUI thread can both have a read lock on the model at the same time and are not protected from each other). Access to a child view hierarchy is serialized via synchronization on the ChildState instance.

Constructor Summary
AsyncBoxView.ChildState(View v)
Construct a child status.
Method Summary
View | getChildView() Fetch the child view this record represents
float | getMajorOffset() Get the offset along the major axis
float | getMajorSpan() What is the span along the major axis.
float | getMinorOffset() What is the offset along the minor axis
float | getMinorSpan() What is the span along the minor axis.
boolean | isLayoutValid() Has the child view been laid out.
void | preferenceChanged(boolean width, boolean height) Mark preferences changed for this child.
void | run() Update the child state.
void | setMajorOffset(float offs) This method should only be called by the ChildLocator, it is simply a convenient place to hold the cached location.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

AsyncBoxView.ChildState

public AsyncBoxView.ChildState(View v)
Construct a child status. This needs to start out as fairly large so we don't falsely begin with the idea that all of the children are visible.

Method Detail

getChildView

public View getChildView()
Fetch the child view this record represents

run

public void run()
Update the child state. This should be called by the thread that desires to spend time updating the child state (intended to be the layout thread).

This aquires a read lock on the associated document for the duration of the update to ensure the model is not changed while it is operating. The first thing to do would be to see if any work actually needs to be done. The following could have conceivably happened while the state was waiting to be updated:

  1. The child may have been removed from the view hierarchy.
  2. The child may have been updated by a higher priority operation (i.e. the child may have become visible).

Specified by:
run in interface Runnable
See Also:
Thread.run()

getMinorSpan

public float getMinorSpan()
What is the span along the minor axis.

getMinorOffset

public float getMinorOffset()
What is the offset along the minor axis

getMajorSpan

public float getMajorSpan()
What is the span along the major axis.

getMajorOffset

public float getMajorOffset()
Get the offset along the major axis

setMajorOffset

public void setMajorOffset(float offs)
This method should only be called by the ChildLocator, it is simply a convenient place to hold the cached location.

preferenceChanged

public void preferenceChanged(boolean width,
                              boolean height)
Mark preferences changed for this child.

Parameters:
width - true if the width preference has changed
height - true if the height preference has changed
See Also:
JComponent.revalidate()

isLayoutValid

public boolean isLayoutValid()
Has the child view been laid out.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


AttributeSet (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Interface AttributeSet

All Known Subinterfaces:
MutableAttributeSet, Style
All Known Implementing Classes:
AbstractDocument.AbstractElement, SimpleAttributeSet, StyleContext.NamedStyle, StyleContext.SmallAttributeSet
public interface AttributeSet

A collection of unique attributes. This is a read-only, immutable interface. An attribute is basically a key and a value assigned to the key. The collection may represent something like a style run, a logical style, etc. These are generally used to describe features that will contribute to some graphical representation such as a font. The set of possible keys is unbounded and can be anything. Typically View implementations will respond to attribute definitions and render something to represent the attributes.

Attributes can potentially resolve in a hierarchy. If a key doesn't resolve locally, and a resolving parent exists, the key will be resolved through the parent.

See Also:
MutableAttributeSet

Nested Class Summary
static interface | AttributeSet.CharacterAttribute This interface is the type signature that is expected to be present on any attribute key that contributes to character level presentation.
static interface | AttributeSet.ColorAttribute This interface is the type signature that is expected to be present on any attribute key that contributes to presentation of color.
static interface | AttributeSet.FontAttribute This interface is the type signature that is expected to be present on any attribute key that contributes to the determination of what font to use to render some text.
static interface | AttributeSet.ParagraphAttribute This interface is the type signature that is expected to be present on any attribute key that contributes to the paragraph level presentation.
Field Summary
static Object | NameAttribute Attribute name used to name the collection of attributes.
static Object | ResolveAttribute Attribute name used to identify the resolving parent set of attributes, if one is defined.
Method Summary
boolean | containsAttribute(Object name, Object value) Returns true if this set contains this attribute with an equal value.
boolean | containsAttributes(AttributeSet attributes) Returns true if this set contains all the attributes with equal values.
AttributeSet | copyAttributes() Returns an attribute set that is guaranteed not to change over time.
Object | getAttribute(Object key) Fetches the value of the given attribute.
int | getAttributeCount() Returns the number of attributes contained in this set.
Enumeration | getAttributeNames() Returns an enumeration over the names of the attributes in the set.
AttributeSet | getResolveParent() Gets the resolving parent.
boolean | isDefined(Object attrName) Checks whether the named attribute has a value specified in the set without resolving through another attribute set.
boolean | isEqual(AttributeSet attr) Determines if the two attribute sets are equivalent.

Field Detail

NameAttribute

public static final Object NameAttribute
Attribute name used to name the collection of attributes.

ResolveAttribute

public static final Object ResolveAttribute
Attribute name used to identify the resolving parent set of attributes, if one is defined.

Method Detail

getAttributeCount

public int getAttributeCount()
Returns the number of attributes contained in this set.

Returns:
the number of attributes >= 0

isDefined

public boolean isDefined(Object attrName)
Checks whether the named attribute has a value specified in the set without resolving through another attribute set.

Parameters:
attrName - the attribute name
Returns:
true if the attribute has a value specified

isEqual

public boolean isEqual(AttributeSet attr)
Determines if the two attribute sets are equivalent.

Parameters:
attr - an attribute set
Returns:
true if the sets are equivalent

copyAttributes

public AttributeSet copyAttributes()
Returns an attribute set that is guaranteed not to change over time.

Returns:
a copy of the attribute set

getAttribute

public Object getAttribute(Object key)
Fetches the value of the given attribute. If the value is not found locally, the search is continued upward through the resolving parent (if one exists) until the value is either found or there are no more parents. If the value is not found, null is returned.

Parameters:
key - the non-null key of the attribute binding
Returns:
the value

getAttributeNames

public Enumeration getAttributeNames()
Returns an enumeration over the names of the attributes in the set. The values of the Enumeration may be anything and are not constrained to a particular Object type. The set does not include the resolving parent, if one is defined.

Returns:
the names

containsAttribute

public boolean containsAttribute(Object name,
                                 Object value)
Returns true if this set contains this attribute with an equal value.

Parameters:
name - the non-null attribute name
value - the value
Returns:
true if the set contains the attribute with an equal value

containsAttributes

public boolean containsAttributes(AttributeSet attributes)
Returns true if this set contains all the attributes with equal values.

Parameters:
attributes - the set of attributes to check against
Returns:
true if this set contains all the attributes with equal values

getResolveParent

public AttributeSet getResolveParent()
Gets the resolving parent.

Returns:
the parent
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


AttributeSet.CharacterAttribute (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Interface AttributeSet.CharacterAttribute

All Known Implementing Classes:
StyleConstants.CharacterConstants, StyleConstants.ColorConstants, StyleConstants.FontConstants
Enclosing interface:
AttributeSet
public static interface AttributeSet.CharacterAttribute

This interface is the type signature that is expected to be present on any attribute key that contributes to character level presentation. This would be any attribute that applies to a so-called run of style.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


AttributeSet.ColorAttribute (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Interface AttributeSet.ColorAttribute

All Known Implementing Classes:
StyleConstants.ColorConstants
Enclosing interface:
AttributeSet
public static interface AttributeSet.ColorAttribute

This interface is the type signature that is expected to be present on any attribute key that contributes to presentation of color.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


AttributeSet.FontAttribute (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Interface AttributeSet.FontAttribute

All Known Implementing Classes:
StyleConstants.FontConstants
Enclosing interface:
AttributeSet
public static interface AttributeSet.FontAttribute

This interface is the type signature that is expected to be present on any attribute key that contributes to the determination of what font to use to render some text. This is not considered to be a closed set, the definition can change across version of the platform and can be amended by additional user added entries that correspond to logical settings that are specific to some type of content.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


AttributeSet.ParagraphAttribute (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Interface AttributeSet.ParagraphAttribute

All Known Implementing Classes:
StyleConstants.ParagraphConstants
Enclosing interface:
AttributeSet
public static interface AttributeSet.ParagraphAttribute

This interface is the type signature that is expected to be present on any attribute key that contributes to the paragraph level presentation.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


BadLocationException (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class BadLocationException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by javax.swing.text.BadLocationException
All Implemented Interfaces:
Serializable
public class BadLocationException
extends Exception

This exception is to report bad locations within a document model (that is, attempts to reference a location that doesn't exist).

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Constructor Summary
BadLocationException(String s, int offs)
Creates a new BadLocationException object.
Method Summary
 int offsetRequested()
Returns the offset into the document that was not legal.
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

BadLocationException

public BadLocationException(String s,
                            int offs)
Creates a new BadLocationException object.

Parameters:
s - a string indicating what was wrong with the arguments
offs - offset within the document that was requested >= 0
Method Detail

offsetRequested

public int offsetRequested()
Returns the offset into the document that was not legal.

Returns:
the offset >= 0
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


BoxView (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class BoxView

java.lang.Object
    extended by javax.swing.text.View
        extended by javax.swing.text.CompositeView
            extended by javax.swing.text.BoxView
All Implemented Interfaces:
SwingConstants
Direct Known Subclasses:
BlockView, FlowView, TableView, TableView.TableCell, TableView.TableRow, WrappedPlainView, ZoneView
public class BoxView
extends CompositeView

A view that arranges its children into a box shape by tiling its children along an axis. The box is somewhat like that found in TeX where there is alignment of the children, flexibility of the children is considered, etc. This is a building block that might be useful to represent things like a collection of lines, paragraphs, lists, columns, pages, etc. The axis along which the children are tiled is considered the major axis. The orthoginal axis is the minor axis.

Layout for each axis is handled separately by the methods layoutMajorAxis and layoutMinorAxis. Subclasses can change the layout algorithm by reimplementing these methods. These methods will be called as necessary depending upon whether or not there is cached layout information and the cache is considered valid. These methods are typically called if the given size along the axis changes, or if layoutChanged is called to force an updated layout. The layoutChanged method invalidates cached layout information, if there is any. The requirements published to the parent view are calculated by the methods calculateMajorAxisRequirements and calculateMinorAxisRequirements. If the layout algorithm is changed, these methods will likely need to be reimplemented.

Field Summary
Fields inherited from class javax.swing.text.View
BadBreakWeight, ExcellentBreakWeight, ForcedBreakWeight, GoodBreakWeight, X_AXIS, Y_AXIS
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
Constructor Summary
BoxView(Element elem, int axis)
Constructs a BoxView.
Method Summary
protected void | baselineLayout(int targetSpan, int axis, int[] offsets, int[] spans) Computes the location and extent of each child view in this BoxView given the targetSpan, which is the width (or height) of the region we have to work with.
protected SizeRequirements | baselineRequirements(int axis, SizeRequirements r) Calculates the size requirements for this BoxView by examining the size of each child view.
protected SizeRequirements | calculateMajorAxisRequirements(int axis, SizeRequirements r) Calculates the size requirements for the major axis axis.
protected SizeRequirements | calculateMinorAxisRequirements(int axis, SizeRequirements r) Calculates the size requirements for the minor axis axis.
protected void | childAllocation(int index, Rectangle alloc) Allocates a region for a child view.
protected boolean | flipEastAndWestAtEnds(int position, Position.Bias bias) Determines in which direction the next view lays.
protected void | forwardUpdate(DocumentEvent.ElementChange ec, DocumentEvent e, Shape a, ViewFactory f) Forwards the given DocumentEvent to the child views that need to be notified of the change to the model.
float | getAlignment(int axis) Determines the desired alignment for this view along an axis.
int | getAxis() Fetches the tile axis property.
Shape | getChildAllocation(int index, Shape a) Fetches the allocation for the given child view.
int | getHeight() Returns the current height of the box.
float | getMaximumSpan(int axis) Determines the maximum span for this view along an axis.
float | getMinimumSpan(int axis) Determines the minimum span for this view along an axis.
protected int | getOffset(int axis, int childIndex) Fetches the offset of a particular child's current layout.
float | getPreferredSpan(int axis) Determines the preferred span for this view along an axis.
int | getResizeWeight(int axis) Gets the resize weight.
protected int | getSpan(int axis, int childIndex) Fetches the span of a particular childs current layout.
protected View | getViewAtPoint(int x, int y, Rectangle alloc) Fetches the child view at the given coordinates.
int | getWidth() Returns the current width of the box.
protected boolean | isAfter(int x, int y, Rectangle innerAlloc) Determines if a point falls after an allocated region.
protected boolean | isAllocationValid() Are the allocations for the children still valid?
protected boolean | isBefore(int x, int y, Rectangle innerAlloc) Determines if a point falls before an allocated region.
protected boolean | isLayoutValid(int axis) Determines if the layout is valid along the given axis.
protected void | layout(int width, int height) Perform layout on the box
void | layoutChanged(int axis) Invalidates the layout along an axis.
protected void | layoutMajorAxis(int targetSpan, int axis, int[] offsets, int[] spans) Performs layout for the major axis of the box (i.e.
protected void | layoutMinorAxis(int targetSpan, int axis, int[] offsets, int[] spans) Performs layout for the minor axis of the box (i.e.
Shape | modelToView(int pos, Shape a, Position.Bias b) Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
void | paint(Graphics g, Shape allocation) Renders the BoxView using the given rendering surface and area on that surface.
protected void | paintChild(Graphics g, Rectangle alloc, int index) Paints a child.
void | preferenceChanged(View child, boolean width, boolean height) This is called by a child to indicate its preferred span has changed.
void | replace(int index, int length, View[] elems) Invalidates the layout and resizes the cache of requests/allocations.
void | setAxis(int axis) Sets the tile axis property.
void | setSize(float width, float height) Sets the size of the view.
int | viewToModel(float x, float y, Shape a, Position.Bias[] bias) Provides a mapping from the view coordinate space to the logical coordinate space of the model.
Methods inherited from class javax.swing.text.CompositeView
getBottomInset, getInsideAllocation, getLeftInset, getNextEastWestVisualPositionFrom, getNextNorthSouthVisualPositionFrom, getNextVisualPositionFrom, getRightInset, getTopInset, getView, getViewAtPosition, getViewCount, getViewIndex, getViewIndexAtPosition, loadChildren, modelToView, setInsets, setParagraphInsets, setParent
Methods inherited from class javax.swing.text.View
append, breakView, changedUpdate, createFragment, forwardUpdateToView, getAttributes, getBreakWeight, getContainer, getDocument, getElement, getEndOffset, getGraphics, getParent, getStartOffset, getToolTipText, getViewFactory, getViewIndex, insert, insertUpdate, isVisible, modelToView, remove, removeAll, removeUpdate, updateChildren, updateLayout, viewToModel
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

BoxView

public BoxView(Element elem,
               int axis)
Constructs a BoxView.

Parameters:
elem - the element this view is responsible for
axis - either View.X_AXIS or View.Y_AXIS
Method Detail

getAxis

public int getAxis()
Fetches the tile axis property. This is the axis along which the child views are tiled.

Returns:
the major axis of the box, either View.X_AXIS or View.Y_AXIS
Since:
1.3

setAxis

public void setAxis(int axis)
Sets the tile axis property. This is the axis along which the child views are tiled.

Parameters:
axis - either View.X_AXIS or View.Y_AXIS
Since:
1.3

layoutChanged

public void layoutChanged(int axis)
Invalidates the layout along an axis. This happens automatically if the preferences have changed for any of the child views. In some cases the layout may need to be recalculated when the preferences have not changed. The layout can be marked as invalid by calling this method. The layout will be updated the next time the setSize method is called on this view (typically in paint).

Parameters:
axis - either View.X_AXIS or View.Y_AXIS
Since:
1.3

isLayoutValid

protected boolean isLayoutValid(int axis)
Determines if the layout is valid along the given axis.

Parameters:
axis - either View.X_AXIS or View.Y_AXIS
Since:
1.4

paintChild

protected void paintChild(Graphics g,
                          Rectangle alloc,
                          int index)
Paints a child. By default that is all it does, but a subclass can use this to paint things relative to the child.

Parameters:
g - the graphics context
alloc - the allocated region to paint into
index - the child index, >= 0 && < getViewCount()

replace

public void replace(int index,
                    int length,
                    View[] elems)
Invalidates the layout and resizes the cache of requests/allocations. The child allocations can still be accessed for the old layout, but the new children will have an offset and span of 0.

Overrides:
replace in class CompositeView
Parameters:
index - the starting index into the child views to insert the new views; this should be a value >= 0 and <= getViewCount
length - the number of existing child views to remove; This should be a value >= 0 and <= (getViewCount() - offset)
elems - the child views to add; this value can be nullto indicate no children are being added (useful to remove)

forwardUpdate

protected void forwardUpdate(DocumentEvent.ElementChange ec,
                             DocumentEvent e,
                             Shape a,
                             ViewFactory f)
Forwards the given DocumentEvent to the child views that need to be notified of the change to the model. If a child changed its requirements and the allocation was valid prior to forwarding the portion of the box from the starting child to the end of the box will be repainted.

Overrides:
forwardUpdate in class View
Parameters:
ec - changes to the element this view is responsible for (may be null if there were no changes)
e - the change information from the associated document
a - the current allocation of the view
f - the factory to use to rebuild if the view has children
See Also:
View.insertUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory),
View.removeUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory),
View.changedUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory)

preferenceChanged

public void preferenceChanged(View child,
                              boolean width,
                              boolean height)
This is called by a child to indicate its preferred span has changed. This is implemented to throw away cached layout information so that new calculations will be done the next time the children need an allocation.

Overrides:
preferenceChanged in class View
Parameters:
child - the child view
width - true if the width preference should change
height - true if the height preference should change
See Also:
JComponent.revalidate()

getResizeWeight

public int getResizeWeight(int axis)
Gets the resize weight. A value of 0 or less is not resizable.

Overrides:
getResizeWeight in class View
Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
Returns:
the weight
Throws:
IllegalArgumentException - for an invalid axis

setSize

public void setSize(float width,
                    float height)
Sets the size of the view. This should cause layout of the view if the view caches any layout information. This is implemented to call the layout method with the sizes inside of the insets.

Overrides:
setSize in class View
Parameters:
width - the width >= 0
height - the height >= 0

paint

public void paint(Graphics g,
                  Shape allocation)
Renders the BoxView using the given rendering surface and area on that surface. Only the children that intersect the clip bounds of the given Graphics will be rendered.

Specified by:
paint in class View
Parameters:
g - the rendering surface to use
allocation - the allocated region to render into
See Also:
View.paint(java.awt.Graphics, java.awt.Shape)

getChildAllocation

public Shape getChildAllocation(int index,
                                Shape a)
Fetches the allocation for the given child view. This enables finding out where various views are located. This is implemented to return null if the layout is invalid, otherwise the superclass behavior is executed.

Overrides:
getChildAllocation in class CompositeView
Parameters:
index - the index of the child, >= 0 && < getViewCount()
a - the allocation to this view
Returns:
the allocation to the child; or null if a is null; or null if the layout is invalid

modelToView

public Shape modelToView(int pos,
                         Shape a,
                         Position.Bias b)
                  throws BadLocationException
Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it. This makes sure the allocation is valid before calling the superclass.

Overrides:
modelToView in class CompositeView
Parameters:
pos - the position to convert >= 0
a - the allocated region to render into
b - a bias value of either Position.Bias.Forward or Position.Bias.Backward
Returns:
the bounding box of the given position
Throws:
BadLocationException - if the given position does not represent a valid location in the associated document
See Also:
View.modelToView(int, java.awt.Shape, javax.swing.text.Position.Bias)

viewToModel

public int viewToModel(float x,
                       float y,
                       Shape a,
                       Position.Bias[] bias)
Provides a mapping from the view coordinate space to the logical coordinate space of the model.

Overrides:
viewToModel in class CompositeView
Parameters:
x - x coordinate of the view location to convert >= 0
y - y coordinate of the view location to convert >= 0
a - the allocated region to render into
bias - either Position.Bias.Forward or Position.Bias.Backward
Returns:
the location within the model that best represents the given point in the view >= 0
See Also:
View.viewToModel(float, float, java.awt.Shape, javax.swing.text.Position.Bias[])

getAlignment

public float getAlignment(int axis)
Determines the desired alignment for this view along an axis. This is implemented to give the total alignment needed to position the children with the alignment points lined up along the axis orthoginal to the axis that is being tiled. The axis being tiled will request to be centered (i.e. 0.5f).

Overrides:
getAlignment in class View
Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
Returns:
the desired alignment >= 0.0f && <= 1.0f; this should be a value between 0.0 and 1.0 where 0 indicates alignment at the origin and 1.0 indicates alignment to the full span away from the origin; an alignment of 0.5 would be the center of the view
Throws:
IllegalArgumentException - for an invalid axis

getPreferredSpan

public float getPreferredSpan(int axis)
Determines the preferred span for this view along an axis.

Specified by:
getPreferredSpan in class View
Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
Returns:
the span the view would like to be rendered into >= 0; typically the view is told to render into the span that is returned, although there is no guarantee; the parent may choose to resize or break the view
Throws:
IllegalArgumentException - for an invalid axis type
See Also:
View.getPreferredSpan(int)

getMinimumSpan

public float getMinimumSpan(int axis)
Determines the minimum span for this view along an axis.

Overrides:
getMinimumSpan in class View
Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
Returns:
the span the view would like to be rendered into >= 0; typically the view is told to render into the span that is returned, although there is no guarantee; the parent may choose to resize or break the view
Throws:
IllegalArgumentException - for an invalid axis type
See Also:
View.getPreferredSpan(int)

getMaximumSpan

public float getMaximumSpan(int axis)
Determines the maximum span for this view along an axis.

Overrides:
getMaximumSpan in class View
Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
Returns:
the span the view would like to be rendered into >= 0; typically the view is told to render into the span that is returned, although there is no guarantee; the parent may choose to resize or break the view
Throws:
IllegalArgumentException - for an invalid axis type
See Also:
View.getPreferredSpan(int)

isAllocationValid

protected boolean isAllocationValid()
Are the allocations for the children still valid?

Returns:
true if allocations still valid

isBefore

protected boolean isBefore(int x,
                           int y,
                           Rectangle innerAlloc)
Determines if a point falls before an allocated region.

Specified by:
isBefore in class CompositeView
Parameters:
x - the X coordinate >= 0
y - the Y coordinate >= 0
innerAlloc - the allocated region; this is the area inside of the insets
Returns:
true if the point lies before the region else false

isAfter

protected boolean isAfter(int x,
                          int y,
                          Rectangle innerAlloc)
Determines if a point falls after an allocated region.

Specified by:
isAfter in class CompositeView
Parameters:
x - the X coordinate >= 0
y - the Y coordinate >= 0
innerAlloc - the allocated region; this is the area inside of the insets
Returns:
true if the point lies after the region else false

getViewAtPoint

protected View getViewAtPoint(int x,
                              int y,
                              Rectangle alloc)
Fetches the child view at the given coordinates.

Specified by:
getViewAtPoint in class CompositeView
Parameters:
x - the X coordinate >= 0
y - the Y coordinate >= 0
alloc - the parents inner allocation on entry, which should be changed to the childs allocation on exit
Returns:
the view

childAllocation

protected void childAllocation(int index,
                               Rectangle alloc)
Allocates a region for a child view.

Specified by:
childAllocation in class CompositeView
Parameters:
index - the index of the child view to allocate, >= 0 && < getViewCount()
alloc - the allocated region

layout

protected void layout(int width,
                      int height)
Perform layout on the box

Parameters:
width - the width (inside of the insets) >= 0
height - the height (inside of the insets) >= 0

getWidth

public int getWidth()
Returns the current width of the box. This is the width that it was last allocated.

Returns:
the current width of the box

getHeight

public int getHeight()
Returns the current height of the box. This is the height that it was last allocated.

Returns:
the current height of the box

layoutMajorAxis

protected void layoutMajorAxis(int targetSpan,
                               int axis,
                               int[] offsets,
                               int[] spans)
Performs layout for the major axis of the box (i.e. the axis that it represents). The results of the layout should be placed in the given arrays which represent the allocations to the children along the major axis.

Parameters:
targetSpan - the total span given to the view, which would be used to layout the children
axis - the axis being layed out
offsets - the offsets from the origin of the view for each of the child views; this is a return value and is filled in by the implementation of this method
spans - the span of each child view; this is a return value and is filled in by the implementation of this method
Returns:
the offset and span for each child view in the offsets and spans parameters

layoutMinorAxis

protected void layoutMinorAxis(int targetSpan,
                               int axis,
                               int[] offsets,
                               int[] spans)
Performs layout for the minor axis of the box (i.e. the axis orthoginal to the axis that it represents). The results of the layout should be placed in the given arrays which represent the allocations to the children along the minor axis.

Parameters:
targetSpan - the total span given to the view, which would be used to layout the children
axis - the axis being layed out
offsets - the offsets from the origin of the view for each of the child views; this is a return value and is filled in by the implementation of this method
spans - the span of each child view; this is a return value and is filled in by the implementation of this method
Returns:
the offset and span for each child view in the offsets and spans parameters

calculateMajorAxisRequirements

protected SizeRequirements calculateMajorAxisRequirements(int axis,
                                                          SizeRequirements r)
Calculates the size requirements for the major axis axis.

Parameters:
axis - the axis being studied
r - the SizeRequirements object; if null one will be created
Returns:
the newly initialized SizeRequirements object
See Also:
SizeRequirements

calculateMinorAxisRequirements

protected SizeRequirements calculateMinorAxisRequirements(int axis,
                                                          SizeRequirements r)
Calculates the size requirements for the minor axis axis.

Parameters:
axis - the axis being studied
r - the SizeRequirements object; if null one will be created
Returns:
the newly initialized SizeRequirements object
See Also:
SizeRequirements

baselineLayout

protected void baselineLayout(int targetSpan,
                              int axis,
                              int[] offsets,
                              int[] spans)
Computes the location and extent of each child view in this BoxView given the targetSpan, which is the width (or height) of the region we have to work with.

Parameters:
targetSpan - the total span given to the view, which would be used to layout the children
axis - the axis being studied, either View.X_AXIS or View.Y_AXIS
offsets - an empty array filled by this method with values specifying the location of each child view
spans - an empty array filled by this method with values specifying the extent of each child view

baselineRequirements

protected SizeRequirements baselineRequirements(int axis,
                                                SizeRequirements r)
Calculates the size requirements for this BoxView by examining the size of each child view.

Parameters:
axis - the axis being studied
r - the SizeRequirements object; if null one will be created
Returns:
the newly initialized SizeRequirements object

getOffset

protected int getOffset(int axis,
                        int childIndex)
Fetches the offset of a particular child's current layout.

Parameters:
axis - the axis being studied
childIndex - the index of the requested child
Returns:
the offset (location) for the specified child

getSpan

protected int getSpan(int axis,
                      int childIndex)
Fetches the span of a particular childs current layout.

Parameters:
axis - the axis being studied
childIndex - the index of the requested child
Returns:
the span (width or height) of the specified child

flipEastAndWestAtEnds

protected boolean flipEastAndWestAtEnds(int position,
                                        Position.Bias bias)
Determines in which direction the next view lays. Consider the View at index n. Typically the Views are layed out from left to right, so that the View to the EAST will be at index n + 1, and the View to the WEST will be at index n - 1. In certain situations, such as with bidirectional text, it is possible that the View to EAST is not at index n + 1, but rather at index n - 1, or that the View to the WEST is not at index n - 1, but index n + 1. In this case this method would return true, indicating the Views are layed out in descending order. Otherwise the method would return false indicating the Views are layed out in ascending order.

If the receiver is laying its Views along the Y_AXIS, this will will return the value from invoking the same method on the View responsible for rendering position and bias. Otherwise this will return false.

Overrides:
flipEastAndWestAtEnds in class CompositeView
Parameters:
position - position into the model
bias - either Position.Bias.Forward or Position.Bias.Backward
Returns:
true if the Views surrounding the View responding for rendering position and bias are layed out in descending order; otherwise false
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Caret (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Interface Caret

All Known Implementing Classes:
DefaultCaret
public interface Caret

A place within a document view that represents where things can be inserted into the document model. A caret has a position in the document referred to as a dot. The dot is where the caret is currently located in the model. There is a second position maintained by the caret that represents the other end of a selection called mark. If there is no selection the dot and mark will be equal. If a selection exists, the two values will be different.

The dot can be placed by either calling setDot or moveDot. Setting the dot has the effect of removing any selection that may have previously existed. The dot and mark will be equal. Moving the dot has the effect of creating a selection as the mark is left at whatever position it previously had.

Method Summary
void | addChangeListener(ChangeListener l) Adds a listener to track whenever the caret position has been changed.
void | deinstall(JTextComponent c) Called when the UI is being removed from the interface of a JTextComponent.
int | getBlinkRate() Gets the blink rate of the caret.
int | getDot() Fetches the current position of the caret.
Point | getMagicCaretPosition() Gets the current caret visual location.
int | getMark() Fetches the current position of the mark.
void | install(JTextComponent c) Called when the UI is being installed into the interface of a JTextComponent.
boolean | isSelectionVisible() Determines if the selection is currently visible.
boolean | isVisible() Determines if the caret is currently visible.
void | moveDot(int dot) Moves the caret position (dot) to some other position, leaving behind the mark.
void | paint(Graphics g) Renders the caret.
void | removeChangeListener(ChangeListener l) Removes a listener that was tracking caret position changes.
void | setBlinkRate(int rate) Sets the blink rate of the caret.
void | setDot(int dot) Sets the caret position to some position.
void | setMagicCaretPosition(Point p) Set the current caret visual location.
void | setSelectionVisible(boolean v) Sets the visibility of the selection
void | setVisible(boolean v) Sets the visibility of the caret.

Method Detail

install

public void install(JTextComponent c)
Called when the UI is being installed into the interface of a JTextComponent. This can be used to gain access to the model that is being navigated by the implementation of this interface.

Parameters:
c - the JTextComponent

deinstall

public void deinstall(JTextComponent c)
Called when the UI is being removed from the interface of a JTextComponent. This is used to unregister any listeners that were attached.

Parameters:
c - the JTextComponent

paint

public void paint(Graphics g)
Renders the caret.

Parameters:
g - the graphics context

addChangeListener

public void addChangeListener(ChangeListener l)
Adds a listener to track whenever the caret position has been changed.

Parameters:
l - the change listener

removeChangeListener

public void removeChangeListener(ChangeListener l)
Removes a listener that was tracking caret position changes.

Parameters:
l - the change listener

isVisible

public boolean isVisible()
Determines if the caret is currently visible.

Returns:
true if the caret is visible else false

setVisible

public void setVisible(boolean v)
Sets the visibility of the caret.

Parameters:
v - true if the caret should be shown, and false if the caret should be hidden

isSelectionVisible

public boolean isSelectionVisible()
Determines if the selection is currently visible.

Returns:
true if the caret is visible else false

setSelectionVisible

public void setSelectionVisible(boolean v)
Sets the visibility of the selection

Parameters:
v - true if the caret should be shown, and false if the caret should be hidden

setMagicCaretPosition

public void setMagicCaretPosition(Point p)
Set the current caret visual location. This can be used when moving between lines that have uneven end positions (such as when caret up or down actions occur). If text flows left-to-right or right-to-left the x-coordinate will indicate the desired navigation location for vertical movement. If the text flow is top-to-bottom, the y-coordinate will indicate the desired navigation location for horizontal movement.

Parameters:
p - the Point to use for the saved position. This can be null to indicate there is no visual location.

getMagicCaretPosition

public Point getMagicCaretPosition()
Gets the current caret visual location.

Returns:
the visual position.
See Also:
setMagicCaretPosition(java.awt.Point)

setBlinkRate

public void setBlinkRate(int rate)
Sets the blink rate of the caret. This determines if and how fast the caret blinks, commonly used as one way to attract attention to the caret.

Parameters:
rate - the delay in milliseconds >= 0. If this is zero the caret will not blink.

getBlinkRate

public int getBlinkRate()
Gets the blink rate of the caret. This determines if and how fast the caret blinks, commonly used as one way to attract attention to the caret.

Returns:
the delay in milliseconds >= 0. If this is zero the caret will not blink.

getDot

public int getDot()
Fetches the current position of the caret.

Returns:
the position >= 0

getMark

public int getMark()
Fetches the current position of the mark. If there is a selection, the mark will not be the same as the dot.

Returns:
the position >= 0

setDot

public void setDot(int dot)
Sets the caret position to some position. This causes the mark to become the same as the dot, effectively setting the selection range to zero.

Parameters:
dot - the new position to set the caret to >= 0

moveDot

public void moveDot(int dot)
Moves the caret position (dot) to some other position, leaving behind the mark. This is useful for making selections.

Parameters:
dot - the new position to move the caret to >= 0
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ChangedCharSetException (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class ChangedCharSetException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.io.IOException
                extended by javax.swing.text.ChangedCharSetException
All Implemented Interfaces:
Serializable
public class ChangedCharSetException
extends IOException

ChangedCharSetException as the name indicates is an exception thrown when the charset is changed.

Constructor Summary
ChangedCharSetException(String charSetSpec, boolean charSetKey)
Method Summary
String | getCharSetSpec()
boolean | keyEqualsCharSet()
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

ChangedCharSetException

public ChangedCharSetException(String charSetSpec,
                               boolean charSetKey)
Method Detail

getCharSetSpec

public String getCharSetSpec()

keyEqualsCharSet

public boolean keyEqualsCharSet()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


ComponentView (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class ComponentView

java.lang.Object
    extended by javax.swing.text.View
        extended by javax.swing.text.ComponentView
All Implemented Interfaces:
SwingConstants
Direct Known Subclasses:
FormView, ObjectView
public class ComponentView
extends View

Component decorator that implements the view interface. The entire element is used to represent the component. This acts as a gateway from the display-only View implementations to interactive lightweight components (ie it allows components to be embedded into the View hierarchy).

The component is placed relative to the text baseline according to the value returned by Component.getAlignmentY. For Swing components this value can be conveniently set using the method JComponent.setAlignmentY. For example, setting a value of 0.75 will cause 75 percent of the component to be above the baseline, and 25 percent of the component to be below the baseline.

This class is implemented to do the extra work necessary to work properly in the presence of multiple threads (i.e. from asynchronous notification of model changes for example) by ensuring that all component access is done on the event thread.

The component used is determined by the return value of the createComponent method. The default implementation of this method is to return the component held as an attribute of the element (by calling StyleConstants.getComponent). A limitation of this behavior is that the component cannot be used by more than one text component (i.e. with a shared model). Subclasses can remove this constraint by implementing the createComponent to actually create a component based upon some kind of specification contained in the attributes. The ObjectView class in the html package is an example of a ComponentView implementation that supports multiple component views of a shared model.

Field Summary
Fields inherited from class javax.swing.text.View
BadBreakWeight, ExcellentBreakWeight, ForcedBreakWeight, GoodBreakWeight, X_AXIS, Y_AXIS
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
Constructor Summary
ComponentView(Element elem)
Creates a new ComponentView object.
Method Summary
protected Component | createComponent() Create the component that is associated with this view.
float | getAlignment(int axis) Determines the desired alignment for this view along an axis.
Component | getComponent() Fetch the component associated with the view.
float | getMaximumSpan(int axis) Determines the maximum span for this view along an axis.
float | getMinimumSpan(int axis) Determines the minimum span for this view along an axis.
float | getPreferredSpan(int axis) Determines the preferred span for this view along an axis.
Shape | modelToView(int pos, Shape a, Position.Bias b) Provides a mapping from the coordinate space of the model to that of the view.
void | paint(Graphics g, Shape a) The real paint behavior occurs naturally from the association that the component has with its parent container (the same container hosting this view).
void | setParent(View p) Sets the parent for a child view.
int | viewToModel(float x, float y, Shape a, Position.Bias[] bias) Provides a mapping from the view coordinate space to the logical coordinate space of the model.
Methods inherited from class javax.swing.text.View
append, breakView, changedUpdate, createFragment, forwardUpdate, forwardUpdateToView, getAttributes, getBreakWeight, getChildAllocation, getContainer, getDocument, getElement, getEndOffset, getGraphics, getNextVisualPositionFrom, getParent, getResizeWeight, getStartOffset, getToolTipText, getView, getViewCount, getViewFactory, getViewIndex, getViewIndex, insert, insertUpdate, isVisible, modelToView, modelToView, preferenceChanged, remove, removeAll, removeUpdate, replace, setSize, updateChildren, updateLayout, viewToModel
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ComponentView

public ComponentView(Element elem)
Creates a new ComponentView object.

Parameters:
elem - the element to decorate
Method Detail

createComponent

protected Component createComponent()
Create the component that is associated with this view. This will be called when it has been determined that a new component is needed. This would result from a call to setParent or as a result of being notified that attributes have changed.

getComponent

public final Component getComponent()
Fetch the component associated with the view.

paint

public void paint(Graphics g,
                  Shape a)
The real paint behavior occurs naturally from the association that the component has with its parent container (the same container hosting this view). This is implemented to do nothing.

Specified by:
paint in class View
Parameters:
g - the graphics context
a - the shape
See Also:
View.paint(java.awt.Graphics, java.awt.Shape)

getPreferredSpan

public float getPreferredSpan(int axis)
Determines the preferred span for this view along an axis. This is implemented to return the value returned by Component.getPreferredSize along the axis of interest.

Specified by:
getPreferredSpan in class View
Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
Returns:
the span the view would like to be rendered into >= 0. Typically the view is told to render into the span that is returned, although there is no guarantee. The parent may choose to resize or break the view.
Throws:
IllegalArgumentException - for an invalid axis
See Also:
View.getPreferredSpan(int)

getMinimumSpan

public float getMinimumSpan(int axis)
Determines the minimum span for this view along an axis. This is implemented to return the value returned by Component.getMinimumSize along the axis of interest.

Overrides:
getMinimumSpan in class View
Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
Returns:
the span the view would like to be rendered into >= 0. Typically the view is told to render into the span that is returned, although there is no guarantee. The parent may choose to resize or break the view.
Throws:
IllegalArgumentException - for an invalid axis
See Also:
View.getPreferredSpan(int)

getMaximumSpan

public float getMaximumSpan(int axis)
Determines the maximum span for this view along an axis. This is implemented to return the value returned by Component.getMaximumSize along the axis of interest.

Overrides:
getMaximumSpan in class View
Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
Returns:
the span the view would like to be rendered into >= 0. Typically the view is told to render into the span that is returned, although there is no guarantee. The parent may choose to resize or break the view.
Throws:
IllegalArgumentException - for an invalid axis
See Also:
View.getPreferredSpan(int)

getAlignment

public float getAlignment(int axis)
Determines the desired alignment for this view along an axis. This is implemented to give the alignment of the embedded component.

Overrides:
getAlignment in class View
Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
Returns:
the desired alignment. This should be a value between 0.0 and 1.0 where 0 indicates alignment at the origin and 1.0 indicates alignment to the full span away from the origin. An alignment of 0.5 would be the center of the view.

setParent

public void setParent(View p)
Sets the parent for a child view. The parent calls this on the child to tell it who its parent is, giving the view access to things like the hosting Container. The superclass behavior is executed, followed by a call to createComponent if the parent view parameter is non-null and a component has not yet been created. The embedded components parent is then set to the value returned by getContainer. If the parent view parameter is null, this view is being cleaned up, thus the component is removed from its parent.

The changing of the component hierarchy will touch the component lock, which is the one thing that is not safe from the View hierarchy. Therefore, this functionality is executed immediately if on the event thread, or is queued on the event queue if called from another thread (notification of change from an asynchronous update).

Overrides:
setParent in class View
Parameters:
p - the parent

modelToView

public Shape modelToView(int pos,
                         Shape a,
                         Position.Bias b)
                  throws BadLocationException
Provides a mapping from the coordinate space of the model to that of the view.

Specified by:
modelToView in class View
Parameters:
pos - the position to convert >= 0
a - the allocated region to render into
b - the bias toward the previous character or the next character represented by the offset, in case the position is a boundary of two views; b will have one of these values:
  • Position.Bias.Forward
  • Position.Bias.Backward
Returns:
the bounding box of the given position is returned
Throws:
BadLocationException - if the given position does not represent a valid location in the associated document
See Also:
View.modelToView(int, java.awt.Shape, javax.swing.text.Position.Bias)

viewToModel

public int viewToModel(float x,
                       float y,
                       Shape a,
                       Position.Bias[] bias)
Provides a mapping from the view coordinate space to the logical coordinate space of the model.

Specified by:
viewToModel in class View
Parameters:
x - the X coordinate >= 0
y - the Y coordinate >= 0
a - the allocated region to render into
Returns:
the location within the model that best represents the given point in the view
See Also:
View.viewToModel(float, float, java.awt.Shape, javax.swing.text.Position.Bias[])
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


CompositeView (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class CompositeView

java.lang.Object
    extended by javax.swing.text.View
        extended by javax.swing.text.CompositeView
All Implemented Interfaces:
SwingConstants
Direct Known Subclasses:
BoxView
public abstract class CompositeView
extends View

CompositeView is an abstract View implementation which manages one or more child views. (Note that CompositeView is intended for managing relatively small numbers of child views.) CompositeView is intended to be used as a starting point for View implementations, such as BoxView, that will contain child Views. Subclasses that wish to manage the collection of child Views should use the replace(int, int, javax.swing.text.View[]) method. As View invokes replace during DocumentListener notification, you normally won't need to directly invoke replace.

While CompositeView does not impose a layout policy on its child Views, it does allow for inseting the child Views it will contain. The insets can be set by either setInsets(short, short, short, short) or setParagraphInsets(javax.swing.text.AttributeSet).

In addition to the abstract methods of View, subclasses of CompositeView will need to override:

  • isBefore(int, int, java.awt.Rectangle) - Used to test if a given View location is before the visual space of the CompositeView.
  • isAfter(int, int, java.awt.Rectangle) - Used to test if a given View location is after the visual space of the CompositeView.
  • getViewAtPoint(int, int, java.awt.Rectangle) - Returns the view at a given visual location.
  • childAllocation(int, java.awt.Rectangle) - Returns the bounds of a particular child View. getChildAllocation will invoke childAllocation after offseting the bounds by the Insets of the CompositeView.

Field Summary
Fields inherited from class javax.swing.text.View
BadBreakWeight, ExcellentBreakWeight, ForcedBreakWeight, GoodBreakWeight, X_AXIS, Y_AXIS
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
Constructor Summary
CompositeView(Element elem)
Constructs a CompositeView for the given element.
Method Summary
protected abstract void | childAllocation(int index, Rectangle a) Returns the allocation for a given child.
protected boolean | flipEastAndWestAtEnds(int position, Position.Bias bias) Determines in which direction the next view lays.
protected short | getBottomInset() Gets the bottom inset.
Shape | getChildAllocation(int index, Shape a) Fetches the allocation for the given child view to render into.
protected Rectangle | getInsideAllocation(Shape a) Translates the immutable allocation given to the view to a mutable allocation that represents the interior allocation (i.e.
protected short | getLeftInset() Gets the left inset.
protected int | getNextEastWestVisualPositionFrom(int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet) Returns the next visual position for the cursor, in either the east or west direction.
protected int | getNextNorthSouthVisualPositionFrom(int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet) Returns the next visual position for the cursor, in either the north or south direction.
int | getNextVisualPositionFrom(int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet) Provides a way to determine the next visually represented model location that one might place a caret.
protected short | getRightInset() Gets the right inset.
protected short | getTopInset() Gets the top inset.
View | getView(int n) Returns the n-th view in this container.
protected abstract View | getViewAtPoint(int x, int y, Rectangle alloc) Fetches the child view at the given coordinates.
protected View | getViewAtPosition(int pos, Rectangle a) Fetches the child view that represents the given position in the model.
int | getViewCount() Returns the number of child views of this view.
int | getViewIndex(int pos, Position.Bias b) Returns the child view index representing the given position in the model.
protected int | getViewIndexAtPosition(int pos) Fetches the child view index representing the given position in the model.
protected abstract boolean | isAfter(int x, int y, Rectangle alloc) Tests whether a point lies after the rectangle range.
protected abstract boolean | isBefore(int x, int y, Rectangle alloc) Tests whether a point lies before the rectangle range.
protected void | loadChildren(ViewFactory f) Loads all of the children to initialize the view.
Shape | modelToView(int p0, Position.Bias b0, int p1, Position.Bias b1, Shape a) Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
Shape | modelToView(int pos, Shape a, Position.Bias b) Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
void | replace(int offset, int length, View[] views) Replaces child views.
protected void | setInsets(short top, short left, short bottom, short right) Sets the insets for the view.
protected void | setParagraphInsets(AttributeSet attr) Sets the insets from the paragraph attributes specified in the given attributes.
void | setParent(View parent) Sets the parent of the view.
int | viewToModel(float x, float y, Shape a, Position.Bias[] bias) Provides a mapping from the view coordinate space to the logical coordinate space of the model.
Methods inherited from class javax.swing.text.View
append, breakView, changedUpdate, createFragment, forwardUpdate, forwardUpdateToView, getAlignment, getAttributes, getBreakWeight, getContainer, getDocument, getElement, getEndOffset, getGraphics, getMaximumSpan, getMinimumSpan, getParent, getPreferredSpan, getResizeWeight, getStartOffset, getToolTipText, getViewFactory, getViewIndex, insert, insertUpdate, isVisible, modelToView, paint, preferenceChanged, remove, removeAll, removeUpdate, setSize, updateChildren, updateLayout, viewToModel
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

CompositeView

public CompositeView(Element elem)
Constructs a CompositeView for the given element.

Parameters:
elem - the element this view is responsible for
Method Detail

loadChildren

protected void loadChildren(ViewFactory f)
Loads all of the children to initialize the view. This is called by the setParent(javax.swing.text.View) method. Subclasses can reimplement this to initialize their child views in a different manner. The default implementation creates a child view for each child element.

Parameters:
f - the view factory
See Also:
setParent(javax.swing.text.View)

setParent

public void setParent(View parent)
Sets the parent of the view. This is reimplemented to provide the superclass behavior as well as calling the loadChildren method if this view does not already have children. The children should not be loaded in the constructor because the act of setting the parent may cause them to try to search up the hierarchy (to get the hosting Container for example). If this view has children (the view is being moved from one place in the view hierarchy to another), the loadChildren method will not be called.

Overrides:
setParent in class View
Parameters:
parent - the parent of the view, null if none

getViewCount

public int getViewCount()
Returns the number of child views of this view.

Overrides:
getViewCount in class View
Returns:
the number of views >= 0
See Also:
getView(int)

getView

public View getView(int n)
Returns the n-th view in this container.

Overrides:
getView in class View
Parameters:
n - the number of the desired view, >= 0 && < getViewCount()
Returns:
the view at index n

replace

public void replace(int offset,
                    int length,
                    View[] views)
Replaces child views. If there are no views to remove this acts as an insert. If there are no views to add this acts as a remove. Views being removed will have the parent set to null, and the internal reference to them removed so that they may be garbage collected.

Overrides:
replace in class View
Parameters:
offset - the starting index into the child views to insert the new views; >= 0 and <= getViewCount
length - the number of existing child views to remove; this should be a value >= 0 and <= (getViewCount() - offset)
views - the child views to add; this value can be null to indicate no children are being added (useful to remove)

getChildAllocation

public Shape getChildAllocation(int index,
                                Shape a)
Fetches the allocation for the given child view to render into. This enables finding out where various views are located.

Overrides:
getChildAllocation in class View
Parameters:
index - the index of the child, >= 0 && < getViewCount()
a - the allocation to this view
Returns:
the allocation to the child

modelToView

public Shape modelToView(int pos,
                         Shape a,
                         Position.Bias b)
                  throws BadLocationException
Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.

Specified by:
modelToView in class View
Parameters:
pos - the position to convert >= 0
a - the allocated region to render into
b - a bias value of either Position.Bias.Forward or Position.Bias.Backward
Returns:
the bounding box of the given position
Throws:
BadLocationException - if the given position does not represent a valid location in the associated document
See Also:
View.modelToView(int, java.awt.Shape, javax.swing.text.Position.Bias)

modelToView

public Shape modelToView(int p0,
                         Position.Bias b0,
                         int p1,
                         Position.Bias b1,
                         Shape a)
                  throws BadLocationException
Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.

Overrides:
modelToView in class View
Parameters:
p0 - the position to convert >= 0
b0 - the bias toward the previous character or the next character represented by p0, in case the position is a boundary of two views; either Position.Bias.Forward or Position.Bias.Backward
p1 - the position to convert >= 0
b1 - the bias toward the previous character or the next character represented by p1, in case the position is a boundary of two views
a - the allocated region to render into
Returns:
the bounding box of the given position is returned
Throws:
BadLocationException - if the given position does not represent a valid location in the associated document
IllegalArgumentException - for an invalid bias argument
See Also:
View.viewToModel(float, float, java.awt.Shape, javax.swing.text.Position.Bias[])

viewToModel

public int viewToModel(float x,
                       float y,
                       Shape a,
                       Position.Bias[] bias)
Provides a mapping from the view coordinate space to the logical coordinate space of the model.

Specified by:
viewToModel in class View
Parameters:
x - x coordinate of the view location to convert >= 0
y - y coordinate of the view location to convert >= 0
a - the allocated region to render into
bias - either Position.Bias.Forward or Position.Bias.Backward
Returns:
the location within the model that best represents the given point in the view >= 0
See Also:
View.viewToModel(float, float, java.awt.Shape, javax.swing.text.Position.Bias[])

getNextVisualPositionFrom

public int getNextVisualPositionFrom(int pos,
                                     Position.Bias b,
                                     Shape a,
                                     int direction,
                                     Position.Bias[] biasRet)
                              throws BadLocationException
Provides a way to determine the next visually represented model location that one might place a caret. Some views may not be visible, they might not be in the same order found in the model, or they just might not allow access to some of the locations in the model. This is a convenience method for getNextNorthSouthVisualPositionFrom(int, javax.swing.text.Position.Bias, java.awt.Shape, int, javax.swing.text.Position.Bias[]) and getNextEastWestVisualPositionFrom(int, javax.swing.text.Position.Bias, java.awt.Shape, int, javax.swing.text.Position.Bias[]).

Overrides:
getNextVisualPositionFrom in class View
Parameters:
pos - the position to convert >= 0
b - a bias value of either Position.Bias.Forward or Position.Bias.Backward
a - the allocated region to render into
direction - the direction from the current position that can be thought of as the arrow keys typically found on a keyboard; this may be one of the following:
  • SwingConstants.WEST
  • SwingConstants.EAST
  • SwingConstants.NORTH
  • SwingConstants.SOUTH
biasRet - an array containing the bias that was checked
Returns:
the location within the model that best represents the next location visual position
Throws:
BadLocationException
IllegalArgumentException - if direction is invalid

getViewIndex

public int getViewIndex(int pos,
                        Position.Bias b)
Returns the child view index representing the given position in the model. This is implemented to call the getViewIndexByPosition method for backward compatibility.

Overrides:
getViewIndex in class View
Parameters:
pos - the position >= 0
Returns:
index of the view representing the given position, or -1 if no view represents that position

isBefore

protected abstract boolean isBefore(int x,
                                    int y,
                                    Rectangle alloc)
Tests whether a point lies before the rectangle range.

Parameters:
x - the X coordinate >= 0
y - the Y coordinate >= 0
alloc - the rectangle
Returns:
true if the point is before the specified range

isAfter

protected abstract boolean isAfter(int x,
                                   int y,
                                   Rectangle alloc)
Tests whether a point lies after the rectangle range.

Parameters:
x - the X coordinate >= 0
y - the Y coordinate >= 0
alloc - the rectangle
Returns:
true if the point is after the specified range

getViewAtPoint

protected abstract View getViewAtPoint(int x,
                                       int y,
                                       Rectangle alloc)
Fetches the child view at the given coordinates.

Parameters:
x - the X coordinate >= 0
y - the Y coordinate >= 0
alloc - the parent's allocation on entry, which should be changed to the child's allocation on exit
Returns:
the child view

childAllocation

protected abstract void childAllocation(int index,
                                        Rectangle a)
Returns the allocation for a given child.

Parameters:
index - the index of the child, >= 0 && < getViewCount()
a - the allocation to the interior of the box on entry, and the allocation of the child view at the index on exit.

getViewAtPosition

protected View getViewAtPosition(int pos,
                                 Rectangle a)
Fetches the child view that represents the given position in the model. This is implemented to fetch the view in the case where there is a child view for each child element.

Parameters:
pos - the position >= 0
a - the allocation to the interior of the box on entry, and the allocation of the view containing the position on exit
Returns:
the view representing the given position, or null if there isn't one

getViewIndexAtPosition

protected int getViewIndexAtPosition(int pos)
Fetches the child view index representing the given position in the model. This is implemented to fetch the view in the case where there is a child view for each child element.

Parameters:
pos - the position >= 0
Returns:
index of the view representing the given position, or -1 if no view represents that position

getInsideAllocation

protected Rectangle getInsideAllocation(Shape a)
Translates the immutable allocation given to the view to a mutable allocation that represents the interior allocation (i.e. the bounds of the given allocation with the top, left, bottom, and right insets removed. It is expected that the returned value would be further mutated to represent an allocation to a child view. This is implemented to reuse an instance variable so it avoids creating excessive Rectangles. Typically the result of calling this method would be fed to the childAllocation method.

Parameters:
a - the allocation given to the view
Returns:
the allocation that represents the inside of the view after the margins have all been removed; if the given allocation was null, the return value is null

setParagraphInsets

protected void setParagraphInsets(AttributeSet attr)
Sets the insets from the paragraph attributes specified in the given attributes.

Parameters:
attr - the attributes

setInsets

protected void setInsets(short top,
                         short left,
                         short bottom,
                         short right)
Sets the insets for the view.

Parameters:
top - the top inset >= 0
left - the left inset >= 0
bottom - the bottom inset >= 0
right - the right inset >= 0

getLeftInset

protected short getLeftInset()
Gets the left inset.

Returns:
the inset >= 0

getRightInset

protected short getRightInset()
Gets the right inset.

Returns:
the inset >= 0

getTopInset

protected short getTopInset()
Gets the top inset.

Returns:
the inset >= 0

getBottomInset

protected short getBottomInset()
Gets the bottom inset.

Returns:
the inset >= 0

getNextNorthSouthVisualPositionFrom

protected int getNextNorthSouthVisualPositionFrom(int pos,
                                                  Position.Bias b,
                                                  Shape a,
                                                  int direction,
                                                  Position.Bias[] biasRet)
                                           throws BadLocationException
Returns the next visual position for the cursor, in either the north or south direction.

Parameters:
pos - the position to convert >= 0
b - a bias value of either Position.Bias.Forward or Position.Bias.Backward
a - the allocated region to render into
direction - the direction from the current position that can be thought of as the arrow keys typically found on a keyboard; this may be one of the following:
  • SwingConstants.NORTH
  • SwingConstants.SOUTH
biasRet - an array containing the bias that was checked
Returns:
the location within the model that best represents the next north or south location
Throws:
BadLocationException
IllegalArgumentException - if direction is invalid
See Also:
getNextVisualPositionFrom(int, javax.swing.text.Position.Bias, java.awt.Shape, int, javax.swing.text.Position.Bias[])

getNextEastWestVisualPositionFrom

protected int getNextEastWestVisualPositionFrom(int pos,
                                                Position.Bias b,
                                                Shape a,
                                                int direction,
                                                Position.Bias[] biasRet)
                                         throws BadLocationException
Returns the next visual position for the cursor, in either the east or west direction.

Parameters:
pos - the position to convert >= 0
b - a bias value of either Position.Bias.Forward or Position.Bias.Backward
a - the allocated region to render into
direction - the direction from the current position that can be thought of as the arrow keys typically found on a keyboard; this may be one of the following:
  • SwingConstants.WEST
  • SwingConstants.EAST
biasRet - an array containing the bias that was checked
Returns:
the location within the model that best represents the next west or east location
Throws:
BadLocationException
IllegalArgumentException - if direction is invalid
See Also:
getNextVisualPositionFrom(int, javax.swing.text.Position.Bias, java.awt.Shape, int, javax.swing.text.Position.Bias[])

flipEastAndWestAtEnds

protected boolean flipEastAndWestAtEnds(int position,
                                        Position.Bias bias)
Determines in which direction the next view lays. Consider the View at index n. Typically the Views are layed out from left to right, so that the View to the EAST will be at index n + 1, and the View to the WEST will be at index n - 1. In certain situations, such as with bidirectional text, it is possible that the View to EAST is not at index n + 1, but rather at index n - 1, or that the View to the WEST is not at index n - 1, but index n + 1. In this case this method would return true, indicating the Views are layed out in descending order.

This unconditionally returns false, subclasses should override this method if there is the possibility for laying Views in descending order.

Parameters:
position - position into the model
bias - either Position.Bias.Forward or Position.Bias.Backward
Returns:
false
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DateFormatter (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class DateFormatter

java.lang.Object
    extended by javax.swing.JFormattedTextField.AbstractFormatter
        extended by javax.swing.text.DefaultFormatter
            extended by javax.swing.text.InternationalFormatter
                extended by javax.swing.text.DateFormatter
All Implemented Interfaces:
Cloneable, Serializable
public class DateFormatter
extends InternationalFormatter

DateFormatter is an InternationalFormatter that does its formatting by way of an instance of java.text.DateFormat.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Since:
1.4
See Also:
DateFormat

Constructor Summary
DateFormatter()
This is shorthand for new DateFormatter(DateFormat.getDateInstance()).
DateFormatter(DateFormat format)
Returns a DateFormatter configured with the specified Format instance.
Method Summary
 void setFormat(DateFormat format)
Sets the format that dictates the legal values that can be edited and displayed.
Methods inherited from class javax.swing.text.InternationalFormatter
clone, getActions, getFields, getFormat, getMaximum, getMinimum, install, setFormat, setMaximum, setMinimum, stringToValue, valueToString
Methods inherited from class javax.swing.text.DefaultFormatter
getAllowsInvalid, getCommitsOnValidEdit, getDocumentFilter, getNavigationFilter, getOverwriteMode, getValueClass, setAllowsInvalid, setCommitsOnValidEdit, setOverwriteMode, setValueClass
Methods inherited from class javax.swing.JFormattedTextField.AbstractFormatter
getFormattedTextField, invalidEdit, setEditValid, uninstall
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DateFormatter

public DateFormatter()
This is shorthand for new DateFormatter(DateFormat.getDateInstance()).

DateFormatter

public DateFormatter(DateFormat format)
Returns a DateFormatter configured with the specified Format instance.

Parameters:
format - Format used to dictate legal values
Method Detail

setFormat

public void setFormat(DateFormat format)
Sets the format that dictates the legal values that can be edited and displayed.

If you have used the nullary constructor the value of this property will be determined for the current locale by way of the Dateformat.getDateInstance() method.

Parameters:
format - DateFormat instance used for converting from/to Strings
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DefaultCaret (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class DefaultCaret

java.lang.Object
    extended by java.awt.geom.RectangularShape
        extended by java.awt.geom.Rectangle2D
            extended by java.awt.Rectangle
                extended by javax.swing.text.DefaultCaret
All Implemented Interfaces:
Caret, Cloneable, EventListener, FocusListener, MouseListener, MouseMotionListener, Serializable, Shape
Direct Known Subclasses:
BasicTextUI.BasicCaret
public class DefaultCaret
extends Rectangle
implements Caret, FocusListener, MouseListener, MouseMotionListener

A default implementation of Caret. The caret is rendered as a vertical line in the color specified by the CaretColor property of the associated JTextComponent. It can blink at the rate specified by the BlinkRate property.

This implementation expects two sources of asynchronous notification. The timer thread fires asynchronously, and causes the caret to simply repaint the most recent bounding box. The caret also tracks change as the document is modified. Typically this will happen on the event thread as a result of some mouse or keyboard event. Updates can also occur from some other thread mutating the document. There is a property AsynchronousMovement that determines if the caret will move on asynchronous updates. The default behavior is to not update on asynchronous updates. If asynchronous updates are allowed, the update thread will fire the caret position change to listeners asynchronously. The repaint of the new caret location will occur on the event thread in any case, as calls to modelToView are only safe on the event thread.

The caret acts as a mouse and focus listener on the text component it has been installed in, and defines the caret semantics based upon those events. The listener methods can be reimplemented to change the semantics. By default, the first mouse button will be used to set focus and caret position. Dragging the mouse pointer with the first mouse button will sweep out a selection that is contiguous in the model. If the associated text component is editable, the caret will become visible when focus is gained, and invisible when focus is lost.

The Highlighter bound to the associated text component is used to render the selection by default. Selection appearance can be customized by supplying a painter to use for the highlights. By default a painter is used that will render a solid color as specified in the associated text component in the SelectionColor property. This can easily be changed by reimplementing the getSelectionHighlighter method.

A customized caret appearance can be achieved by reimplementing the paint method. If the paint method is changed, the damage method should also be reimplemented to cause a repaint for the area needed to render the caret. The caret extends the Rectangle class which is used to hold the bounding box for where the caret was last rendered. This enables the caret to repaint in a thread-safe manner when the caret moves without making a call to modelToView which is unstable between model updates and view repair (i.e. the order of delivery to DocumentListeners is not guaranteed).

The magic caret position is set to null when the caret position changes. A timer is used to determine the new location (after the caret change). When the timer fires, if the magic caret position is still null it is reset to the current caret position. Any actions that change the caret position and want the magic caret position to remain the same, must remember the magic caret position, change the cursor, and then set the magic caret position to its original value. This has the benefit that only actions that want the magic caret position to persist (such as open/down) need to know about it.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

See Also:
Caret

Nested Class Summary
Nested classes inherited from class java.awt.geom.Rectangle2D
Rectangle2D.Double, Rectangle2D.Float
Field Summary
protected ChangeEvent | changeEvent The change event for the model.
protected EventListenerList | listenerList The event listener list.
Fields inherited from class java.awt.Rectangle
height, width, x, y
Fields inherited from class java.awt.geom.Rectangle2D
OUT_BOTTOM, OUT_LEFT, OUT_RIGHT, OUT_TOP
Constructor Summary
DefaultCaret()
Constructs a default caret.
Method Summary
void | addChangeListener(ChangeListener l) Adds a listener to track whenever the caret position has been changed.
protected void | adjustVisibility(Rectangle nloc) Scrolls the associated view (if necessary) to make the caret visible.
protected void | damage(Rectangle r) Damages the area surrounding the caret to cause it to be repainted in a new location.
void | deinstall(JTextComponent c) Called when the UI is being removed from the interface of a JTextComponent.
boolean | equals(Object obj) Compares this object to the specified object.
protected void | fireStateChanged() Notifies all listeners that have registered interest for notification on this event type.
void | focusGained(FocusEvent e) Called when the component containing the caret gains focus.
void | focusLost(FocusEvent e) Called when the component containing the caret loses focus.
int | getBlinkRate() Gets the caret blink rate.
ChangeListener[] | getChangeListeners() Returns an array of all the change listeners registered on this caret.
protected JTextComponent | getComponent() Gets the text editor component that this caret is is bound to.
int | getDot() Fetches the current position of the caret.
EventListener[] | getListeners(Class listenerType) Returns an array of all the objects currently registered as FooListeners upon this caret.
Point | getMagicCaretPosition() Gets the saved caret position.
int | getMark() Fetches the current position of the mark.
protected Highlighter.HighlightPainter | getSelectionPainter() Gets the painter for the Highlighter.
void | install(JTextComponent c) Called when the UI is being installed into the interface of a JTextComponent.
boolean | isSelectionVisible() Checks whether the current selection is visible.
boolean | isVisible() Determines if the caret is currently visible.
void | mouseClicked(MouseEvent e) Called when the mouse is clicked.
void | mouseDragged(MouseEvent e) Moves the caret position according to the mouse pointer's current location.
void | mouseEntered(MouseEvent e) Called when the mouse enters a region.
void | mouseExited(MouseEvent e) Called when the mouse exits a region.
void | mouseMoved(MouseEvent e) Called when the mouse is moved.
void | mousePressed(MouseEvent e) If button 1 is pressed, this is implemented to request focus on the associated text component, and to set the caret position.
void | mouseReleased(MouseEvent e) Called when the mouse is released.
protected void | moveCaret(MouseEvent e) Tries to move the position of the caret from the coordinates of a mouse event, using viewToModel().
void | moveDot(int dot) Moves the caret position to some other position.
void | paint(Graphics g) Renders the caret as a vertical line.
protected void | positionCaret(MouseEvent e) Tries to set the position of the caret from the coordinates of a mouse event, using viewToModel().
void | removeChangeListener(ChangeListener l) Removes a listener that was tracking caret position changes.
protected void | repaint() Cause the caret to be painted.
void | setBlinkRate(int rate) Sets the caret blink rate.
void | setDot(int dot) Sets the caret position and mark to some position.
void | setMagicCaretPosition(Point p) Saves the current caret position.
void | setSelectionVisible(boolean vis) Changes the selection visibility.
void | setVisible(boolean e) Sets the caret visibility, and repaints the caret.
String | toString() Returns a String representing this Rectangle and its values.
Methods inherited from class java.awt.Rectangle
add, add, add, contains, contains, contains, contains, createIntersection, createUnion, getBounds, getBounds2D, getHeight, getLocation, getSize, getWidth, getX, getY, grow, inside, intersection, intersects, isEmpty, move, outcode, reshape, resize, setBounds, setBounds, setLocation, setLocation, setRect, setSize, setSize, translate, union
Methods inherited from class java.awt.geom.Rectangle2D
add, add, add, contains, contains, getPathIterator, getPathIterator, hashCode, intersect, intersects, intersectsLine, intersectsLine, outcode, setFrame, setRect, union
Methods inherited from class java.awt.geom.RectangularShape
clone, contains, contains, getCenterX, getCenterY, getFrame, getMaxX, getMaxY, getMinX, getMinY, intersects, setFrame, setFrame, setFrameFromCenter, setFrameFromCenter, setFrameFromDiagonal, setFrameFromDiagonal
Methods inherited from class java.lang.Object
finalize, getClass, notify, notifyAll, wait, wait, wait
Methods inherited from interface java.awt.Shape
contains, contains, contains, contains, getPathIterator, getPathIterator, intersects, intersects

Field Detail

listenerList

protected EventListenerList listenerList
The event listener list.

changeEvent

protected transient ChangeEvent changeEvent
The change event for the model. Only one ChangeEvent is needed per model instance since the event's only (read-only) state is the source property. The source of events generated here is always "this".

Constructor Detail

DefaultCaret

public DefaultCaret()
Constructs a default caret.

Method Detail

getComponent

protected final JTextComponent getComponent()
Gets the text editor component that this caret is is bound to.

Returns:
the component

repaint

protected final void repaint()
Cause the caret to be painted. The repaint area is the bounding box of the caret (i.e. the caret rectangle or this).

This method is thread safe, although most Swing methods are not. Please see Threads and Swing for more information.

damage

protected void damage(Rectangle r)
Damages the area surrounding the caret to cause it to be repainted in a new location. If paint() is reimplemented, this method should also be reimplemented. This method should update the caret bounds (x, y, width, and height).

Parameters:
r - the current location of the caret
See Also:
paint(java.awt.Graphics)

adjustVisibility

protected void adjustVisibility(Rectangle nloc)
Scrolls the associated view (if necessary) to make the caret visible. Since how this should be done is somewhat of a policy, this method can be reimplemented to change the behavior. By default the scrollRectToVisible method is called on the associated component.

Parameters:
nloc - the new position to scroll to

getSelectionPainter

protected Highlighter.HighlightPainter getSelectionPainter()
Gets the painter for the Highlighter.

Returns:
the painter

positionCaret

protected void positionCaret(MouseEvent e)
Tries to set the position of the caret from the coordinates of a mouse event, using viewToModel().

Parameters:
e - the mouse event

moveCaret

protected void moveCaret(MouseEvent e)
Tries to move the position of the caret from the coordinates of a mouse event, using viewToModel(). This will cause a selection if the dot and mark are different.

Parameters:
e - the mouse event

focusGained

public void focusGained(FocusEvent e)
Called when the component containing the caret gains focus. This is implemented to set the caret to visible if the component is editable.

Specified by:
focusGained in interface FocusListener
Parameters:
e - the focus event
See Also:
FocusListener.focusGained(java.awt.event.FocusEvent)

focusLost

public void focusLost(FocusEvent e)
Called when the component containing the caret loses focus. This is implemented to set the caret to visibility to false.

Specified by:
focusLost in interface FocusListener
Parameters:
e - the focus event
See Also:
FocusListener.focusLost(java.awt.event.FocusEvent)

mouseClicked

public void mouseClicked(MouseEvent e)
Called when the mouse is clicked. If the click was generated from button1, a double click selects a word, and a triple click the current line.

Specified by:
mouseClicked in interface MouseListener
Parameters:
e - the mouse event
See Also:
MouseListener.mouseClicked(java.awt.event.MouseEvent)

mousePressed

public void mousePressed(MouseEvent e)
If button 1 is pressed, this is implemented to request focus on the associated text component, and to set the caret position. If the shift key is held down, the caret will be moved, potentially resulting in a selection, otherwise the caret position will be set to the new location. If the component is not enabled, there will be no request for focus.

Specified by:
mousePressed in interface MouseListener
Parameters:
e - the mouse event
See Also:
MouseListener.mousePressed(java.awt.event.MouseEvent)

mouseReleased

public void mouseReleased(MouseEvent e)
Called when the mouse is released.

Specified by:
mouseReleased in interface MouseListener
Parameters:
e - the mouse event
See Also:
MouseListener.mouseReleased(java.awt.event.MouseEvent)

mouseEntered

public void mouseEntered(MouseEvent e)
Called when the mouse enters a region.

Specified by:
mouseEntered in interface MouseListener
Parameters:
e - the mouse event
See Also:
MouseListener.mouseEntered(java.awt.event.MouseEvent)

mouseExited

public void mouseExited(MouseEvent e)
Called when the mouse exits a region.

Specified by:
mouseExited in interface MouseListener
Parameters:
e - the mouse event
See Also:
MouseListener.mouseExited(java.awt.event.MouseEvent)

mouseDragged

public void mouseDragged(MouseEvent e)
Moves the caret position according to the mouse pointer's current location. This effectively extends the selection. By default, this is only done for mouse button 1.

Specified by:
mouseDragged in interface MouseMotionListener
Parameters:
e - the mouse event
See Also:
MouseMotionListener.mouseDragged(java.awt.event.MouseEvent)

mouseMoved

public void mouseMoved(MouseEvent e)
Called when the mouse is moved.

Specified by:
mouseMoved in interface MouseMotionListener
Parameters:
e - the mouse event
See Also:
MouseMotionListener.mouseMoved(java.awt.event.MouseEvent)

paint

public void paint(Graphics g)
Renders the caret as a vertical line. If this is reimplemented the damage method should also be reimplemented as it assumes the shape of the caret is a vertical line. Sets the caret color to the value returned by getCaretColor().

If there are multiple text directions present in the associated document, a flag indicating the caret bias will be rendered. This will occur only if the associated document is a subclass of AbstractDocument and there are multiple bidi levels present in the bidi element structure (i.e. the text has multiple directions associated with it).

Specified by:
paint in interface Caret
Parameters:
g - the graphics context
See Also:
damage(java.awt.Rectangle)

install

public void install(JTextComponent c)
Called when the UI is being installed into the interface of a JTextComponent. This can be used to gain access to the model that is being navigated by the implementation of this interface. Sets the dot and mark to 0, and establishes document, property change, focus, mouse, and mouse motion listeners.

Specified by:
install in interface Caret
Parameters:
c - the component
See Also:
Caret.install(javax.swing.text.JTextComponent)

deinstall

public void deinstall(JTextComponent c)
Called when the UI is being removed from the interface of a JTextComponent. This is used to unregister any listeners that were attached.

Specified by:
deinstall in interface Caret
Parameters:
c - the component
See Also:
Caret.deinstall(javax.swing.text.JTextComponent)

addChangeListener

public void addChangeListener(ChangeListener l)
Adds a listener to track whenever the caret position has been changed.

Specified by:
addChangeListener in interface Caret
Parameters:
l - the listener
See Also:
Caret.addChangeListener(javax.swing.event.ChangeListener)

removeChangeListener

public void removeChangeListener(ChangeListener l)
Removes a listener that was tracking caret position changes.

Specified by:
removeChangeListener in interface Caret
Parameters:
l - the listener
See Also:
Caret.removeChangeListener(javax.swing.event.ChangeListener)

getChangeListeners

public ChangeListener[] getChangeListeners()
Returns an array of all the change listeners registered on this caret.

Returns:
all of this caret's ChangeListeners or an empty array if no change listeners are currently registered
Since:
1.4
See Also:
addChangeListener(javax.swing.event.ChangeListener), removeChangeListener(javax.swing.event.ChangeListener)

fireStateChanged

protected void fireStateChanged()
Notifies all listeners that have registered interest for notification on this event type. The event instance is lazily created using the parameters passed into the fire method. The listener list is processed last to first.

See Also:
EventListenerList

getListeners

public EventListener[] getListeners(Class listenerType)
Returns an array of all the objects currently registered as FooListeners upon this caret. FooListeners are registered using the addFooListener method.

You can specify the listenerType argument with a class literal, such as FooListener.class. For example, you can query a DefaultCaret c for its change listeners with the following code:

ChangeListener[] cls = (ChangeListener[])(c.getListeners(ChangeListener.class));
If no such listeners exist, this method returns an empty array.

Parameters:
listenerType - the type of listeners requested; this parameter should specify an interface that descends from java.util.EventListener
Returns:
an array of all objects registered as FooListeners on this component, or an empty array if no such listeners have been added
Throws:
ClassCastException - if listenerType doesn't specify a class or interface that implements java.util.EventListener
Since:
1.3
See Also:
getChangeListeners()

setSelectionVisible

public void setSelectionVisible(boolean vis)
Changes the selection visibility.

Specified by:
setSelectionVisible in interface Caret
Parameters:
vis - the new visibility

isSelectionVisible

public boolean isSelectionVisible()
Checks whether the current selection is visible.

Specified by:
isSelectionVisible in interface Caret
Returns:
true if the selection is visible

isVisible

public boolean isVisible()
Determines if the caret is currently visible.

Specified by:
isVisible in interface Caret
Returns:
true if visible else false
See Also:
Caret.isVisible()

setVisible

public void setVisible(boolean e)
Sets the caret visibility, and repaints the caret.

Specified by:
setVisible in interface Caret
Parameters:
e - the visibility specifier
See Also:
Caret.setVisible(boolean)

setBlinkRate

public void setBlinkRate(int rate)
Sets the caret blink rate.

Specified by:
setBlinkRate in interface Caret
Parameters:
rate - the rate in milliseconds, 0 to stop blinking
See Also:
Caret.setBlinkRate(int)

getBlinkRate

public int getBlinkRate()
Gets the caret blink rate.

Specified by:
getBlinkRate in interface Caret
Returns:
the delay in milliseconds. If this is zero the caret will not blink.
See Also:
Caret.getBlinkRate()

getDot

public int getDot()
Fetches the current position of the caret.

Specified by:
getDot in interface Caret
Returns:
the position >= 0
See Also:
Caret.getDot()

getMark

public int getMark()
Fetches the current position of the mark. If there is a selection, the dot and mark will not be the same.

Specified by:
getMark in interface Caret
Returns:
the position >= 0
See Also:
Caret.getMark()

setDot

public void setDot(int dot)
Sets the caret position and mark to some position. This implicitly sets the selection range to zero.

Specified by:
setDot in interface Caret
Parameters:
dot - the position >= 0
See Also:
Caret.setDot(int)

moveDot

public void moveDot(int dot)
Moves the caret position to some other position.

Specified by:
moveDot in interface Caret
Parameters:
dot - the position >= 0
See Also:
Caret.moveDot(int)

setMagicCaretPosition

public void setMagicCaretPosition(Point p)
Saves the current caret position. This is used when caret up/down actions occur, moving between lines that have uneven end positions.

Specified by:
setMagicCaretPosition in interface Caret
Parameters:
p - the position
See Also:
getMagicCaretPosition()

getMagicCaretPosition

public Point getMagicCaretPosition()
Gets the saved caret position.

Specified by:
getMagicCaretPosition in interface Caret
Returns:
the position see #setMagicCaretPosition
See Also:
Caret.setMagicCaretPosition(java.awt.Point)

equals

public boolean equals(Object obj)
Compares this object to the specified object. The superclass behavior of comparing rectangles is not desired, so this is changed to the Object behavior.

Overrides:
equals in class Rectangle
Parameters:
obj - the object to compare this font with
Returns:
true if the objects are equal; false otherwise

toString

public String toString()
Description copied from class: Rectangle
Returns a String representing this Rectangle and its values.

Overrides:
toString in class Rectangle
Returns:
a String representing this Rectangle object's coordinate and size values.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DefaultEditorKit (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class DefaultEditorKit

java.lang.Object
    extended by javax.swing.text.EditorKit
        extended by javax.swing.text.DefaultEditorKit
All Implemented Interfaces:
Cloneable, Serializable
Direct Known Subclasses:
StyledEditorKit
public class DefaultEditorKit
extends EditorKit

This is the set of things needed by a text component to be a reasonably functioning editor for some type of text document. This implementation provides a default implementation which treats text as plain text and provides a minimal set of actions for a simple editor.

Newlines
There are two properties which deal with newlines. The system property, line.separator, is defined to be platform-dependent, either "\n", "\r", or "\r\n". There is also a property defined in DefaultEditorKit, called EndOfLineStringProperty, which is defined automatically when a document is loaded, to be the first occurrence of any of the newline characters. When a document is loaded, EndOfLineStringProperty is set appropriately, and when the document is written back out, the EndOfLineStringProperty is used. But while the document is in memory, the "\n" character is used to define a newline, regardless of how the newline is defined when the document is on disk. Therefore, for searching purposes, "\n" should always be used. When a new document is created, and the EndOfLineStringProperty has not been defined, it will use the System property when writing out the document.

Note that EndOfLineStringProperty is set on the Document using the get/setProperty methods. Subclasses may override this behavior.

Nested Class Summary
static class | DefaultEditorKit.BeepAction Creates a beep.
static class | DefaultEditorKit.CopyAction Copies the selected region and place its contents into the system clipboard.
static class | DefaultEditorKit.CutAction Cuts the selected region and place its contents into the system clipboard.
static class | DefaultEditorKit.DefaultKeyTypedAction The action that is executed by default if a key typed event is received and there is no keymap entry.
static class | DefaultEditorKit.InsertBreakAction Places a line/paragraph break into the document.
static class | DefaultEditorKit.InsertContentAction Places content into the associated document.
static class | DefaultEditorKit.InsertTabAction Places a tab character into the document.
static class | DefaultEditorKit.PasteAction Pastes the contents of the system clipboard into the selected region, or before the caret if nothing is selected.
Field Summary
static String | backwardAction Name of the Action for moving the caret logically backward one position.
static String | beepAction Name of the action to create a beep.
static String | beginAction Name of the Action for moving the caret to the beginning of the document.
static String | beginLineAction Name of the Action for moving the caret to the beginning of a line.
static String | beginParagraphAction Name of the Action for moving the caret to the beginning of a paragraph.
static String | beginWordAction Name of the Action for moving the caret to the beginning of a word.
static String | copyAction Name of the action to copy the selected region and place the contents into the system clipboard.
static String | cutAction Name of the action to cut the selected region and place the contents into the system clipboard.
static String | defaultKeyTypedAction Name of the action that is executed by default if a key typed event is received and there is no keymap entry.
static String | deleteNextCharAction Name of the action to delete the character of content that follows the current caret position.
static String | deletePrevCharAction Name of the action to delete the character of content that precedes the current caret position.
static String | downAction Name of the Action for moving the caret logically downward one position.
static String | endAction Name of the Action for moving the caret to the end of the document.
static String | endLineAction Name of the Action for moving the caret to the end of a line.
static String | EndOfLineStringProperty When reading a document if a CRLF is encountered a property with this name is added and the value will be "\r\n".
static String | endParagraphAction Name of the Action for moving the caret to the end of a paragraph.
static String | endWordAction Name of the Action for moving the caret to the end of a word.
static String | forwardAction Name of the Action for moving the caret logically forward one position.
static String | insertBreakAction Name of the action to place a line/paragraph break into the document.
static String | insertContentAction Name of the action to place content into the associated document.
static String | insertTabAction Name of the action to place a tab character into the document.
static String | nextWordAction Name of the Action for moving the caret to the beginning of the next word.
static String | pageDownAction Name of the action to page down vertically.
static String | pageUpAction Name of the action to page up vertically.
static String | pasteAction Name of the action to paste the contents of the system clipboard into the selected region, or before the caret if nothing is selected.
static String | previousWordAction Name of the Action for moving the caret to the beginning of the previous word.
static String | readOnlyAction Name of the action to set the editor into read-only mode.
static String | selectAllAction Name of the Action for selecting the entire document
static String | selectionBackwardAction Name of the Action for extending the selection by moving the caret logically backward one position.
static String | selectionBeginAction Name of the Action for moving the caret to the beginning of the document.
static String | selectionBeginLineAction Name of the Action for moving the caret to the beginning of a line, extending the selection.
static String | selectionBeginParagraphAction Name of the Action for moving the caret to the beginning of a paragraph, extending the selection.
static String | selectionBeginWordAction Name of the Action for moving the caret to the beginning of a word, extending the selection.
static String | selectionDownAction Name of the Action for moving the caret logically downward one position, extending the selection.
static String | selectionEndAction Name of the Action for moving the caret to the end of the document.
static String | selectionEndLineAction Name of the Action for moving the caret to the end of a line, extending the selection.
static String | selectionEndParagraphAction Name of the Action for moving the caret to the end of a paragraph, extending the selection.
static String | selectionEndWordAction Name of the Action for moving the caret to the end of a word, extending the selection.
static String | selectionForwardAction Name of the Action for extending the selection by moving the caret logically forward one position.
static String | selectionNextWordAction Name of the Action for moving the selection to the beginning of the next word, extending the selection.
static String | selectionPreviousWordAction Name of the Action for moving the selection to the beginning of the previous word, extending the selection.
static String | selectionUpAction Name of the Action for moving the caret logically upward one position, extending the selection.
static String | selectLineAction Name of the Action for selecting a line around the caret.
static String | selectParagraphAction Name of the Action for selecting a paragraph around the caret.
static String | selectWordAction Name of the Action for selecting a word around the caret.
static String | upAction Name of the Action for moving the caret logically upward one position.
static String | writableAction Name of the action to set the editor into writeable mode.
Constructor Summary
DefaultEditorKit()
default constructor for DefaultEditorKit
Method Summary
Caret | createCaret() Fetches a caret that can navigate through views produced by the associated ViewFactory.
Document | createDefaultDocument() Creates an uninitialized text storage model (PlainDocument) that is appropriate for this type of editor.
Action[] | getActions() Fetches the set of commands that can be used on a text component that is using a model and view produced by this kit.
String | getContentType() Gets the MIME type of the data that this kit represents support for.
ViewFactory | getViewFactory() Fetches a factory that is suitable for producing views of any models that are produced by this kit.
void | read(InputStream in, Document doc, int pos) Inserts content from the given stream which is expected to be in a format appropriate for this kind of content handler.
void | read(Reader in, Document doc, int pos) Inserts content from the given stream, which will be treated as plain text.
void | write(OutputStream out, Document doc, int pos, int len) Writes content from a document to the given stream in a format appropriate for this kind of content handler.
void | write(Writer out, Document doc, int pos, int len) Writes content from a document to the given stream as plain text.
Methods inherited from class javax.swing.text.EditorKit
clone, deinstall, install
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

EndOfLineStringProperty

public static final String EndOfLineStringProperty
When reading a document if a CRLF is encountered a property with this name is added and the value will be "\r\n".

See Also:
Constant Field Values

insertContentAction

public static final String insertContentAction
Name of the action to place content into the associated document. If there is a selection, it is removed before the new content is added.

See Also:
getActions(), Constant Field Values

insertBreakAction

public static final String insertBreakAction
Name of the action to place a line/paragraph break into the document. If there is a selection, it is removed before the break is added.

See Also:
getActions(), Constant Field Values

insertTabAction

public static final String insertTabAction
Name of the action to place a tab character into the document. If there is a selection, it is removed before the tab is added.

See Also:
getActions(), Constant Field Values

deletePrevCharAction

public static final String deletePrevCharAction
Name of the action to delete the character of content that precedes the current caret position.

See Also:
getActions(), Constant Field Values

deleteNextCharAction

public static final String deleteNextCharAction
Name of the action to delete the character of content that follows the current caret position.

See Also:
getActions(), Constant Field Values

readOnlyAction

public static final String readOnlyAction
Name of the action to set the editor into read-only mode.

See Also:
getActions(), Constant Field Values

writableAction

public static final String writableAction
Name of the action to set the editor into writeable mode.

See Also:
getActions(), Constant Field Values

cutAction

public static final String cutAction
Name of the action to cut the selected region and place the contents into the system clipboard.

See Also:
JTextComponent.cut(), getActions(), Constant Field Values

copyAction

public static final String copyAction
Name of the action to copy the selected region and place the contents into the system clipboard.

See Also:
JTextComponent.copy(), getActions(), Constant Field Values

pasteAction

public static final String pasteAction
Name of the action to paste the contents of the system clipboard into the selected region, or before the caret if nothing is selected.

See Also:
JTextComponent.paste(), getActions(), Constant Field Values

beepAction

public static final String beepAction
Name of the action to create a beep.

See Also:
getActions(), Constant Field Values

pageUpAction

public static final String pageUpAction
Name of the action to page up vertically.

See Also:
getActions(), Constant Field Values

pageDownAction

public static final String pageDownAction
Name of the action to page down vertically.

See Also:
getActions(), Constant Field Values

forwardAction

public static final String forwardAction
Name of the Action for moving the caret logically forward one position.

See Also:
getActions(), Constant Field Values

backwardAction

public static final String backwardAction
Name of the Action for moving the caret logically backward one position.

See Also:
getActions(), Constant Field Values

selectionForwardAction

public static final String selectionForwardAction
Name of the Action for extending the selection by moving the caret logically forward one position.

See Also:
getActions(), Constant Field Values

selectionBackwardAction

public static final String selectionBackwardAction
Name of the Action for extending the selection by moving the caret logically backward one position.

See Also:
getActions(), Constant Field Values

upAction

public static final String upAction
Name of the Action for moving the caret logically upward one position.

See Also:
getActions(), Constant Field Values

downAction

public static final String downAction
Name of the Action for moving the caret logically downward one position.

See Also:
getActions(), Constant Field Values

selectionUpAction

public static final String selectionUpAction
Name of the Action for moving the caret logically upward one position, extending the selection.

See Also:
getActions(), Constant Field Values

selectionDownAction

public static final String selectionDownAction
Name of the Action for moving the caret logically downward one position, extending the selection.

See Also:
getActions(), Constant Field Values

beginWordAction

public static final String beginWordAction
Name of the Action for moving the caret to the beginning of a word.

See Also:
getActions(), Constant Field Values

endWordAction

public static final String endWordAction
Name of the Action for moving the caret to the end of a word.

See Also:
getActions(), Constant Field Values

selectionBeginWordAction

public static final String selectionBeginWordAction
Name of the Action for moving the caret to the beginning of a word, extending the selection.

See Also:
getActions(), Constant Field Values

selectionEndWordAction

public static final String selectionEndWordAction
Name of the Action for moving the caret to the end of a word, extending the selection.

See Also:
getActions(), Constant Field Values

previousWordAction

public static final String previousWordAction
Name of the Action for moving the caret to the beginning of the previous word.

See Also:
getActions(), Constant Field Values

nextWordAction

public static final String nextWordAction
Name of the Action for moving the caret to the beginning of the next word.

See Also:
getActions(), Constant Field Values

selectionPreviousWordAction

public static final String selectionPreviousWordAction
Name of the Action for moving the selection to the beginning of the previous word, extending the selection.

See Also:
getActions(), Constant Field Values

selectionNextWordAction

public static final String selectionNextWordAction
Name of the Action for moving the selection to the beginning of the next word, extending the selection.

See Also:
getActions(), Constant Field Values

beginLineAction

public static final String beginLineAction
Name of the Action for moving the caret to the beginning of a line.

See Also:
getActions(), Constant Field Values

endLineAction

public static final String endLineAction
Name of the Action for moving the caret to the end of a line.

See Also:
getActions(), Constant Field Values

selectionBeginLineAction

public static final String selectionBeginLineAction
Name of the Action for moving the caret to the beginning of a line, extending the selection.

See Also:
getActions(), Constant Field Values

selectionEndLineAction

public static final String selectionEndLineAction
Name of the Action for moving the caret to the end of a line, extending the selection.

See Also:
getActions(), Constant Field Values

beginParagraphAction

public static final String beginParagraphAction
Name of the Action for moving the caret to the beginning of a paragraph.

See Also:
getActions(), Constant Field Values

endParagraphAction

public static final String endParagraphAction
Name of the Action for moving the caret to the end of a paragraph.

See Also:
getActions(), Constant Field Values

selectionBeginParagraphAction

public static final String selectionBeginParagraphAction
Name of the Action for moving the caret to the beginning of a paragraph, extending the selection.

See Also:
getActions(), Constant Field Values

selectionEndParagraphAction

public static final String selectionEndParagraphAction
Name of the Action for moving the caret to the end of a paragraph, extending the selection.

See Also:
getActions(), Constant Field Values

beginAction

public static final String beginAction
Name of the Action for moving the caret to the beginning of the document.

See Also:
getActions(), Constant Field Values

endAction

public static final String endAction
Name of the Action for moving the caret to the end of the document.

See Also:
getActions(), Constant Field Values

selectionBeginAction

public static final String selectionBeginAction
Name of the Action for moving the caret to the beginning of the document.

See Also:
getActions(), Constant Field Values

selectionEndAction

public static final String selectionEndAction
Name of the Action for moving the caret to the end of the document.

See Also:
getActions(), Constant Field Values

selectWordAction

public static final String selectWordAction
Name of the Action for selecting a word around the caret.

See Also:
getActions(), Constant Field Values

selectLineAction

public static final String selectLineAction
Name of the Action for selecting a line around the caret.

See Also:
getActions(), Constant Field Values

selectParagraphAction

public static final String selectParagraphAction
Name of the Action for selecting a paragraph around the caret.

See Also:
getActions(), Constant Field Values

selectAllAction

public static final String selectAllAction
Name of the Action for selecting the entire document

See Also:
getActions(), Constant Field Values

defaultKeyTypedAction

public static final String defaultKeyTypedAction
Name of the action that is executed by default if a key typed event is received and there is no keymap entry.

See Also:
getActions(), Constant Field Values
Constructor Detail

DefaultEditorKit

public DefaultEditorKit()
default constructor for DefaultEditorKit

Method Detail

getContentType

public String getContentType()
Gets the MIME type of the data that this kit represents support for. The default is text/plain.

Specified by:
getContentType in class EditorKit
Returns:
the type

getViewFactory

public ViewFactory getViewFactory()
Fetches a factory that is suitable for producing views of any models that are produced by this kit. The default is to have the UI produce the factory, so this method has no implementation.

Specified by:
getViewFactory in class EditorKit
Returns:
the view factory

getActions

public Action[] getActions()
Fetches the set of commands that can be used on a text component that is using a model and view produced by this kit.

Specified by:
getActions in class EditorKit
Returns:
the command list

createCaret

public Caret createCaret()
Fetches a caret that can navigate through views produced by the associated ViewFactory.

Specified by:
createCaret in class EditorKit
Returns:
the caret

createDefaultDocument

public Document createDefaultDocument()
Creates an uninitialized text storage model (PlainDocument) that is appropriate for this type of editor.

Specified by:
createDefaultDocument in class EditorKit
Returns:
the model

read

public void read(InputStream in,
                 Document doc,
                 int pos)
          throws IOException,
                 BadLocationException
Inserts content from the given stream which is expected to be in a format appropriate for this kind of content handler.

Specified by:
read in class EditorKit
Parameters:
in - The stream to read from
doc - The destination for the insertion.
pos - The location in the document to place the content >= 0.
Throws:
IOException - on any I/O error
BadLocationException - if pos represents an invalid location within the document.

write

public void write(OutputStream out,
                  Document doc,
                  int pos,
                  int len)
           throws IOException,
                  BadLocationException
Writes content from a document to the given stream in a format appropriate for this kind of content handler.

Specified by:
write in class EditorKit
Parameters:
out - The stream to write to
doc - The source for the write.
pos - The location in the document to fetch the content >= 0.
len - The amount to write out >= 0.
Throws:
IOException - on any I/O error
BadLocationException - if pos represents an invalid location within the document.

read

public void read(Reader in,
                 Document doc,
                 int pos)
          throws IOException,
                 BadLocationException
Inserts content from the given stream, which will be treated as plain text.

Specified by:
read in class EditorKit
Parameters:
in - The stream to read from
doc - The destination for the insertion.
pos - The location in the document to place the content >= 0.
Throws:
IOException - on any I/O error
BadLocationException - if pos represents an invalid location within the document.

write

public void write(Writer out,
                  Document doc,
                  int pos,
                  int len)
           throws IOException,
                  BadLocationException
Writes content from a document to the given stream as plain text.

Specified by:
write in class EditorKit
Parameters:
out - The stream to write to
doc - The source for the write.
pos - The location in the document to fetch the content from >= 0.
len - The amount to write out >= 0.
Throws:
IOException - on any I/O error
BadLocationException - if pos is not within 0 and the length of the document.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DefaultEditorKit.BeepAction (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class DefaultEditorKit.BeepAction

java.lang.Object
    extended by javax.swing.AbstractAction
        extended by javax.swing.text.TextAction
            extended by javax.swing.text.DefaultEditorKit.BeepAction
All Implemented Interfaces:
Action, ActionListener, Cloneable, EventListener, Serializable
Enclosing class:
DefaultEditorKit
public static class DefaultEditorKit.BeepAction
extends TextAction

Creates a beep.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

See Also:
DefaultEditorKit.beepAction, DefaultEditorKit.getActions()

Field Summary
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SHORT_DESCRIPTION, SMALL_ICON
Constructor Summary
DefaultEditorKit.BeepAction()
Create this object with the appropriate identifier.
Method Summary
 void actionPerformed(ActionEvent e)
The operation to perform when this action is triggered.
Methods inherited from class javax.swing.text.TextAction
augmentList, getFocusedComponent, getTextComponent
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DefaultEditorKit.BeepAction

public DefaultEditorKit.BeepAction()
Create this object with the appropriate identifier.

Method Detail

actionPerformed

public void actionPerformed(ActionEvent e)
The operation to perform when this action is triggered.

Parameters:
e - the action event
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DefaultEditorKit.CopyAction (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class DefaultEditorKit.CopyAction

java.lang.Object
    extended by javax.swing.AbstractAction
        extended by javax.swing.text.TextAction
            extended by javax.swing.text.DefaultEditorKit.CopyAction
All Implemented Interfaces:
Action, ActionListener, Cloneable, EventListener, Serializable
Enclosing class:
DefaultEditorKit
public static class DefaultEditorKit.CopyAction
extends TextAction

Copies the selected region and place its contents into the system clipboard.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

See Also:
DefaultEditorKit.copyAction, DefaultEditorKit.getActions()

Field Summary
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SHORT_DESCRIPTION, SMALL_ICON
Constructor Summary
DefaultEditorKit.CopyAction()
Create this object with the appropriate identifier.
Method Summary
 void actionPerformed(ActionEvent e)
The operation to perform when this action is triggered.
Methods inherited from class javax.swing.text.TextAction
augmentList, getFocusedComponent, getTextComponent
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DefaultEditorKit.CopyAction

public DefaultEditorKit.CopyAction()
Create this object with the appropriate identifier.

Method Detail

actionPerformed

public void actionPerformed(ActionEvent e)
The operation to perform when this action is triggered.

Parameters:
e - the action event
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DefaultEditorKit.CutAction (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class DefaultEditorKit.CutAction

java.lang.Object
    extended by javax.swing.AbstractAction
        extended by javax.swing.text.TextAction
            extended by javax.swing.text.DefaultEditorKit.CutAction
All Implemented Interfaces:
Action, ActionListener, Cloneable, EventListener, Serializable
Enclosing class:
DefaultEditorKit
public static class DefaultEditorKit.CutAction
extends TextAction

Cuts the selected region and place its contents into the system clipboard.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

See Also:
DefaultEditorKit.cutAction, DefaultEditorKit.getActions()

Field Summary
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SHORT_DESCRIPTION, SMALL_ICON
Constructor Summary
DefaultEditorKit.CutAction()
Create this object with the appropriate identifier.
Method Summary
 void actionPerformed(ActionEvent e)
The operation to perform when this action is triggered.
Methods inherited from class javax.swing.text.TextAction
augmentList, getFocusedComponent, getTextComponent
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DefaultEditorKit.CutAction

public DefaultEditorKit.CutAction()
Create this object with the appropriate identifier.

Method Detail

actionPerformed

public void actionPerformed(ActionEvent e)
The operation to perform when this action is triggered.

Parameters:
e - the action event
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DefaultEditorKit.DefaultKeyTypedAction (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class DefaultEditorKit.DefaultKeyTypedAction

java.lang.Object
    extended by javax.swing.AbstractAction
        extended by javax.swing.text.TextAction
            extended by javax.swing.text.DefaultEditorKit.DefaultKeyTypedAction
All Implemented Interfaces:
Action, ActionListener, Cloneable, EventListener, Serializable
Enclosing class:
DefaultEditorKit
public static class DefaultEditorKit.DefaultKeyTypedAction
extends TextAction

The action that is executed by default if a key typed event is received and there is no keymap entry. There is a variation across different VM's in what gets sent as a key typed event, and this action tries to filter out the undesired events. This filters the control characters and those with the ALT modifier. It allows Control-Alt sequences through as these form legitimate unicode characters on some PC keyboards.

If the event doesn't get filtered, it will try to insert content into the text editor. The content is fetched from the command string of the ActionEvent. The text entry is done through the replaceSelection method on the target text component. This is the action that will be fired for most text entry tasks.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

See Also:
DefaultEditorKit.defaultKeyTypedAction,
DefaultEditorKit.getActions(),
Keymap.setDefaultAction(javax.swing.Action),
Keymap.getDefaultAction()

Field Summary
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SHORT_DESCRIPTION, SMALL_ICON
Constructor Summary
DefaultEditorKit.DefaultKeyTypedAction()
Creates this object with the appropriate identifier.
Method Summary
 void actionPerformed(ActionEvent e)
The operation to perform when this action is triggered.
Methods inherited from class javax.swing.text.TextAction
augmentList, getFocusedComponent, getTextComponent
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DefaultEditorKit.DefaultKeyTypedAction

public DefaultEditorKit.DefaultKeyTypedAction()
Creates this object with the appropriate identifier.

Method Detail

actionPerformed

public void actionPerformed(ActionEvent e)
The operation to perform when this action is triggered.

Parameters:
e - the action event
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DefaultEditorKit.InsertBreakAction (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class DefaultEditorKit.InsertBreakAction

java.lang.Object
    extended by javax.swing.AbstractAction
        extended by javax.swing.text.TextAction
            extended by javax.swing.text.DefaultEditorKit.InsertBreakAction
All Implemented Interfaces:
Action, ActionListener, Cloneable, EventListener, Serializable
Enclosing class:
DefaultEditorKit
public static class DefaultEditorKit.InsertBreakAction
extends TextAction

Places a line/paragraph break into the document. If there is a selection, it is removed before the break is added.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

See Also:
DefaultEditorKit.insertBreakAction, DefaultEditorKit.getActions()

Field Summary
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SHORT_DESCRIPTION, SMALL_ICON
Constructor Summary
DefaultEditorKit.InsertBreakAction()
Creates this object with the appropriate identifier.
Method Summary
 void actionPerformed(ActionEvent e)
The operation to perform when this action is triggered.
Methods inherited from class javax.swing.text.TextAction
augmentList, getFocusedComponent, getTextComponent
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DefaultEditorKit.InsertBreakAction

public DefaultEditorKit.InsertBreakAction()
Creates this object with the appropriate identifier.

Method Detail

actionPerformed

public void actionPerformed(ActionEvent e)
The operation to perform when this action is triggered.

Parameters:
e - the action event
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DefaultEditorKit.InsertContentAction (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class DefaultEditorKit.InsertContentAction

java.lang.Object
    extended by javax.swing.AbstractAction
        extended by javax.swing.text.TextAction
            extended by javax.swing.text.DefaultEditorKit.InsertContentAction
All Implemented Interfaces:
Action, ActionListener, Cloneable, EventListener, Serializable
Enclosing class:
DefaultEditorKit
public static class DefaultEditorKit.InsertContentAction
extends TextAction

Places content into the associated document. If there is a selection, it is removed before the new content is added.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

See Also:
DefaultEditorKit.insertContentAction, DefaultEditorKit.getActions()

Field Summary
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SHORT_DESCRIPTION, SMALL_ICON
Constructor Summary
DefaultEditorKit.InsertContentAction()
Creates this object with the appropriate identifier.
Method Summary
 void actionPerformed(ActionEvent e)
The operation to perform when this action is triggered.
Methods inherited from class javax.swing.text.TextAction
augmentList, getFocusedComponent, getTextComponent
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DefaultEditorKit.InsertContentAction

public DefaultEditorKit.InsertContentAction()
Creates this object with the appropriate identifier.

Method Detail

actionPerformed

public void actionPerformed(ActionEvent e)
The operation to perform when this action is triggered.

Parameters:
e - the action event
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DefaultEditorKit.InsertTabAction (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class DefaultEditorKit.InsertTabAction

java.lang.Object
    extended by javax.swing.AbstractAction
        extended by javax.swing.text.TextAction
            extended by javax.swing.text.DefaultEditorKit.InsertTabAction
All Implemented Interfaces:
Action, ActionListener, Cloneable, EventListener, Serializable
Enclosing class:
DefaultEditorKit
public static class DefaultEditorKit.InsertTabAction
extends TextAction

Places a tab character into the document. If there is a selection, it is removed before the tab is added.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

See Also:
DefaultEditorKit.insertTabAction, DefaultEditorKit.getActions()

Field Summary
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SHORT_DESCRIPTION, SMALL_ICON
Constructor Summary
DefaultEditorKit.InsertTabAction()
Creates this object with the appropriate identifier.
Method Summary
 void actionPerformed(ActionEvent e)
The operation to perform when this action is triggered.
Methods inherited from class javax.swing.text.TextAction
augmentList, getFocusedComponent, getTextComponent
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DefaultEditorKit.InsertTabAction

public DefaultEditorKit.InsertTabAction()
Creates this object with the appropriate identifier.

Method Detail

actionPerformed

public void actionPerformed(ActionEvent e)
The operation to perform when this action is triggered.

Parameters:
e - the action event
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DefaultEditorKit.PasteAction (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class DefaultEditorKit.PasteAction

java.lang.Object
    extended by javax.swing.AbstractAction
        extended by javax.swing.text.TextAction
            extended by javax.swing.text.DefaultEditorKit.PasteAction
All Implemented Interfaces:
Action, ActionListener, Cloneable, EventListener, Serializable
Enclosing class:
DefaultEditorKit
public static class DefaultEditorKit.PasteAction
extends TextAction

Pastes the contents of the system clipboard into the selected region, or before the caret if nothing is selected.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

See Also:
DefaultEditorKit.pasteAction, DefaultEditorKit.getActions()

Field Summary
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SHORT_DESCRIPTION, SMALL_ICON
Constructor Summary
DefaultEditorKit.PasteAction()
Create this object with the appropriate identifier.
Method Summary
 void actionPerformed(ActionEvent e)
The operation to perform when this action is triggered.
Methods inherited from class javax.swing.text.TextAction
augmentList, getFocusedComponent, getTextComponent
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DefaultEditorKit.PasteAction

public DefaultEditorKit.PasteAction()
Create this object with the appropriate identifier.

Method Detail

actionPerformed

public void actionPerformed(ActionEvent e)
The operation to perform when this action is triggered.

Parameters:
e - the action event
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DefaultFormatter (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class DefaultFormatter

java.lang.Object
    extended by javax.swing.JFormattedTextField.AbstractFormatter
        extended by javax.swing.text.DefaultFormatter
All Implemented Interfaces:
Cloneable, Serializable
Direct Known Subclasses:
InternationalFormatter, MaskFormatter
public class DefaultFormatter
extends JFormattedTextField.AbstractFormatter
implements Cloneable, Serializable

DefaultFormatter formats aribtrary objects. Formatting is done by invoking the toString method. In order to convert the value back to a String, your class must provide a constructor that takes a String argument. If no single argument constructor that takes a String is found, the returned value will be the String passed into stringToValue.

Instances of DefaultFormatter can not be used in multiple instances of JFormattedTextField. To obtain a copy of an already configured DefaultFormatter, use the clone method.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Since:
1.4
See Also:
JFormattedTextField.AbstractFormatter

Constructor Summary
DefaultFormatter()
Creates a DefaultFormatter.
Method Summary
Object | clone() Creates a copy of the DefaultFormatter.
boolean | getAllowsInvalid() Returns whether or not the value being edited is allowed to be invalid for a length of time.
boolean | getCommitsOnValidEdit() Returns when edits are published back to the JFormattedTextField.
protected DocumentFilter | getDocumentFilter() Returns the DocumentFilter used to restrict the characters that can be input into the JFormattedTextField.
protected NavigationFilter | getNavigationFilter() Returns the NavigationFilter used to restrict where the cursor can be placed.
boolean | getOverwriteMode() Returns the behavior when inserting characters.
Class | getValueClass() Returns that class that is used to create new Objects.
void | install(JFormattedTextField ftf) Installs the DefaultFormatter onto a particular JFormattedTextField.
void | setAllowsInvalid(boolean allowsInvalid) Sets whether or not the value being edited is allowed to be invalid for a length of time (that is, stringToValue throws a ParseException).
void | setCommitsOnValidEdit(boolean commit) Sets when edits are published back to the JFormattedTextField.
void | setOverwriteMode(boolean overwriteMode) Configures the behavior when inserting characters.
void | setValueClass(Class valueClass) Sets that class that is used to create new Objects.
Object | stringToValue(String string) Converts the passed in String into an instance of getValueClass by way of the constructor that takes a String argument.
String | valueToString(Object value) Converts the passed in Object into a String by way of the toString method.
Methods inherited from class javax.swing.JFormattedTextField.AbstractFormatter
getActions, getFormattedTextField, invalidEdit, setEditValid, uninstall
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DefaultFormatter

public DefaultFormatter()
Creates a DefaultFormatter.

Method Detail

install

public void install(JFormattedTextField ftf)
Installs the DefaultFormatter onto a particular JFormattedTextField. This will invoke valueToString to convert the current value from the JFormattedTextField to a String. This will then install the Actions from getActions, the DocumentFilter returned from getDocumentFilter and the NavigationFilter returned from getNavigationFilter onto the JFormattedTextField.

Subclasses will typically only need to override this if they wish to install additional listeners on the JFormattedTextField.

If there is a ParseException in converting the current value to a String, this will set the text to an empty String, and mark the JFormattedTextField as being in an invalid state.

While this is a public method, this is typically only useful for subclassers of JFormattedTextField. JFormattedTextField will invoke this method at the appropriate times when the value changes, or its internal state changes.

Overrides:
install in class JFormattedTextField.AbstractFormatter
Parameters:
ftf - JFormattedTextField to format for, may be null indicating uninstall from current JFormattedTextField.

setCommitsOnValidEdit

public void setCommitsOnValidEdit(boolean commit)
Sets when edits are published back to the JFormattedTextField. If true, commitEdit is invoked after every valid edit (any time the text is edited). On the other hand, if this is false than the DefaultFormatter does not publish edits back to the JFormattedTextField. As such, the only time the value of the JFormattedTextField will change is when commitEdit is invoked on JFormattedTextField, typically when enter is pressed or focus leaves the JFormattedTextField.

Parameters:
commit - Used to indicate when edits are commited back to the JTextComponent

getCommitsOnValidEdit

public boolean getCommitsOnValidEdit()
Returns when edits are published back to the JFormattedTextField.

Returns:
true if edits are commited after evey valid edit

setOverwriteMode

public void setOverwriteMode(boolean overwriteMode)
Configures the behavior when inserting characters. If overwriteMode is true (the default), new characters overwrite existing characters in the model.

Parameters:
overwriteMode - Indicates if overwrite or overstrike mode is used

getOverwriteMode

public boolean getOverwriteMode()
Returns the behavior when inserting characters.

Returns:
true if newly inserted characters overwrite existing characters

setAllowsInvalid

public void setAllowsInvalid(boolean allowsInvalid)
Sets whether or not the value being edited is allowed to be invalid for a length of time (that is, stringToValue throws a ParseException). It is often convenient to allow the user to temporarily input an invalid value.

Parameters:
allowsInvalid - Used to indicate if the edited value must always be valid

getAllowsInvalid

public boolean getAllowsInvalid()
Returns whether or not the value being edited is allowed to be invalid for a length of time.

Returns:
false if the edited value must always be valid

setValueClass

public void setValueClass(Class valueClass)
Sets that class that is used to create new Objects. If the passed in class does not have a single argument constructor that takes a String, String values will be used.

Parameters:
valueClass - Class used to construct return value from stringToValue

getValueClass

public Class getValueClass()
Returns that class that is used to create new Objects.

Returns:
Class used to constuct return value from stringToValue

stringToValue

public Object stringToValue(String string)
                     throws ParseException
Converts the passed in String into an instance of getValueClass by way of the constructor that takes a String argument. If getValueClass returns null, the Class of the current value in the JFormattedTextField will be used. If this is null, a String will be returned. If the constructor thows an exception, a ParseException will be thrown. If there is no single argument String constructor, string will be returned.

Specified by:
stringToValue in class JFormattedTextField.AbstractFormatter
Parameters:
string - String to convert
Returns:
Object representation of text
Throws:
ParseException - if there is an error in the conversion

valueToString

public String valueToString(Object value)
                     throws ParseException
Converts the passed in Object into a String by way of the toString method.

Specified by:
valueToString in class JFormattedTextField.AbstractFormatter
Parameters:
value - Value to convert
Returns:
String representation of value
Throws:
ParseException - if there is an error in the conversion

getDocumentFilter

protected DocumentFilter getDocumentFilter()
Returns the DocumentFilter used to restrict the characters that can be input into the JFormattedTextField.

Overrides:
getDocumentFilter in class JFormattedTextField.AbstractFormatter
Returns:
DocumentFilter to restrict edits

getNavigationFilter

protected NavigationFilter getNavigationFilter()
Returns the NavigationFilter used to restrict where the cursor can be placed. characters that can be input into the JFormattedTextField.

Overrides:
getNavigationFilter in class JFormattedTextField.AbstractFormatter
Returns:
NavigationFilter to restrict navigation

clone

public Object clone()
             throws CloneNotSupportedException
Creates a copy of the DefaultFormatter.

Overrides:
clone in class JFormattedTextField.AbstractFormatter
Returns:
copy of the DefaultFormatter
Throws:
CloneNotSupportedException
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DefaultFormatterFactory (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class DefaultFormatterFactory

java.lang.Object
    extended by javax.swing.JFormattedTextField.AbstractFormatterFactory
        extended by javax.swing.text.DefaultFormatterFactory
All Implemented Interfaces:
Serializable
public class DefaultFormatterFactory
extends JFormattedTextField.AbstractFormatterFactory
implements Serializable

An implementation of JFormattedTextField.AbstractFormatterFactory. DefaultFormatterFactory allows specifying a number of different JFormattedTextField.AbstractFormatters that are to be used. The most important one is the default one (setDefaultFormatter). The default formatter will be used if a more specific formatter could not be found. The following process is used to determine the appropriate formatter to use.

  1. Is the passed in value null? Use the null formatter.
  2. Does the JFormattedTextField have focus? Use the edit formatter.
  3. Otherwise, use the display formatter.
  4. If a non-null AbstractFormatter has not been found, use the default formatter.

The following code shows how to configure a JFormattedTextField with two JFormattedTextField.AbstractFormatters, one for display and one for editing.

 JFormattedTextField.AbstractFormatter editFormatter = ...;
 JFormattedTextField.AbstractFormatter displayFormatter = ...;
 DefaultFormatterFactory factory = new DefaultFormatterFactory(
                 displayFormatter, displayFormatter, editFormatter);
 JFormattedTextField tf = new JFormattedTextField(factory);

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Since:
1.4
See Also:
JFormattedTextField

Constructor Summary
DefaultFormatterFactory()
DefaultFormatterFactory(JFormattedTextField.AbstractFormatter defaultFormat)
Creates a DefaultFormatterFactory with the specified JFormattedTextField.AbstractFormatter.
DefaultFormatterFactory(JFormattedTextField.AbstractFormatter defaultFormat, JFormattedTextField.AbstractFormatter displayFormat)
Creates a DefaultFormatterFactory with the specified JFormattedTextField.AbstractFormatters.
DefaultFormatterFactory(JFormattedTextField.AbstractFormatter defaultFormat, JFormattedTextField.AbstractFormatter displayFormat, JFormattedTextField.AbstractFormatter editFormat)
Creates a DefaultFormatterFactory with the specified JFormattedTextField.AbstractFormatters.
DefaultFormatterFactory(JFormattedTextField.AbstractFormatter defaultFormat, JFormattedTextField.AbstractFormatter displayFormat, JFormattedTextField.AbstractFormatter editFormat, JFormattedTextField.AbstractFormatter nullFormat)
Creates a DefaultFormatterFactory with the specified JFormattedTextField.AbstractFormatters.
Method Summary
JFormattedTextField.AbstractFormatter | getDefaultFormatter() Returns the JFormattedTextField.AbstractFormatter to use as a last resort, eg in case a display, edit or null JFormattedTextField.AbstractFormatter has not been specified.
JFormattedTextField.AbstractFormatter | getDisplayFormatter() Returns 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.
JFormattedTextField.AbstractFormatter | getEditFormatter() Returns 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.
JFormattedTextField.AbstractFormatter | getFormatter(JFormattedTextField source) Returns either the default formatter, display formatter, editor formatter or null formatter based on the state of the JFormattedTextField.
JFormattedTextField.AbstractFormatter | getNullFormatter() Returns the formatter to use if the value is null.
void | setDefaultFormatter(JFormattedTextField.AbstractFormatter atf) Sets the JFormattedTextField.AbstractFormatter to use as a last resort, eg in case a display, edit or null JFormattedTextField.AbstractFormatter has not been specified.
void | setDisplayFormatter(JFormattedTextField.AbstractFormatter atf) 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.
void | setEditFormatter(JFormattedTextField.AbstractFormatter atf) Sets the JFormattedTextField.AbstractFormatter to use if the code>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.
void | setNullFormatter(JFormattedTextField.AbstractFormatter atf) Sets the formatter to use if the value of the JFormattedTextField is null.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DefaultFormatterFactory

public DefaultFormatterFactory()

DefaultFormatterFactory

public DefaultFormatterFactory(JFormattedTextField.AbstractFormatter defaultFormat)
Creates a DefaultFormatterFactory with the specified JFormattedTextField.AbstractFormatter.

Parameters:
defaultFormat - JFormattedTextField.AbstractFormatter to be used if a more specific JFormattedTextField.AbstractFormatter can not be found.

DefaultFormatterFactory

public DefaultFormatterFactory(JFormattedTextField.AbstractFormatter defaultFormat,
                               JFormattedTextField.AbstractFormatter displayFormat)
Creates a DefaultFormatterFactory with the specified JFormattedTextField.AbstractFormatters.

Parameters:
defaultFormat - JFormattedTextField.AbstractFormatter to be used if a more specific JFormattedTextField.AbstractFormatter can not be found.
displayFormat - JFormattedTextField.AbstractFormatter to be used when the JFormattedTextField does not have focus.

DefaultFormatterFactory

public DefaultFormatterFactory(JFormattedTextField.AbstractFormatter defaultFormat,
                               JFormattedTextField.AbstractFormatter displayFormat,
                               JFormattedTextField.AbstractFormatter editFormat)
Creates a DefaultFormatterFactory with the specified JFormattedTextField.AbstractFormatters.

Parameters:
defaultFormat - JFormattedTextField.AbstractFormatter to be used if a more specific JFormattedTextField.AbstractFormatter can not be found.
displayFormat - JFormattedTextField.AbstractFormatter to be used when the JFormattedTextField does not have focus.
editFormat - JFormattedTextField.AbstractFormatter to be used when the JFormattedTextField has focus.

DefaultFormatterFactory

public DefaultFormatterFactory(JFormattedTextField.AbstractFormatter defaultFormat,
                               JFormattedTextField.AbstractFormatter displayFormat,
                               JFormattedTextField.AbstractFormatter editFormat,
                               JFormattedTextField.AbstractFormatter nullFormat)
Creates a DefaultFormatterFactory with the specified JFormattedTextField.AbstractFormatters.

Parameters:
defaultFormat - JFormattedTextField.AbstractFormatter to be used if a more specific JFormattedTextField.AbstractFormatter can not be found.
displayFormat - JFormattedTextField.AbstractFormatter to be used when the JFormattedTextField does not have focus.
editFormat - JFormattedTextField.AbstractFormatter to be used when the JFormattedTextField has focus.
nullFormat - JFormattedTextField.AbstractFormatter to be used when the JFormattedTextField has a null value.
Method Detail

setDefaultFormatter

public void setDefaultFormatter(JFormattedTextField.AbstractFormatter atf)
Sets the JFormattedTextField.AbstractFormatter to use as a last resort, eg in case a display, edit or null JFormattedTextField.AbstractFormatter has not been specified.

Parameters:
atf - JFormattedTextField.AbstractFormatter used if a more specific is not specified

getDefaultFormatter

public JFormattedTextField.AbstractFormatter getDefaultFormatter()
Returns the JFormattedTextField.AbstractFormatter to use as a last resort, eg in case a display, edit or null JFormattedTextField.AbstractFormatter has not been specified.

Returns:
JFormattedTextField.AbstractFormatter used if a more specific one is not specified.

setDisplayFormatter

public void setDisplayFormatter(JFormattedTextField.AbstractFormatter atf)
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.

Parameters:
atf - JFormattedTextField.AbstractFormatter to use when the JFormattedTextField does not have focus

getDisplayFormatter

public JFormattedTextField.AbstractFormatter getDisplayFormatter()
Returns 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.

Returns:
JFormattedTextField.AbstractFormatter to use when the JFormattedTextField does not have focus

setEditFormatter

public void setEditFormatter(JFormattedTextField.AbstractFormatter atf)
Sets the JFormattedTextField.AbstractFormatter to use if the code>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.

Parameters:
atf - JFormattedTextField.AbstractFormatter to use when the component has focus

getEditFormatter

public JFormattedTextField.AbstractFormatter getEditFormatter()
Returns 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.

Returns:
JFormattedTextField.AbstractFormatter to use when the component has focus

setNullFormatter

public void setNullFormatter(JFormattedTextField.AbstractFormatter atf)
Sets the formatter to use if the value of the JFormattedTextField is null.

Parameters:
atf - JFormattedTextField.AbstractFormatter to use when the value of the JFormattedTextField is null.

getNullFormatter

public JFormattedTextField.AbstractFormatter getNullFormatter()
Returns the formatter to use if the value is null.

Returns:
JFormattedTextField.AbstractFormatter to use when the value is null

getFormatter

public JFormattedTextField.AbstractFormatter getFormatter(JFormattedTextField source)
Returns either the default formatter, display formatter, editor formatter or null formatter based on the state of the JFormattedTextField.

Specified by:
getFormatter in class JFormattedTextField.AbstractFormatterFactory
Parameters:
source - JFormattedTextField requesting JFormattedTextField.AbstractFormatter
Returns:
JFormattedTextField.AbstractFormatter to handle formatting duties.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DefaultHighlighter (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class DefaultHighlighter

java.lang.Object
    extended by javax.swing.text.LayeredHighlighter
        extended by javax.swing.text.DefaultHighlighter
All Implemented Interfaces:
Highlighter
Direct Known Subclasses:
BasicTextUI.BasicHighlighter
public class DefaultHighlighter
extends LayeredHighlighter

Implements the Highlighter interfaces. Implements a simple highlight painter that renders in a solid color.

See Also:
Highlighter

Nested Class Summary
static class DefaultHighlighter.DefaultHighlightPainter
Simple highlight painter that fills a highlighted area with a solid color.
Nested classes inherited from class javax.swing.text.LayeredHighlighter
LayeredHighlighter.LayerPainter
Nested classes inherited from class javax.swing.text.Highlighter
Highlighter.Highlight, Highlighter.HighlightPainter
Field Summary
static LayeredHighlighter.LayerPainter DefaultPainter
Default implementation of LayeredHighlighter.LayerPainter that can be used for painting highlights.
Constructor Summary
DefaultHighlighter()
Creates a new DefaultHighlighther object.
Method Summary
Object | addHighlight(int p0, int p1, Highlighter.HighlightPainter p) Adds a highlight to the view.
void | changeHighlight(Object tag, int p0, int p1) Changes a highlight.
void | deinstall(JTextComponent c) Called when the UI is being removed from the interface of a JTextComponent.
boolean | getDrawsLayeredHighlights()
Highlighter.Highlight[] | getHighlights() Makes a copy of the highlights.
void | install(JTextComponent c) Called when the UI is being installed into the interface of a JTextComponent.
void | paint(Graphics g) Renders the highlights.
void | paintLayeredHighlights(Graphics g, int p0, int p1, Shape viewBounds, JTextComponent editor, View view) When leaf Views (such as LabelView) are rendering they should call into this method.
void | removeAllHighlights() Removes all highlights.
void | removeHighlight(Object tag) Removes a highlight from the view.
void | setDrawsLayeredHighlights(boolean newValue) If true, highlights are drawn as the Views draw the text.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

DefaultPainter

public static final LayeredHighlighter.LayerPainter DefaultPainter
Default implementation of LayeredHighlighter.LayerPainter that can be used for painting highlights.

As of 1.4 this field is final.

Constructor Detail

DefaultHighlighter

public DefaultHighlighter()
Creates a new DefaultHighlighther object.

Method Detail

paint

public void paint(Graphics g)
Renders the highlights.

Parameters:
g - the graphics context

install

public void install(JTextComponent c)
Called when the UI is being installed into the interface of a JTextComponent. Installs the editor, and removes any existing highlights.

Parameters:
c - the editor component
See Also:
Highlighter.install(javax.swing.text.JTextComponent)

deinstall

public void deinstall(JTextComponent c)
Called when the UI is being removed from the interface of a JTextComponent.

Parameters:
c - the component
See Also:
Highlighter.deinstall(javax.swing.text.JTextComponent)

addHighlight

public Object addHighlight(int p0,
                           int p1,
                           Highlighter.HighlightPainter p)
                    throws BadLocationException
Adds a highlight to the view. Returns a tag that can be used to refer to the highlight.

Parameters:
p0 - the start offset of the range to highlight >= 0
p1 - the end offset of the range to highlight >= p0
p - the painter to use to actually render the highlight
Returns:
an object that can be used as a tag to refer to the highlight
Throws:
BadLocationException - if the specified location is invalid

removeHighlight

public void removeHighlight(Object tag)
Removes a highlight from the view.

Parameters:
tag - the reference to the highlight

removeAllHighlights

public void removeAllHighlights()
Removes all highlights.

changeHighlight

public void changeHighlight(Object tag,
                            int p0,
                            int p1)
                     throws BadLocationException
Changes a highlight.

Parameters:
tag - the highlight tag
p0 - the beginning of the range >= 0
p1 - the end of the range >= p0
Throws:
BadLocationException - if the specified location is invalid

getHighlights

public Highlighter.Highlight[] getHighlights()
Makes a copy of the highlights. Does not actually clone each highlight, but only makes references to them.

Returns:
the copy
See Also:
Highlighter.getHighlights()

paintLayeredHighlights

public void paintLayeredHighlights(Graphics g,
                                   int p0,
                                   int p1,
                                   Shape viewBounds,
                                   JTextComponent editor,
                                   View view)
When leaf Views (such as LabelView) are rendering they should call into this method. If a highlight is in the given region it will be drawn immediately.

Specified by:
paintLayeredHighlights in class LayeredHighlighter
Parameters:
g - Graphics used to draw
p0 - starting offset of view
p1 - ending offset of view
viewBounds - Bounds of View
editor - JTextComponent
view - View instance being rendered

setDrawsLayeredHighlights

public void setDrawsLayeredHighlights(boolean newValue)
If true, highlights are drawn as the Views draw the text. That is the Views will call into paintLayeredHighlight which will result in a rectangle being drawn before the text is drawn (if the offsets are in a highlighted region that is). For this to work the painter supplied must be an instance of LayeredHighlightPainter.

getDrawsLayeredHighlights

public boolean getDrawsLayeredHighlights()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DefaultHighlighter.DefaultHighlightPainter (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class DefaultHighlighter.DefaultHighlightPainter

java.lang.Object
    extended by javax.swing.text.LayeredHighlighter.LayerPainter
        extended by javax.swing.text.DefaultHighlighter.DefaultHighlightPainter
All Implemented Interfaces:
Highlighter.HighlightPainter
Enclosing class:
DefaultHighlighter
public static class DefaultHighlighter.DefaultHighlightPainter
extends LayeredHighlighter.LayerPainter

Simple highlight painter that fills a highlighted area with a solid color.

Constructor Summary
DefaultHighlighter.DefaultHighlightPainter(Color c)
Constructs a new highlight painter.
Method Summary
Color | getColor() Returns the color of the highlight.
void | paint(Graphics g, int offs0, int offs1, Shape bounds, JTextComponent c) Paints a highlight.
Shape | paintLayer(Graphics g, int offs0, int offs1, Shape bounds, JTextComponent c, View view) Paints a portion of a highlight.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DefaultHighlighter.DefaultHighlightPainter

public DefaultHighlighter.DefaultHighlightPainter(Color c)
Constructs a new highlight painter. If c is null, the JTextComponent will be queried for its selection color.

Parameters:
c - the color for the highlight
Method Detail

getColor

public Color getColor()
Returns the color of the highlight.

Returns:
the color

paint

public void paint(Graphics g,
                  int offs0,
                  int offs1,
                  Shape bounds,
                  JTextComponent c)
Paints a highlight.

Parameters:
g - the graphics context
offs0 - the starting model offset >= 0
offs1 - the ending model offset >= offs1
bounds - the bounding box for the highlight
c - the editor

paintLayer

public Shape paintLayer(Graphics g,
                        int offs0,
                        int offs1,
                        Shape bounds,
                        JTextComponent c,
                        View view)
Paints a portion of a highlight.

Specified by:
paintLayer in class LayeredHighlighter.LayerPainter
Parameters:
g - the graphics context
offs0 - the starting model offset >= 0
offs1 - the ending model offset >= offs1
bounds - the bounding box of the view, which is not necessarily the region to paint.
c - the editor
view - View painting for
Returns:
region drawing occured in
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DefaultStyledDocument (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class DefaultStyledDocument

java.lang.Object
    extended by javax.swing.text.AbstractDocument
        extended by javax.swing.text.DefaultStyledDocument
All Implemented Interfaces:
Document, Serializable, StyledDocument
Direct Known Subclasses:
HTMLDocument
public class DefaultStyledDocument
extends AbstractDocument
implements StyledDocument

A document that can be marked up with character and paragraph styles in a manner similar to the Rich Text Format. The element structure for this document represents style crossings for style runs. These style runs are mapped into a paragraph element structure (which may reside in some other structure). The style runs break at paragraph boundaries since logical styles are assigned to paragraph boundaries.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

See Also:
Document, AbstractDocument

Nested Class Summary
static class | DefaultStyledDocument.AttributeUndoableEdit An UndoableEdit used to remember AttributeSet changes to an Element.
class | DefaultStyledDocument.ElementBuffer Class to manage changes to the element hierarchy.
static class | DefaultStyledDocument.ElementSpec Specification for building elements.
protected class | DefaultStyledDocument.SectionElement Default root element for a document...
Nested classes inherited from class javax.swing.text.AbstractDocument
AbstractDocument.AbstractElement, AbstractDocument.AttributeContext, AbstractDocument.BranchElement, AbstractDocument.Content, AbstractDocument.DefaultDocumentEvent, AbstractDocument.ElementEdit, AbstractDocument.LeafElement
Field Summary
protected DefaultStyledDocument.ElementBuffer | buffer
static int | BUFFER_SIZE_DEFAULT The default size of the initial content buffer.
Fields inherited from class javax.swing.text.AbstractDocument
BAD_LOCATION, BidiElementName, ContentElementName, ElementNameAttribute, listenerList, ParagraphElementName, SectionElementName
Fields inherited from interface javax.swing.text.Document
StreamDescriptionProperty, TitleProperty
Constructor Summary
DefaultStyledDocument()
Constructs a default styled document.
DefaultStyledDocument(AbstractDocument.Content c, StyleContext styles)
Constructs a styled document.
DefaultStyledDocument(StyleContext styles)
Constructs a styled document with the default content storage implementation and a shared set of styles.
Method Summary
void | addDocumentListener(DocumentListener listener) Adds a document listener for notification of any changes.
Style | addStyle(String nm, Style parent) Adds a new style into the logical style hierarchy.
protected void | create(DefaultStyledDocument.ElementSpec[] data) Initialize the document to reflect the given element structure (i.e.
protected AbstractDocument.AbstractElement | createDefaultRoot() Creates the root element to be used to represent the default document structure.
Color | getBackground(AttributeSet attr) Gets the background color from an attribute set.
Element | getCharacterElement(int pos) Gets a character element based on a position.
Element | getDefaultRootElement() Gets the default root element.
Font | getFont(AttributeSet attr) Gets the font from an attribute set.
Color | getForeground(AttributeSet attr) Gets the foreground color from an attribute set.
Style | getLogicalStyle(int p) Fetches the logical style assigned to the paragraph represented by the given position.
Element | getParagraphElement(int pos) Gets the paragraph element at the offset pos.
Style | getStyle(String nm) Fetches a named style previously added.
Enumeration | getStyleNames() Fetches the list of of style names.
protected void | insert(int offset, DefaultStyledDocument.ElementSpec[] data) Inserts new elements in bulk.
protected void | insertUpdate(AbstractDocument.DefaultDocumentEvent chng, AttributeSet attr) Updates document structure as a result of text insertion.
void | removeDocumentListener(DocumentListener listener) Removes a document listener.
void | removeStyle(String nm) Removes a named style previously added to the document.
protected void | removeUpdate(AbstractDocument.DefaultDocumentEvent chng) Updates document structure as a result of text removal.
void | setCharacterAttributes(int offset, int length, AttributeSet s, boolean replace) Sets attributes for some part of the document.
void | setLogicalStyle(int pos, Style s) Sets the logical style to use for the paragraph at the given position.
void | setParagraphAttributes(int offset, int length, AttributeSet s, boolean replace) Sets attributes for a paragraph.
protected void | styleChanged(Style style) Called when any of this document's styles have changed.
Methods inherited from class javax.swing.text.AbstractDocument
addUndoableEditListener, createBranchElement, createLeafElement, createPosition, dump, fireChangedUpdate, fireInsertUpdate, fireRemoveUpdate, fireUndoableEditUpdate, getAsynchronousLoadPriority, getAttributeContext, getBidiRootElement, getContent, getCurrentWriter, getDocumentFilter, getDocumentListeners, getDocumentProperties, getEndPosition, getLength, getListeners, getProperty, getRootElements, getStartPosition, getText, getText, getUndoableEditListeners, insertString, postRemoveUpdate, putProperty, readLock, readUnlock, remove, removeUndoableEditListener, render, replace, setAsynchronousLoadPriority, setDocumentFilter, setDocumentProperties, writeLock, writeUnlock
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Methods inherited from interface javax.swing.text.Document
addUndoableEditListener, createPosition, getEndPosition, getLength, getProperty, getRootElements, getStartPosition, getText, getText, insertString, putProperty, remove, removeUndoableEditListener, render

Field Detail

BUFFER_SIZE_DEFAULT

public static final int BUFFER_SIZE_DEFAULT
The default size of the initial content buffer.

See Also:
Constant Field Values

buffer

protected DefaultStyledDocument.ElementBuffer buffer
Constructor Detail

DefaultStyledDocument

public DefaultStyledDocument(AbstractDocument.Content c,
                             StyleContext styles)
Constructs a styled document.

Parameters:
c - the container for the content
styles - resources and style definitions which may be shared across documents

DefaultStyledDocument

public DefaultStyledDocument(StyleContext styles)
Constructs a styled document with the default content storage implementation and a shared set of styles.

Parameters:
styles - the styles

DefaultStyledDocument

public DefaultStyledDocument()
Constructs a default styled document. This buffers input content by a size of BUFFER_SIZE_DEFAULT and has a style context that is scoped by the lifetime of the document and is not shared with other documents.

Method Detail

getDefaultRootElement

public Element getDefaultRootElement()
Gets the default root element.

Specified by:
getDefaultRootElement in interface Document
Specified by:
getDefaultRootElement in class AbstractDocument
Returns:
the root
See Also:
Document.getDefaultRootElement()

create

protected void create(DefaultStyledDocument.ElementSpec[] data)
Initialize the document to reflect the given element structure (i.e. the structure reported by the getDefaultRootElement method. If the document contained any data it will first be removed.

insert

protected void insert(int offset,
                      DefaultStyledDocument.ElementSpec[] data)
               throws BadLocationException
Inserts new elements in bulk. This is useful to allow parsing with the document in an unlocked state and prepare an element structure modification. This method takes an array of tokens that describe how to update an element structure so the time within a write lock can be greatly reduced in an asynchronous update situation.

This method is thread safe, although most Swing methods are not. Please see Threads and Swing for more information.

Parameters:
offset - the starting offset >= 0
data - the element data
Throws:
BadLocationException - for an invalid starting offset

addStyle

public Style addStyle(String nm,
                      Style parent)
Adds a new style into the logical style hierarchy. Style attributes resolve from bottom up so an attribute specified in a child will override an attribute specified in the parent.

Specified by:
addStyle in interface StyledDocument
Parameters:
nm - the name of the style (must be unique within the collection of named styles). The name may be null if the style is unnamed, but the caller is responsible for managing the reference returned as an unnamed style can't be fetched by name. An unnamed style may be useful for things like character attribute overrides such as found in a style run.
parent - the parent style. This may be null if unspecified attributes need not be resolved in some other style.
Returns:
the style

removeStyle

public void removeStyle(String nm)
Removes a named style previously added to the document.

Specified by:
removeStyle in interface StyledDocument
Parameters:
nm - the name of the style to remove

getStyle

public Style getStyle(String nm)
Fetches a named style previously added.

Specified by:
getStyle in interface StyledDocument
Parameters:
nm - the name of the style
Returns:
the style

getStyleNames

public Enumeration getStyleNames()
Fetches the list of of style names.

Returns:
all the style names

setLogicalStyle

public void setLogicalStyle(int pos,
                            Style s)
Sets the logical style to use for the paragraph at the given position. If attributes aren't explicitly set for character and paragraph attributes they will resolve through the logical style assigned to the paragraph, which in turn may resolve through some hierarchy completely independent of the element hierarchy in the document.

This method is thread safe, although most Swing methods are not. Please see Threads and Swing for more information.

Specified by:
setLogicalStyle in interface StyledDocument
Parameters:
pos - the offset from the start of the document >= 0
s - the logical style to assign to the paragraph, null if none

getLogicalStyle

public Style getLogicalStyle(int p)
Fetches the logical style assigned to the paragraph represented by the given position.

Specified by:
getLogicalStyle in interface StyledDocument
Parameters:
p - the location to translate to a paragraph and determine the logical style assigned >= 0. This is an offset from the start of the document.
Returns:
the style, null if none

setCharacterAttributes

public void setCharacterAttributes(int offset,
                                   int length,
                                   AttributeSet s,
                                   boolean replace)
Sets attributes for some part of the document. A write lock is held by this operation while changes are being made, and a DocumentEvent is sent to the listeners after the change has been successfully completed.

This method is thread safe, although most Swing methods are not. Please see Threads and Swing for more information.

Specified by:
setCharacterAttributes in interface StyledDocument
Parameters:
offset - the offset in the document >= 0
length - the length >= 0
s - the attributes
replace - true if the previous attributes should be replaced before setting the new attributes

setParagraphAttributes

public void setParagraphAttributes(int offset,
                                   int length,
                                   AttributeSet s,
                                   boolean replace)
Sets attributes for a paragraph.

This method is thread safe, although most Swing methods are not. Please see Threads and Swing for more information.

Specified by:
setParagraphAttributes in interface StyledDocument
Parameters:
offset - the offset into the paragraph >= 0
length - the number of characters affected >= 0
s - the attributes
replace - whether to replace existing attributes, or merge them

getParagraphElement

public Element getParagraphElement(int pos)
Gets the paragraph element at the offset pos. A paragraph consists of at least one child Element, which is usually a leaf.

Specified by:
getParagraphElement in interface StyledDocument
Specified by:
getParagraphElement in class AbstractDocument
Parameters:
pos - the starting offset >= 0
Returns:
the element

getCharacterElement

public Element getCharacterElement(int pos)
Gets a character element based on a position.

Specified by:
getCharacterElement in interface StyledDocument
Parameters:
pos - the position in the document >= 0
Returns:
the element

insertUpdate

protected void insertUpdate(AbstractDocument.DefaultDocumentEvent chng,
                            AttributeSet attr)
Updates document structure as a result of text insertion. This will happen within a write lock. This implementation simply parses the inserted content for line breaks and builds up a set of instructions for the element buffer.

Overrides:
insertUpdate in class AbstractDocument
Parameters:
chng - a description of the document change
attr - the attributes

removeUpdate

protected void removeUpdate(AbstractDocument.DefaultDocumentEvent chng)
Updates document structure as a result of text removal.

Overrides:
removeUpdate in class AbstractDocument
Parameters:
chng - a description of the document change

createDefaultRoot

protected AbstractDocument.AbstractElement createDefaultRoot()
Creates the root element to be used to represent the default document structure.

Returns:
the element base

getForeground

public Color getForeground(AttributeSet attr)
Gets the foreground color from an attribute set.

Specified by:
getForeground in interface StyledDocument
Parameters:
attr - the attribute set
Returns:
the color

getBackground

public Color getBackground(AttributeSet attr)
Gets the background color from an attribute set.

Specified by:
getBackground in interface StyledDocument
Parameters:
attr - the attribute set
Returns:
the color

getFont

public Font getFont(AttributeSet attr)
Gets the font from an attribute set.

Specified by:
getFont in interface StyledDocument
Parameters:
attr - the attribute set
Returns:
the font

styleChanged

protected void styleChanged(Style style)
Called when any of this document's styles have changed. Subclasses may wish to be intelligent about what gets damaged.

Parameters:
style - The Style that has changed.

addDocumentListener

public void addDocumentListener(DocumentListener listener)
Adds a document listener for notification of any changes.

Specified by:
addDocumentListener in interface Document
Overrides:
addDocumentListener in class AbstractDocument
Parameters:
listener - the listener
See Also:
Document.addDocumentListener(javax.swing.event.DocumentListener)

removeDocumentListener

public void removeDocumentListener(DocumentListener listener)
Removes a document listener.

Specified by:
removeDocumentListener in interface Document
Overrides:
removeDocumentListener in class AbstractDocument
Parameters:
listener - the listener
See Also:
Document.removeDocumentListener(javax.swing.event.DocumentListener)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DefaultStyledDocument.AttributeUndoableEdit (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class DefaultStyledDocument.AttributeUndoableEdit

java.lang.Object
    extended by javax.swing.undo.AbstractUndoableEdit
        extended by javax.swing.text.DefaultStyledDocument.AttributeUndoableEdit
All Implemented Interfaces:
Serializable, UndoableEdit
Enclosing class:
DefaultStyledDocument
public static class DefaultStyledDocument.AttributeUndoableEdit
extends AbstractUndoableEdit

An UndoableEdit used to remember AttributeSet changes to an Element.

Field Summary
protected AttributeSet | copy
protected Element | element
protected boolean | isReplacing
protected AttributeSet | newAttributes
Fields inherited from class javax.swing.undo.AbstractUndoableEdit
RedoName, UndoName
Constructor Summary
DefaultStyledDocument.AttributeUndoableEdit(Element element, AttributeSet newAttributes, boolean isReplacing)
Method Summary
void | redo() Redoes a change.
void | undo() Undoes a change.
Methods inherited from class javax.swing.undo.AbstractUndoableEdit
addEdit, canRedo, canUndo, die, getPresentationName, getRedoPresentationName, getUndoPresentationName, isSignificant, replaceEdit, toString
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

newAttributes

protected AttributeSet newAttributes

copy

protected AttributeSet copy

isReplacing

protected boolean isReplacing

element

protected Element element
Constructor Detail

DefaultStyledDocument.AttributeUndoableEdit

public DefaultStyledDocument.AttributeUndoableEdit(Element element,
                                                   AttributeSet newAttributes,
                                                   boolean isReplacing)
Method Detail

redo

public void redo()
          throws CannotRedoException
Redoes a change.

Specified by:
redo in interface UndoableEdit
Overrides:
redo in class AbstractUndoableEdit
Throws:
CannotRedoException - if the change cannot be redone
See Also:
AbstractUndoableEdit.canRedo()

undo

public void undo()
          throws CannotUndoException
Undoes a change.

Specified by:
undo in interface UndoableEdit
Overrides:
undo in class AbstractUndoableEdit
Throws:
CannotUndoException - if the change cannot be undone
See Also:
AbstractUndoableEdit.canUndo()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DefaultStyledDocument.ElementBuffer (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class DefaultStyledDocument.ElementBuffer

java.lang.Object
    extended by javax.swing.text.DefaultStyledDocument.ElementBuffer
All Implemented Interfaces:
Serializable
Enclosing class:
DefaultStyledDocument
public class DefaultStyledDocument.ElementBuffer
extends Object
implements Serializable

Class to manage changes to the element hierarchy.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Constructor Summary
DefaultStyledDocument.ElementBuffer(Element root)
Creates a new ElementBuffer.
Method Summary
void | change(int offset, int length, AbstractDocument.DefaultDocumentEvent de) Changes content.
protected void | changeUpdate() Updates the element structure in response to a change in the document.
Element | clone(Element parent, Element clonee) Creates a copy of this element, with a different parent.
Element | getRootElement() Gets the root element.
void | insert(int offset, int length, DefaultStyledDocument.ElementSpec[] data, AbstractDocument.DefaultDocumentEvent de) Inserts new content.
protected void | insertUpdate(DefaultStyledDocument.ElementSpec[] data) Inserts an update into the document.
void | remove(int offset, int length, AbstractDocument.DefaultDocumentEvent de) Removes content.
protected void | removeUpdate() Updates the element structure in response to a removal from the associated sequence in the document.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DefaultStyledDocument.ElementBuffer

public DefaultStyledDocument.ElementBuffer(Element root)
Creates a new ElementBuffer.

Parameters:
root - the root element
Method Detail

getRootElement

public Element getRootElement()
Gets the root element.

Returns:
the root element

insert

public void insert(int offset,
                   int length,
                   DefaultStyledDocument.ElementSpec[] data,
                   AbstractDocument.DefaultDocumentEvent de)
Inserts new content.

Parameters:
offset - the starting offset >= 0
length - the length >= 0
data - the data to insert
de - the event capturing this edit

remove

public void remove(int offset,
                   int length,
                   AbstractDocument.DefaultDocumentEvent de)
Removes content.

Parameters:
offset - the starting offset >= 0
length - the length >= 0
de - the event capturing this edit

change

public void change(int offset,
                   int length,
                   AbstractDocument.DefaultDocumentEvent de)
Changes content.

Parameters:
offset - the starting offset >= 0
length - the length >= 0
de - the event capturing this edit

insertUpdate

protected void insertUpdate(DefaultStyledDocument.ElementSpec[] data)
Inserts an update into the document.

Parameters:
data - the elements to insert

removeUpdate

protected void removeUpdate()
Updates the element structure in response to a removal from the associated sequence in the document. Any elements consumed by the span of the removal are removed.

changeUpdate

protected void changeUpdate()
Updates the element structure in response to a change in the document.

clone

public Element clone(Element parent,
                     Element clonee)
Creates a copy of this element, with a different parent.

Parameters:
parent - the parent element
clonee - the element to be cloned
Returns:
the copy
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DefaultStyledDocument.ElementSpec (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class DefaultStyledDocument.ElementSpec

java.lang.Object
    extended by javax.swing.text.DefaultStyledDocument.ElementSpec
Enclosing class:
DefaultStyledDocument
public static class DefaultStyledDocument.ElementSpec
extends Object

Specification for building elements.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Field Summary
static short | ContentType A possible value for getType.
static short | EndTagType A possible value for getType.
static short | JoinFractureDirection A possible value for getDirection.
static short | JoinNextDirection A possible value for getDirection.
static short | JoinPreviousDirection A possible value for getDirection.
static short | OriginateDirection A possible value for getDirection.
static short | StartTagType A possible value for getType.
Constructor Summary
DefaultStyledDocument.ElementSpec(AttributeSet a, short type)
Constructor useful for markup when the markup will not be stored in the document.
DefaultStyledDocument.ElementSpec(AttributeSet a, short type, char[] txt, int offs, int len)
Constructor for creating a spec externally for batch input of content and markup into the document.
DefaultStyledDocument.ElementSpec(AttributeSet a, short type, int len)
Constructor for parsing inside the document when the data has already been added, but len information is needed.
Method Summary
char[] | getArray() Gets the array of characters.
AttributeSet | getAttributes() Gets the element attributes.
short | getDirection() Gets the direction.
int | getLength() Gets the length.
int | getOffset() Gets the starting offset.
short | getType() Gets the element type.
void | setDirection(short direction) Sets the direction.
void | setType(short type) Sets the element type.
String | toString() Converts the element to a string.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

StartTagType

public static final short StartTagType
A possible value for getType. This specifies that this record type is a start tag and represents markup that specifies the start of an element.

See Also:
Constant Field Values

EndTagType

public static final short EndTagType
A possible value for getType. This specifies that this record type is a end tag and represents markup that specifies the end of an element.

See Also:
Constant Field Values

ContentType

public static final short ContentType
A possible value for getType. This specifies that this record type represents content.

See Also:
Constant Field Values

JoinPreviousDirection

public static final short JoinPreviousDirection
A possible value for getDirection. This specifies that the data associated with this record should be joined to what precedes it.

See Also:
Constant Field Values

JoinNextDirection

public static final short JoinNextDirection
A possible value for getDirection. This specifies that the data associated with this record should be joined to what follows it.

See Also:
Constant Field Values

OriginateDirection

public static final short OriginateDirection
A possible value for getDirection. This specifies that the data associated with this record should be used to originate a new element. This would be the normal value.

See Also:
Constant Field Values

JoinFractureDirection

public static final short JoinFractureDirection
A possible value for getDirection. This specifies that the data associated with this record should be joined to the fractured element.

See Also:
Constant Field Values
Constructor Detail

DefaultStyledDocument.ElementSpec

public DefaultStyledDocument.ElementSpec(AttributeSet a,
                                         short type)
Constructor useful for markup when the markup will not be stored in the document.

Parameters:
a - the attributes for the element
type - the type of the element (StartTagType, EndTagType, ContentType)

DefaultStyledDocument.ElementSpec

public DefaultStyledDocument.ElementSpec(AttributeSet a,
                                         short type,
                                         int len)
Constructor for parsing inside the document when the data has already been added, but len information is needed.

Parameters:
a - the attributes for the element
type - the type of the element (StartTagType, EndTagType, ContentType)
len - the length >= 0

DefaultStyledDocument.ElementSpec

public DefaultStyledDocument.ElementSpec(AttributeSet a,
                                         short type,
                                         char[] txt,
                                         int offs,
                                         int len)
Constructor for creating a spec externally for batch input of content and markup into the document.

Parameters:
a - the attributes for the element
type - the type of the element (StartTagType, EndTagType, ContentType)
txt - the text for the element
offs - the offset into the text >= 0
len - the length of the text >= 0
Method Detail

setType

public void setType(short type)
Sets the element type.

Parameters:
type - the type of the element (StartTagType, EndTagType, ContentType)

getType

public short getType()
Gets the element type.

Returns:
the type of the element (StartTagType, EndTagType, ContentType)

setDirection

public void setDirection(short direction)
Sets the direction.

Parameters:
direction - the direction (JoinPreviousDirection, JoinNextDirection)

getDirection

public short getDirection()
Gets the direction.

Returns:
the direction (JoinPreviousDirection, JoinNextDirection)

getAttributes

public AttributeSet getAttributes()
Gets the element attributes.

Returns:
the attribute set

getArray

public char[] getArray()
Gets the array of characters.

Returns:
the array

getOffset

public int getOffset()
Gets the starting offset.

Returns:
the offset >= 0

getLength

public int getLength()
Gets the length.

Returns:
the length >= 0

toString

public String toString()
Converts the element to a string.

Overrides:
toString in class Object
Returns:
the string
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DefaultStyledDocument.SectionElement (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class DefaultStyledDocument.SectionElement

java.lang.Object
    extended by javax.swing.text.AbstractDocument.AbstractElement
        extended by javax.swing.text.AbstractDocument.BranchElement
            extended by javax.swing.text.DefaultStyledDocument.SectionElement
All Implemented Interfaces:
AttributeSet, Element, MutableAttributeSet, Serializable, TreeNode
Enclosing class:
DefaultStyledDocument
protected class DefaultStyledDocument.SectionElement
extends AbstractDocument.BranchElement

Default root element for a document... maps out the paragraphs/lines contained.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Nested Class Summary
Nested classes inherited from class javax.swing.text.AttributeSet
AttributeSet.CharacterAttribute, AttributeSet.ColorAttribute, AttributeSet.FontAttribute, AttributeSet.ParagraphAttribute
Field Summary
Fields inherited from interface javax.swing.text.AttributeSet
NameAttribute, ResolveAttribute
Constructor Summary
DefaultStyledDocument.SectionElement()
Creates a new SectionElement.
Method Summary
 String getName()
Gets the name of the element.
Methods inherited from class javax.swing.text.AbstractDocument.BranchElement
children, getAllowsChildren, getElement, getElementCount, getElementIndex, getEndOffset, getStartOffset, isLeaf, positionToElement, replace, toString
Methods inherited from class javax.swing.text.AbstractDocument.AbstractElement
addAttribute, addAttributes, containsAttribute, containsAttributes, copyAttributes, dump, getAttribute, getAttributeCount, getAttributeNames, getAttributes, getChildAt, getChildCount, getDocument, getIndex, getParent, getParentElement, getResolveParent, isDefined, isEqual, removeAttribute, removeAttributes, removeAttributes, setResolveParent
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

DefaultStyledDocument.SectionElement

public DefaultStyledDocument.SectionElement()
Creates a new SectionElement.

Method Detail

getName

public String getName()
Gets the name of the element.

Specified by:
getName in interface Element
Overrides:
getName in class AbstractDocument.BranchElement
Returns:
the name
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DefaultTextUI (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class DefaultTextUI

java.lang.Object
    extended by javax.swing.plaf.ComponentUI
        extended by javax.swing.plaf.TextUI
            extended by javax.swing.plaf.basic.BasicTextUI
                extended by javax.swing.text.DefaultTextUI
All Implemented Interfaces:
ViewFactory

public abstract class DefaultTextUI
extends BasicTextUI

This class has been deprecated and should no longer be used. The basis of the various TextUI implementations can be found in the javax.swing.plaf.basic package and the class BasicTextUI replaces this class.

Nested Class Summary
Nested classes inherited from class javax.swing.plaf.basic.BasicTextUI
BasicTextUI.BasicCaret, BasicTextUI.BasicHighlighter
Constructor Summary
DefaultTextUI()
Deprecated.
Methods inherited from class javax.swing.plaf.basic.BasicTextUI
create, create, createCaret, createHighlighter, createKeymap, damageRange, damageRange, getComponent, getEditorKit, getKeymapName, getMaximumSize, getMinimumSize, getNextVisualPositionFrom, getPreferredSize, getPropertyPrefix, getRootView, getToolTipText, getVisibleEditorRect, installDefaults, installKeyboardActions, installListeners, installUI, modelChanged, modelToView, modelToView, paint, paintBackground, paintSafely, propertyChange, setView, uninstallDefaults, uninstallKeyboardActions, uninstallListeners, uninstallUI, update, viewToModel, viewToModel
Methods inherited from class javax.swing.plaf.ComponentUI
contains, createUI, getAccessibleChild, getAccessibleChildrenCount
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DefaultTextUI

public DefaultTextUI()
Deprecated.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Document (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Interface Document

All Known Subinterfaces:
StyledDocument
All Known Implementing Classes:
AbstractDocument, DefaultStyledDocument
public interface Document

The Document is a container for text that serves as the model for swing text components. The goal for this interface is to scale from very simple needs (a plain text textfield) to complex needs (an HTML or XML document, for example).

Content

At the simplest level, text can be modeled as a linear sequence of characters. To support internationalization, the Swing text model uses unicode characters. The sequence of characters displayed in a text component is generally referred to as the component's content.

To refer to locations within the sequence, the coordinates used are the location between two characters. As the diagram below shows, a location in a text document can be referred to as a position, or an offset. This position is zero-based.

The following text describes this graphic.

In the example, if the content of a document is the sequence "The quick brown fox," as shown in the preceding diagram, the location just before the word "The" is 0, and the location after the word "The" and before the whitespace that follows it is 3. The entire sequence of characters in the sequence "The" is called a range.

The following methods give access to the character data that makes up the content.

  • getLength()
  • getText(int, int)
  • getText(int, int, Segment)

Structure

Text is rarely represented simply as featureless content. Rather, text typically has some sort of structure associated with it. Exactly what structure is modeled is up to a particular Document implementation. It might be as simple as no structure (i.e. a simple text field), or it might be something like diagram below.

Diagram shows Book->Chapter->Paragraph

The unit of structure (i.e. a node of the tree) is referred to by the Element interface. Each Element can be tagged with a set of attributes. These attributes (name/value pairs) are defined by the AttributeSet interface.

The following methods give access to the document structure.

  • getDefaultRootElement
  • getRootElements

Mutations

All documents need to be able to add and remove simple text. Typically, text is inserted and removed via gestures from a keyboard or a mouse. What effect the insertion or removal has upon the document structure is entirely up to the implementation of the document.

The following methods are related to mutation of the document content:

  • insertString(int, String, AttributeSet)
  • remove(int, int)
  • createPosition(int)

Notification

Mutations to the Document must be communicated to interested observers. The notification of change follows the event model guidelines that are specified for JavaBeans. In the JavaBeans event model, once an event notification is dispatched, all listeners must be notified before any further mutations occur to the source of the event. Further, order of delivery is not guaranteed.

Notification is provided as two separate events, DocumentEvent, and UndoableEditEvent. If a mutation is made to a Document through its api, a DocumentEvent will be sent to all of the registered DocumentListeners. If the Document implementation supports undo/redo capabilities, an UndoableEditEvent will be sent to all of the registered UndoableEditListeners. If an undoable edit is undone, a DocumentEvent should be fired from the Document to indicate it has changed again. In this case however, there should be no UndoableEditEvent generated since that edit is actually the source of the change rather than a mutation to the Document made through its api.

The preceeding text describes this graphic.

Referring to the above diagram, suppose that the component shown on the left mutates the document object represented by the blue rectangle. The document responds by dispatching a DocumentEvent to both component views and sends an UndoableEditEvent to the listening logic, which maintains a history buffer.

Now suppose that the component shown on the right mutates the same document. Again, the document dispatches a DocumentEvent to both component views and sends an UndoableEditEvent to the listening logic that is maintaining the history buffer.

If the history buffer is then rolled back (i.e. the last UndoableEdit undone), a DocumentEvent is sent to both views, causing both of them to reflect the undone mutation to the document (that is, the removal of the right component's mutation). If the history buffer again rolls back another change, another DocumentEvent is sent to both views, causing them to reflect the undone mutation to the document -- that is, the removal of the left component's mutation.

The methods related to observing mutations to the document are:

  • addDocumentListener(DocumentListener)
  • removeDocumentListener(DocumentListener)
  • addUndoableEditListener(UndoableEditListener)
  • removeUndoableEditListener(UndoableEditListener)

Properties

Document implementations will generally have some set of properties associated with them at runtime. Two well known properties are the StreamDescriptionProperty, which can be used to describe where the Document came from, and the TitleProperty, which can be used to name the Document. The methods related to the properties are:

  • getProperty(Object)
  • putProperty(Object, Object)

For more information on the Document class, see The Swing Connection and most particularly the article, The Element Interface.

See Also:
DocumentEvent, DocumentListener, UndoableEditEvent, UndoableEditListener, Element, Position, AttributeSet

Field Summary
static String | StreamDescriptionProperty The property name for the description of the stream used to initialize the document.
static String | TitleProperty The property name for the title of the document, if there is one.
Method Summary
void | addDocumentListener(DocumentListener listener) Registers the given observer to begin receiving notifications when changes are made to the document.
void | addUndoableEditListener(UndoableEditListener listener) Registers the given observer to begin receiving notifications when undoable edits are made to the document.
Position | createPosition(int offs) This method allows an application to mark a place in a sequence of character content.
Element | getDefaultRootElement() Returns the root element that views should be based upon, unless some other mechanism for assigning views to element structures is provided.
Position | getEndPosition() Returns a position that represents the end of the document.
int | getLength() Returns number of characters of content currently in the document.
Object | getProperty(Object key) Gets the properties associated with the document.
Element[] | getRootElements() Returns all of the root elements that are defined.
Position | getStartPosition() Returns a position that represents the start of the document.
String | getText(int offset, int length) Fetches the text contained within the given portion of the document.
void | getText(int offset, int length, Segment txt) Fetches the text contained within the given portion of the document.
void | insertString(int offset, String str, AttributeSet a) Inserts a string of content.
void | putProperty(Object key, Object value) Associates a property with the document.
void | remove(int offs, int len) Removes a portion of the content of the document.
void | removeDocumentListener(DocumentListener listener) Unregisters the given observer from the notification list so it will no longer receive change updates.
void | removeUndoableEditListener(UndoableEditListener listener) Unregisters the given observer from the notification list so it will no longer receive updates.
void | render(Runnable r) This allows the model to be safely rendered in the presence of currency, if the model supports being updated asynchronously.

Field Detail

StreamDescriptionProperty

public static final String StreamDescriptionProperty
The property name for the description of the stream used to initialize the document. This should be used if the document was initialized from a stream and anything is known about the stream.

See Also:
Constant Field Values

TitleProperty

public static final String TitleProperty
The property name for the title of the document, if there is one.

See Also:
Constant Field Values
Method Detail

getLength

public int getLength()
Returns number of characters of content currently in the document.

Returns:
number of characters >= 0

addDocumentListener

public void addDocumentListener(DocumentListener listener)
Registers the given observer to begin receiving notifications when changes are made to the document.

Parameters:
listener - the observer to register
See Also:
removeDocumentListener(javax.swing.event.DocumentListener)

removeDocumentListener

public void removeDocumentListener(DocumentListener listener)
Unregisters the given observer from the notification list so it will no longer receive change updates.

Parameters:
listener - the observer to register
See Also:
addDocumentListener(javax.swing.event.DocumentListener)

addUndoableEditListener

public void addUndoableEditListener(UndoableEditListener listener)
Registers the given observer to begin receiving notifications when undoable edits are made to the document.

Parameters:
listener - the observer to register
See Also:
UndoableEditEvent

removeUndoableEditListener

public void removeUndoableEditListener(UndoableEditListener listener)
Unregisters the given observer from the notification list so it will no longer receive updates.

Parameters:
listener - the observer to register
See Also:
UndoableEditEvent

getProperty

public Object getProperty(Object key)
Gets the properties associated with the document.

Parameters:
key - a non-null property key
Returns:
the properties
See Also:
putProperty(Object, Object)

putProperty

public void putProperty(Object key,
                        Object value)
Associates a property with the document. Two standard property keys provided are: StreamDescriptionProperty and TitleProperty. Other properties, such as author, may also be defined.

Parameters:
key - the non-null property key
value - the property value
See Also:
getProperty(Object)

remove

public void remove(int offs,
                   int len)
            throws BadLocationException
Removes a portion of the content of the document. This will cause a DocumentEvent of type DocumentEvent.EventType.REMOVE to be sent to the registered DocumentListeners, unless an exception is thrown. The notification will be sent to the listeners by calling the removeUpdate method on the DocumentListeners.

To ensure reasonable behavior in the face of concurrency, the event is dispatched after the mutation has occurred. This means that by the time a notification of removal is dispatched, the document has already been updated and any marks created by createPosition have already changed. For a removal, the end of the removal range is collapsed down to the start of the range, and any marks in the removal range are collapsed down to the start of the range.

Diagram shows removal of 'quick' from 'The quick brown fox.'

If the Document structure changed as result of the removal, the details of what Elements were inserted and removed in response to the change will also be contained in the generated DocumentEvent. It is up to the implementation of a Document to decide how the structure should change in response to a remove.

If the Document supports undo/redo, an UndoableEditEvent will also be generated.

Parameters:
offs - the offset from the beginning >= 0
len - the number of characters to remove >= 0
Throws:
BadLocationException - some portion of the removal range was not a valid part of the document. The location in the exception is the first bad position encountered.
See Also:
DocumentEvent, DocumentListener, UndoableEditEvent, UndoableEditListener

insertString

public void insertString(int offset,
                         String str,
                         AttributeSet a)
                  throws BadLocationException
Inserts a string of content. This will cause a DocumentEvent of type DocumentEvent.EventType.INSERT to be sent to the registered DocumentListers, unless an exception is thrown. The DocumentEvent will be delivered by calling the insertUpdate method on the DocumentListener. The offset and length of the generated DocumentEvent will indicate what change was actually made to the Document.

Diagram shows insertion of 'quick' in 'The quick brown fox'

If the Document structure changed as result of the insertion, the details of what Elements were inserted and removed in response to the change will also be contained in the generated DocumentEvent. It is up to the implementation of a Document to decide how the structure should change in response to an insertion.

If the Document supports undo/redo, an UndoableEditEvent will also be generated.

Parameters:
offset - the offset into the document to insert the content >= 0. All positions that track change at or after the given location will move.
str - the string to insert
a - the attributes to associate with the inserted content. This may be null if there are no attributes.
Throws:
BadLocationException - the given insert position is not a valid position within the document
See Also:
DocumentEvent, DocumentListener, UndoableEditEvent, UndoableEditListener

getText

public String getText(int offset,
                      int length)
               throws BadLocationException
Fetches the text contained within the given portion of the document.

Parameters:
offset - the offset into the document representing the desired start of the text >= 0
length - the length of the desired string >= 0
Returns:
the text, in a String of length >= 0
Throws:
BadLocationException - some portion of the given range was not a valid part of the document. The location in the exception is the first bad position encountered.

getText

public void getText(int offset,
                    int length,
                    Segment txt)
             throws BadLocationException
Fetches the text contained within the given portion of the document.

If the partialReturn property on the txt parameter is false, the data returned in the Segment will be the entire length requested and may or may not be a copy depending upon how the data was stored. If the partialReturn property is true, only the amount of text that can be returned without creating a copy is returned. Using partial returns will give better performance for situations where large parts of the document are being scanned. The following is an example of using the partial return to access the entire document:

   int nleft = doc.getDocumentLength();
   Segment text = new Segment();
   int offs = 0;
   text.setPartialReturn(true);
   while (nleft > 0) {
       doc.getText(offs, nleft, text);
       // do someting with text
       nleft -= text.count;
       offs += text.count;
   }

Parameters:
offset - the offset into the document representing the desired start of the text >= 0
length - the length of the desired string >= 0
txt - the Segment object to return the text in
Throws:
BadLocationException - Some portion of the given range was not a valid part of the document. The location in the exception is the first bad position encountered.

getStartPosition

public Position getStartPosition()
Returns a position that represents the start of the document. The position returned can be counted on to track change and stay located at the beginning of the document.

Returns:
the position

getEndPosition

public Position getEndPosition()
Returns a position that represents the end of the document. The position returned can be counted on to track change and stay located at the end of the document.

Returns:
the position

createPosition

public Position createPosition(int offs)
                        throws BadLocationException
This method allows an application to mark a place in a sequence of character content. This mark can then be used to tracks change as insertions and removals are made in the content. The policy is that insertions always occur prior to the current position (the most common case) unless the insertion location is zero, in which case the insertion is forced to a position that follows the original position.

Parameters:
offs - the offset from the start of the document >= 0
Returns:
the position
Throws:
BadLocationException - if the given position does not represent a valid location in the associated document

getRootElements

public Element[] getRootElements()
Returns all of the root elements that are defined.

Typically there will be only one document structure, but the interface supports building an arbitrary number of structural projections over the text data. The document can have multiple root elements to support multiple document structures. Some examples might be:

  • Text direction.
  • Lexical token streams.
  • Parse trees.
  • Conversions to formats other than the native format.
  • Modification specifications.
  • Annotations.

Returns:
the root element

getDefaultRootElement

public Element getDefaultRootElement()
Returns the root element that views should be based upon, unless some other mechanism for assigning views to element structures is provided.

Returns:
the root element

render

public void render(Runnable r)
This allows the model to be safely rendered in the presence of currency, if the model supports being updated asynchronously. The given runnable will be executed in a way that allows it to safely read the model with no changes while the runnable is being executed. The runnable itself may not make any mutations.

Parameters:
r - a Runnable used to render the model
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DocumentFilter (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class DocumentFilter

java.lang.Object
    extended by javax.swing.text.DocumentFilter
public class DocumentFilter
extends Object

DocumentFilter, as the name implies, is a filter for the Document mutation methods. When a Document containing a DocumentFilter is modified (either through insert or remove), it forwards the appropriate method invocation to the DocumentFilter. The default implementation allows the modification to occur. Subclasses can filter the modifications by conditionally invoking methods on the superclass, or invoking the necessary methods on the passed in FilterBypass. Subclasses should NOT call back into the Document for the modification instead call into the superclass or the FilterBypass.

When remove or insertString is invoked on the DocumentFilter, the DocumentFilter may callback into the FilterBypass multiple times, or for different regions, but it should not callback into the FilterBypass after returning from the remove or insertString method.

Since:
1.4
See Also:
Document

Nested Class Summary
static class DocumentFilter.FilterBypass
Used as a way to circumvent calling back into the Document to change it.
Constructor Summary
DocumentFilter()
Method Summary
void | insertString(DocumentFilter.FilterBypass fb, int offset, String string, AttributeSet attr) Invoked prior to insertion of text into the specified Document.
void | remove(DocumentFilter.FilterBypass fb, int offset, int length) Invoked prior to removal of the specified region in the specified Document.
void | replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) Invoked prior to replacing a region of text in the specified Document.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DocumentFilter

public DocumentFilter()
Method Detail

remove

public void remove(DocumentFilter.FilterBypass fb,
                   int offset,
                   int length)
            throws BadLocationException
Invoked prior to removal of the specified region in the specified Document. Subclasses that want to conditionally allow removal should override this and only call supers implementation as necessary, or call directly into the FilterBypass as necessary.

Parameters:
fb - FilterBypass that can be used to mutate Document
offset - the offset from the beginning >= 0
length - the number of characters to remove >= 0
Throws:
BadLocationException - some portion of the removal range was not a valid part of the document. The location in the exception is the first bad position encountered.

insertString

public void insertString(DocumentFilter.FilterBypass fb,
                         int offset,
                         String string,
                         AttributeSet attr)
                  throws BadLocationException
Invoked prior to insertion of text into the specified Document. Subclasses that want to conditionally allow insertion should override this and only call supers implementation as necessary, or call directly into the FilterBypass.

Parameters:
fb - FilterBypass that can be used to mutate Document
offset - the offset into the document to insert the content >= 0. All positions that track change at or after the given location will move.
string - the string to insert
attr - the attributes to associate with the inserted content. This may be null if there are no attributes.
Throws:
BadLocationException - the given insert position is not a valid position within the document

replace

public void replace(DocumentFilter.FilterBypass fb,
                    int offset,
                    int length,
                    String text,
                    AttributeSet attrs)
             throws BadLocationException
Invoked prior to replacing a region of text in the specified Document. Subclasses that want to conditionally allow replace should override this and only call supers implementation as necessary, or call directly into the FilterBypass.

Parameters:
fb - FilterBypass that can be used to mutate Document
offset - Location in Document
length - Length of text to delete
text - Text to insert, null indicates no text to insert
attrs - AttributeSet indicating attributes of inserted text, null is legal.
Throws:
BadLocationException - the given insert position is not a valid position within the document
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DocumentFilter.FilterBypass (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class DocumentFilter.FilterBypass

java.lang.Object
    extended by javax.swing.text.DocumentFilter.FilterBypass
Enclosing class:
DocumentFilter
public abstract static class DocumentFilter.FilterBypass
extends Object

Used as a way to circumvent calling back into the Document to change it. Document implementations that wish to support a DocumentFilter must provide an implementation that will not callback into the DocumentFilter when the following methods are invoked from the DocumentFilter.

Constructor Summary
DocumentFilter.FilterBypass()
Method Summary
abstract Document | getDocument() Returns the Document the mutation is occuring on.
abstract void | insertString(int offset, String string, AttributeSet attr) Inserts the specified text, bypassing the DocumentFilter.
abstract void | remove(int offset, int length) Removes the specified region of text, bypassing the DocumentFilter.
abstract void | replace(int offset, int length, String string, AttributeSet attrs) Deletes the region of text from offset to offset + length, and replaces it with text.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DocumentFilter.FilterBypass

public DocumentFilter.FilterBypass()
Method Detail

getDocument

public abstract Document getDocument()
Returns the Document the mutation is occuring on.

Returns:
Document that remove/insertString will operate on

remove

public abstract void remove(int offset,
                            int length)
                     throws BadLocationException
Removes the specified region of text, bypassing the DocumentFilter.

Parameters:
offset - the offset from the beginning >= 0
length - the number of characters to remove >= 0
Throws:
BadLocationException - some portion of the removal range was not a valid part of the document. The location in the exception is the first bad position encountered.

insertString

public abstract void insertString(int offset,
                                  String string,
                                  AttributeSet attr)
                           throws BadLocationException
Inserts the specified text, bypassing the DocumentFilter.

Parameters:
offset - the offset into the document to insert the content >= 0. All positions that track change at or after the given location will move.
string - the string to insert
attr - the attributes to associate with the inserted content. This may be null if there are no attributes.
Throws:
BadLocationException - the given insert position is not a valid position within the document

replace

public abstract void replace(int offset,
                             int length,
                             String string,
                             AttributeSet attrs)
                      throws BadLocationException
Deletes the region of text from offset to offset + length, and replaces it with text.

Parameters:
offset - Location in Document
length - Length of text to delete
string - Text to insert, null indicates no text to insert
attrs - AttributeSet indicating attributes of inserted text, null is legal.
Throws:
BadLocationException - the given insert is not a valid position within the document
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


EditorKit (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class EditorKit

java.lang.Object
    extended by javax.swing.text.EditorKit
All Implemented Interfaces:
Cloneable, Serializable
Direct Known Subclasses:
DefaultEditorKit
public abstract class EditorKit
extends Object
implements Cloneable, Serializable

Establishes the set of things needed by a text component to be a reasonably functioning editor for some type of text content. The EditorKit acts as a factory for some kind of policy. For example, an implementation of html and rtf can be provided that is replaceable with other implementations.

A kit can safely store editing state as an instance of the kit will be dedicated to a text component. New kits will normally be created by cloning a prototype kit. The kit will have it's setComponent method called to establish it's relationship with a JTextComponent.

Constructor Summary
EditorKit()
Construct an EditorKit.
Method Summary
Object | clone() Creates a copy of the editor kit.
abstract Caret | createCaret() Fetches a caret that can navigate through views produced by the associated ViewFactory.
abstract Document | createDefaultDocument() Creates an uninitialized text storage model that is appropriate for this type of editor.
void | deinstall(JEditorPane c) Called when the kit is being removed from the JEditorPane.
abstract Action[] | getActions() Fetches the set of commands that can be used on a text component that is using a model and view produced by this kit.
abstract String | getContentType() Gets the MIME type of the data that this kit represents support for.
abstract ViewFactory | getViewFactory() Fetches a factory that is suitable for producing views of any models that are produced by this kit.
void | install(JEditorPane c) Called when the kit is being installed into the a JEditorPane.
abstract void | read(InputStream in, Document doc, int pos) Inserts content from the given stream which is expected to be in a format appropriate for this kind of content handler.
abstract void | read(Reader in, Document doc, int pos) Inserts content from the given stream which is expected to be in a format appropriate for this kind of content handler.
abstract void | write(OutputStream out, Document doc, int pos, int len) Writes content from a document to the given stream in a format appropriate for this kind of content handler.
abstract void | write(Writer out, Document doc, int pos, int len) Writes content from a document to the given stream in a format appropriate for this kind of content handler.
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

EditorKit

public EditorKit()
Construct an EditorKit.

Method Detail

clone

public Object clone()
Creates a copy of the editor kit. This is implemented to use Object.clone. If the kit cannot be cloned, null is returned.

Overrides:
clone in class Object
Returns:
the copy
See Also:
Cloneable

install

public void install(JEditorPane c)
Called when the kit is being installed into the a JEditorPane.

Parameters:
c - the JEditorPane

deinstall

public void deinstall(JEditorPane c)
Called when the kit is being removed from the JEditorPane. This is used to unregister any listeners that were attached.

Parameters:
c - the JEditorPane

getContentType

public abstract String getContentType()
Gets the MIME type of the data that this kit represents support for.

Returns:
the type

getViewFactory

public abstract ViewFactory getViewFactory()
Fetches a factory that is suitable for producing views of any models that are produced by this kit.

Returns:
the factory

getActions

public abstract Action[] getActions()
Fetches the set of commands that can be used on a text component that is using a model and view produced by this kit.

Returns:
the set of actions

createCaret

public abstract Caret createCaret()
Fetches a caret that can navigate through views produced by the associated ViewFactory.

Returns:
the caret

createDefaultDocument

public abstract Document createDefaultDocument()
Creates an uninitialized text storage model that is appropriate for this type of editor.

Returns:
the model

read

public abstract void read(InputStream in,
                          Document doc,
                          int pos)
                   throws IOException,
                          BadLocationException
Inserts content from the given stream which is expected to be in a format appropriate for this kind of content handler.

Parameters:
in - The stream to read from
doc - The destination for the insertion.
pos - The location in the document to place the content >= 0.
Throws:
IOException - on any I/O error
BadLocationException - if pos represents an invalid location within the document.

write

public abstract void write(OutputStream out,
                           Document doc,
                           int pos,
                           int len)
                    throws IOException,
                           BadLocationException
Writes content from a document to the given stream in a format appropriate for this kind of content handler.

Parameters:
out - The stream to write to
doc - The source for the write.
pos - The location in the document to fetch the content from >= 0.
len - The amount to write out >= 0.
Throws:
IOException - on any I/O error
BadLocationException - if pos represents an invalid location within the document.

read

public abstract void read(Reader in,
                          Document doc,
                          int pos)
                   throws IOException,
                          BadLocationException
Inserts content from the given stream which is expected to be in a format appropriate for this kind of content handler.

Since actual text editing is unicode based, this would generally be the preferred way to read in the data. Some types of content are stored in an 8-bit form however, and will favor the InputStream.

Parameters:
in - The stream to read from
doc - The destination for the insertion.
pos - The location in the document to place the content >= 0.
Throws:
IOException - on any I/O error
BadLocationException - if pos represents an invalid location within the document.

write

public abstract void write(Writer out,
                           Document doc,
                           int pos,
                           int len)
                    throws IOException,
                           BadLocationException
Writes content from a document to the given stream in a format appropriate for this kind of content handler.

Since actual text editing is unicode based, this would generally be the preferred way to write the data. Some types of content are stored in an 8-bit form however, and will favor the OutputStream.

Parameters:
out - The stream to write to
doc - The source for the write.
pos - The location in the document to fetch the content >= 0.
len - The amount to write out >= 0.
Throws:
IOException - on any I/O error
BadLocationException - if pos represents an invalid location within the document.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Element (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Interface Element

All Known Implementing Classes:
AbstractDocument.AbstractElement
public interface Element

Interface to describe a structural piece of a document. It is intended to capture the spirit of an SGML element.

Method Summary
AttributeSet | getAttributes() Fetches the collection of attributes this element contains.
Document | getDocument() Fetches the document associated with this element.
Element | getElement(int index) Fetches the child element at the given index.
int | getElementCount() Gets the number of child elements contained by this element.
int | getElementIndex(int offset) Gets the child element index closest to the given offset.
int | getEndOffset() Fetches the offset from the beginning of the document that this element ends at.
String | getName() Fetches the name of the element.
Element | getParentElement() Fetches the parent element.
int | getStartOffset() Fetches the offset from the beginning of the document that this element begins at.
boolean | isLeaf() Is this element a leaf element? An element that may have children, even if it currently has no children, would return false.

Method Detail

getDocument

public Document getDocument()
Fetches the document associated with this element.

Returns:
the document

getParentElement

public Element getParentElement()
Fetches the parent element. If the element is a root level element returns null.

Returns:
the parent element

getName

public String getName()
Fetches the name of the element. If the element is used to represent some type of structure, this would be the type name.

Returns:
the element name

getAttributes

public AttributeSet getAttributes()
Fetches the collection of attributes this element contains.

Returns:
the attributes for the element

getStartOffset

public int getStartOffset()
Fetches the offset from the beginning of the document that this element begins at. If this element has children, this will be the offset of the first child. As a document position, there is an implied forward bias.

Returns:
the starting offset >= 0 and < getEndOffset();
See Also:
Document, AbstractDocument

getEndOffset

public int getEndOffset()
Fetches the offset from the beginning of the document that this element ends at. If this element has children, this will be the end offset of the last child. As a document position, there is an implied backward bias.

All the default Document implementations descend from AbstractDocument. AbstractDocument models an implied break at the end of the document. As a result of this, it is possible for this to return a value greater than the length of the document.

Returns:
the ending offset > getStartOffset() and <= getDocument().getLength() + 1
See Also:
Document, AbstractDocument

getElementIndex

public int getElementIndex(int offset)
Gets the child element index closest to the given offset. The offset is specified relative to the beginning of the document. Returns -1 if the Element is a leaf, otherwise returns the index of the Element that best represents the given location. Returns 0 if the location is less than the start offset. Returns getElementCount() - 1 if the location is greater than or equal to the end offset.

Parameters:
offset - the specified offset >= 0
Returns:
the element index >= 0

getElementCount

public int getElementCount()
Gets the number of child elements contained by this element. If this element is a leaf, a count of zero is returned.

Returns:
the number of child elements >= 0

getElement

public Element getElement(int index)
Fetches the child element at the given index.

Parameters:
index - the specified index >= 0
Returns:
the child element

isLeaf

public boolean isLeaf()
Is this element a leaf element? An element that may have children, even if it currently has no children, would return false.

Returns:
true if a leaf element else false
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ElementIterator (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class ElementIterator

java.lang.Object
    extended by javax.swing.text.ElementIterator
All Implemented Interfaces:
Cloneable
public class ElementIterator
extends Object
implements Cloneable

ElementIterator, as the name suggests, iteratates over the Element tree. The constructor can be invoked with either Document or an Element as an argument. If the constructor is invoked with a Document as an argument then the root of the iteration is the return value of document.getDefaultRootElement(). The iteration happens in a depth-first manner. In terms of how boundary conditions are handled: a) if next() is called before first() or current(), the root will be returned. b) next() returns null to indicate the end of the list. c) previous() returns null when the current element is the root or next() has returned null. The ElementIterator does no locking of the Element tree. This means that it does not track any changes. It is the responsibility of the user of this class, to ensure that no changes happen during element iteration. Simple usage example: public void iterate() { ElementIterator it = new ElementIterator(root); Element elem; while (true) { if ((elem = next()) != null) { // process element System.out.println("elem: " + elem.getName()); } else { break; } } }

Constructor Summary
ElementIterator(Document document)
Creates a new ElementIterator.
ElementIterator(Element root)
Creates a new ElementIterator.
Method Summary
Object | clone() Clones the ElementIterator.
Element | current() Fetches the current Element.
int | depth() Fetches the current depth of element tree.
Element | first() Fetches the first element.
Element | next() Fetches the next Element.
Element | previous() Fetches the previous Element.
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ElementIterator

public ElementIterator(Document document)
Creates a new ElementIterator. The root element is taken to get the default root element of the document.

Parameters:
document - a Document.

ElementIterator

public ElementIterator(Element root)
Creates a new ElementIterator.

Parameters:
root - the root Element.
Method Detail

clone

public Object clone()
Clones the ElementIterator.

Overrides:
clone in class Object
Returns:
a cloned ElementIterator Object.
See Also:
Cloneable

first

public Element first()
Fetches the first element.

Returns:
an Element.

depth

public int depth()
Fetches the current depth of element tree.

Returns:
the depth.

current

public Element current()
Fetches the current Element.

Returns:
element on top of the stack or null if the root element is null

next

public Element next()
Fetches the next Element. The strategy used to locate the next element is a depth-first search.

Returns:
the next element or null at the end of the list.

previous

public Element previous()
Fetches the previous Element. If howver the current element is the last element, or the current element is null, then null is returned.

Returns:
previous Element if available
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


FieldView (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class FieldView

java.lang.Object
    extended by javax.swing.text.View
        extended by javax.swing.text.PlainView
            extended by javax.swing.text.FieldView
All Implemented Interfaces:
SwingConstants, TabExpander
Direct Known Subclasses:
PasswordView
public class FieldView
extends PlainView

Extends the multi-line plain text view to be suitable for a single-line editor view. If the view is allocated extra space, the field must adjust for it. If the hosting component is a JTextField, this view will manage the ranges of the associated BoundedRangeModel and will adjust the horizontal allocation to match the current visibility settings of the JTextField.

See Also:
View

Field Summary
Fields inherited from class javax.swing.text.PlainView
metrics
Fields inherited from class javax.swing.text.View
BadBreakWeight, ExcellentBreakWeight, ForcedBreakWeight, GoodBreakWeight, X_AXIS, Y_AXIS
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
Constructor Summary
FieldView(Element elem)
Constructs a new FieldView wrapped on an element.
Method Summary
protected Shape | adjustAllocation(Shape a) Adjusts the allocation given to the view to be a suitable allocation for a text field.
protected FontMetrics | getFontMetrics() Fetches the font metrics associated with the component hosting this view.
float | getPreferredSpan(int axis) Determines the preferred span for this view along an axis.
int | getResizeWeight(int axis) Determines the resizability of the view along the given axis.
void | insertUpdate(DocumentEvent changes, Shape a, ViewFactory f) Gives notification that something was inserted into the document in a location that this view is responsible for.
Shape | modelToView(int pos, Shape a, Position.Bias b) Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
void | paint(Graphics g, Shape a) Renders using the given rendering surface and area on that surface.
void | removeUpdate(DocumentEvent changes, Shape a, ViewFactory f) Gives notification that something was removed from the document in a location that this view is responsible for.
int | viewToModel(float fx, float fy, Shape a, Position.Bias[] bias) Provides a mapping from the view coordinate space to the logical coordinate space of the model.
Methods inherited from class javax.swing.text.PlainView
changedUpdate, damageLineRange, drawLine, drawSelectedText, drawUnselectedText, getLineBuffer, getTabSize, lineToRect, nextTabStop, setSize, updateDamage, updateMetrics
Methods inherited from class javax.swing.text.View
append, breakView, createFragment, forwardUpdate, forwardUpdateToView, getAlignment, getAttributes, getBreakWeight, getChildAllocation, getContainer, getDocument, getElement, getEndOffset, getGraphics, getMaximumSpan, getMinimumSpan, getNextVisualPositionFrom, getParent, getStartOffset, getToolTipText, getView, getViewCount, getViewFactory, getViewIndex, getViewIndex, insert, isVisible, modelToView, modelToView, preferenceChanged, remove, removeAll, replace, setParent, updateChildren, updateLayout, viewToModel
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

FieldView

public FieldView(Element elem)
Constructs a new FieldView wrapped on an element.

Parameters:
elem - the element
Method Detail

getFontMetrics

protected FontMetrics getFontMetrics()
Fetches the font metrics associated with the component hosting this view.

Returns:
the metrics

adjustAllocation

protected Shape adjustAllocation(Shape a)
Adjusts the allocation given to the view to be a suitable allocation for a text field. If the view has been allocated more than the preferred span vertically, the allocation is changed to be centered vertically. Horizontally the view is adjusted according to the horizontal alignment property set on the associated JTextField (if that is the type of the hosting component).

Parameters:
a - the allocation given to the view, which may need to be adjusted.
Returns:
the allocation that the superclass should use.

paint

public void paint(Graphics g,
                  Shape a)
Renders using the given rendering surface and area on that surface. The view may need to do layout and create child views to enable itself to render into the given allocation.

Overrides:
paint in class PlainView
Parameters:
g - the rendering surface to use
a - the allocated region to render into
See Also:
View.paint(java.awt.Graphics, java.awt.Shape)

getPreferredSpan

public float getPreferredSpan(int axis)
Determines the preferred span for this view along an axis.

Overrides:
getPreferredSpan in class PlainView
Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
Returns:
the span the view would like to be rendered into >= 0. Typically the view is told to render into the span that is returned, although there is no guarantee. The parent may choose to resize or break the view.

getResizeWeight

public int getResizeWeight(int axis)
Determines the resizability of the view along the given axis. A value of 0 or less is not resizable.

Overrides:
getResizeWeight in class View
Parameters:
axis - View.X_AXIS or View.Y_AXIS
Returns:
the weight -> 1 for View.X_AXIS, else 0

modelToView

public Shape modelToView(int pos,
                         Shape a,
                         Position.Bias b)
                  throws BadLocationException
Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.

Overrides:
modelToView in class PlainView
Parameters:
pos - the position to convert >= 0
a - the allocated region to render into
Returns:
the bounding box of the given position
Throws:
BadLocationException - if the given position does not represent a valid location in the associated document
See Also:
View.modelToView(int, java.awt.Shape, javax.swing.text.Position.Bias)

viewToModel

public int viewToModel(float fx,
                       float fy,
                       Shape a,
                       Position.Bias[] bias)
Provides a mapping from the view coordinate space to the logical coordinate space of the model.

Overrides:
viewToModel in class PlainView
Parameters:
fx - the X coordinate >= 0.0f
fy - the Y coordinate >= 0.0f
a - the allocated region to render into
Returns:
the location within the model that best represents the given point in the view
See Also:
View.viewToModel(float, float, java.awt.Shape, javax.swing.text.Position.Bias[])

insertUpdate

public void insertUpdate(DocumentEvent changes,
                         Shape a,
                         ViewFactory f)
Gives notification that something was inserted into the document in a location that this view is responsible for.

Overrides:
insertUpdate in class PlainView
Parameters:
changes - the change information from the associated document
a - the current allocation of the view
f - the factory to use to rebuild if the view has children
See Also:
View.insertUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory)

removeUpdate

public void removeUpdate(DocumentEvent changes,
                         Shape a,
                         ViewFactory f)
Gives notification that something was removed from the document in a location that this view is responsible for.

Overrides:
removeUpdate in class PlainView
Parameters:
changes - the change information from the associated document
a - the current allocation of the view
f - the factory to use to rebuild if the view has children
See Also:
View.removeUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


FlowView (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class FlowView

java.lang.Object
    extended by javax.swing.text.View
        extended by javax.swing.text.CompositeView
            extended by javax.swing.text.BoxView
                extended by javax.swing.text.FlowView
All Implemented Interfaces:
SwingConstants
Direct Known Subclasses:
ParagraphView
public abstract class FlowView
extends BoxView

A View that tries to flow it's children into some partially constrained space. This can be used to build things like paragraphs, pages, etc. The flow is made up of the following pieces of functionality.

  • A logical set of child views, which as used as a layout pool from which a physical view is formed.
  • A strategy for translating the logical view to a physical (flowed) view.
  • Constraints for the strategy to work against.
  • A physical structure, that represents the flow. The children of this view are where the pieces of of the logical views are placed to create the flow.

See Also:
View

Nested Class Summary
static class FlowView.FlowStrategy
Strategy for maintaining the physical form of the flow.
Field Summary
protected View | layoutPool These are the views that represent the child elements of the element this view represents (The logical view to translate to a physical view).
protected int | layoutSpan Default constraint against which the flow is created against.
protected FlowView.FlowStrategy | strategy The behavior for keeping the flow updated.
Fields inherited from class javax.swing.text.View
BadBreakWeight, ExcellentBreakWeight, ForcedBreakWeight, GoodBreakWeight, X_AXIS, Y_AXIS
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
Constructor Summary
FlowView(Element elem, int axis)
Constructs a FlowView for the given element.
Method Summary
protected SizeRequirements | calculateMinorAxisRequirements(int axis, SizeRequirements r) Calculate equirements along the minor axis.
void | changedUpdate(DocumentEvent changes, Shape a, ViewFactory f) Gives notification from the document that attributes were changed in a location that this view is responsible for.
protected abstract View | createRow() Create a View that should be used to hold a a rows worth of children in a flow.
int | getFlowAxis() Fetches the axis along which views should be flowed.
int | getFlowSpan(int index) Fetch the constraining span to flow against for the given child index.
int | getFlowStart(int index) Fetch the location along the flow axis that the flow span will start at.
protected int | getViewIndexAtPosition(int pos) Fetches the child view index representing the given position in the model.
void | insertUpdate(DocumentEvent changes, Shape a, ViewFactory f) Gives notification that something was inserted into the document in a location that this view is responsible for.
protected void | layout(int width, int height) Lays out the children.
protected void | loadChildren(ViewFactory f) Loads all of the children to initialize the view.
void | removeUpdate(DocumentEvent changes, Shape a, ViewFactory f) Gives notification that something was removed from the document in a location that this view is responsible for.
Methods inherited from class javax.swing.text.BoxView
baselineLayout, baselineRequirements, calculateMajorAxisRequirements, childAllocation, flipEastAndWestAtEnds, forwardUpdate, getAlignment, getAxis, getChildAllocation, getHeight, getMaximumSpan, getMinimumSpan, getOffset, getPreferredSpan, getResizeWeight, getSpan, getViewAtPoint, getWidth, isAfter, isAllocationValid, isBefore, isLayoutValid, layoutChanged, layoutMajorAxis, layoutMinorAxis, modelToView, paint, paintChild, preferenceChanged, replace, setAxis, setSize, viewToModel
Methods inherited from class javax.swing.text.CompositeView
getBottomInset, getInsideAllocation, getLeftInset, getNextEastWestVisualPositionFrom, getNextNorthSouthVisualPositionFrom, getNextVisualPositionFrom, getRightInset, getTopInset, getView, getViewAtPosition, getViewCount, getViewIndex, modelToView, setInsets, setParagraphInsets, setParent
Methods inherited from class javax.swing.text.View
append, breakView, createFragment, forwardUpdateToView, getAttributes, getBreakWeight, getContainer, getDocument, getElement, getEndOffset, getGraphics, getParent, getStartOffset, getToolTipText, getViewFactory, getViewIndex, insert, isVisible, modelToView, remove, removeAll, updateChildren, updateLayout, viewToModel
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

layoutSpan

protected int layoutSpan
Default constraint against which the flow is created against.

layoutPool

protected View layoutPool
These are the views that represent the child elements of the element this view represents (The logical view to translate to a physical view). These are not directly children of this view. These are either placed into the rows directly or used for the purpose of breaking into smaller chunks, to form the physical view.

strategy

protected FlowView.FlowStrategy strategy
The behavior for keeping the flow updated. By default this is a singleton shared by all instances of FlowView (FlowStrategy is stateless). Subclasses can create an alternative strategy, which might keep state.

Constructor Detail

FlowView

public FlowView(Element elem,
                int axis)
Constructs a FlowView for the given element.

Parameters:
elem - the element that this view is responsible for
axis - may be either View.X_AXIS or View.Y_AXIS
Method Detail

getFlowAxis

public int getFlowAxis()
Fetches the axis along which views should be flowed. By default, this will be the axis orthogonal to the axis along which the flow rows are tiled (the axis of the default flow rows themselves). This is typically used by the FlowStrategy.

getFlowSpan

public int getFlowSpan(int index)
Fetch the constraining span to flow against for the given child index. This is called by the FlowStrategy while it is updating the flow. A flow can be shaped by providing different values for the row constraints. By default, the entire span inside of the insets along the flow axis is returned.

Parameters:
index - the index of the row being updated. This should be a value >= 0 and < getViewCount().
See Also:
getFlowStart(int)

getFlowStart

public int getFlowStart(int index)
Fetch the location along the flow axis that the flow span will start at. This is called by the FlowStrategy while it is updating the flow. A flow can be shaped by providing different values for the row constraints.

Parameters:
index - the index of the row being updated. This should be a value >= 0 and < getViewCount().
See Also:
getFlowSpan(int)

createRow

protected abstract View createRow()
Create a View that should be used to hold a a rows worth of children in a flow. This is called by the FlowStrategy when new children are added or removed (i.e. rows are added or removed) in the process of updating the flow.

loadChildren

protected void loadChildren(ViewFactory f)
Loads all of the children to initialize the view. This is called by the setParent method. This is reimplemented to not load any children directly (as they are created in the process of formatting). If the layoutPool variable is null, an instance of LogicalView is created to represent the logical view that is used in the process of formatting.

Overrides:
loadChildren in class CompositeView
Parameters:
f - the view factory
See Also:
CompositeView.setParent(javax.swing.text.View)

getViewIndexAtPosition

protected int getViewIndexAtPosition(int pos)
Fetches the child view index representing the given position in the model.

Overrides:
getViewIndexAtPosition in class CompositeView
Parameters:
pos - the position >= 0
Returns:
index of the view representing the given position, or -1 if no view represents that position

layout

protected void layout(int width,
                      int height)
Lays out the children. If the span along the flow axis has changed, layout is marked as invalid which which will cause the superclass behavior to recalculate the layout along the box axis. The FlowStrategy.layout method will be called to rebuild the flow rows as appropriate. If the height of this view changes (determined by the perferred size along the box axis), a preferenceChanged is called. Following all of that, the normal box layout of the superclass is performed.

Overrides:
layout in class BoxView
Parameters:
width - the width to lay out against >= 0. This is the width inside of the inset area.
height - the height to lay out against >= 0 This is the height inside of the inset area.

calculateMinorAxisRequirements

protected SizeRequirements calculateMinorAxisRequirements(int axis,
                                                          SizeRequirements r)
Calculate equirements along the minor axis. This is implemented to forward the request to the logical view by calling getMinimumSpan, getPreferredSpan, and getMaximumSpan on it.

Overrides:
calculateMinorAxisRequirements in class BoxView
Parameters:
axis - the axis being studied
r - the SizeRequirements object; if null one will be created
Returns:
the newly initialized SizeRequirements object
See Also:
SizeRequirements

insertUpdate

public void insertUpdate(DocumentEvent changes,
                         Shape a,
                         ViewFactory f)
Gives notification that something was inserted into the document in a location that this view is responsible for.

Overrides:
insertUpdate in class View
Parameters:
changes - the change information from the associated document
a - the current allocation of the view
f - the factory to use to rebuild if the view has children
See Also:
View.insertUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory)

removeUpdate

public void removeUpdate(DocumentEvent changes,
                         Shape a,
                         ViewFactory f)
Gives notification that something was removed from the document in a location that this view is responsible for.

Overrides:
removeUpdate in class View
Parameters:
changes - the change information from the associated document
a - the current allocation of the view
f - the factory to use to rebuild if the view has children
See Also:
View.removeUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory)

changedUpdate

public void changedUpdate(DocumentEvent changes,
                          Shape a,
                          ViewFactory f)
Gives notification from the document that attributes were changed in a location that this view is responsible for.

Overrides:
changedUpdate in class View
Parameters:
changes - the change information from the associated document
a - the current allocation of the view
f - the factory to use to rebuild if the view has children
See Also:
View.changedUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


FlowView.FlowStrategy (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class FlowView.FlowStrategy

java.lang.Object
    extended by javax.swing.text.FlowView.FlowStrategy
Enclosing class:
FlowView
public static class FlowView.FlowStrategy
extends Object

Strategy for maintaining the physical form of the flow. The default implementation is completely stateless, and recalculates the entire flow if the layout is invalid on the given FlowView. Alternative strategies can be implemented by subclassing, and might perform incrementatal repair to the layout or alternative breaking behavior.

Constructor Summary
FlowView.FlowStrategy()
Method Summary
protected void | adjustRow(FlowView fv, int rowIndex, int desiredSpan, int x) Adjusts the given row if possible to fit within the layout span.
void | changedUpdate(FlowView fv, DocumentEvent e, Rectangle alloc) Gives notification from the document that attributes were changed in a location that this view is responsible for.
protected View | createView(FlowView fv, int startOffset, int spanLeft, int rowIndex) Creates a view that can be used to represent the current piece of the flow.
protected View | getLogicalView(FlowView fv) This method gives flow strategies access to the logical view of the FlowView.
void | insertUpdate(FlowView fv, DocumentEvent e, Rectangle alloc) Gives notification that something was inserted into the document in a location that the given flow view is responsible for.
void | layout(FlowView fv) Update the flow on the given FlowView.
protected int | layoutRow(FlowView fv, int rowIndex, int pos) Creates a row of views that will fit within the layout span of the row.
void | removeUpdate(FlowView fv, DocumentEvent e, Rectangle alloc) Gives notification that something was removed from the document in a location that the given flow view is responsible for.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

FlowView.FlowStrategy

public FlowView.FlowStrategy()
Method Detail

insertUpdate

public void insertUpdate(FlowView fv,
                         DocumentEvent e,
                         Rectangle alloc)
Gives notification that something was inserted into the document in a location that the given flow view is responsible for. The strategy should update the appropriate changed region (which depends upon the strategy used for repair).

Parameters:
e - the change information from the associated document
alloc - the current allocation of the view inside of the insets. This value will be null if the view has not yet been displayed.
See Also:
View.insertUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory)

removeUpdate

public void removeUpdate(FlowView fv,
                         DocumentEvent e,
                         Rectangle alloc)
Gives notification that something was removed from the document in a location that the given flow view is responsible for.

Parameters:
e - the change information from the associated document
alloc - the current allocation of the view inside of the insets.
See Also:
View.removeUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory)

changedUpdate

public void changedUpdate(FlowView fv,
                          DocumentEvent e,
                          Rectangle alloc)
Gives notification from the document that attributes were changed in a location that this view is responsible for.

Parameters:
fv - the FlowView containing the changes
e - the DocumentEvent describing the changes done to the Document
alloc - Bounds of the View
See Also:
View.changedUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory)

getLogicalView

protected View getLogicalView(FlowView fv)
This method gives flow strategies access to the logical view of the FlowView.

layout

public void layout(FlowView fv)
Update the flow on the given FlowView. By default, this causes all of the rows (child views) to be rebuilt to match the given constraints for each row. This is called by a FlowView.layout to update the child views in the flow.

Parameters:
fv - the view to reflow

layoutRow

protected int layoutRow(FlowView fv,
                        int rowIndex,
                        int pos)
Creates a row of views that will fit within the layout span of the row. This is called by the layout method. This is implemented to fill the row by repeatedly calling the createView method until the available span has been exhausted, a forced break was encountered, or the createView method returned null. If the remaining span was exhaused, the adjustRow method will be called to perform adjustments to the row to try and make it fit into the given span.

Parameters:
rowIndex - the index of the row to fill in with views. The row is assumed to be empty on entry.
pos - The current position in the children of this views element from which to start.
Returns:
the position to start the next row

adjustRow

protected void adjustRow(FlowView fv,
                         int rowIndex,
                         int desiredSpan,
                         int x)
Adjusts the given row if possible to fit within the layout span. By default this will try to find the highest break weight possible nearest the end of the row. If a forced break is encountered, the break will be positioned there.

Parameters:
rowIndex - the row to adjust to the current layout span.
desiredSpan - the current layout span >= 0
x - the location r starts at.

createView

protected View createView(FlowView fv,
                          int startOffset,
                          int spanLeft,
                          int rowIndex)
Creates a view that can be used to represent the current piece of the flow. This can be either an entire view from the logical view, or a fragment of the logical view.

Parameters:
fv - the view holding the flow
startOffset - the start location for the view being created
spanLeft - the about of span left to fill in the row
rowIndex - the row the view will be placed into
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


GapContent (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class GapContent

java.lang.Object
    extended by javax.swing.text.GapVector
        extended by javax.swing.text.GapContent
All Implemented Interfaces:
AbstractDocument.Content, Serializable
public class GapContent
extends javax.swing.text.GapVector
implements AbstractDocument.Content, Serializable

An implementation of the AbstractDocument.Content interface implemented using a gapped buffer similar to that used by emacs. The underlying storage is a array of unicode characters with a gap somewhere. The gap is moved to the location of changes to take advantage of common behavior where most changes are in the same location. Changes that occur at a gap boundary are generally cheap and moving the gap is generally cheaper than moving the array contents directly to accomodate the change.

The positions tracking change are also generally cheap to maintain. The Position implementations (marks) store the array index and can easily calculate the sequential position from the current gap location. Changes only require update to the the marks between the old and new gap boundaries when the gap is moved, so generally updating the marks is pretty cheap. The marks are stored sorted so they can be located quickly with a binary search. This increases the cost of adding a mark, and decreases the cost of keeping the mark updated.

Constructor Summary
GapContent()
Creates a new GapContent object.
GapContent(int initialLength)
Creates a new GapContent object, with the initial size specified.
Method Summary
protected Object | allocateArray(int len) Allocate an array to store items of the type appropriate (which is determined by the subclass).
Position | createPosition(int offset) Creates a position within the content that will track change as the content is mutated.
protected Object | getArray() Access to the array.
protected int | getArrayLength() Get the length of the allocated array.
void | getChars(int where, int len, Segment chars) Retrieves a portion of the content.
protected int | getGapEnd() Access to the end of the gap.
protected int | getGapStart() Access to the start of the gap.
protected Vector | getPositionsInRange(Vector v, int offset, int length) Returns a Vector containing instances of UndoPosRef for the Positions in the range offset to offset + length.
String | getString(int where, int len) Retrieves a portion of the content.
UndoableEdit | insertString(int where, String str) Inserts a string into the content.
int | length() Returns the length of the content.
UndoableEdit | remove(int where, int nitems) Removes part of the content.
protected void | replace(int position, int rmSize, Object addItems, int addSize) Replace the given logical position in the storage with the given new items.
protected void | resetMarksAtZero() Resets all the marks that have an offset of 0 to have an index of zero as well.
protected void | shiftEnd(int newSize) Make the gap bigger, moving any necessary data and updating the appropriate marks
protected void | shiftGap(int newGapStart) Move the start of the gap to a new location, without changing the size of the gap.
protected void | shiftGapEndUp(int newGapEnd) Adjust the gap end upward.
protected void | shiftGapStartDown(int newGapStart) Adjust the gap end downward.
protected void | updateUndoPositions(Vector positions, int offset, int length) Resets the location for all the UndoPosRef instances in positions.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

GapContent

public GapContent()
Creates a new GapContent object. Initial size defaults to 10.

GapContent

public GapContent(int initialLength)
Creates a new GapContent object, with the initial size specified. The initial size will not be allowed to go below 2, to give room for the implied break and the gap.

Parameters:
initialLength - the initial size
Method Detail

allocateArray

protected Object allocateArray(int len)
Allocate an array to store items of the type appropriate (which is determined by the subclass).

getArrayLength

protected int getArrayLength()
Get the length of the allocated array.

length

public int length()
Returns the length of the content.

Specified by:
length in interface AbstractDocument.Content
Returns:
the length >= 1
See Also:
AbstractDocument.Content.length()

insertString

public UndoableEdit insertString(int where,
                                 String str)
                          throws BadLocationException
Inserts a string into the content.

Specified by:
insertString in interface AbstractDocument.Content
Parameters:
where - the starting position >= 0, < length()
str - the non-null string to insert
Returns:
an UndoableEdit object for undoing
Throws:
BadLocationException - if the specified position is invalid
See Also:
AbstractDocument.Content.insertString(int, java.lang.String)

remove

public UndoableEdit remove(int where,
                           int nitems)
                    throws BadLocationException
Removes part of the content.

Specified by:
remove in interface AbstractDocument.Content
Parameters:
where - the starting position >= 0, where + nitems < length()
nitems - the number of characters to remove >= 0
Returns:
an UndoableEdit object for undoing
Throws:
BadLocationException - if the specified position is invalid
See Also:
AbstractDocument.Content.remove(int, int)

getString

public String getString(int where,
                        int len)
                 throws BadLocationException
Retrieves a portion of the content.

Specified by:
getString in interface AbstractDocument.Content
Parameters:
where - the starting position >= 0
len - the length to retrieve >= 0
Returns:
a string representing the content
Throws:
BadLocationException - if the specified position is invalid
See Also:
AbstractDocument.Content.getString(int, int)

getChars

public void getChars(int where,
                     int len,
                     Segment chars)
              throws BadLocationException
Retrieves a portion of the content. If the desired content spans the gap, we copy the content. If the desired content does not span the gap, the actual store is returned to avoid the copy since it is contiguous.

Specified by:
getChars in interface AbstractDocument.Content
Parameters:
where - the starting position >= 0, where + len <= length()
len - the number of characters to retrieve >= 0
chars - the Segment object to return the characters in
Throws:
BadLocationException - if the specified position is invalid
See Also:
AbstractDocument.Content.getChars(int, int, javax.swing.text.Segment)

createPosition

public Position createPosition(int offset)
                        throws BadLocationException
Creates a position within the content that will track change as the content is mutated.

Specified by:
createPosition in interface AbstractDocument.Content
Parameters:
offset - the offset to track >= 0
Returns:
the position
Throws:
BadLocationException - if the specified position is invalid

shiftEnd

protected void shiftEnd(int newSize)
Make the gap bigger, moving any necessary data and updating the appropriate marks

shiftGap

protected void shiftGap(int newGapStart)
Move the start of the gap to a new location, without changing the size of the gap. This moves the data in the array and updates the marks accordingly.

resetMarksAtZero

protected void resetMarksAtZero()
Resets all the marks that have an offset of 0 to have an index of zero as well.

shiftGapStartDown

protected void shiftGapStartDown(int newGapStart)
Adjust the gap end downward. This doesn't move any data, but it does update any marks affected by the boundary change. All marks from the old gap start down to the new gap start are squeezed to the end of the gap (their location has been removed).

shiftGapEndUp

protected void shiftGapEndUp(int newGapEnd)
Adjust the gap end upward. This doesn't move any data, but it does update any marks affected by the boundary change. All marks from the old gap end up to the new gap end are squeezed to the end of the gap (their location has been removed).

getPositionsInRange

protected Vector getPositionsInRange(Vector v,
                                     int offset,
                                     int length)
Returns a Vector containing instances of UndoPosRef for the Positions in the range offset to offset + length. If v is not null the matching Positions are placed in there. The vector with the resulting Positions are returned.

Parameters:
v - the Vector to use, with a new one created on null
offset - the starting offset >= 0
length - the length >= 0
Returns:
the set of instances

updateUndoPositions

protected void updateUndoPositions(Vector positions,
                                   int offset,
                                   int length)
Resets the location for all the UndoPosRef instances in positions.

This is meant for internal usage, and is generally not of interest to subclasses.

Parameters:
positions - the UndoPosRef instances to reset

getArray

protected final Object getArray()
Access to the array. The actual type of the array is known only by the subclass.

getGapStart

protected final int getGapStart()
Access to the start of the gap.

getGapEnd

protected final int getGapEnd()
Access to the end of the gap.

replace

protected void replace(int position,
                       int rmSize,
                       Object addItems,
                       int addSize)
Replace the given logical position in the storage with the given new items. This will move the gap to the area being changed if the gap is not currently located at the change location.

Parameters:
position - the location to make the replacement. This is not the location in the underlying storage array, but the location in the contiguous space being modeled.
rmSize - the number of items to remove
addItems - the new items to place in storage.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


GlyphView (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class GlyphView

java.lang.Object
    extended by javax.swing.text.View
        extended by javax.swing.text.GlyphView
All Implemented Interfaces:
Cloneable, SwingConstants, TabableView
Direct Known Subclasses:
LabelView
public class GlyphView
extends View
implements TabableView, Cloneable

A GlyphView is a styled chunk of text that represents a view mapped over an element in the text model. This view is generally responsible for displaying text glyphs using character level attributes in some way. An implementation of the GlyphPainter class is used to do the actual rendering and model/view translations. This separates rendering from layout and management of the association with the model.

The view supports breaking for the purpose of formatting. The fragments produced by breaking share the view that has primary responsibility for the element (i.e. they are nested classes and carry only a small amount of state of their own) so they can share its resources.

Since this view represents text that may have tabs embedded in it, it implements the TabableView interface. Tabs will only be expanded if this view is embedded in a container that does tab expansion. ParagraphView is an example of a container that does tab expansion.

Since:
1.3

Nested Class Summary
static class GlyphView.GlyphPainter
A class to perform rendering of the glyphs.
Field Summary
Fields inherited from class javax.swing.text.View
BadBreakWeight, ExcellentBreakWeight, ForcedBreakWeight, GoodBreakWeight, X_AXIS, Y_AXIS
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
Constructor Summary
GlyphView(Element elem)
Constructs a new view wrapped on an element.
Method Summary
View | breakView(int axis, int p0, float pos, float len) Breaks this view on the given axis at the given length.
void | changedUpdate(DocumentEvent e, Shape a, ViewFactory f) Gives notification from the document that attributes were changed in a location that this view is responsible for.
protected void | checkPainter() Check to see that a glyph painter exists.
protected Object | clone() Creates a shallow copy.
View | createFragment(int p0, int p1) Creates a view that represents a portion of the element.
float | getAlignment(int axis) Determines the desired alignment for this view along an axis.
Color | getBackground() Fetch the background color to use to render the glyphs.
int | getBreakWeight(int axis, float pos, float len) Determines how attractive a break opportunity in this view is.
int | getEndOffset() Fetches the portion of the model that this view is responsible for.
Font | getFont() Fetch the font that the glyphs should be based upon.
Color | getForeground() Fetch the foreground color to use to render the glyphs.
GlyphView.GlyphPainter | getGlyphPainter() Fetch the currently installed glyph painter.
int | getNextVisualPositionFrom(int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet) Provides a way to determine the next visually represented model location that one might place a caret.
float | getPartialSpan(int p0, int p1) Determines the span along the same axis as tab expansion for a portion of the view.
float | getPreferredSpan(int axis) Determines the preferred span for this view along an axis.
int | getStartOffset() Fetches the portion of the model that this view is responsible for.
float | getTabbedSpan(float x, TabExpander e) Determines the desired span when using the given tab expansion implementation.
TabExpander | getTabExpander() Fetch the TabExpander to use if tabs are present in this view.
Segment | getText(int p0, int p1) Fetch a reference to the text that occupies the given range.
void | insertUpdate(DocumentEvent e, Shape a, ViewFactory f) Gives notification that something was inserted into the document in a location that this view is responsible for.
boolean | isStrikeThrough() Determine if the glyphs should have a strikethrough line.
boolean | isSubscript() Determine if the glyphs should be rendered as superscript.
boolean | isSuperscript() Determine if the glyphs should be rendered as subscript.
boolean | isUnderline() Determine if the glyphs should be underlined.
Shape | modelToView(int pos, Shape a, Position.Bias b) Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
void | paint(Graphics g, Shape a) Renders a portion of a text style run.
void | removeUpdate(DocumentEvent e, Shape a, ViewFactory f) Gives notification that something was removed from the document in a location that this view is responsible for.
void | setGlyphPainter(GlyphView.GlyphPainter p) Sets the painter to use for rendering glyphs.
int | viewToModel(float x, float y, Shape a, Position.Bias[] biasReturn) Provides a mapping from the view coordinate space to the logical coordinate space of the model.
Methods inherited from class javax.swing.text.View
append, forwardUpdate, forwardUpdateToView, getAttributes, getChildAllocation, getContainer, getDocument, getElement, getGraphics, getMaximumSpan, getMinimumSpan, getParent, getResizeWeight, getToolTipText, getView, getViewCount, getViewFactory, getViewIndex, getViewIndex, insert, isVisible, modelToView, modelToView, preferenceChanged, remove, removeAll, replace, setParent, setSize, updateChildren, updateLayout, viewToModel
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

GlyphView

public GlyphView(Element elem)
Constructs a new view wrapped on an element.

Parameters:
elem - the element
Method Detail

clone

protected final Object clone()
Creates a shallow copy. This is used by the createFragment and breakView methods.

Overrides:
clone in class Object
Returns:
the copy
See Also:
Cloneable

getGlyphPainter

public GlyphView.GlyphPainter getGlyphPainter()
Fetch the currently installed glyph painter. If a painter has not yet been installed, and a default was not yet needed, null is returned.

setGlyphPainter

public void setGlyphPainter(GlyphView.GlyphPainter p)
Sets the painter to use for rendering glyphs.

getText

public Segment getText(int p0,
                       int p1)
Fetch a reference to the text that occupies the given range. This is normally used by the GlyphPainter to determine what characters it should render glyphs for.

Parameters:
p0 - the starting document offset >= 0
p1 - the ending document offset >= p0
Returns:
the Segment containing the text

getBackground

public Color getBackground()
Fetch the background color to use to render the glyphs. If there is no background color, null should be returned. This is implemented to call StyledDocument.getBackground if the associated document is a styled document, otherwise it returns null.

getForeground

public Color getForeground()
Fetch the foreground color to use to render the glyphs. If there is no foreground color, null should be returned. This is implemented to call StyledDocument.getBackground if the associated document is a StyledDocument. If the associated document is not a StyledDocument, the associated components foreground color is used. If there is no associated component, null is returned.

getFont

public Font getFont()
Fetch the font that the glyphs should be based upon. This is implemented to call StyledDocument.getFont if the associated document is a StyledDocument. If the associated document is not a StyledDocument, the associated components font is used. If there is no associated component, null is returned.

isUnderline

public boolean isUnderline()
Determine if the glyphs should be underlined. If true, an underline should be drawn through the baseline.

isStrikeThrough

public boolean isStrikeThrough()
Determine if the glyphs should have a strikethrough line. If true, a line should be drawn through the center of the glyphs.

isSubscript

public boolean isSubscript()
Determine if the glyphs should be rendered as superscript.

isSuperscript

public boolean isSuperscript()
Determine if the glyphs should be rendered as subscript.

getTabExpander

public TabExpander getTabExpander()
Fetch the TabExpander to use if tabs are present in this view.

checkPainter

protected void checkPainter()
Check to see that a glyph painter exists. If a painter doesn't exist, a default glyph painter will be installed.

getTabbedSpan

public float getTabbedSpan(float x,
                           TabExpander e)
Determines the desired span when using the given tab expansion implementation.

Specified by:
getTabbedSpan in interface TabableView
Parameters:
x - the position the view would be located at for the purpose of tab expansion >= 0.
e - how to expand the tabs when encountered.
Returns:
the desired span >= 0
See Also:
TabableView.getTabbedSpan(float, javax.swing.text.TabExpander)

getPartialSpan

public float getPartialSpan(int p0,
                            int p1)
Determines the span along the same axis as tab expansion for a portion of the view. This is intended for use by the TabExpander for cases where the tab expansion involves aligning the portion of text that doesn't have whitespace relative to the tab stop. There is therefore an assumption that the range given does not contain tabs.

This method can be called while servicing the getTabbedSpan or getPreferredSize. It has to arrange for its own text buffer to make the measurements.

Specified by:
getPartialSpan in interface TabableView
Parameters:
p0 - the starting document offset >= 0
p1 - the ending document offset >= p0
Returns:
the span >= 0

getStartOffset

public int getStartOffset()
Fetches the portion of the model that this view is responsible for.

Overrides:
getStartOffset in class View
Returns:
the starting offset into the model
See Also:
View.getStartOffset()

getEndOffset

public int getEndOffset()
Fetches the portion of the model that this view is responsible for.

Overrides:
getEndOffset in class View
Returns:
the ending offset into the model
See Also:
View.getEndOffset()

paint

public void paint(Graphics g,
                  Shape a)
Renders a portion of a text style run.

Specified by:
paint in class View
Parameters:
g - the rendering surface to use
a - the allocated region to render into
See Also:
View.paint(java.awt.Graphics, java.awt.Shape)

getPreferredSpan

public float getPreferredSpan(int axis)
Determines the preferred span for this view along an axis.

Specified by:
getPreferredSpan in class View
Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
Returns:
the span the view would like to be rendered into >= 0. Typically the view is told to render into the span that is returned, although there is no guarantee. The parent may choose to resize or break the view.
See Also:
View.getPreferredSpan(int)

getAlignment

public float getAlignment(int axis)
Determines the desired alignment for this view along an axis. For the label, the alignment is along the font baseline for the y axis, and the superclasses alignment along the x axis.

Overrides:
getAlignment in class View
Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
Returns:
the desired alignment. This should be a value between 0.0 and 1.0 inclusive, where 0 indicates alignment at the origin and 1.0 indicates alignment to the full span away from the origin. An alignment of 0.5 would be the center of the view.

modelToView

public Shape modelToView(int pos,
                         Shape a,
                         Position.Bias b)
                  throws BadLocationException
Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.

Specified by:
modelToView in class View
Parameters:
pos - the position to convert >= 0
a - the allocated region to render into
b - either Position.Bias.Forward or Position.Bias.Backward
Returns:
the bounding box of the given position
Throws:
BadLocationException - if the given position does not represent a valid location in the associated document
See Also:
View.modelToView(int, java.awt.Shape, javax.swing.text.Position.Bias)

viewToModel

public int viewToModel(float x,
                       float y,
                       Shape a,
                       Position.Bias[] biasReturn)
Provides a mapping from the view coordinate space to the logical coordinate space of the model.

Specified by:
viewToModel in class View
Parameters:
x - the X coordinate >= 0
y - the Y coordinate >= 0
a - the allocated region to render into
biasReturn - either Position.Bias.Forward or Position.Bias.Backward is returned as the zero-th element of this array
Returns:
the location within the model that best represents the given point of view >= 0
See Also:
View.viewToModel(float, float, java.awt.Shape, javax.swing.text.Position.Bias[])

getBreakWeight

public int getBreakWeight(int axis,
                          float pos,
                          float len)
Determines how attractive a break opportunity in this view is. This can be used for determining which view is the most attractive to call breakView on in the process of formatting. The higher the weight, the more attractive the break. A value equal to or lower than View.BadBreakWeight should not be considered for a break. A value greater than or equal to View.ForcedBreakWeight should be broken.

This is implemented to forward to the superclass for the Y_AXIS. Along the X_AXIS the following values may be returned.

View.ExcellentBreakWeight
if there is whitespace proceeding the desired break location.
View.BadBreakWeight
if the desired break location results in a break location of the starting offset.
View.GoodBreakWeight
if the other conditions don't occur.
This will normally result in the behavior of breaking on a whitespace location if one can be found, otherwise breaking between characters.

Overrides:
getBreakWeight in class View
Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
pos - the potential location of the start of the broken view >= 0. This may be useful for calculating tab positions.
len - specifies the relative length from pos where a potential break is desired >= 0.
Returns:
the weight, which should be a value between View.ForcedBreakWeight and View.BadBreakWeight.
See Also:
LabelView, ParagraphView, View.BadBreakWeight, View.GoodBreakWeight, View.ExcellentBreakWeight, View.ForcedBreakWeight

breakView

public View breakView(int axis,
                      int p0,
                      float pos,
                      float len)
Breaks this view on the given axis at the given length. This is implemented to attempt to break on a whitespace location, and returns a fragment with the whitespace at the end. If a whitespace location can't be found, the nearest character is used.

Overrides:
breakView in class View
Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
p0 - the location in the model where the fragment should start it's representation >= 0.
pos - the position along the axis that the broken view would occupy >= 0. This may be useful for things like tab calculations.
len - specifies the distance along the axis where a potential break is desired >= 0.
Returns:
the fragment of the view that represents the given span, if the view can be broken. If the view doesn't support breaking behavior, the view itself is returned.
See Also:
View.breakView(int, int, float, float)

createFragment

public View createFragment(int p0,
                           int p1)
Creates a view that represents a portion of the element. This is potentially useful during formatting operations for taking measurements of fragments of the view. If the view doesn't support fragmenting (the default), it should return itself.

This view does support fragmenting. It is implemented to return a nested class that shares state in this view representing only a portion of the view.

Overrides:
createFragment in class View
Parameters:
p0 - the starting offset >= 0. This should be a value greater or equal to the element starting offset and less than the element ending offset.
p1 - the ending offset > p0. This should be a value less than or equal to the elements end offset and greater than the elements starting offset.
Returns:
the view fragment, or itself if the view doesn't support breaking into fragments
See Also:
LabelView

getNextVisualPositionFrom

public int getNextVisualPositionFrom(int pos,
                                     Position.Bias b,
                                     Shape a,
                                     int direction,
                                     Position.Bias[] biasRet)
                              throws BadLocationException
Provides a way to determine the next visually represented model location that one might place a caret. Some views may not be visible, they might not be in the same order found in the model, or they just might not allow access to some of the locations in the model.

Overrides:
getNextVisualPositionFrom in class View
Parameters:
pos - the position to convert >= 0
a - the allocated region to render into
direction - the direction from the current position that can be thought of as the arrow keys typically found on a keyboard. This may be SwingConstants.WEST, SwingConstants.EAST, SwingConstants.NORTH, or SwingConstants.SOUTH.
Returns:
the location within the model that best represents the next location visual position.
Throws:
BadLocationException
IllegalArgumentException - for an invalid direction

insertUpdate

public void insertUpdate(DocumentEvent e,
                         Shape a,
                         ViewFactory f)
Gives notification that something was inserted into the document in a location that this view is responsible for. This is implemented to call preferenceChanged along the axis the glyphs are rendered.

Overrides:
insertUpdate in class View
Parameters:
e - the change information from the associated document
a - the current allocation of the view
f - the factory to use to rebuild if the view has children
See Also:
View.insertUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory)

removeUpdate

public void removeUpdate(DocumentEvent e,
                         Shape a,
                         ViewFactory f)
Gives notification that something was removed from the document in a location that this view is responsible for. This is implemented to call preferenceChanged along the axis the glyphs are rendered.

Overrides:
removeUpdate in class View
Parameters:
e - the change information from the associated document
a - the current allocation of the view
f - the factory to use to rebuild if the view has children
See Also:
View.removeUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory)

changedUpdate

public void changedUpdate(DocumentEvent e,
                          Shape a,
                          ViewFactory f)
Gives notification from the document that attributes were changed in a location that this view is responsible for. This is implemented to call preferenceChanged along both the horizontal and vertical axis.

Overrides:
changedUpdate in class View
Parameters:
e - the change information from the associated document
a - the current allocation of the view
f - the factory to use to rebuild if the view has children
See Also:
View.changedUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


GlyphView.GlyphPainter (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class GlyphView.GlyphPainter

java.lang.Object
    extended by javax.swing.text.GlyphView.GlyphPainter
Enclosing class:
GlyphView
public abstract static class GlyphView.GlyphPainter
extends Object

A class to perform rendering of the glyphs. This can be implemented to be stateless, or to hold some information as a cache to facilitate faster rendering and model/view translation. At a minimum, the GlyphPainter allows a View implementation to perform its duties independant of a particular version of JVM and selection of capabilities (i.e. shaping for i18n, etc).

Since:
1.3

Constructor Summary
GlyphView.GlyphPainter()
Method Summary
abstract float | getAscent(GlyphView v)
abstract int | getBoundedPosition(GlyphView v, int p0, float x, float len) Determines the model location that represents the maximum advance that fits within the given span.
abstract float | getDescent(GlyphView v)
abstract float | getHeight(GlyphView v)
int | getNextVisualPositionFrom(GlyphView v, int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet) Provides a way to determine the next visually represented model location that one might place a caret.
GlyphView.GlyphPainter | getPainter(GlyphView v, int p0, int p1) Create a painter to use for the given GlyphView.
abstract float | getSpan(GlyphView v, int p0, int p1, TabExpander e, float x) Determine the span the glyphs given a start location (for tab expansion).
abstract Shape | modelToView(GlyphView v, int pos, Position.Bias bias, Shape a) Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
abstract void | paint(GlyphView v, Graphics g, Shape a, int p0, int p1) Paint the glyphs representing the given range.
abstract int | viewToModel(GlyphView v, float x, float y, Shape a, Position.Bias[] biasReturn) Provides a mapping from the view coordinate space to the logical coordinate space of the model.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

GlyphView.GlyphPainter

public GlyphView.GlyphPainter()
Method Detail

getSpan

public abstract float getSpan(GlyphView v,
                              int p0,
                              int p1,
                              TabExpander e,
                              float x)
Determine the span the glyphs given a start location (for tab expansion).

getHeight

public abstract float getHeight(GlyphView v)

getAscent

public abstract float getAscent(GlyphView v)

getDescent

public abstract float getDescent(GlyphView v)

paint

public abstract void paint(GlyphView v,
                           Graphics g,
                           Shape a,
                           int p0,
                           int p1)
Paint the glyphs representing the given range.

modelToView

public abstract Shape modelToView(GlyphView v,
                                  int pos,
                                  Position.Bias bias,
                                  Shape a)
                           throws BadLocationException
Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it. This is shared by the broken views.

Parameters:
v - the GlyphView containing the destination coordinate space
pos - the position to convert
bias - either Position.Bias.Forward or Position.Bias.Backward
a - Bounds of the View
Returns:
the bounding box of the given position
Throws:
BadLocationException - if the given position does not represent a valid location in the associated document
See Also:
View.modelToView(int, java.awt.Shape, javax.swing.text.Position.Bias)

viewToModel

public abstract int viewToModel(GlyphView v,
                                float x,
                                float y,
                                Shape a,
                                Position.Bias[] biasReturn)
Provides a mapping from the view coordinate space to the logical coordinate space of the model.

Parameters:
v - the GlyphView to provide a mapping for
x - the X coordinate
y - the Y coordinate
a - the allocated region to render into
biasReturn - either Position.Bias.Forward or Position.Bias.Backward is returned as the zero-th element of this array
Returns:
the location within the model that best represents the given point of view
See Also:
View.viewToModel(float, float, java.awt.Shape, javax.swing.text.Position.Bias[])

getBoundedPosition

public abstract int getBoundedPosition(GlyphView v,
                                       int p0,
                                       float x,
                                       float len)
Determines the model location that represents the maximum advance that fits within the given span. This could be used to break the given view. The result should be a location just shy of the given advance. This differs from viewToModel which returns the closest position which might be proud of the maximum advance.

Parameters:
v - the view to find the model location to break at.
p0 - the location in the model where the fragment should start it's representation >= 0.
x - the graphic location along the axis that the broken view would occupy >= 0. This may be useful for things like tab calculations.
len - specifies the distance into the view where a potential break is desired >= 0.
Returns:
the maximum model location possible for a break.
See Also:
View.breakView(int, int, float, float)

getPainter

public GlyphView.GlyphPainter getPainter(GlyphView v,
                                         int p0,
                                         int p1)
Create a painter to use for the given GlyphView. If the painter carries state it can create another painter to represent a new GlyphView that is being created. If the painter doesn't hold any significant state, it can return itself. The default behavior is to return itself.

Parameters:
v - the GlyphView to provide a painter for
p0 - the starting document offset >= 0
p1 - the ending document offset >= p0

getNextVisualPositionFrom

public int getNextVisualPositionFrom(GlyphView v,
                                     int pos,
                                     Position.Bias b,
                                     Shape a,
                                     int direction,
                                     Position.Bias[] biasRet)
                              throws BadLocationException
Provides a way to determine the next visually represented model location that one might place a caret. Some views may not be visible, they might not be in the same order found in the model, or they just might not allow access to some of the locations in the model.

Parameters:
v - the view to use
pos - the position to convert >= 0
b - either Position.Bias.Forward or Position.Bias.Backward
a - the allocated region to render into
direction - the direction from the current position that can be thought of as the arrow keys typically found on a keyboard. This may be SwingConstants.WEST, SwingConstants.EAST, SwingConstants.NORTH, or SwingConstants.SOUTH.
biasRet - either Position.Bias.Forward or Position.Bias.Backward is returned as the zero-th element of this array
Returns:
the location within the model that best represents the next location visual position.
Throws:
BadLocationException
IllegalArgumentException - for an invalid direction
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Highlighter (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Interface Highlighter

All Known Implementing Classes:
LayeredHighlighter
public interface Highlighter

An interface for an object that allows one to mark up the background with colored areas.

Nested Class Summary
static interface | Highlighter.Highlight
static interface | Highlighter.HighlightPainter Highlight renderer.
Method Summary
Object | addHighlight(int p0, int p1, Highlighter.HighlightPainter p) Adds a highlight to the view.
void | changeHighlight(Object tag, int p0, int p1) Changes the given highlight to span a different portion of the document.
void | deinstall(JTextComponent c) Called when the UI is being removed from the interface of a JTextComponent.
Highlighter.Highlight[] | getHighlights() Fetches the current list of highlights.
void | install(JTextComponent c) Called when the UI is being installed into the interface of a JTextComponent.
void | paint(Graphics g) Renders the highlights.
void | removeAllHighlights() Removes all highlights this highlighter is responsible for.
void | removeHighlight(Object tag) Removes a highlight from the view.

Method Detail

install

public void install(JTextComponent c)
Called when the UI is being installed into the interface of a JTextComponent. This can be used to gain access to the model that is being navigated by the implementation of this interface.

Parameters:
c - the JTextComponent editor

deinstall

public void deinstall(JTextComponent c)
Called when the UI is being removed from the interface of a JTextComponent. This is used to unregister any listeners that were attached.

Parameters:
c - the JTextComponent editor

paint

public void paint(Graphics g)
Renders the highlights.

Parameters:
g - the graphics context.

addHighlight

public Object addHighlight(int p0,
                           int p1,
                           Highlighter.HighlightPainter p)
                    throws BadLocationException
Adds a highlight to the view. Returns a tag that can be used to refer to the highlight.

Parameters:
p0 - the beginning of the range >= 0
p1 - the end of the range >= p0
p - the painter to use for the actual highlighting
Returns:
an object that refers to the highlight
Throws:
BadLocationException - for an invalid range specification

removeHighlight

public void removeHighlight(Object tag)
Removes a highlight from the view.

Parameters:
tag - which highlight to remove

removeAllHighlights

public void removeAllHighlights()
Removes all highlights this highlighter is responsible for.

changeHighlight

public void changeHighlight(Object tag,
                            int p0,
                            int p1)
                     throws BadLocationException
Changes the given highlight to span a different portion of the document. This may be more efficient than a remove/add when a selection is expanding/shrinking (such as a sweep with a mouse) by damaging only what changed.

Parameters:
tag - which highlight to change
p0 - the beginning of the range >= 0
p1 - the end of the range >= p0
Throws:
BadLocationException - for an invalid range specification

getHighlights

public Highlighter.Highlight[] getHighlights()
Fetches the current list of highlights.

Returns:
the highlight list
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Highlighter.Highlight (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Interface Highlighter.Highlight

Enclosing interface:
Highlighter
public static interface Highlighter.Highlight

Method Summary
int | getEndOffset() Gets the ending model offset for the highlight.
Highlighter.HighlightPainter | getPainter() Gets the painter for the highlighter.
int | getStartOffset() Gets the starting model offset for the highlight.

Method Detail

getStartOffset

public int getStartOffset()
Gets the starting model offset for the highlight.

Returns:
the starting offset >= 0

getEndOffset

public int getEndOffset()
Gets the ending model offset for the highlight.

Returns:
the ending offset >= 0

getPainter

public Highlighter.HighlightPainter getPainter()
Gets the painter for the highlighter.

Returns:
the painter
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Highlighter.HighlightPainter (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Interface Highlighter.HighlightPainter

All Known Implementing Classes:
LayeredHighlighter.LayerPainter
Enclosing interface:
Highlighter
public static interface Highlighter.HighlightPainter

Highlight renderer.

Method Summary
 void paint(Graphics g, int p0, int p1, Shape bounds, JTextComponent c)
Renders the highlight.

Method Detail

paint

public void paint(Graphics g,
                  int p0,
                  int p1,
                  Shape bounds,
                  JTextComponent c)
Renders the highlight.

Parameters:
g - the graphics context
p0 - the starting offset in the model >= 0
p1 - the ending offset in the model >= p0
bounds - the bounding box for the highlight
c - the editor
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


IconView (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class IconView

java.lang.Object
    extended by javax.swing.text.View
        extended by javax.swing.text.IconView
All Implemented Interfaces:
SwingConstants
public class IconView
extends View

Icon decorator that implements the view interface. The entire element is used to represent the icon. This acts as a gateway from the display-only View implementations to interactive lightweight icons (that is, it allows icons to be embedded into the View hierarchy. The parent of the icon is the container that is handed out by the associated view factory.

Field Summary
Fields inherited from class javax.swing.text.View
BadBreakWeight, ExcellentBreakWeight, ForcedBreakWeight, GoodBreakWeight, X_AXIS, Y_AXIS
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
Constructor Summary
IconView(Element elem)
Creates a new icon view that represents an element.
Method Summary
float | getAlignment(int axis) Determines the desired alignment for this view along an axis.
float | getPreferredSpan(int axis) Determines the preferred span for this view along an axis.
Shape | modelToView(int pos, Shape a, Position.Bias b) Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
void | paint(Graphics g, Shape a) Paints the icon.
int | viewToModel(float x, float y, Shape a, Position.Bias[] bias) Provides a mapping from the view coordinate space to the logical coordinate space of the model.
Methods inherited from class javax.swing.text.View
append, breakView, changedUpdate, createFragment, forwardUpdate, forwardUpdateToView, getAttributes, getBreakWeight, getChildAllocation, getContainer, getDocument, getElement, getEndOffset, getGraphics, getMaximumSpan, getMinimumSpan, getNextVisualPositionFrom, getParent, getResizeWeight, getStartOffset, getToolTipText, getView, getViewCount, getViewFactory, getViewIndex, getViewIndex, insert, insertUpdate, isVisible, modelToView, modelToView, preferenceChanged, remove, removeAll, removeUpdate, replace, setParent, setSize, updateChildren, updateLayout, viewToModel
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

IconView

public IconView(Element elem)
Creates a new icon view that represents an element.

Parameters:
elem - the element to create a view for
Method Detail

paint

public void paint(Graphics g,
                  Shape a)
Paints the icon. The real paint behavior occurs naturally from the association that the icon has with its parent container (the same container hosting this view), so this simply allows us to position the icon properly relative to the view. Since the coordinate system for the view is simply the parent containers, positioning the child icon is easy.

Specified by:
paint in class View
Parameters:
g - the rendering surface to use
a - the allocated region to render into
See Also:
View.paint(java.awt.Graphics, java.awt.Shape)

getPreferredSpan

public float getPreferredSpan(int axis)
Determines the preferred span for this view along an axis.

Specified by:
getPreferredSpan in class View
Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
Returns:
the span the view would like to be rendered into Typically the view is told to render into the span that is returned, although there is no guarantee. The parent may choose to resize or break the view.
Throws:
IllegalArgumentException - for an invalid axis
See Also:
View.getPreferredSpan(int)

getAlignment

public float getAlignment(int axis)
Determines the desired alignment for this view along an axis. This is implemented to give the alignment to the bottom of the icon along the y axis, and the default along the x axis.

Overrides:
getAlignment in class View
Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
Returns:
the desired alignment >= 0.0f && <= 1.0f. This should be a value between 0.0 and 1.0 where 0 indicates alignment at the origin and 1.0 indicates alignment to the full span away from the origin. An alignment of 0.5 would be the center of the view.

modelToView

public Shape modelToView(int pos,
                         Shape a,
                         Position.Bias b)
                  throws BadLocationException
Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.

Specified by:
modelToView in class View
Parameters:
pos - the position to convert >= 0
a - the allocated region to render into
b - the bias toward the previous character or the next character represented by the offset, in case the position is a boundary of two views; b will have one of these values:
  • Position.Bias.Forward
  • Position.Bias.Backward
Returns:
the bounding box of the given position
Throws:
BadLocationException - if the given position does not represent a valid location in the associated document
See Also:
View.modelToView(int, java.awt.Shape, javax.swing.text.Position.Bias)

viewToModel

public int viewToModel(float x,
                       float y,
                       Shape a,
                       Position.Bias[] bias)
Provides a mapping from the view coordinate space to the logical coordinate space of the model.

Specified by:
viewToModel in class View
Parameters:
x - the X coordinate >= 0
y - the Y coordinate >= 0
a - the allocated region to render into
Returns:
the location within the model that best represents the given point of view >= 0
See Also:
View.viewToModel(float, float, java.awt.Shape, javax.swing.text.Position.Bias[])
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


InternationalFormatter (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class InternationalFormatter

java.lang.Object
    extended by javax.swing.JFormattedTextField.AbstractFormatter
        extended by javax.swing.text.DefaultFormatter
            extended by javax.swing.text.InternationalFormatter
All Implemented Interfaces:
Cloneable, Serializable
Direct Known Subclasses:
DateFormatter, NumberFormatter
public class InternationalFormatter
extends DefaultFormatter

InternationalFormatter extends DefaultFormatter, using an instance of java.text.Format to handle the conversion to a String, and the conversion from a String.

If getAllowsInvalid() is false, this will ask the Format to format the current text on every edit.

You can specify a minimum and maximum value by way of the setMinimum and setMaximum methods. In order for this to work the values returned from stringToValue must be comparable to the min/max values by way of the Comparable interface.

Be careful how you configure the Format and the InternationalFormatter, as it is possible to create a situation where certain values can not be input. Consider the date format 'M/d/yy', an InternationalFormatter that is always valid (setAllowsInvalid(false)), is in overwrite mode (setOverwriteMode(true)) and the date 7/1/99. In this case the user will not be able to enter a two digit month or day of month. To avoid this, the format should be 'MM/dd/yy'.

If InternationalFormatter is configured to only allow valid values (setAllowsInvalid(false)), every valid edit will result in the text of the JFormattedTextField being completely reset from the Format. The cursor position will also be adjusted as literal characters are added/removed from the resulting String.

InternationalFormatter's behavior of stringToValue is slightly different than that of DefaultTextFormatter, it does the following:

  1. parseObject is invoked on the Format specified by setFormat
  2. If a Class has been set for the values (setValueClass), supers implementation is invoked to convert the value returned from parseObject to the appropriate class.
  3. If a ParseException has not been thrown, and the value is outside the min/max a ParseException is thrown.
  4. The value is returned.
InternationalFormatter implements stringToValue in this manner so that you can specify an alternate Class than Format may return.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Since:
1.4
See Also:
Format, Comparable

Constructor Summary
InternationalFormatter()
Creates an InternationalFormatter with no Format specified.
InternationalFormatter(Format format)
Creates an InternationalFormatter with the specified Format instance.
Method Summary
Object | clone() Creates a copy of the DefaultFormatter.
protected Action[] | getActions() If getSupportsIncrement returns true, this returns two Actions suitable for incrementing/decrementing the value.
Format.Field[] | getFields(int offset) Returns the Format.Field constants associated with the text at offset.
Format | getFormat() Returns the format that dictates the legal values that can be edited and displayed.
Comparable | getMaximum() Returns the maximum permissible value.
Comparable | getMinimum() Returns the minimum permissible value.
void | install(JFormattedTextField ftf) Installs the DefaultFormatter onto a particular JFormattedTextField.
void | setFormat(Format format) Sets the format that dictates the legal values that can be edited and displayed.
void | setMaximum(Comparable max) Sets the maximum permissible value.
void | setMinimum(Comparable minimum) Sets the minimum permissible value.
Object | stringToValue(String text) Returns the Object representation of the String text.
String | valueToString(Object value) Returns a String representation of the Object value.
Methods inherited from class javax.swing.text.DefaultFormatter
getAllowsInvalid, getCommitsOnValidEdit, getDocumentFilter, getNavigationFilter, getOverwriteMode, getValueClass, setAllowsInvalid, setCommitsOnValidEdit, setOverwriteMode, setValueClass
Methods inherited from class javax.swing.JFormattedTextField.AbstractFormatter
getFormattedTextField, invalidEdit, setEditValid, uninstall
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

InternationalFormatter

public InternationalFormatter()
Creates an InternationalFormatter with no Format specified.

InternationalFormatter

public InternationalFormatter(Format format)
Creates an InternationalFormatter with the specified Format instance.

Parameters:
format - Format instance used for converting from/to Strings
Method Detail

setFormat

public void setFormat(Format format)
Sets the format that dictates the legal values that can be edited and displayed.

Parameters:
format - Format instance used for converting from/to Strings

getFormat

public Format getFormat()
Returns the format that dictates the legal values that can be edited and displayed.

Returns:
Format instance used for converting from/to Strings

setMinimum

public void setMinimum(Comparable minimum)
Sets the minimum permissible value. If the valueClass has not been specified, and minimum is non null, the valueClass will be set to that of the class of minimum.

Parameters:
minimum - Minimum legal value that can be input
See Also:
DefaultFormatter.setValueClass(java.lang.Class)

getMinimum

public Comparable getMinimum()
Returns the minimum permissible value.

Returns:
Minimum legal value that can be input

setMaximum

public void setMaximum(Comparable max)
Sets the maximum permissible value. If the valueClass has not been specified, and max is non null, the valueClass will be set to that of the class of max.

Parameters:
max - Maximum legal value that can be input
See Also:
DefaultFormatter.setValueClass(java.lang.Class)

getMaximum

public Comparable getMaximum()
Returns the maximum permissible value.

Returns:
Maximum legal value that can be input

install

public void install(JFormattedTextField ftf)
Installs the DefaultFormatter onto a particular JFormattedTextField. This will invoke valueToString to convert the current value from the JFormattedTextField to a String. This will then install the Actions from getActions, the DocumentFilter returned from getDocumentFilter and the NavigationFilter returned from getNavigationFilter onto the JFormattedTextField.

Subclasses will typically only need to override this if they wish to install additional listeners on the JFormattedTextField.

If there is a ParseException in converting the current value to a String, this will set the text to an empty String, and mark the JFormattedTextField as being in an invalid state.

While this is a public method, this is typically only useful for subclassers of JFormattedTextField. JFormattedTextField will invoke this method at the appropriate times when the value changes, or its internal state changes.

Overrides:
install in class DefaultFormatter
Parameters:
ftf - JFormattedTextField to format for, may be null indicating uninstall from current JFormattedTextField.

valueToString

public String valueToString(Object value)
                     throws ParseException
Returns a String representation of the Object value. This invokes format on the current Format.

Overrides:
valueToString in class DefaultFormatter
Parameters:
value - Value to convert
Returns:
String representation of value
Throws:
ParseException - if there is an error in the conversion

stringToValue

public Object stringToValue(String text)
                     throws ParseException
Returns the Object representation of the String text.

Overrides:
stringToValue in class DefaultFormatter
Parameters:
text - String to convert
Returns:
Object representation of text
Throws:
ParseException - if there is an error in the conversion

getFields

public Format.Field[] getFields(int offset)
Returns the Format.Field constants associated with the text at offset. If offset is not a valid location into the current text, this will return an empty array.

Parameters:
offset - offset into text to be examined
Returns:
Format.Field constants associated with the text at the given position.

clone

public Object clone()
             throws CloneNotSupportedException
Creates a copy of the DefaultFormatter.

Overrides:
clone in class DefaultFormatter
Returns:
copy of the DefaultFormatter
Throws:
CloneNotSupportedException

getActions

protected Action[] getActions()
If getSupportsIncrement returns true, this returns two Actions suitable for incrementing/decrementing the value.

Overrides:
getActions in class JFormattedTextField.AbstractFormatter
Returns:
Array of Actions to install on JFormattedTextField
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


JTextComponent (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class JTextComponent

java.lang.Object
    extended by java.awt.Component
        extended by java.awt.Container
            extended by javax.swing.JComponent
                extended by javax.swing.text.JTextComponent
All Implemented Interfaces:
Accessible, ImageObserver, MenuContainer, Scrollable, Serializable
Direct Known Subclasses:
JEditorPane, JTextArea, JTextField
public abstract class JTextComponent
extends JComponent
implements Scrollable, Accessible

JTextComponent is the base class for swing text components. It tries to be compatible with the java.awt.TextComponent class where it can reasonably do so. Also provided are other services for additional flexibility (beyond the pluggable UI and bean support). You can find information on how to use the functionality this class provides in General Rules for Using Text Components, a section in The Java Tutorial.

Caret Changes
The caret is a pluggable object in swing text components. Notification of changes to the caret position and the selection are sent to implementations of the CaretListener interface that have been registered with the text component. The UI will install a default caret unless a customized caret has been set.

Commands
Text components provide a number of commands that can be used to manipulate the component. This is essentially the way that the component expresses its capabilities. These are expressed in terms of the swing Action interface, using the TextAction implementation. The set of commands supported by the text component can be found with the getActions() method. These actions can be bound to key events, fired from buttons, etc.

Text Input
The text components support flexible and internationalized text input, using keymaps and the input method framework, while maintaining compatibility with the AWT listener model.

A Keymap lets an application bind key strokes to actions. In order to allow keymaps to be shared across multiple text components, they can use actions that extend TextAction. TextAction can determine which JTextComponent most recently has or had focus and therefore is the subject of the action (In the case that the ActionEvent sent to the action doesn't contain the target text component as its source).

The input method framework lets text components interact with input methods, separate software components that preprocess events to let users enter thousands of different characters using keyboards with far fewer keys. JTextComponent is an active client of the framework, so it implements the preferred user interface for interacting with input methods. As a consequence, some key events do not reach the text component because they are handled by an input method, and some text input reaches the text component as committed text within an InputMethodEvent instead of as a key event. The complete text input is the combination of the characters in keyTyped key events and committed text in input method events.

The AWT listener model lets applications attach event listeners to components in order to bind events to actions. Swing encourages the use of keymaps instead of listeners, but maintains compatibility with listeners by giving the listeners a chance to steal an event by consuming it.

Keyboard event and input method events are handled in the following stages, with each stage capable of consuming the event:

Stage

KeyEvent

InputMethodEvent

1. | input methods | (generated here)
2. | focus manager
3. | registered key listeners | registered input method listeners
4. | input method handling in JTextComponent
5. | keymap handling using the current keymap
6. | keyboard handling in JComponent (e.g. accelerators, component navigation, etc.)

To maintain compatibility with applications that listen to key events but are not aware of input method events, the input method handling in stage 4 provides a compatibility mode for components that do not process input method events. For these components, the committed text is converted to keyTyped key events and processed in the key event pipeline starting at stage 3 instead of in the input method event pipeline.

By default the component will create a keymap (named DEFAULT_KEYMAP) that is shared by all JTextComponent instances as the default keymap. Typically a look-and-feel implementation will install a different keymap that resolves to the default keymap for those bindings not found in the different keymap. The minimal bindings include:

  • inserting content into the editor for the printable keys.
  • removing content with the backspace and del keys.
  • caret movement forward and backward

Model/View Split
The text components have a model-view split. A text component pulls together the objects used to represent the model, view, and controller. The text document model may be shared by other views which act as observers of the model (e.g. a document may be shared by multiple components).

Diagram showing interaction between Controller, Document, events, and ViewFactory

The model is defined by the Document interface. This is intended to provide a flexible text storage mechanism that tracks change during edits and can be extended to more sophisticated models. The model interfaces are meant to capture the capabilities of expression given by SGML, a system used to express a wide variety of content. Each modification to the document causes notification of the details of the change to be sent to all observers in the form of a DocumentEvent which allows the views to stay up to date with the model. This event is sent to observers that have implemented the DocumentListener interface and registered interest with the model being observed.

Location Information
The capability of determining the location of text in the view is provided. There are two methods, modelToView(int) and viewToModel(java.awt.Point) for determining this information.

Undo/Redo support
Support for an edit history mechanism is provided to allow undo/redo operations. The text component does not itself provide the history buffer by default, but does provide the UndoableEdit records that can be used in conjunction with a history buffer to provide the undo/redo support. The support is provided by the Document model, which allows one to attach UndoableEditListener implementations.

Thread Safety
The swing text components provide some support of thread safe operations. Because of the high level of configurability of the text components, it is possible to circumvent the protection provided. The protection primarily comes from the model, so the documentation of AbstractDocument describes the assumptions of the protection provided. The methods that are safe to call asynchronously are marked with comments.

Newlines
For a discussion on how newlines are handled, see DefaultEditorKit.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

See Also:
Document, DocumentEvent, DocumentListener, Caret, CaretEvent, CaretListener, TextUI, View, ViewFactory

Nested Class Summary
class | JTextComponent.AccessibleJTextComponent This class implements accessibility support for the JTextComponent class.
static class | JTextComponent.KeyBinding Binding record for creating key bindings.
Nested classes inherited from class javax.swing.JComponent
JComponent.AccessibleJComponent
Nested classes inherited from class java.awt.Container
Container.AccessibleAWTContainer
Nested classes inherited from class java.awt.Component
Component.AccessibleAWTComponent, Component.BltBufferStrategy, Component.FlipBufferStrategy
Field Summary
static String | DEFAULT_KEYMAP The default keymap that will be shared by all JTextComponent instances unless they have had a different keymap set.
static String | FOCUS_ACCELERATOR_KEY The bound property name for the focus accelerator.
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
Constructor Summary
JTextComponent()
Creates a new JTextComponent.
Method Summary
void | addCaretListener(CaretListener listener) Adds a caret listener for notification of any changes to the caret.
void | addInputMethodListener(InputMethodListener l) Adds the specified input method listener to receive input method events from this component.
static Keymap | addKeymap(String nm, Keymap parent) Adds a new keymap into the keymap hierarchy.
void | copy() Transfers the currently selected range in the associated text model to the system clipboard, leaving the contents in the text model.
void | cut() Transfers the currently selected range in the associated text model to the system clipboard, removing the contents from the model.
protected void | fireCaretUpdate(CaretEvent e) Notifies all listeners that have registered interest for notification on this event type.
AccessibleContext | getAccessibleContext() Gets the AccessibleContext associated with this JTextComponent.
Action[] | getActions() Fetches the command list for the editor.
Caret | getCaret() Fetches the caret that allows text-oriented navigation over the view.
Color | getCaretColor() Fetches the current color used to render the caret.
CaretListener[] | getCaretListeners() Returns an array of all the caret listeners registered on this text component.
int | getCaretPosition() Returns the position of the text insertion caret for the text component.
Color | getDisabledTextColor() Fetches the current color used to render the selected text.
Document | getDocument() Fetches the model associated with the editor.
boolean | getDragEnabled() Gets the dragEnabled property.
char | getFocusAccelerator() Returns the key accelerator that will cause the receiving text component to get the focus.
Highlighter | getHighlighter() Fetches the object responsible for making highlights.
InputMethodRequests | getInputMethodRequests() Gets the input method request handler which supports requests from input methods for this component.
Keymap | getKeymap() Fetches the keymap currently active in this text component.
static Keymap | getKeymap(String nm) Fetches a named keymap previously added to the document.
Insets | getMargin() Returns the margin between the text component's border and its text.
NavigationFilter | getNavigationFilter() Returns the NavigationFilter.
Dimension | getPreferredScrollableViewportSize() Returns the preferred size of the viewport for a view component.
int | getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) Components that display logical rows or columns should compute the scroll increment that will completely expose one block of rows or columns, depending on the value of orientation.
boolean | getScrollableTracksViewportHeight() Returns true if a viewport should always force the height of this Scrollable to match the height of the viewport.
boolean | getScrollableTracksViewportWidth() Returns true if a viewport should always force the width of this Scrollable to match the width of the viewport.
int | getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) Components that display logical rows or columns should compute the scroll increment that will completely expose one new row or column, depending on the value of orientation.
String | getSelectedText() Returns the selected text contained in this TextComponent.
Color | getSelectedTextColor() Fetches the current color used to render the selected text.
Color | getSelectionColor() Fetches the current color used to render the selection.
int | getSelectionEnd() Returns the selected text's end position.
int | getSelectionStart() Returns the selected text's start position.
String | getText() Returns the text contained in this TextComponent.
String | getText(int offs, int len) Fetches a portion of the text represented by the component.
String | getToolTipText(MouseEvent event) Returns the string to be used as the tooltip for event.
TextUI | getUI() Fetches the user-interface factory for this text-oriented editor.
boolean | isEditable() Returns the boolean indicating whether this TextComponent is editable or not.
static void | loadKeymap(Keymap map, JTextComponent.KeyBinding[] bindings, Action[] actions) Loads a keymap with a bunch of bindings.
Rectangle | modelToView(int pos) Converts the given location in the model to a place in the view coordinate system.
void | moveCaretPosition(int pos) Moves the caret to a new position, leaving behind a mark defined by the last time setCaretPosition was called.
protected String | paramString() Returns a string representation of this JTextComponent.
void | paste() Transfers the contents of the system clipboard into the associated text model.
protected void | processInputMethodEvent(InputMethodEvent e) Processes input method events occurring on this component by dispatching them to any registered InputMethodListener objects.
void | read(Reader in, Object desc) Initializes from a stream.
void | removeCaretListener(CaretListener listener) Removes a caret listener.
static Keymap | removeKeymap(String nm) Removes a named keymap previously added to the document.
void | removeNotify() Notifies this component that it no longer has a parent component.
void | replaceSelection(String content) Replaces the currently selected content with new content represented by the given string.
void | select(int selectionStart, int selectionEnd) Selects the text between the specified start and end positions.
void | selectAll() Selects all the text in the TextComponent.
void | setCaret(Caret c) Sets the caret to be used.
void | setCaretColor(Color c) Sets the current color used to render the caret.
void | setCaretPosition(int position) Sets the position of the text insertion caret for the TextComponent.
void | setComponentOrientation(ComponentOrientation o) Sets the language-sensitive orientation that is to be used to order the elements or text within this component.
void | setDisabledTextColor(Color c) Sets the current color used to render the disabled text.
void | setDocument(Document doc) Associates the editor with a text document.
void | setDragEnabled(boolean b) Sets the dragEnabled property, which must be true to enable automatic drag handling (the first part of drag and drop) on this component.
void | setEditable(boolean b) Sets the specified boolean to indicate whether or not this TextComponent should be editable.
void | setFocusAccelerator(char aKey) Sets the key accelerator that will cause the receiving text component to get the focus.
void | setHighlighter(Highlighter h) Sets the highlighter to be used.
void | setKeymap(Keymap map) Sets the keymap to use for binding events to actions.
void | setMargin(Insets m) Sets margin space between the text component's border and its text.
void | setNavigationFilter(NavigationFilter filter) Sets the NavigationFilter.
void | setSelectedTextColor(Color c) Sets the current color used to render the selected text.
void | setSelectionColor(Color c) Sets the current color used to render the selection.
void | setSelectionEnd(int selectionEnd) Sets the selection end to the specified position.
void | setSelectionStart(int selectionStart) Sets the selection start to the specified position.
void | setText(String t) Sets the text of this TextComponent to the specified text.
void | setUI(TextUI ui) Sets the user-interface factory for this text-oriented editor.
void | updateUI() Reloads the pluggable UI.
int | viewToModel(Point pt) Converts the given place in the view coordinate system to the nearest representative location in the model.
void | write(Writer out) Stores the contents of the model into the given stream.
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addPropertyChangeListener, addPropertyChangeListener, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBorder, getBounds, getClientProperty, getComponentGraphics, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getGraphics, getHeight, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPreferredSize, getPropertyChangeListeners, getPropertyChangeListeners, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getTopLevelAncestor, getTransferHandler, getUIClassID, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isMaximumSizeSet, isMinimumSizeSet, isOpaque, isOptimizedDrawingEnabled, isPaintingTile, isPreferredSizeSet, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removePropertyChangeListener, removePropertyChangeListener, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFont, setForeground, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setFocusCycleRoot, setFocusTraversalKeys, setFocusTraversalPolicy, setLayout, transferFocusBackward, transferFocusDownCycle, validate, validateTree
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getFontMetrics, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMouseWheelListeners, getName, getParent, getPeer, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processMouseEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

FOCUS_ACCELERATOR_KEY

public static final String FOCUS_ACCELERATOR_KEY
The bound property name for the focus accelerator.

See Also:
Constant Field Values

DEFAULT_KEYMAP

public static final String DEFAULT_KEYMAP
The default keymap that will be shared by all JTextComponent instances unless they have had a different keymap set.

See Also:
Constant Field Values
Constructor Detail

JTextComponent

public JTextComponent()
Creates a new JTextComponent. Listeners for caret events are established, and the pluggable UI installed. The component is marked as editable. No layout manager is used, because layout is managed by the view subsystem of text. The document model is set to null.

Method Detail

getUI

public TextUI getUI()
Fetches the user-interface factory for this text-oriented editor.

Returns:
the factory

setUI

public void setUI(TextUI ui)
Sets the user-interface factory for this text-oriented editor.

Parameters:
ui - the factory

updateUI

public void updateUI()
Reloads the pluggable UI. The key used to fetch the new interface is getUIClassID(). The type of the UI is TextUI. invalidate is called after setting the UI.

Overrides:
updateUI in class JComponent
See Also:
JComponent.setUI(javax.swing.plaf.ComponentUI),
UIManager.getLookAndFeel(),
UIManager.getUI(javax.swing.JComponent)

addCaretListener

public void addCaretListener(CaretListener listener)
Adds a caret listener for notification of any changes to the caret.

Parameters:
listener - the listener to be added
See Also:
CaretEvent

removeCaretListener

public void removeCaretListener(CaretListener listener)
Removes a caret listener.

Parameters:
listener - the listener to be removed
See Also:
CaretEvent

getCaretListeners

public CaretListener[] getCaretListeners()
Returns an array of all the caret listeners registered on this text component.

Returns:
all of this component's CaretListeners or an empty array if no caret listeners are currently registered
Since:
1.4
See Also:
addCaretListener(javax.swing.event.CaretListener), removeCaretListener(javax.swing.event.CaretListener)

fireCaretUpdate

protected void fireCaretUpdate(CaretEvent e)
Notifies all listeners that have registered interest for notification on this event type. The event instance is lazily created using the parameters passed into the fire method. The listener list is processed in a last-to-first manner.

Parameters:
e - the event
See Also:
EventListenerList

setDocument

public void setDocument(Document doc)
Associates the editor with a text document. The currently registered factory is used to build a view for the document, which gets displayed by the editor after revalidation. A PropertyChange event ("document") is propagated to each listener.

Parameters:
doc - the document to display/edit
See Also:
getDocument()

getDocument

public Document getDocument()
Fetches the model associated with the editor. This is primarily for the UI to get at the minimal amount of state required to be a text editor. Subclasses will return the actual type of the model which will typically be something that extends Document.

Returns:
the model

setComponentOrientation

public void setComponentOrientation(ComponentOrientation o)
Description copied from class: Component
Sets the language-sensitive orientation that is to be used to order the elements or text within this component. Language-sensitive LayoutManager and Component subclasses will use this property to determine how to lay out and draw components.

At construction time, a component's orientation is set to ComponentOrientation.UNKNOWN, indicating that it has not been specified explicitly. The UNKNOWN orientation behaves the same as ComponentOrientation.LEFT_TO_RIGHT.

To set the orientation of a single component, use this method. To set the orientation of an entire component hierarchy, use applyComponentOrientation.

Overrides:
setComponentOrientation in class Component
See Also:
ComponentOrientation

getActions

public Action[] getActions()
Fetches the command list for the editor. This is the list of commands supported by the plugged-in UI augmented by the collection of commands that the editor itself supports. These are useful for binding to events, such as in a keymap.

Returns:
the command list

setMargin

public void setMargin(Insets m)
Sets margin space between the text component's border and its text. The text component's default Border object will use this value to create the proper margin. However, if a non-default border is set on the text component, it is that Border object's responsibility to create the appropriate margin space (else this property will effectively be ignored). This causes a redraw of the component. A PropertyChange event ("margin") is sent to all listeners.

Parameters:
m - the space between the border and the text

getMargin

public Insets getMargin()
Returns the margin between the text component's border and its text.

Returns:
the margin

setNavigationFilter

public void setNavigationFilter(NavigationFilter filter)
Sets the NavigationFilter. NavigationFilter is used by DefaultCaret and the default cursor movement actions as a way to restrict the cursor movement.

Since:
1.4

getNavigationFilter

public NavigationFilter getNavigationFilter()
Returns the NavigationFilter. NavigationFilter is used by DefaultCaret and the default cursor movement actions as a way to restrict the cursor movement. A null return value implies the cursor movement and selection should not be restricted.

Returns:
the NavigationFilter
Since:
1.4

getCaret

public Caret getCaret()
Fetches the caret that allows text-oriented navigation over the view.

Returns:
the caret

setCaret

public void setCaret(Caret c)
Sets the caret to be used. By default this will be set by the UI that gets installed. This can be changed to a custom caret if desired. Setting the caret results in a PropertyChange event ("caret") being fired.

Parameters:
c - the caret
See Also:
getCaret()

getHighlighter

public Highlighter getHighlighter()
Fetches the object responsible for making highlights.

Returns:
the highlighter

setHighlighter

public void setHighlighter(Highlighter h)
Sets the highlighter to be used. By default this will be set by the UI that gets installed. This can be changed to a custom highlighter if desired. The highlighter can be set to null to disable it. A PropertyChange event ("highlighter") is fired when a new highlighter is installed.

Parameters:
h - the highlighter
See Also:
getHighlighter()

setKeymap

public void setKeymap(Keymap map)
Sets the keymap to use for binding events to actions. Setting to null effectively disables keyboard input. A PropertyChange event ("keymap") is fired when a new keymap is installed.

Parameters:
map - the keymap
See Also:
getKeymap()

setDragEnabled

public void setDragEnabled(boolean b)
Sets the dragEnabled property, which must be true to enable automatic drag handling (the first part of drag and drop) on this component. The transferHandler property needs to be set to a non-null value for the drag to do anything. The default value of the dragEnabled property is false.

When automatic drag handling is enabled, most look and feels begin a drag-and-drop operation whenever the user presses the mouse button over a selection and then moves the mouse a few pixels. Setting this property to true can therefore have a subtle effect on how selections behave.

Some look and feels might not support automatic drag and drop; they will ignore this property. You can work around such look and feels by modifying the component to directly call the exportAsDrag method of a TransferHandler.

Parameters:
b - the value to set the dragEnabled property to
Throws:
HeadlessException - if b is true and GraphicsEnvironment.isHeadless() returns true
Since:
1.4
See Also:
GraphicsEnvironment.isHeadless(),
getDragEnabled(),
JComponent.setTransferHandler(javax.swing.TransferHandler),
TransferHandler

getDragEnabled

public boolean getDragEnabled()
Gets the dragEnabled property.

Returns:
the value of the dragEnabled property
Since:
1.4
See Also:
setDragEnabled(boolean)

getKeymap

public Keymap getKeymap()
Fetches the keymap currently active in this text component.

Returns:
the keymap

addKeymap

public static Keymap addKeymap(String nm,
                               Keymap parent)
Adds a new keymap into the keymap hierarchy. Keymap bindings resolve from bottom up so an attribute specified in a child will override an attribute specified in the parent.

Parameters:
nm - the name of the keymap (must be unique within the collection of named keymaps in the document); the name may be null if the keymap is unnamed, but the caller is responsible for managing the reference returned as an unnamed keymap can't be fetched by name
parent - the parent keymap; this may be null if unspecified bindings need not be resolved in some other keymap
Returns:
the keymap

removeKeymap

public static Keymap removeKeymap(String nm)
Removes a named keymap previously added to the document. Keymaps with null names may not be removed in this way.

Parameters:
nm - the name of the keymap to remove
Returns:
the keymap that was removed

getKeymap

public static Keymap getKeymap(String nm)
Fetches a named keymap previously added to the document. This does not work with null-named keymaps.

Parameters:
nm - the name of the keymap
Returns:
the keymap

loadKeymap

public static void loadKeymap(Keymap map,
                              JTextComponent.KeyBinding[] bindings,
                              Action[] actions)

Loads a keymap with a bunch of bindings. This can be used to take a static table of definitions and load them into some keymap. The following example illustrates an example of binding some keys to the cut, copy, and paste actions associated with a JTextComponent. A code fragment to accomplish this might look as follows:

   static final JTextComponent.KeyBinding[] defaultBindings = {
     new JTextComponent.KeyBinding(
       KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK),
       DefaultEditorKit.copyAction),
     new JTextComponent.KeyBinding(
       KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.CTRL_MASK),
       DefaultEditorKit.pasteAction),
     new JTextComponent.KeyBinding(
       KeyStroke.getKeyStroke(KeyEvent.VK_X, InputEvent.CTRL_MASK),
       DefaultEditorKit.cutAction),
   };

   JTextComponent c = new JTextPane();
   Keymap k = c.getKeymap();
   JTextComponent.loadKeymap(k, defaultBindings, c.getActions());
The sets of bindings and actions may be empty but must be non-null.

Parameters:
map - the keymap
bindings - the bindings
actions - the set of actions

getCaretColor

public Color getCaretColor()
Fetches the current color used to render the caret.

Returns:
the color

setCaretColor

public void setCaretColor(Color c)
Sets the current color used to render the caret. Setting to null effectively restores the default color. Setting the color results in a PropertyChange event ("caretColor") being fired.

Parameters:
c - the color
See Also:
getCaretColor()

getSelectionColor

public Color getSelectionColor()
Fetches the current color used to render the selection.

Returns:
the color

setSelectionColor

public void setSelectionColor(Color c)
Sets the current color used to render the selection. Setting the color to null is the same as setting Color.white. Setting the color results in a PropertyChange event ("selectionColor").

Parameters:
c - the color
See Also:
getSelectionColor()

getSelectedTextColor

public Color getSelectedTextColor()
Fetches the current color used to render the selected text.

Returns:
the color

setSelectedTextColor

public void setSelectedTextColor(Color c)
Sets the current color used to render the selected text. Setting the color to null is the same as Color.black. Setting the color results in a PropertyChange event ("selectedTextColor") being fired.

Parameters:
c - the color
See Also:
getSelectedTextColor()

getDisabledTextColor

public Color getDisabledTextColor()
Fetches the current color used to render the selected text.

Returns:
the color

setDisabledTextColor

public void setDisabledTextColor(Color c)
Sets the current color used to render the disabled text. Setting the color fires off a PropertyChange event ("disabledTextColor").

Parameters:
c - the color
See Also:
getDisabledTextColor()

replaceSelection

public void replaceSelection(String content)
Replaces the currently selected content with new content represented by the given string. If there is no selection this amounts to an insert of the given text. If there is no replacement text this amounts to a removal of the current selection.

This is the method that is used by the default implementation of the action for inserting content that gets bound to the keymap actions.

This method is thread safe, although most Swing methods are not. Please see Threads and Swing for more information.

Parameters:
content - the content to replace the selection with

getText

public String getText(int offs,
                      int len)
               throws BadLocationException
Fetches a portion of the text represented by the component. Returns an empty string if length is 0.

Parameters:
offs - the offset >= 0
len - the length >= 0
Returns:
the text
Throws:
BadLocationException - if the offset or length are invalid

modelToView

public Rectangle modelToView(int pos)
                      throws BadLocationException
Converts the given location in the model to a place in the view coordinate system. The component must have a positive size for this translation to be computed (i.e. layout cannot be computed until the component has been sized). The component does not have to be visible or painted.

Parameters:
pos - the position >= 0
Returns:
the coordinates as a rectangle, with (r.x, r.y) as the location in the coordinate system, or null if the component does not yet have a positive size.
Throws:
BadLocationException - if the given position does not represent a valid location in the associated document
See Also:
TextUI.modelToView(javax.swing.text.JTextComponent, int)

viewToModel

public int viewToModel(Point pt)
Converts the given place in the view coordinate system to the nearest representative location in the model. The component must have a positive size for this translation to be computed (i.e. layout cannot be computed until the component has been sized). The component does not have to be visible or painted.

Parameters:
pt - the location in the view to translate
Returns:
the offset >= 0 from the start of the document, or -1 if the component does not yet have a positive size.
See Also:
TextUI.viewToModel(javax.swing.text.JTextComponent, java.awt.Point)

cut

public void cut()
Transfers the currently selected range in the associated text model to the system clipboard, removing the contents from the model. The current selection is reset. Does nothing for null selections.

See Also:
Toolkit.getSystemClipboard(), Clipboard

copy

public void copy()
Transfers the currently selected range in the associated text model to the system clipboard, leaving the contents in the text model. The current selection remains intact. Does nothing for null selections.

See Also:
Toolkit.getSystemClipboard(), Clipboard

paste

public void paste()
Transfers the contents of the system clipboard into the associated text model. If there is a selection in the associated view, it is replaced with the contents of the clipboard. If there is no selection, the clipboard contents are inserted in front of the current insert position in the associated view. If the clipboard is empty, does nothing.

See Also:
replaceSelection(java.lang.String), Toolkit.getSystemClipboard(), Clipboard

moveCaretPosition

public void moveCaretPosition(int pos)
Moves the caret to a new position, leaving behind a mark defined by the last time setCaretPosition was called. This forms a selection. If the document is null, does nothing. The position must be between 0 and the length of the component's text or else an exception is thrown.

Parameters:
pos - the position
Throws:
IllegalArgumentException - if the value supplied for position is less than zero or greater than the component's text length
See Also:
setCaretPosition(int)

setFocusAccelerator

public void setFocusAccelerator(char aKey)
Sets the key accelerator that will cause the receiving text component to get the focus. The accelerator will be the key combination of the alt key and the character given (converted to upper case). By default, there is no focus accelerator key. Any previous key accelerator setting will be superseded. A '\0' key setting will be registered, and has the effect of turning off the focus accelerator. When the new key is set, a PropertyChange event (FOCUS_ACCELERATOR_KEY) will be fired.

Parameters:
aKey - the key
See Also:
getFocusAccelerator()

getFocusAccelerator

public char getFocusAccelerator()
Returns the key accelerator that will cause the receiving text component to get the focus. Return '\0' if no focus accelerator has been set.

Returns:
the key

read

public void read(Reader in,
                 Object desc)
          throws IOException
Initializes from a stream. This creates a model of the type appropriate for the component and initializes the model from the stream. By default this will load the model as plain text. Previous contents of the model are discarded.

Parameters:
in - the stream to read from
desc - an object describing the stream; this might be a string, a File, a URL, etc. Some kinds of documents (such as html for example) might be able to make use of this information; if non-null, it is added as a property of the document
Throws:
IOException - as thrown by the stream being used to initialize
See Also:
EditorKit.createDefaultDocument(), setDocument(javax.swing.text.Document), PlainDocument

write

public void write(Writer out)
           throws IOException
Stores the contents of the model into the given stream. By default this will store the model as plain text.

Parameters:
out - the output stream
Throws:
IOException - on any I/O error

removeNotify

public void removeNotify()
Description copied from class: JComponent
Notifies this component that it no longer has a parent component. When this method is invoked, any KeyboardActions set up in the the chain of parent components are removed.

Overrides:
removeNotify in class JComponent
See Also:
JComponent.registerKeyboardAction(java.awt.event.ActionListener, java.lang.String, javax.swing.KeyStroke, int)

setCaretPosition

public void setCaretPosition(int position)
Sets the position of the text insertion caret for the TextComponent. Note that the caret tracks change, so this may move if the underlying text of the component is changed. If the document is null, does nothing. The position must be between 0 and the length of the component's text or else an exception is thrown.

Parameters:
position - the position
Throws:
IllegalArgumentException - if the value supplied for position is less than zero or greater than the component's text length

getCaretPosition

public int getCaretPosition()
Returns the position of the text insertion caret for the text component.

Returns:
the position of the text insertion caret for the text component >= 0

setText

public void setText(String t)
Sets the text of this TextComponent to the specified text. If the text is null or empty, has the effect of simply deleting the old text. When text has been inserted, the resulting caret location is determined by the implementation of the caret class.

This method is thread safe, although most Swing methods are not. Please see Threads and Swing for more information.

Parameters:
t - the new text to be set
See Also:
getText(int, int), DefaultCaret

getText

public String getText()
Returns the text contained in this TextComponent. If the underlying document is null, will give a NullPointerException.

Returns:
the text
Throws:
NullPointerException - if the document is null
See Also:
setText(java.lang.String)

getSelectedText

public String getSelectedText()
Returns the selected text contained in this TextComponent. If the selection is null or the document empty, returns null.

Returns:
the text
Throws:
IllegalArgumentException - if the selection doesn't have a valid mapping into the document for some reason
See Also:
setText(java.lang.String)

isEditable

public boolean isEditable()
Returns the boolean indicating whether this TextComponent is editable or not.

Returns:
the boolean value
See Also:
setEditable(boolean)

setEditable

public void setEditable(boolean b)
Sets the specified boolean to indicate whether or not this TextComponent should be editable. A PropertyChange event ("editable") is fired when the state is changed.

Parameters:
b - the boolean to be set
See Also:
isEditable()

getSelectionStart

public int getSelectionStart()
Returns the selected text's start position. Return 0 for an empty document, or the value of dot if no selection.

Returns:
the start position >= 0

setSelectionStart

public void setSelectionStart(int selectionStart)
Sets the selection start to the specified position. The new starting point is constrained to be before or at the current selection end.

This is available for backward compatibility to code that called this method on java.awt.TextComponent. This is implemented to forward to the Caret implementation which is where the actual selection is maintained.

Parameters:
selectionStart - the start position of the text >= 0

getSelectionEnd

public int getSelectionEnd()
Returns the selected text's end position. Return 0 if the document is empty, or the value of dot if there is no selection.

Returns:
the end position >= 0

setSelectionEnd

public void setSelectionEnd(int selectionEnd)
Sets the selection end to the specified position. The new end point is constrained to be at or after the current selection start.

This is available for backward compatibility to code that called this method on java.awt.TextComponent. This is implemented to forward to the Caret implementation which is where the actual selection is maintained.

Parameters:
selectionEnd - the end position of the text >= 0

select

public void select(int selectionStart,
                   int selectionEnd)
Selects the text between the specified start and end positions.

This method sets the start and end positions of the selected text, enforcing the restriction that the start position must be greater than or equal to zero. The end position must be greater than or equal to the start position, and less than or equal to the length of the text component's text.

If the caller supplies values that are inconsistent or out of bounds, the method enforces these constraints silently, and without failure. Specifically, if the start position or end position is greater than the length of the text, it is reset to equal the text length. If the start position is less than zero, it is reset to zero, and if the end position is less than the start position, it is reset to the start position.

This call is provided for backward compatibility. It is routed to a call to setCaretPosition followed by a call to moveCaretPosition. The preferred way to manage selection is by calling those methods directly.

Parameters:
selectionStart - the start position of the text
selectionEnd - the end position of the text
See Also:
setCaretPosition(int), moveCaretPosition(int)

selectAll

public void selectAll()
Selects all the text in the TextComponent. Does nothing on a null or empty document.

getToolTipText

public String getToolTipText(MouseEvent event)
Returns the string to be used as the tooltip for event. This will return one of:
  1. If setToolTipText has been invoked with a non-null value, it will be returned, otherwise
  2. The value from invoking getToolTipText on the UI will be returned.
By default JTextComponent does not register itself with the ToolTipManager. This means that tooltips will NOT be shown from the TextUI unless registerComponent has been invoked on the ToolTipManager.

Overrides:
getToolTipText in class JComponent
Parameters:
event - the event in question
Returns:
the string to be used as the tooltip for event
See Also:
JComponent.setToolTipText(java.lang.String),
TextUI.getToolTipText(javax.swing.text.JTextComponent, java.awt.Point),
ToolTipManager.registerComponent(javax.swing.JComponent)

getPreferredScrollableViewportSize

public Dimension getPreferredScrollableViewportSize()
Returns the preferred size of the viewport for a view component. This is implemented to do the default behavior of returning the preferred size of the component.

Specified by:
getPreferredScrollableViewportSize in interface Scrollable
Returns:
the preferredSize of a JViewport whose view is this Scrollable
See Also:
JComponent.getPreferredSize()

getScrollableUnitIncrement

public int getScrollableUnitIncrement(Rectangle visibleRect,
                                      int orientation,
                                      int direction)
Components that display logical rows or columns should compute the scroll increment that will completely expose one new row or column, depending on the value of orientation. Ideally, components should handle a partially exposed row or column by returning the distance required to completely expose the item.

The default implementation of this is to simply return 10% of the visible area. Subclasses are likely to be able to provide a much more reasonable value.

Specified by:
getScrollableUnitIncrement in interface Scrollable
Parameters:
visibleRect - the view area visible within the viewport
orientation - either SwingConstants.VERTICAL or SwingConstants.HORIZONTAL
direction - less than zero to scroll up/left, greater than zero for down/right
Returns:
the "unit" increment for scrolling in the specified direction
Throws:
IllegalArgumentException - for an invalid orientation
See Also:
JScrollBar.setUnitIncrement(int)

getScrollableBlockIncrement

public int getScrollableBlockIncrement(Rectangle visibleRect,
                                       int orientation,
                                       int direction)
Components that display logical rows or columns should compute the scroll increment that will completely expose one block of rows or columns, depending on the value of orientation.

The default implementation of this is to simply return the visible area. Subclasses will likely be able to provide a much more reasonable value.

Specified by:
getScrollableBlockIncrement in interface Scrollable
Parameters:
visibleRect - the view area visible within the viewport
orientation - either SwingConstants.VERTICAL or SwingConstants.HORIZONTAL
direction - less than zero to scroll up/left, greater than zero for down/right
Returns:
the "block" increment for scrolling in the specified direction
Throws:
IllegalArgumentException - for an invalid orientation
See Also:
JScrollBar.setBlockIncrement(int)

getScrollableTracksViewportWidth

public boolean getScrollableTracksViewportWidth()
Returns true if a viewport should always force the width of this Scrollable to match the width of the viewport. For example a normal text view that supported line wrapping would return true here, since it would be undesirable for wrapped lines to disappear beyond the right edge of the viewport. Note that returning true for a Scrollable whose ancestor is a JScrollPane effectively disables horizontal scrolling.

Scrolling containers, like JViewport, will use this method each time they are validated.

Specified by:
getScrollableTracksViewportWidth in interface Scrollable
Returns:
true if a viewport should force the Scrollables width to match its own

getScrollableTracksViewportHeight

public boolean getScrollableTracksViewportHeight()
Returns true if a viewport should always force the height of this Scrollable to match the height of the viewport. For example a columnar text view that flowed text in left to right columns could effectively disable vertical scrolling by returning true here.

Scrolling containers, like JViewport, will use this method each time they are validated.

Specified by:
getScrollableTracksViewportHeight in interface Scrollable
Returns:
true if a viewport should force the Scrollables height to match its own

getAccessibleContext

public AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JTextComponent. For text components, the AccessibleContext takes the form of an AccessibleJTextComponent. A new AccessibleJTextComponent instance is created if necessary.

Specified by:
getAccessibleContext in interface Accessible
Overrides:
getAccessibleContext in class JComponent
Returns:
an AccessibleJTextComponent that serves as the AccessibleContext of this JTextComponent

paramString

protected String paramString()
Returns a string representation of this JTextComponent. This method is intended to be used only for debugging purposes, and the content and format of the returned string may vary between implementations. The returned string may be empty but may not be null.

Overriding paramString to provide information about the specific new aspects of the JFC components.

Overrides:
paramString in class JComponent
Returns:
a string representation of this JTextComponent

processInputMethodEvent

protected void processInputMethodEvent(InputMethodEvent e)
Description copied from class: Component
Processes input method events occurring on this component by dispatching them to any registered InputMethodListener objects.

This method is not called unless input method events are enabled for this component. Input method events are enabled when one of the following occurs:

  • An InputMethodListener object is registered via addInputMethodListener.
  • Input method events are enabled via enableEvents.

Note that if the event parameter is null the behavior is unspecified and may result in an exception.

Overrides:
processInputMethodEvent in class Component
Parameters:
e - the input method event
See Also:
InputMethodEvent, InputMethodListener, Component.addInputMethodListener(java.awt.event.InputMethodListener), Component.enableEvents(long)

getInputMethodRequests

public InputMethodRequests getInputMethodRequests()
Description copied from class: Component
Gets the input method request handler which supports requests from input methods for this component. A component that supports on-the-spot text input must override this method to return an InputMethodRequests instance. At the same time, it also has to handle input method events.

Overrides:
getInputMethodRequests in class Component
Returns:
the input method request handler for this component, null by default
See Also:
Component.addInputMethodListener(java.awt.event.InputMethodListener)

addInputMethodListener

public void addInputMethodListener(InputMethodListener l)
Description copied from class: Component
Adds the specified input method listener to receive input method events from this component. A component will only receive input method events from input methods if it also overrides getInputMethodRequests to return an InputMethodRequests instance. If listener l is null, no exception is thrown and no action is performed.

Overrides:
addInputMethodListener in class Component
Parameters:
l - the input method listener
See Also:
InputMethodEvent,
InputMethodListener,
Component.removeInputMethodListener(java.awt.event.InputMethodListener),
Component.getInputMethodListeners(),
Component.getInputMethodRequests()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


JTextComponent.AccessibleJTextComponent (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class JTextComponent.AccessibleJTextComponent

java.lang.Object
    extended by javax.accessibility.AccessibleContext
        extended by java.awt.Component.AccessibleAWTComponent
            extended by java.awt.Container.AccessibleAWTContainer
                extended by javax.swing.JComponent.AccessibleJComponent
                    extended by javax.swing.text.JTextComponent.AccessibleJTextComponent
All Implemented Interfaces:
AccessibleAction, AccessibleComponent, AccessibleEditableText, AccessibleExtendedComponent, AccessibleText, CaretListener, DocumentListener, EventListener, Serializable
Direct Known Subclasses:
JEditorPane.AccessibleJEditorPane, JTextArea.AccessibleJTextArea, JTextField.AccessibleJTextField
Enclosing class:
JTextComponent
public class JTextComponent.AccessibleJTextComponent
extends JComponent.AccessibleJComponent
implements AccessibleText, CaretListener, DocumentListener, AccessibleAction, AccessibleEditableText

This class implements accessibility support for the JTextComponent class. It provides an implementation of the Java Accessibility API appropriate to menu user-interface elements.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Nested Class Summary
Nested classes inherited from class javax.swing.JComponent.AccessibleJComponent
JComponent.AccessibleJComponent.AccessibleContainerHandler, JComponent.AccessibleJComponent.AccessibleFocusHandler
Nested classes inherited from class java.awt.Component.AccessibleAWTComponent
Component.AccessibleAWTComponent.AccessibleAWTComponentHandler, Component.AccessibleAWTComponent.AccessibleAWTFocusHandler
Field Summary
Fields inherited from class javax.swing.JComponent.AccessibleJComponent
accessibleContainerHandler, accessibleFocusHandler
Fields inherited from class java.awt.Component.AccessibleAWTComponent
accessibleAWTComponentHandler, accessibleAWTFocusHandler
Fields inherited from class javax.accessibility.AccessibleContext
ACCESSIBLE_ACTION_PROPERTY, ACCESSIBLE_ACTIVE_DESCENDANT_PROPERTY, ACCESSIBLE_CARET_PROPERTY, ACCESSIBLE_CHILD_PROPERTY, ACCESSIBLE_DESCRIPTION_PROPERTY, ACCESSIBLE_HYPERTEXT_OFFSET, ACCESSIBLE_NAME_PROPERTY, ACCESSIBLE_SELECTION_PROPERTY, ACCESSIBLE_STATE_PROPERTY, ACCESSIBLE_TABLE_CAPTION_CHANGED, ACCESSIBLE_TABLE_COLUMN_DESCRIPTION_CHANGED, ACCESSIBLE_TABLE_COLUMN_HEADER_CHANGED, ACCESSIBLE_TABLE_MODEL_CHANGED, ACCESSIBLE_TABLE_ROW_DESCRIPTION_CHANGED, ACCESSIBLE_TABLE_ROW_HEADER_CHANGED, ACCESSIBLE_TABLE_SUMMARY_CHANGED, ACCESSIBLE_TEXT_PROPERTY, ACCESSIBLE_VALUE_PROPERTY, ACCESSIBLE_VISIBLE_DATA_PROPERTY, accessibleDescription, accessibleName, accessibleParent
Fields inherited from interface javax.accessibility.AccessibleText
CHARACTER, SENTENCE, WORD
Constructor Summary
JTextComponent.AccessibleJTextComponent()
Constructs an AccessibleJTextComponent.
Method Summary
void | caretUpdate(CaretEvent e) Handles caret updates (fire appropriate property change event, which are AccessibleContext.ACCESSIBLE_CARET_PROPERTY and AccessibleContext.ACCESSIBLE_SELECTION_PROPERTY).
void | changedUpdate(DocumentEvent e) Handles document remove (fire appropriate property change event, which is AccessibleContext.ACCESSIBLE_TEXT_PROPERTY).
void | cut(int startIndex, int endIndex) Cuts the text between two indices into the system clipboard.
void | delete(int startIndex, int endIndex) Deletes the text between two indices
boolean | doAccessibleAction(int i) Performs the specified Action on the object
AccessibleAction | getAccessibleAction() Gets the AccessibleAction associated with this object that supports one or more actions.
int | getAccessibleActionCount() Returns the number of accessible actions available in this object If there are more than one, the first one is considered the "default" action of the object.
String | getAccessibleActionDescription(int i) Returns a description of the specified action of the object.
AccessibleEditableText | getAccessibleEditableText() Returns the AccessibleEditableText interface for this text component.
AccessibleRole | getAccessibleRole() Gets the role of this object.
AccessibleStateSet | getAccessibleStateSet() Gets the state set of the JTextComponent.
AccessibleText | getAccessibleText() Get the AccessibleText associated with this object.
String | getAfterIndex(int part, int index) Returns the String after a given index.
String | getAtIndex(int part, int index) Returns the String at a given index.
String | getBeforeIndex(int part, int index) Returns the String before a given index.
int | getCaretPosition() Returns the zero-based offset of the caret.
AttributeSet | getCharacterAttribute(int i) Returns the AttributeSet for a given character (at a given index).
Rectangle | getCharacterBounds(int i) Determines the bounding box of the character at the given index into the string.
int | getCharCount() Returns the number of characters (valid indices)
int | getIndexAtPoint(Point p) Given a point in local coordinates, return the zero-based index of the character under that Point.
String | getSelectedText() Returns the portion of the text that is selected.
int | getSelectionEnd() Returns the end offset within the selected text.
int | getSelectionStart() Returns the start offset within the selected text.
String | getTextRange(int startIndex, int endIndex) Returns the text string between two indices.
void | insertTextAtIndex(int index, String s) Inserts the specified string at the given index
void | insertUpdate(DocumentEvent e) Handles document insert (fire appropriate property change event which is AccessibleContext.ACCESSIBLE_TEXT_PROPERTY).
void | paste(int startIndex) Pastes the text from the system clipboard into the text starting at the specified index.
void | removeUpdate(DocumentEvent e) Handles document remove (fire appropriate property change event, which is AccessibleContext.ACCESSIBLE_TEXT_PROPERTY).
void | replaceText(int startIndex, int endIndex, String s) Replaces the text between two indices with the specified string.
void | selectText(int startIndex, int endIndex) Selects the text between two indices.
void | setAttributes(int startIndex, int endIndex, AttributeSet as) Sets attributes for the text between two indices.
void | setTextContents(String s) Sets the text contents to the specified string.
Methods inherited from class javax.swing.JComponent.AccessibleJComponent
addPropertyChangeListener, getAccessibleChild, getAccessibleChildrenCount, getAccessibleDescription, getAccessibleKeyBinding, getAccessibleName, getBorderTitle, getTitledBorderText, getToolTipText, removePropertyChangeListener
Methods inherited from class java.awt.Container.AccessibleAWTContainer
getAccessibleAt
Methods inherited from class java.awt.Component.AccessibleAWTComponent
addFocusListener, contains, getAccessibleComponent, getAccessibleIndexInParent, getAccessibleParent, getBackground, getBounds, getCursor, getFont, getFontMetrics, getForeground, getLocale, getLocation, getLocationOnScreen, getSize, isEnabled, isFocusTraversable, isShowing, isVisible, removeFocusListener, requestFocus, setBackground, setBounds, setCursor, setEnabled, setFont, setForeground, setLocation, setSize, setVisible
Methods inherited from class javax.accessibility.AccessibleContext
firePropertyChange, getAccessibleIcon, getAccessibleRelationSet, getAccessibleSelection, getAccessibleTable, getAccessibleValue, setAccessibleDescription, setAccessibleName, setAccessibleParent
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Methods inherited from interface javax.accessibility.AccessibleComponent
addFocusListener, contains, getAccessibleAt, getBackground, getBounds, getCursor, getFont, getFontMetrics, getForeground, getLocation, getLocationOnScreen, getSize, isEnabled, isFocusTraversable, isShowing, isVisible, removeFocusListener, requestFocus, setBackground, setBounds, setCursor, setEnabled, setFont, setForeground, setLocation, setSize, setVisible

Constructor Detail

JTextComponent.AccessibleJTextComponent

public JTextComponent.AccessibleJTextComponent()
Constructs an AccessibleJTextComponent. Adds a listener to track caret change.

Method Detail

caretUpdate

public void caretUpdate(CaretEvent e)
Handles caret updates (fire appropriate property change event, which are AccessibleContext.ACCESSIBLE_CARET_PROPERTY and AccessibleContext.ACCESSIBLE_SELECTION_PROPERTY). This keeps track of the dot position internally. When the caret moves, the internal position is updated after firing the event.

Specified by:
caretUpdate in interface CaretListener
Parameters:
e - the CaretEvent

insertUpdate

public void insertUpdate(DocumentEvent e)
Handles document insert (fire appropriate property change event which is AccessibleContext.ACCESSIBLE_TEXT_PROPERTY). This tracks the changed offset via the event.

Specified by:
insertUpdate in interface DocumentListener
Parameters:
e - the DocumentEvent

removeUpdate

public void removeUpdate(DocumentEvent e)
Handles document remove (fire appropriate property change event, which is AccessibleContext.ACCESSIBLE_TEXT_PROPERTY). This tracks the changed offset via the event.

Specified by:
removeUpdate in interface DocumentListener
Parameters:
e - the DocumentEvent

changedUpdate

public void changedUpdate(DocumentEvent e)
Handles document remove (fire appropriate property change event, which is AccessibleContext.ACCESSIBLE_TEXT_PROPERTY). This tracks the changed offset via the event.

Specified by:
changedUpdate in interface DocumentListener
Parameters:
e - the DocumentEvent

getAccessibleStateSet

public AccessibleStateSet getAccessibleStateSet()
Gets the state set of the JTextComponent. The AccessibleStateSet of an object is composed of a set of unique AccessibleState's. A change in the AccessibleStateSet of an object will cause a PropertyChangeEvent to be fired for the AccessibleContext.ACCESSIBLE_STATE_PROPERTY property.

Overrides:
getAccessibleStateSet in class JComponent.AccessibleJComponent
Returns:
an instance of AccessibleStateSet containing the current state set of the object
See Also:
AccessibleStateSet, AccessibleState, JComponent.AccessibleJComponent.addPropertyChangeListener(java.beans.PropertyChangeListener)

getAccessibleRole

public AccessibleRole getAccessibleRole()
Gets the role of this object.

Overrides:
getAccessibleRole in class JComponent.AccessibleJComponent
Returns:
an instance of AccessibleRole describing the role of the object (AccessibleRole.TEXT)
See Also:
AccessibleRole

getAccessibleText

public AccessibleText getAccessibleText()
Get the AccessibleText associated with this object. In the implementation of the Java Accessibility API for this class, return this object, which is responsible for implementing the AccessibleText interface on behalf of itself.

Overrides:
getAccessibleText in class AccessibleContext
Returns:
this object
See Also:
AccessibleText

getIndexAtPoint

public int getIndexAtPoint(Point p)
Given a point in local coordinates, return the zero-based index of the character under that Point. If the point is invalid, this method returns -1.

Specified by:
getIndexAtPoint in interface AccessibleText
Parameters:
p - the Point in local coordinates
Returns:
the zero-based index of the character under Point p.

getCharacterBounds

public Rectangle getCharacterBounds(int i)
Determines the bounding box of the character at the given index into the string. The bounds are returned in local coordinates. If the index is invalid a null rectangle is returned. The screen coordinates returned are "unscrolled coordinates" if the JTextComponent is contained in a JScrollPane in which case the resulting rectangle should be composed with the parent coordinates. A good algorithm to use is: Accessible a: AccessibleText at = a.getAccessibleText(); AccessibleComponent ac = a.getAccessibleComponent(); Rectangle r = at.getCharacterBounds(); Point p = ac.getLocation(); r.x += p.x; r.y += p.y; Note: the JTextComponent must have a valid size (e.g. have been added to a parent container whose ancestor container is a valid top-level window) for this method to be able to return a meaningful (non-null) value.

Specified by:
getCharacterBounds in interface AccessibleText
Parameters:
i - the index into the String >= 0
Returns:
the screen coordinates of the character's bounding box

getCharCount

public int getCharCount()
Returns the number of characters (valid indices)

Specified by:
getCharCount in interface AccessibleText
Returns:
the number of characters >= 0

getCaretPosition

public int getCaretPosition()
Returns the zero-based offset of the caret. Note: The character to the right of the caret will have the same index value as the offset (the caret is between two characters).

Specified by:
getCaretPosition in interface AccessibleText
Returns:
the zero-based offset of the caret.

getCharacterAttribute

public AttributeSet getCharacterAttribute(int i)
Returns the AttributeSet for a given character (at a given index).

Specified by:
getCharacterAttribute in interface AccessibleText
Parameters:
i - the zero-based index into the text
Returns:
the AttributeSet of the character

getSelectionStart

public int getSelectionStart()
Returns the start offset within the selected text. If there is no selection, but there is a caret, the start and end offsets will be the same. Return 0 if the text is empty, or the caret position if no selection.

Specified by:
getSelectionStart in interface AccessibleText
Returns:
the index into the text of the start of the selection >= 0

getSelectionEnd

public int getSelectionEnd()
Returns the end offset within the selected text. If there is no selection, but there is a caret, the start and end offsets will be the same. Return 0 if the text is empty, or the caret position if no selection.

Specified by:
getSelectionEnd in interface AccessibleText
Returns:
the index into teh text of the end of the selection >= 0

getSelectedText

public String getSelectedText()
Returns the portion of the text that is selected.

Specified by:
getSelectedText in interface AccessibleText
Returns:
the text, null if no selection

getAtIndex

public String getAtIndex(int part,
                         int index)
Description copied from interface: AccessibleText
Returns the String at a given index.

Specified by:
getAtIndex in interface AccessibleText
Parameters:
part - the CHARACTER, WORD, or SENTENCE to retrieve
index - an index within the text
Returns:
the letter, word, or sentence

getAfterIndex

public String getAfterIndex(int part,
                            int index)
Description copied from interface: AccessibleText
Returns the String after a given index.

Specified by:
getAfterIndex in interface AccessibleText
Parameters:
part - the CHARACTER, WORD, or SENTENCE to retrieve
index - an index within the text
Returns:
the letter, word, or sentence

getBeforeIndex

public String getBeforeIndex(int part,
                             int index)
Description copied from interface: AccessibleText
Returns the String before a given index.

Specified by:
getBeforeIndex in interface AccessibleText
Parameters:
part - the CHARACTER, WORD, or SENTENCE to retrieve
index - an index within the text
Returns:
the letter, word, or sentence

getAccessibleEditableText

public AccessibleEditableText getAccessibleEditableText()
Returns the AccessibleEditableText interface for this text component.

Overrides:
getAccessibleEditableText in class AccessibleContext
Returns:
the AccessibleEditableText interface
See Also:
AccessibleEditableText

setTextContents

public void setTextContents(String s)
Sets the text contents to the specified string.

Specified by:
setTextContents in interface AccessibleEditableText
Parameters:
s - the string to set the text contents

insertTextAtIndex

public void insertTextAtIndex(int index,
                              String s)
Inserts the specified string at the given index

Specified by:
insertTextAtIndex in interface AccessibleEditableText
Parameters:
index - the index in the text where the string will be inserted
s - the string to insert in the text

getTextRange

public String getTextRange(int startIndex,
                           int endIndex)
Returns the text string between two indices.

Specified by:
getTextRange in interface AccessibleEditableText
Parameters:
startIndex - the starting index in the text
endIndex - the ending index in the text
Returns:
the text string between the indices

delete

public void delete(int startIndex,
                   int endIndex)
Deletes the text between two indices

Specified by:
delete in interface AccessibleEditableText
Parameters:
startIndex - the starting index in the text
endIndex - the ending index in the text

cut

public void cut(int startIndex,
                int endIndex)
Cuts the text between two indices into the system clipboard.

Specified by:
cut in interface AccessibleEditableText
Parameters:
startIndex - the starting index in the text
endIndex - the ending index in the text

paste

public void paste(int startIndex)
Pastes the text from the system clipboard into the text starting at the specified index.

Specified by:
paste in interface AccessibleEditableText
Parameters:
startIndex - the starting index in the text

replaceText

public void replaceText(int startIndex,
                        int endIndex,
                        String s)
Replaces the text between two indices with the specified string.

Specified by:
replaceText in interface AccessibleEditableText
Parameters:
startIndex - the starting index in the text
endIndex - the ending index in the text
s - the string to replace the text between two indices

selectText

public void selectText(int startIndex,
                       int endIndex)
Selects the text between two indices.

Specified by:
selectText in interface AccessibleEditableText
Parameters:
startIndex - the starting index in the text
endIndex - the ending index in the text

setAttributes

public void setAttributes(int startIndex,
                          int endIndex,
                          AttributeSet as)
Sets attributes for the text between two indices.

Specified by:
setAttributes in interface AccessibleEditableText
Parameters:
startIndex - the starting index in the text
endIndex - the ending index in the text
as - the attribute set
See Also:
AttributeSet

getAccessibleAction

public AccessibleAction getAccessibleAction()
Description copied from class: AccessibleContext
Gets the AccessibleAction associated with this object that supports one or more actions.

Overrides:
getAccessibleAction in class AccessibleContext
Returns:
AccessibleAction if supported by object; else return null
See Also:
AccessibleAction

getAccessibleActionCount

public int getAccessibleActionCount()
Returns the number of accessible actions available in this object If there are more than one, the first one is considered the "default" action of the object.

Specified by:
getAccessibleActionCount in interface AccessibleAction
Returns:
the zero-based number of Actions in this object

getAccessibleActionDescription

public String getAccessibleActionDescription(int i)
Returns a description of the specified action of the object.

Specified by:
getAccessibleActionDescription in interface AccessibleAction
Parameters:
i - zero-based index of the actions
Returns:
a String description of the action
See Also:
getAccessibleActionCount()

doAccessibleAction

public boolean doAccessibleAction(int i)
Performs the specified Action on the object

Specified by:
doAccessibleAction in interface AccessibleAction
Parameters:
i - zero-based index of actions
Returns:
true if the action was performed; otherwise false.
See Also:
getAccessibleActionCount()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


JTextComponent.KeyBinding (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class JTextComponent.KeyBinding

java.lang.Object
    extended by javax.swing.text.JTextComponent.KeyBinding
Enclosing class:
JTextComponent
public static class JTextComponent.KeyBinding
extends Object

Binding record for creating key bindings.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Field Summary
String | actionName The name of the action for the key.
KeyStroke | key The key.
Constructor Summary
JTextComponent.KeyBinding(KeyStroke key, String actionName)
Creates a new key binding.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

key

public KeyStroke key
The key.

actionName

public String actionName
The name of the action for the key.

Constructor Detail

JTextComponent.KeyBinding

public JTextComponent.KeyBinding(KeyStroke key,
                                 String actionName)
Creates a new key binding.

Parameters:
key - the key
actionName - the name of the action for the key
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Keymap (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Interface Keymap

public interface Keymap

A collection of bindings of KeyStrokes to actions. The bindings are basically name-value pairs that potentially resolve in a hierarchy.

Method Summary
void | addActionForKeyStroke(KeyStroke key, Action a) Adds a binding to the keymap.
Action | getAction(KeyStroke key) Fetches the action appropriate for the given symbolic event sequence.
Action[] | getBoundActions() Fetches all of the actions defined in this keymap.
KeyStroke[] | getBoundKeyStrokes() Fetches all of the keystrokes in this map that are bound to some action.
Action | getDefaultAction() Fetches the default action to fire if a key is typed (i.e.
KeyStroke[] | getKeyStrokesForAction(Action a) Fetches the keystrokes that will result in the given action.
String | getName() Fetches the name of the set of key-bindings.
Keymap | getResolveParent() Fetches the parent keymap used to resolve key-bindings.
boolean | isLocallyDefined(KeyStroke key) Determines if the given key sequence is locally defined.
void | removeBindings() Removes all bindings from the keymap.
void | removeKeyStrokeBinding(KeyStroke keys) Removes a binding from the keymap.
void | setDefaultAction(Action a) Set the default action to fire if a key is typed.
void | setResolveParent(Keymap parent) Sets the parent keymap, which will be used to resolve key-bindings.

Method Detail

getName

public String getName()
Fetches the name of the set of key-bindings.

Returns:
the name

getDefaultAction

public Action getDefaultAction()
Fetches the default action to fire if a key is typed (i.e. a KEY_TYPED KeyEvent is received) and there is no binding for it. Typically this would be some action that inserts text so that the keymap doesn't require an action for each possible key.

Returns:
the default action

setDefaultAction

public void setDefaultAction(Action a)
Set the default action to fire if a key is typed.

Parameters:
a - the action

getAction

public Action getAction(KeyStroke key)
Fetches the action appropriate for the given symbolic event sequence. This is used by JTextController to determine how to interpret key sequences. If the binding is not resolved locally, an attempt is made to resolve through the parent keymap, if one is set.

Parameters:
key - the key sequence
Returns:
the action associated with the key sequence if one is defined, otherwise null

getBoundKeyStrokes

public KeyStroke[] getBoundKeyStrokes()
Fetches all of the keystrokes in this map that are bound to some action.

Returns:
the list of keystrokes

getBoundActions

public Action[] getBoundActions()
Fetches all of the actions defined in this keymap.

Returns:
the list of actions

getKeyStrokesForAction

public KeyStroke[] getKeyStrokesForAction(Action a)
Fetches the keystrokes that will result in the given action.

Parameters:
a - the action
Returns:
the list of keystrokes

isLocallyDefined

public boolean isLocallyDefined(KeyStroke key)
Determines if the given key sequence is locally defined.

Parameters:
key - the key sequence
Returns:
true if the key sequence is locally defined else false

addActionForKeyStroke

public void addActionForKeyStroke(KeyStroke key,
                                  Action a)
Adds a binding to the keymap.

Parameters:
key - the key sequence
a - the action

removeKeyStrokeBinding

public void removeKeyStrokeBinding(KeyStroke keys)
Removes a binding from the keymap.

Parameters:
keys - the key sequence

removeBindings

public void removeBindings()
Removes all bindings from the keymap.

getResolveParent

public Keymap getResolveParent()
Fetches the parent keymap used to resolve key-bindings.

Returns:
the keymap

setResolveParent

public void setResolveParent(Keymap parent)
Sets the parent keymap, which will be used to resolve key-bindings.

Parameters:
parent - the parent keymap
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


LabelView (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class LabelView

java.lang.Object
    extended by javax.swing.text.View
        extended by javax.swing.text.GlyphView
            extended by javax.swing.text.LabelView
All Implemented Interfaces:
Cloneable, SwingConstants, TabableView
Direct Known Subclasses:
InlineView
public class LabelView
extends GlyphView
implements TabableView

A LabelView is a styled chunk of text that represents a view mapped over an element in the text model. It caches the character level attributes used for rendering.

Nested Class Summary
Nested classes inherited from class javax.swing.text.GlyphView
GlyphView.GlyphPainter
Field Summary
Fields inherited from class javax.swing.text.View
BadBreakWeight, ExcellentBreakWeight, ForcedBreakWeight, GoodBreakWeight, X_AXIS, Y_AXIS
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
Constructor Summary
LabelView(Element elem)
Constructs a new view wrapped on an element.
Method Summary
void | changedUpdate(DocumentEvent e, Shape a, ViewFactory f) Gives notification from the document that attributes were changed in a location that this view is responsible for.
Color | getBackground() Fetches the background color to use to render the glyphs.
Font | getFont() Fetches the font that the glyphs should be based upon.
protected FontMetrics | getFontMetrics() Deprecated. FontMetrics are not used for glyph rendering when running in the Java2 SDK.
Color | getForeground() Fetches the foreground color to use to render the glyphs.
boolean | isStrikeThrough() Determines if the glyphs should have a strikethrough line.
boolean | isSubscript() Determines if the glyphs should be rendered as superscript.
boolean | isSuperscript() Determines if the glyphs should be rendered as subscript.
boolean | isUnderline() Determines if the glyphs should be underlined.
protected void | setPropertiesFromAttributes() Sets the cached properties from the attributes.
protected void | setStrikeThrough(boolean s) Sets whether or not the view has a strike/line through it.
protected void | setSubscript(boolean s) Sets whether or not the view represents a subscript.
protected void | setSuperscript(boolean s) Sets whether or not the view represents a superscript.
protected void | setUnderline(boolean u) Sets whether or not the view is underlined.
Methods inherited from class javax.swing.text.GlyphView
breakView, checkPainter, clone, createFragment, getAlignment, getBreakWeight, getEndOffset, getGlyphPainter, getNextVisualPositionFrom, getPartialSpan, getPreferredSpan, getStartOffset, getTabbedSpan, getTabExpander, getText, insertUpdate, modelToView, paint, removeUpdate, setGlyphPainter, viewToModel
Methods inherited from class javax.swing.text.View
append, forwardUpdate, forwardUpdateToView, getAttributes, getChildAllocation, getContainer, getDocument, getElement, getGraphics, getMaximumSpan, getMinimumSpan, getParent, getResizeWeight, getToolTipText, getView, getViewCount, getViewFactory, getViewIndex, getViewIndex, insert, isVisible, modelToView, modelToView, preferenceChanged, remove, removeAll, replace, setParent, setSize, updateChildren, updateLayout, viewToModel
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Methods inherited from interface javax.swing.text.TabableView
getPartialSpan, getTabbedSpan

Constructor Detail

LabelView

public LabelView(Element elem)
Constructs a new view wrapped on an element.

Parameters:
elem - the element
Method Detail

setUnderline

protected void setUnderline(boolean u)
Sets whether or not the view is underlined. Note that this setter is protected and is really only meant if you need to update some additional state when set.

Parameters:
u - true if the view is underlined, otherwise false
See Also:
isUnderline()

setStrikeThrough

protected void setStrikeThrough(boolean s)
Sets whether or not the view has a strike/line through it. Note that this setter is protected and is really only meant if you need to update some additional state when set.

Parameters:
s - true if the view has a strike/line through it, otherwise false
See Also:
isStrikeThrough()

setSuperscript

protected void setSuperscript(boolean s)
Sets whether or not the view represents a superscript. Note that this setter is protected and is really only meant if you need to update some additional state when set.

Parameters:
s - true if the view represents a superscript, otherwise false
See Also:
isSuperscript()

setSubscript

protected void setSubscript(boolean s)
Sets whether or not the view represents a subscript. Note that this setter is protected and is really only meant if you need to update some additional state when set.

Parameters:
s - true if the view represents a subscript, otherwise false
See Also:
isSubscript()

setPropertiesFromAttributes

protected void setPropertiesFromAttributes()
Sets the cached properties from the attributes.

getFontMetrics

protected FontMetrics getFontMetrics()
Deprecated. FontMetrics are not used for glyph rendering when running in the Java2 SDK.

Fetches the FontMetrics used for this view.

getBackground

public Color getBackground()
Fetches the background color to use to render the glyphs. This is implemented to return a cached background color, which defaults to null.

Overrides:
getBackground in class GlyphView
Returns:
the cached background color

getForeground

public Color getForeground()
Fetches the foreground color to use to render the glyphs. This is implemented to return a cached foreground color, which defaults to null.

Overrides:
getForeground in class GlyphView
Returns:
the cached foreground color

getFont

public Font getFont()
Fetches the font that the glyphs should be based upon. This is implemented to return a cached font.

Overrides:
getFont in class GlyphView
Returns:
the cached font

isUnderline

public boolean isUnderline()
Determines if the glyphs should be underlined. If true, an underline should be drawn through the baseline. This is implemented to return the cached underline property.

When you request this property, LabelView re-syncs its state with the properties of the Element's AttributeSet. If Element's AttributeSet does not have this property set, it will revert to false.

Overrides:
isUnderline in class GlyphView
Returns:
the value of the cached underline property

isStrikeThrough

public boolean isStrikeThrough()
Determines if the glyphs should have a strikethrough line. If true, a line should be drawn through the center of the glyphs. This is implemented to return the cached strikeThrough property.

When you request this property, LabelView re-syncs its state with the properties of the Element's AttributeSet. If Element's AttributeSet does not have this property set, it will revert to false.

Overrides:
isStrikeThrough in class GlyphView
Returns:
the value of the cached strikeThrough property

isSubscript

public boolean isSubscript()
Determines if the glyphs should be rendered as superscript.

Overrides:
isSubscript in class GlyphView
Returns:
the value of the cached subscript property

When you request this property, LabelView re-syncs its state with the properties of the Element's AttributeSet. If Element's AttributeSet does not have this property set, it will revert to false.

isSuperscript

public boolean isSuperscript()
Determines if the glyphs should be rendered as subscript.

When you request this property, LabelView re-syncs its state with the properties of the Element's AttributeSet. If Element's AttributeSet does not have this property set, it will revert to false.

Overrides:
isSuperscript in class GlyphView
Returns:
the value of the cached superscript property

changedUpdate

public void changedUpdate(DocumentEvent e,
                          Shape a,
                          ViewFactory f)
Gives notification from the document that attributes were changed in a location that this view is responsible for.

Overrides:
changedUpdate in class GlyphView
Parameters:
e - the change information from the associated document
a - the current allocation of the view
f - the factory to use to rebuild if the view has children
See Also:
View.changedUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


LayeredHighlighter (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class LayeredHighlighter

java.lang.Object
    extended by javax.swing.text.LayeredHighlighter
All Implemented Interfaces:
Highlighter
Direct Known Subclasses:
DefaultHighlighter
public abstract class LayeredHighlighter
extends Object
implements Highlighter

See Also:
Highlighter

Nested Class Summary
static class LayeredHighlighter.LayerPainter
Layered highlight renderer.
Nested classes inherited from class javax.swing.text.Highlighter
Highlighter.Highlight, Highlighter.HighlightPainter
Constructor Summary
LayeredHighlighter()
Method Summary
abstract  void paintLayeredHighlights(Graphics g, int p0, int p1, Shape viewBounds, JTextComponent editor, View view)
When leaf Views (such as LabelView) are rendering they should call into this method.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Methods inherited from interface javax.swing.text.Highlighter
addHighlight, changeHighlight, deinstall, getHighlights, install, paint, removeAllHighlights, removeHighlight

Constructor Detail

LayeredHighlighter

public LayeredHighlighter()
Method Detail

paintLayeredHighlights

public abstract void paintLayeredHighlights(Graphics g,
                                            int p0,
                                            int p1,
                                            Shape viewBounds,
                                            JTextComponent editor,
                                            View view)
When leaf Views (such as LabelView) are rendering they should call into this method. If a highlight is in the given region it will be drawn immediately.

Parameters:
g - Graphics used to draw
p0 - starting offset of view
p1 - ending offset of view
viewBounds - Bounds of View
editor - JTextComponent
view - View instance being rendered
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


LayeredHighlighter.LayerPainter (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class LayeredHighlighter.LayerPainter

java.lang.Object
    extended by javax.swing.text.LayeredHighlighter.LayerPainter
All Implemented Interfaces:
Highlighter.HighlightPainter
Direct Known Subclasses:
DefaultHighlighter.DefaultHighlightPainter
Enclosing class:
LayeredHighlighter
public abstract static class LayeredHighlighter.LayerPainter
extends Object
implements Highlighter.HighlightPainter

Layered highlight renderer.

Constructor Summary
LayeredHighlighter.LayerPainter()
Method Summary
abstract  Shape paintLayer(Graphics g, int p0, int p1, Shape viewBounds, JTextComponent editor, View view)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Methods inherited from interface javax.swing.text.Highlighter.HighlightPainter
paint

Constructor Detail

LayeredHighlighter.LayerPainter

public LayeredHighlighter.LayerPainter()
Method Detail

paintLayer

public abstract Shape paintLayer(Graphics g,
                                 int p0,
                                 int p1,
                                 Shape viewBounds,
                                 JTextComponent editor,
                                 View view)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


LayoutQueue (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class LayoutQueue

java.lang.Object
    extended by javax.swing.text.LayoutQueue
public class LayoutQueue
extends Object

A queue of text layout tasks.

Since:
1.3
See Also:
AsyncBoxView

Constructor Summary
LayoutQueue()
Construct a layout queue.
Method Summary
void | addTask(Runnable task) Add a task that is not needed immediately because the results are not believed to be visible.
static LayoutQueue | getDefaultQueue() Fetch the default layout queue.
static void | setDefaultQueue(LayoutQueue q) Set the default layout queue.
protected Runnable | waitForWork() Used by the worker thread to get a new task to execute
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

LayoutQueue

public LayoutQueue()
Construct a layout queue.

Method Detail

getDefaultQueue

public static LayoutQueue getDefaultQueue()
Fetch the default layout queue.

setDefaultQueue

public static void setDefaultQueue(LayoutQueue q)
Set the default layout queue.

Parameters:
q - the new queue.

addTask

public void addTask(Runnable task)
Add a task that is not needed immediately because the results are not believed to be visible.

waitForWork

protected Runnable waitForWork()
Used by the worker thread to get a new task to execute

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MaskFormatter (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class MaskFormatter

java.lang.Object
    extended by javax.swing.JFormattedTextField.AbstractFormatter
        extended by javax.swing.text.DefaultFormatter
            extended by javax.swing.text.MaskFormatter
All Implemented Interfaces:
Cloneable, Serializable
public class MaskFormatter
extends DefaultFormatter

MaskFormatter is used to format and edit strings. The behavior of a MaskFormatter is controlled by way of a String mask that specifies the valid characters that can be contained at a particular location in the Document model. The following characters can be specified:

Character | Description
# | Any valid number, uses Character.isDigit.
' | Escape character, used to escape any of the special formatting characters.
U | Any character (Character.isLetter). All lowercase letters are mapped to upper case.
L | Any character (Character.isLetter). All upper case letters are mapped to lower case.
A | Any character or number (Character.isLetter or Character.isDigit)
? | Any character (Character.isLetter).
* | Anything.
H | Any hex character (0-9, a-f or A-F).

Typically characters correspond to one char, but in certain languages this is not the case. The mask is on a per character basis, and will thus adjust to fit as many chars as are needed.

You can further restrict the characters that can be input by the setInvalidCharacters and setValidCharacters methods. setInvalidCharacters allows you to specify which characters are not legal. setValidCharacters allows you to specify which characters are valid. For example, the following code block is equivalent to a mask of '0xHHH' with no invalid/valid characters:

 MaskFormatter formatter = new MaskFormatter("0x***");
 formatter.setValidCharacters("0123456789abcdefABCDEF");

When initially formatting a value if the length of the string is less than the length of the mask, two things can happen. Either the placeholder string will be used, or the placeholder character will be used. Precedence is given to the placeholder string. For example:

   MaskFormatter formatter = new MaskFormatter("###-####");
   formatter.setPlaceholderCharacter('_');
   formatter.getDisplayValue(tf, "123");

Would result in the string '123-____'. If setPlaceholder("555-1212") was invoked '123-1212' would result. The placeholder String is only used on the initial format, on subsequent formats only the placeholder character will be used.

If a MaskFormatter is configured to only allow valid characters (setAllowsInvalid(false)) literal characters will be skipped as necessary when editing. Consider a MaskFormatter with the mask "###-####" and current value "555-1212". Using the right arrow key to navigate through the field will result in (| indicates the position of the caret):

   |555-1212
   5|55-1212
   55|5-1212
   555-|1212
   555-1|212
The '-' is a literal (non-editable) character, and is skipped.

Similar behavior will result when editing. Consider inserting the string '123-45' and '12345' into the MaskFormatter in the previous example. Both inserts will result in the same String, '123-45__'. When MaskFormatter is processing the insert at character position 3 (the '-'), two things can happen:

  1. If the inserted character is '-', it is accepted.
  2. If the inserted character matches the mask for the next non-literal character, it is accepted at the new location.
  3. Anything else results in an invalid edit

By default MaskFormatter will not allow invalid edits, you can change this with the setAllowsInvalid method, and will commit edits on valid edits (use the setCommitsOnValidEdit to change this).

By default, MaskFormatter is in overwrite mode. That is as characters are typed a new character is not inserted, rather the character at the current location is replaced with the newly typed character. You can change this behavior by way of the method setOverwriteMode.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Since:
1.4

Constructor Summary
MaskFormatter()
Creates a MaskFormatter with no mask.
MaskFormatter(String mask)
Creates a MaskFormatter with the specified mask.
Method Summary
String | getInvalidCharacters() Returns the characters that are not valid for input.
String | getMask() Returns the formatting mask.
String | getPlaceholder() Returns the String to use if the value does not completely fill in the mask.
char | getPlaceholderCharacter() Returns the character to use in place of characters that are not present in the value, ie the user must fill them in.
String | getValidCharacters() Returns the valid characters that can be input.
boolean | getValueContainsLiteralCharacters() Returns true if stringToValue should return literal characters in the mask.
void | install(JFormattedTextField ftf) Installs the DefaultFormatter onto a particular JFormattedTextField.
void | setInvalidCharacters(String invalidCharacters) Allows for further restricting of the characters that can be input.
void | setMask(String mask) Sets the mask dictating the legal characters.
void | setPlaceholder(String placeholder) Sets the string to use if the value does not completely fill in the mask.
void | setPlaceholderCharacter(char placeholder) Sets the character to use in place of characters that are not present in the value, ie the user must fill them in.
void | setValidCharacters(String validCharacters) Allows for further restricting of the characters that can be input.
void | setValueContainsLiteralCharacters(boolean containsLiteralChars) If true, the returned value and set value will also contain the literal characters in mask.
Object | stringToValue(String value) Parses the text, returning the appropriate Object representation of the String value.
String | valueToString(Object value) Returns a String representation of the Object value based on the mask.
Methods inherited from class javax.swing.text.DefaultFormatter
clone, getAllowsInvalid, getCommitsOnValidEdit, getDocumentFilter, getNavigationFilter, getOverwriteMode, getValueClass, setAllowsInvalid, setCommitsOnValidEdit, setOverwriteMode, setValueClass
Methods inherited from class javax.swing.JFormattedTextField.AbstractFormatter
getActions, getFormattedTextField, invalidEdit, setEditValid, uninstall
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

MaskFormatter

public MaskFormatter()
Creates a MaskFormatter with no mask.

MaskFormatter

public MaskFormatter(String mask)
              throws ParseException
Creates a MaskFormatter with the specified mask. A ParseException will be thrown if mask is an invalid mask.

Throws:
ParseException - if mask does not contain valid mask characters
Method Detail

setMask

public void setMask(String mask)
             throws ParseException
Sets the mask dictating the legal characters. This will throw a ParseException if mask is not valid.

Throws:
ParseException - if mask does not contain valid mask characters

getMask

public String getMask()
Returns the formatting mask.

Returns:
Mask dictating legal character values.

setValidCharacters

public void setValidCharacters(String validCharacters)
Allows for further restricting of the characters that can be input. Only characters specified in the mask, not in the invalidCharacters, and in validCharacters will be allowed to be input. Passing in null (the default) implies the valid characters are only bound by the mask and the invalid characters.

Parameters:
validCharacters - If non-null, specifies legal characters.

getValidCharacters

public String getValidCharacters()
Returns the valid characters that can be input.

Returns:
Legal characters

setInvalidCharacters

public void setInvalidCharacters(String invalidCharacters)
Allows for further restricting of the characters that can be input. Only characters specified in the mask, not in the invalidCharacters, and in validCharacters will be allowed to be input. Passing in null (the default) implies the valid characters are only bound by the mask and the valid characters.

Parameters:
invalidCharacters - If non-null, specifies illegal characters.

getInvalidCharacters

public String getInvalidCharacters()
Returns the characters that are not valid for input.

Returns:
illegal characters.

setPlaceholder

public void setPlaceholder(String placeholder)
Sets the string to use if the value does not completely fill in the mask. A null value implies the placeholder char should be used.

Parameters:
placeholder - String used when formatting if the value does not completely fill the mask

getPlaceholder

public String getPlaceholder()
Returns the String to use if the value does not completely fill in the mask.

Returns:
String used when formatting if the value does not completely fill the mask

setPlaceholderCharacter

public void setPlaceholderCharacter(char placeholder)
Sets the character to use in place of characters that are not present in the value, ie the user must fill them in. The default value is a space.

This is only applicable if the placeholder string has not been specified, or does not completely fill in the mask.

Parameters:
placeholder - Character used when formatting if the value does not completely fill the mask

getPlaceholderCharacter

public char getPlaceholderCharacter()
Returns the character to use in place of characters that are not present in the value, ie the user must fill them in.

Returns:
Character used when formatting if the value does not completely fill the mask

setValueContainsLiteralCharacters

public void setValueContainsLiteralCharacters(boolean containsLiteralChars)
If true, the returned value and set value will also contain the literal characters in mask.

For example, if the mask is '(###) ###-####', the current value is '(415) 555-1212', and valueContainsLiteralCharacters is true stringToValue will return '(415) 555-1212'. On the other hand, if valueContainsLiteralCharacters is false, stringToValue will return '4155551212'.

Parameters:
containsLiteralChars - Used to indicate if literal characters in mask should be returned in stringToValue

getValueContainsLiteralCharacters

public boolean getValueContainsLiteralCharacters()
Returns true if stringToValue should return literal characters in the mask.

Returns:
True if literal characters in mask should be returned in stringToValue

stringToValue

public Object stringToValue(String value)
                     throws ParseException
Parses the text, returning the appropriate Object representation of the String value. This strips the literal characters as necessary and invokes supers stringToValue, so that if you have specified a value class (setValueClass) an instance of it will be created. This will thrown a ParseException if the value does not match the current mask.

Overrides:
stringToValue in class DefaultFormatter
Parameters:
value - String to convert
Returns:
Object representation of text
Throws:
ParseException - if there is an error in the conversion

valueToString

public String valueToString(Object value)
                     throws ParseException
Returns a String representation of the Object value based on the mask.

Overrides:
valueToString in class DefaultFormatter
Parameters:
value - Value to convert
Returns:
String representation of value
Throws:
ParseException - if there is an error in the conversion

install

public void install(JFormattedTextField ftf)
Installs the DefaultFormatter onto a particular JFormattedTextField. This will invoke valueToString to convert the current value from the JFormattedTextField to a String. This will then install the Actions from getActions, the DocumentFilter returned from getDocumentFilter and the NavigationFilter returned from getNavigationFilter onto the JFormattedTextField.

Subclasses will typically only need to override this if they wish to install additional listeners on the JFormattedTextField.

If there is a ParseException in converting the current value to a String, this will set the text to an empty String, and mark the JFormattedTextField as being in an invalid state.

While this is a public method, this is typically only useful for subclassers of JFormattedTextField. JFormattedTextField will invoke this method at the appropriate times when the value changes, or its internal state changes.

Overrides:
install in class DefaultFormatter
Parameters:
ftf - JFormattedTextField to format for, may be null indicating uninstall from current JFormattedTextField.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MutableAttributeSet (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Interface MutableAttributeSet

All Superinterfaces:
AttributeSet
All Known Subinterfaces:
Style
All Known Implementing Classes:
AbstractDocument.AbstractElement, SimpleAttributeSet, StyleContext.NamedStyle
public interface MutableAttributeSet
extends AttributeSet

A generic interface for a mutable collection of unique attributes. Implementations will probably want to provide a constructor of the form: public XXXAttributeSet(ConstAttributeSet source);

Nested Class Summary
Nested classes inherited from class javax.swing.text.AttributeSet
AttributeSet.CharacterAttribute, AttributeSet.ColorAttribute, AttributeSet.FontAttribute, AttributeSet.ParagraphAttribute
Field Summary
Fields inherited from interface javax.swing.text.AttributeSet
NameAttribute, ResolveAttribute
Method Summary
void | addAttribute(Object name, Object value) Creates a new attribute set similar to this one except that it contains an attribute with the given name and value.
void | addAttributes(AttributeSet attributes) Creates a new attribute set similar to this one except that it contains the given attributes and values.
void | removeAttribute(Object name) Removes an attribute with the given name.
void | removeAttributes(AttributeSet attributes) Removes a set of attributes with the given name.
void | removeAttributes(Enumeration names) Removes an attribute set with the given names.
void | setResolveParent(AttributeSet parent) Sets the resolving parent.
Methods inherited from interface javax.swing.text.AttributeSet
containsAttribute, containsAttributes, copyAttributes, getAttribute, getAttributeCount, getAttributeNames, getResolveParent, isDefined, isEqual

Method Detail

addAttribute

public void addAttribute(Object name,
                         Object value)
Creates a new attribute set similar to this one except that it contains an attribute with the given name and value. The object must be immutable, or not mutated by any client.

Parameters:
name - the name
value - the value

addAttributes

public void addAttributes(AttributeSet attributes)
Creates a new attribute set similar to this one except that it contains the given attributes and values.

Parameters:
attributes - the set of attributes

removeAttribute

public void removeAttribute(Object name)
Removes an attribute with the given name.

Parameters:
name - the attribute name

removeAttributes

public void removeAttributes(Enumeration names)
Removes an attribute set with the given names.

Parameters:
names - the set of names

removeAttributes

public void removeAttributes(AttributeSet attributes)
Removes a set of attributes with the given name.

Parameters:
attributes - the set of attributes

setResolveParent

public void setResolveParent(AttributeSet parent)
Sets the resolving parent. This is the set of attributes to resolve through if an attribute isn't defined locally.

Parameters:
parent - the parent
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NavigationFilter (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class NavigationFilter

java.lang.Object
    extended by javax.swing.text.NavigationFilter
public class NavigationFilter
extends Object

NavigationFilter can be used to restrict where the cursor can be positioned. When the default cursor positioning actions attempt to reposition the cursor they will call into the NavigationFilter, assuming the JTextComponent has a non-null NavigationFilter set. In this manner the NavigationFilter can effectively restrict where the cursor can be positioned. Similarly DefaultCaret will call into the NavigationFilter when the user is changing the selection to further restrict where the cursor can be positioned.

Subclasses can conditionally call into supers implementation to restrict where the cursor can be placed, or call directly into the FilterBypass.

Since:
1.4
See Also:
Caret, DefaultCaret, View

Nested Class Summary
static class NavigationFilter.FilterBypass
Used as a way to circumvent calling back into the caret to position the cursor.
Constructor Summary
NavigationFilter()
Method Summary
int | getNextVisualPositionFrom(JTextComponent text, int pos, Position.Bias bias, int direction, Position.Bias[] biasRet) Returns the next visual position to place the caret at from an existing position.
void | moveDot(NavigationFilter.FilterBypass fb, int dot, Position.Bias bias) Invoked prior to the Caret moving the dot.
void | setDot(NavigationFilter.FilterBypass fb, int dot, Position.Bias bias) Invoked prior to the Caret setting the dot.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

NavigationFilter

public NavigationFilter()
Method Detail

setDot

public void setDot(NavigationFilter.FilterBypass fb,
                   int dot,
                   Position.Bias bias)
Invoked prior to the Caret setting the dot. The default implementation calls directly into the FilterBypass with the passed in arguments. Subclasses may wish to conditionally call super with a different location, or invoke the necessary method on the FilterBypass

Parameters:
fb - FilterBypass that can be used to mutate caret position
dot - the position >= 0
bias - Bias to place the dot at

moveDot

public void moveDot(NavigationFilter.FilterBypass fb,
                    int dot,
                    Position.Bias bias)
Invoked prior to the Caret moving the dot. The default implementation calls directly into the FilterBypass with the passed in arguments. Subclasses may wish to conditionally call super with a different location, or invoke the necessary methods on the FilterBypass.

Parameters:
fb - FilterBypass that can be used to mutate caret position
dot - the position >= 0
bias - Bias for new location

getNextVisualPositionFrom

public int getNextVisualPositionFrom(JTextComponent text,
                                     int pos,
                                     Position.Bias bias,
                                     int direction,
                                     Position.Bias[] biasRet)
                              throws BadLocationException
Returns the next visual position to place the caret at from an existing position. The default implementation simply forwards the method to the root View. Subclasses may wish to further restrict the location based on additional criteria.

Parameters:
text - JTextComponent containing text
pos - Position used in determining next position
bias - Bias used in determining next position
direction - the direction from the current position that can be thought of as the arrow keys typically found on a keyboard. This will be one of the following values:
  • SwingConstants.WEST
  • SwingConstants.EAST
  • SwingConstants.NORTH
  • SwingConstants.SOUTH
biasRet - Used to return resulting Bias of next position
Returns:
the location within the model that best represents the next location visual position
Throws:
BadLocationException
IllegalArgumentException - if direction doesn't have one of the legal values above
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NavigationFilter.FilterBypass (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class NavigationFilter.FilterBypass

java.lang.Object
    extended by javax.swing.text.NavigationFilter.FilterBypass
Enclosing class:
NavigationFilter
public abstract static class NavigationFilter.FilterBypass
extends Object

Used as a way to circumvent calling back into the caret to position the cursor. Caret implementations that wish to support a NavigationFilter must provide an implementation that will not callback into the NavigationFilter.

Constructor Summary
NavigationFilter.FilterBypass()
Method Summary
abstract Caret | getCaret() Returns the Caret that is changing.
abstract void | moveDot(int dot, Position.Bias bias) Moves the caret location, bypassing the NavigationFilter.
abstract void | setDot(int dot, Position.Bias bias) Sets the caret location, bypassing the NavigationFilter.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

NavigationFilter.FilterBypass

public NavigationFilter.FilterBypass()
Method Detail

getCaret

public abstract Caret getCaret()
Returns the Caret that is changing.

Returns:
Caret that is changing

setDot

public abstract void setDot(int dot,
                            Position.Bias bias)
Sets the caret location, bypassing the NavigationFilter.

Parameters:
dot - the position >= 0
bias - Bias to place the dot at

moveDot

public abstract void moveDot(int dot,
                             Position.Bias bias)
Moves the caret location, bypassing the NavigationFilter.

Parameters:
dot - the position >= 0
bias - Bias for new location
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NumberFormatter (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class NumberFormatter

java.lang.Object
    extended by javax.swing.JFormattedTextField.AbstractFormatter
        extended by javax.swing.text.DefaultFormatter
            extended by javax.swing.text.InternationalFormatter
                extended by javax.swing.text.NumberFormatter
All Implemented Interfaces:
Cloneable, Serializable
public class NumberFormatter
extends InternationalFormatter

NumberFormatter subclasses InternationalFormatter adding special behavior for numbers. Among the specializations are (these are only used if the NumberFormatter does not display invalid nubers, eg setAllowsInvalid(false)):

  • Pressing +/- (- is determined from the DecimalFormatSymbols associated with the DecimalFormat) in any field but the exponent field will attempt to change the sign of the number to positive/negative.
  • Pressing +/- (- is determined from the DecimalFormatSymbols associated with the DecimalFormat) in the exponent field will attemp to change the sign of the exponent to positive/negative.

If you are displaying scientific numbers, you may wish to turn on overwrite mode, setOverwriteMode(true). For example:

 DecimalFormat decimalFormat = new DecimalFormat("0.000E0");
 NumberFormatter textFormatter = new NumberFormatter(decimalFormat);
 textFormatter.setOverwriteMode(true);
 textFormatter.setAllowsInvalid(false);

If you are going to allow the user to enter decimal values, you should either force the DecimalFormat to contain at least one decimal (#.0###), or allow the value to be invalid setAllowsInvalid(true). Otherwise users may not be able to input decimal values.

NumberFormatter provides slightly different behavior to stringToValue than that of its superclass. If you have specified a Class for values, DefaultFormatter.setValueClass(java.lang.Class), that is one of of Integer, Long, Float, Double, Byte or Short and the Format's parseObject returns an instance of Number, the corresponding instance of the value class will be created using the constructor appropriate for the primitive type the value class represents. For example: setValueClass(Integer.class) will cause the resulting value to be created via new Integer(((Number)formatter.parseObject(string)).intValue()). This is typically useful if you wish to set a min/max value as the various Number implementations are generally not comparable to each other. This is also useful if for some reason you need a specific Number implementation for your values.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Since:
1.4

Constructor Summary
NumberFormatter()
Creates a NumberFormatter with the a default NumberFormat instance obtained from NumberFormat.getNumberInstance().
NumberFormatter(NumberFormat format)
Creates a NumberFormatter with the specified Format instance.
Method Summary
 void setFormat(Format format)
Sets the format that dictates the legal values that can be edited and displayed.
Methods inherited from class javax.swing.text.InternationalFormatter
clone, getActions, getFields, getFormat, getMaximum, getMinimum, install, setMaximum, setMinimum, stringToValue, valueToString
Methods inherited from class javax.swing.text.DefaultFormatter
getAllowsInvalid, getCommitsOnValidEdit, getDocumentFilter, getNavigationFilter, getOverwriteMode, getValueClass, setAllowsInvalid, setCommitsOnValidEdit, setOverwriteMode, setValueClass
Methods inherited from class javax.swing.JFormattedTextField.AbstractFormatter
getFormattedTextField, invalidEdit, setEditValid, uninstall
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

NumberFormatter

public NumberFormatter()
Creates a NumberFormatter with the a default NumberFormat instance obtained from NumberFormat.getNumberInstance().

NumberFormatter

public NumberFormatter(NumberFormat format)
Creates a NumberFormatter with the specified Format instance.

Parameters:
format - Format used to dictate legal values
Method Detail

setFormat

public void setFormat(Format format)
Sets the format that dictates the legal values that can be edited and displayed.

If you have used the nullary constructor the value of this property will be determined for the current locale by way of the NumberFormat.getNumberInstance() method.

Overrides:
setFormat in class InternationalFormatter
Parameters:
format - NumberFormat instance used to dictate legal values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


javax.swing.text (Java 2 Platform SE v1.4.2)

 javax.swing.text
Interfaces
AbstractDocument.AttributeContext
AbstractDocument.Content
AttributeSet
AttributeSet.CharacterAttribute
AttributeSet.ColorAttribute
AttributeSet.FontAttribute
AttributeSet.ParagraphAttribute
Caret
Document
Element
Highlighter
Highlighter.Highlight
Highlighter.HighlightPainter
Keymap
MutableAttributeSet
Position
Style
StyledDocument
TabableView
TabExpander
ViewFactory
Classes
AbstractDocument
AbstractDocument.ElementEdit
AbstractWriter
AsyncBoxView
BoxView
ComponentView
CompositeView
DateFormatter
DefaultCaret
DefaultEditorKit
DefaultEditorKit.BeepAction
DefaultEditorKit.CopyAction
DefaultEditorKit.CutAction
DefaultEditorKit.DefaultKeyTypedAction
DefaultEditorKit.InsertBreakAction
DefaultEditorKit.InsertContentAction
DefaultEditorKit.InsertTabAction
DefaultEditorKit.PasteAction
DefaultFormatter
DefaultFormatterFactory
DefaultHighlighter
DefaultHighlighter.DefaultHighlightPainter
DefaultStyledDocument
DefaultStyledDocument.AttributeUndoableEdit
DefaultStyledDocument.ElementSpec
DefaultTextUI
DocumentFilter
DocumentFilter.FilterBypass
EditorKit
ElementIterator
FieldView
FlowView
FlowView.FlowStrategy
GapContent
GlyphView
GlyphView.GlyphPainter
IconView
InternationalFormatter
JTextComponent
JTextComponent.KeyBinding
LabelView
LayeredHighlighter
LayeredHighlighter.LayerPainter
LayoutQueue
MaskFormatter
NavigationFilter
NavigationFilter.FilterBypass
NumberFormatter
ParagraphView
PasswordView
PlainDocument
PlainView
Position.Bias
Segment
SimpleAttributeSet
StringContent
StyleConstants
StyleConstants.CharacterConstants
StyleConstants.ColorConstants
StyleConstants.FontConstants
StyleConstants.ParagraphConstants
StyleContext
StyledEditorKit
StyledEditorKit.AlignmentAction
StyledEditorKit.BoldAction
StyledEditorKit.FontFamilyAction
StyledEditorKit.FontSizeAction
StyledEditorKit.ForegroundAction
StyledEditorKit.ItalicAction
StyledEditorKit.StyledTextAction
StyledEditorKit.UnderlineAction
TableView
TabSet
TabStop
TextAction
Utilities
View
WrappedPlainView
ZoneView
Exceptions
BadLocationException
ChangedCharSetException


javax.swing.text (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package javax.swing.text

Provides classes and interfaces that deal with editable and noneditable text components.

See:
Description

Interface Summary
AbstractDocument.AttributeContext | An interface that can be used to allow MutableAttributeSet implementations to use pluggable attribute compression techniques.
AbstractDocument.Content | Interface to describe a sequence of character content that can be edited.
AttributeSet | A collection of unique attributes.
AttributeSet.CharacterAttribute | This interface is the type signature that is expected to be present on any attribute key that contributes to character level presentation.
AttributeSet.ColorAttribute | This interface is the type signature that is expected to be present on any attribute key that contributes to presentation of color.
AttributeSet.FontAttribute | This interface is the type signature that is expected to be present on any attribute key that contributes to the determination of what font to use to render some text.
AttributeSet.ParagraphAttribute | This interface is the type signature that is expected to be present on any attribute key that contributes to the paragraph level presentation.
Caret | A place within a document view that represents where things can be inserted into the document model.
Document | The Document is a container for text that serves as the model for swing text components.
Element | Interface to describe a structural piece of a document.
Highlighter | An interface for an object that allows one to mark up the background with colored areas.
Highlighter.Highlight |
Highlighter.HighlightPainter | Highlight renderer.
Keymap | A collection of bindings of KeyStrokes to actions.
MutableAttributeSet | A generic interface for a mutable collection of unique attributes.
Position | Represents a location within a document.
Style | A collection of attributes to associate with an element in a document.
StyledDocument | Interface for a generic styled document.
TabableView | Interface for Views that have size dependent upon tabs.
TabExpander | Simple interface to allow for different types of implementations of tab expansion.
ViewFactory | A factory to create a view of some portion of document subject.

Class Summary
AbstractDocument | An implementation of the document interface to serve as a basis for implementing various kinds of documents.
AbstractDocument.ElementEdit | An implementation of ElementChange that can be added to the document event.
AbstractWriter | AbstractWriter is an abstract class that actually does the work of writing out the element tree including the attributes.
AsyncBoxView | A box that does layout asynchronously.
BoxView | A view that arranges its children into a box shape by tiling its children along an axis.
ComponentView | Component decorator that implements the view interface.
CompositeView | CompositeView is an abstract View implementation which manages one or more child views.
DateFormatter | DateFormatter is an InternationalFormatter that does its formatting by way of an instance of java.text.DateFormat.
DefaultCaret | A default implementation of Caret.
DefaultEditorKit | This is the set of things needed by a text component to be a reasonably functioning editor for some type of text document.
DefaultEditorKit.BeepAction | Creates a beep.
DefaultEditorKit.CopyAction | Copies the selected region and place its contents into the system clipboard.
DefaultEditorKit.CutAction | Cuts the selected region and place its contents into the system clipboard.
DefaultEditorKit.DefaultKeyTypedAction | The action that is executed by default if a key typed event is received and there is no keymap entry.
DefaultEditorKit.InsertBreakAction | Places a line/paragraph break into the document.
DefaultEditorKit.InsertContentAction | Places content into the associated document.
DefaultEditorKit.InsertTabAction | Places a tab character into the document.
DefaultEditorKit.PasteAction | Pastes the contents of the system clipboard into the selected region, or before the caret if nothing is selected.
DefaultFormatter | DefaultFormatter formats aribtrary objects.
DefaultFormatterFactory | An implementation of JFormattedTextField.AbstractFormatterFactory.
DefaultHighlighter | Implements the Highlighter interfaces.
DefaultHighlighter.DefaultHighlightPainter | Simple highlight painter that fills a highlighted area with a solid color.
DefaultStyledDocument | A document that can be marked up with character and paragraph styles in a manner similar to the Rich Text Format.
DefaultStyledDocument.AttributeUndoableEdit | An UndoableEdit used to remember AttributeSet changes to an Element.
DefaultStyledDocument.ElementSpec | Specification for building elements.
DefaultTextUI | Deprecated.
DocumentFilter | DocumentFilter, as the name implies, is a filter for the Document mutation methods.
DocumentFilter.FilterBypass | Used as a way to circumvent calling back into the Document to change it.
EditorKit | Establishes the set of things needed by a text component to be a reasonably functioning editor for some type of text content.
ElementIterator | ElementIterator, as the name suggests, iteratates over the Element tree.
FieldView | Extends the multi-line plain text view to be suitable for a single-line editor view.
FlowView | A View that tries to flow it's children into some partially constrained space.
FlowView.FlowStrategy | Strategy for maintaining the physical form of the flow.
GapContent | An implementation of the AbstractDocument.Content interface implemented using a gapped buffer similar to that used by emacs.
GlyphView | A GlyphView is a styled chunk of text that represents a view mapped over an element in the text model.
GlyphView.GlyphPainter | A class to perform rendering of the glyphs.
IconView | Icon decorator that implements the view interface.
InternationalFormatter | InternationalFormatter extends DefaultFormatter, using an instance of java.text.Format to handle the conversion to a String, and the conversion from a String.
JTextComponent | JTextComponent is the base class for swing text components.
JTextComponent.KeyBinding | Binding record for creating key bindings.
LabelView | A LabelView is a styled chunk of text that represents a view mapped over an element in the text model.
LayeredHighlighter |
LayeredHighlighter.LayerPainter | Layered highlight renderer.
LayoutQueue | A queue of text layout tasks.
MaskFormatter | MaskFormatter is used to format and edit strings.
NavigationFilter | NavigationFilter can be used to restrict where the cursor can be positioned.
NavigationFilter.FilterBypass | Used as a way to circumvent calling back into the caret to position the cursor.
NumberFormatter | NumberFormatter subclasses InternationalFormatter adding special behavior for numbers.
ParagraphView | View of a simple line-wrapping paragraph that supports multiple fonts, colors, components, icons, etc.
PasswordView | Implements a View suitable for use in JPasswordField UI implementations.
PlainDocument | A plain document that maintains no character attributes.
PlainView | Implements View interface for a simple multi-line text view that has text in one font and color.
Position.Bias | A typesafe enumeration to indicate bias to a position in the model.
Segment | A segment of a character array representing a fragment of text.
SimpleAttributeSet | A straightforward implementation of MutableAttributeSet using a hash table.
StringContent | An implementation of the AbstractDocument.Content interface that is a brute force implementation that is useful for relatively small documents and/or debugging.
StyleConstants | 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 | This is a typesafe enumeration of the well-known attributes that contribute to a character style.
StyleConstants.ColorConstants | This is a typesafe enumeration of the well-known attributes that contribute to a color.
StyleConstants.FontConstants | This is a typesafe enumeration of the well-known attributes that contribute to a font.
StyleConstants.ParagraphConstants | This is a typesafe enumeration of the well-known attributes that contribute to a paragraph style.
StyleContext | A pool of styles and their associated resources.
StyledEditorKit | This is the set of things needed by a text component to be a reasonably functioning editor for some type of text document.
StyledEditorKit.AlignmentAction | An action to set paragraph alignment.
StyledEditorKit.BoldAction | An action to toggle the bold attribute.
StyledEditorKit.FontFamilyAction | An action to set the font family in the associated JEditorPane.
StyledEditorKit.FontSizeAction | An action to set the font size in the associated JEditorPane.
StyledEditorKit.ForegroundAction | An action to set foreground color.
StyledEditorKit.ItalicAction | An action to toggle the italic attribute.
StyledEditorKit.StyledTextAction | An action that assumes it's being fired on a JEditorPane with a StyledEditorKit (or subclass) installed.
StyledEditorKit.UnderlineAction | An action to toggle the underline attribute.
TableView | 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.
TabSet | A TabSet is comprised of many TabStops.
TabStop | This class encapsulates a single tab stop (basically as tab stops are thought of by RTF).
TextAction | An Action implementation useful for key bindings that are shared across a number of different text components.
Utilities | A collection of methods to deal with various text related activities.
View | A very important part of the text package is the View class.
WrappedPlainView | View of plain text (text with only one font and color) that does line-wrapping.
ZoneView | 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.

Exception Summary
BadLocationException | This exception is to report bad locations within a document model (that is, attempts to reference a location that doesn't exist).
ChangedCharSetException | ChangedCharSetException as the name indicates is an exception thrown when the charset is changed.

Package javax.swing.text Description

Provides classes and interfaces that deal with editable and noneditable text components. Examples of text components are text fields and text areas, of which password fields and document editors are special instantiations. Features that are supported by this package include selection/highlighting, editing, style, and key mapping.

Note: Most of the Swing API is not thread safe. For details, see Threads and Swing, a section in The Java Tutorial.

Related Documentation

For overviews, tutorials, examples, guides, and tool documentation, please see:
  • Using Text Components, a section in The Java Tutorial

Since:
1.2
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


javax.swing.text Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package javax.swing.text

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class javax.swing.AbstractAction (implements javax.swing.Action, java.lang.Cloneable, java.io.Serializable)
      • class javax.swing.text.TextAction
        • class javax.swing.text.DefaultEditorKit.BeepAction
        • class javax.swing.text.DefaultEditorKit.CopyAction
        • class javax.swing.text.DefaultEditorKit.CutAction
        • class javax.swing.text.DefaultEditorKit.DefaultKeyTypedAction
        • class javax.swing.text.DefaultEditorKit.InsertBreakAction
        • class javax.swing.text.DefaultEditorKit.InsertContentAction
        • class javax.swing.text.DefaultEditorKit.InsertTabAction
        • class javax.swing.text.DefaultEditorKit.PasteAction
        • class javax.swing.text.StyledEditorKit.StyledTextAction
          • class javax.swing.text.StyledEditorKit.AlignmentAction
          • class javax.swing.text.StyledEditorKit.BoldAction
          • class javax.swing.text.StyledEditorKit.FontFamilyAction
          • class javax.swing.text.StyledEditorKit.FontSizeAction
          • class javax.swing.text.StyledEditorKit.ForegroundAction
          • class javax.swing.text.StyledEditorKit.ItalicAction
          • class javax.swing.text.StyledEditorKit.UnderlineAction
    • class javax.swing.text.AbstractDocument (implements javax.swing.text.Document, java.io.Serializable)
      • class javax.swing.text.DefaultStyledDocument (implements javax.swing.text.StyledDocument)
      • class javax.swing.text.PlainDocument
    • class javax.swing.text.AbstractDocument.AbstractElement (implements javax.swing.text.Element, javax.swing.text.MutableAttributeSet, java.io.Serializable, javax.swing.tree.TreeNode)
      • class javax.swing.text.AbstractDocument.BranchElement
        • class javax.swing.text.DefaultStyledDocument.SectionElement
      • class javax.swing.text.AbstractDocument.LeafElement
    • class javax.swing.undo.AbstractUndoableEdit (implements java.io.Serializable, javax.swing.undo.UndoableEdit)
      • class javax.swing.text.AbstractDocument.ElementEdit (implements javax.swing.event.DocumentEvent.ElementChange)
      • class javax.swing.undo.CompoundEdit
        • class javax.swing.text.AbstractDocument.DefaultDocumentEvent (implements javax.swing.event.DocumentEvent)
      • class javax.swing.text.DefaultStyledDocument.AttributeUndoableEdit
    • class javax.swing.text.AbstractWriter
    • class javax.accessibility.AccessibleContext
      • class java.awt.Component.AccessibleAWTComponent (implements javax.accessibility.AccessibleComponent, java.io.Serializable)
        • class java.awt.Container.AccessibleAWTContainer
          • class javax.swing.JComponent.AccessibleJComponent (implements javax.accessibility.AccessibleExtendedComponent)
            • class javax.swing.text.JTextComponent.AccessibleJTextComponent (implements javax.accessibility.AccessibleAction, javax.accessibility.AccessibleEditableText, javax.accessibility.AccessibleText, javax.swing.event.CaretListener, javax.swing.event.DocumentListener)
    • class javax.swing.text.AsyncBoxView.ChildLocator
    • class javax.swing.text.AsyncBoxView.ChildState (implements java.lang.Runnable)
    • class java.awt.Component (implements java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable)
      • class java.awt.Container
        • class javax.swing.JComponent (implements java.io.Serializable)
          • class javax.swing.text.JTextComponent (implements javax.accessibility.Accessible, javax.swing.Scrollable)
    • class javax.swing.plaf.ComponentUI
      • class javax.swing.plaf.TextUI
        • class javax.swing.plaf.basic.BasicTextUI (implements javax.swing.text.ViewFactory)
          • class javax.swing.text.DefaultTextUI
    • class javax.swing.text.DefaultStyledDocument.ElementBuffer (implements java.io.Serializable)
    • class javax.swing.text.DefaultStyledDocument.ElementSpec
    • class javax.swing.text.DocumentFilter
    • class javax.swing.text.DocumentFilter.FilterBypass
    • class javax.swing.text.EditorKit (implements java.lang.Cloneable, java.io.Serializable)
      • class javax.swing.text.DefaultEditorKit
        • class javax.swing.text.StyledEditorKit
    • class javax.swing.text.ElementIterator (implements java.lang.Cloneable)
    • class javax.swing.text.FlowView.FlowStrategy
    • class javax.swing.text.GapVector (implements java.io.Serializable)
      • class javax.swing.text.GapContent (implements javax.swing.text.AbstractDocument.Content, java.io.Serializable)
    • class javax.swing.text.GlyphView.GlyphPainter
    • class javax.swing.JFormattedTextField.AbstractFormatter (implements java.io.Serializable)
      • class javax.swing.text.DefaultFormatter (implements java.lang.Cloneable, java.io.Serializable)
        • class javax.swing.text.InternationalFormatter
          • class javax.swing.text.DateFormatter
          • class javax.swing.text.NumberFormatter
        • class javax.swing.text.MaskFormatter
    • class javax.swing.JFormattedTextField.AbstractFormatterFactory
      • class javax.swing.text.DefaultFormatterFactory (implements java.io.Serializable)
    • class javax.swing.text.JTextComponent.KeyBinding
    • class javax.swing.text.LayeredHighlighter (implements javax.swing.text.Highlighter)
      • class javax.swing.text.DefaultHighlighter
    • class javax.swing.text.LayeredHighlighter.LayerPainter (implements javax.swing.text.Highlighter.HighlightPainter)
      • class javax.swing.text.DefaultHighlighter.DefaultHighlightPainter
    • class javax.swing.text.LayoutQueue
    • class javax.swing.text.NavigationFilter
    • class javax.swing.text.NavigationFilter.FilterBypass
    • class javax.swing.text.Position.Bias
    • class java.awt.geom.RectangularShape (implements java.lang.Cloneable, java.awt.Shape)
      • class java.awt.geom.Rectangle2D
        • class java.awt.Rectangle (implements java.io.Serializable, java.awt.Shape)
          • class javax.swing.text.DefaultCaret (implements javax.swing.text.Caret, java.awt.event.FocusListener, java.awt.event.MouseListener, java.awt.event.MouseMotionListener)
    • class javax.swing.text.Segment (implements java.text.CharacterIterator, java.lang.Cloneable)
    • class javax.swing.text.SimpleAttributeSet (implements java.lang.Cloneable, javax.swing.text.MutableAttributeSet, java.io.Serializable)
    • class javax.swing.text.StringContent (implements javax.swing.text.AbstractDocument.Content, java.io.Serializable)
    • class javax.swing.text.StyleConstants
      • class javax.swing.text.StyleConstants.CharacterConstants (implements javax.swing.text.AttributeSet.CharacterAttribute)
      • class javax.swing.text.StyleConstants.ColorConstants (implements javax.swing.text.AttributeSet.CharacterAttribute, javax.swing.text.AttributeSet.ColorAttribute)
      • class javax.swing.text.StyleConstants.FontConstants (implements javax.swing.text.AttributeSet.CharacterAttribute, javax.swing.text.AttributeSet.FontAttribute)
      • class javax.swing.text.StyleConstants.ParagraphConstants (implements javax.swing.text.AttributeSet.ParagraphAttribute)
    • class javax.swing.text.StyleContext (implements javax.swing.text.AbstractDocument.AttributeContext, java.io.Serializable)
    • class javax.swing.text.StyleContext.NamedStyle (implements java.io.Serializable, javax.swing.text.Style)
    • class javax.swing.text.StyleContext.SmallAttributeSet (implements javax.swing.text.AttributeSet)
    • class javax.swing.text.TabSet (implements java.io.Serializable)
    • class javax.swing.text.TabStop (implements java.io.Serializable)
    • class java.lang.Throwable (implements java.io.Serializable)
      • class java.lang.Exception
        • class javax.swing.text.BadLocationException
        • class java.io.IOException
          • class javax.swing.text.ChangedCharSetException
    • class javax.swing.text.Utilities
    • class javax.swing.text.View (implements javax.swing.SwingConstants)
      • class javax.swing.text.AsyncBoxView
      • class javax.swing.text.ComponentView
      • class javax.swing.text.CompositeView
        • class javax.swing.text.BoxView
          • class javax.swing.text.FlowView
            • class javax.swing.text.ParagraphView (implements javax.swing.text.TabExpander)
          • class javax.swing.text.TableView
          • class javax.swing.text.TableView.TableCell (implements javax.swing.text.TableView.GridCell)
          • class javax.swing.text.TableView.TableRow
          • class javax.swing.text.WrappedPlainView (implements javax.swing.text.TabExpander)
          • class javax.swing.text.ZoneView
      • class javax.swing.text.GlyphView (implements java.lang.Cloneable, javax.swing.text.TabableView)
        • class javax.swing.text.LabelView (implements javax.swing.text.TabableView)
      • class javax.swing.text.IconView
      • class javax.swing.text.PlainView (implements javax.swing.text.TabExpander)
        • class javax.swing.text.FieldView
          • class javax.swing.text.PasswordView

Interface Hierarchy

  • interface javax.swing.text.AbstractDocument.AttributeContext
  • interface javax.swing.text.AbstractDocument.Content
  • interface javax.swing.text.AttributeSet
    • interface javax.swing.text.MutableAttributeSet
      • interface javax.swing.text.Style
  • interface javax.swing.text.AttributeSet.CharacterAttribute
  • interface javax.swing.text.AttributeSet.ColorAttribute
  • interface javax.swing.text.AttributeSet.FontAttribute
  • interface javax.swing.text.AttributeSet.ParagraphAttribute
  • interface javax.swing.text.Caret
  • interface javax.swing.text.Document
    • interface javax.swing.text.StyledDocument
  • interface javax.swing.text.Element
  • interface javax.swing.text.Highlighter
  • interface javax.swing.text.Highlighter.Highlight
  • interface javax.swing.text.Highlighter.HighlightPainter
  • interface javax.swing.text.Keymap
  • interface javax.swing.text.Position
  • interface javax.swing.text.TabableView
  • interface javax.swing.text.TabExpander
  • interface javax.swing.text.ViewFactory
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package javax.swing.text (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
javax.swing.text

Packages that use javax.swing.text
java.awt | Contains all of the classes for creating user interfaces and for painting graphics and images.
javax.accessibility | Defines a contract between user-interface components and an assistive technology that provides access to those components.
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.event | Provides for events fired by Swing components.
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 | Provides user interface objects built according to the Basic look and feel.
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 | Provides user interface objects that combine two or more look and feels.
javax.swing.text | Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.text.html | Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.
javax.swing.text.html.parser | Provides the default HTML parser, along with support classes.
javax.swing.text.rtf | Provides a class (RTFEditorKit) for creating Rich-Text-Format text editors.
javax.swing.tree | Provides classes and interfaces for dealing with javax.swing.JTree.

Classes in javax.swing.text used by java.awt
AttributeSet
A collection of unique attributes.

Classes in javax.swing.text used by javax.accessibility
AttributeSet
A collection of unique attributes.

Classes in javax.swing.text used by javax.swing
AttributeSet
A collection of unique attributes.
BadLocationException
This exception is to report bad locations within a document model (that is, attempts to reference a location that doesn't exist).
Document
The Document is a container for text that serves as the model for swing text components.
DocumentFilter
DocumentFilter, as the name implies, is a filter for the Document mutation methods.
EditorKit
Establishes the set of things needed by a text component to be a reasonably functioning editor for some type of text content.
Element
Interface to describe a structural piece of a document.
JTextComponent
JTextComponent is the base class for swing text components.
JTextComponent.AccessibleJTextComponent
This class implements accessibility support for the JTextComponent class.
JTextComponent.KeyBinding
Binding record for creating key bindings.
MutableAttributeSet
A generic interface for a mutable collection of unique attributes.
NavigationFilter
NavigationFilter can be used to restrict where the cursor can be positioned.
Position.Bias
A typesafe enumeration to indicate bias to a position in the model.
Style
A collection of attributes to associate with an element in a document.
StyledDocument
Interface for a generic styled document.
StyledEditorKit
This is the set of things needed by a text component to be a reasonably functioning editor for some type of text document.

Classes in javax.swing.text used by javax.swing.event
Document
The Document is a container for text that serves as the model for swing text components.
Element
Interface to describe a structural piece of a document.

Classes in javax.swing.text used by javax.swing.plaf
BadLocationException
This exception is to report bad locations within a document model (that is, attempts to reference a location that doesn't exist).
EditorKit
Establishes the set of things needed by a text component to be a reasonably functioning editor for some type of text content.
JTextComponent
JTextComponent is the base class for swing text components.
Position.Bias
A typesafe enumeration to indicate bias to a position in the model.
View
A very important part of the text package is the View class.

Classes in javax.swing.text used by javax.swing.plaf.basic
BadLocationException
This exception is to report bad locations within a document model (that is, attempts to reference a location that doesn't exist).
Caret
A place within a document view that represents where things can be inserted into the document model.
DefaultCaret
A default implementation of Caret.
DefaultHighlighter
Implements the Highlighter interfaces.
EditorKit
Establishes the set of things needed by a text component to be a reasonably functioning editor for some type of text content.
Element
Interface to describe a structural piece of a document.
Highlighter
An interface for an object that allows one to mark up the background with colored areas.
JTextComponent
JTextComponent is the base class for swing text components.
Keymap
A collection of bindings of KeyStrokes to actions.
LayeredHighlighter
Position.Bias
A typesafe enumeration to indicate bias to a position in the model.
View
A very important part of the text package is the View class.
ViewFactory
A factory to create a view of some portion of document subject.

Classes in javax.swing.text used by javax.swing.plaf.metal
ViewFactory
A factory to create a view of some portion of document subject.

Classes in javax.swing.text used by javax.swing.plaf.multi
BadLocationException
This exception is to report bad locations within a document model (that is, attempts to reference a location that doesn't exist).
EditorKit
Establishes the set of things needed by a text component to be a reasonably functioning editor for some type of text content.
JTextComponent
JTextComponent is the base class for swing text components.
Position.Bias
A typesafe enumeration to indicate bias to a position in the model.
View
A very important part of the text package is the View class.

Classes in javax.swing.text used by javax.swing.text
AbstractDocument
An implementation of the document interface to serve as a basis for implementing various kinds of documents.
AbstractDocument.AbstractElement
Implements the abstract part of an element.
AbstractDocument.AttributeContext
An interface that can be used to allow MutableAttributeSet implementations to use pluggable attribute compression techniques.
AbstractDocument.BranchElement
Implements a composite element that contains other elements.
AbstractDocument.Content
Interface to describe a sequence of character content that can be edited.
AbstractDocument.DefaultDocumentEvent
Stores document changes as the document is being modified.
AsyncBoxView.ChildLocator
A class to manage the effective position of the child views in a localized area while changes are being made around the localized area.
AsyncBoxView.ChildState
A record representing the layout state of a child view.
AttributeSet
A collection of unique attributes.
AttributeSet.CharacterAttribute
This interface is the type signature that is expected to be present on any attribute key that contributes to character level presentation.
AttributeSet.ColorAttribute
This interface is the type signature that is expected to be present on any attribute key that contributes to presentation of color.
AttributeSet.FontAttribute
This interface is the type signature that is expected to be present on any attribute key that contributes to the determination of what font to use to render some text.
AttributeSet.ParagraphAttribute
This interface is the type signature that is expected to be present on any attribute key that contributes to the paragraph level presentation.
BadLocationException
This exception is to report bad locations within a document model (that is, attempts to reference a location that doesn't exist).
BoxView
A view that arranges its children into a box shape by tiling its children along an axis.
Caret
A place within a document view that represents where things can be inserted into the document model.
CompositeView
CompositeView is an abstract View implementation which manages one or more child views.
DefaultEditorKit
This is the set of things needed by a text component to be a reasonably functioning editor for some type of text document.
DefaultFormatter
DefaultFormatter formats aribtrary objects.
DefaultStyledDocument.ElementBuffer
Class to manage changes to the element hierarchy.
DefaultStyledDocument.ElementSpec
Specification for building elements.
Document
The Document is a container for text that serves as the model for swing text components.
DocumentFilter
DocumentFilter, as the name implies, is a filter for the Document mutation methods.
DocumentFilter.FilterBypass
Used as a way to circumvent calling back into the Document to change it.
EditorKit
Establishes the set of things needed by a text component to be a reasonably functioning editor for some type of text content.
Element
Interface to describe a structural piece of a document.
ElementIterator
ElementIterator, as the name suggests, iteratates over the Element tree.
FieldView
Extends the multi-line plain text view to be suitable for a single-line editor view.
FlowView
A View that tries to flow it's children into some partially constrained space.
FlowView.FlowStrategy
Strategy for maintaining the physical form of the flow.
GlyphView
A GlyphView is a styled chunk of text that represents a view mapped over an element in the text model.
GlyphView.GlyphPainter
A class to perform rendering of the glyphs.
Highlighter
An interface for an object that allows one to mark up the background with colored areas.
Highlighter.Highlight
Highlighter.HighlightPainter
Highlight renderer.
InternationalFormatter
InternationalFormatter extends DefaultFormatter, using an instance of java.text.Format to handle the conversion to a String, and the conversion from a String.
JTextComponent
JTextComponent is the base class for swing text components.
JTextComponent.KeyBinding
Binding record for creating key bindings.
Keymap
A collection of bindings of KeyStrokes to actions.
LayeredHighlighter
LayeredHighlighter.LayerPainter
Layered highlight renderer.
LayoutQueue
A queue of text layout tasks.
MutableAttributeSet
A generic interface for a mutable collection of unique attributes.
NavigationFilter
NavigationFilter can be used to restrict where the cursor can be positioned.
NavigationFilter.FilterBypass
Used as a way to circumvent calling back into the caret to position the cursor.
PlainView
Implements View interface for a simple multi-line text view that has text in one font and color.
Position
Represents a location within a document.
Position.Bias
A typesafe enumeration to indicate bias to a position in the model.
Segment
A segment of a character array representing a fragment of text.
Style
A collection of attributes to associate with an element in a document.
StyleConstants
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.
StyleContext
A pool of styles and their associated resources.
StyleContext.SmallAttributeSet
This class holds a small number of attributes in an array.
StyledDocument
Interface for a generic styled document.
StyledEditorKit
This is the set of things needed by a text component to be a reasonably functioning editor for some type of text document.
StyledEditorKit.StyledTextAction
An action that assumes it's being fired on a JEditorPane with a StyledEditorKit (or subclass) installed.
TabableView
Interface for Views that have size dependent upon tabs.
TabExpander
Simple interface to allow for different types of implementations of tab expansion.
TableView.TableCell
Deprecated. A table cell can now be any View implementation.
TableView.TableRow
View of a row in a row-centric table.
TabSet
A TabSet is comprised of many TabStops.
TabStop
This class encapsulates a single tab stop (basically as tab stops are thought of by RTF).
TextAction
An Action implementation useful for key bindings that are shared across a number of different text components.
View
A very important part of the text package is the View class.
ViewFactory
A factory to create a view of some portion of document subject.

Classes in javax.swing.text used by javax.swing.text.html
AbstractDocument
An implementation of the document interface to serve as a basis for implementing various kinds of documents.
AbstractDocument.AbstractElement
Implements the abstract part of an element.
AbstractDocument.AttributeContext
An interface that can be used to allow MutableAttributeSet implementations to use pluggable attribute compression techniques.
AbstractDocument.BranchElement
Implements a composite element that contains other elements.
AbstractDocument.Content
Interface to describe a sequence of character content that can be edited.
AbstractDocument.DefaultDocumentEvent
Stores document changes as the document is being modified.
AbstractDocument.LeafElement
Implements an element that directly represents content of some kind.
AbstractWriter
AbstractWriter is an abstract class that actually does the work of writing out the element tree including the attributes.
AttributeSet
A collection of unique attributes.
BadLocationException
This exception is to report bad locations within a document model (that is, attempts to reference a location that doesn't exist).
BoxView
A view that arranges its children into a box shape by tiling its children along an axis.
ComponentView
Component decorator that implements the view interface.
CompositeView
CompositeView is an abstract View implementation which manages one or more child views.
DefaultEditorKit
This is the set of things needed by a text component to be a reasonably functioning editor for some type of text document.
DefaultStyledDocument
A document that can be marked up with character and paragraph styles in a manner similar to the Rich Text Format.
DefaultStyledDocument.ElementSpec
Specification for building elements.
Document
The Document is a container for text that serves as the model for swing text components.
EditorKit
Establishes the set of things needed by a text component to be a reasonably functioning editor for some type of text content.
Element
Interface to describe a structural piece of a document.
GlyphView
A GlyphView is a styled chunk of text that represents a view mapped over an element in the text model.
LabelView
A LabelView is a styled chunk of text that represents a view mapped over an element in the text model.
MutableAttributeSet
A generic interface for a mutable collection of unique attributes.
ParagraphView
View of a simple line-wrapping paragraph that supports multiple fonts, colors, components, icons, etc.
Position.Bias
A typesafe enumeration to indicate bias to a position in the model.
Style
A collection of attributes to associate with an element in a document.
StyleContext
A pool of styles and their associated resources.
StyleContext.SmallAttributeSet
This class holds a small number of attributes in an array.
StyledDocument
Interface for a generic styled document.
StyledEditorKit
This is the set of things needed by a text component to be a reasonably functioning editor for some type of text document.
StyledEditorKit.StyledTextAction
An action that assumes it's being fired on a JEditorPane with a StyledEditorKit (or subclass) installed.
TabableView
Interface for Views that have size dependent upon tabs.
TextAction
An Action implementation useful for key bindings that are shared across a number of different text components.
View
A very important part of the text package is the View class.
ViewFactory
A factory to create a view of some portion of document subject.

Classes in javax.swing.text used by javax.swing.text.html.parser
ChangedCharSetException
ChangedCharSetException as the name indicates is an exception thrown when the charset is changed.
SimpleAttributeSet
A straightforward implementation of MutableAttributeSet using a hash table.

Classes in javax.swing.text used by javax.swing.text.rtf
BadLocationException
This exception is to report bad locations within a document model (that is, attempts to reference a location that doesn't exist).
DefaultEditorKit
This is the set of things needed by a text component to be a reasonably functioning editor for some type of text document.
Document
The Document is a container for text that serves as the model for swing text components.
EditorKit
Establishes the set of things needed by a text component to be a reasonably functioning editor for some type of text content.
StyledEditorKit
This is the set of things needed by a text component to be a reasonably functioning editor for some type of text document.

Classes in javax.swing.text used by javax.swing.tree
JTextComponent
JTextComponent is the base class for swing text components.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


ParagraphView (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class ParagraphView

java.lang.Object
    extended by javax.swing.text.View
        extended by javax.swing.text.CompositeView
            extended by javax.swing.text.BoxView
                extended by javax.swing.text.FlowView
                    extended by javax.swing.text.ParagraphView
All Implemented Interfaces:
SwingConstants, TabExpander
Direct Known Subclasses:
ParagraphView
public class ParagraphView
extends FlowView
implements TabExpander

View of a simple line-wrapping paragraph that supports multiple fonts, colors, components, icons, etc. It is basically a vertical box with a margin around it. The contents of the box are a bunch of rows which are special horizontal boxes. This view creates a collection of views that represent the child elements of the paragraph element. Each of these views are placed into a row directly if they will fit, otherwise the breakView method is called to try and carve the view into pieces that fit.

See Also:
View

Nested Class Summary
Nested classes inherited from class javax.swing.text.FlowView
FlowView.FlowStrategy
Field Summary
protected  int firstLineIndent
Indentation for the first line, from the left inset.
Fields inherited from class javax.swing.text.FlowView
layoutPool, layoutSpan, strategy
Fields inherited from class javax.swing.text.View
BadBreakWeight, ExcellentBreakWeight, ForcedBreakWeight, GoodBreakWeight, X_AXIS, Y_AXIS
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
Constructor Summary
ParagraphView(Element elem)
Constructs a ParagraphView for the given element.
Method Summary
protected void | adjustRow(javax.swing.text.ParagraphView.Row r, int desiredSpan, int x) Adjusts the given row if possible to fit within the layout span.
View | breakView(int axis, float len, Shape a) Breaks this view on the given axis at the given length.
void | changedUpdate(DocumentEvent changes, Shape a, ViewFactory f) Gives notification from the document that attributes were changed in a location that this view is responsible for.
protected View | createRow() Create a View that should be used to hold a a row's worth of children in a flow.
protected int | findOffsetToCharactersInString(char[] string, int start) Finds the next character in the document with a character in string, starting at offset start.
protected boolean | flipEastAndWestAtEnds(int position, Position.Bias bias) Determines in which direction the next view lays.
float | getAlignment(int axis) Determines the desired alignment for this view along an axis.
int | getBreakWeight(int axis, float len) Gets the break weight for a given location.
protected int | getClosestPositionTo(int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet, int rowIndex, int x) Returns the closest model position to x.
int | getFlowSpan(int index) Fetches the constraining span to flow against for the given child index.
int | getFlowStart(int index) Fetches the location along the flow axis that the flow span will start at.
protected View | getLayoutView(int index) Returns the view at a given index.
protected int | getLayoutViewCount() Returns the number of views that this view is responsible for.
protected int | getNextNorthSouthVisualPositionFrom(int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet) Returns the next visual position for the cursor, in either the east or west direction.
protected float | getPartialSize(int startOffset, int endOffset) Returns the size used by the views between startOffset and endOffset.
protected float | getTabBase() Returns where the tabs are calculated from.
protected TabSet | getTabSet() Gets the Tabset to be used in calculating tabs.
float | nextTabStop(float x, int tabOffset) Returns the next tab stop position given a reference position.
void | paint(Graphics g, Shape a) Renders using the given rendering surface and area on that surface.
protected void | setFirstLineIndent(float fi) Sets the indent on the first line.
protected void | setJustification(int j) Sets the type of justification.
protected void | setLineSpacing(float ls) Sets the line spacing.
protected void | setPropertiesFromAttributes() Set the cached properties from the attributes.
Methods inherited from class javax.swing.text.FlowView
calculateMinorAxisRequirements, getFlowAxis, getViewIndexAtPosition, insertUpdate, layout, loadChildren, removeUpdate
Methods inherited from class javax.swing.text.BoxView
baselineLayout, baselineRequirements, calculateMajorAxisRequirements, childAllocation, forwardUpdate, getAxis, getChildAllocation, getHeight, getMaximumSpan, getMinimumSpan, getOffset, getPreferredSpan, getResizeWeight, getSpan, getViewAtPoint, getWidth, isAfter, isAllocationValid, isBefore, isLayoutValid, layoutChanged, layoutMajorAxis, layoutMinorAxis, modelToView, paintChild, preferenceChanged, replace, setAxis, setSize, viewToModel
Methods inherited from class javax.swing.text.CompositeView
getBottomInset, getInsideAllocation, getLeftInset, getNextEastWestVisualPositionFrom, getNextVisualPositionFrom, getRightInset, getTopInset, getView, getViewAtPosition, getViewCount, getViewIndex, modelToView, setInsets, setParagraphInsets, setParent
Methods inherited from class javax.swing.text.View
append, breakView, createFragment, forwardUpdateToView, getAttributes, getBreakWeight, getContainer, getDocument, getElement, getEndOffset, getGraphics, getParent, getStartOffset, getToolTipText, getViewFactory, getViewIndex, insert, isVisible, modelToView, remove, removeAll, updateChildren, updateLayout, viewToModel
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

firstLineIndent

protected int firstLineIndent
Indentation for the first line, from the left inset.

Constructor Detail

ParagraphView

public ParagraphView(Element elem)
Constructs a ParagraphView for the given element.

Parameters:
elem - the element that this view is responsible for
Method Detail

setJustification

protected void setJustification(int j)
Sets the type of justification.

Parameters:
j - one of the following values:
  • StyleConstants.ALIGN_LEFT
  • StyleConstants.ALIGN_CENTER
  • StyleConstants.ALIGN_RIGHT

setLineSpacing

protected void setLineSpacing(float ls)
Sets the line spacing.

Parameters:
ls - the value is a factor of the line hight

setFirstLineIndent

protected void setFirstLineIndent(float fi)
Sets the indent on the first line.

Parameters:
fi - the value in points

setPropertiesFromAttributes

protected void setPropertiesFromAttributes()
Set the cached properties from the attributes.

getLayoutViewCount

protected int getLayoutViewCount()
Returns the number of views that this view is responsible for. The child views of the paragraph are rows which have been used to arrange pieces of the Views that represent the child elements. This is the number of views that have been tiled in two dimensions, and should be equivalent to the number of child elements to the element this view is responsible for.

Returns:
the number of views that this ParagraphView is responsible for

getLayoutView

protected View getLayoutView(int index)
Returns the view at a given index. The child views of the paragraph are rows which have been used to arrange pieces of the Views that represent the child elements. This methods returns the view responsible for the child element index (prior to breaking). These are the Views that were produced from a factory (to represent the child elements) and used for layout.

Parameters:
index - the index of the desired view
Returns:
the view at index

adjustRow

protected void adjustRow(javax.swing.text.ParagraphView.Row r,
                         int desiredSpan,
                         int x)
Adjusts the given row if possible to fit within the layout span. By default this will try to find the highest break weight possible nearest the end of the row. If a forced break is encountered, the break will be positioned there.

This is meant for internal usage, and should not be used directly.

Parameters:
r - the row to adjust to the current layout span
desiredSpan - the current layout span >= 0
x - the location r starts at

getNextNorthSouthVisualPositionFrom

protected int getNextNorthSouthVisualPositionFrom(int pos,
                                                  Position.Bias b,
                                                  Shape a,
                                                  int direction,
                                                  Position.Bias[] biasRet)
                                           throws BadLocationException
Returns the next visual position for the cursor, in either the east or west direction. Overridden from CompositeView.

Overrides:
getNextNorthSouthVisualPositionFrom in class CompositeView
Parameters:
pos - position into the model
b - either Position.Bias.Forward or Position.Bias.Backward
a - the allocated region to render into
direction - either SwingConstants.NORTH or SwingConstants.SOUTH
biasRet - an array containing the bias that were checked in this method
Returns:
the location in the model that represents the next location visual position
Throws:
BadLocationException
See Also:
CompositeView.getNextVisualPositionFrom(int, javax.swing.text.Position.Bias, java.awt.Shape, int, javax.swing.text.Position.Bias[])

getClosestPositionTo

protected int getClosestPositionTo(int pos,
                                   Position.Bias b,
                                   Shape a,
                                   int direction,
                                   Position.Bias[] biasRet,
                                   int rowIndex,
                                   int x)
                            throws BadLocationException
Returns the closest model position to x. rowIndex gives the index of the view that corresponds that should be looked in.

Parameters:
pos - position into the model
a - the allocated region to render into
direction - one of the following values:
  • SwingConstants.NORTH
  • SwingConstants.SOUTH
biasRet - an array containing the bias that were checked in this method
rowIndex - the index of the view
x - the x coordinate of interest
Returns:
the closest model position to x
Throws:
BadLocationException

flipEastAndWestAtEnds

protected boolean flipEastAndWestAtEnds(int position,
                                        Position.Bias bias)
Determines in which direction the next view lays. Consider the View at index n. Typically the Views are layed out from left to right, so that the View to the EAST will be at index n + 1, and the View to the WEST will be at index n - 1. In certain situations, such as with bidirectional text, it is possible that the View to EAST is not at index n + 1, but rather at index n - 1, or that the View to the WEST is not at index n - 1, but index n + 1. In this case this method would return true, indicating the Views are layed out in descending order.

This will return true if the text is layed out right to left at position, otherwise false.

Overrides:
flipEastAndWestAtEnds in class BoxView
Parameters:
position - position into the model
bias - either Position.Bias.Forward or Position.Bias.Backward
Returns:
true if the text is layed out right to left at position, otherwise false.

getFlowSpan

public int getFlowSpan(int index)
Fetches the constraining span to flow against for the given child index.

Overrides:
getFlowSpan in class FlowView
Parameters:
index - the index of the view being queried
Returns:
the constraining span for the given view at index
See Also:
FlowView.getFlowStart(int)

getFlowStart

public int getFlowStart(int index)
Fetches the location along the flow axis that the flow span will start at.

Overrides:
getFlowStart in class FlowView
Parameters:
index - the index of the view being queried
Returns:
the location for the given view at index
See Also:
FlowView.getFlowSpan(int)

createRow

protected View createRow()
Create a View that should be used to hold a a row's worth of children in a flow.

Specified by:
createRow in class FlowView
Returns:
the new View

nextTabStop

public float nextTabStop(float x,
                         int tabOffset)
Returns the next tab stop position given a reference position. This view implements the tab coordinate system, and calls getTabbedSpan on the logical children in the process of layout to determine the desired span of the children. The logical children can delegate their tab expansion upward to the paragraph which knows how to expand tabs. LabelView is an example of a view that delegates its tab expansion needs upward to the paragraph.

This is implemented to try and locate a TabSet in the paragraph element's attribute set. If one can be found, its settings will be used, otherwise a default expansion will be provided. The base location for for tab expansion is the left inset from the paragraphs most recent allocation (which is what the layout of the children is based upon).

Specified by:
nextTabStop in interface TabExpander
Parameters:
x - the X reference position
tabOffset - the position within the text stream that the tab occurred at >= 0
Returns:
the trailing end of the tab expansion >= 0
See Also:
TabSet, TabStop, LabelView

getTabSet

protected TabSet getTabSet()
Gets the Tabset to be used in calculating tabs.

Returns:
the TabSet

getPartialSize

protected float getPartialSize(int startOffset,
                               int endOffset)
Returns the size used by the views between startOffset and endOffset. This uses getPartialView to calculate the size if the child view implements the TabableView interface. If a size is needed and a View does not implement the TabableView interface, the preferredSpan will be used.

Parameters:
startOffset - the starting document offset >= 0
endOffset - the ending document offset >= startOffset
Returns:
the size >= 0

findOffsetToCharactersInString

protected int findOffsetToCharactersInString(char[] string,
                                             int start)
Finds the next character in the document with a character in string, starting at offset start. If there are no characters found, -1 will be returned.

Parameters:
string - the string of characters
start - where to start in the model >= 0
Returns:
the document offset, or -1 if no characters found

getTabBase

protected float getTabBase()
Returns where the tabs are calculated from.

Returns:
where tabs are calculated from

paint

public void paint(Graphics g,
                  Shape a)
Renders using the given rendering surface and area on that surface. This is implemented to delgate to the superclass after stashing the base coordinate for tab calculations.

Overrides:
paint in class BoxView
Parameters:
g - the rendering surface to use
a - the allocated region to render into
See Also:
View.paint(java.awt.Graphics, java.awt.Shape)

getAlignment

public float getAlignment(int axis)
Determines the desired alignment for this view along an axis. This is implemented to give the alignment to the center of the first row along the y axis, and the default along the x axis.

Overrides:
getAlignment in class BoxView
Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
Returns:
the desired alignment. This should be a value between 0.0 and 1.0 inclusive, where 0 indicates alignment at the origin and 1.0 indicates alignment to the full span away from the origin. An alignment of 0.5 would be the center of the view.

breakView

public View breakView(int axis,
                      float len,
                      Shape a)
Breaks this view on the given axis at the given length.

ParagraphView instances are breakable along the Y_AXIS only, and only if len is after the first line.

Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
len - specifies where a potential break is desired along the given axis >= 0
a - the current allocation of the view
Returns:
the fragment of the view that represents the given span, if the view can be broken; if the view doesn't support breaking behavior, the view itself is returned
See Also:
View.breakView(int, int, float, float)

getBreakWeight

public int getBreakWeight(int axis,
                          float len)
Gets the break weight for a given location.

ParagraphView instances are breakable along the Y_AXIS only, and only if len is after the first row. If the length is less than one row, a value of BadBreakWeight is returned.

Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
len - specifies where a potential break is desired >= 0
Returns:
a value indicating the attractiveness of breaking here; either GoodBreakWeight or BadBreakWeight
See Also:
View.getBreakWeight(int, float, float)

changedUpdate

public void changedUpdate(DocumentEvent changes,
                          Shape a,
                          ViewFactory f)
Gives notification from the document that attributes were changed in a location that this view is responsible for.

Overrides:
changedUpdate in class FlowView
Parameters:
changes - the change information from the associated document
a - the current allocation of the view
f - the factory to use to rebuild if the view has children
See Also:
View.changedUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


PasswordView (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class PasswordView

java.lang.Object
    extended by javax.swing.text.View
        extended by javax.swing.text.PlainView
            extended by javax.swing.text.FieldView
                extended by javax.swing.text.PasswordView
All Implemented Interfaces:
SwingConstants, TabExpander
public class PasswordView
extends FieldView

Implements a View suitable for use in JPasswordField UI implementations. This is basically a field ui that renders its contents as the echo character specified in the associated component (if it can narrow the component to a JPasswordField).

See Also:
View

Field Summary
Fields inherited from class javax.swing.text.PlainView
metrics
Fields inherited from class javax.swing.text.View
BadBreakWeight, ExcellentBreakWeight, ForcedBreakWeight, GoodBreakWeight, X_AXIS, Y_AXIS
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
Constructor Summary
PasswordView(Element elem)
Constructs a new view wrapped on an element.
Method Summary
protected int | drawEchoCharacter(Graphics g, int x, int y, char c) Renders the echo character, or whatever graphic should be used to display the password characters.
protected int | drawSelectedText(Graphics g, int x, int y, int p0, int p1) Renders the given range in the model as selected text.
protected int | drawUnselectedText(Graphics g, int x, int y, int p0, int p1) Renders the given range in the model as normal unselected text.
float | getPreferredSpan(int axis) Determines the preferred span for this view along an axis.
Shape | modelToView(int pos, Shape a, Position.Bias b) Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
int | viewToModel(float fx, float fy, Shape a, Position.Bias[] bias) Provides a mapping from the view coordinate space to the logical coordinate space of the model.
Methods inherited from class javax.swing.text.FieldView
adjustAllocation, getFontMetrics, getResizeWeight, insertUpdate, paint, removeUpdate
Methods inherited from class javax.swing.text.PlainView
changedUpdate, damageLineRange, drawLine, getLineBuffer, getTabSize, lineToRect, nextTabStop, setSize, updateDamage, updateMetrics
Methods inherited from class javax.swing.text.View
append, breakView, createFragment, forwardUpdate, forwardUpdateToView, getAlignment, getAttributes, getBreakWeight, getChildAllocation, getContainer, getDocument, getElement, getEndOffset, getGraphics, getMaximumSpan, getMinimumSpan, getNextVisualPositionFrom, getParent, getStartOffset, getToolTipText, getView, getViewCount, getViewFactory, getViewIndex, getViewIndex, insert, isVisible, modelToView, modelToView, preferenceChanged, remove, removeAll, replace, setParent, updateChildren, updateLayout, viewToModel
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

PasswordView

public PasswordView(Element elem)
Constructs a new view wrapped on an element.

Parameters:
elem - the element
Method Detail

drawUnselectedText

protected int drawUnselectedText(Graphics g,
                                 int x,
                                 int y,
                                 int p0,
                                 int p1)
                          throws BadLocationException
Renders the given range in the model as normal unselected text. This sets the foreground color and echos the characters using the value returned by getEchoChar().

Overrides:
drawUnselectedText in class PlainView
Parameters:
g - the graphics context
x - the starting X coordinate >= 0
y - the starting Y coordinate >= 0
p0 - the starting offset in the model >= 0
p1 - the ending offset in the model >= p0
Returns:
the X location of the end of the range >= 0
Throws:
BadLocationException - if p0 or p1 are out of range

drawSelectedText

protected int drawSelectedText(Graphics g,
                               int x,
                               int y,
                               int p0,
                               int p1)
                        throws BadLocationException
Renders the given range in the model as selected text. This is implemented to render the text in the color specified in the hosting component. It assumes the highlighter will render the selected background. Uses the result of getEchoChar() to display the characters.

Overrides:
drawSelectedText in class PlainView
Parameters:
g - the graphics context
x - the starting X coordinate >= 0
y - the starting Y coordinate >= 0
p0 - the starting offset in the model >= 0
p1 - the ending offset in the model >= p0
Returns:
the X location of the end of the range >= 0
Throws:
BadLocationException - if p0 or p1 are out of range

drawEchoCharacter

protected int drawEchoCharacter(Graphics g,
                                int x,
                                int y,
                                char c)
Renders the echo character, or whatever graphic should be used to display the password characters. The color in the Graphics object is set to the appropriate foreground color for selected or unselected text.

Parameters:
g - the graphics context
x - the starting X coordinate >= 0
y - the starting Y coordinate >= 0
c - the echo character
Returns:
the updated X position >= 0

modelToView

public Shape modelToView(int pos,
                         Shape a,
                         Position.Bias b)
                  throws BadLocationException
Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.

Overrides:
modelToView in class FieldView
Parameters:
pos - the position to convert >= 0
a - the allocated region to render into
Returns:
the bounding box of the given position
Throws:
BadLocationException - if the given position does not represent a valid location in the associated document
See Also:
View.modelToView(int, java.awt.Shape, javax.swing.text.Position.Bias)

viewToModel

public int viewToModel(float fx,
                       float fy,
                       Shape a,
                       Position.Bias[] bias)
Provides a mapping from the view coordinate space to the logical coordinate space of the model.

Overrides:
viewToModel in class FieldView
Parameters:
fx - the X coordinate >= 0.0f
fy - the Y coordinate >= 0.0f
a - the allocated region to render into
Returns:
the location within the model that best represents the given point in the view
See Also:
View.viewToModel(float, float, java.awt.Shape, javax.swing.text.Position.Bias[])

getPreferredSpan

public float getPreferredSpan(int axis)
Determines the preferred span for this view along an axis.

Overrides:
getPreferredSpan in class FieldView
Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
Returns:
the span the view would like to be rendered into >= 0. Typically the view is told to render into the span that is returned, although there is no guarantee. The parent may choose to resize or break the view.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


PlainDocument (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class PlainDocument

java.lang.Object
    extended by javax.swing.text.AbstractDocument
        extended by javax.swing.text.PlainDocument
All Implemented Interfaces:
Document, Serializable
public class PlainDocument
extends AbstractDocument

A plain document that maintains no character attributes. The default element structure for this document is a map of the lines in the text. The Element returned by getDefaultRootElement is a map of the lines, and each child element represents a line. This model does not maintain any character level attributes, but each line can be tagged with an arbitrary set of attributes. Line to offset, and offset to line translations can be quickly performed using the default root element. The structure information of the DocumentEvent's fired by edits will indicate the line structure changes.

The default content storage management is performed by a gapped buffer implementation (GapContent). It supports editing reasonably large documents with good efficiency when the edits are contiguous or clustered, as is typical.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

See Also:
Document, AbstractDocument

Nested Class Summary
Nested classes inherited from class javax.swing.text.AbstractDocument
AbstractDocument.AbstractElement, AbstractDocument.AttributeContext, AbstractDocument.BranchElement, AbstractDocument.Content, AbstractDocument.DefaultDocumentEvent, AbstractDocument.ElementEdit, AbstractDocument.LeafElement
Field Summary
static String | lineLimitAttribute Name of the attribute that specifies the maximum length of a line, if there is a maximum length.
static String | tabSizeAttribute Name of the attribute that specifies the tab size for tabs contained in the content.
Fields inherited from class javax.swing.text.AbstractDocument
BAD_LOCATION, BidiElementName, ContentElementName, ElementNameAttribute, listenerList, ParagraphElementName, SectionElementName
Fields inherited from interface javax.swing.text.Document
StreamDescriptionProperty, TitleProperty
Constructor Summary
PlainDocument()
Constructs a plain text document.
PlainDocument(AbstractDocument.Content c)
Constructs a plain text document.
Method Summary
protected AbstractDocument.AbstractElement | createDefaultRoot() Creates the root element to be used to represent the default document structure.
Element | getDefaultRootElement() Gets the default root element for the document model.
Element | getParagraphElement(int pos) Get the paragraph element containing the given position.
void | insertString(int offs, String str, AttributeSet a) Inserts some content into the document.
protected void | insertUpdate(AbstractDocument.DefaultDocumentEvent chng, AttributeSet attr) Updates document structure as a result of text insertion.
protected void | removeUpdate(AbstractDocument.DefaultDocumentEvent chng) Updates any document structure as a result of text removal.
Methods inherited from class javax.swing.text.AbstractDocument
addDocumentListener, addUndoableEditListener, createBranchElement, createLeafElement, createPosition, dump, fireChangedUpdate, fireInsertUpdate, fireRemoveUpdate, fireUndoableEditUpdate, getAsynchronousLoadPriority, getAttributeContext, getBidiRootElement, getContent, getCurrentWriter, getDocumentFilter, getDocumentListeners, getDocumentProperties, getEndPosition, getLength, getListeners, getProperty, getRootElements, getStartPosition, getText, getText, getUndoableEditListeners, postRemoveUpdate, putProperty, readLock, readUnlock, remove, removeDocumentListener, removeUndoableEditListener, render, replace, setAsynchronousLoadPriority, setDocumentFilter, setDocumentProperties, writeLock, writeUnlock
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

tabSizeAttribute

public static final String tabSizeAttribute
Name of the attribute that specifies the tab size for tabs contained in the content. The type for the value is Integer.

See Also:
Constant Field Values

lineLimitAttribute

public static final String lineLimitAttribute
Name of the attribute that specifies the maximum length of a line, if there is a maximum length. The type for the value is Integer.

See Also:
Constant Field Values
Constructor Detail

PlainDocument

public PlainDocument()
Constructs a plain text document. A default model using GapContent is constructed and set.

PlainDocument

public PlainDocument(AbstractDocument.Content c)
Constructs a plain text document. A default root element is created, and the tab size set to 8.

Parameters:
c - the container for the content
Method Detail

insertString

public void insertString(int offs,
                         String str,
                         AttributeSet a)
                  throws BadLocationException
Inserts some content into the document. Inserting content causes a write lock to be held while the actual changes are taking place, followed by notification to the observers on the thread that grabbed the write lock.

This method is thread safe, although most Swing methods are not. Please see Threads and Swing for more information.

Specified by:
insertString in interface Document
Overrides:
insertString in class AbstractDocument
Parameters:
offs - the starting offset >= 0
str - the string to insert; does nothing with null/empty strings
a - the attributes for the inserted content
Throws:
BadLocationException - the given insert position is not a valid position within the document
See Also:
Document.insertString(int, java.lang.String, javax.swing.text.AttributeSet)

getDefaultRootElement

public Element getDefaultRootElement()
Gets the default root element for the document model.

Specified by:
getDefaultRootElement in interface Document
Specified by:
getDefaultRootElement in class AbstractDocument
Returns:
the root
See Also:
Document.getDefaultRootElement()

createDefaultRoot

protected AbstractDocument.AbstractElement createDefaultRoot()
Creates the root element to be used to represent the default document structure.

Returns:
the element base

getParagraphElement

public Element getParagraphElement(int pos)
Get the paragraph element containing the given position. Since this document only models lines, it returns the line instead.

Specified by:
getParagraphElement in class AbstractDocument
Parameters:
pos - the starting offset >= 0
Returns:
the element

insertUpdate

protected void insertUpdate(AbstractDocument.DefaultDocumentEvent chng,
                            AttributeSet attr)
Updates document structure as a result of text insertion. This will happen within a write lock. Since this document simply maps out lines, we refresh the line map.

Overrides:
insertUpdate in class AbstractDocument
Parameters:
chng - the change event describing the dit
attr - the set of attributes for the inserted text

removeUpdate

protected void removeUpdate(AbstractDocument.DefaultDocumentEvent chng)
Updates any document structure as a result of text removal. This will happen within a write lock. Since the structure represents a line map, this just checks to see if the removal spans lines. If it does, the two lines outside of the removal area are joined together.

Overrides:
removeUpdate in class AbstractDocument
Parameters:
chng - the change event describing the edit
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


PlainView (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class PlainView

java.lang.Object
    extended by javax.swing.text.View
        extended by javax.swing.text.PlainView
All Implemented Interfaces:
SwingConstants, TabExpander
Direct Known Subclasses:
FieldView
public class PlainView
extends View
implements TabExpander

Implements View interface for a simple multi-line text view that has text in one font and color. The view represents each child element as a line of text.

See Also:
View

Field Summary
protected  FontMetrics metrics
Font metrics for the current font.
Fields inherited from class javax.swing.text.View
BadBreakWeight, ExcellentBreakWeight, ForcedBreakWeight, GoodBreakWeight, X_AXIS, Y_AXIS
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
Constructor Summary
PlainView(Element elem)
Constructs a new PlainView wrapped on an element.
Method Summary
void | changedUpdate(DocumentEvent changes, Shape a, ViewFactory f) Gives notification from the document that attributes were changed in a location that this view is responsible for.
protected void | damageLineRange(int line0, int line1, Shape a, Component host) Repaint the given line range.
protected void | drawLine(int lineIndex, Graphics g, int x, int y) Renders a line of text, suppressing whitespace at the end and expanding any tabs.
protected int | drawSelectedText(Graphics g, int x, int y, int p0, int p1) Renders the given range in the model as selected text.
protected int | drawUnselectedText(Graphics g, int x, int y, int p0, int p1) Renders the given range in the model as normal unselected text.
protected Segment | getLineBuffer() Gives access to a buffer that can be used to fetch text from the associated document.
float | getPreferredSpan(int axis) Determines the preferred span for this view along an axis.
protected int | getTabSize() Returns the tab size set for the document, defaulting to 8.
void | insertUpdate(DocumentEvent changes, Shape a, ViewFactory f) Gives notification that something was inserted into the document in a location that this view is responsible for.
protected Rectangle | lineToRect(Shape a, int line) Determine the rectangle that represents the given line.
Shape | modelToView(int pos, Shape a, Position.Bias b) Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
float | nextTabStop(float x, int tabOffset) Returns the next tab stop position after a given reference position.
void | paint(Graphics g, Shape a) Renders using the given rendering surface and area on that surface.
void | removeUpdate(DocumentEvent changes, Shape a, ViewFactory f) Gives notification that something was removed from the document in a location that this view is responsible for.
void | setSize(float width, float height) Sets the size of the view.
protected void | updateDamage(DocumentEvent changes, Shape a, ViewFactory f)
protected void | updateMetrics() Checks to see if the font metrics and longest line are up-to-date.
int | viewToModel(float fx, float fy, Shape a, Position.Bias[] bias) Provides a mapping from the view coordinate space to the logical coordinate space of the model.
Methods inherited from class javax.swing.text.View
append, breakView, createFragment, forwardUpdate, forwardUpdateToView, getAlignment, getAttributes, getBreakWeight, getChildAllocation, getContainer, getDocument, getElement, getEndOffset, getGraphics, getMaximumSpan, getMinimumSpan, getNextVisualPositionFrom, getParent, getResizeWeight, getStartOffset, getToolTipText, getView, getViewCount, getViewFactory, getViewIndex, getViewIndex, insert, isVisible, modelToView, modelToView, preferenceChanged, remove, removeAll, replace, setParent, updateChildren, updateLayout, viewToModel
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

metrics

protected FontMetrics metrics
Font metrics for the current font.

Constructor Detail

PlainView

public PlainView(Element elem)
Constructs a new PlainView wrapped on an element.

Parameters:
elem - the element
Method Detail

getTabSize

protected int getTabSize()
Returns the tab size set for the document, defaulting to 8.

Returns:
the tab size

drawLine

protected void drawLine(int lineIndex,
                        Graphics g,
                        int x,
                        int y)
Renders a line of text, suppressing whitespace at the end and expanding any tabs. This is implemented to make calls to the methods drawUnselectedText and drawSelectedText so that the way selected and unselected text are rendered can be customized.

Parameters:
lineIndex - the line to draw >= 0
g - the Graphics context
x - the starting X position >= 0
y - the starting Y position >= 0
See Also:
drawUnselectedText(java.awt.Graphics, int, int, int, int), drawSelectedText(java.awt.Graphics, int, int, int, int)

drawUnselectedText

protected int drawUnselectedText(Graphics g,
                                 int x,
                                 int y,
                                 int p0,
                                 int p1)
                          throws BadLocationException
Renders the given range in the model as normal unselected text. Uses the foreground or disabled color to render the text.

Parameters:
g - the graphics context
x - the starting X coordinate >= 0
y - the starting Y coordinate >= 0
p0 - the beginning position in the model >= 0
p1 - the ending position in the model >= 0
Returns:
the X location of the end of the range >= 0
Throws:
BadLocationException - if the range is invalid

drawSelectedText

protected int drawSelectedText(Graphics g,
                               int x,
                               int y,
                               int p0,
                               int p1)
                        throws BadLocationException
Renders the given range in the model as selected text. This is implemented to render the text in the color specified in the hosting component. It assumes the highlighter will render the selected background.

Parameters:
g - the graphics context
x - the starting X coordinate >= 0
y - the starting Y coordinate >= 0
p0 - the beginning position in the model >= 0
p1 - the ending position in the model >= 0
Returns:
the location of the end of the range
Throws:
BadLocationException - if the range is invalid

getLineBuffer

protected final Segment getLineBuffer()
Gives access to a buffer that can be used to fetch text from the associated document.

Returns:
the buffer

updateMetrics

protected void updateMetrics()
Checks to see if the font metrics and longest line are up-to-date.

Since:
1.4

getPreferredSpan

public float getPreferredSpan(int axis)
Determines the preferred span for this view along an axis.

Specified by:
getPreferredSpan in class View
Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
Returns:
the span the view would like to be rendered into >= 0. Typically the view is told to render into the span that is returned, although there is no guarantee. The parent may choose to resize or break the view.
Throws:
IllegalArgumentException - for an invalid axis
See Also:
View.getPreferredSpan(int)

paint

public void paint(Graphics g,
                  Shape a)
Renders using the given rendering surface and area on that surface. The view may need to do layout and create child views to enable itself to render into the given allocation.

Specified by:
paint in class View
Parameters:
g - the rendering surface to use
a - the allocated region to render into
See Also:
View.paint(java.awt.Graphics, java.awt.Shape)

modelToView

public Shape modelToView(int pos,
                         Shape a,
                         Position.Bias b)
                  throws BadLocationException
Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.

Specified by:
modelToView in class View
Parameters:
pos - the position to convert >= 0
a - the allocated region to render into
b - the bias toward the previous character or the next character represented by the offset, in case the position is a boundary of two views; b will have one of these values:
  • Position.Bias.Forward
  • Position.Bias.Backward
Returns:
the bounding box of the given position
Throws:
BadLocationException - if the given position does not represent a valid location in the associated document
See Also:
View.modelToView(int, java.awt.Shape, javax.swing.text.Position.Bias)

viewToModel

public int viewToModel(float fx,
                       float fy,
                       Shape a,
                       Position.Bias[] bias)
Provides a mapping from the view coordinate space to the logical coordinate space of the model.

Specified by:
viewToModel in class View
Parameters:
fx - the X coordinate >= 0
fy - the Y coordinate >= 0
a - the allocated region to render into
Returns:
the location within the model that best represents the given point in the view >= 0
See Also:
View.viewToModel(float, float, java.awt.Shape, javax.swing.text.Position.Bias[])

insertUpdate

public void insertUpdate(DocumentEvent changes,
                         Shape a,
                         ViewFactory f)
Gives notification that something was inserted into the document in a location that this view is responsible for.

Overrides:
insertUpdate in class View
Parameters:
changes - the change information from the associated document
a - the current allocation of the view
f - the factory to use to rebuild if the view has children
See Also:
View.insertUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory)

removeUpdate

public void removeUpdate(DocumentEvent changes,
                         Shape a,
                         ViewFactory f)
Gives notification that something was removed from the document in a location that this view is responsible for.

Overrides:
removeUpdate in class View
Parameters:
changes - the change information from the associated document
a - the current allocation of the view
f - the factory to use to rebuild if the view has children
See Also:
View.removeUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory)

changedUpdate

public void changedUpdate(DocumentEvent changes,
                          Shape a,
                          ViewFactory f)
Gives notification from the document that attributes were changed in a location that this view is responsible for.

Overrides:
changedUpdate in class View
Parameters:
changes - the change information from the associated document
a - the current allocation of the view
f - the factory to use to rebuild if the view has children
See Also:
View.changedUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory)

setSize

public void setSize(float width,
                    float height)
Sets the size of the view. This should cause layout of the view along the given axis, if it has any layout duties.

Overrides:
setSize in class View
Parameters:
width - the width >= 0
height - the height >= 0

nextTabStop

public float nextTabStop(float x,
                         int tabOffset)
Returns the next tab stop position after a given reference position. This implementation does not support things like centering so it ignores the tabOffset argument.

Specified by:
nextTabStop in interface TabExpander
Parameters:
x - the current position >= 0
tabOffset - the position within the text stream that the tab occurred at >= 0.
Returns:
the tab stop, measured in points >= 0

updateDamage

protected void updateDamage(DocumentEvent changes,
                            Shape a,
                            ViewFactory f)

damageLineRange

protected void damageLineRange(int line0,
                               int line1,
                               Shape a,
                               Component host)
Repaint the given line range.

Parameters:
host - the component hosting the view (used to call repaint)
a - the region allocated for the view to render into
line0 - the starting line number to repaint. This must be a valid line number in the model.
line1 - the ending line number to repaint. This must be a valid line number in the model.
Since:
1.4

lineToRect

protected Rectangle lineToRect(Shape a,
                               int line)
Determine the rectangle that represents the given line.

Parameters:
a - the region allocated for the view to render into
line - the line number to find the region of. This must be a valid line number in the model.
Since:
1.4
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Position (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Interface Position

public interface Position

Represents a location within a document. It is intended to abstract away implementation details of the document and enable specification of positions within the document that are capable of tracking of change as the document is edited (i.e. offsets are fragile).

Nested Class Summary
static class Position.Bias
A typesafe enumeration to indicate bias to a position in the model.
Method Summary
 int getOffset()
Fetches the current offset within the document.

Method Detail

getOffset

public int getOffset()
Fetches the current offset within the document.

Returns:
the offset >= 0
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Position.Bias (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class Position.Bias

java.lang.Object
    extended by javax.swing.text.Position.Bias
Enclosing class:
Position
public static final class Position.Bias
extends Object

A typesafe enumeration to indicate bias to a position in the model. A position indicates a location between two characters. The bias can be used to indicate an interest toward one of the two sides of the position in boundary conditions where a simple offset is ambiguous.

Field Summary
static Position.Bias | Backward Indicates a bias toward the previous character in the model.
static Position.Bias | Forward Indicates to bias toward the next character in the model.
Method Summary
 String toString()
string representation
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

Forward

public static final Position.Bias Forward
Indicates to bias toward the next character in the model.

Backward

public static final Position.Bias Backward
Indicates a bias toward the previous character in the model.

Method Detail

toString

public String toString()
string representation

Overrides:
toString in class Object
Returns:
a string representation of the object.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Segment (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class Segment

java.lang.Object
    extended by javax.swing.text.Segment
All Implemented Interfaces:
CharacterIterator, Cloneable
public class Segment
extends Object
implements Cloneable, CharacterIterator

A segment of a character array representing a fragment of text. It should be treated as immutable even though the array is directly accessible. This gives fast access to fragments of text without the overhead of copying around characters. This is effectively an unprotected String.

The Segment implements the java.text.CharacterIterator interface to support use with the i18n support without copying text into a string.

Field Summary
char[] | array This is the array containing the text of interest.
int | count This is the number of array elements that make up the text of interest.
int | offset This is the offset into the array that the desired text begins.
Fields inherited from interface java.text.CharacterIterator
DONE
Constructor Summary
Segment()
Creates a new segment.
Segment(char[] array, int offset, int count)
Creates a new segment referring to an existing array.
Method Summary
 Object clone()
Creates a shallow copy.
 char current()
Gets the character at the current position (as returned by getIndex()).
 char first()
Sets the position to getBeginIndex() and returns the character at that position.
 int getBeginIndex()
Returns the start index of the text.
 int getEndIndex()
Returns the end index of the text.
 int getIndex()
Returns the current index.
 boolean isPartialReturn()
Flag to indicate that partial returns are valid.
 char last()
Sets the position to getEndIndex()-1 (getEndIndex() if the text is empty) and returns the character at that position.
 char next()
Increments the iterator's index by one and returns the character at the new index.
 char previous()
Decrements the iterator's index by one and returns the character at the new index.
 char setIndex(int position)
Sets the position to the specified position in the text and returns that character.
 void setPartialReturn(boolean p)
Flag to indicate that partial returns are valid.
 String toString()
Converts a segment into a String.
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

array

public char[] array
This is the array containing the text of interest. This array should never be modified; it is available only for efficiency.

offset

public int offset
This is the offset into the array that the desired text begins.

count

public int count
This is the number of array elements that make up the text of interest.

Constructor Detail

Segment

public Segment()
Creates a new segment.

Segment

public Segment(char[] array,
               int offset,
               int count)
Creates a new segment referring to an existing array.

Parameters:
array - the array to refer to
offset - the offset into the array
count - the number of characters
Method Detail

setPartialReturn

public void setPartialReturn(boolean p)
Flag to indicate that partial returns are valid. If the flag is true, an implementation of the interface method Document.getText(position,length,Segment) should return as much text as possible without making a copy. The default state of the flag is false which will cause Document.getText(position,length,Segment) to provide the same return behavior it always had, which may or may not make a copy of the text depending upon the request.

Parameters:
p - whether or not partial returns are valid.
Since:
1.4

isPartialReturn

public boolean isPartialReturn()
Flag to indicate that partial returns are valid.

Returns:
whether or not partial returns are valid.
Since:
1.4

toString

public String toString()
Converts a segment into a String.

Overrides:
toString in class Object
Returns:
the string

first

public char first()
Sets the position to getBeginIndex() and returns the character at that position.

Specified by:
first in interface CharacterIterator
Returns:
the first character in the text, or DONE if the text is empty
See Also:
getBeginIndex()

last

public char last()
Sets the position to getEndIndex()-1 (getEndIndex() if the text is empty) and returns the character at that position.

Specified by:
last in interface CharacterIterator
Returns:
the last character in the text, or DONE if the text is empty
See Also:
getEndIndex()

current

public char current()
Gets the character at the current position (as returned by getIndex()).

Specified by:
current in interface CharacterIterator
Returns:
the character at the current position or DONE if the current position is off the end of the text.
See Also:
getIndex()

next

public char next()
Increments the iterator's index by one and returns the character at the new index. If the resulting index is greater or equal to getEndIndex(), the current index is reset to getEndIndex() and a value of DONE is returned.

Specified by:
next in interface CharacterIterator
Returns:
the character at the new position or DONE if the new position is off the end of the text range.

previous

public char previous()
Decrements the iterator's index by one and returns the character at the new index. If the current index is getBeginIndex(), the index remains at getBeginIndex() and a value of DONE is returned.

Specified by:
previous in interface CharacterIterator
Returns:
the character at the new position or DONE if the current position is equal to getBeginIndex().

setIndex

public char setIndex(int position)
Sets the position to the specified position in the text and returns that character.

Specified by:
setIndex in interface CharacterIterator
Parameters:
position - the position within the text. Valid values range from getBeginIndex() to getEndIndex(). An IllegalArgumentException is thrown if an invalid value is supplied.
Returns:
the character at the specified position or DONE if the specified position is equal to getEndIndex()

getBeginIndex

public int getBeginIndex()
Returns the start index of the text.

Specified by:
getBeginIndex in interface CharacterIterator
Returns:
the index at which the text begins.

getEndIndex

public int getEndIndex()
Returns the end index of the text. This index is the index of the first character following the end of the text.

Specified by:
getEndIndex in interface CharacterIterator
Returns:
the index after the last character in the text

getIndex

public int getIndex()
Returns the current index.

Specified by:
getIndex in interface CharacterIterator
Returns:
the current index.

clone

public Object clone()
Creates a shallow copy.

Specified by:
clone in interface CharacterIterator
Overrides:
clone in class Object
Returns:
the copy
See Also:
Cloneable
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


SimpleAttributeSet (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class SimpleAttributeSet

java.lang.Object
    extended by javax.swing.text.SimpleAttributeSet
All Implemented Interfaces:
AttributeSet, Cloneable, MutableAttributeSet, Serializable
public class SimpleAttributeSet
extends Object
implements MutableAttributeSet, Serializable, Cloneable

A straightforward implementation of MutableAttributeSet using a hash table.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Nested Class Summary
Nested classes inherited from class javax.swing.text.AttributeSet
AttributeSet.CharacterAttribute, AttributeSet.ColorAttribute, AttributeSet.FontAttribute, AttributeSet.ParagraphAttribute
Field Summary
static AttributeSet EMPTY
An empty attribute set.
Fields inherited from interface javax.swing.text.AttributeSet
NameAttribute, ResolveAttribute
Constructor Summary
SimpleAttributeSet()
Creates a new attribute set.
SimpleAttributeSet(AttributeSet source)
Creates a new attribute set based on a supplied set of attributes.
Method Summary
void | addAttribute(Object name, Object value) Adds an attribute to the list.
void | addAttributes(AttributeSet attributes) Adds a set of attributes to the list.
Object | clone() Clones a set of attributes.
boolean | containsAttribute(Object name, Object value) Checks whether the attribute list contains a specified attribute name/value pair.
boolean | containsAttributes(AttributeSet attributes) Checks whether the attribute list contains all the specified name/value pairs.
AttributeSet | copyAttributes() Makes a copy of the attributes.
boolean | equals(Object obj) Compares this object to the specified object.
Object | getAttribute(Object name) Gets the value of an attribute.
int | getAttributeCount() Gets a count of the number of attributes.
Enumeration | getAttributeNames() Gets the names of the attributes in the set.
AttributeSet | getResolveParent() Gets the resolving parent.
int | hashCode() Returns a hashcode for this set of attributes.
boolean | isDefined(Object attrName) Tells whether a given attribute is defined.
boolean | isEmpty() Checks whether the set of attributes is empty.
boolean | isEqual(AttributeSet attr) Compares two attribute sets.
void | removeAttribute(Object name) Removes an attribute from the list.
void | removeAttributes(AttributeSet attributes) Removes a set of attributes from the list.
void | removeAttributes(Enumeration names) Removes a set of attributes from the list.
void | setResolveParent(AttributeSet parent) Sets the resolving parent.
String | toString() Converts the attribute set to a String.
Methods inherited from class java.lang.Object
finalize, getClass, notify, notifyAll, wait, wait, wait

Field Detail

EMPTY

public static final AttributeSet EMPTY
An empty attribute set.

Constructor Detail

SimpleAttributeSet

public SimpleAttributeSet()
Creates a new attribute set.

SimpleAttributeSet

public SimpleAttributeSet(AttributeSet source)
Creates a new attribute set based on a supplied set of attributes.

Parameters:
source - the set of attributes
Method Detail

isEmpty

public boolean isEmpty()
Checks whether the set of attributes is empty.

Returns:
true if the set is empty else false

getAttributeCount

public int getAttributeCount()
Gets a count of the number of attributes.

Specified by:
getAttributeCount in interface AttributeSet
Returns:
the count

isDefined

public boolean isDefined(Object attrName)
Tells whether a given attribute is defined.

Specified by:
isDefined in interface AttributeSet
Parameters:
attrName - the attribute name
Returns:
true if the attribute is defined

isEqual

public boolean isEqual(AttributeSet attr)
Compares two attribute sets.

Specified by:
isEqual in interface AttributeSet
Parameters:
attr - the second attribute set
Returns:
true if the sets are equal, false otherwise

copyAttributes

public AttributeSet copyAttributes()
Makes a copy of the attributes.

Specified by:
copyAttributes in interface AttributeSet
Returns:
the copy

getAttributeNames

public Enumeration getAttributeNames()
Gets the names of the attributes in the set.

Specified by:
getAttributeNames in interface AttributeSet
Returns:
the names as an Enumeration

getAttribute

public Object getAttribute(Object name)
Gets the value of an attribute.

Specified by:
getAttribute in interface AttributeSet
Parameters:
name - the attribute name
Returns:
the value

containsAttribute

public boolean containsAttribute(Object name,
                                 Object value)
Checks whether the attribute list contains a specified attribute name/value pair.

Specified by:
containsAttribute in interface AttributeSet
Parameters:
name - the name
value - the value
Returns:
true if the name/value pair is in the list

containsAttributes

public boolean containsAttributes(AttributeSet attributes)
Checks whether the attribute list contains all the specified name/value pairs.

Specified by:
containsAttributes in interface AttributeSet
Parameters:
attributes - the attribute list
Returns:
true if the list contains all the name/value pairs

addAttribute

public void addAttribute(Object name,
                         Object value)
Adds an attribute to the list.

Specified by:
addAttribute in interface MutableAttributeSet
Parameters:
name - the attribute name
value - the attribute value

addAttributes

public void addAttributes(AttributeSet attributes)
Adds a set of attributes to the list.

Specified by:
addAttributes in interface MutableAttributeSet
Parameters:
attributes - the set of attributes to add

removeAttribute

public void removeAttribute(Object name)
Removes an attribute from the list.

Specified by:
removeAttribute in interface MutableAttributeSet
Parameters:
name - the attribute name

removeAttributes

public void removeAttributes(Enumeration names)
Removes a set of attributes from the list.

Specified by:
removeAttributes in interface MutableAttributeSet
Parameters:
names - the set of names to remove

removeAttributes

public void removeAttributes(AttributeSet attributes)
Removes a set of attributes from the list.

Specified by:
removeAttributes in interface MutableAttributeSet
Parameters:
attributes - the set of attributes to remove

getResolveParent

public AttributeSet getResolveParent()
Gets the resolving parent. This is the set of attributes to resolve through if an attribute isn't defined locally. This is null if there are no other sets of attributes to resolve through.

Specified by:
getResolveParent in interface AttributeSet
Returns:
the parent

setResolveParent

public void setResolveParent(AttributeSet parent)
Sets the resolving parent.

Specified by:
setResolveParent in interface MutableAttributeSet
Parameters:
parent - the parent

clone

public Object clone()
Clones a set of attributes.

Overrides:
clone in class Object
Returns:
the new set of attributes
See Also:
Cloneable

hashCode

public int hashCode()
Returns a hashcode for this set of attributes.

Overrides:
hashCode in class Object
Returns:
a hashcode value for this set of attributes.
See Also:
Object.equals(java.lang.Object), Hashtable

equals

public boolean equals(Object obj)
Compares this object to the specified object. The result is true if the object is an equivalent set of attributes.

Overrides:
equals in class Object
Parameters:
obj - the object to compare this attribute set with
Returns:
true if the objects are equal; false otherwise
See Also:
Object.hashCode(), Hashtable

toString

public String toString()
Converts the attribute set to a String.

Overrides:
toString in class Object
Returns:
the string
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


StringContent (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class StringContent

java.lang.Object
    extended by javax.swing.text.StringContent
All Implemented Interfaces:
AbstractDocument.Content, Serializable
public final class StringContent
extends Object
implements AbstractDocument.Content, Serializable

An implementation of the AbstractDocument.Content interface that is a brute force implementation that is useful for relatively small documents and/or debugging. It manages the character content as a simple character array. It is also quite inefficient.

It is generally recommended that the gap buffer or piece table implementations be used instead. This buffer does not scale up to large sizes.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Constructor Summary
StringContent()
Creates a new StringContent object.
StringContent(int initialLength)
Creates a new StringContent object, with the initial size specified.
Method Summary
Position | createPosition(int offset) Creates a position within the content that will track change as the content is mutated.
void | getChars(int where, int len, Segment chars) Retrieves a portion of the content.
protected Vector | getPositionsInRange(Vector v, int offset, int length) Returns a Vector containing instances of UndoPosRef for the Positions in the range offset to offset + length.
String | getString(int where, int len) Retrieves a portion of the content.
UndoableEdit | insertString(int where, String str) Inserts a string into the content.
int | length() Returns the length of the content.
UndoableEdit | remove(int where, int nitems) Removes part of the content.
protected void | updateUndoPositions(Vector positions) Resets the location for all the UndoPosRef instances in positions.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

StringContent

public StringContent()
Creates a new StringContent object. Initial size defaults to 10.

StringContent

public StringContent(int initialLength)
Creates a new StringContent object, with the initial size specified. If the length is < 1, a size of 1 is used.

Parameters:
initialLength - the initial size
Method Detail

length

public int length()
Returns the length of the content.

Specified by:
length in interface AbstractDocument.Content
Returns:
the length >= 1
See Also:
AbstractDocument.Content.length()

insertString

public UndoableEdit insertString(int where,
                                 String str)
                          throws BadLocationException
Inserts a string into the content.

Specified by:
insertString in interface AbstractDocument.Content
Parameters:
where - the starting position >= 0 && < length()
str - the non-null string to insert
Returns:
an UndoableEdit object for undoing
Throws:
BadLocationException - if the specified position is invalid
See Also:
AbstractDocument.Content.insertString(int, java.lang.String)

remove

public UndoableEdit remove(int where,
                           int nitems)
                    throws BadLocationException
Removes part of the content. where + nitems must be < length().

Specified by:
remove in interface AbstractDocument.Content
Parameters:
where - the starting position >= 0
nitems - the number of characters to remove >= 0
Returns:
an UndoableEdit object for undoing
Throws:
BadLocationException - if the specified position is invalid
See Also:
AbstractDocument.Content.remove(int, int)

getString

public String getString(int where,
                        int len)
                 throws BadLocationException
Retrieves a portion of the content. where + len must be <= length().

Specified by:
getString in interface AbstractDocument.Content
Parameters:
where - the starting position >= 0
len - the length to retrieve >= 0
Returns:
a string representing the content; may be empty
Throws:
BadLocationException - if the specified position is invalid
See Also:
AbstractDocument.Content.getString(int, int)

getChars

public void getChars(int where,
                     int len,
                     Segment chars)
              throws BadLocationException
Retrieves a portion of the content. where + len must be <= length()

Specified by:
getChars in interface AbstractDocument.Content
Parameters:
where - the starting position >= 0
len - the number of characters to retrieve >= 0
chars - the Segment object to return the characters in
Throws:
BadLocationException - if the specified position is invalid
See Also:
AbstractDocument.Content.getChars(int, int, javax.swing.text.Segment)

createPosition

public Position createPosition(int offset)
                        throws BadLocationException
Creates a position within the content that will track change as the content is mutated.

Specified by:
createPosition in interface AbstractDocument.Content
Parameters:
offset - the offset to create a position for >= 0
Returns:
the position
Throws:
BadLocationException - if the specified position is invalid

getPositionsInRange

protected Vector getPositionsInRange(Vector v,
                                     int offset,
                                     int length)
Returns a Vector containing instances of UndoPosRef for the Positions in the range offset to offset + length. If v is not null the matching Positions are placed in there. The vector with the resulting Positions are returned.

This is meant for internal usage, and is generally not of interest to subclasses.

Parameters:
v - the Vector to use, with a new one created on null
offset - the starting offset >= 0
length - the length >= 0
Returns:
the set of instances

updateUndoPositions

protected void updateUndoPositions(Vector positions)
Resets the location for all the UndoPosRef instances in positions.

This is meant for internal usage, and is generally not of interest to subclasses.

Parameters:
positions - the positions of the instances
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Style (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Interface Style

All Superinterfaces:
AttributeSet, MutableAttributeSet
All Known Implementing Classes:
StyleContext.NamedStyle
public interface Style
extends MutableAttributeSet

A collection of attributes to associate with an element in a document. Since these are typically used to associate character and paragraph styles with the element, operations for this are provided. Other customized attributes that get associated with the element will effectively be name-value pairs that live in a hierarchy and if a name (key) is not found locally, the request is forwarded to the parent. Commonly used attributes are separated out to facilitate alternative implementations that are more efficient.

Nested Class Summary
Nested classes inherited from class javax.swing.text.AttributeSet
AttributeSet.CharacterAttribute, AttributeSet.ColorAttribute, AttributeSet.FontAttribute, AttributeSet.ParagraphAttribute
Field Summary
Fields inherited from interface javax.swing.text.AttributeSet
NameAttribute, ResolveAttribute
Method Summary
void | addChangeListener(ChangeListener l) Adds a listener to track whenever an attribute has been changed.
String | getName() Fetches the name of the style.
void | removeChangeListener(ChangeListener l) Removes a listener that was tracking attribute changes.
Methods inherited from interface javax.swing.text.MutableAttributeSet
addAttribute, addAttributes, removeAttribute, removeAttributes, removeAttributes, setResolveParent
Methods inherited from interface javax.swing.text.AttributeSet
containsAttribute, containsAttributes, copyAttributes, getAttribute, getAttributeCount, getAttributeNames, getResolveParent, isDefined, isEqual

Method Detail

getName

public String getName()
Fetches the name of the style. A style is not required to be named, so null is returned if there is no name associated with the style.

Returns:
the name

addChangeListener

public void addChangeListener(ChangeListener l)
Adds a listener to track whenever an attribute has been changed.

Parameters:
l - the change listener

removeChangeListener

public void removeChangeListener(ChangeListener l)
Removes a listener that was tracking attribute changes.

Parameters:
l - the change listener
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


StyleConstants (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class StyleConstants

java.lang.Object
    extended by javax.swing.text.StyleConstants
Direct Known Subclasses:
StyleConstants.CharacterConstants, StyleConstants.ColorConstants, StyleConstants.FontConstants, StyleConstants.ParagraphConstants
public class StyleConstants
extends Object

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.

The paragraph attributes form the definition of a paragraph to be rendered. All sizes are specified in points (such as found in postscript), a device independent measure.

Diagram shows SpaceAbove, FirstLineIndent, LeftIndent, RightIndent, and SpaceBelow a paragraph.

Nested Class Summary
static class | StyleConstants.CharacterConstants This is a typesafe enumeration of the well-known attributes that contribute to a character style.
static class | StyleConstants.ColorConstants This is a typesafe enumeration of the well-known attributes that contribute to a color.
static class | StyleConstants.FontConstants This is a typesafe enumeration of the well-known attributes that contribute to a font.
static class | StyleConstants.ParagraphConstants This is a typesafe enumeration of the well-known attributes that contribute to a paragraph style.
Field Summary
static int | ALIGN_CENTER A possible value for paragraph alignment.
static int | ALIGN_JUSTIFIED A possible value for paragraph alignment.
static int | ALIGN_LEFT A possible value for paragraph alignment.
static int | ALIGN_RIGHT A possible value for paragraph alignment.
static Object | Alignment Alignment for the paragraph.
static Object | Background Name of the background color attribute.
static Object | BidiLevel Bidirectional level of a character as assigned by the Unicode bidi algorithm.
static Object | Bold Name of the bold attribute.
static Object | ComponentAttribute Name of the component attribute.
static String | ComponentElementName Name of elements used to represent components.
static Object | ComposedTextAttribute Name of the input method composed text attribute.
static Object | FirstLineIndent The amount of space to indent the first line of the paragraph.
static Object | FontFamily Name of the font family.
static Object | FontSize Name of the font size.
static Object | Foreground Name of the foreground color attribute.
static Object | IconAttribute Name of the icon attribute.
static String | IconElementName Name of elements used to represent icons.
static Object | Italic Name of the italic attribute.
static Object | LeftIndent The amount to indent the left side of the paragraph.
static Object | LineSpacing The amount of space between lines of the paragraph.
static Object | ModelAttribute Attribute used to identify the model for embedded objects that have a model view separation.
static Object | NameAttribute Attribute name used to name the collection of attributes.
static Object | Orientation Orientation for a paragraph.
static Object | ResolveAttribute Attribute name used to identifiy the resolving parent set of attributes, if one is defined.
static Object | RightIndent The amount to indent the right side of the paragraph.
static Object | SpaceAbove The amount of space above the paragraph.
static Object | SpaceBelow The amount of space below the paragraph.
static Object | StrikeThrough Name of the Strikethrough attribute.
static Object | Subscript Name of the Subscript attribute.
static Object | Superscript Name of the Superscript attribute.
static Object | TabSet TabSet for the paragraph, type is a TabSet containing TabStops.
static Object | Underline Name of the underline attribute.
Method Summary
static int | getAlignment(AttributeSet a) Gets the alignment setting.
static Color | getBackground(AttributeSet a) Gets the background color setting from the attribute list.
static int | getBidiLevel(AttributeSet a) Gets the BidiLevel setting.
static Component | getComponent(AttributeSet a) Gets the component setting from the attribute list.
static float | getFirstLineIndent(AttributeSet a) Gets the first line indent setting.
static String | getFontFamily(AttributeSet a) Gets the font family setting from the attribute list.
static int | getFontSize(AttributeSet a) Gets the font size setting from the attribute list.
static Color | getForeground(AttributeSet a) Gets the foreground color setting from the attribute list.
static Icon | getIcon(AttributeSet a) Gets the icon setting from the attribute list.
static float | getLeftIndent(AttributeSet a) Gets the left indent setting.
static float | getLineSpacing(AttributeSet a) Gets the line spacing setting.
static float | getRightIndent(AttributeSet a) Gets the right indent setting.
static float | getSpaceAbove(AttributeSet a) Gets the space above setting.
static float | getSpaceBelow(AttributeSet a) Gets the space below setting.
static TabSet | getTabSet(AttributeSet a) Gets the TabSet.
static boolean | isBold(AttributeSet a) Checks whether the bold attribute is set.
static boolean | isItalic(AttributeSet a) Checks whether the italic attribute is set.
static boolean | isStrikeThrough(AttributeSet a) Checks whether the strikethrough attribute is set.
static boolean | isSubscript(AttributeSet a) Checks whether the subscript attribute is set.
static boolean | isSuperscript(AttributeSet a) Checks whether the superscript attribute is set.
static boolean | isUnderline(AttributeSet a) Checks whether the underline attribute is set.
static void | setAlignment(MutableAttributeSet a, int align) Sets alignment.
static void | setBackground(MutableAttributeSet a, Color fg) Sets the background color.
static void | setBidiLevel(MutableAttributeSet a, int o) Sets the BidiLevel.
static void | setBold(MutableAttributeSet a, boolean b) Sets the bold attribute.
static void | setComponent(MutableAttributeSet a, Component c) Sets the component attribute.
static void | setFirstLineIndent(MutableAttributeSet a, float i) Sets the first line indent.
static void | setFontFamily(MutableAttributeSet a, String fam) Sets the font attribute.
static void | setFontSize(MutableAttributeSet a, int s) Sets the font size attribute.
static void | setForeground(MutableAttributeSet a, Color fg) Sets the foreground color.
static void | setIcon(MutableAttributeSet a, Icon c) Sets the icon attribute.
static void | setItalic(MutableAttributeSet a, boolean b) Sets the italic attribute.
static void | setLeftIndent(MutableAttributeSet a, float i) Sets left indent.
static void | setLineSpacing(MutableAttributeSet a, float i) Sets line spacing.
static void | setRightIndent(MutableAttributeSet a, float i) Sets right indent.
static void | setSpaceAbove(MutableAttributeSet a, float i) Sets space above.
static void | setSpaceBelow(MutableAttributeSet a, float i) Sets space below.
static void | setStrikeThrough(MutableAttributeSet a, boolean b) Sets the strikethrough attribute.
static void | setSubscript(MutableAttributeSet a, boolean b) Sets the subscript attribute.
static void | setSuperscript(MutableAttributeSet a, boolean b) Sets the superscript attribute.
static void | setTabSet(MutableAttributeSet a, TabSet tabs) Sets the TabSet.
static void | setUnderline(MutableAttributeSet a, boolean b) Sets the underline attribute.
String | toString() Returns the string representation.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

ComponentElementName

public static final String ComponentElementName
Name of elements used to represent components.

See Also:
Constant Field Values

IconElementName

public static final String IconElementName
Name of elements used to represent icons.

See Also:
Constant Field Values

NameAttribute

public static final Object NameAttribute
Attribute name used to name the collection of attributes.

ResolveAttribute

public static final Object ResolveAttribute
Attribute name used to identifiy the resolving parent set of attributes, if one is defined.

ModelAttribute

public static final Object ModelAttribute
Attribute used to identify the model for embedded objects that have a model view separation.

BidiLevel

public static final Object BidiLevel
Bidirectional level of a character as assigned by the Unicode bidi algorithm.

FontFamily

public static final Object FontFamily
Name of the font family.

FontSize

public static final Object FontSize
Name of the font size.

Bold

public static final Object Bold
Name of the bold attribute.

Italic

public static final Object Italic
Name of the italic attribute.

Underline

public static final Object Underline
Name of the underline attribute.

StrikeThrough

public static final Object StrikeThrough
Name of the Strikethrough attribute.

Superscript

public static final Object Superscript
Name of the Superscript attribute.

Subscript

public static final Object Subscript
Name of the Subscript attribute.

Foreground

public static final Object Foreground
Name of the foreground color attribute.

Background

public static final Object Background
Name of the background color attribute.

ComponentAttribute

public static final Object ComponentAttribute
Name of the component attribute.

IconAttribute

public static final Object IconAttribute
Name of the icon attribute.

ComposedTextAttribute

public static final Object ComposedTextAttribute
Name of the input method composed text attribute. The value of this attribute is an instance of AttributedString which represents the composed text.

FirstLineIndent

public static final Object FirstLineIndent
The amount of space to indent the first line of the paragraph. This value may be negative to offset in the reverse direction. The type is Float and specifies the size of the space in points.

LeftIndent

public static final Object LeftIndent
The amount to indent the left side of the paragraph. Type is float and specifies the size in points.

RightIndent

public static final Object RightIndent
The amount to indent the right side of the paragraph. Type is float and specifies the size in points.

LineSpacing

public static final Object LineSpacing
The amount of space between lines of the paragraph. Type is float and specifies the size as a factor of the line height

SpaceAbove

public static final Object SpaceAbove
The amount of space above the paragraph. Type is float and specifies the size in points.

SpaceBelow

public static final Object SpaceBelow
The amount of space below the paragraph. Type is float and specifies the size in points.

Alignment

public static final Object Alignment
Alignment for the paragraph. The type is Integer. Valid values are:
  • ALIGN_LEFT
  • ALIGN_RIGHT
  • ALIGN_CENTER
  • ALIGN_JUSTIFED

TabSet

public static final Object TabSet
TabSet for the paragraph, type is a TabSet containing TabStops.

Orientation

public static final Object Orientation
Orientation for a paragraph.

ALIGN_LEFT

public static final int ALIGN_LEFT
A possible value for paragraph alignment. This specifies that the text is aligned to the left indent and extra whitespace should be placed on the right.

See Also:
Constant Field Values

ALIGN_CENTER

public static final int ALIGN_CENTER
A possible value for paragraph alignment. This specifies that the text is aligned to the center and extra whitespace should be placed equally on the left and right.

See Also:
Constant Field Values

ALIGN_RIGHT

public static final int ALIGN_RIGHT
A possible value for paragraph alignment. This specifies that the text is aligned to the right indent and extra whitespace should be placed on the left.

See Also:
Constant Field Values

ALIGN_JUSTIFIED

public static final int ALIGN_JUSTIFIED
A possible value for paragraph alignment. This specifies that extra whitespace should be spread out through the rows of the paragraph with the text lined up with the left and right indent except on the last line which should be aligned to the left.

See Also:
Constant Field Values
Method Detail

toString

public String toString()
Returns the string representation.

Overrides:
toString in class Object
Returns:
the string

getBidiLevel

public static int getBidiLevel(AttributeSet a)
Gets the BidiLevel setting.

Parameters:
a - the attribute set
Returns:
the value

setBidiLevel

public static void setBidiLevel(MutableAttributeSet a,
                                int o)
Sets the BidiLevel.

Parameters:
a - the attribute set
o - the bidi level value

getComponent

public static Component getComponent(AttributeSet a)
Gets the component setting from the attribute list.

Parameters:
a - the attribute set
Returns:
the component, null if none

setComponent

public static void setComponent(MutableAttributeSet a,
                                Component c)
Sets the component attribute.

Parameters:
a - the attribute set
c - the component

getIcon

public static Icon getIcon(AttributeSet a)
Gets the icon setting from the attribute list.

Parameters:
a - the attribute set
Returns:
the icon, null if none

setIcon

public static void setIcon(MutableAttributeSet a,
                           Icon c)
Sets the icon attribute.

Parameters:
a - the attribute set
c - the icon

getFontFamily

public static String getFontFamily(AttributeSet a)
Gets the font family setting from the attribute list.

Parameters:
a - the attribute set
Returns:
the font family, "Monospaced" as the default

setFontFamily

public static void setFontFamily(MutableAttributeSet a,
                                 String fam)
Sets the font attribute.

Parameters:
a - the attribute set
fam - the font

getFontSize

public static int getFontSize(AttributeSet a)
Gets the font size setting from the attribute list.

Parameters:
a - the attribute set
Returns:
the font size, 12 as the default

setFontSize

public static void setFontSize(MutableAttributeSet a,
                               int s)
Sets the font size attribute.

Parameters:
a - the attribute set
s - the font size

isBold

public static boolean isBold(AttributeSet a)
Checks whether the bold attribute is set.

Parameters:
a - the attribute set
Returns:
true if set else false

setBold

public static void setBold(MutableAttributeSet a,
                           boolean b)
Sets the bold attribute.

Parameters:
a - the attribute set
b - specifies true/false for setting the attribute

isItalic

public static boolean isItalic(AttributeSet a)
Checks whether the italic attribute is set.

Parameters:
a - the attribute set
Returns:
true if set else false

setItalic

public static void setItalic(MutableAttributeSet a,
                             boolean b)
Sets the italic attribute.

Parameters:
a - the attribute set
b - specifies true/false for setting the attribute

isUnderline

public static boolean isUnderline(AttributeSet a)
Checks whether the underline attribute is set.

Parameters:
a - the attribute set
Returns:
true if set else false

isStrikeThrough

public static boolean isStrikeThrough(AttributeSet a)
Checks whether the strikethrough attribute is set.

Parameters:
a - the attribute set
Returns:
true if set else false

isSuperscript

public static boolean isSuperscript(AttributeSet a)
Checks whether the superscript attribute is set.

Parameters:
a - the attribute set
Returns:
true if set else false

isSubscript

public static boolean isSubscript(AttributeSet a)
Checks whether the subscript attribute is set.

Parameters:
a - the attribute set
Returns:
true if set else false

setUnderline

public static void setUnderline(MutableAttributeSet a,
                                boolean b)
Sets the underline attribute.

Parameters:
a - the attribute set
b - specifies true/false for setting the attribute

setStrikeThrough

public static void setStrikeThrough(MutableAttributeSet a,
                                    boolean b)
Sets the strikethrough attribute.

Parameters:
a - the attribute set
b - specifies true/false for setting the attribute

setSuperscript

public static void setSuperscript(MutableAttributeSet a,
                                  boolean b)
Sets the superscript attribute.

Parameters:
a - the attribute set
b - specifies true/false for setting the attribute

setSubscript

public static void setSubscript(MutableAttributeSet a,
                                boolean b)
Sets the subscript attribute.

Parameters:
a - the attribute set
b - specifies true/false for setting the attribute

getForeground

public static Color getForeground(AttributeSet a)
Gets the foreground color setting from the attribute list.

Parameters:
a - the attribute set
Returns:
the color, Color.black as the default

setForeground

public static void setForeground(MutableAttributeSet a,
                                 Color fg)
Sets the foreground color.

Parameters:
a - the attribute set
fg - the color

getBackground

public static Color getBackground(AttributeSet a)
Gets the background color setting from the attribute list.

Parameters:
a - the attribute set
Returns:
the color, Color.black as the default

setBackground

public static void setBackground(MutableAttributeSet a,
                                 Color fg)
Sets the background color.

Parameters:
a - the attribute set
fg - the color

getFirstLineIndent

public static float getFirstLineIndent(AttributeSet a)
Gets the first line indent setting.

Parameters:
a - the attribute set
Returns:
the value, 0 if not set

setFirstLineIndent

public static void setFirstLineIndent(MutableAttributeSet a,
                                      float i)
Sets the first line indent.

Parameters:
a - the attribute set
i - the value

getRightIndent

public static float getRightIndent(AttributeSet a)
Gets the right indent setting.

Parameters:
a - the attribute set
Returns:
the value, 0 if not set

setRightIndent

public static void setRightIndent(MutableAttributeSet a,
                                  float i)
Sets right indent.

Parameters:
a - the attribute set
i - the value

getLeftIndent

public static float getLeftIndent(AttributeSet a)
Gets the left indent setting.

Parameters:
a - the attribute set
Returns:
the value, 0 if not set

setLeftIndent

public static void setLeftIndent(MutableAttributeSet a,
                                 float i)
Sets left indent.

Parameters:
a - the attribute set
i - the value

getLineSpacing

public static float getLineSpacing(AttributeSet a)
Gets the line spacing setting.

Parameters:
a - the attribute set
Returns:
the value, 0 if not set

setLineSpacing

public static void setLineSpacing(MutableAttributeSet a,
                                  float i)
Sets line spacing.

Parameters:
a - the attribute set
i - the value

getSpaceAbove

public static float getSpaceAbove(AttributeSet a)
Gets the space above setting.

Parameters:
a - the attribute set
Returns:
the value, 0 if not set

setSpaceAbove

public static void setSpaceAbove(MutableAttributeSet a,
                                 float i)
Sets space above.

Parameters:
a - the attribute set
i - the value

getSpaceBelow

public static float getSpaceBelow(AttributeSet a)
Gets the space below setting.

Parameters:
a - the attribute set
Returns:
the value, 0 if not set

setSpaceBelow

public static void setSpaceBelow(MutableAttributeSet a,
                                 float i)
Sets space below.

Parameters:
a - the attribute set
i - the value

getAlignment

public static int getAlignment(AttributeSet a)
Gets the alignment setting.

Parameters:
a - the attribute set
Returns:
the value StyleConstants.ALIGN_LEFT if not set

setAlignment

public static void setAlignment(MutableAttributeSet a,
                                int align)
Sets alignment.

Parameters:
a - the attribute set
align - the alignment value

getTabSet

public static TabSet getTabSet(AttributeSet a)
Gets the TabSet.

Parameters:
a - the attribute set
Returns:
the TabSet

setTabSet

public static void setTabSet(MutableAttributeSet a,
                             TabSet tabs)
Sets the TabSet.

Parameters:
a - the attribute set.
tabs - the TabSet
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


StyleConstants.CharacterConstants (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class StyleConstants.CharacterConstants

java.lang.Object
    extended by javax.swing.text.StyleConstants
        extended by javax.swing.text.StyleConstants.CharacterConstants
All Implemented Interfaces:
AttributeSet.CharacterAttribute
Enclosing class:
StyleConstants
public static class StyleConstants.CharacterConstants
extends StyleConstants
implements AttributeSet.CharacterAttribute

This is a typesafe enumeration of the well-known attributes that contribute to a character style. These are aliased by the outer class for general presentation.

Nested Class Summary
Nested classes inherited from class javax.swing.text.StyleConstants
StyleConstants.CharacterConstants, StyleConstants.ColorConstants, StyleConstants.FontConstants, StyleConstants.ParagraphConstants
Field Summary
static Object | Background Name of the background color attribute.
static Object | BidiLevel Bidirectional level of a character as assigned by the Unicode bidi algorithm.
static Object | Bold Name of the bold attribute.
static Object | ComponentAttribute Name of the component attribute.
static Object | Family Name of the font family.
static Object | Foreground Name of the foreground color attribute.
static Object | IconAttribute Name of the icon attribute.
static Object | Italic Name of the italic attribute.
static Object | Size Name of the font size.
static Object | StrikeThrough Name of the strikethrough attribute.
static Object | Subscript Name of the subscript attribute.
static Object | Superscript Name of the superscript attribute.
static Object | Underline Name of the underline attribute.
Fields inherited from class javax.swing.text.StyleConstants
ALIGN_CENTER, ALIGN_JUSTIFIED, ALIGN_LEFT, ALIGN_RIGHT, Alignment, ComponentElementName, ComposedTextAttribute, FirstLineIndent, FontFamily, FontSize, IconElementName, LeftIndent, LineSpacing, ModelAttribute, NameAttribute, Orientation, ResolveAttribute, RightIndent, SpaceAbove, SpaceBelow, TabSet
Methods inherited from class javax.swing.text.StyleConstants
getAlignment, getBackground, getBidiLevel, getComponent, getFirstLineIndent, getFontFamily, getFontSize, getForeground, getIcon, getLeftIndent, getLineSpacing, getRightIndent, getSpaceAbove, getSpaceBelow, getTabSet, isBold, isItalic, isStrikeThrough, isSubscript, isSuperscript, isUnderline, setAlignment, setBackground, setBidiLevel, setBold, setComponent, setFirstLineIndent, setFontFamily, setFontSize, setForeground, setIcon, setItalic, setLeftIndent, setLineSpacing, setRightIndent, setSpaceAbove, setSpaceBelow, setStrikeThrough, setSubscript, setSuperscript, setTabSet, setUnderline, toString
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

Underline

public static final Object Underline
Name of the underline attribute.

StrikeThrough

public static final Object StrikeThrough
Name of the strikethrough attribute.

Superscript

public static final Object Superscript
Name of the superscript attribute.

Subscript

public static final Object Subscript
Name of the subscript attribute.

ComponentAttribute

public static final Object ComponentAttribute
Name of the component attribute.

IconAttribute

public static final Object IconAttribute
Name of the icon attribute.

BidiLevel

public static final Object BidiLevel
Bidirectional level of a character as assigned by the Unicode bidi algorithm.

Family

public static final Object Family
Name of the font family.

Size

public static final Object Size
Name of the font size.

Bold

public static final Object Bold
Name of the bold attribute.

Italic

public static final Object Italic
Name of the italic attribute.

Foreground

public static final Object Foreground
Name of the foreground color attribute.

Background

public static final Object Background
Name of the background color attribute.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


StyleConstants.ColorConstants (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class StyleConstants.ColorConstants

java.lang.Object
    extended by javax.swing.text.StyleConstants
        extended by javax.swing.text.StyleConstants.ColorConstants
All Implemented Interfaces:
AttributeSet.CharacterAttribute, AttributeSet.ColorAttribute
Enclosing class:
StyleConstants
public static class StyleConstants.ColorConstants
extends StyleConstants
implements AttributeSet.ColorAttribute, AttributeSet.CharacterAttribute

This is a typesafe enumeration of the well-known attributes that contribute to a color. These are aliased by the outer class for general presentation.

Nested Class Summary
Nested classes inherited from class javax.swing.text.StyleConstants
StyleConstants.CharacterConstants, StyleConstants.ColorConstants, StyleConstants.FontConstants, StyleConstants.ParagraphConstants
Field Summary
static Object | Background Name of the background color attribute.
static Object | Foreground Name of the foreground color attribute.
Fields inherited from class javax.swing.text.StyleConstants
ALIGN_CENTER, ALIGN_JUSTIFIED, ALIGN_LEFT, ALIGN_RIGHT, Alignment, BidiLevel, Bold, ComponentAttribute, ComponentElementName, ComposedTextAttribute, FirstLineIndent, FontFamily, FontSize, IconAttribute, IconElementName, Italic, LeftIndent, LineSpacing, ModelAttribute, NameAttribute, Orientation, ResolveAttribute, RightIndent, SpaceAbove, SpaceBelow, StrikeThrough, Subscript, Superscript, TabSet, Underline
Methods inherited from class javax.swing.text.StyleConstants
getAlignment, getBackground, getBidiLevel, getComponent, getFirstLineIndent, getFontFamily, getFontSize, getForeground, getIcon, getLeftIndent, getLineSpacing, getRightIndent, getSpaceAbove, getSpaceBelow, getTabSet, isBold, isItalic, isStrikeThrough, isSubscript, isSuperscript, isUnderline, setAlignment, setBackground, setBidiLevel, setBold, setComponent, setFirstLineIndent, setFontFamily, setFontSize, setForeground, setIcon, setItalic, setLeftIndent, setLineSpacing, setRightIndent, setSpaceAbove, setSpaceBelow, setStrikeThrough, setSubscript, setSuperscript, setTabSet, setUnderline, toString
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

Foreground

public static final Object Foreground
Name of the foreground color attribute.

Background

public static final Object Background
Name of the background color attribute.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


StyleConstants.FontConstants (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class StyleConstants.FontConstants

java.lang.Object
    extended by javax.swing.text.StyleConstants
        extended by javax.swing.text.StyleConstants.FontConstants
All Implemented Interfaces:
AttributeSet.CharacterAttribute, AttributeSet.FontAttribute
Enclosing class:
StyleConstants
public static class StyleConstants.FontConstants
extends StyleConstants
implements AttributeSet.FontAttribute, AttributeSet.CharacterAttribute

This is a typesafe enumeration of the well-known attributes that contribute to a font. These are aliased by the outer class for general presentation.

Nested Class Summary
Nested classes inherited from class javax.swing.text.StyleConstants
StyleConstants.CharacterConstants, StyleConstants.ColorConstants, StyleConstants.FontConstants, StyleConstants.ParagraphConstants
Field Summary
static Object | Bold Name of the bold attribute.
static Object | Family Name of the font family.
static Object | Italic Name of the italic attribute.
static Object | Size Name of the font size.
Fields inherited from class javax.swing.text.StyleConstants
ALIGN_CENTER, ALIGN_JUSTIFIED, ALIGN_LEFT, ALIGN_RIGHT, Alignment, Background, BidiLevel, ComponentAttribute, ComponentElementName, ComposedTextAttribute, FirstLineIndent, FontFamily, FontSize, Foreground, IconAttribute, IconElementName, LeftIndent, LineSpacing, ModelAttribute, NameAttribute, Orientation, ResolveAttribute, RightIndent, SpaceAbove, SpaceBelow, StrikeThrough, Subscript, Superscript, TabSet, Underline
Methods inherited from class javax.swing.text.StyleConstants
getAlignment, getBackground, getBidiLevel, getComponent, getFirstLineIndent, getFontFamily, getFontSize, getForeground, getIcon, getLeftIndent, getLineSpacing, getRightIndent, getSpaceAbove, getSpaceBelow, getTabSet, isBold, isItalic, isStrikeThrough, isSubscript, isSuperscript, isUnderline, setAlignment, setBackground, setBidiLevel, setBold, setComponent, setFirstLineIndent, setFontFamily, setFontSize, setForeground, setIcon, setItalic, setLeftIndent, setLineSpacing, setRightIndent, setSpaceAbove, setSpaceBelow, setStrikeThrough, setSubscript, setSuperscript, setTabSet, setUnderline, toString
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

Family

public static final Object Family
Name of the font family.

Size

public static final Object Size
Name of the font size.

Bold

public static final Object Bold
Name of the bold attribute.

Italic

public static final Object Italic
Name of the italic attribute.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


StyleConstants.ParagraphConstants (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class StyleConstants.ParagraphConstants

java.lang.Object
    extended by javax.swing.text.StyleConstants
        extended by javax.swing.text.StyleConstants.ParagraphConstants
All Implemented Interfaces:
AttributeSet.ParagraphAttribute
Enclosing class:
StyleConstants
public static class StyleConstants.ParagraphConstants
extends StyleConstants
implements AttributeSet.ParagraphAttribute

This is a typesafe enumeration of the well-known attributes that contribute to a paragraph style. These are aliased by the outer class for general presentation.

Nested Class Summary
Nested classes inherited from class javax.swing.text.StyleConstants
StyleConstants.CharacterConstants, StyleConstants.ColorConstants, StyleConstants.FontConstants, StyleConstants.ParagraphConstants
Field Summary
static Object | Alignment Alignment for the paragraph.
static Object | FirstLineIndent The amount of space to indent the first line of the paragraph.
static Object | LeftIndent The amount to indent the left side of the paragraph.
static Object | LineSpacing The amount of space between lines of the paragraph.
static Object | Orientation Orientation for the paragraph.
static Object | RightIndent The amount to indent the right side of the paragraph.
static Object | SpaceAbove The amount of space above the paragraph.
static Object | SpaceBelow The amount of space below the paragraph.
static Object | TabSet TabSet for the paragraph.
Fields inherited from class javax.swing.text.StyleConstants
ALIGN_CENTER, ALIGN_JUSTIFIED, ALIGN_LEFT, ALIGN_RIGHT, Background, BidiLevel, Bold, ComponentAttribute, ComponentElementName, ComposedTextAttribute, FontFamily, FontSize, Foreground, IconAttribute, IconElementName, Italic, ModelAttribute, NameAttribute, ResolveAttribute, StrikeThrough, Subscript, Superscript, Underline
Methods inherited from class javax.swing.text.StyleConstants
getAlignment, getBackground, getBidiLevel, getComponent, getFirstLineIndent, getFontFamily, getFontSize, getForeground, getIcon, getLeftIndent, getLineSpacing, getRightIndent, getSpaceAbove, getSpaceBelow, getTabSet, isBold, isItalic, isStrikeThrough, isSubscript, isSuperscript, isUnderline, setAlignment, setBackground, setBidiLevel, setBold, setComponent, setFirstLineIndent, setFontFamily, setFontSize, setForeground, setIcon, setItalic, setLeftIndent, setLineSpacing, setRightIndent, setSpaceAbove, setSpaceBelow, setStrikeThrough, setSubscript, setSuperscript, setTabSet, setUnderline, toString
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

FirstLineIndent

public static final Object FirstLineIndent
The amount of space to indent the first line of the paragraph. This value may be negative to offset in the reverse direction. The type is Float and specifies the size of the space in points.

LeftIndent

public static final Object LeftIndent
The amount to indent the left side of the paragraph. Type is float and specifies the size in points.

RightIndent

public static final Object RightIndent
The amount to indent the right side of the paragraph. Type is float and specifies the size in points.

LineSpacing

public static final Object LineSpacing
The amount of space between lines of the paragraph. Type is float and specifies the size as a factor of the line height

SpaceAbove

public static final Object SpaceAbove
The amount of space above the paragraph. Type is float and specifies the size in points.

SpaceBelow

public static final Object SpaceBelow
The amount of space below the paragraph. Type is float and specifies the size in points.

Alignment

public static final Object Alignment
Alignment for the paragraph. The type is Integer. Valid values are:
  • ALIGN_LEFT
  • ALIGN_RIGHT
  • ALIGN_CENTER
  • ALIGN_JUSTIFED

TabSet

public static final Object TabSet
TabSet for the paragraph.

Orientation

public static final Object Orientation
Orientation for the paragraph.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


StyleContext (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class StyleContext

java.lang.Object
    extended by javax.swing.text.StyleContext
All Implemented Interfaces:
AbstractDocument.AttributeContext, Serializable
Direct Known Subclasses:
StyleSheet
public class StyleContext
extends Object
implements Serializable, AbstractDocument.AttributeContext

A pool of styles and their associated resources. This class determines the lifetime of a group of resources by being a container that holds caches for various resources such as font and color that get reused by the various style definitions. This can be shared by multiple documents if desired to maximize the sharing of related resources.

This class also provides efficient support for small sets of attributes and compresses them by sharing across uses and taking advantage of their immutable nature. Since many styles are replicated, the potential for sharing is significant, and copies can be extremely cheap. Larger sets reduce the possibility of sharing, and therefore revert automatically to a less space-efficient implementation.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Nested Class Summary
class | StyleContext.NamedStyle A collection of attributes, typically used to represent character and paragraph styles.
class | StyleContext.SmallAttributeSet This class holds a small number of attributes in an array.
Field Summary
static String DEFAULT_STYLE
The name given to the default logical style attached to paragraphs.
Constructor Summary
StyleContext()
Creates a new StyleContext object.
Method Summary
 AttributeSet addAttribute(AttributeSet old, Object name, Object value)
Adds an attribute to the given set, and returns the new representative set.
 AttributeSet addAttributes(AttributeSet old, AttributeSet attr)
Adds a set of attributes to the element.
 void addChangeListener(ChangeListener l)
Adds a listener to track when styles are added or removed.
 Style addStyle(String nm, Style parent)
Adds a new style into the style hierarchy.
protected  MutableAttributeSet createLargeAttributeSet(AttributeSet a)
Create a large set of attributes that should trade off space for time.
protected  StyleContext.SmallAttributeSet createSmallAttributeSet(AttributeSet a)
Create a compact set of attributes that might be shared.
 Color getBackground(AttributeSet attr)
Takes a set of attributes and turn it into a background color specification.
 ChangeListener[] getChangeListeners()
Returns an array of all the ChangeListeners added to this StyleContext with addChangeListener().
protected  int getCompressionThreshold()
Returns the maximum number of key/value pairs to try and compress into unique/immutable sets.
static StyleContext getDefaultStyleContext()
Returns default AttributeContext shared by all documents that don't bother to define/supply their own context.
 AttributeSet getEmptySet()
Fetches an empty AttributeSet.
 Font getFont(AttributeSet attr)
Gets the font from an attribute set.
 Font getFont(String family, int style, int size)
Gets a new font.
 FontMetrics getFontMetrics(Font f)
Returns font metrics for a font.
 Color getForeground(AttributeSet attr)
Takes a set of attributes and turn it into a foreground color specification.
static Object getStaticAttribute(Object key)
Returns the object previously registered with registerStaticAttributeKey.
static Object getStaticAttributeKey(Object key)
Returns the String that key will be registered with
 Style getStyle(String nm)
Fetches a named style previously added to the document
 Enumeration getStyleNames()
Fetches the names of the styles defined.
 void readAttributes(ObjectInputStream in, MutableAttributeSet a)
Context-specific handling of reading in attributes
static void readAttributeSet(ObjectInputStream in, MutableAttributeSet a)
Reads a set of attributes from the given object input stream that have been previously written out with writeAttributeSet.
 void reclaim(AttributeSet a)
Returns a set no longer needed by the MutableAttributeSet implmentation.
static void registerStaticAttributeKey(Object key)
Registers an object as a static object that is being used as a key in attribute sets.
 AttributeSet removeAttribute(AttributeSet old, Object name)
Removes an attribute from the set.
 AttributeSet removeAttributes(AttributeSet old, AttributeSet attrs)
Removes a set of attributes for the element.
 AttributeSet removeAttributes(AttributeSet old, Enumeration names)
Removes a set of attributes for the element.
 void removeChangeListener(ChangeListener l)
Removes a listener that was tracking styles being added or removed.
 void removeStyle(String nm)
Removes a named style previously added to the document.
 String toString()
Converts a StyleContext to a String.
 void writeAttributes(ObjectOutputStream out, AttributeSet a)
Context-specific handling of writing out attributes
static void writeAttributeSet(ObjectOutputStream out, AttributeSet a)
Writes a set of attributes to the given object stream for the purpose of serialization.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

DEFAULT_STYLE

public static final String DEFAULT_STYLE
The name given to the default logical style attached to paragraphs.

See Also:
Constant Field Values
Constructor Detail

StyleContext

public StyleContext()
Creates a new StyleContext object.

Method Detail

getDefaultStyleContext

public static final StyleContext getDefaultStyleContext()
Returns default AttributeContext shared by all documents that don't bother to define/supply their own context.

Returns:
the context

addStyle

public Style addStyle(String nm,
                      Style parent)
Adds a new style into the style hierarchy. Style attributes resolve from bottom up so an attribute specified in a child will override an attribute specified in the parent.

Parameters:
nm - the name of the style (must be unique within the collection of named styles in the document). The name may be null if the style is unnamed, but the caller is responsible for managing the reference returned as an unnamed style can't be fetched by name. An unnamed style may be useful for things like character attribute overrides such as found in a style run.
parent - the parent style. This may be null if unspecified attributes need not be resolved in some other style.
Returns:
the created style

removeStyle

public void removeStyle(String nm)
Removes a named style previously added to the document.

Parameters:
nm - the name of the style to remove

getStyle

public Style getStyle(String nm)
Fetches a named style previously added to the document

Parameters:
nm - the name of the style
Returns:
the style

getStyleNames

public Enumeration getStyleNames()
Fetches the names of the styles defined.

Returns:
the list of names as an enumeration

addChangeListener

public void addChangeListener(ChangeListener l)
Adds a listener to track when styles are added or removed.

Parameters:
l - the change listener

removeChangeListener

public void removeChangeListener(ChangeListener l)
Removes a listener that was tracking styles being added or removed.

Parameters:
l - the change listener

getChangeListeners

public ChangeListener[] getChangeListeners()
Returns an array of all the ChangeListeners added to this StyleContext with addChangeListener().

Returns:
all of the ChangeListeners added or an empty array if no listeners have been added
Since:
1.4

getFont

public Font getFont(AttributeSet attr)
Gets the font from an attribute set. This is implemented to try and fetch a cached font for the given AttributeSet, and if that fails the font features are resolved and the font is fetched from the low-level font cache.

Parameters:
attr - the attribute set
Returns:
the font

getForeground

public Color getForeground(AttributeSet attr)
Takes a set of attributes and turn it into a foreground color specification. This might be used to specify things like brighter, more hue, etc. By default it simply returns the value specified by the StyleConstants.Foreground attribute.

Parameters:
attr - the set of attributes
Returns:
the color

getBackground

public Color getBackground(AttributeSet attr)
Takes a set of attributes and turn it into a background color specification. This might be used to specify things like brighter, more hue, etc. By default it simply returns the value specified by the StyleConstants.Background attribute.

Parameters:
attr - the set of attributes
Returns:
the color

getFont

public Font getFont(String family,
                    int style,
                    int size)
Gets a new font. This returns a Font from a cache if a cached font exists. If not, a Font is added to the cache. This is basically a low-level cache for 1.1 font features.

Parameters:
family - the font family (such as "Monospaced")
style - the style of the font (such as Font.PLAIN)
size - the point size >= 1
Returns:
the new font

getFontMetrics

public FontMetrics getFontMetrics(Font f)
Returns font metrics for a font.

Parameters:
f - the font
Returns:
the metrics

addAttribute

public AttributeSet addAttribute(AttributeSet old,
                                 Object name,
                                 Object value)
Adds an attribute to the given set, and returns the new representative set.

This method is thread safe, although most Swing methods are not. Please see Threads and Swing for more information.

Specified by:
addAttribute in interface AbstractDocument.AttributeContext
Parameters:
old - the old attribute set
name - the non-null attribute name
value - the attribute value
Returns:
the updated attribute set
See Also:
MutableAttributeSet.addAttribute(java.lang.Object, java.lang.Object)

addAttributes

public AttributeSet addAttributes(AttributeSet old,
                                  AttributeSet attr)
Adds a set of attributes to the element.

This method is thread safe, although most Swing methods are not. Please see Threads and Swing for more information.

Specified by:
addAttributes in interface AbstractDocument.AttributeContext
Parameters:
old - the old attribute set
attr - the attributes to add
Returns:
the updated attribute set
See Also:
MutableAttributeSet.addAttribute(java.lang.Object, java.lang.Object)

removeAttribute

public AttributeSet removeAttribute(AttributeSet old,
                                    Object name)
Removes an attribute from the set.

This method is thread safe, although most Swing methods are not. Please see Threads and Swing for more information.

Specified by:
removeAttribute in interface AbstractDocument.AttributeContext
Parameters:
old - the old set of attributes
name - the non-null attribute name
Returns:
the updated attribute set
See Also:
MutableAttributeSet.removeAttribute(java.lang.Object)

removeAttributes

public AttributeSet removeAttributes(AttributeSet old,
                                     Enumeration names)
Removes a set of attributes for the element.

This method is thread safe, although most Swing methods are not. Please see Threads and Swing for more information.

Specified by:
removeAttributes in interface AbstractDocument.AttributeContext
Parameters:
old - the old attribute set
names - the attribute names
Returns:
the updated attribute set
See Also:
MutableAttributeSet.removeAttributes(java.util.Enumeration)

removeAttributes

public AttributeSet removeAttributes(AttributeSet old,
                                     AttributeSet attrs)
Removes a set of attributes for the element.

This method is thread safe, although most Swing methods are not. Please see Threads and Swing for more information.

Specified by:
removeAttributes in interface AbstractDocument.AttributeContext
Parameters:
old - the old attribute set
attrs - the attributes
Returns:
the updated attribute set
See Also:
MutableAttributeSet.removeAttributes(java.util.Enumeration)

getEmptySet

public AttributeSet getEmptySet()
Fetches an empty AttributeSet.

Specified by:
getEmptySet in interface AbstractDocument.AttributeContext
Returns:
the set

reclaim

public void reclaim(AttributeSet a)
Returns a set no longer needed by the MutableAttributeSet implmentation. This is useful for operation under 1.1 where there are no weak references. This would typically be called by the finalize method of the MutableAttributeSet implementation.

This method is thread safe, although most Swing methods are not. Please see Threads and Swing for more information.

Specified by:
reclaim in interface AbstractDocument.AttributeContext
Parameters:
a - the set to reclaim

getCompressionThreshold

protected int getCompressionThreshold()
Returns the maximum number of key/value pairs to try and compress into unique/immutable sets. Any sets above this limit will use hashtables and be a MutableAttributeSet.

Returns:
the threshold

createSmallAttributeSet

protected StyleContext.SmallAttributeSet createSmallAttributeSet(AttributeSet a)
Create a compact set of attributes that might be shared. This is a hook for subclasses that want to alter the behavior of SmallAttributeSet. This can be reimplemented to return an AttributeSet that provides some sort of attribute conversion.

Parameters:
a - The set of attributes to be represented in the the compact form.

createLargeAttributeSet

protected MutableAttributeSet createLargeAttributeSet(AttributeSet a)
Create a large set of attributes that should trade off space for time. This set will not be shared. This is a hook for subclasses that want to alter the behavior of the larger attribute storage format (which is SimpleAttributeSet by default). This can be reimplemented to return a MutableAttributeSet that provides some sort of attribute conversion.

Parameters:
a - The set of attributes to be represented in the the larger form.

toString

public String toString()
Converts a StyleContext to a String.

Overrides:
toString in class Object
Returns:
the string

writeAttributes

public void writeAttributes(ObjectOutputStream out,
                            AttributeSet a)
                     throws IOException
Context-specific handling of writing out attributes

Throws:
IOException

readAttributes

public void readAttributes(ObjectInputStream in,
                           MutableAttributeSet a)
                    throws ClassNotFoundException,
                           IOException
Context-specific handling of reading in attributes

Throws:
ClassNotFoundException
IOException

writeAttributeSet

public static void writeAttributeSet(ObjectOutputStream out,
                                     AttributeSet a)
                              throws IOException
Writes a set of attributes to the given object stream for the purpose of serialization. This will take special care to deal with static attribute keys that have been registered wit the registerStaticAttributeKey method. Any attribute key not regsitered as a static key will be serialized directly. All values are expected to be serializable.

Parameters:
out - the output stream
a - the attribute set
Throws:
IOException - on any I/O error

readAttributeSet

public static void readAttributeSet(ObjectInputStream in,
                                    MutableAttributeSet a)
                             throws ClassNotFoundException,
                                    IOException
Reads a set of attributes from the given object input stream that have been previously written out with writeAttributeSet. This will try to restore keys that were static objects to the static objects in the current virtual machine considering only those keys that have been registered with the registerStaticAttributeKey method. The attributes retrieved from the stream will be placed into the given mutable set.

Parameters:
in - the object stream to read the attribute data from.
a - the attribute set to place the attribute definitions in.
Throws:
ClassNotFoundException - passed upward if encountered when reading the object stream.
IOException - passed upward if encountered when reading the object stream.

registerStaticAttributeKey

public static void registerStaticAttributeKey(Object key)
Registers an object as a static object that is being used as a key in attribute sets. This allows the key to be treated specially for serialization.

For operation under a 1.1 virtual machine, this uses the value returned by toString concatenated to the classname. The value returned by toString should not have the class reference in it (ie it should be reimplemented from the definition in Object) in order to be the same when recomputed later.

Parameters:
key - the non-null object key

getStaticAttribute

public static Object getStaticAttribute(Object key)
Returns the object previously registered with registerStaticAttributeKey.

getStaticAttributeKey

public static Object getStaticAttributeKey(Object key)
Returns the String that key will be registered with

See Also:
getStaticAttribute(java.lang.Object), registerStaticAttributeKey(java.lang.Object)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


StyleContext.NamedStyle (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class StyleContext.NamedStyle

java.lang.Object
    extended by javax.swing.text.StyleContext.NamedStyle
All Implemented Interfaces:
AttributeSet, MutableAttributeSet, Serializable, Style
Enclosing class:
StyleContext
public class StyleContext.NamedStyle
extends Object
implements Style, Serializable

A collection of attributes, typically used to represent character and paragraph styles. This is an implementation of MutableAttributeSet that can be observed if desired. These styles will take advantage of immutability while the sets are small enough, and may be substantially more efficient than something like SimpleAttributeSet.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Nested Class Summary
Nested classes inherited from class javax.swing.text.AttributeSet
AttributeSet.CharacterAttribute, AttributeSet.ColorAttribute, AttributeSet.FontAttribute, AttributeSet.ParagraphAttribute
Field Summary
protected ChangeEvent | changeEvent Only one ChangeEvent is needed per model instance since the event's only (read-only) state is the source property.
protected EventListenerList | listenerList The change listeners for the model.
Fields inherited from interface javax.swing.text.AttributeSet
NameAttribute, ResolveAttribute
Constructor Summary
StyleContext.NamedStyle()
Creates a new named style, with a null name and parent.
StyleContext.NamedStyle(String name, Style parent)
Creates a new named style.
StyleContext.NamedStyle(Style parent)
Creates a new named style.
Method Summary
 void addAttribute(Object name, Object value)
Adds an attribute.
 void addAttributes(AttributeSet attr)
Adds a set of attributes to the element.
 void addChangeListener(ChangeListener l)
Adds a change listener.
 boolean containsAttribute(Object name, Object value)
Checks whether a given attribute name/value is defined.
 boolean containsAttributes(AttributeSet attrs)
Checks whether the element contains all the attributes.
 AttributeSet copyAttributes()
Copies a set of attributes.
protected  void fireStateChanged()
Notifies all listeners that have registered interest for notification on this event type.
 Object getAttribute(Object attrName)
Gets the value of an attribute.
 int getAttributeCount()
Gets the number of attributes that are defined.
 Enumeration getAttributeNames()
Gets the names of all attributes.
 ChangeListener[] getChangeListeners()
Returns an array of all the ChangeListeners added to this NamedStyle with addChangeListener().
 EventListener[] getListeners(Class listenerType)
Return an array of all the listeners of the given type that were added to this model.
 String getName()
Fetches the name of the style.
 AttributeSet getResolveParent()
Gets attributes from the parent.
 boolean isDefined(Object attrName)
Checks whether a given attribute is defined.
 boolean isEqual(AttributeSet attr)
Checks whether two attribute sets are equal.
 void removeAttribute(Object name)
Removes an attribute from the set.
 void removeAttributes(AttributeSet attrs)
Removes a set of attributes for the element.
 void removeAttributes(Enumeration names)
Removes a set of attributes for the element.
 void removeChangeListener(ChangeListener l)
Removes a change listener.
 void setName(String name)
Changes the name of the style.
 void setResolveParent(AttributeSet parent)
Sets the resolving parent.
 String toString()
Converts the style to a string.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

listenerList

protected EventListenerList listenerList
The change listeners for the model.

changeEvent

protected transient ChangeEvent changeEvent
Only one ChangeEvent is needed per model instance since the event's only (read-only) state is the source property. The source of events generated here is always "this".

Constructor Detail

StyleContext.NamedStyle

public StyleContext.NamedStyle(String name,
                               Style parent)
Creates a new named style.

Parameters:
name - the style name, null for unnamed
parent - the parent style, null if none

StyleContext.NamedStyle

public StyleContext.NamedStyle(Style parent)
Creates a new named style.

Parameters:
parent - the parent style, null if none

StyleContext.NamedStyle

public StyleContext.NamedStyle()
Creates a new named style, with a null name and parent.

Method Detail

toString

public String toString()
Converts the style to a string.

Overrides:
toString in class Object
Returns:
the string

getName

public String getName()
Fetches the name of the style. A style is not required to be named, so null is returned if there is no name associated with the style.

Specified by:
getName in interface Style
Returns:
the name

setName

public void setName(String name)
Changes the name of the style. Does nothing with a null name.

Parameters:
name - the new name

addChangeListener

public void addChangeListener(ChangeListener l)
Adds a change listener.

Specified by:
addChangeListener in interface Style
Parameters:
l - the change listener

removeChangeListener

public void removeChangeListener(ChangeListener l)
Removes a change listener.

Specified by:
removeChangeListener in interface Style
Parameters:
l - the change listener

getChangeListeners

public ChangeListener[] getChangeListeners()
Returns an array of all the ChangeListeners added to this NamedStyle with addChangeListener().

Returns:
all of the ChangeListeners added or an empty array if no listeners have been added
Since:
1.4

fireStateChanged

protected void fireStateChanged()
Notifies all listeners that have registered interest for notification on this event type. The event instance is lazily created using the parameters passed into the fire method.

See Also:
EventListenerList

getListeners

public EventListener[] getListeners(Class listenerType)
Return an array of all the listeners of the given type that were added to this model.

Returns:
all of the objects receiving listenerType notifications from this model
Since:
1.3

getAttributeCount

public int getAttributeCount()
Gets the number of attributes that are defined.

Specified by:
getAttributeCount in interface AttributeSet
Returns:
the number of attributes >= 0
See Also:
AttributeSet.getAttributeCount()

isDefined

public boolean isDefined(Object attrName)
Checks whether a given attribute is defined.

Specified by:
isDefined in interface AttributeSet
Parameters:
attrName - the non-null attribute name
Returns:
true if the attribute is defined
See Also:
AttributeSet.isDefined(java.lang.Object)

isEqual

public boolean isEqual(AttributeSet attr)
Checks whether two attribute sets are equal.

Specified by:
isEqual in interface AttributeSet
Parameters:
attr - the attribute set to check against
Returns:
true if the same
See Also:
AttributeSet.isEqual(javax.swing.text.AttributeSet)

copyAttributes

public AttributeSet copyAttributes()
Copies a set of attributes.

Specified by:
copyAttributes in interface AttributeSet
Returns:
the copy
See Also:
AttributeSet.copyAttributes()

getAttribute

public Object getAttribute(Object attrName)
Gets the value of an attribute.

Specified by:
getAttribute in interface AttributeSet
Parameters:
attrName - the non-null attribute name
Returns:
the attribute value
See Also:
AttributeSet.getAttribute(java.lang.Object)

getAttributeNames

public Enumeration getAttributeNames()
Gets the names of all attributes.

Specified by:
getAttributeNames in interface AttributeSet
Returns:
the attribute names as an enumeration
See Also:
AttributeSet.getAttributeNames()

containsAttribute

public boolean containsAttribute(Object name,
                                 Object value)
Checks whether a given attribute name/value is defined.

Specified by:
containsAttribute in interface AttributeSet
Parameters:
name - the non-null attribute name
value - the attribute value
Returns:
true if the name/value is defined
See Also:
AttributeSet.containsAttribute(java.lang.Object, java.lang.Object)

containsAttributes

public boolean containsAttributes(AttributeSet attrs)
Checks whether the element contains all the attributes.

Specified by:
containsAttributes in interface AttributeSet
Parameters:
attrs - the attributes to check
Returns:
true if the element contains all the attributes
See Also:
AttributeSet.containsAttributes(javax.swing.text.AttributeSet)

getResolveParent

public AttributeSet getResolveParent()
Gets attributes from the parent. If not overriden, the resolving parent defaults to the parent element.

Specified by:
getResolveParent in interface AttributeSet
Returns:
the attributes from the parent
See Also:
AttributeSet.getResolveParent()

addAttribute

public void addAttribute(Object name,
                         Object value)
Adds an attribute.

Specified by:
addAttribute in interface MutableAttributeSet
Parameters:
name - the non-null attribute name
value - the attribute value
See Also:
MutableAttributeSet.addAttribute(java.lang.Object, java.lang.Object)

addAttributes

public void addAttributes(AttributeSet attr)
Adds a set of attributes to the element.

Specified by:
addAttributes in interface MutableAttributeSet
Parameters:
attr - the attributes to add
See Also:
MutableAttributeSet.addAttribute(java.lang.Object, java.lang.Object)

removeAttribute

public void removeAttribute(Object name)
Removes an attribute from the set.

Specified by:
removeAttribute in interface MutableAttributeSet
Parameters:
name - the non-null attribute name
See Also:
MutableAttributeSet.removeAttribute(java.lang.Object)

removeAttributes

public void removeAttributes(Enumeration names)
Removes a set of attributes for the element.

Specified by:
removeAttributes in interface MutableAttributeSet
Parameters:
names - the attribute names
See Also:
MutableAttributeSet.removeAttributes(java.util.Enumeration)

removeAttributes

public void removeAttributes(AttributeSet attrs)
Removes a set of attributes for the element.

Specified by:
removeAttributes in interface MutableAttributeSet
Parameters:
attrs - the attributes
See Also:
MutableAttributeSet.removeAttributes(java.util.Enumeration)

setResolveParent

public void setResolveParent(AttributeSet parent)
Sets the resolving parent.

Specified by:
setResolveParent in interface MutableAttributeSet
Parameters:
parent - the parent, null if none
See Also:
MutableAttributeSet.setResolveParent(javax.swing.text.AttributeSet)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


StyleContext.SmallAttributeSet (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class StyleContext.SmallAttributeSet

java.lang.Object
    extended by javax.swing.text.StyleContext.SmallAttributeSet
All Implemented Interfaces:
AttributeSet
Enclosing class:
StyleContext
public class StyleContext.SmallAttributeSet
extends Object
implements AttributeSet

This class holds a small number of attributes in an array. The storage format is key, value, key, value, etc. The size of the set is the length of the array divided by two. By default, this is the class that will be used to store attributes when held in the compact sharable form.

Nested Class Summary
Nested classes inherited from class javax.swing.text.AttributeSet
AttributeSet.CharacterAttribute, AttributeSet.ColorAttribute, AttributeSet.FontAttribute, AttributeSet.ParagraphAttribute
Field Summary
Fields inherited from interface javax.swing.text.AttributeSet
NameAttribute, ResolveAttribute
Constructor Summary
StyleContext.SmallAttributeSet(AttributeSet attrs)
StyleContext.SmallAttributeSet(Object[] attributes)
Method Summary
Object | clone() Clones a set of attributes.
boolean | containsAttribute(Object name, Object value) Checks whether a given attribute name/value is defined.
boolean | containsAttributes(AttributeSet attrs) Checks whether the attribute set contains all of the given attributes.
AttributeSet | copyAttributes() Copies a set of attributes.
boolean | equals(Object obj) Compares this object to the specifed object.
Object | getAttribute(Object key) Gets the value of an attribute.
int | getAttributeCount() Gets the number of attributes that are defined.
Enumeration | getAttributeNames() Gets the names of all attributes.
AttributeSet | getResolveParent() If not overriden, the resolving parent defaults to the parent element.
int | hashCode() Returns a hashcode for this set of attributes.
boolean | isDefined(Object key) Checks whether a given attribute is defined.
boolean | isEqual(AttributeSet attr) Checks whether two attribute sets are equal.
String | toString() Returns a string showing the key/value pairs
Methods inherited from class java.lang.Object
finalize, getClass, notify, notifyAll, wait, wait, wait

Constructor Detail

StyleContext.SmallAttributeSet

public StyleContext.SmallAttributeSet(Object[] attributes)

StyleContext.SmallAttributeSet

public StyleContext.SmallAttributeSet(AttributeSet attrs)
Method Detail

toString

public String toString()
Returns a string showing the key/value pairs

Overrides:
toString in class Object
Returns:
a string representation of the object.

hashCode

public int hashCode()
Returns a hashcode for this set of attributes.

Overrides:
hashCode in class Object
Returns:
a hashcode value for this set of attributes.
See Also:
Object.equals(java.lang.Object), Hashtable

equals

public boolean equals(Object obj)
Compares this object to the specifed object. The result is true if the object is an equivalent set of attributes.

Overrides:
equals in class Object
Parameters:
obj - the object to compare with.
Returns:
true if the objects are equal; false otherwise.
See Also:
Object.hashCode(), Hashtable

clone

public Object clone()
Clones a set of attributes. Since the set is immutable, a clone is basically the same set.

Overrides:
clone in class Object
Returns:
the set of attributes
See Also:
Cloneable

getAttributeCount

public int getAttributeCount()
Gets the number of attributes that are defined.

Specified by:
getAttributeCount in interface AttributeSet
Returns:
the number of attributes
See Also:
AttributeSet.getAttributeCount()

isDefined

public boolean isDefined(Object key)
Checks whether a given attribute is defined.

Specified by:
isDefined in interface AttributeSet
Parameters:
key - the attribute key
Returns:
true if the attribute is defined
See Also:
AttributeSet.isDefined(java.lang.Object)

isEqual

public boolean isEqual(AttributeSet attr)
Checks whether two attribute sets are equal.

Specified by:
isEqual in interface AttributeSet
Parameters:
attr - the attribute set to check against
Returns:
true if the same
See Also:
AttributeSet.isEqual(javax.swing.text.AttributeSet)

copyAttributes

public AttributeSet copyAttributes()
Copies a set of attributes.

Specified by:
copyAttributes in interface AttributeSet
Returns:
the copy
See Also:
AttributeSet.copyAttributes()

getAttribute

public Object getAttribute(Object key)
Gets the value of an attribute.

Specified by:
getAttribute in interface AttributeSet
Parameters:
key - the attribute name
Returns:
the attribute value
See Also:
AttributeSet.getAttribute(java.lang.Object)

getAttributeNames

public Enumeration getAttributeNames()
Gets the names of all attributes.

Specified by:
getAttributeNames in interface AttributeSet
Returns:
the attribute names
See Also:
AttributeSet.getAttributeNames()

containsAttribute

public boolean containsAttribute(Object name,
                                 Object value)
Checks whether a given attribute name/value is defined.

Specified by:
containsAttribute in interface AttributeSet
Parameters:
name - the attribute name
value - the attribute value
Returns:
true if the name/value is defined
See Also:
AttributeSet.containsAttribute(java.lang.Object, java.lang.Object)

containsAttributes

public boolean containsAttributes(AttributeSet attrs)
Checks whether the attribute set contains all of the given attributes.

Specified by:
containsAttributes in interface AttributeSet
Parameters:
attrs - the attributes to check
Returns:
true if the element contains all the attributes
See Also:
AttributeSet.containsAttributes(javax.swing.text.AttributeSet)

getResolveParent

public AttributeSet getResolveParent()
If not overriden, the resolving parent defaults to the parent element.

Specified by:
getResolveParent in interface AttributeSet
Returns:
the attributes from the parent
See Also:
AttributeSet.getResolveParent()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


StyledDocument (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Interface StyledDocument

All Superinterfaces:
Document
All Known Implementing Classes:
DefaultStyledDocument
public interface StyledDocument
extends Document

Interface for a generic styled document.

Field Summary
Fields inherited from interface javax.swing.text.Document
StreamDescriptionProperty, TitleProperty
Method Summary
Style | addStyle(String nm, Style parent) Adds a new style into the logical style hierarchy.
Color | getBackground(AttributeSet attr) Takes a set of attributes and turn it into a background color specification.
Element | getCharacterElement(int pos) Gets the element that represents the character that is at the given offset within the document.
Font | getFont(AttributeSet attr) Takes a set of attributes and turn it into a font specification.
Color | getForeground(AttributeSet attr) Takes a set of attributes and turn it into a foreground color specification.
Style | getLogicalStyle(int p) Gets a logical style for a given position in a paragraph.
Element | getParagraphElement(int pos) Gets the element that represents the paragraph that encloses the given offset within the document.
Style | getStyle(String nm) Fetches a named style previously added.
void | removeStyle(String nm) Removes a named style previously added to the document.
void | setCharacterAttributes(int offset, int length, AttributeSet s, boolean replace) Changes the content element attributes used for the given range of existing content in the document.
void | setLogicalStyle(int pos, Style s) Sets the logical style to use for the paragraph at the given position.
void | setParagraphAttributes(int offset, int length, AttributeSet s, boolean replace) Sets paragraph attributes.
Methods inherited from interface javax.swing.text.Document
addDocumentListener, addUndoableEditListener, createPosition, getDefaultRootElement, getEndPosition, getLength, getProperty, getRootElements, getStartPosition, getText, getText, insertString, putProperty, remove, removeDocumentListener, removeUndoableEditListener, render

Method Detail

addStyle

public Style addStyle(String nm,
                      Style parent)
Adds a new style into the logical style hierarchy. Style attributes resolve from bottom up so an attribute specified in a child will override an attribute specified in the parent.

Parameters:
nm - the name of the style (must be unique within the collection of named styles). The name may be null if the style is unnamed, but the caller is responsible for managing the reference returned as an unnamed style can't be fetched by name. An unnamed style may be useful for things like character attribute overrides such as found in a style run.
parent - the parent style. This may be null if unspecified attributes need not be resolved in some other style.
Returns:
the style

removeStyle

public void removeStyle(String nm)
Removes a named style previously added to the document.

Parameters:
nm - the name of the style to remove

getStyle

public Style getStyle(String nm)
Fetches a named style previously added.

Parameters:
nm - the name of the style
Returns:
the style

setCharacterAttributes

public void setCharacterAttributes(int offset,
                                   int length,
                                   AttributeSet s,
                                   boolean replace)
Changes the content element attributes used for the given range of existing content in the document. All of the attributes defined in the given Attributes argument are applied to the given range. This method can be used to completely remove all content level attributes for the given range by giving an Attributes argument that has no attributes defined and setting replace to true.

Parameters:
offset - the start of the change >= 0
length - the length of the change >= 0
s - the non-null attributes to change to. Any attributes defined will be applied to the text for the given range.
replace - indicates whether or not the previous attributes should be cleared before the new attributes as set. If true, the operation will replace the previous attributes entirely. If false, the new attributes will be merged with the previous attributes.

setParagraphAttributes

public void setParagraphAttributes(int offset,
                                   int length,
                                   AttributeSet s,
                                   boolean replace)
Sets paragraph attributes.

Parameters:
offset - the start of the change >= 0
length - the length of the change >= 0
s - the non-null attributes to change to. Any attributes defined will be applied to the text for the given range.
replace - indicates whether or not the previous attributes should be cleared before the new attributes are set. If true, the operation will replace the previous attributes entirely. If false, the new attributes will be merged with the previous attributes.

setLogicalStyle

public void setLogicalStyle(int pos,
                            Style s)
Sets the logical style to use for the paragraph at the given position. If attributes aren't explicitly set for character and paragraph attributes they will resolve through the logical style assigned to the paragraph, which in turn may resolve through some hierarchy completely independent of the element hierarchy in the document.

Parameters:
pos - the starting position >= 0
s - the style to set

getLogicalStyle

public Style getLogicalStyle(int p)
Gets a logical style for a given position in a paragraph.

Parameters:
p - the position >= 0
Returns:
the style

getParagraphElement

public Element getParagraphElement(int pos)
Gets the element that represents the paragraph that encloses the given offset within the document.

Parameters:
pos - the offset >= 0
Returns:
the element

getCharacterElement

public Element getCharacterElement(int pos)
Gets the element that represents the character that is at the given offset within the document.

Parameters:
pos - the offset >= 0
Returns:
the element

getForeground

public Color getForeground(AttributeSet attr)
Takes a set of attributes and turn it into a foreground color specification. This might be used to specify things like brighter, more hue, etc.

Parameters:
attr - the set of attributes
Returns:
the color

getBackground

public Color getBackground(AttributeSet attr)
Takes a set of attributes and turn it into a background color specification. This might be used to specify things like brighter, more hue, etc.

Parameters:
attr - the set of attributes
Returns:
the color

getFont

public Font getFont(AttributeSet attr)
Takes a set of attributes and turn it into a font specification. This can be used to turn things like family, style, size, etc into a font that is available on the system the document is currently being used on.

Parameters:
attr - the set of attributes
Returns:
the font
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


StyledEditorKit (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class StyledEditorKit

java.lang.Object
    extended by javax.swing.text.EditorKit
        extended by javax.swing.text.DefaultEditorKit
            extended by javax.swing.text.StyledEditorKit
All Implemented Interfaces:
Cloneable, Serializable
Direct Known Subclasses:
HTMLEditorKit, RTFEditorKit
public class StyledEditorKit
extends DefaultEditorKit

This is the set of things needed by a text component to be a reasonably functioning editor for some type of text document. This implementation provides a default implementation which treats text as styled text and provides a minimal set of actions for editing styled text.

Nested Class Summary
static class | StyledEditorKit.AlignmentAction An action to set paragraph alignment.
static class | StyledEditorKit.BoldAction An action to toggle the bold attribute.
static class | StyledEditorKit.FontFamilyAction An action to set the font family in the associated JEditorPane.
static class | StyledEditorKit.FontSizeAction An action to set the font size in the associated JEditorPane.
static class | StyledEditorKit.ForegroundAction An action to set foreground color.
static class | StyledEditorKit.ItalicAction An action to toggle the italic attribute.
static class | StyledEditorKit.StyledTextAction An action that assumes it's being fired on a JEditorPane with a StyledEditorKit (or subclass) installed.
static class | StyledEditorKit.UnderlineAction An action to toggle the underline attribute.
Nested classes inherited from class javax.swing.text.DefaultEditorKit
DefaultEditorKit.BeepAction, DefaultEditorKit.CopyAction, DefaultEditorKit.CutAction, DefaultEditorKit.DefaultKeyTypedAction, DefaultEditorKit.InsertBreakAction, DefaultEditorKit.InsertContentAction, DefaultEditorKit.InsertTabAction, DefaultEditorKit.PasteAction
Field Summary
Fields inherited from class javax.swing.text.DefaultEditorKit
backwardAction, beepAction, beginAction, beginLineAction, beginParagraphAction, beginWordAction, copyAction, cutAction, defaultKeyTypedAction, deleteNextCharAction, deletePrevCharAction, downAction, endAction, endLineAction, EndOfLineStringProperty, endParagraphAction, endWordAction, forwardAction, insertBreakAction, insertContentAction, insertTabAction, nextWordAction, pageDownAction, pageUpAction, pasteAction, previousWordAction, readOnlyAction, selectAllAction, selectionBackwardAction, selectionBeginAction, selectionBeginLineAction, selectionBeginParagraphAction, selectionBeginWordAction, selectionDownAction, selectionEndAction, selectionEndLineAction, selectionEndParagraphAction, selectionEndWordAction, selectionForwardAction, selectionNextWordAction, selectionPreviousWordAction, selectionUpAction, selectLineAction, selectParagraphAction, selectWordAction, upAction, writableAction
Constructor Summary
StyledEditorKit()
Creates a new EditorKit used for styled documents.
Method Summary
Object | clone() Creates a copy of the editor kit.
Document | createDefaultDocument() Creates an uninitialized text storage model that is appropriate for this type of editor.
protected void | createInputAttributes(Element element, MutableAttributeSet set) Copies the key/values in elements AttributeSet into set.
void | deinstall(JEditorPane c) Called when the kit is being removed from the JEditorPane.
Action[] | getActions() Fetches the command list for the editor.
Element | getCharacterAttributeRun() Fetches the element representing the current run of character attributes for the caret.
MutableAttributeSet | getInputAttributes() Gets the input attributes for the pane.
ViewFactory | getViewFactory() Fetches a factory that is suitable for producing views of any models that are produced by this kit.
void | install(JEditorPane c) Called when the kit is being installed into a JEditorPane.
Methods inherited from class javax.swing.text.DefaultEditorKit
createCaret, getContentType, read, read, write, write
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

StyledEditorKit

public StyledEditorKit()
Creates a new EditorKit used for styled documents.

Method Detail

getInputAttributes

public MutableAttributeSet getInputAttributes()
Gets the input attributes for the pane. When the caret moves and there is no selection, the input attributes are automatically mutated to reflect the character attributes of the current caret location. The styled editing actions use the input attributes to carry out their actions.

Returns:
the attribute set

getCharacterAttributeRun

public Element getCharacterAttributeRun()
Fetches the element representing the current run of character attributes for the caret.

Returns:
the element

getActions

public Action[] getActions()
Fetches the command list for the editor. This is the list of commands supported by the superclass augmented by the collection of commands defined locally for style operations.

Overrides:
getActions in class DefaultEditorKit
Returns:
the command list

createDefaultDocument

public Document createDefaultDocument()
Creates an uninitialized text storage model that is appropriate for this type of editor.

Overrides:
createDefaultDocument in class DefaultEditorKit
Returns:
the model

install

public void install(JEditorPane c)
Called when the kit is being installed into a JEditorPane.

Overrides:
install in class EditorKit
Parameters:
c - the JEditorPane

deinstall

public void deinstall(JEditorPane c)
Called when the kit is being removed from the JEditorPane. This is used to unregister any listeners that were attached.

Overrides:
deinstall in class EditorKit
Parameters:
c - the JEditorPane

getViewFactory

public ViewFactory getViewFactory()
Fetches a factory that is suitable for producing views of any models that are produced by this kit. This is implemented to return View implementations for the following kinds of elements:
  • AbstractDocument.ContentElementName
  • AbstractDocument.ParagraphElementName
  • AbstractDocument.SectionElementName
  • StyleConstants.ComponentElementName
  • StyleConstants.IconElementName

Overrides:
getViewFactory in class DefaultEditorKit
Returns:
the factory

clone

public Object clone()
Creates a copy of the editor kit.

Overrides:
clone in class EditorKit
Returns:
the copy

createInputAttributes

protected void createInputAttributes(Element element,
                                     MutableAttributeSet set)
Copies the key/values in elements AttributeSet into set. This does not copy component, icon, or element names attributes. Subclasses may wish to refine what is and what isn't copied here. But be sure to first remove all the attributes that are in set.

This is called anytime the caret moves over a different location.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


StyledEditorKit.AlignmentAction (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class StyledEditorKit.AlignmentAction

java.lang.Object
    extended by javax.swing.AbstractAction
        extended by javax.swing.text.TextAction
            extended by javax.swing.text.StyledEditorKit.StyledTextAction
                extended by javax.swing.text.StyledEditorKit.AlignmentAction
All Implemented Interfaces:
Action, ActionListener, Cloneable, EventListener, Serializable
Enclosing class:
StyledEditorKit
public static class StyledEditorKit.AlignmentAction
extends StyledEditorKit.StyledTextAction

An action to set paragraph alignment. This sets the StyleConstants.Alignment attribute for the currently selected range of the target JEditorPane. This is done by calling StyledDocument.setParagraphAttributes on the styled document associated with the target JEditorPane.

If the target text component is specified as the source of the ActionEvent and there is a command string, the command string will be interpreted as an integer that should be one of the legal values for the StyleConstants.Alignment attribute.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Field Summary
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SHORT_DESCRIPTION, SMALL_ICON
Constructor Summary
StyledEditorKit.AlignmentAction(String nm, int a)
Creates a new AlignmentAction.
Method Summary
 void actionPerformed(ActionEvent e)
Sets the alignment.
Methods inherited from class javax.swing.text.StyledEditorKit.StyledTextAction
getEditor, getStyledDocument, getStyledEditorKit, setCharacterAttributes, setParagraphAttributes
Methods inherited from class javax.swing.text.TextAction
augmentList, getFocusedComponent, getTextComponent
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

StyledEditorKit.AlignmentAction

public StyledEditorKit.AlignmentAction(String nm,
                                       int a)
Creates a new AlignmentAction.

Parameters:
nm - the action name
a - the alignment >= 0
Method Detail

actionPerformed

public void actionPerformed(ActionEvent e)
Sets the alignment.

Parameters:
e - the action event
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


StyledEditorKit.BoldAction (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class StyledEditorKit.BoldAction

java.lang.Object
    extended by javax.swing.AbstractAction
        extended by javax.swing.text.TextAction
            extended by javax.swing.text.StyledEditorKit.StyledTextAction
                extended by javax.swing.text.StyledEditorKit.BoldAction
All Implemented Interfaces:
Action, ActionListener, Cloneable, EventListener, Serializable
Enclosing class:
StyledEditorKit
public static class StyledEditorKit.BoldAction
extends StyledEditorKit.StyledTextAction

An action to toggle the bold attribute.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Field Summary
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SHORT_DESCRIPTION, SMALL_ICON
Constructor Summary
StyledEditorKit.BoldAction()
Constructs a new BoldAction.
Method Summary
 void actionPerformed(ActionEvent e)
Toggles the bold attribute.
Methods inherited from class javax.swing.text.StyledEditorKit.StyledTextAction
getEditor, getStyledDocument, getStyledEditorKit, setCharacterAttributes, setParagraphAttributes
Methods inherited from class javax.swing.text.TextAction
augmentList, getFocusedComponent, getTextComponent
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

StyledEditorKit.BoldAction

public StyledEditorKit.BoldAction()
Constructs a new BoldAction.

Method Detail

actionPerformed

public void actionPerformed(ActionEvent e)
Toggles the bold attribute.

Parameters:
e - the action event
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


StyledEditorKit.FontFamilyAction (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class StyledEditorKit.FontFamilyAction

java.lang.Object
    extended by javax.swing.AbstractAction
        extended by javax.swing.text.TextAction
            extended by javax.swing.text.StyledEditorKit.StyledTextAction
                extended by javax.swing.text.StyledEditorKit.FontFamilyAction
All Implemented Interfaces:
Action, ActionListener, Cloneable, EventListener, Serializable
Enclosing class:
StyledEditorKit
public static class StyledEditorKit.FontFamilyAction
extends StyledEditorKit.StyledTextAction

An action to set the font family in the associated JEditorPane. This will use the family specified as the command string on the ActionEvent if there is one, otherwise the family that was initialized with will be used.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Field Summary
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SHORT_DESCRIPTION, SMALL_ICON
Constructor Summary
StyledEditorKit.FontFamilyAction(String nm, String family)
Creates a new FontFamilyAction.
Method Summary
 void actionPerformed(ActionEvent e)
Sets the font family.
Methods inherited from class javax.swing.text.StyledEditorKit.StyledTextAction
getEditor, getStyledDocument, getStyledEditorKit, setCharacterAttributes, setParagraphAttributes
Methods inherited from class javax.swing.text.TextAction
augmentList, getFocusedComponent, getTextComponent
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

StyledEditorKit.FontFamilyAction

public StyledEditorKit.FontFamilyAction(String nm,
                                        String family)
Creates a new FontFamilyAction.

Parameters:
nm - the action name
family - the font family
Method Detail

actionPerformed

public void actionPerformed(ActionEvent e)
Sets the font family.

Parameters:
e - the event
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


StyledEditorKit.FontSizeAction (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class StyledEditorKit.FontSizeAction

java.lang.Object
    extended by javax.swing.AbstractAction
        extended by javax.swing.text.TextAction
            extended by javax.swing.text.StyledEditorKit.StyledTextAction
                extended by javax.swing.text.StyledEditorKit.FontSizeAction
All Implemented Interfaces:
Action, ActionListener, Cloneable, EventListener, Serializable
Enclosing class:
StyledEditorKit
public static class StyledEditorKit.FontSizeAction
extends StyledEditorKit.StyledTextAction

An action to set the font size in the associated JEditorPane. This will use the size specified as the command string on the ActionEvent if there is one, otherwise the size that was initialized with will be used.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Field Summary
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SHORT_DESCRIPTION, SMALL_ICON
Constructor Summary
StyledEditorKit.FontSizeAction(String nm, int size)
Creates a new FontSizeAction.
Method Summary
 void actionPerformed(ActionEvent e)
Sets the font size.
Methods inherited from class javax.swing.text.StyledEditorKit.StyledTextAction
getEditor, getStyledDocument, getStyledEditorKit, setCharacterAttributes, setParagraphAttributes
Methods inherited from class javax.swing.text.TextAction
augmentList, getFocusedComponent, getTextComponent
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

StyledEditorKit.FontSizeAction

public StyledEditorKit.FontSizeAction(String nm,
                                      int size)
Creates a new FontSizeAction.

Parameters:
nm - the action name
size - the font size
Method Detail

actionPerformed

public void actionPerformed(ActionEvent e)
Sets the font size.

Parameters:
e - the action event
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


StyledEditorKit.ForegroundAction (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class StyledEditorKit.ForegroundAction

java.lang.Object
    extended by javax.swing.AbstractAction
        extended by javax.swing.text.TextAction
            extended by javax.swing.text.StyledEditorKit.StyledTextAction
                extended by javax.swing.text.StyledEditorKit.ForegroundAction
All Implemented Interfaces:
Action, ActionListener, Cloneable, EventListener, Serializable
Enclosing class:
StyledEditorKit
public static class StyledEditorKit.ForegroundAction
extends StyledEditorKit.StyledTextAction

An action to set foreground color. This sets the StyleConstants.Foreground attribute for the currently selected range of the target JEditorPane. This is done by calling StyledDocument.setCharacterAttributes on the styled document associated with the target JEditorPane.

If the target text component is specified as the source of the ActionEvent and there is a command string, the command string will be interpreted as the foreground color. It will be interpreted by called Color.decode, and should therefore be legal input for that method.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Field Summary
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SHORT_DESCRIPTION, SMALL_ICON
Constructor Summary
StyledEditorKit.ForegroundAction(String nm, Color fg)
Creates a new ForegroundAction.
Method Summary
 void actionPerformed(ActionEvent e)
Sets the foreground color.
Methods inherited from class javax.swing.text.StyledEditorKit.StyledTextAction
getEditor, getStyledDocument, getStyledEditorKit, setCharacterAttributes, setParagraphAttributes
Methods inherited from class javax.swing.text.TextAction
augmentList, getFocusedComponent, getTextComponent
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

StyledEditorKit.ForegroundAction

public StyledEditorKit.ForegroundAction(String nm,
                                        Color fg)
Creates a new ForegroundAction.

Parameters:
nm - the action name
fg - the foreground color
Method Detail

actionPerformed

public void actionPerformed(ActionEvent e)
Sets the foreground color.

Parameters:
e - the action event
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


StyledEditorKit.ItalicAction (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class StyledEditorKit.ItalicAction

java.lang.Object
    extended by javax.swing.AbstractAction
        extended by javax.swing.text.TextAction
            extended by javax.swing.text.StyledEditorKit.StyledTextAction
                extended by javax.swing.text.StyledEditorKit.ItalicAction
All Implemented Interfaces:
Action, ActionListener, Cloneable, EventListener, Serializable
Enclosing class:
StyledEditorKit
public static class StyledEditorKit.ItalicAction
extends StyledEditorKit.StyledTextAction

An action to toggle the italic attribute.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Field Summary
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SHORT_DESCRIPTION, SMALL_ICON
Constructor Summary
StyledEditorKit.ItalicAction()
Constructs a new ItalicAction.
Method Summary
 void actionPerformed(ActionEvent e)
Toggles the italic attribute.
Methods inherited from class javax.swing.text.StyledEditorKit.StyledTextAction
getEditor, getStyledDocument, getStyledEditorKit, setCharacterAttributes, setParagraphAttributes
Methods inherited from class javax.swing.text.TextAction
augmentList, getFocusedComponent, getTextComponent
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

StyledEditorKit.ItalicAction

public StyledEditorKit.ItalicAction()
Constructs a new ItalicAction.

Method Detail

actionPerformed

public void actionPerformed(ActionEvent e)
Toggles the italic attribute.

Parameters:
e - the action event
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


StyledEditorKit.StyledTextAction (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class StyledEditorKit.StyledTextAction

java.lang.Object
    extended by javax.swing.AbstractAction
        extended by javax.swing.text.TextAction
            extended by javax.swing.text.StyledEditorKit.StyledTextAction
All Implemented Interfaces:
Action, ActionListener, Cloneable, EventListener, Serializable
Direct Known Subclasses:
HTMLEditorKit.HTMLTextAction, StyledEditorKit.AlignmentAction, StyledEditorKit.BoldAction, StyledEditorKit.FontFamilyAction, StyledEditorKit.FontSizeAction, StyledEditorKit.ForegroundAction, StyledEditorKit.ItalicAction, StyledEditorKit.UnderlineAction
Enclosing class:
StyledEditorKit
public abstract static class StyledEditorKit.StyledTextAction
extends TextAction

An action that assumes it's being fired on a JEditorPane with a StyledEditorKit (or subclass) installed. This has some convenience methods for causing character or paragraph level attribute changes. The convenience methods will throw an IllegalArgumentException if the assumption of a StyledDocument, a JEditorPane, or a StyledEditorKit fail to be true.

The component that gets acted upon by the action will be the source of the ActionEvent if the source can be narrowed to a JEditorPane type. If the source can't be narrowed, the most recently focused text component is changed. If neither of these are the case, the action cannot be performed.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Field Summary
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SHORT_DESCRIPTION, SMALL_ICON
Constructor Summary
StyledEditorKit.StyledTextAction(String nm)
Creates a new StyledTextAction from a string action name.
Method Summary
protected JEditorPane | getEditor(ActionEvent e) Gets the target editor for an action.
protected StyledDocument | getStyledDocument(JEditorPane e) Gets the document associated with an editor pane.
protected StyledEditorKit | getStyledEditorKit(JEditorPane e) Gets the editor kit associated with an editor pane.
protected void | setCharacterAttributes(JEditorPane editor, AttributeSet attr, boolean replace) Applies the given attributes to character content.
protected void | setParagraphAttributes(JEditorPane editor, AttributeSet attr, boolean replace) Applies the given attributes to paragraphs.
Methods inherited from class javax.swing.text.TextAction
augmentList, getFocusedComponent, getTextComponent
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Methods inherited from interface java.awt.event.ActionListener
actionPerformed

Constructor Detail

StyledEditorKit.StyledTextAction

public StyledEditorKit.StyledTextAction(String nm)
Creates a new StyledTextAction from a string action name.

Parameters:
nm - the name of the action
Method Detail

getEditor

protected final JEditorPane getEditor(ActionEvent e)
Gets the target editor for an action.

Parameters:
e - the action event
Returns:
the editor

getStyledDocument

protected final StyledDocument getStyledDocument(JEditorPane e)
Gets the document associated with an editor pane.

Parameters:
e - the editor
Returns:
the document
Throws:
IllegalArgumentException - for the wrong document type

getStyledEditorKit

protected final StyledEditorKit getStyledEditorKit(JEditorPane e)
Gets the editor kit associated with an editor pane.

Parameters:
e - the editor pane
Returns:
the kit
Throws:
IllegalArgumentException - for the wrong document type

setCharacterAttributes

protected final void setCharacterAttributes(JEditorPane editor,
                                            AttributeSet attr,
                                            boolean replace)
Applies the given attributes to character content. If there is a selection, the attributes are applied to the selection range. If there is no selection, the attributes are applied to the input attribute set which defines the attributes for any new text that gets inserted.

Parameters:
editor - the editor
attr - the attributes
replace - if true, then replace the existing attributes first

setParagraphAttributes

protected final void setParagraphAttributes(JEditorPane editor,
                                            AttributeSet attr,
                                            boolean replace)
Applies the given attributes to paragraphs. If there is a selection, the attributes are applied to the paragraphs that intersect the selection. if there is no selection, the attributes are applied to the paragraph at the current caret position.

Parameters:
editor - the editor
attr - the attributes
replace - if true, replace the existing attributes first
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


StyledEditorKit.UnderlineAction (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class StyledEditorKit.UnderlineAction

java.lang.Object
    extended by javax.swing.AbstractAction
        extended by javax.swing.text.TextAction
            extended by javax.swing.text.StyledEditorKit.StyledTextAction
                extended by javax.swing.text.StyledEditorKit.UnderlineAction
All Implemented Interfaces:
Action, ActionListener, Cloneable, EventListener, Serializable
Enclosing class:
StyledEditorKit
public static class StyledEditorKit.UnderlineAction
extends StyledEditorKit.StyledTextAction

An action to toggle the underline attribute.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Field Summary
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SHORT_DESCRIPTION, SMALL_ICON
Constructor Summary
StyledEditorKit.UnderlineAction()
Constructs a new UnderlineAction.
Method Summary
 void actionPerformed(ActionEvent e)
Toggles the Underline attribute.
Methods inherited from class javax.swing.text.StyledEditorKit.StyledTextAction
getEditor, getStyledDocument, getStyledEditorKit, setCharacterAttributes, setParagraphAttributes
Methods inherited from class javax.swing.text.TextAction
augmentList, getFocusedComponent, getTextComponent
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

StyledEditorKit.UnderlineAction

public StyledEditorKit.UnderlineAction()
Constructs a new UnderlineAction.

Method Detail

actionPerformed

public void actionPerformed(ActionEvent e)
Toggles the Underline attribute.

Parameters:
e - the action event
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TabableView (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Interface TabableView

All Known Implementing Classes:
GlyphView, LabelView
public interface TabableView

Interface for Views that have size dependent upon tabs.

See Also:
TabExpander, LabelView, ParagraphView

Method Summary
float | getPartialSpan(int p0, int p1) Determines the span along the same axis as tab expansion for a portion of the view.
float | getTabbedSpan(float x, TabExpander e) Determines the desired span when using the given tab expansion implementation.

Method Detail

getTabbedSpan

public float getTabbedSpan(float x,
                           TabExpander e)
Determines the desired span when using the given tab expansion implementation. If a container calls this method, it will do so prior to the normal layout which would call getPreferredSpan. A view implementing this should give the same result in any subsequent calls to getPreferredSpan along the axis of tab expansion.

Parameters:
x - the position the view would be located at for the purpose of tab expansion >= 0.
e - how to expand the tabs when encountered.
Returns:
the desired span >= 0

getPartialSpan

public float getPartialSpan(int p0,
                            int p1)
Determines the span along the same axis as tab expansion for a portion of the view. This is intended for use by the TabExpander for cases where the tab expansion involves aligning the portion of text that doesn't have whitespace relative to the tab stop. There is therefore an assumption that the range given does not contain tabs.

Parameters:
p0 - the starting location in the text document >= 0
p1 - the ending location in the text document >= p0
Returns:
the span >= 0
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TabExpander (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Interface TabExpander

All Known Implementing Classes:
ParagraphView, PlainView, WrappedPlainView
public interface TabExpander

Simple interface to allow for different types of implementations of tab expansion.

Method Summary
 float nextTabStop(float x, int tabOffset)
Returns the next tab stop position given a reference position.

Method Detail

nextTabStop

public float nextTabStop(float x,
                         int tabOffset)
Returns the next tab stop position given a reference position. Values are expressed in points.

Parameters:
x - the position in points >= 0
tabOffset - the position within the text stream that the tab occurred at >= 0.
Returns:
the next tab stop >= 0
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TableView (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class TableView

java.lang.Object
    extended by javax.swing.text.View
        extended by javax.swing.text.CompositeView
            extended by javax.swing.text.BoxView
                extended by javax.swing.text.TableView
All Implemented Interfaces:
SwingConstants
public abstract class TableView
extends BoxView

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. The cell elements can have an arbitrary element structure under them, which will be built with the ViewFactory returned by the getViewFactory method.

    TABLE
      ROW
        CELL
        CELL
      ROW
        CELL
        CELL

This is implemented as a hierarchy of boxes, the table itself is a vertical box, the rows are horizontal boxes, and the cells are vertical boxes. The cells are allowed to span multiple columns and rows. By default, the table can be thought of as being formed over a grid (i.e. somewhat like one would find in gridbag layout), where table cells can request to span more than one grid cell. The default horizontal span of table cells will be based upon this grid, but can be changed by reimplementing the requested span of the cell (i.e. table cells can have independant spans if desired).

See Also:
View

Nested Class Summary
class | TableView.TableCell Deprecated. A table cell can now be any View implementation.
class | TableView.TableRow View of a row in a row-centric table.
Field Summary
Fields inherited from class javax.swing.text.View
BadBreakWeight, ExcellentBreakWeight, ForcedBreakWeight, GoodBreakWeight, X_AXIS, Y_AXIS
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
Constructor Summary
TableView(Element elem)
Constructs a TableView for the given element.
Method Summary
protected SizeRequirements | calculateMinorAxisRequirements(int axis, SizeRequirements r) Calculate the requirements for the minor axis.
protected TableView.TableCell | createTableCell(Element elem) Deprecated. Table cells can now be any arbitrary View implementation and should be produced by the ViewFactory rather than the table.
protected TableView.TableRow | createTableRow(Element elem) Creates a new table row.
protected void | forwardUpdate(DocumentEvent.ElementChange ec, DocumentEvent e, Shape a, ViewFactory f) Forwards the given DocumentEvent to the child views that need to be notified of the change to the model.
protected View | getViewAtPosition(int pos, Rectangle a) Fetches the child view that represents the given position in the model.
protected void | layoutColumns(int targetSpan, int[] offsets, int[] spans, SizeRequirements[] reqs) Layout the columns to fit within the given target span.
protected void | layoutMinorAxis(int targetSpan, int axis, int[] offsets, int[] spans) Perform layout for the minor axis of the box (i.e.
void | replace(int offset, int length, View[] views) Change the child views.
Methods inherited from class javax.swing.text.BoxView
baselineLayout, baselineRequirements, calculateMajorAxisRequirements, childAllocation, flipEastAndWestAtEnds, getAlignment, getAxis, getChildAllocation, getHeight, getMaximumSpan, getMinimumSpan, getOffset, getPreferredSpan, getResizeWeight, getSpan, getViewAtPoint, getWidth, isAfter, isAllocationValid, isBefore, isLayoutValid, layout, layoutChanged, layoutMajorAxis, modelToView, paint, paintChild, preferenceChanged, setAxis, setSize, viewToModel
Methods inherited from class javax.swing.text.CompositeView
getBottomInset, getInsideAllocation, getLeftInset, getNextEastWestVisualPositionFrom, getNextNorthSouthVisualPositionFrom, getNextVisualPositionFrom, getRightInset, getTopInset, getView, getViewCount, getViewIndex, getViewIndexAtPosition, loadChildren, modelToView, setInsets, setParagraphInsets, setParent
Methods inherited from class javax.swing.text.View
append, breakView, changedUpdate, createFragment, forwardUpdateToView, getAttributes, getBreakWeight, getContainer, getDocument, getElement, getEndOffset, getGraphics, getParent, getStartOffset, getToolTipText, getViewFactory, getViewIndex, insert, insertUpdate, isVisible, modelToView, remove, removeAll, removeUpdate, updateChildren, updateLayout, viewToModel
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

TableView

public TableView(Element elem)
Constructs a TableView for the given element.

Parameters:
elem - the element that this view is responsible for
Method Detail

createTableRow

protected TableView.TableRow createTableRow(Element elem)
Creates a new table row.

Parameters:
elem - an element
Returns:
the row

createTableCell

protected TableView.TableCell createTableCell(Element elem)
Deprecated. Table cells can now be any arbitrary View implementation and should be produced by the ViewFactory rather than the table.

Parameters:
elem - an element
Returns:
the cell

forwardUpdate

protected void forwardUpdate(DocumentEvent.ElementChange ec,
                             DocumentEvent e,
                             Shape a,
                             ViewFactory f)
Description copied from class: BoxView
Forwards the given DocumentEvent to the child views that need to be notified of the change to the model. If a child changed its requirements and the allocation was valid prior to forwarding the portion of the box from the starting child to the end of the box will be repainted.

Overrides:
forwardUpdate in class BoxView
Parameters:
ec - changes to the element this view is responsible for (may be null if there were no changes)
e - the change information from the associated document
a - the current allocation of the view
f - the factory to use to rebuild if the view has children
See Also:
View.insertUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory),
View.removeUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory),
View.changedUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory)

replace

public void replace(int offset,
                    int length,
                    View[] views)
Change the child views. This is implemented to provide the superclass behavior and invalidate the grid so that rows and columns will be recalculated.

Overrides:
replace in class BoxView
Parameters:
offset - the starting index into the child views to insert the new views; this should be a value >= 0 and <= getViewCount
length - the number of existing child views to remove; This should be a value >= 0 and <= (getViewCount() - offset)
views - the child views to add; this value can be nullto indicate no children are being added (useful to remove)

layoutColumns

protected void layoutColumns(int targetSpan,
                             int[] offsets,
                             int[] spans,
                             SizeRequirements[] reqs)
Layout the columns to fit within the given target span.

Parameters:
targetSpan - the given span for total of all the table columns.
reqs - the requirements desired for each column. This is the column maximum of the cells minimum, preferred, and maximum requested span.
spans - the return value of how much to allocated to each column.
offsets - the return value of the offset from the origin for each column.
Returns:
the offset from the origin and the span for each column in the offsets and spans parameters

layoutMinorAxis

protected void layoutMinorAxis(int targetSpan,
                               int axis,
                               int[] offsets,
                               int[] spans)
Perform layout for the minor axis of the box (i.e. the axis orthoginal to the axis that it represents). The results of the layout should be placed in the given arrays which represent the allocations to the children along the minor axis. This is called by the superclass whenever the layout needs to be updated along the minor axis.

This is implemented to call the layoutColumns method, and then forward to the superclass to actually carry out the layout of the tables rows.

Overrides:
layoutMinorAxis in class BoxView
Parameters:
targetSpan - the total span given to the view, which whould be used to layout the children.
axis - the axis being layed out.
offsets - the offsets from the origin of the view for each of the child views. This is a return value and is filled in by the implementation of this method.
spans - the span of each child view. This is a return value and is filled in by the implementation of this method.
Returns:
the offset and span for each child view in the offsets and spans parameters

calculateMinorAxisRequirements

protected SizeRequirements calculateMinorAxisRequirements(int axis,
                                                          SizeRequirements r)
Calculate the requirements for the minor axis. This is called by the superclass whenever the requirements need to be updated (i.e. a preferenceChanged was messaged through this view).

This is implemented to calculate the requirements as the sum of the requirements of the columns.

Overrides:
calculateMinorAxisRequirements in class BoxView
Parameters:
axis - the axis being studied
r - the SizeRequirements object; if null one will be created
Returns:
the newly initialized SizeRequirements object
See Also:
SizeRequirements

getViewAtPosition

protected View getViewAtPosition(int pos,
                                 Rectangle a)
Fetches the child view that represents the given position in the model. This is implemented to walk through the children looking for a range that contains the given position. In this view the children do not necessarily have a one to one mapping with the child elements.

Overrides:
getViewAtPosition in class CompositeView
Parameters:
pos - the search position >= 0
a - the allocation to the table on entry, and the allocation of the view containing the position on exit
Returns:
the view representing the given position, or null if there isn't one
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TableView.TableCell (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class TableView.TableCell

java.lang.Object
    extended by javax.swing.text.View
        extended by javax.swing.text.CompositeView
            extended by javax.swing.text.BoxView
                extended by javax.swing.text.TableView.TableCell
All Implemented Interfaces:
SwingConstants, javax.swing.text.TableView.GridCell
Enclosing class:
TableView
Deprecated. A table cell can now be any View implementation.

public class TableView.TableCell
extends BoxView
implements javax.swing.text.TableView.GridCell

Field Summary
Fields inherited from class javax.swing.text.View
BadBreakWeight, ExcellentBreakWeight, ForcedBreakWeight, GoodBreakWeight, X_AXIS, Y_AXIS
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
Constructor Summary
TableView.TableCell(Element elem)
Deprecated. Constructs a TableCell for the given element.
Method Summary
int | getColumnCount() Deprecated. Gets the number of columns this cell spans (e.g.
int | getGridColumn() Deprecated. Gets the column of the grid location
int | getGridRow() Deprecated. Gets the row of the grid location
int | getRowCount() Deprecated. Gets the number of rows this cell spans (that is, the grid height).
void | setGridLocation(int row, int col) Deprecated. Sets the grid location.
Methods inherited from class javax.swing.text.BoxView
baselineLayout, baselineRequirements, calculateMajorAxisRequirements, calculateMinorAxisRequirements, childAllocation, flipEastAndWestAtEnds, forwardUpdate, getAlignment, getAxis, getChildAllocation, getHeight, getMaximumSpan, getMinimumSpan, getOffset, getPreferredSpan, getResizeWeight, getSpan, getViewAtPoint, getWidth, isAfter, isAllocationValid, isBefore, isLayoutValid, layout, layoutChanged, layoutMajorAxis, layoutMinorAxis, modelToView, paint, paintChild, preferenceChanged, replace, setAxis, setSize, viewToModel
Methods inherited from class javax.swing.text.CompositeView
getBottomInset, getInsideAllocation, getLeftInset, getNextEastWestVisualPositionFrom, getNextNorthSouthVisualPositionFrom, getNextVisualPositionFrom, getRightInset, getTopInset, getView, getViewAtPosition, getViewCount, getViewIndex, getViewIndexAtPosition, loadChildren, modelToView, setInsets, setParagraphInsets, setParent
Methods inherited from class javax.swing.text.View
append, breakView, changedUpdate, createFragment, forwardUpdateToView, getAttributes, getBreakWeight, getContainer, getDocument, getElement, getEndOffset, getGraphics, getParent, getStartOffset, getToolTipText, getViewFactory, getViewIndex, insert, insertUpdate, isVisible, modelToView, remove, removeAll, removeUpdate, updateChildren, updateLayout, viewToModel
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

TableView.TableCell

public TableView.TableCell(Element elem)
Deprecated.
Constructs a TableCell for the given element.

Parameters:
elem - the element that this view is responsible for
Method Detail

getColumnCount

public int getColumnCount()
Deprecated.
Gets the number of columns this cell spans (e.g. the grid width).

Specified by:
getColumnCount in interface javax.swing.text.TableView.GridCell
Returns:
the number of columns

getRowCount

public int getRowCount()
Deprecated.
Gets the number of rows this cell spans (that is, the grid height).

Specified by:
getRowCount in interface javax.swing.text.TableView.GridCell
Returns:
the number of rows

setGridLocation

public void setGridLocation(int row,
                            int col)
Deprecated.
Sets the grid location.

Specified by:
setGridLocation in interface javax.swing.text.TableView.GridCell
Parameters:
row - the row >= 0
col - the column >= 0

getGridRow

public int getGridRow()
Deprecated.
Gets the row of the grid location

Specified by:
getGridRow in interface javax.swing.text.TableView.GridCell

getGridColumn

public int getGridColumn()
Deprecated.
Gets the column of the grid location

Specified by:
getGridColumn in interface javax.swing.text.TableView.GridCell
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TableView.TableRow (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class TableView.TableRow

java.lang.Object
    extended by javax.swing.text.View
        extended by javax.swing.text.CompositeView
            extended by javax.swing.text.BoxView
                extended by javax.swing.text.TableView.TableRow
All Implemented Interfaces:
SwingConstants
Enclosing class:
TableView
public class TableView.TableRow
extends BoxView

View of a row in a row-centric table.

Field Summary
Fields inherited from class javax.swing.text.View
BadBreakWeight, ExcellentBreakWeight, ForcedBreakWeight, GoodBreakWeight, X_AXIS, Y_AXIS
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
Constructor Summary
TableView.TableRow(Element elem)
Constructs a TableView for the given element.
Method Summary
int | getResizeWeight(int axis) Determines the resizability of the view along the given axis.
protected View | getViewAtPosition(int pos, Rectangle a) Fetches the child view that represents the given position in the model.
protected void | layoutMajorAxis(int targetSpan, int axis, int[] offsets, int[] spans) Perform layout for the major axis of the box (i.e.
protected void | layoutMinorAxis(int targetSpan, int axis, int[] offsets, int[] spans) Perform layout for the minor axis of the box (i.e.
void | replace(int offset, int length, View[] views) Change the child views.
Methods inherited from class javax.swing.text.BoxView
baselineLayout, baselineRequirements, calculateMajorAxisRequirements, calculateMinorAxisRequirements, childAllocation, flipEastAndWestAtEnds, forwardUpdate, getAlignment, getAxis, getChildAllocation, getHeight, getMaximumSpan, getMinimumSpan, getOffset, getPreferredSpan, getSpan, getViewAtPoint, getWidth, isAfter, isAllocationValid, isBefore, isLayoutValid, layout, layoutChanged, modelToView, paint, paintChild, preferenceChanged, setAxis, setSize, viewToModel
Methods inherited from class javax.swing.text.CompositeView
getBottomInset, getInsideAllocation, getLeftInset, getNextEastWestVisualPositionFrom, getNextNorthSouthVisualPositionFrom, getNextVisualPositionFrom, getRightInset, getTopInset, getView, getViewCount, getViewIndex, getViewIndexAtPosition, loadChildren, modelToView, setInsets, setParagraphInsets, setParent
Methods inherited from class javax.swing.text.View
append, breakView, changedUpdate, createFragment, forwardUpdateToView, getAttributes, getBreakWeight, getContainer, getDocument, getElement, getEndOffset, getGraphics, getParent, getStartOffset, getToolTipText, getViewFactory, getViewIndex, insert, insertUpdate, isVisible, modelToView, remove, removeAll, removeUpdate, updateChildren, updateLayout, viewToModel
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

TableView.TableRow

public TableView.TableRow(Element elem)
Constructs a TableView for the given element.

Parameters:
elem - the element that this view is responsible for
Method Detail

replace

public void replace(int offset,
                    int length,
                    View[] views)
Change the child views. This is implemented to provide the superclass behavior and invalidate the grid so that rows and columns will be recalculated.

Overrides:
replace in class BoxView
Parameters:
offset - the starting index into the child views to insert the new views; this should be a value >= 0 and <= getViewCount
length - the number of existing child views to remove; This should be a value >= 0 and <= (getViewCount() - offset)
views - the child views to add; this value can be nullto indicate no children are being added (useful to remove)

layoutMajorAxis

protected void layoutMajorAxis(int targetSpan,
                               int axis,
                               int[] offsets,
                               int[] spans)
Perform layout for the major axis of the box (i.e. the axis that it represents). The results of the layout should be placed in the given arrays which represent the allocations to the children along the major axis.

This is re-implemented to give each child the span of the column width for the table, and to give cells that span multiple columns the multi-column span.

Overrides:
layoutMajorAxis in class BoxView
Parameters:
targetSpan - the total span given to the view, which whould be used to layout the children.
axis - the axis being layed out.
offsets - the offsets from the origin of the view for each of the child views. This is a return value and is filled in by the implementation of this method.
spans - the span of each child view. This is a return value and is filled in by the implementation of this method.
Returns:
the offset and span for each child view in the offsets and spans parameters

layoutMinorAxis

protected void layoutMinorAxis(int targetSpan,
                               int axis,
                               int[] offsets,
                               int[] spans)
Perform layout for the minor axis of the box (i.e. the axis orthoginal to the axis that it represents). The results of the layout should be placed in the given arrays which represent the allocations to the children along the minor axis. This is called by the superclass whenever the layout needs to be updated along the minor axis.

This is implemented to delegate to the superclass, then adjust the span for any cell that spans multiple rows.

Overrides:
layoutMinorAxis in class BoxView
Parameters:
targetSpan - the total span given to the view, which whould be used to layout the children.
axis - the axis being layed out.
offsets - the offsets from the origin of the view for each of the child views. This is a return value and is filled in by the implementation of this method.
spans - the span of each child view. This is a return value and is filled in by the implementation of this method.
Returns:
the offset and span for each child view in the offsets and spans parameters

getResizeWeight

public int getResizeWeight(int axis)
Determines the resizability of the view along the given axis. A value of 0 or less is not resizable.

Overrides:
getResizeWeight in class BoxView
Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
Returns:
the resize weight
Throws:
IllegalArgumentException - for an invalid axis

getViewAtPosition

protected View getViewAtPosition(int pos,
                                 Rectangle a)
Fetches the child view that represents the given position in the model. This is implemented to walk through the children looking for a range that contains the given position. In this view the children do not necessarily have a one to one mapping with the child elements.

Overrides:
getViewAtPosition in class CompositeView
Parameters:
pos - the search position >= 0
a - the allocation to the table on entry, and the allocation of the view containing the position on exit
Returns:
the view representing the given position, or null if there isn't one
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TabSet (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class TabSet

java.lang.Object
    extended by javax.swing.text.TabSet
All Implemented Interfaces:
Serializable
public class TabSet
extends Object
implements Serializable

A TabSet is comprised of many TabStops. It offers methods for locating the closest TabStop to a given position and finding all the potential TabStops. It is also immutable.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Constructor Summary
TabSet(TabStop[] tabs)
Creates and returns an instance of TabSet.
Method Summary
TabStop | getTab(int index) Returns the TabStop at index index.
TabStop | getTabAfter(float location) Returns the Tab instance after location.
int | getTabCount() Returns the number of Tab instances the receiver contains.
int | getTabIndex(TabStop tab)
int | getTabIndexAfter(float location) Returns the index of the Tab to be used after location.
String | toString() Returns the string representation of the set of tabs.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

TabSet

public TabSet(TabStop[] tabs)
Creates and returns an instance of TabSet. The array of Tabs passed in must be sorted in ascending order.

Method Detail

getTabCount

public int getTabCount()
Returns the number of Tab instances the receiver contains.

getTab

public TabStop getTab(int index)
Returns the TabStop at index index. This will throw an IllegalArgumentException if index is outside the range of tabs.

getTabAfter

public TabStop getTabAfter(float location)
Returns the Tab instance after location. This will return null if there are no tabs after location.

getTabIndex

public int getTabIndex(TabStop tab)
Returns:
the index of the TabStop tab, or -1 if tab is not contained in the receiver.

getTabIndexAfter

public int getTabIndexAfter(float location)
Returns the index of the Tab to be used after location. This will return -1 if there are no tabs after location.

toString

public String toString()
Returns the string representation of the set of tabs.

Overrides:
toString in class Object
Returns:
a string representation of the object.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TabStop (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class TabStop

java.lang.Object
    extended by javax.swing.text.TabStop
All Implemented Interfaces:
Serializable
public class TabStop
extends Object
implements Serializable

This class encapsulates a single tab stop (basically as tab stops are thought of by RTF). A tab stop is at a specified distance from the left margin, aligns text in a specified way, and has a specified leader. TabStops are immutable, and usually contained in TabSets.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Field Summary
static int | ALIGN_BAR
static int | ALIGN_CENTER Characters following tab are positioned such that all following characters up to next tab/newline are centered around the tabs location.
static int | ALIGN_DECIMAL Characters following tab are aligned such that next decimal/tab/newline is at the tab location, very similar to RIGHT_TAB, just includes decimal as additional character to look for.
static int | ALIGN_LEFT Character following tab is positioned at location.
static int | ALIGN_RIGHT Characters following tab are positioned such that all following characters up to next tab/newline end at location.
static int | LEAD_DOTS
static int | LEAD_EQUALS
static int | LEAD_HYPHENS
static int | LEAD_NONE
static int | LEAD_THICKLINE
static int | LEAD_UNDERLINE
Constructor Summary
TabStop(float pos)
Creates a tab at position pos with a default alignment and default leader.
TabStop(float pos, int align, int leader)
Creates a tab with the specified position pos, alignment align and leader leader.
Method Summary
boolean | equals(Object other) Returns true if the tabs are equal.
int | getAlignment() Returns the alignment, as an integer, of the tab.
int | getLeader() Returns the leader of the tab.
float | getPosition() Returns the position, as a float, of the tab.
int | hashCode() Returns the hashCode for the object.
String | toString() Returns a string representation of the object.
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait

Field Detail

ALIGN_LEFT

public static final int ALIGN_LEFT
Character following tab is positioned at location.

See Also:
Constant Field Values

ALIGN_RIGHT

public static final int ALIGN_RIGHT
Characters following tab are positioned such that all following characters up to next tab/newline end at location.

See Also:
Constant Field Values

ALIGN_CENTER

public static final int ALIGN_CENTER
Characters following tab are positioned such that all following characters up to next tab/newline are centered around the tabs location.

See Also:
Constant Field Values

ALIGN_DECIMAL

public static final int ALIGN_DECIMAL
Characters following tab are aligned such that next decimal/tab/newline is at the tab location, very similar to RIGHT_TAB, just includes decimal as additional character to look for.

See Also:
Constant Field Values

ALIGN_BAR

public static final int ALIGN_BAR
See Also:
Constant Field Values

LEAD_NONE

public static final int LEAD_NONE
See Also:
Constant Field Values

LEAD_DOTS

public static final int LEAD_DOTS
See Also:
Constant Field Values

LEAD_HYPHENS

public static final int LEAD_HYPHENS
See Also:
Constant Field Values

LEAD_UNDERLINE

public static final int LEAD_UNDERLINE
See Also:
Constant Field Values

LEAD_THICKLINE

public static final int LEAD_THICKLINE
See Also:
Constant Field Values

LEAD_EQUALS

public static final int LEAD_EQUALS
See Also:
Constant Field Values
Constructor Detail

TabStop

public TabStop(float pos)
Creates a tab at position pos with a default alignment and default leader.

TabStop

public TabStop(float pos,
               int align,
               int leader)
Creates a tab with the specified position pos, alignment align and leader leader.

Method Detail

getPosition

public float getPosition()
Returns the position, as a float, of the tab.

Returns:
the position of the tab

getAlignment

public int getAlignment()
Returns the alignment, as an integer, of the tab.

Returns:
the alignment of the tab

getLeader

public int getLeader()
Returns the leader of the tab.

Returns:
the leader of the tab

equals

public boolean equals(Object other)
Returns true if the tabs are equal.

Overrides:
equals in class Object
Parameters:
other - the reference object with which to compare.
Returns:
true if the tabs are equal, otherwise false
See Also:
Object.hashCode(), Hashtable

hashCode

public int hashCode()
Returns the hashCode for the object. This must be defined here to ensure 100% pure.

Overrides:
hashCode in class Object
Returns:
the hashCode for the object
See Also:
Object.equals(java.lang.Object), Hashtable

toString

public String toString()
Description copied from class: Object
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

 getClass().getName() + '@' + Integer.toHexString(hashCode())

Overrides:
toString in class Object
Returns:
a string representation of the object.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TextAction (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class TextAction

java.lang.Object
    extended by javax.swing.AbstractAction
        extended by javax.swing.text.TextAction
All Implemented Interfaces:
Action, ActionListener, Cloneable, EventListener, Serializable
Direct Known Subclasses:
DefaultEditorKit.BeepAction, DefaultEditorKit.CopyAction, DefaultEditorKit.CutAction, DefaultEditorKit.DefaultKeyTypedAction, DefaultEditorKit.InsertBreakAction, DefaultEditorKit.InsertContentAction, DefaultEditorKit.InsertTabAction, DefaultEditorKit.PasteAction, StyledEditorKit.StyledTextAction
public abstract class TextAction
extends AbstractAction

An Action implementation useful for key bindings that are shared across a number of different text components. Because the action is shared, it must have a way of getting it's target to act upon. This class provides support to try and find a text component to operate on. The preferred way of getting the component to act upon is through the ActionEvent that is received. If the Object returned by getSource can be narrowed to a text component, it will be used. If the action event is null or can't be narrowed, the last focused text component is tried. This is determined by being used in conjunction with a JTextController which arranges to share that information with a TextAction.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Field Summary
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SHORT_DESCRIPTION, SMALL_ICON
Constructor Summary
TextAction(String name)
Creates a new JTextAction object.
Method Summary
static Action[] | augmentList(Action[] list1, Action[] list2) Takes one list of commands and augments it with another list of commands.
protected JTextComponent | getFocusedComponent() Fetches the text component that currently has focus.
protected JTextComponent | getTextComponent(ActionEvent e) Determines the component to use for the action.
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Methods inherited from interface java.awt.event.ActionListener
actionPerformed

Constructor Detail

TextAction

public TextAction(String name)
Creates a new JTextAction object.

Parameters:
name - the name of the action
Method Detail

getTextComponent

protected final JTextComponent getTextComponent(ActionEvent e)
Determines the component to use for the action. This if fetched from the source of the ActionEvent if it's not null and can be narrowed. Otherwise, the last focused component is used.

Parameters:
e - the ActionEvent
Returns:
the component

augmentList

public static final Action[] augmentList(Action[] list1,
                                         Action[] list2)
Takes one list of commands and augments it with another list of commands. The second list is considered to be higher priority than the first list and commands with the same name will both lists will only have the dominate command found in the second list in the returned list.

Parameters:
list1 - the first list, may be empty but not null
list2 - the second list, may be empty but not null
Returns:
the augmented list

getFocusedComponent

protected final JTextComponent getFocusedComponent()
Fetches the text component that currently has focus. This allows actions to be shared across text components which is useful for key-bindings where a large set of actions are defined, but generally used the same way across many different components.

Returns:
the component
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Utilities (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class Utilities

java.lang.Object
    extended by javax.swing.text.Utilities
public class Utilities
extends Object

A collection of methods to deal with various text related activities.

Constructor Summary
Utilities()
Method Summary
static int | drawTabbedText(Segment s, int x, int y, Graphics g, TabExpander e, int startOffset) Draws the given text, expanding any tabs that are contained using the given tab expansion technique.
static int | getBreakLocation(Segment s, FontMetrics metrics, int x0, int x, TabExpander e, int startOffset) Determine where to break the given text to fit within the the given span.
static int | getNextWord(JTextComponent c, int offs) Determines the start of the next word for the given location.
static Element | getParagraphElement(JTextComponent c, int offs) Determines the element to use for a paragraph/line.
static int | getPositionAbove(JTextComponent c, int offs, int x) Determines the position in the model that is closest to the given view location in the row above.
static int | getPositionBelow(JTextComponent c, int offs, int x) Determines the position in the model that is closest to the given view location in the row below.
static int | getPreviousWord(JTextComponent c, int offs) Determine the start of the prev word for the given location.
static int | getRowEnd(JTextComponent c, int offs) Determines the ending row model position of the row that contains the specified model position.
static int | getRowStart(JTextComponent c, int offs) Determines the starting row model position of the row that contains the specified model position.
static int | getTabbedTextOffset(Segment s, FontMetrics metrics, int x0, int x, TabExpander e, int startOffset) Determines the relative offset into the given text that best represents the given span in the view coordinate system.
static int | getTabbedTextOffset(Segment s, FontMetrics metrics, int x0, int x, TabExpander e, int startOffset, boolean round)
static int | getTabbedTextWidth(Segment s, FontMetrics metrics, int x, TabExpander e, int startOffset) Determines the width of the given segment of text taking tabs into consideration.
static int | getWordEnd(JTextComponent c, int offs) Determines the end of a word for the given location.
static int | getWordStart(JTextComponent c, int offs) Determines the start of a word for the given model location.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

Utilities

public Utilities()
Method Detail

drawTabbedText

public static final int drawTabbedText(Segment s,
                                       int x,
                                       int y,
                                       Graphics g,
                                       TabExpander e,
                                       int startOffset)
Draws the given text, expanding any tabs that are contained using the given tab expansion technique. This particular implementation renders in a 1.1 style coordinate system where ints are used and 72dpi is assumed.

Parameters:
s - the source of the text
x - the X origin >= 0
y - the Y origin >= 0
g - the graphics context
e - how to expand the tabs. If this value is null, tabs will be expanded as a space character.
startOffset - starting offset of the text in the document >= 0
Returns:
the X location at the end of the rendered text

getTabbedTextWidth

public static final int getTabbedTextWidth(Segment s,
                                           FontMetrics metrics,
                                           int x,
                                           TabExpander e,
                                           int startOffset)
Determines the width of the given segment of text taking tabs into consideration. This is implemented in a 1.1 style coordinate system where ints are used and 72dpi is assumed.

Parameters:
s - the source of the text
metrics - the font metrics to use for the calculation
x - the X origin >= 0
e - how to expand the tabs. If this value is null, tabs will be expanded as a space character.
startOffset - starting offset of the text in the document >= 0
Returns:
the width of the text

getTabbedTextOffset

public static final int getTabbedTextOffset(Segment s,
                                            FontMetrics metrics,
                                            int x0,
                                            int x,
                                            TabExpander e,
                                            int startOffset)
Determines the relative offset into the given text that best represents the given span in the view coordinate system. This is implemented in a 1.1 style coordinate system where ints are used and 72dpi is assumed.

Parameters:
s - the source of the text
metrics - the font metrics to use for the calculation
x0 - the starting view location representing the start of the given text >= 0.
x - the target view location to translate to an offset into the text >= 0.
e - how to expand the tabs. If this value is null, tabs will be expanded as a space character.
startOffset - starting offset of the text in the document >= 0
Returns:
the offset into the text >= 0

getTabbedTextOffset

public static final int getTabbedTextOffset(Segment s,
                                            FontMetrics metrics,
                                            int x0,
                                            int x,
                                            TabExpander e,
                                            int startOffset,
                                            boolean round)

getBreakLocation

public static final int getBreakLocation(Segment s,
                                         FontMetrics metrics,
                                         int x0,
                                         int x,
                                         TabExpander e,
                                         int startOffset)
Determine where to break the given text to fit within the the given span. This tries to find a whitespace boundary.

Parameters:
s - the source of the text
metrics - the font metrics to use for the calculation
x0 - the starting view location representing the start of the given text.
x - the target view location to translate to an offset into the text.
e - how to expand the tabs. If this value is null, tabs will be expanded as a space character.
startOffset - starting offset in the document of the text
Returns:
the offset into the given text

getRowStart

public static final int getRowStart(JTextComponent c,
                                    int offs)
                             throws BadLocationException
Determines the starting row model position of the row that contains the specified model position. The component given must have a size to compute the result. If the component doesn't have a size a value of -1 will be returned.

Parameters:
c - the editor
offs - the offset in the document >= 0
Returns:
the position >= 0 if the request can be computed, otherwise a value of -1 will be returned.
Throws:
BadLocationException - if the offset is out of range

getRowEnd

public static final int getRowEnd(JTextComponent c,
                                  int offs)
                           throws BadLocationException
Determines the ending row model position of the row that contains the specified model position. The component given must have a size to compute the result. If the component doesn't have a size a value of -1 will be returned.

Parameters:
c - the editor
offs - the offset in the document >= 0
Returns:
the position >= 0 if the request can be computed, otherwise a value of -1 will be returned.
Throws:
BadLocationException - if the offset is out of range

getPositionAbove

public static final int getPositionAbove(JTextComponent c,
                                         int offs,
                                         int x)
                                  throws BadLocationException
Determines the position in the model that is closest to the given view location in the row above. The component given must have a size to compute the result. If the component doesn't have a size a value of -1 will be returned.

Parameters:
c - the editor
offs - the offset in the document >= 0
x - the X coordinate >= 0
Returns:
the position >= 0 if the request can be computed, otherwise a value of -1 will be returned.
Throws:
BadLocationException - if the offset is out of range

getPositionBelow

public static final int getPositionBelow(JTextComponent c,
                                         int offs,
                                         int x)
                                  throws BadLocationException
Determines the position in the model that is closest to the given view location in the row below. The component given must have a size to compute the result. If the component doesn't have a size a value of -1 will be returned.

Parameters:
c - the editor
offs - the offset in the document >= 0
x - the X coordinate >= 0
Returns:
the position >= 0 if the request can be computed, otherwise a value of -1 will be returned.
Throws:
BadLocationException - if the offset is out of range

getWordStart

public static final int getWordStart(JTextComponent c,
                                     int offs)
                              throws BadLocationException
Determines the start of a word for the given model location. Uses BreakIterator.getWordInstance() to actually get the words.

Parameters:
c - the editor
offs - the offset in the document >= 0
Returns:
the location in the model of the word start >= 0
Throws:
BadLocationException - if the offset is out of range

getWordEnd

public static final int getWordEnd(JTextComponent c,
                                   int offs)
                            throws BadLocationException
Determines the end of a word for the given location. Uses BreakIterator.getWordInstance() to actually get the words.

Parameters:
c - the editor
offs - the offset in the document >= 0
Returns:
the location in the model of the word end >= 0
Throws:
BadLocationException - if the offset is out of range

getNextWord

public static final int getNextWord(JTextComponent c,
                                    int offs)
                             throws BadLocationException
Determines the start of the next word for the given location. Uses BreakIterator.getWordInstance() to actually get the words.

Parameters:
c - the editor
offs - the offset in the document >= 0
Returns:
the location in the model of the word start >= 0
Throws:
BadLocationException - if the offset is out of range

getPreviousWord

public static final int getPreviousWord(JTextComponent c,
                                        int offs)
                                 throws BadLocationException
Determine the start of the prev word for the given location. Uses BreakIterator.getWordInstance() to actually get the words.

Parameters:
c - the editor
offs - the offset in the document >= 0
Returns:
the location in the model of the word start >= 0
Throws:
BadLocationException - if the offset is out of range

getParagraphElement

public static final Element getParagraphElement(JTextComponent c,
                                                int offs)
Determines the element to use for a paragraph/line.

Parameters:
c - the editor
offs - the starting offset in the document >= 0
Returns:
the element
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


View (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class View

java.lang.Object
    extended by javax.swing.text.View
All Implemented Interfaces:
SwingConstants
Direct Known Subclasses:
AsyncBoxView, ComponentView, CompositeView, GlyphView, IconView, ImageView, PlainView
public abstract class View
extends Object
implements SwingConstants

A very important part of the text package is the View class. As the name suggests it represents a view of the text model, or a piece of the text model. It is this class that is responsible for the look of the text component. The view is not intended to be some completely new thing that one must learn, but rather is much like a lightweight component. In fact, the original View implementation was a lightweight component. There were several reasons why the Component implementation was abandoned in favor of an alternative.

  1. There was barely time to get the lightweight component support in the 1.1 version of the JDK. There simply wasn't time to lighten up the component further to where it would need to be to be used for text purposes. The additions made to JComponent increased the memory consumption, and as it currently stands its much too heavy for representing text.

  2. The layout semantics aren't quite right for text, and changing the current layout semantics of component might break existing applications.

  3. The component api uses integers, but in 1.2 one can use floating point device independent coordinates. An api that works in both 1.1 and 1.2 would be convenient for minimizing transition difficulties. The View class uses the Shape interface and float arguments to enable View implementations for the Java 2 platform v1.2 and later while still functioning in the older 1.1 JDK.

By default, a view is very light. It contains a reference to the parent view from which it can fetch many things without holding state, and it contains a reference to a portion of the model (Element). A view does not have to exactly represent an element in the model, that is simply a typical and therefore convenient mapping. A view can alternatively maintain a couple of Position objects to maintain its location in the model (i.e. represent a fragment of an element). This is typically the result of formatting where views have been broken down into pieces. The convenience of a substantial relationship to the element makes it easier to build factories to produce the views, and makes it easier to keep track of the view pieces as the model is changed and the view must be changed to reflect the model. Simple views therefore represent an Element directly and complex views do not.

A view has the following responsibilities:

Participate in layout.

The view has a setSize method which is like doLayout and setSize in Component combined. The view has a preferenceChanged method which is like invalidate in Component except that one can invalidate just one axis and the child requesting the change is identified.

A View expresses the size that it would like to be in terms of three values, a minimum, a preferred, and a maximum span. Layout in a view is can be done independently upon each axis. For a properly functioning View implementation, the minimum span will be <= the preferred span which in turn will be <= the maximum span.

The above text describes this graphic.

The minimum set of methods for layout are:

  • getMinimumSpan
  • getPreferredSpan
  • getMaximumSpan
  • getAlignment
  • preferenceChanged
  • setSize

The setSize method should be prepared to be called a number of times (i.e. It may be called even if the size didn't change). The setSize method is generally called to make sure the View layout is complete prior to trying to perform an operation on it that requires an up-to-date layout. A view's size should always be set to a value within the minimum and maximum span specified by that view. Additionally, the view must always call the preferenceChanged method on the parent if it has changed the values for the layout it would like, and expects the parent to honor. The parent View is not required to recognize a change until the preferenceChanged has been sent. This allows parent View implementations to cache the child requirements if desired. The calling sequence looks something like the following:

Sample calling sequence between parent view and child view: setSize, getMinimum, getPreferred, getMaximum, getAlignment, setSize

The exact calling sequence is up to the layout functionality of the parent view (if the view has any children). The view may collect the preferences of the children prior to determining what it will give each child, or it might iteratively update the children one at a time.

Render a portion of the model.

This is done in the paint method, which is pretty much like a component paint method. Views are expected to potentially populate a fairly large tree. A View has the following semantics for rendering:

  • The view gets its allocation from the parent at paint time, so it must be prepared to redo layout if the allocated area is different from what it is prepared to deal with.
  • The coordinate system is the same as the hosting Component (i.e. the Component returned by the getContainer method). This means a child view lives in the same coordinate system as the parent view unless the parent has explicitly changed the coordinate system. To schedule itself to be repainted a view can call repaint on the hosting Component.
  • The default is to not clip the children. It is more efficient to allow a view to clip only if it really feels it needs clipping.
  • The Graphics object given is not initialized in any way. A view should set any settings needed.
  • A View is inherently transparent. While a view may render into its entire allocation, typically a view does not. Rendering is performed by tranversing down the tree of View implementations. Each View is responsible for rendering its children. This behavior is depended upon for thread safety. While view implementations do not necessarily have to be implemented with thread safety in mind, other view implementations that do make use of concurrency can depend upon a tree traversal to guarantee thread safety.
  • The order of views relative to the model is up to the implementation. Although child views will typically be arranged in the same order that they occur in the model, they may be visually arranged in an entirely different order. View implementations may have Z-Order associated with them if the children are overlapping.

The methods for rendering are:

  • paint

Translate between the model and view coordinate systems.

Because the view objects are produced from a factory and therefore cannot necessarily be counted upon to be in a particular pattern, one must be able to perform translation to properly locate spatial representation of the model. The methods for doing this are:

  • modelToView
  • viewToModel
  • getDocument
  • getElement
  • getStartOffset
  • getEndOffset

The layout must be valid prior to attempting to make the translation. The translation is not valid, and must not be attempted while changes are being broadcasted from the model via a DocumentEvent.

Respond to changes from the model.

If the overall view is represented by many pieces (which is the best situation if one want to be able to change the view and write the least amount of new code), it would be impractical to have a huge number of DocumentListeners. If each view listened to the model, only a few would actually be interested in the changes broadcasted at any given time. Since the model has no knowledge of views, it has no way to filter the broadcast of change information. The view hierarchy itself is instead responsible for propagating the change information. At any level in the view hierarchy, that view knows enough about its children to best distribute the change information further. Changes are therefore broadcasted starting from the root of the view hierarchy. The methods for doing this are:

  • insertUpdate
  • removeUpdate
  • changedUpdate

Field Summary
static int | BadBreakWeight The weight to indicate a view is a bad break opportunity for the purpose of formatting.
static int | ExcellentBreakWeight The weight to indicate a view supports breaking, and this represents a very attractive place to break.
static int | ForcedBreakWeight The weight to indicate a view supports breaking, and must be broken to be represented properly when placed in a view that formats its children by breaking them.
static int | GoodBreakWeight The weight to indicate a view supports breaking, but better opportunities probably exist.
static int | X_AXIS Axis for format/break operations.
static int | Y_AXIS Axis for format/break operations.
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
Constructor Summary
View(Element elem)
Creates a new View object.
Method Summary
void | append(View v) Appends a single child view.
View | breakView(int axis, int offset, float pos, float len) Tries to break this view on the given axis.
void | changedUpdate(DocumentEvent e, Shape a, ViewFactory f) Gives notification from the document that attributes were changed in a location that this view is responsible for.
View | createFragment(int p0, int p1) Creates a view that represents a portion of the element.
protected void | forwardUpdate(DocumentEvent.ElementChange ec, DocumentEvent e, Shape a, ViewFactory f) Forwards the given DocumentEvent to the child views that need to be notified of the change to the model.
protected void | forwardUpdateToView(View v, DocumentEvent e, Shape a, ViewFactory f) Forwards the DocumentEvent to the give child view.
float | getAlignment(int axis) Determines the desired alignment for this view along an axis.
AttributeSet | getAttributes() Fetches the attributes to use when rendering.
int | getBreakWeight(int axis, float pos, float len) Determines how attractive a break opportunity in this view is.
Shape | getChildAllocation(int index, Shape a) Fetches the allocation for the given child view.
Container | getContainer() Fetches the container hosting the view.
Document | getDocument() Fetches the model associated with the view.
Element | getElement() Fetches the structural portion of the subject that this view is mapped to.
int | getEndOffset() Fetches the portion of the model for which this view is responsible.
Graphics | getGraphics() Fetch a Graphics for rendering.
float | getMaximumSpan(int axis) Determines the maximum span for this view along an axis.
float | getMinimumSpan(int axis) Determines the minimum span for this view along an axis.
int | getNextVisualPositionFrom(int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet) Provides a way to determine the next visually represented model location at which one might place a caret.
View | getParent() Returns the parent of the view.
abstract float | getPreferredSpan(int axis) Determines the preferred span for this view along an axis.
int | getResizeWeight(int axis) Determines the resizability of the view along the given axis.
int | getStartOffset() Fetches the portion of the model for which this view is responsible.
String | getToolTipText(float x, float y, Shape allocation) Returns the tooltip text at the specified location.
View | getView(int n) Gets the nth child view.
int | getViewCount() Returns the number of views in this view.
ViewFactory | getViewFactory() Fetches the ViewFactory implementation that is feeding the view hierarchy.
int | getViewIndex(float x, float y, Shape allocation) Returns the child view index representing the given position in the view.
int | getViewIndex(int pos, Position.Bias b) Returns the child view index representing the given position in the model.
void | insert(int offs, View v) Inserts a single child view.
void | insertUpdate(DocumentEvent e, Shape a, ViewFactory f) Gives notification that something was inserted into the document in a location that this view is responsible for.
boolean | isVisible() Returns a boolean that indicates whether the view is visible or not.
Shape | modelToView(int p0, Position.Bias b0, int p1, Position.Bias b1, Shape a) Provides a mapping, for a given region, from the document model coordinate space to the view coordinate space.
Shape | modelToView(int pos, Shape a) Deprecated.
abstract Shape | modelToView(int pos, Shape a, Position.Bias b) Provides a mapping, for a given character, from the document model coordinate space to the view coordinate space.
abstract void | paint(Graphics g, Shape allocation) Renders using the given rendering surface and area on that surface.
void | preferenceChanged(View child, boolean width, boolean height) Child views can call this on the parent to indicate that the preference has changed and should be reconsidered for layout.
void | remove(int i) Removes one of the children at the given position.
void | removeAll() Removes all of the children.
void | removeUpdate(DocumentEvent e, Shape a, ViewFactory f) Gives notification that something was removed from the document in a location that this view is responsible for.
void | replace(int offset, int length, View[] views) Replaces child views.
void | setParent(View parent) Establishes the parent view for this view.
void | setSize(float width, float height) Sets the size of the view.
protected boolean | updateChildren(DocumentEvent.ElementChange ec, DocumentEvent e, ViewFactory f) 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.
protected void | updateLayout(DocumentEvent.ElementChange ec, DocumentEvent e, Shape a) Updates the layout in response to receiving notification of change from the model.
int | viewToModel(float x, float y, Shape a) Deprecated.
abstract int | viewToModel(float x, float y, Shape a, Position.Bias[] biasReturn) Provides a mapping from the view coordinate space to the logical coordinate space of the model.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

BadBreakWeight

public static final int BadBreakWeight
The weight to indicate a view is a bad break opportunity for the purpose of formatting. This value indicates that no attempt should be made to break the view into fragments as the view has not been written to support fragmenting.

See Also:
getBreakWeight(int, float, float), GoodBreakWeight, ExcellentBreakWeight, ForcedBreakWeight, Constant Field Values

GoodBreakWeight

public static final int GoodBreakWeight
The weight to indicate a view supports breaking, but better opportunities probably exist.

See Also:
getBreakWeight(int, float, float), BadBreakWeight, ExcellentBreakWeight, ForcedBreakWeight, Constant Field Values

ExcellentBreakWeight

public static final int ExcellentBreakWeight
The weight to indicate a view supports breaking, and this represents a very attractive place to break.

See Also:
getBreakWeight(int, float, float), BadBreakWeight, GoodBreakWeight, ForcedBreakWeight, Constant Field Values

ForcedBreakWeight

public static final int ForcedBreakWeight
The weight to indicate a view supports breaking, and must be broken to be represented properly when placed in a view that formats its children by breaking them.

See Also:
getBreakWeight(int, float, float), BadBreakWeight, GoodBreakWeight, ExcellentBreakWeight, Constant Field Values

X_AXIS

public static final int X_AXIS
Axis for format/break operations.

See Also:
Constant Field Values

Y_AXIS

public static final int Y_AXIS
Axis for format/break operations.

See Also:
Constant Field Values
Constructor Detail

View

public View(Element elem)
Creates a new View object.

Parameters:
elem - the Element to represent
Method Detail

getParent

public View getParent()
Returns the parent of the view.

Returns:
the parent, or null if none exists

isVisible

public boolean isVisible()
Returns a boolean that indicates whether the view is visible or not. By default all views are visible.

Returns:
always returns true

getPreferredSpan

public abstract float getPreferredSpan(int axis)
Determines the preferred span for this view along an axis.

Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
Returns:
the span the view would like to be rendered into. Typically the view is told to render into the span that is returned, although there is no guarantee. The parent may choose to resize or break the view
See Also:
getPreferredSpan(int)

getMinimumSpan

public float getMinimumSpan(int axis)
Determines the minimum span for this view along an axis.

Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
Returns:
the minimum span the view can be rendered into
See Also:
getPreferredSpan(int)

getMaximumSpan

public float getMaximumSpan(int axis)
Determines the maximum span for this view along an axis.

Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
Returns:
the maximum span the view can be rendered into
See Also:
getPreferredSpan(int)

preferenceChanged

public void preferenceChanged(View child,
                              boolean width,
                              boolean height)
Child views can call this on the parent to indicate that the preference has changed and should be reconsidered for layout. By default this just propagates upward to the next parent. The root view will call revalidate on the associated text component.

Parameters:
child - the child view
width - true if the width preference has changed
height - true if the height preference has changed
See Also:
JComponent.revalidate()

getAlignment

public float getAlignment(int axis)
Determines the desired alignment for this view along an axis. The desired alignment is returned. This should be a value >= 0.0 and <= 1.0, where 0 indicates alignment at the origin and 1.0 indicates alignment to the full span away from the origin. An alignment of 0.5 would be the center of the view.

Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
Returns:
the value 0.5

paint

public abstract void paint(Graphics g,
                           Shape allocation)
Renders using the given rendering surface and area on that surface. The view may need to do layout and create child views to enable itself to render into the given allocation.

Parameters:
g - the rendering surface to use
allocation - the allocated region to render into
See Also:
paint(java.awt.Graphics, java.awt.Shape)

setParent

public void setParent(View parent)
Establishes the parent view for this view. This is guaranteed to be called before any other methods if the parent view is functioning properly. This is also the last method called, since it is called to indicate the view has been removed from the hierarchy as well. When this method is called to set the parent to null, this method does the same for each of its children, propogating the notification that they have been disconnected from the view tree. If this is reimplemented, super.setParent() should be called.

Parameters:
parent - the new parent, or null if the view is being removed from a parent

getViewCount

public int getViewCount()
Returns the number of views in this view. Since the default is to not be a composite view this returns 0.

Returns:
the number of views >= 0
See Also:
getViewCount()

getView

public View getView(int n)
Gets the nth child view. Since there are no children by default, this returns null.

Parameters:
n - the number of the view to get, >= 0 && < getViewCount()
Returns:
the view

removeAll

public void removeAll()
Removes all of the children. This is a convenience call to replace.

Since:
1.3

remove

public void remove(int i)
Removes one of the children at the given position. This is a convenience call to replace.

Since:
1.3

insert

public void insert(int offs,
                   View v)
Inserts a single child view. This is a convenience call to replace.

Parameters:
offs - the offset of the view to insert before >= 0
v - the view
Since:
1.3
See Also:
replace(int, int, javax.swing.text.View[])

append

public void append(View v)
Appends a single child view. This is a convenience call to replace.

Parameters:
v - the view
Since:
1.3
See Also:
replace(int, int, javax.swing.text.View[])

replace

public void replace(int offset,
                    int length,
                    View[] views)
Replaces child views. If there are no views to remove this acts as an insert. If there are no views to add this acts as a remove. Views being removed will have the parent set to null, and the internal reference to them removed so that they can be garbage collected. This is implemented to do nothing, because by default a view has no children.

Parameters:
offset - the starting index into the child views to insert the new views. This should be a value >= 0 and <= getViewCount
length - the number of existing child views to remove This should be a value >= 0 and <= (getViewCount() - offset).
views - the child views to add. This value can be null to indicate no children are being added (useful to remove).
Since:
1.3

getViewIndex

public int getViewIndex(int pos,
                        Position.Bias b)
Returns the child view index representing the given position in the model. By default a view has no children so this is implemented to return -1 to indicate there is no valid child index for any position.

Parameters:
pos - the position >= 0
Returns:
index of the view representing the given position, or -1 if no view represents that position
Since:
1.3

getChildAllocation

public Shape getChildAllocation(int index,
                                Shape a)
Fetches the allocation for the given child view. This enables finding out where various views are located, without assuming how the views store their location. This returns null since the default is to not have any child views.

Parameters:
index - the index of the child, >= 0 && < getViewCount()
a - the allocation to this view
Returns:
the allocation to the child

getNextVisualPositionFrom

public int getNextVisualPositionFrom(int pos,
                                     Position.Bias b,
                                     Shape a,
                                     int direction,
                                     Position.Bias[] biasRet)
                              throws BadLocationException
Provides a way to determine the next visually represented model location at which one might place a caret. Some views may not be visible, they might not be in the same order found in the model, or they just might not allow access to some of the locations in the model.

Parameters:
pos - the position to convert >= 0
a - the allocated region in which to render
direction - the direction from the current position that can be thought of as the arrow keys typically found on a keyboard. This will be one of the following values:
  • SwingConstants.WEST
  • SwingConstants.EAST
  • SwingConstants.NORTH
  • SwingConstants.SOUTH
Returns:
the location within the model that best represents the next location visual position
Throws:
BadLocationException
IllegalArgumentException - if direction doesn't have one of the legal values above

modelToView

public abstract Shape modelToView(int pos,
                                  Shape a,
                                  Position.Bias b)
                           throws BadLocationException
Provides a mapping, for a given character, from the document model coordinate space to the view coordinate space.

Parameters:
pos - the position of the desired character (>=0)
a - the area of the view, which encompasses the requested character
b - the bias toward the previous character or the next character represented by the offset, in case the position is a boundary of two views; b will have one of these values:
  • Position.Bias.Forward
  • Position.Bias.Backward
Returns:
the bounding box, in view coordinate space, of the character at the specified position
Throws:
BadLocationException - if the specified position does not represent a valid location in the associated document
IllegalArgumentException - if b is not one of the legal Position.Bias values listed above
See Also:
viewToModel(float, float, java.awt.Shape, javax.swing.text.Position.Bias[])

modelToView

public Shape modelToView(int p0,
                         Position.Bias b0,
                         int p1,
                         Position.Bias b1,
                         Shape a)
                  throws BadLocationException
Provides a mapping, for a given region, from the document model coordinate space to the view coordinate space. The specified region is created as a union of the first and last character positions.

Parameters:
p0 - the position of the first character (>=0)
b0 - the bias of the first character position, toward the previous character or the next character represented by the offset, in case the position is a boundary of two views; b0 will have one of these values:
  • Position.Bias.Forward
  • Position.Bias.Backward
p1 - the position of the last character (>=0)
b1 - the bias for the second character position, defined one of the legal values shown above
a - the area of the view, which encompasses the requested region
Returns:
the bounding box which is a union of the region specified by the first and last character positions
Throws:
BadLocationException - if the given position does not represent a valid location in the associated document
IllegalArgumentException - if b0 or b1 are not one of the legal Position.Bias values listed above
See Also:
viewToModel(float, float, java.awt.Shape, javax.swing.text.Position.Bias[])

viewToModel

public abstract int viewToModel(float x,
                                float y,
                                Shape a,
                                Position.Bias[] biasReturn)
Provides a mapping from the view coordinate space to the logical coordinate space of the model. The biasReturn argument will be filled in to indicate that the point given is closer to the next character in the model or the previous character in the model.

Parameters:
x - the X coordinate >= 0
y - the Y coordinate >= 0
a - the allocated region in which to render
Returns:
the location within the model that best represents the given point in the view >= 0. The biasReturn argument will be filled in to indicate that the point given is closer to the next character in the model or the previous character in the model.

insertUpdate

public void insertUpdate(DocumentEvent e,
                         Shape a,
                         ViewFactory f)
Gives notification that something was inserted into the document in a location that this view is responsible for. To reduce the burden to subclasses, this functionality is spread out into the following calls that subclasses can reimplement:
  1. updateChildren is called if there were any changes to the element this view is responsible for. If this view has child views that are represent the child elements, then this method should do whatever is necessary to make sure the child views correctly represent the model.
  2. forwardUpdate is called to forward the DocumentEvent to the appropriate child views.
  3. updateLayout is called to give the view a chance to either repair its layout, to reschedule layout, or do nothing.

Parameters:
e - the change information from the associated document
a - the current allocation of the view
f - the factory to use to rebuild if the view has children
See Also:
insertUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory)

removeUpdate

public void removeUpdate(DocumentEvent e,
                         Shape a,
                         ViewFactory f)
Gives notification that something was removed from the document in a location that this view is responsible for. To reduce the burden to subclasses, this functionality is spread out into the following calls that subclasses can reimplement:
  1. updateChildren is called if there were any changes to the element this view is responsible for. If this view has child views that are represent the child elements, then this method should do whatever is necessary to make sure the child views correctly represent the model.
  2. forwardUpdate is called to forward the DocumentEvent to the appropriate child views.
  3. updateLayout is called to give the view a chance to either repair its layout, to reschedule layout, or do nothing.

Parameters:
e - the change information from the associated document
a - the current allocation of the view
f - the factory to use to rebuild if the view has children
See Also:
removeUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory)

changedUpdate

public void changedUpdate(DocumentEvent e,
                          Shape a,
                          ViewFactory f)
Gives notification from the document that attributes were changed in a location that this view is responsible for. To reduce the burden to subclasses, this functionality is spread out into the following calls that subclasses can reimplement:
  1. updateChildren is called if there were any changes to the element this view is responsible for. If this view has child views that are represent the child elements, then this method should do whatever is necessary to make sure the child views correctly represent the model.
  2. forwardUpdate is called to forward the DocumentEvent to the appropriate child views.
  3. updateLayout is called to give the view a chance to either repair its layout, to reschedule layout, or do nothing.

Parameters:
e - the change information from the associated document
a - the current allocation of the view
f - the factory to use to rebuild if the view has children
See Also:
changedUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory)

getDocument

public Document getDocument()
Fetches the model associated with the view.

Returns:
the view model, null if none
See Also:
getDocument()

getStartOffset

public int getStartOffset()
Fetches the portion of the model for which this view is responsible.

Returns:
the starting offset into the model >= 0
See Also:
getStartOffset()

getEndOffset

public int getEndOffset()
Fetches the portion of the model for which this view is responsible.

Returns:
the ending offset into the model >= 0
See Also:
getEndOffset()

getElement

public Element getElement()
Fetches the structural portion of the subject that this view is mapped to. The view may not be responsible for the entire portion of the element.

Returns:
the subject
See Also:
getElement()

getGraphics

public Graphics getGraphics()
Fetch a Graphics for rendering. This can be used to determine font characteristics, and will be different for a print view than a component view.

Returns:
a Graphics object for rendering
Since:
1.3

getAttributes

public AttributeSet getAttributes()
Fetches the attributes to use when rendering. By default this simply returns the attributes of the associated element. This method should be used rather than using the element directly to obtain access to the attributes to allow view-specific attributes to be mixed in or to allow the view to have view-specific conversion of attributes by subclasses. Each view should document what attributes it recognizes for the purpose of rendering or layout, and should always access them through the AttributeSet returned by this method.

breakView

public View breakView(int axis,
                      int offset,
                      float pos,
                      float len)
Tries to break this view on the given axis. This is called by views that try to do formatting of their children. For example, a view of a paragraph will typically try to place its children into row and views representing chunks of text can sometimes be broken down into smaller pieces.

This is implemented to return the view itself, which represents the default behavior on not being breakable. If the view does support breaking, the starting offset of the view returned should be the given offset, and the end offset should be less than or equal to the end offset of the view being broken.

Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
offset - the location in the document model that a broken fragment would occupy >= 0. This would be the starting offset of the fragment returned
pos - the position along the axis that the broken view would occupy >= 0. This may be useful for things like tab calculations
len - specifies the distance along the axis where a potential break is desired >= 0
Returns:
the fragment of the view that represents the given span, if the view can be broken. If the view doesn't support breaking behavior, the view itself is returned.
See Also:
ParagraphView

createFragment

public View createFragment(int p0,
                           int p1)
Creates a view that represents a portion of the element. This is potentially useful during formatting operations for taking measurements of fragments of the view. If the view doesn't support fragmenting (the default), it should return itself.

Parameters:
p0 - the starting offset >= 0. This should be a value greater or equal to the element starting offset and less than the element ending offset.
p1 - the ending offset > p0. This should be a value less than or equal to the elements end offset and greater than the elements starting offset.
Returns:
the view fragment, or itself if the view doesn't support breaking into fragments
See Also:
LabelView

getBreakWeight

public int getBreakWeight(int axis,
                          float pos,
                          float len)
Determines how attractive a break opportunity in this view is. This can be used for determining which view is the most attractive to call breakView on in the process of formatting. A view that represents text that has whitespace in it might be more attractive than a view that has no whitespace, for example. The higher the weight, the more attractive the break. A value equal to or lower than BadBreakWeight should not be considered for a break. A value greater than or equal to ForcedBreakWeight should be broken.

This is implemented to provide the default behavior of returning BadBreakWeight unless the length is greater than the length of the view in which case the entire view represents the fragment. Unless a view has been written to support breaking behavior, it is not attractive to try and break the view. An example of a view that does support breaking is LabelView. An example of a view that uses break weight is ParagraphView.

Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
pos - the potential location of the start of the broken view >= 0. This may be useful for calculating tab positions
len - specifies the relative length from pos where a potential break is desired >= 0
Returns:
the weight, which should be a value between ForcedBreakWeight and BadBreakWeight
See Also:
LabelView, ParagraphView, BadBreakWeight, GoodBreakWeight, ExcellentBreakWeight, ForcedBreakWeight

getResizeWeight

public int getResizeWeight(int axis)
Determines the resizability of the view along the given axis. A value of 0 or less is not resizable.

Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
Returns:
the weight

setSize

public void setSize(float width,
                    float height)
Sets the size of the view. This should cause layout of the view along the given axis, if it has any layout duties.

Parameters:
width - the width >= 0
height - the height >= 0

getContainer

public Container getContainer()
Fetches the container hosting the view. This is useful for things like scheduling a repaint, finding out the host components font, etc. The default implementation of this is to forward the query to the parent view.

Returns:
the container, null if none

getViewFactory

public ViewFactory getViewFactory()
Fetches the ViewFactory implementation that is feeding the view hierarchy. Normally the views are given this as an argument to updates from the model when they are most likely to need the factory, but this method serves to provide it at other times.

Returns:
the factory, null if none

getToolTipText

public String getToolTipText(float x,
                             float y,
                             Shape allocation)
Returns the tooltip text at the specified location. The default implementation returns the value from the child View identified by the passed in location.

Since:
1.4
See Also:
JTextComponent.getToolTipText(java.awt.event.MouseEvent)

getViewIndex

public int getViewIndex(float x,
                        float y,
                        Shape allocation)
Returns the child view index representing the given position in the view. This iterates over all the children returning the first with a bounds that contains x, y.

Parameters:
x - the x coordinate
y - the y coordinate
allocation - current allocation of the View.
Returns:
index of the view representing the given location, or -1 if no view represents that position
Since:
1.4

updateChildren

protected boolean updateChildren(DocumentEvent.ElementChange ec,
                                 DocumentEvent e,
                                 ViewFactory f)
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. This is implemented to assume the child views are directly responsible for the child elements of the element this view represents. The ViewFactory is used to create child views for each element specified as added in the ElementChange, starting at the index specified in the given ElementChange. The number of child views representing the removed elements specified are removed.

Parameters:
ec - the change information for the element this view is responsible for. This should not be null if this method gets called
e - the change information from the associated document
f - the factory to use to build child views
Returns:
whether or not the child views represent the child elements of the element this view is responsible for. Some views create children that represent a portion of the element they are responsible for, and should return false. This information is used to determine if views in the range of the added elements should be forwarded to or not
Since:
1.3
See Also:
insertUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory),
removeUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory),
changedUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory)

forwardUpdate

protected void forwardUpdate(DocumentEvent.ElementChange ec,
                             DocumentEvent e,
                             Shape a,
                             ViewFactory f)
Forwards the given DocumentEvent to the child views that need to be notified of the change to the model. If there were changes to the element this view is responsible for, that should be considered when forwarding (i.e. new child views should not get notified).

Parameters:
ec - changes to the element this view is responsible for (may be null if there were no changes).
e - the change information from the associated document
a - the current allocation of the view
f - the factory to use to rebuild if the view has children
Since:
1.3
See Also:
insertUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory),
removeUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory),
changedUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory)

forwardUpdateToView

protected void forwardUpdateToView(View v,
                                   DocumentEvent e,
                                   Shape a,
                                   ViewFactory f)
Forwards the DocumentEvent to the give child view. This simply messages the view with a call to insertUpdate, removeUpdate, or changedUpdate depending upon the type of the event. This is called by forwardUpdate to forward the event to children that need it.

Parameters:
v - the child view to forward the event to
e - the change information from the associated document
a - the current allocation of the view
f - the factory to use to rebuild if the view has children
Since:
1.3
See Also:
forwardUpdate(javax.swing.event.DocumentEvent.ElementChange, javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory)

updateLayout

protected void updateLayout(DocumentEvent.ElementChange ec,
                            DocumentEvent e,
                            Shape a)
Updates the layout in response to receiving notification of change from the model. This is implemented to call preferenceChanged to reschedule a new layout if the ElementChange record is not null.

Parameters:
ec - changes to the element this view is responsible for (may be null if there were no changes)
e - the change information from the associated document
a - the current allocation of the view
Since:
1.3
See Also:
insertUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory),
removeUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory),
changedUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory)

modelToView

public Shape modelToView(int pos,
                         Shape a)
                  throws BadLocationException
Deprecated.

Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it. This is implemented to default the bias to Position.Bias.Forward which was previously implied.

Parameters:
pos - the position to convert >= 0
a - the allocated region in which to render
Returns:
the bounding box of the given position is returned
Throws:
BadLocationException - if the given position does not represent a valid location in the associated document
See Also:
modelToView(int, java.awt.Shape, javax.swing.text.Position.Bias)

viewToModel

public int viewToModel(float x,
                       float y,
                       Shape a)
Deprecated.

Provides a mapping from the view coordinate space to the logical coordinate space of the model.

Parameters:
x - the X coordinate >= 0
y - the Y coordinate >= 0
a - the allocated region in which to render
Returns:
the location within the model that best represents the given point in the view >= 0
See Also:
viewToModel(float, float, java.awt.Shape, javax.swing.text.Position.Bias[])
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ViewFactory (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Interface ViewFactory

All Known Implementing Classes:
BasicTextUI, HTMLEditorKit.HTMLFactory
public interface ViewFactory

A factory to create a view of some portion of document subject. This is intended to enable customization of how views get mapped over a document model.

Method Summary
 View create(Element elem)
Creates a view from the given structural element of a document.

Method Detail

create

public View create(Element elem)
Creates a view from the given structural element of a document.

Parameters:
elem - the piece of the document to build a view of
Returns:
the view
See Also:
View
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


WrappedPlainView (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class WrappedPlainView

java.lang.Object
    extended by javax.swing.text.View
        extended by javax.swing.text.CompositeView
            extended by javax.swing.text.BoxView
                extended by javax.swing.text.WrappedPlainView
All Implemented Interfaces:
SwingConstants, TabExpander
public class WrappedPlainView
extends BoxView
implements TabExpander

View of plain text (text with only one font and color) that does line-wrapping. This view expects that its associated element has child elements that represent the lines it should be wrapping. It is implemented as a vertical box that contains logical line views. The logical line views are nested classes that render the logical line as multiple physical line if the logical line is too wide to fit within the allocation. The line views draw upon the outer class for its state to reduce their memory requirements.

The line views do all of their rendering through the drawLine method which in turn does all of its rendering through the drawSelectedText and drawUnselectedText methods. This enables subclasses to easily specialize the rendering without concern for the layout aspects.

See Also:
View

Field Summary
Fields inherited from class javax.swing.text.View
BadBreakWeight, ExcellentBreakWeight, ForcedBreakWeight, GoodBreakWeight, X_AXIS, Y_AXIS
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
Constructor Summary
WrappedPlainView(Element elem)
Creates a new WrappedPlainView.
WrappedPlainView(Element elem, boolean wordWrap)
Creates a new WrappedPlainView.
Method Summary
protected int | calculateBreakPosition(int p0, int p1) This is called by the nested wrapped line views to determine the break location.
void | changedUpdate(DocumentEvent e, Shape a, ViewFactory f) Gives notification from the document that attributes were changed in a location that this view is responsible for.
protected void | drawLine(int p0, int p1, Graphics g, int x, int y) Renders a line of text, suppressing whitespace at the end and expanding any tabs.
protected int | drawSelectedText(Graphics g, int x, int y, int p0, int p1) Renders the given range in the model as selected text.
protected int | drawUnselectedText(Graphics g, int x, int y, int p0, int p1) Renders the given range in the model as normal unselected text.
protected Segment | getLineBuffer() Gives access to a buffer that can be used to fetch text from the associated document.
float | getMaximumSpan(int axis) Determines the maximum span for this view along an axis.
float | getMinimumSpan(int axis) Determines the minimum span for this view along an axis.
float | getPreferredSpan(int axis) Determines the preferred span for this view along an axis.
protected int | getTabSize() Returns the tab size set for the document, defaulting to 8.
void | insertUpdate(DocumentEvent e, Shape a, ViewFactory f) Gives notification that something was inserted into the document in a location that this view is responsible for.
protected void | loadChildren(ViewFactory f) Loads all of the children to initialize the view.
float | nextTabStop(float x, int tabOffset) Returns the next tab stop position after a given reference position.
void | paint(Graphics g, Shape a) Renders using the given rendering surface and area on that surface.
void | removeUpdate(DocumentEvent e, Shape a, ViewFactory f) Gives notification that something was removed from the document in a location that this view is responsible for.
void | setSize(float width, float height) Sets the size of the view.
Methods inherited from class javax.swing.text.BoxView
baselineLayout, baselineRequirements, calculateMajorAxisRequirements, calculateMinorAxisRequirements, childAllocation, flipEastAndWestAtEnds, forwardUpdate, getAlignment, getAxis, getChildAllocation, getHeight, getOffset, getResizeWeight, getSpan, getViewAtPoint, getWidth, isAfter, isAllocationValid, isBefore, isLayoutValid, layout, layoutChanged, layoutMajorAxis, layoutMinorAxis, modelToView, paintChild, preferenceChanged, replace, setAxis, viewToModel
Methods inherited from class javax.swing.text.CompositeView
getBottomInset, getInsideAllocation, getLeftInset, getNextEastWestVisualPositionFrom, getNextNorthSouthVisualPositionFrom, getNextVisualPositionFrom, getRightInset, getTopInset, getView, getViewAtPosition, getViewCount, getViewIndex, getViewIndexAtPosition, modelToView, setInsets, setParagraphInsets, setParent
Methods inherited from class javax.swing.text.View
append, breakView, createFragment, forwardUpdateToView, getAttributes, getBreakWeight, getContainer, getDocument, getElement, getEndOffset, getGraphics, getParent, getStartOffset, getToolTipText, getViewFactory, getViewIndex, insert, isVisible, modelToView, remove, removeAll, updateChildren, updateLayout, viewToModel
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

WrappedPlainView

public WrappedPlainView(Element elem)
Creates a new WrappedPlainView. Lines will be wrapped on character boundaries.

Parameters:
elem - the element underlying the view

WrappedPlainView

public WrappedPlainView(Element elem,
                        boolean wordWrap)
Creates a new WrappedPlainView. Lines can be wrapped on either character or word boundaries depending upon the setting of the wordWrap parameter.

Parameters:
elem - the element underlying the view
wordWrap - should lines be wrapped on word boundaries?
Method Detail

getTabSize

protected int getTabSize()
Returns the tab size set for the document, defaulting to 8.

Returns:
the tab size

drawLine

protected void drawLine(int p0,
                        int p1,
                        Graphics g,
                        int x,
                        int y)
Renders a line of text, suppressing whitespace at the end and expanding any tabs. This is implemented to make calls to the methods drawUnselectedText and drawSelectedText so that the way selected and unselected text are rendered can be customized.

Parameters:
p0 - the starting document location to use >= 0
p1 - the ending document location to use >= p1
g - the graphics context
x - the starting X position >= 0
y - the starting Y position >= 0
See Also:
drawUnselectedText(java.awt.Graphics, int, int, int, int), drawSelectedText(java.awt.Graphics, int, int, int, int)

drawUnselectedText

protected int drawUnselectedText(Graphics g,
                                 int x,
                                 int y,
                                 int p0,
                                 int p1)
                          throws BadLocationException
Renders the given range in the model as normal unselected text.

Parameters:
g - the graphics context
x - the starting X coordinate >= 0
y - the starting Y coordinate >= 0
p0 - the beginning position in the model >= 0
p1 - the ending position in the model >= p0
Returns:
the X location of the end of the range >= 0
Throws:
BadLocationException - if the range is invalid

drawSelectedText

protected int drawSelectedText(Graphics g,
                               int x,
                               int y,
                               int p0,
                               int p1)
                        throws BadLocationException
Renders the given range in the model as selected text. This is implemented to render the text in the color specified in the hosting component. It assumes the highlighter will render the selected background.

Parameters:
g - the graphics context
x - the starting X coordinate >= 0
y - the starting Y coordinate >= 0
p0 - the beginning position in the model >= 0
p1 - the ending position in the model >= p0
Returns:
the location of the end of the range.
Throws:
BadLocationException - if the range is invalid

getLineBuffer

protected final Segment getLineBuffer()
Gives access to a buffer that can be used to fetch text from the associated document.

Returns:
the buffer

calculateBreakPosition

protected int calculateBreakPosition(int p0,
                                     int p1)
This is called by the nested wrapped line views to determine the break location. This can be reimplemented to alter the breaking behavior. It will either break at word or character boundaries depending upon the break argument given at construction.

loadChildren

protected void loadChildren(ViewFactory f)
Loads all of the children to initialize the view. This is called by the setParent method. Subclasses can reimplement this to initialize their child views in a different manner. The default implementation creates a child view for each child element.

Overrides:
loadChildren in class CompositeView
Parameters:
f - the view factory
See Also:
CompositeView.setParent(javax.swing.text.View)

nextTabStop

public float nextTabStop(float x,
                         int tabOffset)
Returns the next tab stop position after a given reference position. This implementation does not support things like centering so it ignores the tabOffset argument.

Specified by:
nextTabStop in interface TabExpander
Parameters:
x - the current position >= 0
tabOffset - the position within the text stream that the tab occurred at >= 0.
Returns:
the tab stop, measured in points >= 0

paint

public void paint(Graphics g,
                  Shape a)
Renders using the given rendering surface and area on that surface. This is implemented to stash the selection positions, selection colors, and font metrics for the nested lines to use.

Overrides:
paint in class BoxView
Parameters:
g - the rendering surface to use
a - the allocated region to render into
See Also:
View.paint(java.awt.Graphics, java.awt.Shape)

setSize

public void setSize(float width,
                    float height)
Sets the size of the view. This should cause layout of the view along the given axis, if it has any layout duties.

Overrides:
setSize in class BoxView
Parameters:
width - the width >= 0
height - the height >= 0

getPreferredSpan

public float getPreferredSpan(int axis)
Determines the preferred span for this view along an axis. This is implemented to provide the superclass behavior after first making sure that the current font metrics are cached (for the nested lines which use the metrics to determine the height of the potentially wrapped lines).

Overrides:
getPreferredSpan in class BoxView
Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
Returns:
the span the view would like to be rendered into. Typically the view is told to render into the span that is returned, although there is no guarantee. The parent may choose to resize or break the view.
See Also:
View.getPreferredSpan(int)

getMinimumSpan

public float getMinimumSpan(int axis)
Determines the minimum span for this view along an axis. This is implemented to provide the superclass behavior after first making sure that the current font metrics are cached (for the nested lines which use the metrics to determine the height of the potentially wrapped lines).

Overrides:
getMinimumSpan in class BoxView
Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
Returns:
the span the view would like to be rendered into. Typically the view is told to render into the span that is returned, although there is no guarantee. The parent may choose to resize or break the view.
See Also:
View.getMinimumSpan(int)

getMaximumSpan

public float getMaximumSpan(int axis)
Determines the maximum span for this view along an axis. This is implemented to provide the superclass behavior after first making sure that the current font metrics are cached (for the nested lines which use the metrics to determine the height of the potentially wrapped lines).

Overrides:
getMaximumSpan in class BoxView
Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
Returns:
the span the view would like to be rendered into. Typically the view is told to render into the span that is returned, although there is no guarantee. The parent may choose to resize or break the view.
See Also:
View.getMaximumSpan(int)

insertUpdate

public void insertUpdate(DocumentEvent e,
                         Shape a,
                         ViewFactory f)
Gives notification that something was inserted into the document in a location that this view is responsible for. This is implemented to simply update the children.

Overrides:
insertUpdate in class View
Parameters:
e - the change information from the associated document
a - the current allocation of the view
f - the factory to use to rebuild if the view has children
See Also:
View.insertUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory)

removeUpdate

public void removeUpdate(DocumentEvent e,
                         Shape a,
                         ViewFactory f)
Gives notification that something was removed from the document in a location that this view is responsible for. This is implemented to simply update the children.

Overrides:
removeUpdate in class View
Parameters:
e - the change information from the associated document
a - the current allocation of the view
f - the factory to use to rebuild if the view has children
See Also:
View.removeUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory)

changedUpdate

public void changedUpdate(DocumentEvent e,
                          Shape a,
                          ViewFactory f)
Gives notification from the document that attributes were changed in a location that this view is responsible for.

Overrides:
changedUpdate in class View
Parameters:
e - the change information from the associated document
a - the current allocation of the view
f - the factory to use to rebuild if the view has children
See Also:
View.changedUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ZoneView (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.swing.text
Class ZoneView

java.lang.Object
    extended by javax.swing.text.View
        extended by javax.swing.text.CompositeView
            extended by javax.swing.text.BoxView
                extended by javax.swing.text.ZoneView
All Implemented Interfaces:
SwingConstants
public class ZoneView
extends BoxView

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. This enables a substantial reduction in memory consumption for situations where the model being represented is very large, by building view objects only for the region being actively viewed/edited. The size of the children can be estimated in some way, or calculated asynchronously with only the result being saved.

ZoneView extends BoxView to provide a box that implements zones for it's children. The zones are special View implementations (the children of an instance of this class) that represent only a portion of the model that an instance of ZoneView is responsible for. The zones don't create child views until an attempt is made to display them. A box shaped view is well suited to this because:

  • Boxes are a heavily used view, and having a box that provides this behavior gives substantial opportunity to plug the behavior into a view hierarchy from the view factory.
  • Boxes are tiled in one direction, so it is easy to divide them into zones in a reliable way.
  • Boxes typically have a simple relationship to the model (i.e. they create child views that directly represent the child elements).
  • Boxes are easier to estimate the size of than some other shapes.

The default behavior is controled by two properties, maxZoneSize and maxZonesLoaded. Setting maxZoneSize to Integer.MAX_VALUE would have the effect of causing only one zone to be created. This would effectively turn the view into an implementation of the decorator pattern. Setting maxZonesLoaded to a value of Integer.MAX_VALUE would cause zones to never be unloaded. For simplicity, zones are created on boundaries represented by the child elements of the element the view is responsible for. The zones can be any View implementation, but the default implementation is based upon AsyncBoxView which supports fairly large zones efficiently.

Since:
1.3
See Also:
View

Field Summary
Fields inherited from class javax.swing.text.View
BadBreakWeight, ExcellentBreakWeight, ForcedBreakWeight, GoodBreakWeight, X_AXIS, Y_AXIS
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
Constructor Summary
ZoneView(Element elem, int axis)
Constructs a ZoneView.
Method Summary
protected View | createZone(int p0, int p1) Create a view to represent a zone for the given range within the model (which should be within the range of this objects responsibility).
int | getMaximumZoneSize() Get the current maximum zone size.
int | getMaxZonesLoaded() Get the current setting of the number of zones allowed to be loaded at the same time.
protected int | getViewIndexAtPosition(int pos) Returns the child view index representing the given position in the model.
void | insertUpdate(DocumentEvent changes, Shape a, ViewFactory f) Gives notification that something was inserted into the document in a location that this view is responsible for.
protected boolean | isZoneLoaded(View zone) Determine if a zone is in the loaded state.
protected void | loadChildren(ViewFactory f) Loads all of the children to initialize the view.
void | removeUpdate(DocumentEvent changes, Shape a, ViewFactory f) Gives notification that something was removed from the document in a location that this view is responsible for.
void | setMaximumZoneSize(int size) Set the desired maximum zone size.
void | setMaxZonesLoaded(int mzl) Sets the current setting of the number of zones allowed to be loaded at the same time.
protected void | unloadZone(View zone) Unload a zone (Convert the zone to its memory saving state).
protected boolean | updateChildren(DocumentEvent.ElementChange ec, DocumentEvent e, ViewFactory f) 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.
protected void | zoneWasLoaded(View zone) Called by a zone when it gets loaded.
Methods inherited from class javax.swing.text.BoxView
baselineLayout, baselineRequirements, calculateMajorAxisRequirements, calculateMinorAxisRequirements, childAllocation, flipEastAndWestAtEnds, forwardUpdate, getAlignment, getAxis, getChildAllocation, getHeight, getMaximumSpan, getMinimumSpan, getOffset, getPreferredSpan, getResizeWeight, getSpan, getViewAtPoint, getWidth, isAfter, isAllocationValid, isBefore, isLayoutValid, layout, layoutChanged, layoutMajorAxis, layoutMinorAxis, modelToView, paint, paintChild, preferenceChanged, replace, setAxis, setSize, viewToModel
Methods inherited from class javax.swing.text.CompositeView
getBottomInset, getInsideAllocation, getLeftInset, getNextEastWestVisualPositionFrom, getNextNorthSouthVisualPositionFrom, getNextVisualPositionFrom, getRightInset, getTopInset, getView, getViewAtPosition, getViewCount, getViewIndex, modelToView, setInsets, setParagraphInsets, setParent
Methods inherited from class javax.swing.text.View
append, breakView, changedUpdate, createFragment, forwardUpdateToView, getAttributes, getBreakWeight, getContainer, getDocument, getElement, getEndOffset, getGraphics, getParent, getStartOffset, getToolTipText, getViewFactory, getViewIndex, insert, isVisible, modelToView, remove, removeAll, updateLayout, viewToModel
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ZoneView

public ZoneView(Element elem,
                int axis)
Constructs a ZoneView.

Parameters:
elem - the element this view is responsible for
axis - either View.X_AXIS or View.Y_AXIS
Method Detail

getMaximumZoneSize

public int getMaximumZoneSize()
Get the current maximum zone size.

setMaximumZoneSize

public void setMaximumZoneSize(int size)
Set the desired maximum zone size. A zone may get larger than this size if a single child view is larger than this size since zones are formed on child view boundaries.

Parameters:
size - the number of characters the zone may represent before attempting to break the zone into a smaller size.

getMaxZonesLoaded

public int getMaxZonesLoaded()
Get the current setting of the number of zones allowed to be loaded at the same time.

setMaxZonesLoaded

public void setMaxZonesLoaded(int mzl)
Sets the current setting of the number of zones allowed to be loaded at the same time. This will throw an IllegalArgumentException if mzl is less than 1.

Parameters:
mzl - the desired maximum number of zones to be actively loaded, must be greater than 0
Throws:
IllegalArgumentException - if mzl is < 1

zoneWasLoaded

protected void zoneWasLoaded(View zone)
Called by a zone when it gets loaded. This happens when an attempt is made to display or perform a model/view translation on a zone that was in an unloaded state. This is imlemented to check if the maximum number of zones was reached and to unload the oldest zone if so.

Parameters:
zone - the child view that was just loaded.

unloadZone

protected void unloadZone(View zone)
Unload a zone (Convert the zone to its memory saving state). The zones are expected to represent a subset of the child elements of the element this view is responsible for. Therefore, the default implementation is to simple remove all the children.

Parameters:
zone - the child view desired to be set to an unloaded state.

isZoneLoaded

protected boolean isZoneLoaded(View zone)
Determine if a zone is in the loaded state. The zones are expected to represent a subset of the child elements of the element this view is responsible for. Therefore, the default implementation is to return true if the view has children.

createZone

protected View createZone(int p0,
                          int p1)
Create a view to represent a zone for the given range within the model (which should be within the range of this objects responsibility). This is called by the zone management logic to create new zones. Subclasses can provide a different implementation for a zone by changing this method.

Parameters:
p0 - the start of the desired zone. This should be >= getStartOffset() and < getEndOffset(). This value should also be < p1.
p1 - the end of the desired zone. This should be > getStartOffset() and <= getEndOffset(). This value should also be > p0.

loadChildren

protected void loadChildren(ViewFactory f)
Loads all of the children to initialize the view. This is called by the setParent method. This is reimplemented to not load any children directly (as they are created by the zones). This method creates the initial set of zones. Zones don't actually get populated however until an attempt is made to display them or to do model/view coordinate translation.

Overrides:
loadChildren in class CompositeView
Parameters:
f - the view factory
See Also:
CompositeView.setParent(javax.swing.text.View)

getViewIndexAtPosition

protected int getViewIndexAtPosition(int pos)
Returns the child view index representing the given position in the model.

Overrides:
getViewIndexAtPosition in class CompositeView
Parameters:
pos - the position >= 0
Returns:
index of the view representing the given position, or -1 if no view represents that position

updateChildren

protected boolean updateChildren(DocumentEvent.ElementChange ec,
                                 DocumentEvent e,
                                 ViewFactory f)
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. This is reimplemented to do nothing and return false.

Overrides:
updateChildren in class View
Parameters:
ec - the change information for the element this view is responsible for. This should not be null if this method gets called
e - the change information from the associated document
f - the factory to use to build child views
Returns:
whether or not the child views represent the child elements of the element this view is responsible for. Some views create children that represent a portion of the element they are responsible for, and should return false. This information is used to determine if views in the range of the added elements should be forwarded to or not
See Also:
View.insertUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory),
View.removeUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory),
View.changedUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory)

insertUpdate

public void insertUpdate(DocumentEvent changes,
                         Shape a,
                         ViewFactory f)
Gives notification that something was inserted into the document in a location that this view is responsible for. This is largely delegated to the superclass, but is reimplemented to update the relevant zone (i.e. determine if a zone needs to be split into a set of 2 or more zones).

Overrides:
insertUpdate in class View
Parameters:
changes - the change information from the associated document
a - the current allocation of the view
f - the factory to use to rebuild if the view has children
See Also:
View.insertUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory)

removeUpdate

public void removeUpdate(DocumentEvent changes,
                         Shape a,
                         ViewFactory f)
Gives notification that something was removed from the document in a location that this view is responsible for. This is largely delegated to the superclass, but is reimplemented to update the relevant zones (i.e. determine if zones need to be removed or joined with another zone).

Overrides:
removeUpdate in class View
Parameters:
changes - the change information from the associated document
a - the current allocation of the view
f - the factory to use to rebuild if the view has children
See Also:
View.removeUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Uses of Class javax.swing.text.AbstractDocument (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.AbstractDocument

Packages that use AbstractDocument
javax.swing.text | Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.text.html | Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of AbstractDocument in javax.swing.text

Subclasses of AbstractDocument in javax.swing.text
class | DefaultStyledDocument A document that can be marked up with character and paragraph styles in a manner similar to the Rich Text Format.
class | PlainDocument A plain document that maintains no character attributes.

Uses of AbstractDocument in javax.swing.text.html

Subclasses of AbstractDocument in javax.swing.text.html
 class HTMLDocument
A document that models HTML.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.AbstractDocument.AbstractElement (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.AbstractDocument.AbstractElement

Packages that use AbstractDocument.AbstractElement
javax.swing.text | Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.text.html | Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of AbstractDocument.AbstractElement in javax.swing.text

Subclasses of AbstractDocument.AbstractElement in javax.swing.text
class | AbstractDocument.BranchElement Implements a composite element that contains other elements.
class | AbstractDocument.LeafElement Implements an element that directly represents content of some kind.
protected class | DefaultStyledDocument.SectionElement Default root element for a document...

Methods in javax.swing.text that return AbstractDocument.AbstractElement
protected AbstractDocument.AbstractElement | DefaultStyledDocument.createDefaultRoot() Creates the root element to be used to represent the default document structure.
protected AbstractDocument.AbstractElement | PlainDocument.createDefaultRoot() Creates the root element to be used to represent the default document structure.

Uses of AbstractDocument.AbstractElement in javax.swing.text.html

Subclasses of AbstractDocument.AbstractElement in javax.swing.text.html
class | HTMLDocument.BlockElement An element that represents a structural block of HTML.
class | HTMLDocument.RunElement An element that represents a chunk of text that has a set of HTML character level attributes assigned to it.

Methods in javax.swing.text.html that return AbstractDocument.AbstractElement
protected  AbstractDocument.AbstractElement HTMLDocument.createDefaultRoot()
Creates the root element to be used to represent the default document structure.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.swing.text.AbstractDocument.AttributeContext (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.swing.text.AbstractDocument.AttributeContext

Packages that use AbstractDocument.AttributeContext
javax.swing.text | Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.text.html | Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of AbstractDocument.AttributeContext in javax.swing.text

Classes in javax.swing.text that implement AbstractDocument.AttributeContext
 class StyleContext
A pool of styles and their associated resources.

Methods in javax.swing.text that return AbstractDocument.AttributeContext
protected  AbstractDocument.AttributeContext AbstractDocument.getAttributeContext()
Fetches the context for managing attributes.

Constructors in javax.swing.text with parameters of type AbstractDocument.AttributeContext
AbstractDocument(AbstractDocument.Content data, AbstractDocument.AttributeContext context)
Constructs a new AbstractDocument, wrapped around some specified content storage mechanism.

Uses of AbstractDocument.AttributeContext in javax.swing.text.html

Classes in javax.swing.text.html that implement AbstractDocument.AttributeContext
 class StyleSheet
Support for defining the visual characteristics of HTML views being rendered.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.AbstractDocument.BranchElement (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.AbstractDocument.BranchElement

Packages that use AbstractDocument.BranchElement
javax.swing.text | Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.text.html | Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of AbstractDocument.BranchElement in javax.swing.text

Subclasses of AbstractDocument.BranchElement in javax.swing.text
protected  class DefaultStyledDocument.SectionElement
Default root element for a document...

Uses of AbstractDocument.BranchElement in javax.swing.text.html

Subclasses of AbstractDocument.BranchElement in javax.swing.text.html
 class HTMLDocument.BlockElement
An element that represents a structural block of HTML.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.swing.text.AbstractDocument.Content (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.swing.text.AbstractDocument.Content

Packages that use AbstractDocument.Content
javax.swing.text | Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.text.html | Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of AbstractDocument.Content in javax.swing.text

Classes in javax.swing.text that implement AbstractDocument.Content
class | GapContent An implementation of the AbstractDocument.Content interface implemented using a gapped buffer similar to that used by emacs.
class | StringContent An implementation of the AbstractDocument.Content interface that is a brute force implementation that is useful for relatively small documents and/or debugging.

Methods in javax.swing.text that return AbstractDocument.Content
protected  AbstractDocument.Content AbstractDocument.getContent()
Gets the content for the document.

Constructors in javax.swing.text with parameters of type AbstractDocument.Content
DefaultStyledDocument(AbstractDocument.Content c, StyleContext styles)
Constructs a styled document.
PlainDocument(AbstractDocument.Content c)
Constructs a plain text document.
AbstractDocument(AbstractDocument.Content data)
Constructs a new AbstractDocument, wrapped around some specified content storage mechanism.
AbstractDocument(AbstractDocument.Content data, AbstractDocument.AttributeContext context)
Constructs a new AbstractDocument, wrapped around some specified content storage mechanism.

Uses of AbstractDocument.Content in javax.swing.text.html

Constructors in javax.swing.text.html with parameters of type AbstractDocument.Content
HTMLDocument(AbstractDocument.Content c, StyleSheet styles)
Constructs an HTML document with the given content storage implementation and the given style/attribute storage mechanism.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.AbstractDocument.DefaultDocumentEvent (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.AbstractDocument.DefaultDocumentEvent

Packages that use AbstractDocument.DefaultDocumentEvent
javax.swing.text | Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.text.html | Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of AbstractDocument.DefaultDocumentEvent in javax.swing.text

Methods in javax.swing.text with parameters of type AbstractDocument.DefaultDocumentEvent
protected void | DefaultStyledDocument.insertUpdate(AbstractDocument.DefaultDocumentEvent chng, AttributeSet attr) Updates document structure as a result of text insertion.
protected void | DefaultStyledDocument.removeUpdate(AbstractDocument.DefaultDocumentEvent chng) Updates document structure as a result of text removal.
void | DefaultStyledDocument.ElementBuffer.insert(int offset, int length, DefaultStyledDocument.ElementSpec[] data, AbstractDocument.DefaultDocumentEvent de) Inserts new content.
void | DefaultStyledDocument.ElementBuffer.remove(int offset, int length, AbstractDocument.DefaultDocumentEvent de) Removes content.
void | DefaultStyledDocument.ElementBuffer.change(int offset, int length, AbstractDocument.DefaultDocumentEvent de) Changes content.
protected void | PlainDocument.insertUpdate(AbstractDocument.DefaultDocumentEvent chng, AttributeSet attr) Updates document structure as a result of text insertion.
protected void | PlainDocument.removeUpdate(AbstractDocument.DefaultDocumentEvent chng) Updates any document structure as a result of text removal.
protected void | AbstractDocument.insertUpdate(AbstractDocument.DefaultDocumentEvent chng, AttributeSet attr) Updates document structure as a result of text insertion.
protected void | AbstractDocument.removeUpdate(AbstractDocument.DefaultDocumentEvent chng) Updates any document structure as a result of text removal.
protected void | AbstractDocument.postRemoveUpdate(AbstractDocument.DefaultDocumentEvent chng) Updates any document structure as a result of text removal.

Uses of AbstractDocument.DefaultDocumentEvent in javax.swing.text.html

Methods in javax.swing.text.html with parameters of type AbstractDocument.DefaultDocumentEvent
protected  void HTMLDocument.insertUpdate(AbstractDocument.DefaultDocumentEvent chng, AttributeSet attr)
Updates document structure as a result of text insertion.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.AbstractDocument.ElementEdit (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.AbstractDocument.ElementEdit

No usage of javax.swing.text.AbstractDocument.ElementEdit

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.AbstractDocument.LeafElement (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.AbstractDocument.LeafElement

Packages that use AbstractDocument.LeafElement
javax.swing.text.html Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of AbstractDocument.LeafElement in javax.swing.text.html

Subclasses of AbstractDocument.LeafElement in javax.swing.text.html
 class HTMLDocument.RunElement
An element that represents a chunk of text that has a set of HTML character level attributes assigned to it.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.AbstractWriter (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.AbstractWriter

Packages that use AbstractWriter
javax.swing.text.html Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of AbstractWriter in javax.swing.text.html

Subclasses of AbstractWriter in javax.swing.text.html
class | HTMLWriter This is a writer for HTMLDocuments.
class | MinimalHTMLWriter MinimalHTMLWriter is a fallback writer used by the HTMLEditorKit to write out HTML for a document that is a not produced by the EditorKit.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.AsyncBoxView (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.AsyncBoxView

No usage of javax.swing.text.AsyncBoxView

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.AsyncBoxView.ChildLocator (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.AsyncBoxView.ChildLocator

Packages that use AsyncBoxView.ChildLocator
javax.swing.text Provides classes and interfaces that deal with editable and noneditable text components.

Uses of AsyncBoxView.ChildLocator in javax.swing.text

Fields in javax.swing.text declared as AsyncBoxView.ChildLocator
protected  AsyncBoxView.ChildLocator AsyncBoxView.locator
Object that manages the offsets of the children.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.AsyncBoxView.ChildState (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.AsyncBoxView.ChildState

Packages that use AsyncBoxView.ChildState
javax.swing.text Provides classes and interfaces that deal with editable and noneditable text components.

Uses of AsyncBoxView.ChildState in javax.swing.text

Fields in javax.swing.text declared as AsyncBoxView.ChildState
protected  AsyncBoxView.ChildState AsyncBoxView.ChildLocator.lastValidOffset
The location of the last offset calculation that is valid.

Methods in javax.swing.text that return AsyncBoxView.ChildState
protected AsyncBoxView.ChildState | AsyncBoxView.getChildState(int index) Fetch the object representing the layout state of of the child at the given index.
protected AsyncBoxView.ChildState | AsyncBoxView.createChildState(View v) New ChildState records are created through this method to allow subclasses the extend the ChildState records to do/hold more

Methods in javax.swing.text with parameters of type AsyncBoxView.ChildState
protected void | AsyncBoxView.majorRequirementChange(AsyncBoxView.ChildState cs, float delta) Requirements changed along the major axis.
protected void | AsyncBoxView.minorRequirementChange(AsyncBoxView.ChildState cs) Requirements changed along the minor axis.
void | AsyncBoxView.ChildLocator.childChanged(AsyncBoxView.ChildState cs) Notification that a child changed.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.swing.text.AttributeSet (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.swing.text.AttributeSet

Packages that use AttributeSet
java.awt | Contains all of the classes for creating user interfaces and for painting graphics and images.
javax.accessibility | Defines a contract between user-interface components and an assistive technology that provides access to those components.
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.text | Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.text.html | Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of AttributeSet in java.awt

Methods in java.awt that return AttributeSet
 AttributeSet TextComponent.AccessibleAWTTextComponent.getCharacterAttribute(int i)
Returns the AttributeSet for a given character (at a given index).

Uses of AttributeSet in javax.accessibility

Methods in javax.accessibility that return AttributeSet
 AttributeSet AccessibleText.getCharacterAttribute(int i)
Returns the AttributeSet for a given character at a given index

Methods in javax.accessibility with parameters of type AttributeSet
 void AccessibleEditableText.setAttributes(int startIndex, int endIndex, AttributeSet as)
Sets attributes for the text between two indices.

Uses of AttributeSet in javax.swing

Methods in javax.swing that return AttributeSet
AttributeSet | JTextPane.getCharacterAttributes() Fetches the character attributes in effect at the current location of the caret, or null.
AttributeSet | JTextPane.getParagraphAttributes() Fetches the current paragraph attributes in effect at the location of the caret, or null if none.
AttributeSet | JLabel.AccessibleJLabel.getCharacterAttribute(int i) Return the AttributeSet for a given character at a given index
AttributeSet | AbstractButton.AccessibleAbstractButton.getCharacterAttribute(int i) Return the AttributeSet for a given character at a given index

Methods in javax.swing with parameters of type AttributeSet
void | JTextPane.setCharacterAttributes(AttributeSet attr, boolean replace) Applies the given attributes to character content.
void | JTextPane.setParagraphAttributes(AttributeSet attr, boolean replace) Applies the given attributes to paragraphs.

Uses of AttributeSet in javax.swing.text

Subinterfaces of AttributeSet in javax.swing.text
interface | MutableAttributeSet A generic interface for a mutable collection of unique attributes.
interface | Style A collection of attributes to associate with an element in a document.

Classes in javax.swing.text that implement AttributeSet
class | AbstractDocument.AbstractElement Implements the abstract part of an element.
class | AbstractDocument.BranchElement Implements a composite element that contains other elements.
class | AbstractDocument.LeafElement Implements an element that directly represents content of some kind.
protected class | DefaultStyledDocument.SectionElement Default root element for a document...
class | SimpleAttributeSet A straightforward implementation of MutableAttributeSet using a hash table.
class | StyleContext.NamedStyle A collection of attributes, typically used to represent character and paragraph styles.
class | StyleContext.SmallAttributeSet This class holds a small number of attributes in an array.

Fields in javax.swing.text declared as AttributeSet
protected AttributeSet | DefaultStyledDocument.AttributeUndoableEdit.newAttributes
protected AttributeSet | DefaultStyledDocument.AttributeUndoableEdit.copy
static AttributeSet | SimpleAttributeSet.EMPTY An empty attribute set.

Methods in javax.swing.text that return AttributeSet
AttributeSet | StyleContext.addAttribute(AttributeSet old, Object name, Object value) Adds an attribute to the given set, and returns the new representative set.
AttributeSet | StyleContext.addAttributes(AttributeSet old, AttributeSet attr) Adds a set of attributes to the element.
AttributeSet | StyleContext.removeAttribute(AttributeSet old, Object name) Removes an attribute from the set.
AttributeSet | StyleContext.removeAttributes(AttributeSet old, Enumeration names) Removes a set of attributes for the element.
AttributeSet | StyleContext.removeAttributes(AttributeSet old, AttributeSet attrs) Removes a set of attributes for the element.
AttributeSet | StyleContext.getEmptySet() Fetches an empty AttributeSet.
AttributeSet | StyleContext.SmallAttributeSet.copyAttributes() Copies a set of attributes.
AttributeSet | StyleContext.SmallAttributeSet.getResolveParent() If not overriden, the resolving parent defaults to the parent element.
AttributeSet | StyleContext.NamedStyle.copyAttributes() Copies a set of attributes.
AttributeSet | StyleContext.NamedStyle.getResolveParent() Gets attributes from the parent.
AttributeSet | DefaultStyledDocument.ElementSpec.getAttributes() Gets the element attributes.
AttributeSet | SimpleAttributeSet.copyAttributes() Makes a copy of the attributes.
AttributeSet | SimpleAttributeSet.getResolveParent() Gets the resolving parent.
AttributeSet | AbstractDocument.AttributeContext.addAttribute(AttributeSet old, Object name, Object value) Adds an attribute to the given set, and returns the new representative set.
AttributeSet | AbstractDocument.AttributeContext.addAttributes(AttributeSet old, AttributeSet attr) Adds a set of attributes to the element.
AttributeSet | AbstractDocument.AttributeContext.removeAttribute(AttributeSet old, Object name) Removes an attribute from the set.
AttributeSet | AbstractDocument.AttributeContext.removeAttributes(AttributeSet old, Enumeration names) Removes a set of attributes for the element.
AttributeSet | AbstractDocument.AttributeContext.removeAttributes(AttributeSet old, AttributeSet attrs) Removes a set of attributes for the element.
AttributeSet | AbstractDocument.AttributeContext.getEmptySet() Fetches an empty AttributeSet.
AttributeSet | AbstractDocument.AbstractElement.copyAttributes() Copies a set of attributes.
AttributeSet | AbstractDocument.AbstractElement.getResolveParent() Gets the resolving parent.
AttributeSet | AbstractDocument.AbstractElement.getAttributes() Gets the attributes for the element.
AttributeSet | JTextComponent.AccessibleJTextComponent.getCharacterAttribute(int i) Returns the AttributeSet for a given character (at a given index).
AttributeSet | Element.getAttributes() Fetches the collection of attributes this element contains.
AttributeSet | View.getAttributes() Fetches the attributes to use when rendering.
AttributeSet | AttributeSet.copyAttributes() Returns an attribute set that is guaranteed not to change over time.
AttributeSet | AttributeSet.getResolveParent() Gets the resolving parent.

Methods in javax.swing.text with parameters of type AttributeSet
protected void | AbstractWriter.writeAttributes(AttributeSet attr) Writes out the set of attributes as " =" pairs.
protected void | StyledEditorKit.StyledTextAction.setCharacterAttributes(JEditorPane editor, AttributeSet attr, boolean replace) Applies the given attributes to character content.
protected void | StyledEditorKit.StyledTextAction.setParagraphAttributes(JEditorPane editor, AttributeSet attr, boolean replace) Applies the given attributes to paragraphs.
Font | StyleContext.getFont(AttributeSet attr) Gets the font from an attribute set.
Color | StyleContext.getForeground(AttributeSet attr) Takes a set of attributes and turn it into a foreground color specification.
Color | StyleContext.getBackground(AttributeSet attr) Takes a set of attributes and turn it into a background color specification.
AttributeSet | StyleContext.addAttribute(AttributeSet old, Object name, Object value) Adds an attribute to the given set, and returns the new representative set.
AttributeSet | StyleContext.addAttributes(AttributeSet old, AttributeSet attr) Adds a set of attributes to the element.
AttributeSet | StyleContext.removeAttribute(AttributeSet old, Object name) Removes an attribute from the set.
AttributeSet | StyleContext.removeAttributes(AttributeSet old, Enumeration names) Removes a set of attributes for the element.
AttributeSet | StyleContext.removeAttributes(AttributeSet old, AttributeSet attrs) Removes a set of attributes for the element.
void | StyleContext.reclaim(AttributeSet a) Returns a set no longer needed by the MutableAttributeSet implmentation.
protected StyleContext.SmallAttributeSet | StyleContext.createSmallAttributeSet(AttributeSet a) Create a compact set of attributes that might be shared.
protected MutableAttributeSet | StyleContext.createLargeAttributeSet(AttributeSet a) Create a large set of attributes that should trade off space for time.
void | StyleContext.writeAttributes(ObjectOutputStream out, AttributeSet a) Context-specific handling of writing out attributes
static void | StyleContext.writeAttributeSet(ObjectOutputStream out, AttributeSet a) Writes a set of attributes to the given object stream for the purpose of serialization.
boolean | StyleContext.SmallAttributeSet.isEqual(AttributeSet attr) Checks whether two attribute sets are equal.
boolean | StyleContext.SmallAttributeSet.containsAttributes(AttributeSet attrs) Checks whether the attribute set contains all of the given attributes.
boolean | StyleContext.NamedStyle.isEqual(AttributeSet attr) Checks whether two attribute sets are equal.
boolean | StyleContext.NamedStyle.containsAttributes(AttributeSet attrs) Checks whether the element contains all the attributes.
void | StyleContext.NamedStyle.addAttributes(AttributeSet attr) Adds a set of attributes to the element.
void | StyleContext.NamedStyle.removeAttributes(AttributeSet attrs) Removes a set of attributes for the element.
void | StyleContext.NamedStyle.setResolveParent(AttributeSet parent) Sets the resolving parent.
void | DefaultStyledDocument.setCharacterAttributes(int offset, int length, AttributeSet s, boolean replace) Sets attributes for some part of the document.
void | DefaultStyledDocument.setParagraphAttributes(int offset, int length, AttributeSet s, boolean replace) Sets attributes for a paragraph.
protected void | DefaultStyledDocument.insertUpdate(AbstractDocument.DefaultDocumentEvent chng, AttributeSet attr) Updates document structure as a result of text insertion.
Color | DefaultStyledDocument.getForeground(AttributeSet attr) Gets the foreground color from an attribute set.
Color | DefaultStyledDocument.getBackground(AttributeSet attr) Gets the background color from an attribute set.
Font | DefaultStyledDocument.getFont(AttributeSet attr) Gets the font from an attribute set.
boolean | SimpleAttributeSet.isEqual(AttributeSet attr) Compares two attribute sets.
boolean | SimpleAttributeSet.containsAttributes(AttributeSet attributes) Checks whether the attribute list contains all the specified name/value pairs.
void | SimpleAttributeSet.addAttributes(AttributeSet attributes) Adds a set of attributes to the list.
void | SimpleAttributeSet.removeAttributes(AttributeSet attributes) Removes a set of attributes from the list.
void | SimpleAttributeSet.setResolveParent(AttributeSet parent) Sets the resolving parent.
void | PlainDocument.insertString(int offs, String str, AttributeSet a) Inserts some content into the document.
protected void | PlainDocument.insertUpdate(AbstractDocument.DefaultDocumentEvent chng, AttributeSet attr) Updates document structure as a result of text insertion.
void | DocumentFilter.insertString(DocumentFilter.FilterBypass fb, int offset, String string, AttributeSet attr) Invoked prior to insertion of text into the specified Document.
void | DocumentFilter.replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) Invoked prior to replacing a region of text in the specified Document.
abstract void | DocumentFilter.FilterBypass.insertString(int offset, String string, AttributeSet attr) Inserts the specified text, bypassing the DocumentFilter.
abstract void | DocumentFilter.FilterBypass.replace(int offset, int length, String string, AttributeSet attrs) Deletes the region of text from offset to offset + length, and replaces it with text.
void | AbstractDocument.replace(int offset, int length, String text, AttributeSet attrs) Deletes the region of text from offset to offset + length, and replaces it with text.
void | AbstractDocument.insertString(int offs, String str, AttributeSet a) Inserts some content into the document.
protected void | AbstractDocument.insertUpdate(AbstractDocument.DefaultDocumentEvent chng, AttributeSet attr) Updates document structure as a result of text insertion.
protected Element | AbstractDocument.createLeafElement(Element parent, AttributeSet a, int p0, int p1) Creates a document leaf element.
protected Element | AbstractDocument.createBranchElement(Element parent, AttributeSet a) Creates a document branch element, that can contain other elements.
AttributeSet | AbstractDocument.AttributeContext.addAttribute(AttributeSet old, Object name, Object value) Adds an attribute to the given set, and returns the new representative set.
AttributeSet | AbstractDocument.AttributeContext.addAttributes(AttributeSet old, AttributeSet attr) Adds a set of attributes to the element.
AttributeSet | AbstractDocument.AttributeContext.removeAttribute(AttributeSet old, Object name) Removes an attribute from the set.
AttributeSet | AbstractDocument.AttributeContext.removeAttributes(AttributeSet old, Enumeration names) Removes a set of attributes for the element.
AttributeSet | AbstractDocument.AttributeContext.removeAttributes(AttributeSet old, AttributeSet attrs) Removes a set of attributes for the element.
void | AbstractDocument.AttributeContext.reclaim(AttributeSet a) Reclaims an attribute set.
boolean | AbstractDocument.AbstractElement.isEqual(AttributeSet attr) Checks whether two attribute sets are equal.
boolean | AbstractDocument.AbstractElement.containsAttributes(AttributeSet attrs) Checks whether the element contains all the attributes.
void | AbstractDocument.AbstractElement.addAttributes(AttributeSet attr) Adds a set of attributes to the element.
void | AbstractDocument.AbstractElement.removeAttributes(AttributeSet attrs) Removes a set of attributes for the element.
void | AbstractDocument.AbstractElement.setResolveParent(AttributeSet parent) Sets the resolving parent.
void | StyledDocument.setCharacterAttributes(int offset, int length, AttributeSet s, boolean replace) Changes the content element attributes used for the given range of existing content in the document.
void | StyledDocument.setParagraphAttributes(int offset, int length, AttributeSet s, boolean replace) Sets paragraph attributes.
Color | StyledDocument.getForeground(AttributeSet attr) Takes a set of attributes and turn it into a foreground color specification.
Color | StyledDocument.getBackground(AttributeSet attr) Takes a set of attributes and turn it into a background color specification.
Font | StyledDocument.getFont(AttributeSet attr) Takes a set of attributes and turn it into a font specification.
protected void | CompositeView.setParagraphInsets(AttributeSet attr) Sets the insets from the paragraph attributes specified in the given attributes.
void | JTextComponent.AccessibleJTextComponent.setAttributes(int startIndex, int endIndex, AttributeSet as) Sets attributes for the text between two indices.
void | MutableAttributeSet.addAttributes(AttributeSet attributes) Creates a new attribute set similar to this one except that it contains the given attributes and values.
void | MutableAttributeSet.removeAttributes(AttributeSet attributes) Removes a set of attributes with the given name.
void | MutableAttributeSet.setResolveParent(AttributeSet parent) Sets the resolving parent.
static int | StyleConstants.getBidiLevel(AttributeSet a) Gets the BidiLevel setting.
static Component | StyleConstants.getComponent(AttributeSet a) Gets the component setting from the attribute list.
static Icon | StyleConstants.getIcon(AttributeSet a) Gets the icon setting from the attribute list.
static String | StyleConstants.getFontFamily(AttributeSet a) Gets the font family setting from the attribute list.
static int | StyleConstants.getFontSize(AttributeSet a) Gets the font size setting from the attribute list.
static boolean | StyleConstants.isBold(AttributeSet a) Checks whether the bold attribute is set.
static boolean | StyleConstants.isItalic(AttributeSet a) Checks whether the italic attribute is set.
static boolean | StyleConstants.isUnderline(AttributeSet a) Checks whether the underline attribute is set.
static boolean | StyleConstants.isStrikeThrough(AttributeSet a) Checks whether the strikethrough attribute is set.
static boolean | StyleConstants.isSuperscript(AttributeSet a) Checks whether the superscript attribute is set.
static boolean | StyleConstants.isSubscript(AttributeSet a) Checks whether the subscript attribute is set.
static Color | StyleConstants.getForeground(AttributeSet a) Gets the foreground color setting from the attribute list.
static Color | StyleConstants.getBackground(AttributeSet a) Gets the background color setting from the attribute list.
static float | StyleConstants.getFirstLineIndent(AttributeSet a) Gets the first line indent setting.
static float | StyleConstants.getRightIndent(AttributeSet a) Gets the right indent setting.
static float | StyleConstants.getLeftIndent(AttributeSet a) Gets the left indent setting.
static float | StyleConstants.getLineSpacing(AttributeSet a) Gets the line spacing setting.
static float | StyleConstants.getSpaceAbove(AttributeSet a) Gets the space above setting.
static float | StyleConstants.getSpaceBelow(AttributeSet a) Gets the space below setting.
static int | StyleConstants.getAlignment(AttributeSet a) Gets the alignment setting.
static TabSet | StyleConstants.getTabSet(AttributeSet a) Gets the TabSet.
void | Document.insertString(int offset, String str, AttributeSet a) Inserts a string of content.
boolean | AttributeSet.isEqual(AttributeSet attr) Determines if the two attribute sets are equivalent.
boolean | AttributeSet.containsAttributes(AttributeSet attributes) Returns true if this set contains all the attributes with equal values.

Constructors in javax.swing.text with parameters of type AttributeSet
StyleContext.SmallAttributeSet(AttributeSet attrs)
DefaultStyledDocument.ElementSpec(AttributeSet a, short type)
Constructor useful for markup when the markup will not be stored in the document.
DefaultStyledDocument.ElementSpec(AttributeSet a, short type, int len)
Constructor for parsing inside the document when the data has already been added, but len information is needed.
DefaultStyledDocument.ElementSpec(AttributeSet a, short type, char[] txt, int offs, int len)
Constructor for creating a spec externally for batch input of content and markup into the document.
DefaultStyledDocument.AttributeUndoableEdit(Element element, AttributeSet newAttributes, boolean isReplacing)
SimpleAttributeSet(AttributeSet source)
Creates a new attribute set based on a supplied set of attributes.
AbstractDocument.AbstractElement(Element parent, AttributeSet a)
Creates a new AbstractElement.
AbstractDocument.BranchElement(Element parent, AttributeSet a)
Constructs a composite element that initially contains no children.
AbstractDocument.LeafElement(Element parent, AttributeSet a, int offs0, int offs1)
Constructs an element that represents content within the document (has no children).

Uses of AttributeSet in javax.swing.text.html

Classes in javax.swing.text.html that implement AttributeSet
class | HTMLDocument.BlockElement An element that represents a structural block of HTML.
class | HTMLDocument.RunElement An element that represents a chunk of text that has a set of HTML character level attributes assigned to it.

Methods in javax.swing.text.html that return AttributeSet
AttributeSet | ImageView.getAttributes() Fetches the attributes to use when rendering.
AttributeSet | ParagraphView.getAttributes() Fetches the attributes to use when rendering.
AttributeSet | InlineView.getAttributes() Fetches the attributes to use when rendering.
AttributeSet | BlockView.getAttributes() Fetches the attributes to use when rendering.
AttributeSet | Option.getAttributes() Fetch the attributes associated with this option.
AttributeSet | StyleSheet.getDeclaration(String decl) Translates a CSS declaration to an AttributeSet that represents the CSS declaration.
AttributeSet | StyleSheet.getViewAttributes(View v) Fetches a set of attributes to use in the view for displaying.
AttributeSet | StyleSheet.translateHTMLToCSS(AttributeSet htmlAttrSet) Converts a set of HTML attributes to an equivalent set of CSS attributes.
AttributeSet | StyleSheet.addAttribute(AttributeSet old, Object key, Object value) Adds an attribute to the given set, and returns the new representative set.
AttributeSet | StyleSheet.addAttributes(AttributeSet old, AttributeSet attr) Adds a set of attributes to the element.
AttributeSet | StyleSheet.removeAttribute(AttributeSet old, Object key) Removes an attribute from the set.
AttributeSet | StyleSheet.removeAttributes(AttributeSet old, Enumeration names) Removes a set of attributes for the element.
AttributeSet | StyleSheet.removeAttributes(AttributeSet old, AttributeSet attrs) Removes a set of attributes.
abstract AttributeSet | HTMLDocument.Iterator.getAttributes() Return the attributes for this tag.
AttributeSet | HTMLDocument.RunElement.getResolveParent() Gets the resolving parent.
AttributeSet | HTMLDocument.BlockElement.getResolveParent() Gets the resolving parent.

Methods in javax.swing.text.html with parameters of type AttributeSet
protected void | MinimalHTMLWriter.writeAttributes(AttributeSet attr) Writes out all the attributes for the following types: StyleConstants.ParagraphConstants, StyleConstants.CharacterConstants, StyleConstants.FontConstants, StyleConstants.ColorConstants.
protected void | MinimalHTMLWriter.writeHTMLTags(AttributeSet attr) Generates bold <b>, italic <i>, and <u> tags for the text based on its attribute settings.
protected void | MinimalHTMLWriter.writeNonHTMLAttributes(AttributeSet attr) Writes out the remaining character-level attributes (attributes other than bold, italic, and underline) in an HTML-compliant way.
protected void | HTMLWriter.writeAttributes(AttributeSet attr) Writes out the attribute set.
protected boolean | HTMLWriter.isBlockTag(AttributeSet attr) Determines if the HTML.Tag associated with the element is a block tag.
protected void | HTMLWriter.textAreaContent(AttributeSet attr) Writes out text that is contained in a TEXTAREA form element.
protected void | HTMLWriter.selectContent(AttributeSet attr) Writes out the content of the SELECT form element.
protected boolean | HTMLWriter.matchNameAttribute(AttributeSet attr, HTML.Tag tag) Returns true if the StyleConstants.NameAttribute is equal to the tag that is passed in as a parameter.
protected void | HTMLWriter.writeEmbeddedTags(AttributeSet attr) Searches for embedded tags in the AttributeSet and writes them out.
protected void | HTMLWriter.closeOutUnwantedEmbeddedTags(AttributeSet attr) Searches the attribute set and for each tag that is stored in the tag vector.
static int | HTML.getIntegerAttributeValue(AttributeSet attr, HTML.Attribute key, int def) Fetches an integer attribute value.
AttributeSet | StyleSheet.translateHTMLToCSS(AttributeSet htmlAttrSet) Converts a set of HTML attributes to an equivalent set of CSS attributes.
AttributeSet | StyleSheet.addAttribute(AttributeSet old, Object key, Object value) Adds an attribute to the given set, and returns the new representative set.
AttributeSet | StyleSheet.addAttributes(AttributeSet old, AttributeSet attr) Adds a set of attributes to the element.
AttributeSet | StyleSheet.removeAttribute(AttributeSet old, Object key) Removes an attribute from the set.
AttributeSet | StyleSheet.removeAttributes(AttributeSet old, Enumeration names) Removes a set of attributes for the element.
AttributeSet | StyleSheet.removeAttributes(AttributeSet old, AttributeSet attrs) Removes a set of attributes.
protected StyleContext.SmallAttributeSet | StyleSheet.createSmallAttributeSet(AttributeSet a) Creates a compact set of attributes that might be shared.
protected MutableAttributeSet | StyleSheet.createLargeAttributeSet(AttributeSet a) Creates a large set of attributes that should trade off space for time.
Font | StyleSheet.getFont(AttributeSet a) Fetches the font to use for the given set of attributes.
Color | StyleSheet.getForeground(AttributeSet a) Takes a set of attributes and turn it into a foreground color specification.
Color | StyleSheet.getBackground(AttributeSet a) Takes a set of attributes and turn it into a background color specification.
StyleSheet.BoxPainter | StyleSheet.getBoxPainter(AttributeSet a) Fetches the box formatter to use for the given set of CSS attributes.
StyleSheet.ListPainter | StyleSheet.getListPainter(AttributeSet a) Fetches the list formatter to use for the given set of CSS attributes.
protected void | HTMLDocument.insertUpdate(AbstractDocument.DefaultDocumentEvent chng, AttributeSet attr) Updates document structure as a result of text insertion.
void | HTMLDocument.setParagraphAttributes(int offset, int length, AttributeSet s, boolean replace) Sets attributes for a paragraph.
protected Element | HTMLDocument.createLeafElement(Element parent, AttributeSet a, int p0, int p1) Creates a document leaf element that directly represents text (doesn't have any children).
protected Element | HTMLDocument.createBranchElement(Element parent, AttributeSet a) Creates a document branch element, that can contain other elements.

Constructors in javax.swing.text.html with parameters of type AttributeSet
Option(AttributeSet attr)
Creates a new Option object.
HTMLDocument.RunElement(Element parent, AttributeSet a, int offs0, int offs1)
Constructs an element that represents content within the document (has no children).
HTMLDocument.BlockElement(Element parent, AttributeSet a)
Constructs a composite element that initially contains no children.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.swing.text.AttributeSet.CharacterAttribute (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.swing.text.AttributeSet.CharacterAttribute

Packages that use AttributeSet.CharacterAttribute
javax.swing.text Provides classes and interfaces that deal with editable and noneditable text components.

Uses of AttributeSet.CharacterAttribute in javax.swing.text

Classes in javax.swing.text that implement AttributeSet.CharacterAttribute
static class | StyleConstants.CharacterConstants This is a typesafe enumeration of the well-known attributes that contribute to a character style.
static class | StyleConstants.ColorConstants This is a typesafe enumeration of the well-known attributes that contribute to a color.
static class | StyleConstants.FontConstants This is a typesafe enumeration of the well-known attributes that contribute to a font.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.swing.text.AttributeSet.ColorAttribute (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.swing.text.AttributeSet.ColorAttribute

Packages that use AttributeSet.ColorAttribute
javax.swing.text Provides classes and interfaces that deal with editable and noneditable text components.

Uses of AttributeSet.ColorAttribute in javax.swing.text

Classes in javax.swing.text that implement AttributeSet.ColorAttribute
static class StyleConstants.ColorConstants
This is a typesafe enumeration of the well-known attributes that contribute to a color.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.swing.text.AttributeSet.FontAttribute (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.swing.text.AttributeSet.FontAttribute

Packages that use AttributeSet.FontAttribute
javax.swing.text Provides classes and interfaces that deal with editable and noneditable text components.

Uses of AttributeSet.FontAttribute in javax.swing.text

Classes in javax.swing.text that implement AttributeSet.FontAttribute
static class StyleConstants.FontConstants
This is a typesafe enumeration of the well-known attributes that contribute to a font.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.swing.text.AttributeSet.ParagraphAttribute (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.swing.text.AttributeSet.ParagraphAttribute

Packages that use AttributeSet.ParagraphAttribute
javax.swing.text Provides classes and interfaces that deal with editable and noneditable text components.

Uses of AttributeSet.ParagraphAttribute in javax.swing.text

Classes in javax.swing.text that implement AttributeSet.ParagraphAttribute
static class StyleConstants.ParagraphConstants
This is a typesafe enumeration of the well-known attributes that contribute to a paragraph style.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.BadLocationException (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.BadLocationException

Packages that use BadLocationException
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.plaf | Provides one interface and many abstract classes that Swing uses to provide its pluggable look-and-feel capabilities.
javax.swing.plaf.basic | Provides user interface objects built according to the Basic look and feel.
javax.swing.plaf.multi | Provides user interface objects that combine two or more look and feels.
javax.swing.text | Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.text.html | Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.
javax.swing.text.rtf | Provides a class (RTFEditorKit) for creating Rich-Text-Format text editors.

Uses of BadLocationException in javax.swing

Methods in javax.swing that throw BadLocationException
String | JPasswordField.getText(int offs, int len) Deprecated. As of Java 2 platform v1.2, replaced by getPassword.
int | JTextArea.getLineOfOffset(int offset) Translates an offset into the components text to a line number.
int | JTextArea.getLineStartOffset(int line) Determines the offset of the start of the given line.
int | JTextArea.getLineEndOffset(int line) Determines the offset of the end of the given line.

Uses of BadLocationException in javax.swing.plaf

Methods in javax.swing.plaf that throw BadLocationException
abstract Rectangle | TextUI.modelToView(JTextComponent t, int pos) Converts the given location in the model to a place in the view coordinate system.
abstract Rectangle | TextUI.modelToView(JTextComponent t, int pos, Position.Bias bias) Converts the given location in the model to a place in the view coordinate system.
abstract int | TextUI.getNextVisualPositionFrom(JTextComponent t, int pos, Position.Bias b, int direction, Position.Bias[] biasRet) Provides a way to determine the next visually represented model location that one might place a caret.

Uses of BadLocationException in javax.swing.plaf.basic

Methods in javax.swing.plaf.basic that throw BadLocationException
Rectangle | BasicTextUI.modelToView(JTextComponent tc, int pos) Converts the given location in the model to a place in the view coordinate system.
Rectangle | BasicTextUI.modelToView(JTextComponent tc, int pos, Position.Bias bias) Converts the given location in the model to a place in the view coordinate system.
int | BasicTextUI.getNextVisualPositionFrom(JTextComponent t, int pos, Position.Bias b, int direction, Position.Bias[] biasRet) Provides a way to determine the next visually represented model location that one might place a caret.

Uses of BadLocationException in javax.swing.plaf.multi

Methods in javax.swing.plaf.multi that throw BadLocationException
Rectangle | MultiTextUI.modelToView(JTextComponent a, int b) Invokes the modelToView method on each UI handled by this object.
Rectangle | MultiTextUI.modelToView(JTextComponent a, int b, Position.Bias c) Invokes the modelToView method on each UI handled by this object.
int | MultiTextUI.getNextVisualPositionFrom(JTextComponent a, int b, Position.Bias c, int d, Position.Bias[] e) Invokes the getNextVisualPositionFrom method on each UI handled by this object.

Uses of BadLocationException in javax.swing.text

Methods in javax.swing.text that throw BadLocationException
UndoableEdit | StringContent.insertString(int where, String str) Inserts a string into the content.
UndoableEdit | StringContent.remove(int where, int nitems) Removes part of the content.
String | StringContent.getString(int where, int len) Retrieves a portion of the content.
void | StringContent.getChars(int where, int len, Segment chars) Retrieves a portion of the content.
Position | StringContent.createPosition(int offset) Creates a position within the content that will track change as the content is mutated.
protected int | PasswordView.drawUnselectedText(Graphics g, int x, int y, int p0, int p1) Renders the given range in the model as normal unselected text.
protected int | PasswordView.drawSelectedText(Graphics g, int x, int y, int p0, int p1) Renders the given range in the model as selected text.
Shape | PasswordView.modelToView(int pos, Shape a, Position.Bias b) Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
protected int | PlainView.drawUnselectedText(Graphics g, int x, int y, int p0, int p1) Renders the given range in the model as normal unselected text.
protected int | PlainView.drawSelectedText(Graphics g, int x, int y, int p0, int p1) Renders the given range in the model as selected text.
Shape | PlainView.modelToView(int pos, Shape a, Position.Bias b) Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
Shape | FieldView.modelToView(int pos, Shape a, Position.Bias b) Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
Shape | AsyncBoxView.modelToView(int pos, Shape a, Position.Bias b) Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
int | AsyncBoxView.getNextVisualPositionFrom(int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet) Provides a way to determine the next visually represented model location that one might place a caret.
protected abstract void | AbstractWriter.write() This abstract method needs to be implemented by subclasses.
protected String | AbstractWriter.getText(Element elem) Returns the text associated with the element.
protected void | AbstractWriter.text(Element elem) Writes out text.
Shape | IconView.modelToView(int pos, Shape a, Position.Bias b) Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
Shape | ComponentView.modelToView(int pos, Shape a, Position.Bias b) Provides a mapping from the coordinate space of the model to that of the view.
UndoableEdit | GapContent.insertString(int where, String str) Inserts a string into the content.
UndoableEdit | GapContent.remove(int where, int nitems) Removes part of the content.
String | GapContent.getString(int where, int len) Retrieves a portion of the content.
void | GapContent.getChars(int where, int len, Segment chars) Retrieves a portion of the content.
Position | GapContent.createPosition(int offset) Creates a position within the content that will track change as the content is mutated.
protected int | WrappedPlainView.drawUnselectedText(Graphics g, int x, int y, int p0, int p1) Renders the given range in the model as normal unselected text.
protected int | WrappedPlainView.drawSelectedText(Graphics g, int x, int y, int p0, int p1) Renders the given range in the model as selected text.
protected void | DefaultStyledDocument.insert(int offset, DefaultStyledDocument.ElementSpec[] data) Inserts new elements in bulk.
Object | DefaultHighlighter.addHighlight(int p0, int p1, Highlighter.HighlightPainter p) Adds a highlight to the view.
void | DefaultHighlighter.changeHighlight(Object tag, int p0, int p1) Changes a highlight.
void | PlainDocument.insertString(int offs, String str, AttributeSet a) Inserts some content into the document.
void | DocumentFilter.remove(DocumentFilter.FilterBypass fb, int offset, int length) Invoked prior to removal of the specified region in the specified Document.
void | DocumentFilter.insertString(DocumentFilter.FilterBypass fb, int offset, String string, AttributeSet attr) Invoked prior to insertion of text into the specified Document.
void | DocumentFilter.replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) Invoked prior to replacing a region of text in the specified Document.
abstract void | DocumentFilter.FilterBypass.remove(int offset, int length) Removes the specified region of text, bypassing the DocumentFilter.
abstract void | DocumentFilter.FilterBypass.insertString(int offset, String string, AttributeSet attr) Inserts the specified text, bypassing the DocumentFilter.
abstract void | DocumentFilter.FilterBypass.replace(int offset, int length, String string, AttributeSet attrs) Deletes the region of text from offset to offset + length, and replaces it with text.
void | AbstractDocument.remove(int offs, int len) Removes some content from the document.
void | AbstractDocument.replace(int offset, int length, String text, AttributeSet attrs) Deletes the region of text from offset to offset + length, and replaces it with text.
void | AbstractDocument.insertString(int offs, String str, AttributeSet a) Inserts some content into the document.
String | AbstractDocument.getText(int offset, int length) Gets a sequence of text from the document.
void | AbstractDocument.getText(int offset, int length, Segment txt) Fetches the text contained within the given portion of the document.
Position | AbstractDocument.createPosition(int offs) Returns a position that will track change as the document is altered.
Position | AbstractDocument.Content.createPosition(int offset) Creates a position within the content that will track change as the content is mutated.
UndoableEdit | AbstractDocument.Content.insertString(int where, String str) Inserts a string of characters into the sequence.
UndoableEdit | AbstractDocument.Content.remove(int where, int nitems) Removes some portion of the sequence.
String | AbstractDocument.Content.getString(int where, int len) Fetches a string of characters contained in the sequence.
void | AbstractDocument.Content.getChars(int where, int len, Segment txt) Gets a sequence of characters and copies them into a Segment.
Shape | GlyphView.modelToView(int pos, Shape a, Position.Bias b) Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
int | GlyphView.getNextVisualPositionFrom(int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet) Provides a way to determine the next visually represented model location that one might place a caret.
abstract Shape | GlyphView.GlyphPainter.modelToView(GlyphView v, int pos, Position.Bias bias, Shape a) Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
int | GlyphView.GlyphPainter.getNextVisualPositionFrom(GlyphView v, int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet) Provides a way to determine the next visually represented model location that one might place a caret.
static int | Utilities.getRowStart(JTextComponent c, int offs) Determines the starting row model position of the row that contains the specified model position.
static int | Utilities.getRowEnd(JTextComponent c, int offs) Determines the ending row model position of the row that contains the specified model position.
static int | Utilities.getPositionAbove(JTextComponent c, int offs, int x) Determines the position in the model that is closest to the given view location in the row above.
static int | Utilities.getPositionBelow(JTextComponent c, int offs, int x) Determines the position in the model that is closest to the given view location in the row below.
static int | Utilities.getWordStart(JTextComponent c, int offs) Determines the start of a word for the given model location.
static int | Utilities.getWordEnd(JTextComponent c, int offs) Determines the end of a word for the given location.
static int | Utilities.getNextWord(JTextComponent c, int offs) Determines the start of the next word for the given location.
static int | Utilities.getPreviousWord(JTextComponent c, int offs) Determine the start of the prev word for the given location.
Shape | CompositeView.modelToView(int pos, Shape a, Position.Bias b) Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
Shape | CompositeView.modelToView(int p0, Position.Bias b0, int p1, Position.Bias b1, Shape a) Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
int | CompositeView.getNextVisualPositionFrom(int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet) Provides a way to determine the next visually represented model location that one might place a caret.
protected int | CompositeView.getNextNorthSouthVisualPositionFrom(int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet) Returns the next visual position for the cursor, in either the north or south direction.
protected int | CompositeView.getNextEastWestVisualPositionFrom(int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet) Returns the next visual position for the cursor, in either the east or west direction.
Shape | BoxView.modelToView(int pos, Shape a, Position.Bias b) Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
void | DefaultEditorKit.read(InputStream in, Document doc, int pos) Inserts content from the given stream which is expected to be in a format appropriate for this kind of content handler.
void | DefaultEditorKit.write(OutputStream out, Document doc, int pos, int len) Writes content from a document to the given stream in a format appropriate for this kind of content handler.
void | DefaultEditorKit.read(Reader in, Document doc, int pos) Inserts content from the given stream, which will be treated as plain text.
void | DefaultEditorKit.write(Writer out, Document doc, int pos, int len) Writes content from a document to the given stream as plain text.
protected int | ParagraphView.getNextNorthSouthVisualPositionFrom(int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet) Returns the next visual position for the cursor, in either the east or west direction.
protected int | ParagraphView.getClosestPositionTo(int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet, int rowIndex, int x) Returns the closest model position to x.
abstract void | EditorKit.read(InputStream in, Document doc, int pos) Inserts content from the given stream which is expected to be in a format appropriate for this kind of content handler.
abstract void | EditorKit.write(OutputStream out, Document doc, int pos, int len) Writes content from a document to the given stream in a format appropriate for this kind of content handler.
abstract void | EditorKit.read(Reader in, Document doc, int pos) Inserts content from the given stream which is expected to be in a format appropriate for this kind of content handler.
abstract void | EditorKit.write(Writer out, Document doc, int pos, int len) Writes content from a document to the given stream in a format appropriate for this kind of content handler.
Object | Highlighter.addHighlight(int p0, int p1, Highlighter.HighlightPainter p) Adds a highlight to the view.
void | Highlighter.changeHighlight(Object tag, int p0, int p1) Changes the given highlight to span a different portion of the document.
int | NavigationFilter.getNextVisualPositionFrom(JTextComponent text, int pos, Position.Bias bias, int direction, Position.Bias[] biasRet) Returns the next visual position to place the caret at from an existing position.
String | JTextComponent.getText(int offs, int len) Fetches a portion of the text represented by the component.
Rectangle | JTextComponent.modelToView(int pos) Converts the given location in the model to a place in the view coordinate system.
void | Document.remove(int offs, int len) Removes a portion of the content of the document.
void | Document.insertString(int offset, String str, AttributeSet a) Inserts a string of content.
String | Document.getText(int offset, int length) Fetches the text contained within the given portion of the document.
void | Document.getText(int offset, int length, Segment txt) Fetches the text contained within the given portion of the document.
Position | Document.createPosition(int offs) This method allows an application to mark a place in a sequence of character content.
int | View.getNextVisualPositionFrom(int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet) Provides a way to determine the next visually represented model location at which one might place a caret.
abstract Shape | View.modelToView(int pos, Shape a, Position.Bias b) Provides a mapping, for a given character, from the document model coordinate space to the view coordinate space.
Shape | View.modelToView(int p0, Position.Bias b0, int p1, Position.Bias b1, Shape a) Provides a mapping, for a given region, from the document model coordinate space to the view coordinate space.
Shape | View.modelToView(int pos, Shape a) Deprecated.

Uses of BadLocationException in javax.swing.text.html

Methods in javax.swing.text.html that throw BadLocationException
Shape | ImageView.modelToView(int pos, Shape a, Position.Bias b) Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
void | MinimalHTMLWriter.write() Generates HTML output from a StyledDocument.
protected void | MinimalHTMLWriter.text(Element elem) Writes out text.
protected void | MinimalHTMLWriter.writeBody() Iterates over the elements in the document and processes elements based on whether they are branch elements or leaf elements.
protected void | MinimalHTMLWriter.writeContent(Element elem, boolean needsIndenting) Writes out the attribute set in an HTML-compliant manner.
void | HTMLWriter.write() Iterates over the Element tree and controls the writing out of all the tags and its attributes.
protected void | HTMLWriter.emptyTag(Element elem) Writes out all empty elements (all tags that have no corresponding end tag).
protected void | HTMLWriter.startTag(Element elem) Writes out a start tag for the element.
protected void | HTMLWriter.textAreaContent(AttributeSet attr) Writes out text that is contained in a TEXTAREA form element.
protected void | HTMLWriter.text(Element elem) Writes out text.
protected void | HTMLWriter.comment(Element elem) Writes out comments.
void | HTMLEditorKit.read(Reader in, Document doc, int pos) Inserts content from the given stream.
void | HTMLEditorKit.insertHTML(HTMLDocument doc, int offset, String html, int popDepth, int pushDepth, HTML.Tag insertTag) Inserts HTML into an existing document.
void | HTMLEditorKit.write(Writer out, Document doc, int pos, int len) Write content from a document to the given stream in a format appropriate for this kind of content handler.
void | HTMLEditorKit.ParserCallback.flush()
protected void | HTMLDocument.insert(int offset, DefaultStyledDocument.ElementSpec[] data) Inserts new elements in bulk.
void | HTMLDocument.setInnerHTML(Element elem, String htmlText) Replaces the children of the given element with the contents specified as an HTML string.
void | HTMLDocument.setOuterHTML(Element elem, String htmlText) Replaces the given element in the parent with the contents specified as an HTML string.
void | HTMLDocument.insertAfterStart(Element elem, String htmlText) Inserts the HTML specified as a string at the start of the element.
void | HTMLDocument.insertBeforeEnd(Element elem, String htmlText) Inserts the HTML specified as a string at the end of the element.
void | HTMLDocument.insertBeforeStart(Element elem, String htmlText) Inserts the HTML specified as a string before the start of the given element.
void | HTMLDocument.insertAfterEnd(Element elem, String htmlText) Inserts the HTML specified as a string after the the end of the given element.
void | HTMLDocument.HTMLReader.flush() The last method called on the reader.

Uses of BadLocationException in javax.swing.text.rtf

Methods in javax.swing.text.rtf that throw BadLocationException
void | RTFEditorKit.read(InputStream in, Document doc, int pos) Insert content from the given stream which is expected to be in a format appropriate for this kind of content handler.
void | RTFEditorKit.write(OutputStream out, Document doc, int pos, int len) Write content from a document to the given stream in a format appropriate for this kind of content handler.
void | RTFEditorKit.read(Reader in, Document doc, int pos) Insert content from the given stream, which will be treated as plain text.
void | RTFEditorKit.write(Writer out, Document doc, int pos, int len) Write content from a document to the given stream as plain text.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.BoxView (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.BoxView

Packages that use BoxView
javax.swing.text | Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.text.html | Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of BoxView in javax.swing.text

Subclasses of BoxView in javax.swing.text
class | FlowView A View that tries to flow it's children into some partially constrained space.
class | ParagraphView View of a simple line-wrapping paragraph that supports multiple fonts, colors, components, icons, etc.
class | TableView 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.
class | TableView.TableCell Deprecated. A table cell can now be any View implementation.
class | TableView.TableRow View of a row in a row-centric table.
class | WrappedPlainView View of plain text (text with only one font and color) that does line-wrapping.
class | ZoneView 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.

Uses of BoxView in javax.swing.text.html

Subclasses of BoxView in javax.swing.text.html
class | BlockView A view implementation to display a block (as a box) with CSS specifications.
class | ListView A view implementation to display an html list

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.swing.text.Caret (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.swing.text.Caret

Packages that use Caret
javax.swing.plaf.basic | Provides user interface objects built according to the Basic look and feel.
javax.swing.text | Provides classes and interfaces that deal with editable and noneditable text components.

Uses of Caret in javax.swing.plaf.basic

Classes in javax.swing.plaf.basic that implement Caret
static class BasicTextUI.BasicCaret

Methods in javax.swing.plaf.basic that return Caret
protected  Caret BasicTextUI.createCaret()
Creates the object to use for a caret.

Uses of Caret in javax.swing.text

Classes in javax.swing.text that implement Caret
 class DefaultCaret
A default implementation of Caret.

Methods in javax.swing.text that return Caret
Caret | DefaultEditorKit.createCaret() Fetches a caret that can navigate through views produced by the associated ViewFactory.
abstract Caret | EditorKit.createCaret() Fetches a caret that can navigate through views produced by the associated ViewFactory.
abstract Caret | NavigationFilter.FilterBypass.getCaret() Returns the Caret that is changing.
Caret | JTextComponent.getCaret() Fetches the caret that allows text-oriented navigation over the view.

Methods in javax.swing.text with parameters of type Caret
 void JTextComponent.setCaret(Caret c)
Sets the caret to be used.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.ChangedCharSetException (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.ChangedCharSetException

Packages that use ChangedCharSetException
javax.swing.text.html.parser Provides the default HTML parser, along with support classes.

Uses of ChangedCharSetException in javax.swing.text.html.parser

Methods in javax.swing.text.html.parser that throw ChangedCharSetException
protected void | Parser.handleEmptyTag(TagElement tag) Called when an empty tag is encountered.
protected void | Parser.startTag(TagElement tag) Handle a start tag.
protected void | DocumentParser.handleEmptyTag(TagElement tag) Handle Empty Tag.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.ComponentView (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.ComponentView

Packages that use ComponentView
javax.swing.text.html Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of ComponentView in javax.swing.text.html

Subclasses of ComponentView in javax.swing.text.html
class | FormView Component decorator that implements the view interface for form elements, <input>, <textarea>, and <select>.
class | ObjectView Component decorator that implements the view interface for <object> elements.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.CompositeView (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.CompositeView

Packages that use CompositeView
javax.swing.text | Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.text.html | Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of CompositeView in javax.swing.text

Subclasses of CompositeView in javax.swing.text
class | BoxView A view that arranges its children into a box shape by tiling its children along an axis.
class | FlowView A View that tries to flow it's children into some partially constrained space.
class | ParagraphView View of a simple line-wrapping paragraph that supports multiple fonts, colors, components, icons, etc.
class | TableView 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.
class | TableView.TableCell Deprecated. A table cell can now be any View implementation.
class | TableView.TableRow View of a row in a row-centric table.
class | WrappedPlainView View of plain text (text with only one font and color) that does line-wrapping.
class | ZoneView 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.

Uses of CompositeView in javax.swing.text.html

Subclasses of CompositeView in javax.swing.text.html
class | BlockView A view implementation to display a block (as a box) with CSS specifications.
class | ListView A view implementation to display an html list

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.DateFormatter (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.DateFormatter

No usage of javax.swing.text.DateFormatter

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.DefaultCaret (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.DefaultCaret

Packages that use DefaultCaret
javax.swing.plaf.basic Provides user interface objects built according to the Basic look and feel.

Uses of DefaultCaret in javax.swing.plaf.basic

Subclasses of DefaultCaret in javax.swing.plaf.basic
static class BasicTextUI.BasicCaret

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.DefaultEditorKit (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.DefaultEditorKit

Packages that use DefaultEditorKit
javax.swing.text | Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.text.html | Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.
javax.swing.text.rtf | Provides a class (RTFEditorKit) for creating Rich-Text-Format text editors.

Uses of DefaultEditorKit in javax.swing.text

Subclasses of DefaultEditorKit in javax.swing.text
 class StyledEditorKit
This is the set of things needed by a text component to be a reasonably functioning editor for some type of text document.

Uses of DefaultEditorKit in javax.swing.text.html

Subclasses of DefaultEditorKit in javax.swing.text.html
 class HTMLEditorKit
The Swing JEditorPane text component supports different kinds of content via a plug-in mechanism called an EditorKit.

Uses of DefaultEditorKit in javax.swing.text.rtf

Subclasses of DefaultEditorKit in javax.swing.text.rtf
 class RTFEditorKit
This is the default implementation of RTF editing functionality.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.DefaultEditorKit.BeepAction (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.DefaultEditorKit.BeepAction

No usage of javax.swing.text.DefaultEditorKit.BeepAction

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.DefaultEditorKit.CopyAction (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.DefaultEditorKit.CopyAction

No usage of javax.swing.text.DefaultEditorKit.CopyAction

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.DefaultEditorKit.CutAction (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.DefaultEditorKit.CutAction

No usage of javax.swing.text.DefaultEditorKit.CutAction

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.DefaultEditorKit.DefaultKeyTypedAction (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.DefaultEditorKit.DefaultKeyTypedAction

No usage of javax.swing.text.DefaultEditorKit.DefaultKeyTypedAction

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.DefaultEditorKit.InsertBreakAction (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.DefaultEditorKit.InsertBreakAction

No usage of javax.swing.text.DefaultEditorKit.InsertBreakAction

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.DefaultEditorKit.InsertContentAction (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.DefaultEditorKit.InsertContentAction

No usage of javax.swing.text.DefaultEditorKit.InsertContentAction

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.DefaultEditorKit.InsertTabAction (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.DefaultEditorKit.InsertTabAction

No usage of javax.swing.text.DefaultEditorKit.InsertTabAction

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.DefaultEditorKit.PasteAction (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.DefaultEditorKit.PasteAction

No usage of javax.swing.text.DefaultEditorKit.PasteAction

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.DefaultFormatter (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.DefaultFormatter

Packages that use DefaultFormatter
javax.swing.text Provides classes and interfaces that deal with editable and noneditable text components.

Uses of DefaultFormatter in javax.swing.text

Subclasses of DefaultFormatter in javax.swing.text
class | DateFormatter DateFormatter is an InternationalFormatter that does its formatting by way of an instance of java.text.DateFormat.
class | InternationalFormatter InternationalFormatter extends DefaultFormatter, using an instance of java.text.Format to handle the conversion to a String, and the conversion from a String.
class | MaskFormatter MaskFormatter is used to format and edit strings.
class | NumberFormatter NumberFormatter subclasses InternationalFormatter adding special behavior for numbers.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.DefaultFormatterFactory (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.DefaultFormatterFactory

No usage of javax.swing.text.DefaultFormatterFactory

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.DefaultHighlighter (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.DefaultHighlighter

Packages that use DefaultHighlighter
javax.swing.plaf.basic Provides user interface objects built according to the Basic look and feel.

Uses of DefaultHighlighter in javax.swing.plaf.basic

Subclasses of DefaultHighlighter in javax.swing.plaf.basic
static class BasicTextUI.BasicHighlighter

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.DefaultHighlighter.DefaultHighlightPainter (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.DefaultHighlighter.DefaultHighlightPainter

No usage of javax.swing.text.DefaultHighlighter.DefaultHighlightPainter

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.DefaultStyledDocument (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.DefaultStyledDocument

Packages that use DefaultStyledDocument
javax.swing.text.html Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of DefaultStyledDocument in javax.swing.text.html

Subclasses of DefaultStyledDocument in javax.swing.text.html
 class HTMLDocument
A document that models HTML.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.DefaultStyledDocument.AttributeUndoableEdit (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.DefaultStyledDocument.AttributeUndoableEdit

No usage of javax.swing.text.DefaultStyledDocument.AttributeUndoableEdit

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.DefaultStyledDocument.ElementBuffer (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.DefaultStyledDocument.ElementBuffer

Packages that use DefaultStyledDocument.ElementBuffer
javax.swing.text Provides classes and interfaces that deal with editable and noneditable text components.

Uses of DefaultStyledDocument.ElementBuffer in javax.swing.text

Fields in javax.swing.text declared as DefaultStyledDocument.ElementBuffer
protected  DefaultStyledDocument.ElementBuffer DefaultStyledDocument.buffer

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.DefaultStyledDocument.ElementSpec (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.DefaultStyledDocument.ElementSpec

Packages that use DefaultStyledDocument.ElementSpec
javax.swing.text | Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.text.html | Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of DefaultStyledDocument.ElementSpec in javax.swing.text

Methods in javax.swing.text with parameters of type DefaultStyledDocument.ElementSpec
protected void | DefaultStyledDocument.create(DefaultStyledDocument.ElementSpec[] data) Initialize the document to reflect the given element structure (i.e.
protected void | DefaultStyledDocument.insert(int offset, DefaultStyledDocument.ElementSpec[] data) Inserts new elements in bulk.
void | DefaultStyledDocument.ElementBuffer.insert(int offset, int length, DefaultStyledDocument.ElementSpec[] data, AbstractDocument.DefaultDocumentEvent de) Inserts new content.
protected void | DefaultStyledDocument.ElementBuffer.insertUpdate(DefaultStyledDocument.ElementSpec[] data) Inserts an update into the document.

Uses of DefaultStyledDocument.ElementSpec in javax.swing.text.html

Methods in javax.swing.text.html with parameters of type DefaultStyledDocument.ElementSpec
protected void | HTMLDocument.insert(int offset, DefaultStyledDocument.ElementSpec[] data) Inserts new elements in bulk.
protected void | HTMLDocument.create(DefaultStyledDocument.ElementSpec[] data) Replaces the contents of the document with the given element specifications.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.DefaultStyledDocument.SectionElement (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.DefaultStyledDocument.SectionElement

No usage of javax.swing.text.DefaultStyledDocument.SectionElement

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.DefaultTextUI (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.DefaultTextUI

No usage of javax.swing.text.DefaultTextUI

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.swing.text.Document (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.swing.text.Document

Packages that use Document
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.event | Provides for events fired by Swing components.
javax.swing.text | Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.text.html | Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.
javax.swing.text.rtf | Provides a class (RTFEditorKit) for creating Rich-Text-Format text editors.

Uses of Document in javax.swing

Methods in javax.swing that return Document
protected Document | JTextArea.createDefaultModel() Creates the default implementation of the model to be used at construction if one isn't explicitly given.
protected Document | JTextField.createDefaultModel() Creates the default implementation of the model to be used at construction if one isn't explicitly given.

Methods in javax.swing with parameters of type Document
void | JTextPane.setDocument(Document doc) Associates the editor with a text document.
void | JFormattedTextField.setDocument(Document doc) Associates the editor with a text document.
void | JTextField.setDocument(Document doc) Associates the editor with a text document.

Constructors in javax.swing with parameters of type Document
JPasswordField(Document doc, String txt, int columns)
Constructs a new JPasswordField that uses the given text storage model and the given number of columns.
JTextArea(Document doc)
Constructs a new JTextArea with the given document model, and defaults for all of the other arguments (null, 0, 0).
JTextArea(Document doc, String text, int rows, int columns)
Constructs a new JTextArea with the specified number of rows and columns, and the given model.
JTextField(Document doc, String text, int columns)
Constructs a new JTextField that uses the given text storage model and the given number of columns.

Uses of Document in javax.swing.event

Methods in javax.swing.event that return Document
 Document DocumentEvent.getDocument()
Gets the document that sourced the change event.

Uses of Document in javax.swing.text

Subinterfaces of Document in javax.swing.text
 interface StyledDocument
Interface for a generic styled document.

Classes in javax.swing.text that implement Document
class | AbstractDocument An implementation of the document interface to serve as a basis for implementing various kinds of documents.
class | DefaultStyledDocument A document that can be marked up with character and paragraph styles in a manner similar to the Rich Text Format.
class | PlainDocument A plain document that maintains no character attributes.

Methods in javax.swing.text that return Document
protected Document | AbstractWriter.getDocument() Fetches the document.
Document | StyledEditorKit.createDefaultDocument() Creates an uninitialized text storage model that is appropriate for this type of editor.
abstract Document | DocumentFilter.FilterBypass.getDocument() Returns the Document the mutation is occuring on.
Document | AbstractDocument.AbstractElement.getDocument() Retrieves the underlying model.
Document | AbstractDocument.DefaultDocumentEvent.getDocument() Gets the document that sourced the change event.
Document | DefaultEditorKit.createDefaultDocument() Creates an uninitialized text storage model (PlainDocument) that is appropriate for this type of editor.
abstract Document | EditorKit.createDefaultDocument() Creates an uninitialized text storage model that is appropriate for this type of editor.
Document | JTextComponent.getDocument() Fetches the model associated with the editor.
Document | Element.getDocument() Fetches the document associated with this element.
Document | View.getDocument() Fetches the model associated with the view.

Methods in javax.swing.text with parameters of type Document
void | DefaultEditorKit.read(InputStream in, Document doc, int pos) Inserts content from the given stream which is expected to be in a format appropriate for this kind of content handler.
void | DefaultEditorKit.write(OutputStream out, Document doc, int pos, int len) Writes content from a document to the given stream in a format appropriate for this kind of content handler.
void | DefaultEditorKit.read(Reader in, Document doc, int pos) Inserts content from the given stream, which will be treated as plain text.
void | DefaultEditorKit.write(Writer out, Document doc, int pos, int len) Writes content from a document to the given stream as plain text.
abstract void | EditorKit.read(InputStream in, Document doc, int pos) Inserts content from the given stream which is expected to be in a format appropriate for this kind of content handler.
abstract void | EditorKit.write(OutputStream out, Document doc, int pos, int len) Writes content from a document to the given stream in a format appropriate for this kind of content handler.
abstract void | EditorKit.read(Reader in, Document doc, int pos) Inserts content from the given stream which is expected to be in a format appropriate for this kind of content handler.
abstract void | EditorKit.write(Writer out, Document doc, int pos, int len) Writes content from a document to the given stream in a format appropriate for this kind of content handler.
void | JTextComponent.setDocument(Document doc) Associates the editor with a text document.

Constructors in javax.swing.text with parameters of type Document
AbstractWriter(Writer w, Document doc)
Creates a new AbstractWriter.
AbstractWriter(Writer w, Document doc, int pos, int len)
Creates a new AbstractWriter.
ElementIterator(Document document)
Creates a new ElementIterator.

Uses of Document in javax.swing.text.html

Classes in javax.swing.text.html that implement Document
 class HTMLDocument
A document that models HTML.

Methods in javax.swing.text.html that return Document
 Document HTMLEditorKit.createDefaultDocument()
Create an uninitialized text storage model that is appropriate for this type of editor.

Methods in javax.swing.text.html with parameters of type Document
void | HTMLEditorKit.read(Reader in, Document doc, int pos) Inserts content from the given stream.
void | HTMLEditorKit.write(Writer out, Document doc, int pos, int len) Write content from a document to the given stream in a format appropriate for this kind of content handler.

Uses of Document in javax.swing.text.rtf

Methods in javax.swing.text.rtf with parameters of type Document
void | RTFEditorKit.read(InputStream in, Document doc, int pos) Insert content from the given stream which is expected to be in a format appropriate for this kind of content handler.
void | RTFEditorKit.write(OutputStream out, Document doc, int pos, int len) Write content from a document to the given stream in a format appropriate for this kind of content handler.
void | RTFEditorKit.read(Reader in, Document doc, int pos) Insert content from the given stream, which will be treated as plain text.
void | RTFEditorKit.write(Writer out, Document doc, int pos, int len) Write content from a document to the given stream as plain text.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.DocumentFilter (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.DocumentFilter

Packages that use DocumentFilter
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.text | Provides classes and interfaces that deal with editable and noneditable text components.

Uses of DocumentFilter in javax.swing

Methods in javax.swing that return DocumentFilter
protected  DocumentFilter JFormattedTextField.AbstractFormatter.getDocumentFilter()
Subclass and override if you wish to provide a DocumentFilter to restrict what can be input.

Uses of DocumentFilter in javax.swing.text

Methods in javax.swing.text that return DocumentFilter
protected DocumentFilter | DefaultFormatter.getDocumentFilter() Returns the DocumentFilter used to restrict the characters that can be input into the JFormattedTextField.
DocumentFilter | AbstractDocument.getDocumentFilter() Returns the DocumentFilter that is responsible for filtering of insertion/removal.

Methods in javax.swing.text with parameters of type DocumentFilter
 void AbstractDocument.setDocumentFilter(DocumentFilter filter)
Sets the DocumentFilter.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.DocumentFilter.FilterBypass (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.DocumentFilter.FilterBypass

Packages that use DocumentFilter.FilterBypass
javax.swing.text Provides classes and interfaces that deal with editable and noneditable text components.

Uses of DocumentFilter.FilterBypass in javax.swing.text

Methods in javax.swing.text with parameters of type DocumentFilter.FilterBypass
void | DocumentFilter.remove(DocumentFilter.FilterBypass fb, int offset, int length) Invoked prior to removal of the specified region in the specified Document.
void | DocumentFilter.insertString(DocumentFilter.FilterBypass fb, int offset, String string, AttributeSet attr) Invoked prior to insertion of text into the specified Document.
void | DocumentFilter.replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) Invoked prior to replacing a region of text in the specified Document.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.EditorKit (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.EditorKit

Packages that use EditorKit
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.plaf | Provides one interface and many abstract classes that Swing uses to provide its pluggable look-and-feel capabilities.
javax.swing.plaf.basic | Provides user interface objects built according to the Basic look and feel.
javax.swing.plaf.multi | Provides user interface objects that combine two or more look and feels.
javax.swing.text | Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.text.html | Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.
javax.swing.text.rtf | Provides a class (RTFEditorKit) for creating Rich-Text-Format text editors.

Uses of EditorKit in javax.swing

Methods in javax.swing that return EditorKit
protected EditorKit | JTextPane.createDefaultEditorKit() Creates the EditorKit to use by default.
protected EditorKit | JEditorPane.createDefaultEditorKit() Creates the default editor kit (PlainEditorKit) for when the component is first created.
EditorKit | JEditorPane.getEditorKit() Fetches the currently installed kit for handling content.
EditorKit | JEditorPane.getEditorKitForContentType(String type) Fetches the editor kit to use for the given type of content.
static EditorKit | JEditorPane.createEditorKitForContentType(String type) Creates a handler for the given type from the default registry of editor kits.

Methods in javax.swing with parameters of type EditorKit
void | JTextPane.setEditorKit(EditorKit kit) Sets the currently installed kit for handling content.
void | JEditorPane.setEditorKit(EditorKit kit) Sets the currently installed kit for handling content.
void | JEditorPane.setEditorKitForContentType(String type, EditorKit k) Directly sets the editor kit to use for the given type.

Uses of EditorKit in javax.swing.plaf

Methods in javax.swing.plaf that return EditorKit
abstract  EditorKit TextUI.getEditorKit(JTextComponent t)
Fetches the binding of services that set a policy for the type of document being edited.

Uses of EditorKit in javax.swing.plaf.basic

Methods in javax.swing.plaf.basic that return EditorKit
EditorKit | BasicEditorPaneUI.getEditorKit(JTextComponent tc) Fetches the EditorKit for the UI.
EditorKit | BasicTextUI.getEditorKit(JTextComponent tc) Fetches the EditorKit for the UI.

Uses of EditorKit in javax.swing.plaf.multi

Methods in javax.swing.plaf.multi that return EditorKit
 EditorKit MultiTextUI.getEditorKit(JTextComponent a)
Invokes the getEditorKit method on each UI handled by this object.

Uses of EditorKit in javax.swing.text

Subclasses of EditorKit in javax.swing.text
class | DefaultEditorKit This is the set of things needed by a text component to be a reasonably functioning editor for some type of text document.
class | StyledEditorKit This is the set of things needed by a text component to be a reasonably functioning editor for some type of text document.

Uses of EditorKit in javax.swing.text.html

Subclasses of EditorKit in javax.swing.text.html
 class HTMLEditorKit
The Swing JEditorPane text component supports different kinds of content via a plug-in mechanism called an EditorKit.

Uses of EditorKit in javax.swing.text.rtf

Subclasses of EditorKit in javax.swing.text.rtf
 class RTFEditorKit
This is the default implementation of RTF editing functionality.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.swing.text.Element (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.swing.text.Element

Packages that use Element
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.event | Provides for events fired by Swing components.
javax.swing.plaf.basic | Provides user interface objects built according to the Basic look and feel.
javax.swing.text | Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.text.html | Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of Element in javax.swing

Constructors in javax.swing with parameters of type Element
JEditorPane.JEditorPaneAccessibleHypertextSupport.HTMLLink(Element e)

Uses of Element in javax.swing.event

Methods in javax.swing.event that return Element
Element | HyperlinkEvent.getSourceElement() Returns the Element that corresponds to the source of the event.
Element | DocumentEvent.ElementChange.getElement() Returns the element represented.
Element[] | DocumentEvent.ElementChange.getChildrenRemoved() Gets the child elements that were removed from the given parent element.
Element[] | DocumentEvent.ElementChange.getChildrenAdded() Gets the child elements that were added to the given parent element.

Methods in javax.swing.event with parameters of type Element
 DocumentEvent.ElementChange DocumentEvent.getChange(Element elem)
Gets the change information for the given element.

Constructors in javax.swing.event with parameters of type Element
HyperlinkEvent(Object source, HyperlinkEvent.EventType type, URL u, String desc, Element sourceElement)
Creates a new object representing a hypertext link event.

Uses of Element in javax.swing.plaf.basic

Methods in javax.swing.plaf.basic with parameters of type Element
View | BasicTextAreaUI.create(Element elem) Creates the view for an element.
View | BasicPasswordFieldUI.create(Element elem) Creates a view (PasswordView) for an element.
View | BasicTextFieldUI.create(Element elem) Creates a view (FieldView) based on an element.
View | BasicTextUI.create(Element elem) Creates a view for an element.
View | BasicTextUI.create(Element elem, int p0, int p1) Creates a view for an element.

Uses of Element in javax.swing.text

Classes in javax.swing.text that implement Element
class | AbstractDocument.AbstractElement Implements the abstract part of an element.
class | AbstractDocument.BranchElement Implements a composite element that contains other elements.
class | AbstractDocument.LeafElement Implements an element that directly represents content of some kind.
protected class | DefaultStyledDocument.SectionElement Default root element for a document...

Fields in javax.swing.text declared as Element
protected  Element DefaultStyledDocument.AttributeUndoableEdit.element

Methods in javax.swing.text that return Element
Element | ElementIterator.first() Fetches the first element.
Element | ElementIterator.current() Fetches the current Element.
Element | ElementIterator.next() Fetches the next Element.
Element | ElementIterator.previous() Fetches the previous Element.
Element | StyledEditorKit.getCharacterAttributeRun() Fetches the element representing the current run of character attributes for the caret.
Element | DefaultStyledDocument.getDefaultRootElement() Gets the default root element.
Element | DefaultStyledDocument.getParagraphElement(int pos) Gets the paragraph element at the offset pos.
Element | DefaultStyledDocument.getCharacterElement(int pos) Gets a character element based on a position.
Element | DefaultStyledDocument.ElementBuffer.getRootElement() Gets the root element.
Element | DefaultStyledDocument.ElementBuffer.clone(Element parent, Element clonee) Creates a copy of this element, with a different parent.
Element | PlainDocument.getDefaultRootElement() Gets the default root element for the document model.
Element | PlainDocument.getParagraphElement(int pos) Get the paragraph element containing the given position.
Element[] | AbstractDocument.getRootElements() Gets all root elements defined.
abstract Element | AbstractDocument.getDefaultRootElement() Returns the root element that views should be based upon unless some other mechanism for assigning views to element structures is provided.
Element | AbstractDocument.getBidiRootElement() Returns the root element of the bidirectional structure for this document.
abstract Element | AbstractDocument.getParagraphElement(int pos) Get the paragraph element containing the given position.
protected Element | AbstractDocument.createLeafElement(Element parent, AttributeSet a, int p0, int p1) Creates a document leaf element.
protected Element | AbstractDocument.createBranchElement(Element parent, AttributeSet a) Creates a document branch element, that can contain other elements.
Element | AbstractDocument.AbstractElement.getParentElement() Gets the parent of the element.
abstract Element | AbstractDocument.AbstractElement.getElement(int index) Gets a child element.
Element | AbstractDocument.BranchElement.positionToElement(int pos) Gets the child element that contains the given model position.
Element | AbstractDocument.BranchElement.getElement(int index) Gets a child element.
Element | AbstractDocument.LeafElement.getElement(int index) Gets a child element.
Element | AbstractDocument.ElementEdit.getElement() Returns the underlying element.
Element[] | AbstractDocument.ElementEdit.getChildrenRemoved() Gets a list of children that were removed.
Element[] | AbstractDocument.ElementEdit.getChildrenAdded() Gets a list of children that were added.
static Element | Utilities.getParagraphElement(JTextComponent c, int offs) Determines the element to use for a paragraph/line.
Element | StyledDocument.getParagraphElement(int pos) Gets the element that represents the paragraph that encloses the given offset within the document.
Element | StyledDocument.getCharacterElement(int pos) Gets the element that represents the character that is at the given offset within the document.
Element[] | Document.getRootElements() Returns all of the root elements that are defined.
Element | Document.getDefaultRootElement() Returns the root element that views should be based upon, unless some other mechanism for assigning views to element structures is provided.
Element | Element.getParentElement() Fetches the parent element.
Element | Element.getElement(int index) Fetches the child element at the given index.
Element | View.getElement() Fetches the structural portion of the subject that this view is mapped to.

Methods in javax.swing.text with parameters of type Element
protected TableView.TableRow | TableView.createTableRow(Element elem) Creates a new table row.
protected TableView.TableCell | TableView.createTableCell(Element elem) Deprecated. Table cells can now be any arbitrary View implementation and should be produced by the ViewFactory rather than the table.
protected boolean | AbstractWriter.inRange(Element next) This method determines whether the current element is in the range specified.
protected String | AbstractWriter.getText(Element elem) Returns the text associated with the element.
protected void | AbstractWriter.text(Element elem) Writes out text.
protected void | StyledEditorKit.createInputAttributes(Element element, MutableAttributeSet set) Copies the key/values in elements AttributeSet into set.
Element | DefaultStyledDocument.ElementBuffer.clone(Element parent, Element clonee) Creates a copy of this element, with a different parent.
protected Element | AbstractDocument.createLeafElement(Element parent, AttributeSet a, int p0, int p1) Creates a document leaf element.
protected Element | AbstractDocument.createBranchElement(Element parent, AttributeSet a) Creates a document branch element, that can contain other elements.
void | AbstractDocument.BranchElement.replace(int offset, int length, Element[] elems) Replaces content with a new set of elements.
DocumentEvent.ElementChange | AbstractDocument.DefaultDocumentEvent.getChange(Element elem) Gets the changes for an element.
View | ViewFactory.create(Element elem) Creates a view from the given structural element of a document.

Constructors in javax.swing.text with parameters of type Element
ZoneView(Element elem, int axis)
Constructs a ZoneView.
TableView(Element elem)
Constructs a TableView for the given element.
TableView.TableRow(Element elem)
Constructs a TableView for the given element.
TableView.TableCell(Element elem)
Deprecated. Constructs a TableCell for the given element.
PasswordView(Element elem)
Constructs a new view wrapped on an element.
PlainView(Element elem)
Constructs a new PlainView wrapped on an element.
FieldView(Element elem)
Constructs a new FieldView wrapped on an element.
AsyncBoxView(Element elem, int axis)
Construct a box view that does asynchronous layout.
AbstractWriter(Writer w, Element root)
Creates a new AbstractWriter.
AbstractWriter(Writer w, Element root, int pos, int len)
Creates a new AbstractWriter.
IconView(Element elem)
Creates a new icon view that represents an element.
ComponentView(Element elem)
Creates a new ComponentView object.
WrappedPlainView(Element elem)
Creates a new WrappedPlainView.
WrappedPlainView(Element elem, boolean wordWrap)
Creates a new WrappedPlainView.
ElementIterator(Element root)
Creates a new ElementIterator.
DefaultStyledDocument.ElementBuffer(Element root)
Creates a new ElementBuffer.
DefaultStyledDocument.AttributeUndoableEdit(Element element, AttributeSet newAttributes, boolean isReplacing)
AbstractDocument.AbstractElement(Element parent, AttributeSet a)
Creates a new AbstractElement.
AbstractDocument.BranchElement(Element parent, AttributeSet a)
Constructs a composite element that initially contains no children.
AbstractDocument.LeafElement(Element parent, AttributeSet a, int offs0, int offs1)
Constructs an element that represents content within the document (has no children).
AbstractDocument.ElementEdit(Element e, int index, Element[] removed, Element[] added)
Constructs an edit record.
LabelView(Element elem)
Constructs a new view wrapped on an element.
GlyphView(Element elem)
Constructs a new view wrapped on an element.
CompositeView(Element elem)
Constructs a CompositeView for the given element.
BoxView(Element elem, int axis)
Constructs a BoxView.
FlowView(Element elem, int axis)
Constructs a FlowView for the given element.
ParagraphView(Element elem)
Constructs a ParagraphView for the given element.
View(Element elem)
Creates a new View object.

Uses of Element in javax.swing.text.html

Classes in javax.swing.text.html that implement Element
class | HTMLDocument.BlockElement An element that represents a structural block of HTML.
class | HTMLDocument.RunElement An element that represents a chunk of text that has a set of HTML character level attributes assigned to it.

Methods in javax.swing.text.html that return Element
protected Element[] | HTMLEditorKit.HTMLTextAction.getElementsAt(HTMLDocument doc, int offset) Returns an array of the Elements that contain offset.
protected Element | HTMLEditorKit.HTMLTextAction.findElementMatchingTag(HTMLDocument doc, int offset, HTML.Tag tag) Returns the deepest element at offset matching tag.
protected Element | HTMLDocument.createLeafElement(Element parent, AttributeSet a, int p0, int p1) Creates a document leaf element that directly represents text (doesn't have any children).
protected Element | HTMLDocument.createBranchElement(Element parent, AttributeSet a) Creates a document branch element, that can contain other elements.
Element | HTMLDocument.getElement(String id) Returns the element that has the given id Attribute.
Element | HTMLDocument.getElement(Element e, Object attribute, Object value) Returns the child element of e that contains the attribute, attribute with value value, or null if one isn't found.

Methods in javax.swing.text.html with parameters of type Element
protected void | MinimalHTMLWriter.text(Element elem) Writes out text.
protected void | MinimalHTMLWriter.writeStartParagraph(Element elem) Emits the start tag for a paragraph.
protected void | MinimalHTMLWriter.writeLeaf(Element elem) Responsible for writing out other non-text leaf elements.
protected void | MinimalHTMLWriter.writeImage(Element elem) Responsible for handling Icon Elements; deliberately unimplemented.
protected void | MinimalHTMLWriter.writeComponent(Element elem) Responsible for handling Component Elements; deliberately unimplemented.
protected boolean | MinimalHTMLWriter.isText(Element elem) Returns true if the element is a text element.
protected void | MinimalHTMLWriter.writeContent(Element elem, boolean needsIndenting) Writes out the attribute set in an HTML-compliant manner.
protected void | HTMLWriter.emptyTag(Element elem) Writes out all empty elements (all tags that have no corresponding end tag).
protected void | HTMLWriter.startTag(Element elem) Writes out a start tag for the element.
protected void | HTMLWriter.text(Element elem) Writes out text.
protected void | HTMLWriter.endTag(Element elem) Writes out an end tag for the element.
protected void | HTMLWriter.comment(Element elem) Writes out comments.
protected boolean | HTMLWriter.synthesizedElement(Element elem) Returns true if the element is a synthesized element.
protected void | HTMLEditorKit.createInputAttributes(Element element, MutableAttributeSet set) Copies the key/values in elements AttributeSet into set.
View | HTMLEditorKit.HTMLFactory.create(Element elem) Creates a view from an element.
protected void | HTMLEditorKit.InsertHTMLTextAction.insertAtBoundary(JEditorPane editor, HTMLDocument doc, int offset, Element insertElement, String html, HTML.Tag parentTag, HTML.Tag addTag) This is invoked when inserting at a boundary.
protected void | HTMLEditorKit.InsertHTMLTextAction.insertAtBoundry(JEditorPane editor, HTMLDocument doc, int offset, Element insertElement, String html, HTML.Tag parentTag, HTML.Tag addTag) Deprecated. As of Java 2 platform v1.3, use insertAtBoundary
Style | StyleSheet.getRule(HTML.Tag t, Element e) Fetches the style to use to render the given type of HTML tag.
protected Element | HTMLDocument.createLeafElement(Element parent, AttributeSet a, int p0, int p1) Creates a document leaf element that directly represents text (doesn't have any children).
protected Element | HTMLDocument.createBranchElement(Element parent, AttributeSet a) Creates a document branch element, that can contain other elements.
void | HTMLDocument.setInnerHTML(Element elem, String htmlText) Replaces the children of the given element with the contents specified as an HTML string.
void | HTMLDocument.setOuterHTML(Element elem, String htmlText) Replaces the given element in the parent with the contents specified as an HTML string.
void | HTMLDocument.insertAfterStart(Element elem, String htmlText) Inserts the HTML specified as a string at the start of the element.
void | HTMLDocument.insertBeforeEnd(Element elem, String htmlText) Inserts the HTML specified as a string at the end of the element.
void | HTMLDocument.insertBeforeStart(Element elem, String htmlText) Inserts the HTML specified as a string before the start of the given element.
void | HTMLDocument.insertAfterEnd(Element elem, String htmlText) Inserts the HTML specified as a string after the the end of the given element.
Element | HTMLDocument.getElement(Element e, Object attribute, Object value) Returns the child element of e that contains the attribute, attribute with value value, or null if one isn't found.

Constructors in javax.swing.text.html with parameters of type Element
ObjectView(Element elem)
Creates a new ObjectView object.
FormView(Element elem)
Creates a new FormView object.
ImageView(Element elem)
Creates a new view that represents an IMG element.
ListView(Element elem)
Creates a new view that represents a list element.
ParagraphView(Element elem)
Constructs a ParagraphView for the given element.
InlineView(Element elem)
Constructs a new view wrapped on an element.
BlockView(Element elem, int axis)
Creates a new view that represents an html box.
HTMLFrameHyperlinkEvent(Object source, HyperlinkEvent.EventType type, URL targetURL, Element sourceElement, String targetFrame)
Creates a new object representing a hypertext link event.
HTMLFrameHyperlinkEvent(Object source, HyperlinkEvent.EventType type, URL targetURL, String desc, Element sourceElement, String targetFrame)
Creates a new object representing a hypertext link event.
HTMLDocument.RunElement(Element parent, AttributeSet a, int offs0, int offs1)
Constructs an element that represents content within the document (has no children).
HTMLDocument.BlockElement(Element parent, AttributeSet a)
Constructs a composite element that initially contains no children.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.ElementIterator (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.ElementIterator

Packages that use ElementIterator
javax.swing.text Provides classes and interfaces that deal with editable and noneditable text components.

Uses of ElementIterator in javax.swing.text

Methods in javax.swing.text that return ElementIterator
protected  ElementIterator AbstractWriter.getElementIterator()
Fetches the ElementIterator.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.FieldView (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.FieldView

Packages that use FieldView
javax.swing.text Provides classes and interfaces that deal with editable and noneditable text components.

Uses of FieldView in javax.swing.text

Subclasses of FieldView in javax.swing.text
 class PasswordView
Implements a View suitable for use in JPasswordField UI implementations.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.FlowView (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.FlowView

Packages that use FlowView
javax.swing.text Provides classes and interfaces that deal with editable and noneditable text components.

Uses of FlowView in javax.swing.text

Subclasses of FlowView in javax.swing.text
 class ParagraphView
View of a simple line-wrapping paragraph that supports multiple fonts, colors, components, icons, etc.

Methods in javax.swing.text with parameters of type FlowView
void | FlowView.FlowStrategy.insertUpdate(FlowView fv, DocumentEvent e, Rectangle alloc) Gives notification that something was inserted into the document in a location that the given flow view is responsible for.
void | FlowView.FlowStrategy.removeUpdate(FlowView fv, DocumentEvent e, Rectangle alloc) Gives notification that something was removed from the document in a location that the given flow view is responsible for.
void | FlowView.FlowStrategy.changedUpdate(FlowView fv, DocumentEvent e, Rectangle alloc) Gives notification from the document that attributes were changed in a location that this view is responsible for.
protected View | FlowView.FlowStrategy.getLogicalView(FlowView fv) This method gives flow strategies access to the logical view of the FlowView.
void | FlowView.FlowStrategy.layout(FlowView fv) Update the flow on the given FlowView.
protected int | FlowView.FlowStrategy.layoutRow(FlowView fv, int rowIndex, int pos) Creates a row of views that will fit within the layout span of the row.
protected void | FlowView.FlowStrategy.adjustRow(FlowView fv, int rowIndex, int desiredSpan, int x) Adjusts the given row if possible to fit within the layout span.
protected View | FlowView.FlowStrategy.createView(FlowView fv, int startOffset, int spanLeft, int rowIndex) Creates a view that can be used to represent the current piece of the flow.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.FlowView.FlowStrategy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.FlowView.FlowStrategy

Packages that use FlowView.FlowStrategy
javax.swing.text Provides classes and interfaces that deal with editable and noneditable text components.

Uses of FlowView.FlowStrategy in javax.swing.text

Fields in javax.swing.text declared as FlowView.FlowStrategy
protected  FlowView.FlowStrategy FlowView.strategy
The behavior for keeping the flow updated.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.GapContent (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.GapContent

No usage of javax.swing.text.GapContent

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.GlyphView (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.GlyphView

Packages that use GlyphView
javax.swing.text | Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.text.html | Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of GlyphView in javax.swing.text

Subclasses of GlyphView in javax.swing.text
 class LabelView
A LabelView is a styled chunk of text that represents a view mapped over an element in the text model.

Methods in javax.swing.text with parameters of type GlyphView
abstract float | GlyphView.GlyphPainter.getSpan(GlyphView v, int p0, int p1, TabExpander e, float x) Determine the span the glyphs given a start location (for tab expansion).
abstract float | GlyphView.GlyphPainter.getHeight(GlyphView v)
abstract float | GlyphView.GlyphPainter.getAscent(GlyphView v)
abstract float | GlyphView.GlyphPainter.getDescent(GlyphView v)
abstract void | GlyphView.GlyphPainter.paint(GlyphView v, Graphics g, Shape a, int p0, int p1) Paint the glyphs representing the given range.
abstract Shape | GlyphView.GlyphPainter.modelToView(GlyphView v, int pos, Position.Bias bias, Shape a) Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
abstract int | GlyphView.GlyphPainter.viewToModel(GlyphView v, float x, float y, Shape a, Position.Bias[] biasReturn) Provides a mapping from the view coordinate space to the logical coordinate space of the model.
abstract int | GlyphView.GlyphPainter.getBoundedPosition(GlyphView v, int p0, float x, float len) Determines the model location that represents the maximum advance that fits within the given span.
GlyphView.GlyphPainter | GlyphView.GlyphPainter.getPainter(GlyphView v, int p0, int p1) Create a painter to use for the given GlyphView.
int | GlyphView.GlyphPainter.getNextVisualPositionFrom(GlyphView v, int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet) Provides a way to determine the next visually represented model location that one might place a caret.

Uses of GlyphView in javax.swing.text.html

Subclasses of GlyphView in javax.swing.text.html
 class InlineView
Displays the inline element styles based upon css attributes.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.GlyphView.GlyphPainter (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.GlyphView.GlyphPainter

Packages that use GlyphView.GlyphPainter
javax.swing.text Provides classes and interfaces that deal with editable and noneditable text components.

Uses of GlyphView.GlyphPainter in javax.swing.text

Methods in javax.swing.text that return GlyphView.GlyphPainter
GlyphView.GlyphPainter | GlyphView.getGlyphPainter() Fetch the currently installed glyph painter.
GlyphView.GlyphPainter | GlyphView.GlyphPainter.getPainter(GlyphView v, int p0, int p1) Create a painter to use for the given GlyphView.

Methods in javax.swing.text with parameters of type GlyphView.GlyphPainter
 void GlyphView.setGlyphPainter(GlyphView.GlyphPainter p)
Sets the painter to use for rendering glyphs.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.swing.text.Highlighter (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.swing.text.Highlighter

Packages that use Highlighter
javax.swing.plaf.basic | Provides user interface objects built according to the Basic look and feel.
javax.swing.text | Provides classes and interfaces that deal with editable and noneditable text components.

Uses of Highlighter in javax.swing.plaf.basic

Classes in javax.swing.plaf.basic that implement Highlighter
static class BasicTextUI.BasicHighlighter

Methods in javax.swing.plaf.basic that return Highlighter
protected  Highlighter BasicTextUI.createHighlighter()
Creates the object to use for adding highlights.

Uses of Highlighter in javax.swing.text

Classes in javax.swing.text that implement Highlighter
class | DefaultHighlighter Implements the Highlighter interfaces.
class | LayeredHighlighter

Methods in javax.swing.text that return Highlighter
 Highlighter JTextComponent.getHighlighter()
Fetches the object responsible for making highlights.

Methods in javax.swing.text with parameters of type Highlighter
 void JTextComponent.setHighlighter(Highlighter h)
Sets the highlighter to be used.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.swing.text.Highlighter.Highlight (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.swing.text.Highlighter.Highlight

Packages that use Highlighter.Highlight
javax.swing.text Provides classes and interfaces that deal with editable and noneditable text components.

Uses of Highlighter.Highlight in javax.swing.text

Methods in javax.swing.text that return Highlighter.Highlight
Highlighter.Highlight[] | DefaultHighlighter.getHighlights() Makes a copy of the highlights.
Highlighter.Highlight[] | Highlighter.getHighlights() Fetches the current list of highlights.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.swing.text.Highlighter.HighlightPainter (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.swing.text.Highlighter.HighlightPainter

Packages that use Highlighter.HighlightPainter
javax.swing.text Provides classes and interfaces that deal with editable and noneditable text components.

Uses of Highlighter.HighlightPainter in javax.swing.text

Classes in javax.swing.text that implement Highlighter.HighlightPainter
static class | DefaultHighlighter.DefaultHighlightPainter Simple highlight painter that fills a highlighted area with a solid color.
static class | LayeredHighlighter.LayerPainter Layered highlight renderer.

Methods in javax.swing.text that return Highlighter.HighlightPainter
protected Highlighter.HighlightPainter | DefaultCaret.getSelectionPainter() Gets the painter for the Highlighter.
Highlighter.HighlightPainter | Highlighter.Highlight.getPainter() Gets the painter for the highlighter.

Methods in javax.swing.text with parameters of type Highlighter.HighlightPainter
Object | DefaultHighlighter.addHighlight(int p0, int p1, Highlighter.HighlightPainter p) Adds a highlight to the view.
Object | Highlighter.addHighlight(int p0, int p1, Highlighter.HighlightPainter p) Adds a highlight to the view.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.IconView (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.IconView

No usage of javax.swing.text.IconView

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.InternationalFormatter (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.InternationalFormatter

Packages that use InternationalFormatter
javax.swing.text Provides classes and interfaces that deal with editable and noneditable text components.

Uses of InternationalFormatter in javax.swing.text

Subclasses of InternationalFormatter in javax.swing.text
class | DateFormatter DateFormatter is an InternationalFormatter that does its formatting by way of an instance of java.text.DateFormat.
class | NumberFormatter NumberFormatter subclasses InternationalFormatter adding special behavior for numbers.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.JTextComponent (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.JTextComponent

Packages that use JTextComponent
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.plaf | Provides one interface and many abstract classes that Swing uses to provide its pluggable look-and-feel capabilities.
javax.swing.plaf.basic | Provides user interface objects built according to the Basic look and feel.
javax.swing.plaf.multi | Provides user interface objects that combine two or more look and feels.
javax.swing.text | Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.tree | Provides classes and interfaces for dealing with javax.swing.JTree.

Uses of JTextComponent in javax.swing

Subclasses of JTextComponent in javax.swing
class | JEditorPane A text component to edit various kinds of content.
class | JFormattedTextField JFormattedTextField extends JTextField adding support for formatting arbitrary values, as well as retrieving a particular object once the user has edited the text.
class | JPasswordField 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.
class | JTextArea A JTextArea is a multi-line area that displays plain text.
class | JTextField JTextField is a lightweight component that allows the editing of a single line of text.
class | JTextPane A text component that can be marked up with attributes that are represented graphically.

Uses of JTextComponent in javax.swing.plaf

Methods in javax.swing.plaf with parameters of type JTextComponent
abstract Rectangle | TextUI.modelToView(JTextComponent t, int pos) Converts the given location in the model to a place in the view coordinate system.
abstract Rectangle | TextUI.modelToView(JTextComponent t, int pos, Position.Bias bias) Converts the given location in the model to a place in the view coordinate system.
abstract int | TextUI.viewToModel(JTextComponent t, Point pt) Converts the given place in the view coordinate system to the nearest representative location in the model.
abstract int | TextUI.viewToModel(JTextComponent t, Point pt, Position.Bias[] biasReturn) Provides a mapping from the view coordinate space to the logical coordinate space of the model.
abstract int | TextUI.getNextVisualPositionFrom(JTextComponent t, int pos, Position.Bias b, int direction, Position.Bias[] biasRet) Provides a way to determine the next visually represented model location that one might place a caret.
abstract void | TextUI.damageRange(JTextComponent t, int p0, int p1) Causes the portion of the view responsible for the given part of the model to be repainted.
abstract void | TextUI.damageRange(JTextComponent t, int p0, int p1, Position.Bias firstBias, Position.Bias secondBias) Causes the portion of the view responsible for the given part of the model to be repainted.
abstract EditorKit | TextUI.getEditorKit(JTextComponent t) Fetches the binding of services that set a policy for the type of document being edited.
abstract View | TextUI.getRootView(JTextComponent t) Fetches a View with the allocation of the associated text component (i.e.
String | TextUI.getToolTipText(JTextComponent t, Point pt) Returns the string to be used as the tooltip at the passed in location.

Uses of JTextComponent in javax.swing.plaf.basic

Methods in javax.swing.plaf.basic that return JTextComponent
protected  JTextComponent BasicTextUI.getComponent()
Fetches the text component associated with this UI implementation.

Methods in javax.swing.plaf.basic with parameters of type JTextComponent
EditorKit | BasicEditorPaneUI.getEditorKit(JTextComponent tc) Fetches the EditorKit for the UI.
Rectangle | BasicTextUI.modelToView(JTextComponent tc, int pos) Converts the given location in the model to a place in the view coordinate system.
Rectangle | BasicTextUI.modelToView(JTextComponent tc, int pos, Position.Bias bias) Converts the given location in the model to a place in the view coordinate system.
int | BasicTextUI.viewToModel(JTextComponent tc, Point pt) Converts the given place in the view coordinate system to the nearest representative location in the model.
int | BasicTextUI.viewToModel(JTextComponent tc, Point pt, Position.Bias[] biasReturn) Converts the given place in the view coordinate system to the nearest representative location in the model.
int | BasicTextUI.getNextVisualPositionFrom(JTextComponent t, int pos, Position.Bias b, int direction, Position.Bias[] biasRet) Provides a way to determine the next visually represented model location that one might place a caret.
void | BasicTextUI.damageRange(JTextComponent tc, int p0, int p1) Causes the portion of the view responsible for the given part of the model to be repainted.
void | BasicTextUI.damageRange(JTextComponent t, int p0, int p1, Position.Bias p0Bias, Position.Bias p1Bias) Causes the portion of the view responsible for the given part of the model to be repainted.
EditorKit | BasicTextUI.getEditorKit(JTextComponent tc) Fetches the EditorKit for the UI.
View | BasicTextUI.getRootView(JTextComponent tc) Fetches a View with the allocation of the associated text component (i.e.
String | BasicTextUI.getToolTipText(JTextComponent t, Point pt) Returns the string to be used as the tooltip at the passed in location.

Uses of JTextComponent in javax.swing.plaf.multi

Methods in javax.swing.plaf.multi with parameters of type JTextComponent
String | MultiTextUI.getToolTipText(JTextComponent a, Point b) Invokes the getToolTipText method on each UI handled by this object.
Rectangle | MultiTextUI.modelToView(JTextComponent a, int b) Invokes the modelToView method on each UI handled by this object.
Rectangle | MultiTextUI.modelToView(JTextComponent a, int b, Position.Bias c) Invokes the modelToView method on each UI handled by this object.
int | MultiTextUI.viewToModel(JTextComponent a, Point b) Invokes the viewToModel method on each UI handled by this object.
int | MultiTextUI.viewToModel(JTextComponent a, Point b, Position.Bias[] c) Invokes the viewToModel method on each UI handled by this object.
int | MultiTextUI.getNextVisualPositionFrom(JTextComponent a, int b, Position.Bias c, int d, Position.Bias[] e) Invokes the getNextVisualPositionFrom method on each UI handled by this object.
void | MultiTextUI.damageRange(JTextComponent a, int b, int c) Invokes the damageRange method on each UI handled by this object.
void | MultiTextUI.damageRange(JTextComponent a, int b, int c, Position.Bias d, Position.Bias e) Invokes the damageRange method on each UI handled by this object.
EditorKit | MultiTextUI.getEditorKit(JTextComponent a) Invokes the getEditorKit method on each UI handled by this object.
View | MultiTextUI.getRootView(JTextComponent a) Invokes the getRootView method on each UI handled by this object.

Uses of JTextComponent in javax.swing.text

Methods in javax.swing.text that return JTextComponent
protected JTextComponent | TextAction.getTextComponent(ActionEvent e) Determines the component to use for the action.
protected JTextComponent | TextAction.getFocusedComponent() Fetches the text component that currently has focus.
protected JTextComponent | DefaultCaret.getComponent() Gets the text editor component that this caret is is bound to.

Methods in javax.swing.text with parameters of type JTextComponent
abstract void | LayeredHighlighter.paintLayeredHighlights(Graphics g, int p0, int p1, Shape viewBounds, JTextComponent editor, View view) When leaf Views (such as LabelView) are rendering they should call into this method.
abstract Shape | LayeredHighlighter.LayerPainter.paintLayer(Graphics g, int p0, int p1, Shape viewBounds, JTextComponent editor, View view)
void | DefaultHighlighter.install(JTextComponent c) Called when the UI is being installed into the interface of a JTextComponent.
void | DefaultHighlighter.deinstall(JTextComponent c) Called when the UI is being removed from the interface of a JTextComponent.
void | DefaultHighlighter.paintLayeredHighlights(Graphics g, int p0, int p1, Shape viewBounds, JTextComponent editor, View view) When leaf Views (such as LabelView) are rendering they should call into this method.
void | DefaultHighlighter.DefaultHighlightPainter.paint(Graphics g, int offs0, int offs1, Shape bounds, JTextComponent c) Paints a highlight.
Shape | DefaultHighlighter.DefaultHighlightPainter.paintLayer(Graphics g, int offs0, int offs1, Shape bounds, JTextComponent c, View view) Paints a portion of a highlight.
static int | Utilities.getRowStart(JTextComponent c, int offs) Determines the starting row model position of the row that contains the specified model position.
static int | Utilities.getRowEnd(JTextComponent c, int offs) Determines the ending row model position of the row that contains the specified model position.
static int | Utilities.getPositionAbove(JTextComponent c, int offs, int x) Determines the position in the model that is closest to the given view location in the row above.
static int | Utilities.getPositionBelow(JTextComponent c, int offs, int x) Determines the position in the model that is closest to the given view location in the row below.
static int | Utilities.getWordStart(JTextComponent c, int offs) Determines the start of a word for the given model location.
static int | Utilities.getWordEnd(JTextComponent c, int offs) Determines the end of a word for the given location.
static int | Utilities.getNextWord(JTextComponent c, int offs) Determines the start of the next word for the given location.
static int | Utilities.getPreviousWord(JTextComponent c, int offs) Determine the start of the prev word for the given location.
static Element | Utilities.getParagraphElement(JTextComponent c, int offs) Determines the element to use for a paragraph/line.
void | DefaultCaret.install(JTextComponent c) Called when the UI is being installed into the interface of a JTextComponent.
void | DefaultCaret.deinstall(JTextComponent c) Called when the UI is being removed from the interface of a JTextComponent.
void | Highlighter.install(JTextComponent c) Called when the UI is being installed into the interface of a JTextComponent.
void | Highlighter.deinstall(JTextComponent c) Called when the UI is being removed from the interface of a JTextComponent.
void | Highlighter.HighlightPainter.paint(Graphics g, int p0, int p1, Shape bounds, JTextComponent c) Renders the highlight.
int | NavigationFilter.getNextVisualPositionFrom(JTextComponent text, int pos, Position.Bias bias, int direction, Position.Bias[] biasRet) Returns the next visual position to place the caret at from an existing position.
void | Caret.install(JTextComponent c) Called when the UI is being installed into the interface of a JTextComponent.
void | Caret.deinstall(JTextComponent c) Called when the UI is being removed from the interface of a JTextComponent.

Uses of JTextComponent in javax.swing.tree

Subclasses of JTextComponent in javax.swing.tree
 class DefaultTreeCellEditor.DefaultTextField
TextField used when no editor is supplied.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.JTextComponent.AccessibleJTextComponent (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.JTextComponent.AccessibleJTextComponent

Packages that use JTextComponent.AccessibleJTextComponent
javax.swing Provides a set of "lightweight" (all-Java language) components that, to the maximum degree possible, work the same on all platforms.

Uses of JTextComponent.AccessibleJTextComponent in javax.swing

Subclasses of JTextComponent.AccessibleJTextComponent in javax.swing
protected class | JEditorPane.AccessibleJEditorPane This class implements accessibility support for the JEditorPane class.
protected class | JEditorPane.AccessibleJEditorPaneHTML This class provides support for AccessibleHypertext, and is used in instances where the EditorKit installed in this JEditorPane is an instance of HTMLEditorKit.
protected class | JEditorPane.JEditorPaneAccessibleHypertextSupport What's returned by AccessibleJEditorPaneHTML.getAccessibleText.
protected class | JPasswordField.AccessibleJPasswordField This class implements accessibility support for the JPasswordField class.
protected class | JTextArea.AccessibleJTextArea This class implements accessibility support for the JTextArea class.
protected class | JTextField.AccessibleJTextField This class implements accessibility support for the JTextField class.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.JTextComponent.KeyBinding (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.JTextComponent.KeyBinding

Packages that use JTextComponent.KeyBinding
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.text | Provides classes and interfaces that deal with editable and noneditable text components.

Uses of JTextComponent.KeyBinding in javax.swing

Methods in javax.swing that return JTextComponent.KeyBinding
static JTextComponent.KeyBinding[] LookAndFeel.makeKeyBindings(Object[] keyBindingList)
Convenience method for building lists of KeyBindings.

Uses of JTextComponent.KeyBinding in javax.swing.text

Methods in javax.swing.text with parameters of type JTextComponent.KeyBinding
static void JTextComponent.loadKeymap(Keymap map, JTextComponent.KeyBinding[] bindings, Action[] actions)
Loads a keymap with a bunch of bindings.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.swing.text.Keymap (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.swing.text.Keymap

Packages that use Keymap
javax.swing.plaf.basic | Provides user interface objects built according to the Basic look and feel.
javax.swing.text | Provides classes and interfaces that deal with editable and noneditable text components.

Uses of Keymap in javax.swing.plaf.basic

Methods in javax.swing.plaf.basic that return Keymap
protected  Keymap BasicTextUI.createKeymap()
Creates the keymap to use for the text component, and installs any necessary bindings into it.

Uses of Keymap in javax.swing.text

Methods in javax.swing.text that return Keymap
Keymap | Keymap.getResolveParent() Fetches the parent keymap used to resolve key-bindings.
Keymap | JTextComponent.getKeymap() Fetches the keymap currently active in this text component.
static Keymap | JTextComponent.addKeymap(String nm, Keymap parent) Adds a new keymap into the keymap hierarchy.
static Keymap | JTextComponent.removeKeymap(String nm) Removes a named keymap previously added to the document.
static Keymap | JTextComponent.getKeymap(String nm) Fetches a named keymap previously added to the document.

Methods in javax.swing.text with parameters of type Keymap
void | Keymap.setResolveParent(Keymap parent) Sets the parent keymap, which will be used to resolve key-bindings.
void | JTextComponent.setKeymap(Keymap map) Sets the keymap to use for binding events to actions.
static Keymap | JTextComponent.addKeymap(String nm, Keymap parent) Adds a new keymap into the keymap hierarchy.
static void | JTextComponent.loadKeymap(Keymap map, JTextComponent.KeyBinding[] bindings, Action[] actions) Loads a keymap with a bunch of bindings.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.LabelView (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.LabelView

Packages that use LabelView
javax.swing.text.html Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of LabelView in javax.swing.text.html

Subclasses of LabelView in javax.swing.text.html
 class InlineView
Displays the inline element styles based upon css attributes.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.LayeredHighlighter (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.LayeredHighlighter

Packages that use LayeredHighlighter
javax.swing.plaf.basic | Provides user interface objects built according to the Basic look and feel.
javax.swing.text | Provides classes and interfaces that deal with editable and noneditable text components.

Uses of LayeredHighlighter in javax.swing.plaf.basic

Subclasses of LayeredHighlighter in javax.swing.plaf.basic
static class BasicTextUI.BasicHighlighter

Uses of LayeredHighlighter in javax.swing.text

Subclasses of LayeredHighlighter in javax.swing.text
 class DefaultHighlighter
Implements the Highlighter interfaces.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.LayeredHighlighter.LayerPainter (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.LayeredHighlighter.LayerPainter

Packages that use LayeredHighlighter.LayerPainter
javax.swing.text Provides classes and interfaces that deal with editable and noneditable text components.

Uses of LayeredHighlighter.LayerPainter in javax.swing.text

Subclasses of LayeredHighlighter.LayerPainter in javax.swing.text
static class DefaultHighlighter.DefaultHighlightPainter
Simple highlight painter that fills a highlighted area with a solid color.

Fields in javax.swing.text declared as LayeredHighlighter.LayerPainter
static LayeredHighlighter.LayerPainter DefaultHighlighter.DefaultPainter
Default implementation of LayeredHighlighter.LayerPainter that can be used for painting highlights.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.LayoutQueue (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.LayoutQueue

Packages that use LayoutQueue
javax.swing.text Provides classes and interfaces that deal with editable and noneditable text components.

Uses of LayoutQueue in javax.swing.text

Methods in javax.swing.text that return LayoutQueue
static LayoutQueue | LayoutQueue.getDefaultQueue() Fetch the default layout queue.
protected LayoutQueue | AsyncBoxView.getLayoutQueue() Fetch the queue to use for layout.

Methods in javax.swing.text with parameters of type LayoutQueue
static void LayoutQueue.setDefaultQueue(LayoutQueue q)
Set the default layout queue.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.MaskFormatter (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.MaskFormatter

No usage of javax.swing.text.MaskFormatter

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.swing.text.MutableAttributeSet (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.swing.text.MutableAttributeSet

Packages that use MutableAttributeSet
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.text | Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.text.html | Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of MutableAttributeSet in javax.swing

Methods in javax.swing that return MutableAttributeSet
 MutableAttributeSet JTextPane.getInputAttributes()
Gets the input attributes for the pane.

Uses of MutableAttributeSet in javax.swing.text

Subinterfaces of MutableAttributeSet in javax.swing.text
 interface Style
A collection of attributes to associate with an element in a document.

Classes in javax.swing.text that implement MutableAttributeSet
class | AbstractDocument.AbstractElement Implements the abstract part of an element.
class | AbstractDocument.BranchElement Implements a composite element that contains other elements.
class | AbstractDocument.LeafElement Implements an element that directly represents content of some kind.
protected class | DefaultStyledDocument.SectionElement Default root element for a document...
class | SimpleAttributeSet A straightforward implementation of MutableAttributeSet using a hash table.
class | StyleContext.NamedStyle A collection of attributes, typically used to represent character and paragraph styles.

Methods in javax.swing.text that return MutableAttributeSet
MutableAttributeSet | StyledEditorKit.getInputAttributes() Gets the input attributes for the pane.
protected MutableAttributeSet | StyleContext.createLargeAttributeSet(AttributeSet a) Create a large set of attributes that should trade off space for time.

Methods in javax.swing.text with parameters of type MutableAttributeSet
protected void | StyledEditorKit.createInputAttributes(Element element, MutableAttributeSet set) Copies the key/values in elements AttributeSet into set.
void | StyleContext.readAttributes(ObjectInputStream in, MutableAttributeSet a) Context-specific handling of reading in attributes
static void | StyleContext.readAttributeSet(ObjectInputStream in, MutableAttributeSet a) Reads a set of attributes from the given object input stream that have been previously written out with writeAttributeSet.
static void | StyleConstants.setBidiLevel(MutableAttributeSet a, int o) Sets the BidiLevel.
static void | StyleConstants.setComponent(MutableAttributeSet a, Component c) Sets the component attribute.
static void | StyleConstants.setIcon(MutableAttributeSet a, Icon c) Sets the icon attribute.
static void | StyleConstants.setFontFamily(MutableAttributeSet a, String fam) Sets the font attribute.
static void | StyleConstants.setFontSize(MutableAttributeSet a, int s) Sets the font size attribute.
static void | StyleConstants.setBold(MutableAttributeSet a, boolean b) Sets the bold attribute.
static void | StyleConstants.setItalic(MutableAttributeSet a, boolean b) Sets the italic attribute.
static void | StyleConstants.setUnderline(MutableAttributeSet a, boolean b) Sets the underline attribute.
static void | StyleConstants.setStrikeThrough(MutableAttributeSet a, boolean b) Sets the strikethrough attribute.
static void | StyleConstants.setSuperscript(MutableAttributeSet a, boolean b) Sets the superscript attribute.
static void | StyleConstants.setSubscript(MutableAttributeSet a, boolean b) Sets the subscript attribute.
static void | StyleConstants.setForeground(MutableAttributeSet a, Color fg) Sets the foreground color.
static void | StyleConstants.setBackground(MutableAttributeSet a, Color fg) Sets the background color.
static void | StyleConstants.setFirstLineIndent(MutableAttributeSet a, float i) Sets the first line indent.
static void | StyleConstants.setRightIndent(MutableAttributeSet a, float i) Sets right indent.
static void | StyleConstants.setLeftIndent(MutableAttributeSet a, float i) Sets left indent.
static void | StyleConstants.setLineSpacing(MutableAttributeSet a, float i) Sets line spacing.
static void | StyleConstants.setSpaceAbove(MutableAttributeSet a, float i) Sets space above.
static void | StyleConstants.setSpaceBelow(MutableAttributeSet a, float i) Sets space below.
static void | StyleConstants.setAlignment(MutableAttributeSet a, int align) Sets alignment.
static void | StyleConstants.setTabSet(MutableAttributeSet a, TabSet tabs) Sets the TabSet.

Uses of MutableAttributeSet in javax.swing.text.html

Classes in javax.swing.text.html that implement MutableAttributeSet
class | HTMLDocument.BlockElement An element that represents a structural block of HTML.
class | HTMLDocument.RunElement An element that represents a chunk of text that has a set of HTML character level attributes assigned to it.

Fields in javax.swing.text.html declared as MutableAttributeSet
protected  MutableAttributeSet HTMLDocument.HTMLReader.charAttr

Methods in javax.swing.text.html that return MutableAttributeSet
MutableAttributeSet | HTMLEditorKit.getInputAttributes() Gets the input attributes used for the styled editing actions.
protected MutableAttributeSet | StyleSheet.createLargeAttributeSet(AttributeSet a) Creates a large set of attributes that should trade off space for time.

Methods in javax.swing.text.html with parameters of type MutableAttributeSet
protected void | HTMLEditorKit.createInputAttributes(Element element, MutableAttributeSet set) Copies the key/values in elements AttributeSet into set.
void | HTMLEditorKit.ParserCallback.handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos)
void | HTMLEditorKit.ParserCallback.handleSimpleTag(HTML.Tag t, MutableAttributeSet a, int pos)
void | StyleSheet.addCSSAttribute(MutableAttributeSet attr, CSS.Attribute key, String value) Adds a CSS attribute to the given set.
boolean | StyleSheet.addCSSAttributeFromHTML(MutableAttributeSet attr, CSS.Attribute key, String value) Adds a CSS attribute to the given set.
void | HTMLDocument.HTMLReader.handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos) Callback from the parser.
void | HTMLDocument.HTMLReader.handleSimpleTag(HTML.Tag t, MutableAttributeSet a, int pos) Callback from the parser.
protected void | HTMLDocument.HTMLReader.blockOpen(HTML.Tag t, MutableAttributeSet attr) Adds an instruction to the parse buffer to create a block element with the given attributes.
protected void | HTMLDocument.HTMLReader.addSpecialElement(HTML.Tag t, MutableAttributeSet a) Adds content that is basically specified entirely in the attribute set.
void | HTMLDocument.HTMLReader.TagAction.start(HTML.Tag t, MutableAttributeSet a) Called when a start tag is seen for the type of tag this action was registered to.
void | HTMLDocument.HTMLReader.BlockAction.start(HTML.Tag t, MutableAttributeSet attr)
void | HTMLDocument.HTMLReader.ParagraphAction.start(HTML.Tag t, MutableAttributeSet a)
void | HTMLDocument.HTMLReader.SpecialAction.start(HTML.Tag t, MutableAttributeSet a)
void | HTMLDocument.HTMLReader.IsindexAction.start(HTML.Tag t, MutableAttributeSet a)
void | HTMLDocument.HTMLReader.HiddenAction.start(HTML.Tag t, MutableAttributeSet a)
void | HTMLDocument.HTMLReader.PreAction.start(HTML.Tag t, MutableAttributeSet attr)
void | HTMLDocument.HTMLReader.CharacterAction.start(HTML.Tag t, MutableAttributeSet attr)
void | HTMLDocument.HTMLReader.FormAction.start(HTML.Tag t, MutableAttributeSet attr)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.NavigationFilter (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.NavigationFilter

Packages that use NavigationFilter
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.text | Provides classes and interfaces that deal with editable and noneditable text components.

Uses of NavigationFilter in javax.swing

Methods in javax.swing that return NavigationFilter
protected  NavigationFilter JFormattedTextField.AbstractFormatter.getNavigationFilter()
Subclass and override if you wish to provide a filter to restrict where the user can navigate to.

Uses of NavigationFilter in javax.swing.text

Methods in javax.swing.text that return NavigationFilter
protected NavigationFilter | DefaultFormatter.getNavigationFilter() Returns the NavigationFilter used to restrict where the cursor can be placed.
NavigationFilter | JTextComponent.getNavigationFilter() Returns the NavigationFilter.

Methods in javax.swing.text with parameters of type NavigationFilter
 void JTextComponent.setNavigationFilter(NavigationFilter filter)
Sets the NavigationFilter.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.NavigationFilter.FilterBypass (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.NavigationFilter.FilterBypass

Packages that use NavigationFilter.FilterBypass
javax.swing.text Provides classes and interfaces that deal with editable and noneditable text components.

Uses of NavigationFilter.FilterBypass in javax.swing.text

Methods in javax.swing.text with parameters of type NavigationFilter.FilterBypass
void | NavigationFilter.setDot(NavigationFilter.FilterBypass fb, int dot, Position.Bias bias) Invoked prior to the Caret setting the dot.
void | NavigationFilter.moveDot(NavigationFilter.FilterBypass fb, int dot, Position.Bias bias) Invoked prior to the Caret moving the dot.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.NumberFormatter (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.NumberFormatter

No usage of javax.swing.text.NumberFormatter

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.ParagraphView (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.ParagraphView

Packages that use ParagraphView
javax.swing.text.html Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of ParagraphView in javax.swing.text.html

Subclasses of ParagraphView in javax.swing.text.html
 class ParagraphView
Displays the a paragraph, and uses css attributes for its configuration.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.PasswordView (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.PasswordView

No usage of javax.swing.text.PasswordView

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.PlainDocument (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.PlainDocument

No usage of javax.swing.text.PlainDocument

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.PlainView (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.PlainView

Packages that use PlainView
javax.swing.text Provides classes and interfaces that deal with editable and noneditable text components.

Uses of PlainView in javax.swing.text

Subclasses of PlainView in javax.swing.text
class | FieldView Extends the multi-line plain text view to be suitable for a single-line editor view.
class | PasswordView Implements a View suitable for use in JPasswordField UI implementations.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.swing.text.Position (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.swing.text.Position

Packages that use Position
javax.swing.text Provides classes and interfaces that deal with editable and noneditable text components.

Uses of Position in javax.swing.text

Methods in javax.swing.text that return Position
Position | StringContent.createPosition(int offset) Creates a position within the content that will track change as the content is mutated.
Position | GapContent.createPosition(int offset) Creates a position within the content that will track change as the content is mutated.
Position | AbstractDocument.createPosition(int offs) Returns a position that will track change as the document is altered.
Position | AbstractDocument.getStartPosition() Returns a position that represents the start of the document.
Position | AbstractDocument.getEndPosition() Returns a position that represents the end of the document.
Position | AbstractDocument.Content.createPosition(int offset) Creates a position within the content that will track change as the content is mutated.
Position | Document.getStartPosition() Returns a position that represents the start of the document.
Position | Document.getEndPosition() Returns a position that represents the end of the document.
Position | Document.createPosition(int offs) This method allows an application to mark a place in a sequence of character content.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.Position.Bias (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.Position.Bias

Packages that use Position.Bias
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.plaf | Provides one interface and many abstract classes that Swing uses to provide its pluggable look-and-feel capabilities.
javax.swing.plaf.basic | Provides user interface objects built according to the Basic look and feel.
javax.swing.plaf.multi | Provides user interface objects that combine two or more look and feels.
javax.swing.text | Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.text.html | Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of Position.Bias in javax.swing

Methods in javax.swing with parameters of type Position.Bias
int | JList.getNextMatch(String prefix, int startIndex, Position.Bias bias) Returns the next list element that starts with a prefix.
TreePath | JTree.getNextMatch(String prefix, int startingRow, Position.Bias bias) Returns the TreePath to the next tree element that begins with a prefix.

Uses of Position.Bias in javax.swing.plaf

Methods in javax.swing.plaf with parameters of type Position.Bias
abstract Rectangle | TextUI.modelToView(JTextComponent t, int pos, Position.Bias bias) Converts the given location in the model to a place in the view coordinate system.
abstract int | TextUI.viewToModel(JTextComponent t, Point pt, Position.Bias[] biasReturn) Provides a mapping from the view coordinate space to the logical coordinate space of the model.
abstract int | TextUI.getNextVisualPositionFrom(JTextComponent t, int pos, Position.Bias b, int direction, Position.Bias[] biasRet) Provides a way to determine the next visually represented model location that one might place a caret.
abstract void | TextUI.damageRange(JTextComponent t, int p0, int p1, Position.Bias firstBias, Position.Bias secondBias) Causes the portion of the view responsible for the given part of the model to be repainted.

Uses of Position.Bias in javax.swing.plaf.basic

Methods in javax.swing.plaf.basic with parameters of type Position.Bias
Rectangle | BasicTextUI.modelToView(JTextComponent tc, int pos, Position.Bias bias) Converts the given location in the model to a place in the view coordinate system.
int | BasicTextUI.viewToModel(JTextComponent tc, Point pt, Position.Bias[] biasReturn) Converts the given place in the view coordinate system to the nearest representative location in the model.
int | BasicTextUI.getNextVisualPositionFrom(JTextComponent t, int pos, Position.Bias b, int direction, Position.Bias[] biasRet) Provides a way to determine the next visually represented model location that one might place a caret.
void | BasicTextUI.damageRange(JTextComponent t, int p0, int p1, Position.Bias p0Bias, Position.Bias p1Bias) Causes the portion of the view responsible for the given part of the model to be repainted.

Uses of Position.Bias in javax.swing.plaf.multi

Methods in javax.swing.plaf.multi with parameters of type Position.Bias
Rectangle | MultiTextUI.modelToView(JTextComponent a, int b, Position.Bias c) Invokes the modelToView method on each UI handled by this object.
int | MultiTextUI.viewToModel(JTextComponent a, Point b, Position.Bias[] c) Invokes the viewToModel method on each UI handled by this object.
int | MultiTextUI.getNextVisualPositionFrom(JTextComponent a, int b, Position.Bias c, int d, Position.Bias[] e) Invokes the getNextVisualPositionFrom method on each UI handled by this object.
void | MultiTextUI.damageRange(JTextComponent a, int b, int c, Position.Bias d, Position.Bias e) Invokes the damageRange method on each UI handled by this object.

Uses of Position.Bias in javax.swing.text

Fields in javax.swing.text declared as Position.Bias
static Position.Bias | Position.Bias.Forward Indicates to bias toward the next character in the model.
static Position.Bias | Position.Bias.Backward Indicates a bias toward the previous character in the model.

Methods in javax.swing.text with parameters of type Position.Bias
Shape | PasswordView.modelToView(int pos, Shape a, Position.Bias b) Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
int | PasswordView.viewToModel(float fx, float fy, Shape a, Position.Bias[] bias) Provides a mapping from the view coordinate space to the logical coordinate space of the model.
Shape | PlainView.modelToView(int pos, Shape a, Position.Bias b) Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
int | PlainView.viewToModel(float fx, float fy, Shape a, Position.Bias[] bias) Provides a mapping from the view coordinate space to the logical coordinate space of the model.
Shape | FieldView.modelToView(int pos, Shape a, Position.Bias b) Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
int | FieldView.viewToModel(float fx, float fy, Shape a, Position.Bias[] bias) Provides a mapping from the view coordinate space to the logical coordinate space of the model.
protected int | AsyncBoxView.getViewIndexAtPosition(int pos, Position.Bias b) Fetches the child view index representing the given position in the model.
int | AsyncBoxView.getViewIndex(int pos, Position.Bias b) Returns the child view index representing the given position in the model.
Shape | AsyncBoxView.modelToView(int pos, Shape a, Position.Bias b) Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
int | AsyncBoxView.viewToModel(float x, float y, Shape a, Position.Bias[] biasReturn) Provides a mapping from the view coordinate space to the logical coordinate space of the model.
int | AsyncBoxView.getNextVisualPositionFrom(int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet) Provides a way to determine the next visually represented model location that one might place a caret.
Shape | IconView.modelToView(int pos, Shape a, Position.Bias b) Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
int | IconView.viewToModel(float x, float y, Shape a, Position.Bias[] bias) Provides a mapping from the view coordinate space to the logical coordinate space of the model.
Shape | ComponentView.modelToView(int pos, Shape a, Position.Bias b) Provides a mapping from the coordinate space of the model to that of the view.
int | ComponentView.viewToModel(float x, float y, Shape a, Position.Bias[] bias) Provides a mapping from the view coordinate space to the logical coordinate space of the model.
Shape | GlyphView.modelToView(int pos, Shape a, Position.Bias b) Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
int | GlyphView.viewToModel(float x, float y, Shape a, Position.Bias[] biasReturn) Provides a mapping from the view coordinate space to the logical coordinate space of the model.
int | GlyphView.getNextVisualPositionFrom(int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet) Provides a way to determine the next visually represented model location that one might place a caret.
abstract Shape | GlyphView.GlyphPainter.modelToView(GlyphView v, int pos, Position.Bias bias, Shape a) Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
abstract int | GlyphView.GlyphPainter.viewToModel(GlyphView v, float x, float y, Shape a, Position.Bias[] biasReturn) Provides a mapping from the view coordinate space to the logical coordinate space of the model.
int | GlyphView.GlyphPainter.getNextVisualPositionFrom(GlyphView v, int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet) Provides a way to determine the next visually represented model location that one might place a caret.
Shape | CompositeView.modelToView(int pos, Shape a, Position.Bias b) Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
Shape | CompositeView.modelToView(int p0, Position.Bias b0, int p1, Position.Bias b1, Shape a) Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
int | CompositeView.viewToModel(float x, float y, Shape a, Position.Bias[] bias) Provides a mapping from the view coordinate space to the logical coordinate space of the model.
int | CompositeView.getNextVisualPositionFrom(int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet) Provides a way to determine the next visually represented model location that one might place a caret.
int | CompositeView.getViewIndex(int pos, Position.Bias b) Returns the child view index representing the given position in the model.
protected int | CompositeView.getNextNorthSouthVisualPositionFrom(int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet) Returns the next visual position for the cursor, in either the north or south direction.
protected int | CompositeView.getNextEastWestVisualPositionFrom(int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet) Returns the next visual position for the cursor, in either the east or west direction.
protected boolean | CompositeView.flipEastAndWestAtEnds(int position, Position.Bias bias) Determines in which direction the next view lays.
Shape | BoxView.modelToView(int pos, Shape a, Position.Bias b) Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
int | BoxView.viewToModel(float x, float y, Shape a, Position.Bias[] bias) Provides a mapping from the view coordinate space to the logical coordinate space of the model.
protected boolean | BoxView.flipEastAndWestAtEnds(int position, Position.Bias bias) Determines in which direction the next view lays.
protected int | ParagraphView.getNextNorthSouthVisualPositionFrom(int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet) Returns the next visual position for the cursor, in either the east or west direction.
protected int | ParagraphView.getClosestPositionTo(int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet, int rowIndex, int x) Returns the closest model position to x.
protected boolean | ParagraphView.flipEastAndWestAtEnds(int position, Position.Bias bias) Determines in which direction the next view lays.
void | NavigationFilter.setDot(NavigationFilter.FilterBypass fb, int dot, Position.Bias bias) Invoked prior to the Caret setting the dot.
void | NavigationFilter.moveDot(NavigationFilter.FilterBypass fb, int dot, Position.Bias bias) Invoked prior to the Caret moving the dot.
int | NavigationFilter.getNextVisualPositionFrom(JTextComponent text, int pos, Position.Bias bias, int direction, Position.Bias[] biasRet) Returns the next visual position to place the caret at from an existing position.
abstract void | NavigationFilter.FilterBypass.setDot(int dot, Position.Bias bias) Sets the caret location, bypassing the NavigationFilter.
abstract void | NavigationFilter.FilterBypass.moveDot(int dot, Position.Bias bias) Moves the caret location, bypassing the NavigationFilter.
int | View.getViewIndex(int pos, Position.Bias b) Returns the child view index representing the given position in the model.
int | View.getNextVisualPositionFrom(int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet) Provides a way to determine the next visually represented model location at which one might place a caret.
abstract Shape | View.modelToView(int pos, Shape a, Position.Bias b) Provides a mapping, for a given character, from the document model coordinate space to the view coordinate space.
Shape | View.modelToView(int p0, Position.Bias b0, int p1, Position.Bias b1, Shape a) Provides a mapping, for a given region, from the document model coordinate space to the view coordinate space.
abstract int | View.viewToModel(float x, float y, Shape a, Position.Bias[] biasReturn) Provides a mapping from the view coordinate space to the logical coordinate space of the model.

Uses of Position.Bias in javax.swing.text.html

Methods in javax.swing.text.html with parameters of type Position.Bias
Shape | ImageView.modelToView(int pos, Shape a, Position.Bias b) Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
int | ImageView.viewToModel(float x, float y, Shape a, Position.Bias[] bias) Provides a mapping from the view coordinate space to the logical coordinate space of the model.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.Segment (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.Segment

Packages that use Segment
javax.swing.text Provides classes and interfaces that deal with editable and noneditable text components.

Uses of Segment in javax.swing.text

Methods in javax.swing.text that return Segment
protected Segment | PlainView.getLineBuffer() Gives access to a buffer that can be used to fetch text from the associated document.
protected Segment | WrappedPlainView.getLineBuffer() Gives access to a buffer that can be used to fetch text from the associated document.
Segment | GlyphView.getText(int p0, int p1) Fetch a reference to the text that occupies the given range.

Methods in javax.swing.text with parameters of type Segment
void | StringContent.getChars(int where, int len, Segment chars) Retrieves a portion of the content.
void | GapContent.getChars(int where, int len, Segment chars) Retrieves a portion of the content.
void | AbstractDocument.getText(int offset, int length, Segment txt) Fetches the text contained within the given portion of the document.
void | AbstractDocument.Content.getChars(int where, int len, Segment txt) Gets a sequence of characters and copies them into a Segment.
static int | Utilities.drawTabbedText(Segment s, int x, int y, Graphics g, TabExpander e, int startOffset) Draws the given text, expanding any tabs that are contained using the given tab expansion technique.
static int | Utilities.getTabbedTextWidth(Segment s, FontMetrics metrics, int x, TabExpander e, int startOffset) Determines the width of the given segment of text taking tabs into consideration.
static int | Utilities.getTabbedTextOffset(Segment s, FontMetrics metrics, int x0, int x, TabExpander e, int startOffset) Determines the relative offset into the given text that best represents the given span in the view coordinate system.
static int | Utilities.getTabbedTextOffset(Segment s, FontMetrics metrics, int x0, int x, TabExpander e, int startOffset, boolean round)
static int | Utilities.getBreakLocation(Segment s, FontMetrics metrics, int x0, int x, TabExpander e, int startOffset) Determine where to break the given text to fit within the the given span.
void | Document.getText(int offset, int length, Segment txt) Fetches the text contained within the given portion of the document.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.SimpleAttributeSet (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.SimpleAttributeSet

Packages that use SimpleAttributeSet
javax.swing.text.html.parser Provides the default HTML parser, along with support classes.

Uses of SimpleAttributeSet in javax.swing.text.html.parser

Methods in javax.swing.text.html.parser that return SimpleAttributeSet
protected  SimpleAttributeSet Parser.getAttributes()

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.StringContent (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.StringContent

No usage of javax.swing.text.StringContent

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.swing.text.Style (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.swing.text.Style

Packages that use Style
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.text | Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.text.html | Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of Style in javax.swing

Methods in javax.swing that return Style
Style | JTextPane.addStyle(String nm, Style parent) Adds a new style into the logical style hierarchy.
Style | JTextPane.getStyle(String nm) Fetches a named non-null style previously added.
Style | JTextPane.getLogicalStyle() Fetches the logical style assigned to the paragraph represented by the current position of the caret, or null.

Methods in javax.swing with parameters of type Style
Style | JTextPane.addStyle(String nm, Style parent) Adds a new style into the logical style hierarchy.
void | JTextPane.setLogicalStyle(Style s) Sets the logical style to use for the paragraph at the current caret position.

Uses of Style in javax.swing.text

Classes in javax.swing.text that implement Style
 class StyleContext.NamedStyle
A collection of attributes, typically used to represent character and paragraph styles.

Methods in javax.swing.text that return Style
Style | StyleContext.addStyle(String nm, Style parent) Adds a new style into the style hierarchy.
Style | StyleContext.getStyle(String nm) Fetches a named style previously added to the document
Style | DefaultStyledDocument.addStyle(String nm, Style parent) Adds a new style into the logical style hierarchy.
Style | DefaultStyledDocument.getStyle(String nm) Fetches a named style previously added.
Style | DefaultStyledDocument.getLogicalStyle(int p) Fetches the logical style assigned to the paragraph represented by the given position.
Style | StyledDocument.addStyle(String nm, Style parent) Adds a new style into the logical style hierarchy.
Style | StyledDocument.getStyle(String nm) Fetches a named style previously added.
Style | StyledDocument.getLogicalStyle(int p) Gets a logical style for a given position in a paragraph.

Methods in javax.swing.text with parameters of type Style
Style | StyleContext.addStyle(String nm, Style parent) Adds a new style into the style hierarchy.
Style | DefaultStyledDocument.addStyle(String nm, Style parent) Adds a new style into the logical style hierarchy.
void | DefaultStyledDocument.setLogicalStyle(int pos, Style s) Sets the logical style to use for the paragraph at the given position.
protected void | DefaultStyledDocument.styleChanged(Style style) Called when any of this document's styles have changed.
Style | StyledDocument.addStyle(String nm, Style parent) Adds a new style into the logical style hierarchy.
void | StyledDocument.setLogicalStyle(int pos, Style s) Sets the logical style to use for the paragraph at the given position.

Constructors in javax.swing.text with parameters of type Style
StyleContext.NamedStyle(String name, Style parent)
Creates a new named style.
StyleContext.NamedStyle(Style parent)
Creates a new named style.

Uses of Style in javax.swing.text.html

Methods in javax.swing.text.html that return Style
Style | StyleSheet.getRule(HTML.Tag t, Element e) Fetches the style to use to render the given type of HTML tag.
Style | StyleSheet.getRule(String selector) Fetches the rule that best matches the selector given in string form.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.StyleConstants (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.StyleConstants

Packages that use StyleConstants
javax.swing.text Provides classes and interfaces that deal with editable and noneditable text components.

Uses of StyleConstants in javax.swing.text

Subclasses of StyleConstants in javax.swing.text
static class | StyleConstants.CharacterConstants This is a typesafe enumeration of the well-known attributes that contribute to a character style.
static class | StyleConstants.ColorConstants This is a typesafe enumeration of the well-known attributes that contribute to a color.
static class | StyleConstants.FontConstants This is a typesafe enumeration of the well-known attributes that contribute to a font.
static class | StyleConstants.ParagraphConstants This is a typesafe enumeration of the well-known attributes that contribute to a paragraph style.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.StyleConstants.CharacterConstants (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.StyleConstants.CharacterConstants

No usage of javax.swing.text.StyleConstants.CharacterConstants

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.StyleConstants.ColorConstants (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.StyleConstants.ColorConstants

No usage of javax.swing.text.StyleConstants.ColorConstants

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.StyleConstants.FontConstants (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.StyleConstants.FontConstants

No usage of javax.swing.text.StyleConstants.FontConstants

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.StyleConstants.ParagraphConstants (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.StyleConstants.ParagraphConstants

No usage of javax.swing.text.StyleConstants.ParagraphConstants

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.StyleContext (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.StyleContext

Packages that use StyleContext
javax.swing.text | Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.text.html | Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of StyleContext in javax.swing.text

Methods in javax.swing.text that return StyleContext
static StyleContext StyleContext.getDefaultStyleContext()
Returns default AttributeContext shared by all documents that don't bother to define/supply their own context.

Constructors in javax.swing.text with parameters of type StyleContext
DefaultStyledDocument(AbstractDocument.Content c, StyleContext styles)
Constructs a styled document.
DefaultStyledDocument(StyleContext styles)
Constructs a styled document with the default content storage implementation and a shared set of styles.

Uses of StyleContext in javax.swing.text.html

Subclasses of StyleContext in javax.swing.text.html
 class StyleSheet
Support for defining the visual characteristics of HTML views being rendered.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.StyleContext.NamedStyle (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.StyleContext.NamedStyle

No usage of javax.swing.text.StyleContext.NamedStyle

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.StyleContext.SmallAttributeSet (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.StyleContext.SmallAttributeSet

Packages that use StyleContext.SmallAttributeSet
javax.swing.text | Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.text.html | Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of StyleContext.SmallAttributeSet in javax.swing.text

Methods in javax.swing.text that return StyleContext.SmallAttributeSet
protected  StyleContext.SmallAttributeSet StyleContext.createSmallAttributeSet(AttributeSet a)
Create a compact set of attributes that might be shared.

Uses of StyleContext.SmallAttributeSet in javax.swing.text.html

Methods in javax.swing.text.html that return StyleContext.SmallAttributeSet
protected  StyleContext.SmallAttributeSet StyleSheet.createSmallAttributeSet(AttributeSet a)
Creates a compact set of attributes that might be shared.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.swing.text.StyledDocument (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.swing.text.StyledDocument

Packages that use StyledDocument
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.text | Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.text.html | Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of StyledDocument in javax.swing

Methods in javax.swing that return StyledDocument
 StyledDocument JTextPane.getStyledDocument()
Fetches the model associated with the editor.

Methods in javax.swing with parameters of type StyledDocument
 void JTextPane.setStyledDocument(StyledDocument doc)
Associates the editor with a text document.

Constructors in javax.swing with parameters of type StyledDocument
JTextPane(StyledDocument doc)
Creates a new JTextPane, with a specified document model.

Uses of StyledDocument in javax.swing.text

Classes in javax.swing.text that implement StyledDocument
 class DefaultStyledDocument
A document that can be marked up with character and paragraph styles in a manner similar to the Rich Text Format.

Methods in javax.swing.text that return StyledDocument
protected  StyledDocument StyledEditorKit.StyledTextAction.getStyledDocument(JEditorPane e)
Gets the document associated with an editor pane.

Uses of StyledDocument in javax.swing.text.html

Classes in javax.swing.text.html that implement StyledDocument
 class HTMLDocument
A document that models HTML.

Constructors in javax.swing.text.html with parameters of type StyledDocument
MinimalHTMLWriter(Writer w, StyledDocument doc)
Creates a new MinimalHTMLWriter.
MinimalHTMLWriter(Writer w, StyledDocument doc, int pos, int len)
Creates a new MinimalHTMLWriter.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.StyledEditorKit (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.StyledEditorKit

Packages that use StyledEditorKit
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.text | Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.text.html | Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.
javax.swing.text.rtf | Provides a class (RTFEditorKit) for creating Rich-Text-Format text editors.

Uses of StyledEditorKit in javax.swing

Methods in javax.swing that return StyledEditorKit
protected  StyledEditorKit JTextPane.getStyledEditorKit()
Gets the editor kit.

Uses of StyledEditorKit in javax.swing.text

Methods in javax.swing.text that return StyledEditorKit
protected  StyledEditorKit StyledEditorKit.StyledTextAction.getStyledEditorKit(JEditorPane e)
Gets the editor kit associated with an editor pane.

Uses of StyledEditorKit in javax.swing.text.html

Subclasses of StyledEditorKit in javax.swing.text.html
 class HTMLEditorKit
The Swing JEditorPane text component supports different kinds of content via a plug-in mechanism called an EditorKit.

Uses of StyledEditorKit in javax.swing.text.rtf

Subclasses of StyledEditorKit in javax.swing.text.rtf
 class RTFEditorKit
This is the default implementation of RTF editing functionality.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.StyledEditorKit.AlignmentAction (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.StyledEditorKit.AlignmentAction

No usage of javax.swing.text.StyledEditorKit.AlignmentAction

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.StyledEditorKit.BoldAction (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.StyledEditorKit.BoldAction

No usage of javax.swing.text.StyledEditorKit.BoldAction

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.StyledEditorKit.FontFamilyAction (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.StyledEditorKit.FontFamilyAction

No usage of javax.swing.text.StyledEditorKit.FontFamilyAction

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.StyledEditorKit.FontSizeAction (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.StyledEditorKit.FontSizeAction

No usage of javax.swing.text.StyledEditorKit.FontSizeAction

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.StyledEditorKit.ForegroundAction (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.StyledEditorKit.ForegroundAction

No usage of javax.swing.text.StyledEditorKit.ForegroundAction

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.StyledEditorKit.ItalicAction (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.StyledEditorKit.ItalicAction

No usage of javax.swing.text.StyledEditorKit.ItalicAction

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.StyledEditorKit.StyledTextAction (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.StyledEditorKit.StyledTextAction

Packages that use StyledEditorKit.StyledTextAction
javax.swing.text | Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.text.html | Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of StyledEditorKit.StyledTextAction in javax.swing.text

Subclasses of StyledEditorKit.StyledTextAction in javax.swing.text
static class | StyledEditorKit.AlignmentAction An action to set paragraph alignment.
static class | StyledEditorKit.BoldAction An action to toggle the bold attribute.
static class | StyledEditorKit.FontFamilyAction An action to set the font family in the associated JEditorPane.
static class | StyledEditorKit.FontSizeAction An action to set the font size in the associated JEditorPane.
static class | StyledEditorKit.ForegroundAction An action to set foreground color.
static class | StyledEditorKit.ItalicAction An action to toggle the italic attribute.
static class | StyledEditorKit.UnderlineAction An action to toggle the underline attribute.

Uses of StyledEditorKit.StyledTextAction in javax.swing.text.html

Subclasses of StyledEditorKit.StyledTextAction in javax.swing.text.html
static class | HTMLEditorKit.HTMLTextAction An abstract Action providing some convenience methods that may be useful in inserting HTML into an existing document.
static class | HTMLEditorKit.InsertHTMLTextAction InsertHTMLTextAction can be used to insert an arbitrary string of HTML into an existing HTML document.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.StyledEditorKit.UnderlineAction (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.StyledEditorKit.UnderlineAction

No usage of javax.swing.text.StyledEditorKit.UnderlineAction

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.swing.text.TabableView (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.swing.text.TabableView

Packages that use TabableView
javax.swing.text | Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.text.html | Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of TabableView in javax.swing.text

Classes in javax.swing.text that implement TabableView
class | GlyphView A GlyphView is a styled chunk of text that represents a view mapped over an element in the text model.
class | LabelView A LabelView is a styled chunk of text that represents a view mapped over an element in the text model.

Uses of TabableView in javax.swing.text.html

Classes in javax.swing.text.html that implement TabableView
 class InlineView
Displays the inline element styles based upon css attributes.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.swing.text.TabExpander (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.swing.text.TabExpander

Packages that use TabExpander
javax.swing.text Provides classes and interfaces that deal with editable and noneditable text components.

Uses of TabExpander in javax.swing.text

Classes in javax.swing.text that implement TabExpander
class | FieldView Extends the multi-line plain text view to be suitable for a single-line editor view.
class | ParagraphView View of a simple line-wrapping paragraph that supports multiple fonts, colors, components, icons, etc.
class | PasswordView Implements a View suitable for use in JPasswordField UI implementations.
class | PlainView Implements View interface for a simple multi-line text view that has text in one font and color.
class | WrappedPlainView View of plain text (text with only one font and color) that does line-wrapping.

Methods in javax.swing.text that return TabExpander
 TabExpander GlyphView.getTabExpander()
Fetch the TabExpander to use if tabs are present in this view.

Methods in javax.swing.text with parameters of type TabExpander
float | TabableView.getTabbedSpan(float x, TabExpander e) Determines the desired span when using the given tab expansion implementation.
float | GlyphView.getTabbedSpan(float x, TabExpander e) Determines the desired span when using the given tab expansion implementation.
abstract float | GlyphView.GlyphPainter.getSpan(GlyphView v, int p0, int p1, TabExpander e, float x) Determine the span the glyphs given a start location (for tab expansion).
static int | Utilities.drawTabbedText(Segment s, int x, int y, Graphics g, TabExpander e, int startOffset) Draws the given text, expanding any tabs that are contained using the given tab expansion technique.
static int | Utilities.getTabbedTextWidth(Segment s, FontMetrics metrics, int x, TabExpander e, int startOffset) Determines the width of the given segment of text taking tabs into consideration.
static int | Utilities.getTabbedTextOffset(Segment s, FontMetrics metrics, int x0, int x, TabExpander e, int startOffset) Determines the relative offset into the given text that best represents the given span in the view coordinate system.
static int | Utilities.getTabbedTextOffset(Segment s, FontMetrics metrics, int x0, int x, TabExpander e, int startOffset, boolean round)
static int | Utilities.getBreakLocation(Segment s, FontMetrics metrics, int x0, int x, TabExpander e, int startOffset) Determine where to break the given text to fit within the the given span.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.TableView (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.TableView

No usage of javax.swing.text.TableView

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.TableView.TableCell (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.TableView.TableCell

Packages that use TableView.TableCell
javax.swing.text Provides classes and interfaces that deal with editable and noneditable text components.

Uses of TableView.TableCell in javax.swing.text

Methods in javax.swing.text that return TableView.TableCell
protected  TableView.TableCell TableView.createTableCell(Element elem)
Deprecated. Table cells can now be any arbitrary View implementation and should be produced by the ViewFactory rather than the table.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.TableView.TableRow (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.TableView.TableRow

Packages that use TableView.TableRow
javax.swing.text Provides classes and interfaces that deal with editable and noneditable text components.

Uses of TableView.TableRow in javax.swing.text

Methods in javax.swing.text that return TableView.TableRow
protected  TableView.TableRow TableView.createTableRow(Element elem)
Creates a new table row.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.TabSet (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.TabSet

Packages that use TabSet
javax.swing.text Provides classes and interfaces that deal with editable and noneditable text components.

Uses of TabSet in javax.swing.text

Methods in javax.swing.text that return TabSet
protected TabSet | ParagraphView.getTabSet() Gets the Tabset to be used in calculating tabs.
static TabSet | StyleConstants.getTabSet(AttributeSet a) Gets the TabSet.

Methods in javax.swing.text with parameters of type TabSet
static void StyleConstants.setTabSet(MutableAttributeSet a, TabSet tabs)
Sets the TabSet.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.TabStop (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.TabStop

Packages that use TabStop
javax.swing.text Provides classes and interfaces that deal with editable and noneditable text components.

Uses of TabStop in javax.swing.text

Methods in javax.swing.text that return TabStop
TabStop | TabSet.getTab(int index) Returns the TabStop at index index.
TabStop | TabSet.getTabAfter(float location) Returns the Tab instance after location.

Methods in javax.swing.text with parameters of type TabStop
 int TabSet.getTabIndex(TabStop tab)

Constructors in javax.swing.text with parameters of type TabStop
TabSet(TabStop[] tabs)
Creates and returns an instance of TabSet.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.TextAction (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.TextAction

Packages that use TextAction
javax.swing.text | Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.text.html | Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of TextAction in javax.swing.text

Subclasses of TextAction in javax.swing.text
static class | DefaultEditorKit.BeepAction Creates a beep.
static class | DefaultEditorKit.CopyAction Copies the selected region and place its contents into the system clipboard.
static class | DefaultEditorKit.CutAction Cuts the selected region and place its contents into the system clipboard.
static class | DefaultEditorKit.DefaultKeyTypedAction The action that is executed by default if a key typed event is received and there is no keymap entry.
static class | DefaultEditorKit.InsertBreakAction Places a line/paragraph break into the document.
static class | DefaultEditorKit.InsertContentAction Places content into the associated document.
static class | DefaultEditorKit.InsertTabAction Places a tab character into the document.
static class | DefaultEditorKit.PasteAction Pastes the contents of the system clipboard into the selected region, or before the caret if nothing is selected.
static class | StyledEditorKit.AlignmentAction An action to set paragraph alignment.
static class | StyledEditorKit.BoldAction An action to toggle the bold attribute.
static class | StyledEditorKit.FontFamilyAction An action to set the font family in the associated JEditorPane.
static class | StyledEditorKit.FontSizeAction An action to set the font size in the associated JEditorPane.
static class | StyledEditorKit.ForegroundAction An action to set foreground color.
static class | StyledEditorKit.ItalicAction An action to toggle the italic attribute.
static class | StyledEditorKit.StyledTextAction An action that assumes it's being fired on a JEditorPane with a StyledEditorKit (or subclass) installed.
static class | StyledEditorKit.UnderlineAction An action to toggle the underline attribute.

Uses of TextAction in javax.swing.text.html

Subclasses of TextAction in javax.swing.text.html
static class | HTMLEditorKit.HTMLTextAction An abstract Action providing some convenience methods that may be useful in inserting HTML into an existing document.
static class | HTMLEditorKit.InsertHTMLTextAction InsertHTMLTextAction can be used to insert an arbitrary string of HTML into an existing HTML document.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.Utilities (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.Utilities

No usage of javax.swing.text.Utilities

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.View (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.View

Packages that use View
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 | Provides user interface objects built according to the Basic look and feel.
javax.swing.plaf.multi | Provides user interface objects that combine two or more look and feels.
javax.swing.text | Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.text.html | Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of View in javax.swing.plaf

Methods in javax.swing.plaf that return View
abstract  View TextUI.getRootView(JTextComponent t)
Fetches a View with the allocation of the associated text component (i.e.

Uses of View in javax.swing.plaf.basic

Methods in javax.swing.plaf.basic that return View
View | BasicTextAreaUI.create(Element elem) Creates the view for an element.
protected View | BasicTabbedPaneUI.getTextViewForTab(int tabIndex) Returns the text View object required to render stylized text (HTML) for the specified tab or null if no specialized text rendering is needed for this tab.
View | BasicPasswordFieldUI.create(Element elem) Creates a view (PasswordView) for an element.
View | BasicTextFieldUI.create(Element elem) Creates a view (FieldView) based on an element.
static View | BasicHTML.createHTMLView(JComponent c, String html) Create an html renderer for the given component and string of html.
View | BasicTextUI.getRootView(JTextComponent tc) Fetches a View with the allocation of the associated text component (i.e.
View | BasicTextUI.create(Element elem) Creates a view for an element.
View | BasicTextUI.create(Element elem, int p0, int p1) Creates a view for an element.

Methods in javax.swing.plaf.basic with parameters of type View
protected  void BasicTextUI.setView(View v)
Sets the current root of the view hierarchy and calls invalidate().

Uses of View in javax.swing.plaf.multi

Methods in javax.swing.plaf.multi that return View
 View MultiTextUI.getRootView(JTextComponent a)
Invokes the getRootView method on each UI handled by this object.

Uses of View in javax.swing.text

Subclasses of View in javax.swing.text
class | AsyncBoxView A box that does layout asynchronously.
class | BoxView A view that arranges its children into a box shape by tiling its children along an axis.
class | ComponentView Component decorator that implements the view interface.
class | CompositeView CompositeView is an abstract View implementation which manages one or more child views.
class | FieldView Extends the multi-line plain text view to be suitable for a single-line editor view.
class | FlowView A View that tries to flow it's children into some partially constrained space.
class | GlyphView A GlyphView is a styled chunk of text that represents a view mapped over an element in the text model.
class | IconView Icon decorator that implements the view interface.
class | LabelView A LabelView is a styled chunk of text that represents a view mapped over an element in the text model.
class | ParagraphView View of a simple line-wrapping paragraph that supports multiple fonts, colors, components, icons, etc.
class | PasswordView Implements a View suitable for use in JPasswordField UI implementations.
class | PlainView Implements View interface for a simple multi-line text view that has text in one font and color.
class | TableView 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.
class | TableView.TableCell Deprecated. A table cell can now be any View implementation.
class | TableView.TableRow View of a row in a row-centric table.
class | WrappedPlainView View of plain text (text with only one font and color) that does line-wrapping.
class | ZoneView 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.

Fields in javax.swing.text declared as View
protected  View FlowView.layoutPool
These are the views that represent the child elements of the element this view represents (The logical view to translate to a physical view).

Methods in javax.swing.text that return View
protected View | ZoneView.createZone(int p0, int p1) Create a view to represent a zone for the given range within the model (which should be within the range of this objects responsibility).
protected View | TableView.getViewAtPosition(int pos, Rectangle a) Fetches the child view that represents the given position in the model.
protected View | TableView.TableRow.getViewAtPosition(int pos, Rectangle a) Fetches the child view that represents the given position in the model.
View | AsyncBoxView.getView(int n) Gets the nth child view.
View | AsyncBoxView.ChildState.getChildView() Fetch the child view this record represents
View | GlyphView.breakView(int axis, int p0, float pos, float len) Breaks this view on the given axis at the given length.
View | GlyphView.createFragment(int p0, int p1) Creates a view that represents a portion of the element.
View | CompositeView.getView(int n) Returns the n-th view in this container.
protected abstract View | CompositeView.getViewAtPoint(int x, int y, Rectangle alloc) Fetches the child view at the given coordinates.
protected View | CompositeView.getViewAtPosition(int pos, Rectangle a) Fetches the child view that represents the given position in the model.
protected View | BoxView.getViewAtPoint(int x, int y, Rectangle alloc) Fetches the child view at the given coordinates.
protected View | FlowView.FlowStrategy.getLogicalView(FlowView fv) This method gives flow strategies access to the logical view of the FlowView.
protected View | FlowView.FlowStrategy.createView(FlowView fv, int startOffset, int spanLeft, int rowIndex) Creates a view that can be used to represent the current piece of the flow.
protected abstract View | FlowView.createRow() Create a View that should be used to hold a a rows worth of children in a flow.
protected View | ParagraphView.getLayoutView(int index) Returns the view at a given index.
protected View | ParagraphView.createRow() Create a View that should be used to hold a a row's worth of children in a flow.
View | ParagraphView.breakView(int axis, float len, Shape a) Breaks this view on the given axis at the given length.
View | ViewFactory.create(Element elem) Creates a view from the given structural element of a document.
View | View.getParent() Returns the parent of the view.
View | View.getView(int n) Gets the nth child view.
View | View.breakView(int axis, int offset, float pos, float len) Tries to break this view on the given axis.
View | View.createFragment(int p0, int p1) Creates a view that represents a portion of the element.

Methods in javax.swing.text with parameters of type View
protected void | ZoneView.zoneWasLoaded(View zone) Called by a zone when it gets loaded.
protected void | ZoneView.unloadZone(View zone) Unload a zone (Convert the zone to its memory saving state).
protected boolean | ZoneView.isZoneLoaded(View zone) Determine if a zone is in the loaded state.
void | TableView.replace(int offset, int length, View[] views) Change the child views.
void | TableView.TableRow.replace(int offset, int length, View[] views) Change the child views.
protected AsyncBoxView.ChildState | AsyncBoxView.createChildState(View v) New ChildState records are created through this method to allow subclasses the extend the ChildState records to do/hold more
void | AsyncBoxView.replace(int offset, int length, View[] views) Calls the superclass to update the child views, and updates the status records for the children.
void | AsyncBoxView.setParent(View parent) Sets the parent of the view.
void | AsyncBoxView.preferenceChanged(View child, boolean width, boolean height) Child views can call this on the parent to indicate that the preference has changed and should be reconsidered for layout.
void | ComponentView.setParent(View p) Sets the parent for a child view.
abstract void | LayeredHighlighter.paintLayeredHighlights(Graphics g, int p0, int p1, Shape viewBounds, JTextComponent editor, View view) When leaf Views (such as LabelView) are rendering they should call into this method.
abstract Shape | LayeredHighlighter.LayerPainter.paintLayer(Graphics g, int p0, int p1, Shape viewBounds, JTextComponent editor, View view)
void | DefaultHighlighter.paintLayeredHighlights(Graphics g, int p0, int p1, Shape viewBounds, JTextComponent editor, View view) When leaf Views (such as LabelView) are rendering they should call into this method.
Shape | DefaultHighlighter.DefaultHighlightPainter.paintLayer(Graphics g, int offs0, int offs1, Shape bounds, JTextComponent c, View view) Paints a portion of a highlight.
void | CompositeView.setParent(View parent) Sets the parent of the view.
void | CompositeView.replace(int offset, int length, View[] views) Replaces child views.
void | BoxView.replace(int index, int length, View[] elems) Invalidates the layout and resizes the cache of requests/allocations.
void | BoxView.preferenceChanged(View child, boolean width, boolean height) This is called by a child to indicate its preferred span has changed.
void | View.preferenceChanged(View child, boolean width, boolean height) Child views can call this on the parent to indicate that the preference has changed and should be reconsidered for layout.
void | View.setParent(View parent) Establishes the parent view for this view.
void | View.insert(int offs, View v) Inserts a single child view.
void | View.append(View v) Appends a single child view.
void | View.replace(int offset, int length, View[] views) Replaces child views.
protected void | View.forwardUpdateToView(View v, DocumentEvent e, Shape a, ViewFactory f) Forwards the DocumentEvent to the give child view.

Constructors in javax.swing.text with parameters of type View
AsyncBoxView.ChildState(View v)
Construct a child status.

Uses of View in javax.swing.text.html

Subclasses of View in javax.swing.text.html
class | BlockView A view implementation to display a block (as a box) with CSS specifications.
class | FormView Component decorator that implements the view interface for form elements, <input>, <textarea>, and <select>.
class | ImageView View of an Image, intended to support the HTML <IMG> tag.
class | InlineView Displays the inline element styles based upon css attributes.
class | ListView A view implementation to display an html list
class | ObjectView Component decorator that implements the view interface for <object> elements.

Methods in javax.swing.text.html that return View
 View HTMLEditorKit.HTMLFactory.create(Element elem)
Creates a view from an element.

Methods in javax.swing.text.html with parameters of type View
void | ImageView.setParent(View parent) Establishes the parent view for this view.
void | ParagraphView.setParent(View parent) Establishes the parent view for this view.
void | BlockView.setParent(View parent) Establishes the parent view for this view.
AttributeSet | StyleSheet.getViewAttributes(View v) Fetches a set of attributes to use in the view for displaying.
float | StyleSheet.BoxPainter.getInset(int side, View v) Fetches the inset needed on a given side to account for the margin, border, and padding.
void | StyleSheet.BoxPainter.paint(Graphics g, float x, float y, float w, float h, View v) Paints the CSS box according to the attributes given.
void | StyleSheet.ListPainter.paint(Graphics g, float x, float y, float w, float h, View v, int item) Paints the CSS list decoration according to the attributes given.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.swing.text.ViewFactory (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.swing.text.ViewFactory

Packages that use ViewFactory
javax.swing.plaf.basic | Provides user interface objects built according to the Basic look and feel.
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.text | Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.text.html | Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of ViewFactory in javax.swing.plaf.basic

Classes in javax.swing.plaf.basic that implement ViewFactory
class | BasicEditorPaneUI Provides the look and feel for a JEditorPane.
class | BasicFormattedTextFieldUI Provides the look and feel implementation for JFormattedTextField.
class | BasicPasswordFieldUI Provides the Windows look and feel for a password field.
class | BasicTextAreaUI Provides the look and feel for a plain text editor.
class | BasicTextFieldUI Basis of a look and feel for a JTextField.
class | BasicTextPaneUI Provides the look and feel for a styled text editor.
class | BasicTextUI Basis of a text components look-and-feel.

Uses of ViewFactory in javax.swing.plaf.metal

Classes in javax.swing.plaf.metal that implement ViewFactory
 class MetalTextFieldUI
Basis of a look and feel for a JTextField.

Uses of ViewFactory in javax.swing.text

Classes in javax.swing.text that implement ViewFactory
 class DefaultTextUI
Deprecated.

Methods in javax.swing.text that return ViewFactory
ViewFactory | StyledEditorKit.getViewFactory() Fetches a factory that is suitable for producing views of any models that are produced by this kit.
ViewFactory | DefaultEditorKit.getViewFactory() Fetches a factory that is suitable for producing views of any models that are produced by this kit.
abstract ViewFactory | EditorKit.getViewFactory() Fetches a factory that is suitable for producing views of any models that are produced by this kit.
ViewFactory | View.getViewFactory() Fetches the ViewFactory implementation that is feeding the view hierarchy.

Methods in javax.swing.text with parameters of type ViewFactory
protected void | ZoneView.loadChildren(ViewFactory f) Loads all of the children to initialize the view.
protected boolean | ZoneView.updateChildren(DocumentEvent.ElementChange ec, DocumentEvent e, ViewFactory f) 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.
void | ZoneView.insertUpdate(DocumentEvent changes, Shape a, ViewFactory f) Gives notification that something was inserted into the document in a location that this view is responsible for.
void | ZoneView.removeUpdate(DocumentEvent changes, Shape a, ViewFactory f) Gives notification that something was removed from the document in a location that this view is responsible for.
protected void | TableView.forwardUpdate(DocumentEvent.ElementChange ec, DocumentEvent e, Shape a, ViewFactory f)
void | PlainView.insertUpdate(DocumentEvent changes, Shape a, ViewFactory f) Gives notification that something was inserted into the document in a location that this view is responsible for.
void | PlainView.removeUpdate(DocumentEvent changes, Shape a, ViewFactory f) Gives notification that something was removed from the document in a location that this view is responsible for.
void | PlainView.changedUpdate(DocumentEvent changes, Shape a, ViewFactory f) Gives notification from the document that attributes were changed in a location that this view is responsible for.
protected void | PlainView.updateDamage(DocumentEvent changes, Shape a, ViewFactory f)
void | FieldView.insertUpdate(DocumentEvent changes, Shape a, ViewFactory f) Gives notification that something was inserted into the document in a location that this view is responsible for.
void | FieldView.removeUpdate(DocumentEvent changes, Shape a, ViewFactory f) Gives notification that something was removed from the document in a location that this view is responsible for.
protected void | AsyncBoxView.loadChildren(ViewFactory f) Loads all of the children to initialize the view.
protected void | WrappedPlainView.loadChildren(ViewFactory f) Loads all of the children to initialize the view.
void | WrappedPlainView.insertUpdate(DocumentEvent e, Shape a, ViewFactory f) Gives notification that something was inserted into the document in a location that this view is responsible for.
void | WrappedPlainView.removeUpdate(DocumentEvent e, Shape a, ViewFactory f) Gives notification that something was removed from the document in a location that this view is responsible for.
void | WrappedPlainView.changedUpdate(DocumentEvent e, Shape a, ViewFactory f) Gives notification from the document that attributes were changed in a location that this view is responsible for.
void | LabelView.changedUpdate(DocumentEvent e, Shape a, ViewFactory f) Gives notification from the document that attributes were changed in a location that this view is responsible for.
void | GlyphView.insertUpdate(DocumentEvent e, Shape a, ViewFactory f) Gives notification that something was inserted into the document in a location that this view is responsible for.
void | GlyphView.removeUpdate(DocumentEvent e, Shape a, ViewFactory f) Gives notification that something was removed from the document in a location that this view is responsible for.
void | GlyphView.changedUpdate(DocumentEvent e, Shape a, ViewFactory f) Gives notification from the document that attributes were changed in a location that this view is responsible for.
protected void | CompositeView.loadChildren(ViewFactory f) Loads all of the children to initialize the view.
protected void | BoxView.forwardUpdate(DocumentEvent.ElementChange ec, DocumentEvent e, Shape a, ViewFactory f) Forwards the given DocumentEvent to the child views that need to be notified of the change to the model.
protected void | FlowView.loadChildren(ViewFactory f) Loads all of the children to initialize the view.
void | FlowView.insertUpdate(DocumentEvent changes, Shape a, ViewFactory f) Gives notification that something was inserted into the document in a location that this view is responsible for.
void | FlowView.removeUpdate(DocumentEvent changes, Shape a, ViewFactory f) Gives notification that something was removed from the document in a location that this view is responsible for.
void | FlowView.changedUpdate(DocumentEvent changes, Shape a, ViewFactory f) Gives notification from the document that attributes were changed in a location that this view is responsible for.
void | ParagraphView.changedUpdate(DocumentEvent changes, Shape a, ViewFactory f) Gives notification from the document that attributes were changed in a location that this view is responsible for.
void | View.insertUpdate(DocumentEvent e, Shape a, ViewFactory f) Gives notification that something was inserted into the document in a location that this view is responsible for.
void | View.removeUpdate(DocumentEvent e, Shape a, ViewFactory f) Gives notification that something was removed from the document in a location that this view is responsible for.
void | View.changedUpdate(DocumentEvent e, Shape a, ViewFactory f) Gives notification from the document that attributes were changed in a location that this view is responsible for.
protected boolean | View.updateChildren(DocumentEvent.ElementChange ec, DocumentEvent e, ViewFactory f) 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.
protected void | View.forwardUpdate(DocumentEvent.ElementChange ec, DocumentEvent e, Shape a, ViewFactory f) Forwards the given DocumentEvent to the child views that need to be notified of the change to the model.
protected void | View.forwardUpdateToView(View v, DocumentEvent e, Shape a, ViewFactory f) Forwards the DocumentEvent to the give child view.

Uses of ViewFactory in javax.swing.text.html

Classes in javax.swing.text.html that implement ViewFactory
static class HTMLEditorKit.HTMLFactory
A factory to build views for HTML.

Methods in javax.swing.text.html that return ViewFactory
 ViewFactory HTMLEditorKit.getViewFactory()
Fetch a factory that is suitable for producing views of any models that are produced by this kit.

Methods in javax.swing.text.html with parameters of type ViewFactory
void | ImageView.changedUpdate(DocumentEvent e, Shape a, ViewFactory f) Invoked when the Elements attributes have changed.
void | InlineView.changedUpdate(DocumentEvent e, Shape a, ViewFactory f) Gives notification from the document that attributes were changed in a location that this view is responsible for.
void | BlockView.changedUpdate(DocumentEvent changes, Shape a, ViewFactory f)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.WrappedPlainView (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.WrappedPlainView

No usage of javax.swing.text.WrappedPlainView

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.ZoneView (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.ZoneView

No usage of javax.swing.text.ZoneView

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


BlockView (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class BlockView

java.lang.Object
    extended by javax.swing.text.View
        extended by javax.swing.text.CompositeView
            extended by javax.swing.text.BoxView
                extended by javax.swing.text.html.BlockView
All Implemented Interfaces:
SwingConstants
Direct Known Subclasses:
ListView
public class BlockView
extends BoxView

A view implementation to display a block (as a box) with CSS specifications.

Field Summary
Fields inherited from class javax.swing.text.View
BadBreakWeight, ExcellentBreakWeight, ForcedBreakWeight, GoodBreakWeight, X_AXIS, Y_AXIS
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
Constructor Summary
BlockView(Element elem, int axis)
Creates a new view that represents an html box.
Method Summary
protected SizeRequirements | calculateMajorAxisRequirements(int axis, SizeRequirements r) Calculate the requirements of the block along the major axis (i.e.
protected SizeRequirements | calculateMinorAxisRequirements(int axis, SizeRequirements r) Calculate the requirements of the block along the minor axis (i.e.
void | changedUpdate(DocumentEvent changes, Shape a, ViewFactory f) Gives notification from the document that attributes were changed in a location that this view is responsible for.
float | getAlignment(int axis) Gets the alignment.
AttributeSet | getAttributes() Fetches the attributes to use when rendering.
float | getMaximumSpan(int axis) Determines the maximum span for this view along an axis.
float | getMinimumSpan(int axis) Determines the minimum span for this view along an axis.
float | getPreferredSpan(int axis) Determines the preferred span for this view along an axis.
int | getResizeWeight(int axis) Gets the resize weight.
protected StyleSheet | getStyleSheet()
protected void | layoutMinorAxis(int targetSpan, int axis, int[] offsets, int[] spans) Perform layout for the minor axis of the box (i.e.
void | paint(Graphics g, Shape allocation) Renders using the given rendering surface and area on that surface.
void | setParent(View parent) Establishes the parent view for this view.
protected void | setPropertiesFromAttributes() Update any cached values that come from attributes.
Methods inherited from class javax.swing.text.BoxView
baselineLayout, baselineRequirements, childAllocation, flipEastAndWestAtEnds, forwardUpdate, getAxis, getChildAllocation, getHeight, getOffset, getSpan, getViewAtPoint, getWidth, isAfter, isAllocationValid, isBefore, isLayoutValid, layout, layoutChanged, layoutMajorAxis, modelToView, paintChild, preferenceChanged, replace, setAxis, setSize, viewToModel
Methods inherited from class javax.swing.text.CompositeView
getBottomInset, getInsideAllocation, getLeftInset, getNextEastWestVisualPositionFrom, getNextNorthSouthVisualPositionFrom, getNextVisualPositionFrom, getRightInset, getTopInset, getView, getViewAtPosition, getViewCount, getViewIndex, getViewIndexAtPosition, loadChildren, modelToView, setInsets, setParagraphInsets
Methods inherited from class javax.swing.text.View
append, breakView, createFragment, forwardUpdateToView, getBreakWeight, getContainer, getDocument, getElement, getEndOffset, getGraphics, getParent, getStartOffset, getToolTipText, getViewFactory, getViewIndex, insert, insertUpdate, isVisible, modelToView, remove, removeAll, removeUpdate, updateChildren, updateLayout, viewToModel
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

BlockView

public BlockView(Element elem,
                 int axis)
Creates a new view that represents an html box. This can be used for a number of elements.

Parameters:
elem - the element to create a view for
axis - either View.X_AXIS or View.Y_AXIS
Method Detail

setParent

public void setParent(View parent)
Establishes the parent view for this view. This is guaranteed to be called before any other methods if the parent view is functioning properly.

This is implemented to forward to the superclass as well as call the setPropertiesFromAttributes() method to set the paragraph properties from the css attributes. The call is made at this time to ensure the ability to resolve upward through the parents view attributes.

Overrides:
setParent in class CompositeView
Parameters:
parent - the new parent, or null if the view is being removed from a parent it was previously added to

calculateMajorAxisRequirements

protected SizeRequirements calculateMajorAxisRequirements(int axis,
                                                          SizeRequirements r)
Calculate the requirements of the block along the major axis (i.e. the axis along with it tiles). This is implemented to provide the superclass behavior and then adjust it if the CSS width or height attribute is specified and applicable to the axis.

Overrides:
calculateMajorAxisRequirements in class BoxView
Parameters:
axis - the axis being studied
r - the SizeRequirements object; if null one will be created
Returns:
the newly initialized SizeRequirements object
See Also:
SizeRequirements

calculateMinorAxisRequirements

protected SizeRequirements calculateMinorAxisRequirements(int axis,
                                                          SizeRequirements r)
Calculate the requirements of the block along the minor axis (i.e. the axis orthoginal to the axis along with it tiles). This is implemented to provide the superclass behavior and then adjust it if the CSS width or height attribute is specified and applicable to the axis.

Overrides:
calculateMinorAxisRequirements in class BoxView
Parameters:
axis - the axis being studied
r - the SizeRequirements object; if null one will be created
Returns:
the newly initialized SizeRequirements object
See Also:
SizeRequirements

layoutMinorAxis

protected void layoutMinorAxis(int targetSpan,
                               int axis,
                               int[] offsets,
                               int[] spans)
Perform layout for the minor axis of the box (i.e. the axis orthoginal to the axis that it represents). The results of the layout should be placed in the given arrays which represent the allocations to the children along the minor axis.

Overrides:
layoutMinorAxis in class BoxView
Parameters:
targetSpan - the total span given to the view, which whould be used to layout the childre.
axis - the axis being layed out
offsets - the offsets from the origin of the view for each of the child views; this is a return value and is filled in by the implementation of this method
spans - the span of each child view; this is a return value and is filled in by the implementation of this method
Returns:
the offset and span for each child view in the offsets and spans parameters

paint

public void paint(Graphics g,
                  Shape allocation)
Renders using the given rendering surface and area on that surface. This is implemented to delegate to the css box painter to paint the border and background prior to the interior.

Overrides:
paint in class BoxView
Parameters:
g - the rendering surface to use
allocation - the allocated region to render into
See Also:
View.paint(java.awt.Graphics, java.awt.Shape)

getAttributes

public AttributeSet getAttributes()
Fetches the attributes to use when rendering. This is implemented to multiplex the attributes specified in the model with a StyleSheet.

Overrides:
getAttributes in class View

getResizeWeight

public int getResizeWeight(int axis)
Gets the resize weight.

Overrides:
getResizeWeight in class BoxView
Parameters:
axis - may be either X_AXIS or Y_AXIS
Returns:
the weight
Throws:
IllegalArgumentException - for an invalid axis

getAlignment

public float getAlignment(int axis)
Gets the alignment.

Overrides:
getAlignment in class BoxView
Parameters:
axis - may be either X_AXIS or Y_AXIS
Returns:
the alignment

changedUpdate

public void changedUpdate(DocumentEvent changes,
                          Shape a,
                          ViewFactory f)
Description copied from class: View
Gives notification from the document that attributes were changed in a location that this view is responsible for. To reduce the burden to subclasses, this functionality is spread out into the following calls that subclasses can reimplement:
  1. updateChildren is called if there were any changes to the element this view is responsible for. If this view has child views that are represent the child elements, then this method should do whatever is necessary to make sure the child views correctly represent the model.
  2. forwardUpdate is called to forward the DocumentEvent to the appropriate child views.
  3. updateLayout is called to give the view a chance to either repair its layout, to reschedule layout, or do nothing.

Overrides:
changedUpdate in class View
Parameters:
changes - the change information from the associated document
a - the current allocation of the view
f - the factory to use to rebuild if the view has children
See Also:
View.changedUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory)

getPreferredSpan

public float getPreferredSpan(int axis)
Determines the preferred span for this view along an axis.

Overrides:
getPreferredSpan in class BoxView
Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
Returns:
the span the view would like to be rendered into >= 0; typically the view is told to render into the span that is returned, although there is no guarantee; the parent may choose to resize or break the view
Throws:
IllegalArgumentException - for an invalid axis type

getMinimumSpan

public float getMinimumSpan(int axis)
Determines the minimum span for this view along an axis.

Overrides:
getMinimumSpan in class BoxView
Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
Returns:
the span the view would like to be rendered into >= 0; typically the view is told to render into the span that is returned, although there is no guarantee; the parent may choose to resize or break the view
Throws:
IllegalArgumentException - for an invalid axis type

getMaximumSpan

public float getMaximumSpan(int axis)
Determines the maximum span for this view along an axis.

Overrides:
getMaximumSpan in class BoxView
Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
Returns:
the span the view would like to be rendered into >= 0; typically the view is told to render into the span that is returned, although there is no guarantee; the parent may choose to resize or break the view
Throws:
IllegalArgumentException - for an invalid axis type

setPropertiesFromAttributes

protected void setPropertiesFromAttributes()
Update any cached values that come from attributes.

getStyleSheet

protected StyleSheet getStyleSheet()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


CSS (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class CSS

java.lang.Object
    extended by javax.swing.text.html.CSS
All Implemented Interfaces:
Serializable
public class CSS
extends Object
implements Serializable

Defines a set of CSS attributes as a typesafe enumeration. The HTML View implementations use CSS attributes to determine how they will render. This also defines methods to map between CSS/HTML/StyleConstants. Any shorthand properties, such as font, are mapped to the intrinsic properties.

The following describes the CSS properties that are suppored by the rendering engine:

  • font-family
  • font-style
  • font-size (supports relative units)
  • font-weight
  • font
  • color
  • background-color (with the exception of transparent)
  • background-image
  • background-repeat
  • background-position
  • background
  • background-repeat
  • text-decoration (with the exception of blink and overline)
  • vertical-align (only sup and super)
  • text-align (justify is treated as center)
  • margin-top
  • margin-right
  • margin-bottom
  • margin-left
  • margin
  • padding-top
  • padding-right
  • padding-bottom
  • padding-left
  • border-style (only supports inset, outset and none)
  • list-style-type
  • list-style-position
The following are modeled, but currently not rendered.
  • font-variant
  • background-attachment (background always treated as scroll)
  • word-spacing
  • letter-spacing
  • text-indent
  • text-transform
  • line-height
  • border-top-width (this is used to indicate if a border should be used)
  • border-right-width
  • border-bottom-width
  • border-left-width
  • border-width
  • border-top
  • border-right
  • border-bottom
  • border-left
  • border
  • width
  • height
  • float
  • clear
  • display
  • white-space
  • list-style

Note: for the time being we do not fully support relative units, unless noted, so that p { margin-top: 10% } will be treated as if no margin-top was specified.

See Also:
StyleSheet

Nested Class Summary
static class CSS.Attribute
Definitions to be used as a key on AttributeSet's that might hold CSS attributes.
Constructor Summary
CSS()
Method Summary
static CSS.Attribute[] | getAllAttributeKeys() Return the set of all possible CSS attribute keys.
static CSS.Attribute | getAttribute(String name) Translates a string to a CSS.Attribute object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

CSS

public CSS()
Method Detail

getAllAttributeKeys

public static CSS.Attribute[] getAllAttributeKeys()
Return the set of all possible CSS attribute keys.

getAttribute

public static final CSS.Attribute getAttribute(String name)
Translates a string to a CSS.Attribute object. This will return null if there is no attribute by the given name.

Parameters:
name - the name of the CSS attribute to fetch the typesafe enumeration for
Returns:
the CSS.Attribute object, or null if the string doesn't represent a valid attribute key
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


CSS.Attribute (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class CSS.Attribute

java.lang.Object
    extended by javax.swing.text.html.CSS.Attribute
Enclosing class:
CSS
public static final class CSS.Attribute
extends Object

Definitions to be used as a key on AttributeSet's that might hold CSS attributes. Since this is a closed set (i.e. defined exactly by the specification), it is final and cannot be extended.

Field Summary
static CSS.Attribute | BACKGROUND
static CSS.Attribute | BACKGROUND_ATTACHMENT
static CSS.Attribute | BACKGROUND_COLOR
static CSS.Attribute | BACKGROUND_IMAGE
static CSS.Attribute | BACKGROUND_POSITION
static CSS.Attribute | BACKGROUND_REPEAT
static CSS.Attribute | BORDER
static CSS.Attribute | BORDER_BOTTOM
static CSS.Attribute | BORDER_BOTTOM_WIDTH
static CSS.Attribute | BORDER_COLOR
static CSS.Attribute | BORDER_LEFT
static CSS.Attribute | BORDER_LEFT_WIDTH
static CSS.Attribute | BORDER_RIGHT
static CSS.Attribute | BORDER_RIGHT_WIDTH
static CSS.Attribute | BORDER_STYLE
static CSS.Attribute | BORDER_TOP
static CSS.Attribute | BORDER_TOP_WIDTH
static CSS.Attribute | BORDER_WIDTH
static CSS.Attribute | CLEAR
static CSS.Attribute | COLOR
static CSS.Attribute | DISPLAY
static CSS.Attribute | FLOAT
static CSS.Attribute | FONT
static CSS.Attribute | FONT_FAMILY
static CSS.Attribute | FONT_SIZE
static CSS.Attribute | FONT_STYLE
static CSS.Attribute | FONT_VARIANT
static CSS.Attribute | FONT_WEIGHT
static CSS.Attribute | HEIGHT
static CSS.Attribute | LETTER_SPACING
static CSS.Attribute | LINE_HEIGHT
static CSS.Attribute | LIST_STYLE
static CSS.Attribute | LIST_STYLE_IMAGE
static CSS.Attribute | LIST_STYLE_POSITION
static CSS.Attribute | LIST_STYLE_TYPE
static CSS.Attribute | MARGIN
static CSS.Attribute | MARGIN_BOTTOM
static CSS.Attribute | MARGIN_LEFT
static CSS.Attribute | MARGIN_RIGHT
static CSS.Attribute | MARGIN_TOP
static CSS.Attribute | PADDING
static CSS.Attribute | PADDING_BOTTOM
static CSS.Attribute | PADDING_LEFT
static CSS.Attribute | PADDING_RIGHT
static CSS.Attribute | PADDING_TOP
static CSS.Attribute | TEXT_ALIGN
static CSS.Attribute | TEXT_DECORATION
static CSS.Attribute | TEXT_INDENT
static CSS.Attribute | TEXT_TRANSFORM
static CSS.Attribute | VERTICAL_ALIGN
static CSS.Attribute | WHITE_SPACE
static CSS.Attribute | WIDTH
static CSS.Attribute | WORD_SPACING
Method Summary
String | getDefaultValue() Fetch the default value for the attribute.
boolean | isInherited() Indicates if the attribute should be inherited from the parent or not.
String | toString() The string representation of the attribute.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

BACKGROUND

public static final CSS.Attribute BACKGROUND

BACKGROUND_ATTACHMENT

public static final CSS.Attribute BACKGROUND_ATTACHMENT

BACKGROUND_COLOR

public static final CSS.Attribute BACKGROUND_COLOR

BACKGROUND_IMAGE

public static final CSS.Attribute BACKGROUND_IMAGE

BACKGROUND_POSITION

public static final CSS.Attribute BACKGROUND_POSITION

BACKGROUND_REPEAT

public static final CSS.Attribute BACKGROUND_REPEAT

BORDER

public static final CSS.Attribute BORDER

BORDER_BOTTOM

public static final CSS.Attribute BORDER_BOTTOM

BORDER_BOTTOM_WIDTH

public static final CSS.Attribute BORDER_BOTTOM_WIDTH

BORDER_COLOR

public static final CSS.Attribute BORDER_COLOR

BORDER_LEFT

public static final CSS.Attribute BORDER_LEFT

BORDER_LEFT_WIDTH

public static final CSS.Attribute BORDER_LEFT_WIDTH

BORDER_RIGHT

public static final CSS.Attribute BORDER_RIGHT

BORDER_RIGHT_WIDTH

public static final CSS.Attribute BORDER_RIGHT_WIDTH

BORDER_STYLE

public static final CSS.Attribute BORDER_STYLE

BORDER_TOP

public static final CSS.Attribute BORDER_TOP

BORDER_TOP_WIDTH

public static final CSS.Attribute BORDER_TOP_WIDTH

BORDER_WIDTH

public static final CSS.Attribute BORDER_WIDTH

CLEAR

public static final CSS.Attribute CLEAR

COLOR

public static final CSS.Attribute COLOR

DISPLAY

public static final CSS.Attribute DISPLAY

FLOAT

public static final CSS.Attribute FLOAT

FONT

public static final CSS.Attribute FONT

FONT_FAMILY

public static final CSS.Attribute FONT_FAMILY

FONT_SIZE

public static final CSS.Attribute FONT_SIZE

FONT_STYLE

public static final CSS.Attribute FONT_STYLE

FONT_VARIANT

public static final CSS.Attribute FONT_VARIANT

FONT_WEIGHT

public static final CSS.Attribute FONT_WEIGHT

HEIGHT

public static final CSS.Attribute HEIGHT

LETTER_SPACING

public static final CSS.Attribute LETTER_SPACING

LINE_HEIGHT

public static final CSS.Attribute LINE_HEIGHT

LIST_STYLE

public static final CSS.Attribute LIST_STYLE

LIST_STYLE_IMAGE

public static final CSS.Attribute LIST_STYLE_IMAGE

LIST_STYLE_POSITION

public static final CSS.Attribute LIST_STYLE_POSITION

LIST_STYLE_TYPE

public static final CSS.Attribute LIST_STYLE_TYPE

MARGIN

public static final CSS.Attribute MARGIN

MARGIN_BOTTOM

public static final CSS.Attribute MARGIN_BOTTOM

MARGIN_LEFT

public static final CSS.Attribute MARGIN_LEFT

MARGIN_RIGHT

public static final CSS.Attribute MARGIN_RIGHT

MARGIN_TOP

public static final CSS.Attribute MARGIN_TOP

PADDING

public static final CSS.Attribute PADDING

PADDING_BOTTOM

public static final CSS.Attribute PADDING_BOTTOM

PADDING_LEFT

public static final CSS.Attribute PADDING_LEFT

PADDING_RIGHT

public static final CSS.Attribute PADDING_RIGHT

PADDING_TOP

public static final CSS.Attribute PADDING_TOP

TEXT_ALIGN

public static final CSS.Attribute TEXT_ALIGN

TEXT_DECORATION

public static final CSS.Attribute TEXT_DECORATION

TEXT_INDENT

public static final CSS.Attribute TEXT_INDENT

TEXT_TRANSFORM

public static final CSS.Attribute TEXT_TRANSFORM

VERTICAL_ALIGN

public static final CSS.Attribute VERTICAL_ALIGN

WORD_SPACING

public static final CSS.Attribute WORD_SPACING

WHITE_SPACE

public static final CSS.Attribute WHITE_SPACE

WIDTH

public static final CSS.Attribute WIDTH
Method Detail

toString

public String toString()
The string representation of the attribute. This should exactly match the string specified in the CSS specification.

Overrides:
toString in class Object
Returns:
a string representation of the object.

getDefaultValue

public String getDefaultValue()
Fetch the default value for the attribute. If there is no default value (such as for composite attributes), null will be returned.

isInherited

public boolean isInherited()
Indicates if the attribute should be inherited from the parent or not.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


FormView (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class FormView

java.lang.Object
    extended by javax.swing.text.View
        extended by javax.swing.text.ComponentView
            extended by javax.swing.text.html.FormView
All Implemented Interfaces:
ActionListener, EventListener, SwingConstants
public class FormView
extends ComponentView
implements ActionListener

Component decorator that implements the view interface for form elements, <input>, <textarea>, and <select>. The model for the component is stored as an attribute of the the element (using StyleConstants.ModelAttribute), and is used to build the component of the view. The type of the model is assumed to of the type that would be set by HTMLDocument.HTMLReader.FormAction. If there are multiple views mapped over the document, they will share the embedded component models.

The following table shows what components get built by this view.

Element Type | Component built
input, type button | JButton
input, type checkbox | JCheckBox
input, type image | JButton
input, type password | JPasswordField
input, type radio | JRadioButton
input, type reset | JButton
input, type submit | JButton
input, type text | JTextField
select, size > 1 or multiple attribute defined | JList in a JScrollPane
select, size unspecified or 1 | JComboBox
textarea | JTextArea in a JScrollPane
input, type file | JTextField

Nested Class Summary
protected  class FormView.MouseEventListener
MouseEventListener class to handle form submissions when an input with type equal to image is clicked on.
Field Summary
static String | RESET Deprecated. As of 1.3, value comes from UIManager UIManager property FormView.resetButtonText
static String | SUBMIT Deprecated. As of 1.3, value now comes from UIManager property FormView.submitButtonText
Fields inherited from class javax.swing.text.View
BadBreakWeight, ExcellentBreakWeight, ForcedBreakWeight, GoodBreakWeight, X_AXIS, Y_AXIS
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
Constructor Summary
FormView(Element elem)
Creates a new FormView object.
Method Summary
void | actionPerformed(ActionEvent evt) Responsible for processeing the ActionEvent.
protected Component | createComponent() Create the component.
float | getMaximumSpan(int axis) Determines the maximum span for this view along an axis.
protected void | imageSubmit(String imageData) This method is called to submit a form in response to a click on an image -- an <INPUT> form element of type "image".
protected void | submitData(String data) This method is responsible for submitting the form data.
Methods inherited from class javax.swing.text.ComponentView
getAlignment, getComponent, getMinimumSpan, getPreferredSpan, modelToView, paint, setParent, viewToModel
Methods inherited from class javax.swing.text.View
append, breakView, changedUpdate, createFragment, forwardUpdate, forwardUpdateToView, getAttributes, getBreakWeight, getChildAllocation, getContainer, getDocument, getElement, getEndOffset, getGraphics, getNextVisualPositionFrom, getParent, getResizeWeight, getStartOffset, getToolTipText, getView, getViewCount, getViewFactory, getViewIndex, getViewIndex, insert, insertUpdate, isVisible, modelToView, modelToView, preferenceChanged, remove, removeAll, removeUpdate, replace, setSize, updateChildren, updateLayout, viewToModel
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

SUBMIT

public static final String SUBMIT
Deprecated. As of 1.3, value now comes from UIManager property FormView.submitButtonText

If a value attribute is not specified for a FORM input element of type "submit", then this default string is used.

RESET

public static final String RESET
Deprecated. As of 1.3, value comes from UIManager UIManager property FormView.resetButtonText

If a value attribute is not specified for a FORM input element of type "reset", then this default string is used.

Constructor Detail

FormView

public FormView(Element elem)
Creates a new FormView object.

Parameters:
elem - the element to decorate
Method Detail

createComponent

protected Component createComponent()
Create the component. This is basically a big switch statement based upon the tag type and html attributes of the associated element.

Overrides:
createComponent in class ComponentView

getMaximumSpan

public float getMaximumSpan(int axis)
Determines the maximum span for this view along an axis. For certain components, the maximum and preferred span are the same. For others this will return the value returned by Component.getMaximumSize along the axis of interest.

Overrides:
getMaximumSpan in class ComponentView
Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
Returns:
the span the view would like to be rendered into >= 0. Typically the view is told to render into the span that is returned, although there is no guarantee. The parent may choose to resize or break the view.
Throws:
IllegalArgumentException - for an invalid axis

actionPerformed

public void actionPerformed(ActionEvent evt)
Responsible for processeing the ActionEvent. If the element associated with the FormView, has a type of "submit", "reset", "text" or "password" then the action is processed. In the case of a "submit" the form is submitted. In the case of a "reset" the form is reset to its original state. In the case of "text" or "password", if the element is the last one of type "text" or "password", the form is submitted. Otherwise, focus is transferred to the next component in the form.

Specified by:
actionPerformed in interface ActionListener
Parameters:
evt - the ActionEvent.

submitData

protected void submitData(String data)
This method is responsible for submitting the form data. A thread is forked to undertake the submission.

imageSubmit

protected void imageSubmit(String imageData)
This method is called to submit a form in response to a click on an image -- an <INPUT> form element of type "image".

Parameters:
imageData - the mouse click coordinates.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


FormView.MouseEventListener (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class FormView.MouseEventListener

java.lang.Object
    extended by java.awt.event.MouseAdapter
        extended by javax.swing.text.html.FormView.MouseEventListener
All Implemented Interfaces:
EventListener, MouseListener
Enclosing class:
FormView
protected class FormView.MouseEventListener
extends MouseAdapter

MouseEventListener class to handle form submissions when an input with type equal to image is clicked on. A MouseListener is necessary since along with the image data the coordinates associated with the mouse click need to be submitted.

Constructor Summary
protected FormView.MouseEventListener()
Method Summary
 void mouseReleased(MouseEvent evt)
Invoked when a mouse button has been released on a component.
Methods inherited from class java.awt.event.MouseAdapter
mouseClicked, mouseEntered, mouseExited, mousePressed
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

FormView.MouseEventListener

protected FormView.MouseEventListener()
Method Detail

mouseReleased

public void mouseReleased(MouseEvent evt)
Description copied from class: MouseAdapter
Invoked when a mouse button has been released on a component.

Specified by:
mouseReleased in interface MouseListener
Overrides:
mouseReleased in class MouseAdapter
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


HTML (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class HTML

java.lang.Object
    extended by javax.swing.text.html.HTML
public class HTML
extends Object

Constants used in the HTMLDocument. These are basically tag and attribute definitions.

Nested Class Summary
static class | HTML.Attribute Typesafe enumeration representing an HTML attribute.
static class | HTML.Tag Typesafe enumeration for an HTML tag.
static class | HTML.UnknownTag
Field Summary
static String NULL_ATTRIBUTE_VALUE
Constructor Summary
HTML()
Method Summary
static HTML.Attribute[] | getAllAttributeKeys() Returns the set of HTML attributes recognized.
static HTML.Tag[] | getAllTags() Returns the set of actual HTML tags that are recognized by the default HTML reader.
static HTML.Attribute | getAttributeKey(String attName) Fetches an attribute constant for a well-known attribute name (i.e.
static int | getIntegerAttributeValue(AttributeSet attr, HTML.Attribute key, int def) Fetches an integer attribute value.
static HTML.Tag | getTag(String tagName) Fetches a tag constant for a well-known tag name (i.e.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

NULL_ATTRIBUTE_VALUE

public static final String NULL_ATTRIBUTE_VALUE
See Also:
Constant Field Values
Constructor Detail

HTML

public HTML()
Method Detail

getAllTags

public static HTML.Tag[] getAllTags()
Returns the set of actual HTML tags that are recognized by the default HTML reader. This set does not include tags that are manufactured by the reader.

getTag

public static HTML.Tag getTag(String tagName)
Fetches a tag constant for a well-known tag name (i.e. one of the tags in the set {A, ADDRESS, APPLET, AREA, B, BASE, BASEFONT, BIG, BLOCKQUOTE, BODY, BR, CAPTION, CENTER, CITE, CODE, DD, DFN, DIR, DIV, DL, DT, EM, FONT, FORM, FRAME, FRAMESET, H1, H2, H3, H4, H5, H6, HEAD, HR, HTML, I, IMG, INPUT, ISINDEX, KBD, LI, LINK, MAP, MENU, META, NOBR, NOFRAMES, OBJECT, OL, OPTION, P, PARAM, PRE, SAMP, SCRIPT, SELECT, SMALL, SPAN, STRIKE, S, STRONG, STYLE, SUB, SUP, TABLE, TD, TEXTAREA, TH, TITLE, TR, TT, U, UL, VAR}. If the given name does not represent one of the well-known tags, then null will be returned.

Parameters:
tagName - the String name requested
Returns:
a tag constant corresponding to the tagName, or null if not found

getIntegerAttributeValue

public static int getIntegerAttributeValue(AttributeSet attr,
                                           HTML.Attribute key,
                                           int def)
Fetches an integer attribute value. Attribute values are stored as a string, and this is a convenience method to convert to an actual integer.

Parameters:
attr - the set of attributes to use to try to fetch a value
key - the key to use to fetch the value
def - the default value to use if the attribute isn't defined or there is an error converting to an integer

getAllAttributeKeys

public static HTML.Attribute[] getAllAttributeKeys()
Returns the set of HTML attributes recognized.

Returns:
the set of HTML attributes recognized

getAttributeKey

public static HTML.Attribute getAttributeKey(String attName)
Fetches an attribute constant for a well-known attribute name (i.e. one of the attributes in the set {FACE, COMMENT, SIZE, COLOR, CLEAR, BACKGROUND, BGCOLOR, TEXT, LINK, VLINK, ALINK, WIDTH, HEIGHT, ALIGN, NAME, HREF, REL, REV, TITLE, TARGET, SHAPE, COORDS, ISMAP, NOHREF, ALT, ID, SRC, HSPACE, VSPACE, USEMAP, LOWSRC, CODEBASE, CODE, ARCHIVE, VALUE, VALUETYPE, TYPE, CLASS, STYLE, LANG, DIR, DECLARE, CLASSID, DATA, CODETYPE, STANDBY, BORDER, SHAPES, NOSHADE, COMPACT, START, ACTION, METHOD, ENCTYPE, CHECKED, MAXLENGTH, MULTIPLE, SELECTED, ROWS, COLS, DUMMY, CELLSPACING, CELLPADDING, VALIGN, HALIGN, NOWRAP, ROWSPAN, COLSPAN, PROMPT, HTTPEQUIV, CONTENT, LANGUAGE, VERSION, N, FRAMEBORDER, MARGINWIDTH, MARGINHEIGHT, SCROLLING, NORESIZE, MEDIA, ENDTAG}). If the given name does not represent one of the well-known attributes, then null will be returned.

Parameters:
attName - the String requested
Returns:
the Attribute corresponding to attName
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


HTML.Attribute (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class HTML.Attribute

java.lang.Object
    extended by javax.swing.text.html.HTML.Attribute
Enclosing class:
HTML
public static final class HTML.Attribute
extends Object

Typesafe enumeration representing an HTML attribute.

Field Summary
static HTML.Attribute | ACTION
static HTML.Attribute | ALIGN
static HTML.Attribute | ALINK
static HTML.Attribute | ALT
static HTML.Attribute | ARCHIVE
static HTML.Attribute | BACKGROUND
static HTML.Attribute | BGCOLOR
static HTML.Attribute | BORDER
static HTML.Attribute | CELLPADDING
static HTML.Attribute | CELLSPACING
static HTML.Attribute | CHECKED
static HTML.Attribute | CLASS
static HTML.Attribute | CLASSID
static HTML.Attribute | CLEAR
static HTML.Attribute | CODE
static HTML.Attribute | CODEBASE
static HTML.Attribute | CODETYPE
static HTML.Attribute | COLOR
static HTML.Attribute | COLS
static HTML.Attribute | COLSPAN
static HTML.Attribute | COMMENT
static HTML.Attribute | COMPACT
static HTML.Attribute | CONTENT
static HTML.Attribute | COORDS
static HTML.Attribute | DATA
static HTML.Attribute | DECLARE
static HTML.Attribute | DIR
static HTML.Attribute | DUMMY
static HTML.Attribute | ENCTYPE
static HTML.Attribute | ENDTAG
static HTML.Attribute | FACE
static HTML.Attribute | FRAMEBORDER
static HTML.Attribute | HALIGN
static HTML.Attribute | HEIGHT
static HTML.Attribute | HREF
static HTML.Attribute | HSPACE
static HTML.Attribute | HTTPEQUIV
static HTML.Attribute | ID
static HTML.Attribute | ISMAP
static HTML.Attribute | LANG
static HTML.Attribute | LANGUAGE
static HTML.Attribute | LINK
static HTML.Attribute | LOWSRC
static HTML.Attribute | MARGINHEIGHT
static HTML.Attribute | MARGINWIDTH
static HTML.Attribute | MAXLENGTH
static HTML.Attribute | METHOD
static HTML.Attribute | MULTIPLE
static HTML.Attribute | N
static HTML.Attribute | NAME
static HTML.Attribute | NOHREF
static HTML.Attribute | NORESIZE
static HTML.Attribute | NOSHADE
static HTML.Attribute | NOWRAP
static HTML.Attribute | PROMPT
static HTML.Attribute | REL
static HTML.Attribute | REV
static HTML.Attribute | ROWS
static HTML.Attribute | ROWSPAN
static HTML.Attribute | SCROLLING
static HTML.Attribute | SELECTED
static HTML.Attribute | SHAPE
static HTML.Attribute | SHAPES
static HTML.Attribute | SIZE
static HTML.Attribute | SRC
static HTML.Attribute | STANDBY
static HTML.Attribute | START
static HTML.Attribute | STYLE
static HTML.Attribute | TARGET
static HTML.Attribute | TEXT
static HTML.Attribute | TITLE
static HTML.Attribute | TYPE
static HTML.Attribute | USEMAP
static HTML.Attribute | VALIGN
static HTML.Attribute | VALUE
static HTML.Attribute | VALUETYPE
static HTML.Attribute | VERSION
static HTML.Attribute | VLINK
static HTML.Attribute | VSPACE
static HTML.Attribute | WIDTH
Method Summary
 String toString()
Returns the string representation of this attribute.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

SIZE

public static final HTML.Attribute SIZE

COLOR

public static final HTML.Attribute COLOR

CLEAR

public static final HTML.Attribute CLEAR

BACKGROUND

public static final HTML.Attribute BACKGROUND

BGCOLOR

public static final HTML.Attribute BGCOLOR

TEXT

public static final HTML.Attribute TEXT

LINK

public static final HTML.Attribute LINK

VLINK

public static final HTML.Attribute VLINK

ALINK

public static final HTML.Attribute ALINK

WIDTH

public static final HTML.Attribute WIDTH

HEIGHT

public static final HTML.Attribute HEIGHT

ALIGN

public static final HTML.Attribute ALIGN

NAME

public static final HTML.Attribute NAME

HREF

public static final HTML.Attribute HREF

REL

public static final HTML.Attribute REL

REV

public static final HTML.Attribute REV

TITLE

public static final HTML.Attribute TITLE

TARGET

public static final HTML.Attribute TARGET

SHAPE

public static final HTML.Attribute SHAPE

COORDS

public static final HTML.Attribute COORDS

ISMAP

public static final HTML.Attribute ISMAP

NOHREF

public static final HTML.Attribute NOHREF

ALT

public static final HTML.Attribute ALT

ID

public static final HTML.Attribute ID

SRC

public static final HTML.Attribute SRC

HSPACE

public static final HTML.Attribute HSPACE

VSPACE

public static final HTML.Attribute VSPACE

USEMAP

public static final HTML.Attribute USEMAP

LOWSRC

public static final HTML.Attribute LOWSRC

CODEBASE

public static final HTML.Attribute CODEBASE

CODE

public static final HTML.Attribute CODE

ARCHIVE

public static final HTML.Attribute ARCHIVE

VALUE

public static final HTML.Attribute VALUE

VALUETYPE

public static final HTML.Attribute VALUETYPE

TYPE

public static final HTML.Attribute TYPE

CLASS

public static final HTML.Attribute CLASS

STYLE

public static final HTML.Attribute STYLE

LANG

public static final HTML.Attribute LANG

FACE

public static final HTML.Attribute FACE

DIR

public static final HTML.Attribute DIR

DECLARE

public static final HTML.Attribute DECLARE

CLASSID

public static final HTML.Attribute CLASSID

DATA

public static final HTML.Attribute DATA

CODETYPE

public static final HTML.Attribute CODETYPE

STANDBY

public static final HTML.Attribute STANDBY

BORDER

public static final HTML.Attribute BORDER

SHAPES

public static final HTML.Attribute SHAPES

NOSHADE

public static final HTML.Attribute NOSHADE

COMPACT

public static final HTML.Attribute COMPACT

START

public static final HTML.Attribute START

ACTION

public static final HTML.Attribute ACTION

METHOD

public static final HTML.Attribute METHOD

ENCTYPE

public static final HTML.Attribute ENCTYPE

CHECKED

public static final HTML.Attribute CHECKED

MAXLENGTH

public static final HTML.Attribute MAXLENGTH

MULTIPLE

public static final HTML.Attribute MULTIPLE

SELECTED

public static final HTML.Attribute SELECTED

ROWS

public static final HTML.Attribute ROWS

COLS

public static final HTML.Attribute COLS

DUMMY

public static final HTML.Attribute DUMMY

CELLSPACING

public static final HTML.Attribute CELLSPACING

CELLPADDING

public static final HTML.Attribute CELLPADDING

VALIGN

public static final HTML.Attribute VALIGN

HALIGN

public static final HTML.Attribute HALIGN

NOWRAP

public static final HTML.Attribute NOWRAP

ROWSPAN

public static final HTML.Attribute ROWSPAN

COLSPAN

public static final HTML.Attribute COLSPAN

PROMPT

public static final HTML.Attribute PROMPT

HTTPEQUIV

public static final HTML.Attribute HTTPEQUIV

CONTENT

public static final HTML.Attribute CONTENT

LANGUAGE

public static final HTML.Attribute LANGUAGE

VERSION

public static final HTML.Attribute VERSION

N

public static final HTML.Attribute N

FRAMEBORDER

public static final HTML.Attribute FRAMEBORDER

MARGINWIDTH

public static final HTML.Attribute MARGINWIDTH

MARGINHEIGHT

public static final HTML.Attribute MARGINHEIGHT

SCROLLING

public static final HTML.Attribute SCROLLING

NORESIZE

public static final HTML.Attribute NORESIZE

ENDTAG

public static final HTML.Attribute ENDTAG

COMMENT

public static final HTML.Attribute COMMENT
Method Detail

toString

public String toString()
Returns the string representation of this attribute.

Overrides:
toString in class Object
Returns:
the string representation of this attribute
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


HTML.Tag (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class HTML.Tag

java.lang.Object
    extended by javax.swing.text.html.HTML.Tag
Direct Known Subclasses:
HTML.UnknownTag
Enclosing class:
HTML
public static class HTML.Tag
extends Object

Typesafe enumeration for an HTML tag. Although the set of HTML tags is a closed set, we have left the set open so that people can add their own tag types to their custom parser and still communicate to the reader.

Field Summary
static HTML.Tag | A
static HTML.Tag | ADDRESS
static HTML.Tag | APPLET
static HTML.Tag | AREA
static HTML.Tag | B
static HTML.Tag | BASE
static HTML.Tag | BASEFONT
static HTML.Tag | BIG
static HTML.Tag | BLOCKQUOTE
static HTML.Tag | BODY
static HTML.Tag | BR
static HTML.Tag | CAPTION
static HTML.Tag | CENTER
static HTML.Tag | CITE
static HTML.Tag | CODE
static HTML.Tag | COMMENT All comments are labeled with this tag.
static HTML.Tag | CONTENT All text content is labeled with this tag.
static HTML.Tag | DD
static HTML.Tag | DFN
static HTML.Tag | DIR
static HTML.Tag | DIV
static HTML.Tag | DL
static HTML.Tag | DT
static HTML.Tag | EM
static HTML.Tag | FONT
static HTML.Tag | FORM
static HTML.Tag | FRAME
static HTML.Tag | FRAMESET
static HTML.Tag | H1
static HTML.Tag | H2
static HTML.Tag | H3
static HTML.Tag | H4
static HTML.Tag | H5
static HTML.Tag | H6
static HTML.Tag | HEAD
static HTML.Tag | HR
static HTML.Tag | HTML
static HTML.Tag | I
static HTML.Tag | IMG
static HTML.Tag | IMPLIED All text content must be in a paragraph element.
static HTML.Tag | INPUT
static HTML.Tag | ISINDEX
static HTML.Tag | KBD
static HTML.Tag | LI
static HTML.Tag | LINK
static HTML.Tag | MAP
static HTML.Tag | MENU
static HTML.Tag | META
static HTML.Tag | NOFRAMES
static HTML.Tag | OBJECT
static HTML.Tag | OL
static HTML.Tag | OPTION
static HTML.Tag | P
static HTML.Tag | PARAM
static HTML.Tag | PRE
static HTML.Tag | S
static HTML.Tag | SAMP
static HTML.Tag | SCRIPT
static HTML.Tag | SELECT
static HTML.Tag | SMALL
static HTML.Tag | SPAN
static HTML.Tag | STRIKE
static HTML.Tag | STRONG
static HTML.Tag | STYLE
static HTML.Tag | SUB
static HTML.Tag | SUP
static HTML.Tag | TABLE
static HTML.Tag | TD
static HTML.Tag | TEXTAREA
static HTML.Tag | TH
static HTML.Tag | TITLE
static HTML.Tag | TR
static HTML.Tag | TT
static HTML.Tag | U
static HTML.Tag | UL
static HTML.Tag | VAR
Constructor Summary
 | HTML.Tag()
protected | HTML.Tag(String id) Creates a new Tag with the specified id, and with causesBreak and isBlock set to false.
protected | HTML.Tag(String id, boolean causesBreak, boolean isBlock) Creates a new Tag with the specified id; causesBreak and isBlock are defined by the user.
Method Summary
boolean | breaksFlow() Returns true if this tag causes a line break to the flow of data, otherwise returns false.
boolean | isBlock() Returns true if this tag is a block tag, which is a tag used to add structure to a document.
boolean | isPreformatted() Returns true if this tag is pre-formatted, which is true if the tag is either PRE or TEXTAREA.
String | toString() Returns the string representation of the tag.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

A

public static final HTML.Tag A

ADDRESS

public static final HTML.Tag ADDRESS

APPLET

public static final HTML.Tag APPLET

AREA

public static final HTML.Tag AREA

B

public static final HTML.Tag B

BASE

public static final HTML.Tag BASE

BASEFONT

public static final HTML.Tag BASEFONT

BIG

public static final HTML.Tag BIG

BLOCKQUOTE

public static final HTML.Tag BLOCKQUOTE

BODY

public static final HTML.Tag BODY

BR

public static final HTML.Tag BR

CAPTION

public static final HTML.Tag CAPTION

CENTER

public static final HTML.Tag CENTER

CITE

public static final HTML.Tag CITE

CODE

public static final HTML.Tag CODE

DD

public static final HTML.Tag DD

DFN

public static final HTML.Tag DFN

DIR

public static final HTML.Tag DIR

DIV

public static final HTML.Tag DIV

DL

public static final HTML.Tag DL

DT

public static final HTML.Tag DT

EM

public static final HTML.Tag EM

FONT

public static final HTML.Tag FONT

FORM

public static final HTML.Tag FORM

FRAME

public static final HTML.Tag FRAME

FRAMESET

public static final HTML.Tag FRAMESET

H1

public static final HTML.Tag H1

H2

public static final HTML.Tag H2

H3

public static final HTML.Tag H3

H4

public static final HTML.Tag H4

H5

public static final HTML.Tag H5

H6

public static final HTML.Tag H6

HEAD

public static final HTML.Tag HEAD

HR

public static final HTML.Tag HR

HTML

public static final HTML.Tag HTML

I

public static final HTML.Tag I

IMG

public static final HTML.Tag IMG

INPUT

public static final HTML.Tag INPUT

ISINDEX

public static final HTML.Tag ISINDEX

KBD

public static final HTML.Tag KBD

LI

public static final HTML.Tag LI

LINK

public static final HTML.Tag LINK

MAP

public static final HTML.Tag MAP

MENU

public static final HTML.Tag MENU

META

public static final HTML.Tag META

NOFRAMES

public static final HTML.Tag NOFRAMES

OBJECT

public static final HTML.Tag OBJECT

OL

public static final HTML.Tag OL

OPTION

public static final HTML.Tag OPTION

P

public static final HTML.Tag P

PARAM

public static final HTML.Tag PARAM

PRE

public static final HTML.Tag PRE

SAMP

public static final HTML.Tag SAMP

SCRIPT

public static final HTML.Tag SCRIPT

SELECT

public static final HTML.Tag SELECT

SMALL

public static final HTML.Tag SMALL

SPAN

public static final HTML.Tag SPAN

STRIKE

public static final HTML.Tag STRIKE

S

public static final HTML.Tag S

STRONG

public static final HTML.Tag STRONG

STYLE

public static final HTML.Tag STYLE

SUB

public static final HTML.Tag SUB

SUP

public static final HTML.Tag SUP

TABLE

public static final HTML.Tag TABLE

TD

public static final HTML.Tag TD

TEXTAREA

public static final HTML.Tag TEXTAREA

TH

public static final HTML.Tag TH

TITLE

public static final HTML.Tag TITLE

TR

public static final HTML.Tag TR

TT

public static final HTML.Tag TT

U

public static final HTML.Tag U

UL

public static final HTML.Tag UL

VAR

public static final HTML.Tag VAR

IMPLIED

public static final HTML.Tag IMPLIED
All text content must be in a paragraph element. If a paragraph didn't exist when content was encountered, a paragraph is manufactured.

This is a tag synthesized by the HTML reader. Since elements are identified by their tag type, we create a some fake tag types to mark the elements that were manufactured.

CONTENT

public static final HTML.Tag CONTENT
All text content is labeled with this tag.

This is a tag synthesized by the HTML reader. Since elements are identified by their tag type, we create a some fake tag types to mark the elements that were manufactured.

COMMENT

public static final HTML.Tag COMMENT
All comments are labeled with this tag.

This is a tag synthesized by the HTML reader. Since elements are identified by their tag type, we create a some fake tag types to mark the elements that were manufactured.

Constructor Detail

HTML.Tag

public HTML.Tag()
Since:
1.3

HTML.Tag

protected HTML.Tag(String id)
Creates a new Tag with the specified id, and with causesBreak and isBlock set to false.

Parameters:
id - the id of the new tag

HTML.Tag

protected HTML.Tag(String id,
                   boolean causesBreak,
                   boolean isBlock)
Creates a new Tag with the specified id; causesBreak and isBlock are defined by the user.

Parameters:
id - the id of the new tag
causesBreak - true if this tag causes a break to the flow of data
isBlock - true if the tag is used to add structure to a document
Method Detail

isBlock

public boolean isBlock()
Returns true if this tag is a block tag, which is a tag used to add structure to a document.

Returns:
true if this tag is a block tag, otherwise returns false

breaksFlow

public boolean breaksFlow()
Returns true if this tag causes a line break to the flow of data, otherwise returns false.

Returns:
true if this tag causes a line break to the flow of data, otherwise returns false

isPreformatted

public boolean isPreformatted()
Returns true if this tag is pre-formatted, which is true if the tag is either PRE or TEXTAREA.

Returns:
true if this tag is pre-formatted, otherwise returns false

toString

public String toString()
Returns the string representation of the tag.

Overrides:
toString in class Object
Returns:
the String representation of the tag
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


HTML.UnknownTag (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class HTML.UnknownTag

java.lang.Object
    extended by javax.swing.text.html.HTML.Tag
        extended by javax.swing.text.html.HTML.UnknownTag
All Implemented Interfaces:
Serializable
Enclosing class:
HTML
public static class HTML.UnknownTag
extends HTML.Tag
implements Serializable

Field Summary
Fields inherited from class javax.swing.text.html.HTML.Tag
A, ADDRESS, APPLET, AREA, B, BASE, BASEFONT, BIG, BLOCKQUOTE, BODY, BR, CAPTION, CENTER, CITE, CODE, COMMENT, CONTENT, DD, DFN, DIR, DIV, DL, DT, EM, FONT, FORM, FRAME, FRAMESET, H1, H2, H3, H4, H5, H6, HEAD, HR, HTML, I, IMG, IMPLIED, INPUT, ISINDEX, KBD, LI, LINK, MAP, MENU, META, NOFRAMES, OBJECT, OL, OPTION, P, PARAM, PRE, S, SAMP, SCRIPT, SELECT, SMALL, SPAN, STRIKE, STRONG, STYLE, SUB, SUP, TABLE, TD, TEXTAREA, TH, TITLE, TR, TT, U, UL, VAR
Constructor Summary
HTML.UnknownTag(String id)
Creates a new UnknownTag with the specified id.
Method Summary
boolean | equals(Object obj) Compares this object to the specifed object.
int | hashCode() Returns the hash code which corresponds to the string for this tag.
Methods inherited from class javax.swing.text.html.HTML.Tag
breaksFlow, isBlock, isPreformatted, toString
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait

Constructor Detail

HTML.UnknownTag

public HTML.UnknownTag(String id)
Creates a new UnknownTag with the specified id.

Parameters:
id - the id of the new tag
Method Detail

hashCode

public int hashCode()
Returns the hash code which corresponds to the string for this tag.

Overrides:
hashCode in class Object
Returns:
a hash code value for this object.
See Also:
Object.equals(java.lang.Object), Hashtable

equals

public boolean equals(Object obj)
Compares this object to the specifed object. The result is true if and only if the argument is not null and is an UnknownTag object with the same name.

Overrides:
equals in class Object
Parameters:
obj - the object to compare this tag with
Returns:
true if the objects are equal; false otherwise
See Also:
Object.hashCode(), Hashtable
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


HTMLDocument (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class HTMLDocument

java.lang.Object
    extended by javax.swing.text.AbstractDocument
        extended by javax.swing.text.DefaultStyledDocument
            extended by javax.swing.text.html.HTMLDocument
All Implemented Interfaces:
Document, Serializable, StyledDocument
public class HTMLDocument
extends DefaultStyledDocument

A document that models HTML. The purpose of this model is to support both browsing and editing. As a result, the structure described by an HTML document is not exactly replicated by default. The element structure that is modeled by default, is built by the class HTMLDocument.HTMLReader, which implements the HTMLEditorKit.ParserCallback protocol that the parser expects. To change the structure one can subclass HTMLReader, and reimplement the method getReader(int) to return the new reader implementation. The documentation for HTMLReader should be consulted for the details of the default structure created. The intent is that the document be non-lossy (although reproducing the HTML format may result in a different format).

The document models only HTML, and makes no attempt to store view attributes in it. The elements are identified by the StyleContext.NameAttribute attribute, which should always have a value of type HTML.Tag that identifies the kind of element. Some of the elements (such as comments) are synthesized. The HTMLFactory uses this attribute to determine what kind of view to build.

This document supports incremental loading. The TokenThreshold property controls how much of the parse is buffered before trying to update the element structure of the document. This property is set by the EditorKit so that subclasses can disable it.

The Base property determines the URL against which relative URLs are resolved. By default, this will be the Document.StreamDescriptionProperty if the value of the property is a URL. If a <BASE> tag is encountered, the base will become the URL specified by that tag. Because the base URL is a property, it can of course be set directly.

The default content storage mechanism for this document is a gap buffer (GapContent). Alternatives can be supplied by using the constructor that takes a Content implementation.

Nested Class Summary
class | HTMLDocument.BlockElement An element that represents a structural block of HTML.
class | HTMLDocument.HTMLReader An HTML reader to load an HTML document with an HTML element structure.
static class | HTMLDocument.Iterator An iterator to iterate over a particular type of tag.
class | HTMLDocument.RunElement An element that represents a chunk of text that has a set of HTML character level attributes assigned to it.
Nested classes inherited from class javax.swing.text.DefaultStyledDocument
DefaultStyledDocument.AttributeUndoableEdit, DefaultStyledDocument.ElementBuffer, DefaultStyledDocument.ElementSpec, DefaultStyledDocument.SectionElement
Nested classes inherited from class javax.swing.text.AbstractDocument
AbstractDocument.AbstractElement, AbstractDocument.AttributeContext, AbstractDocument.BranchElement, AbstractDocument.Content, AbstractDocument.DefaultDocumentEvent, AbstractDocument.ElementEdit, AbstractDocument.LeafElement
Field Summary
static String AdditionalComments
Document property key value.
Fields inherited from class javax.swing.text.DefaultStyledDocument
buffer, BUFFER_SIZE_DEFAULT
Fields inherited from class javax.swing.text.AbstractDocument
BAD_LOCATION, BidiElementName, ContentElementName, ElementNameAttribute, listenerList, ParagraphElementName, SectionElementName
Fields inherited from interface javax.swing.text.Document
StreamDescriptionProperty, TitleProperty
Constructor Summary
HTMLDocument()
Constructs an HTML document using the default buffer size and a default StyleSheet.
HTMLDocument(AbstractDocument.Content c, StyleSheet styles)
Constructs an HTML document with the given content storage implementation and the given style/attribute storage mechanism.
HTMLDocument(StyleSheet styles)
Constructs an HTML document with the default content storage implementation and the specified style/attribute storage mechanism.
Method Summary
protected void | create(DefaultStyledDocument.ElementSpec[] data) Replaces the contents of the document with the given element specifications.
protected Element | createBranchElement(Element parent, AttributeSet a) Creates a document branch element, that can contain other elements.
protected AbstractDocument.AbstractElement | createDefaultRoot() Creates the root element to be used to represent the default document structure.
protected Element | createLeafElement(Element parent, AttributeSet a, int p0, int p1) Creates a document leaf element that directly represents text (doesn't have any children).
protected void | fireChangedUpdate(DocumentEvent e) Notifies all listeners that have registered interest for notification on this event type.
protected void | fireUndoableEditUpdate(UndoableEditEvent e) Notifies all listeners that have registered interest for notification on this event type.
URL | getBase() Returns the location to resolve relative URLs against.
Element | getElement(Element e, Object attribute, Object value) Returns the child element of e that contains the attribute, attribute with value value, or null if one isn't found.
Element | getElement(String id) Returns the element that has the given id Attribute.
HTMLDocument.Iterator | getIterator(HTML.Tag t) Fetches an iterator for the specified HTML tag.
HTMLEditorKit.Parser | getParser() Returns the parser that is used when inserting HTML into the existing document.
boolean | getPreservesUnknownTags() Returns the behavior the parser observes when encountering unknown tags.
HTMLEditorKit.ParserCallback | getReader(int pos) Fetches the reader for the parser to use when loading the document with HTML.
HTMLEditorKit.ParserCallback | getReader(int pos, int popDepth, int pushDepth, HTML.Tag insertTag) Returns the reader for the parser to use to load the document with HTML.
StyleSheet | getStyleSheet() Fetches the StyleSheet with the document-specific display rules (CSS) that were specified in the HTML document itself.
int | getTokenThreshold() Gets the number of tokens to buffer before trying to update the documents element structure.
protected void | insert(int offset, DefaultStyledDocument.ElementSpec[] data) Inserts new elements in bulk.
void | insertAfterEnd(Element elem, String htmlText) Inserts the HTML specified as a string after the the end of the given element.
void | insertAfterStart(Element elem, String htmlText) Inserts the HTML specified as a string at the start of the element.
void | insertBeforeEnd(Element elem, String htmlText) Inserts the HTML specified as a string at the end of the element.
void | insertBeforeStart(Element elem, String htmlText) Inserts the HTML specified as a string before the start of the given element.
protected void | insertUpdate(AbstractDocument.DefaultDocumentEvent chng, AttributeSet attr) Updates document structure as a result of text insertion.
void | processHTMLFrameHyperlinkEvent(HTMLFrameHyperlinkEvent e) Processes HyperlinkEvents that are generated by documents in an HTML frame.
void | setBase(URL u) Sets the location to resolve relative URLs against.
void | setInnerHTML(Element elem, String htmlText) Replaces the children of the given element with the contents specified as an HTML string.
void | setOuterHTML(Element elem, String htmlText) Replaces the given element in the parent with the contents specified as an HTML string.
void | setParagraphAttributes(int offset, int length, AttributeSet s, boolean replace) Sets attributes for a paragraph.
void | setParser(HTMLEditorKit.Parser parser) Sets the parser that is used by the methods that insert html into the existing document, such as setInnerHTML, and setOuterHTML.
void | setPreservesUnknownTags(boolean preservesTags) Determines how unknown tags are handled by the parser.
void | setTokenThreshold(int n) Sets the number of tokens to buffer before trying to update the documents element structure.
Methods inherited from class javax.swing.text.DefaultStyledDocument
addDocumentListener, addStyle, getBackground, getCharacterElement, getDefaultRootElement, getFont, getForeground, getLogicalStyle, getParagraphElement, getStyle, getStyleNames, removeDocumentListener, removeStyle, removeUpdate, setCharacterAttributes, setLogicalStyle, styleChanged
Methods inherited from class javax.swing.text.AbstractDocument
addUndoableEditListener, createPosition, dump, fireInsertUpdate, fireRemoveUpdate, getAsynchronousLoadPriority, getAttributeContext, getBidiRootElement, getContent, getCurrentWriter, getDocumentFilter, getDocumentListeners, getDocumentProperties, getEndPosition, getLength, getListeners, getProperty, getRootElements, getStartPosition, getText, getText, getUndoableEditListeners, insertString, postRemoveUpdate, putProperty, readLock, readUnlock, remove, removeUndoableEditListener, render, replace, setAsynchronousLoadPriority, setDocumentFilter, setDocumentProperties, writeLock, writeUnlock
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Methods inherited from interface javax.swing.text.Document
addUndoableEditListener, createPosition, getEndPosition, getLength, getProperty, getRootElements, getStartPosition, getText, getText, insertString, putProperty, remove, removeUndoableEditListener, render

Field Detail

AdditionalComments

public static final String AdditionalComments
Document property key value. The value for the key will be a Vector of Strings that are comments not found in the body.

See Also:
Constant Field Values
Constructor Detail

HTMLDocument

public HTMLDocument()
Constructs an HTML document using the default buffer size and a default StyleSheet. This is a convenience method for the constructor HTMLDocument(Content, StyleSheet).

HTMLDocument

public HTMLDocument(StyleSheet styles)
Constructs an HTML document with the default content storage implementation and the specified style/attribute storage mechanism. This is a convenience method for the constructor HTMLDocument(Content, StyleSheet).

Parameters:
styles - the styles

HTMLDocument

public HTMLDocument(AbstractDocument.Content c,
                    StyleSheet styles)
Constructs an HTML document with the given content storage implementation and the given style/attribute storage mechanism.

Parameters:
c - the container for the content
styles - the styles
Method Detail

getReader

public HTMLEditorKit.ParserCallback getReader(int pos)
Fetches the reader for the parser to use when loading the document with HTML. This is implemented to return an instance of HTMLDocument.HTMLReader. Subclasses can reimplement this method to change how the document gets structured if desired. (For example, to handle custom tags, or structurally represent character style elements.)

Parameters:
pos - the starting position
Returns:
the reader used by the parser to load the document

getReader

public HTMLEditorKit.ParserCallback getReader(int pos,
                                              int popDepth,
                                              int pushDepth,
                                              HTML.Tag insertTag)
Returns the reader for the parser to use to load the document with HTML. This is implemented to return an instance of HTMLDocument.HTMLReader. Subclasses can reimplement this method to change how the document gets structured if desired. (For example, to handle custom tags, or structurally represent character style elements.)

This is a convenience method for getReader(int, int, int, HTML.Tag, TRUE).

Parameters:
popDepth - the number of ElementSpec.EndTagTypes to generate before inserting
pushDepth - the number of ElementSpec.StartTagTypes with a direction of ElementSpec.JoinNextDirection that should be generated before inserting, but after the end tags have been generated
insertTag - the first tag to start inserting into document
Returns:
the reader used by the parser to load the document

getBase

public URL getBase()
Returns the location to resolve relative URLs against. By default this will be the document's URL if the document was loaded from a URL. If a base tag is found and can be parsed, it will be used as the base location.

Returns:
the base location

setBase

public void setBase(URL u)
Sets the location to resolve relative URLs against. By default this will be the document's URL if the document was loaded from a URL. If a base tag is found and can be parsed, it will be used as the base location.

This also sets the base of the StyleSheet to be u as well as the base of the document.

Parameters:
u - the desired base URL

insert

protected void insert(int offset,
                      DefaultStyledDocument.ElementSpec[] data)
               throws BadLocationException
Inserts new elements in bulk. This is how elements get created in the document. The parsing determines what structure is needed and creates the specification as a set of tokens that describe the edit while leaving the document free of a write-lock. This method can then be called in bursts by the reader to acquire a write-lock for a shorter duration (i.e. while the document is actually being altered).

Overrides:
insert in class DefaultStyledDocument
Parameters:
offset - the starting offset
data - the element data
Throws:
BadLocationException - if the given position does not represent a valid location in the associated document.

insertUpdate

protected void insertUpdate(AbstractDocument.DefaultDocumentEvent chng,
                            AttributeSet attr)
Updates document structure as a result of text insertion. This will happen within a write lock. This implementation simply parses the inserted content for line breaks and builds up a set of instructions for the element buffer.

Overrides:
insertUpdate in class DefaultStyledDocument
Parameters:
chng - a description of the document change
attr - the attributes

create

protected void create(DefaultStyledDocument.ElementSpec[] data)
Replaces the contents of the document with the given element specifications. This is called before insert if the loading is done in bursts. This is the only method called if loading the document entirely in one burst.

Overrides:
create in class DefaultStyledDocument
Parameters:
data - the new contents of the document

setParagraphAttributes

public void setParagraphAttributes(int offset,
                                   int length,
                                   AttributeSet s,
                                   boolean replace)
Sets attributes for a paragraph.

This method is thread safe, although most Swing methods are not. Please see Threads and Swing for more information.

Specified by:
setParagraphAttributes in interface StyledDocument
Overrides:
setParagraphAttributes in class DefaultStyledDocument
Parameters:
offset - the offset into the paragraph (must be at least 0)
length - the number of characters affected (must be at least 0)
s - the attributes
replace - whether to replace existing attributes, or merge them

getStyleSheet

public StyleSheet getStyleSheet()
Fetches the StyleSheet with the document-specific display rules (CSS) that were specified in the HTML document itself.

Returns:
the StyleSheet

getIterator

public HTMLDocument.Iterator getIterator(HTML.Tag t)
Fetches an iterator for the specified HTML tag. This can be used for things like iterating over the set of anchors contained, or iterating over the input elements.

Parameters:
t - the requested HTML.Tag
Returns:
the Iterator for the given HTML tag
See Also:
HTML.Tag

createLeafElement

protected Element createLeafElement(Element parent,
                                    AttributeSet a,
                                    int p0,
                                    int p1)
Creates a document leaf element that directly represents text (doesn't have any children). This is implemented to return an element of type HTMLDocument.RunElement.

Overrides:
createLeafElement in class AbstractDocument
Parameters:
parent - the parent element
a - the attributes for the element
p0 - the beginning of the range (must be at least 0)
p1 - the end of the range (must be at least p0)
Returns:
the new element

createBranchElement

protected Element createBranchElement(Element parent,
                                      AttributeSet a)
Creates a document branch element, that can contain other elements. This is implemented to return an element of type HTMLDocument.BlockElement.

Overrides:
createBranchElement in class AbstractDocument
Parameters:
parent - the parent element
a - the attributes
Returns:
the element

createDefaultRoot

protected AbstractDocument.AbstractElement createDefaultRoot()
Creates the root element to be used to represent the default document structure.

Overrides:
createDefaultRoot in class DefaultStyledDocument
Returns:
the element base

setTokenThreshold

public void setTokenThreshold(int n)
Sets the number of tokens to buffer before trying to update the documents element structure.

Parameters:
n - the number of tokens to buffer

getTokenThreshold

public int getTokenThreshold()
Gets the number of tokens to buffer before trying to update the documents element structure. The default value is Integer.MAX_VALUE.

Returns:
the number of tokens to buffer

setPreservesUnknownTags

public void setPreservesUnknownTags(boolean preservesTags)
Determines how unknown tags are handled by the parser. If set to true, unknown tags are put in the model, otherwise they are dropped.

Parameters:
preservesTags - true if unknown tags should be saved in the model, otherwise tags are dropped
See Also:
HTML.Tag

getPreservesUnknownTags

public boolean getPreservesUnknownTags()
Returns the behavior the parser observes when encountering unknown tags.

Returns:
true if unknown tags are to be preserved when parsing
See Also:
HTML.Tag

processHTMLFrameHyperlinkEvent

public void processHTMLFrameHyperlinkEvent(HTMLFrameHyperlinkEvent e)
Processes HyperlinkEvents that are generated by documents in an HTML frame. The HyperlinkEvent type, as the parameter suggests, is HTMLFrameHyperlinkEvent. In addition to the typical information contained in a HyperlinkEvent, this event contains the element that corresponds to the frame in which the click happened (the source element) and the target name. The target name has 4 possible values:
  • _self
  • _parent
  • _top
  • a named frame
If target is _self, the action is to change the value of the HTML.Attribute.SRC attribute and fires a ChangedUpdate event.

If the target is _parent, then it deletes the parent element, which is a <FRAMESET> element, and inserts a new <FRAME> element, and sets its HTML.Attribute.SRC attribute to have a value equal to the destination URL and fire a RemovedUpdate and InsertUpdate.

If the target is _top, this method does nothing. In the implementation of the view for a frame, namely the FrameView, the processing of _top is handled. Given that _top implies replacing the entire document, it made sense to handle this outside of the document that it will replace.

If the target is a named frame, then the element hierarchy is searched for an element with a name equal to the target, its HTML.Attribute.SRC attribute is updated and a ChangedUpdate event is fired.

Parameters:
e - the event

setParser

public void setParser(HTMLEditorKit.Parser parser)
Sets the parser that is used by the methods that insert html into the existing document, such as setInnerHTML, and setOuterHTML.

HTMLEditorKit.createDefaultDocument will set the parser for you. If you create an HTMLDocument by hand, be sure and set the parser accordingly.

Parameters:
parser - the parser to be used for text insertion
Since:
1.3

getParser

public HTMLEditorKit.Parser getParser()
Returns the parser that is used when inserting HTML into the existing document.

Returns:
the parser used for text insertion
Since:
1.3

setInnerHTML

public void setInnerHTML(Element elem,
                         String htmlText)
                  throws BadLocationException,
                         IOException
Replaces the children of the given element with the contents specified as an HTML string.

This will be seen as at least two events, n inserts followed by a remove.

For this to work correcty, the document must have an HTMLEditorKit.Parser set. This will be the case if the document was created from an HTMLEditorKit via the createDefaultDocument method.

Parameters:
elem - the branch element whose children will be replaced
htmlText - the string to be parsed and assigned to elem
Throws:
IllegalArgumentException - if elem is a leaf
IllegalStateException - if an HTMLEditorKit.Parser has not been defined
BadLocationException
IOException
Since:
1.3

setOuterHTML

public void setOuterHTML(Element elem,
                         String htmlText)
                  throws BadLocationException,
                         IOException
Replaces the given element in the parent with the contents specified as an HTML string.

This will be seen as at least two events, n inserts followed by a remove.

When replacing a leaf this will attempt to make sure there is a newline present if one is needed. This may result in an additional element being inserted. Consider, if you were to replace a character element that contained a newline with <img> this would create two elements, one for the image, ane one for the newline.

If you try to replace the element at length you will most likely end up with two elements, eg setOuterHTML(getCharacterElement (getLength()), "blah") will result in two leaf elements at the end, one representing 'blah', and the other representing the end element.

For this to work correcty, the document must have an HTMLEditorKit.Parser set. This will be the case if the document was created from an HTMLEditorKit via the createDefaultDocument method.

Parameters:
elem - the branch element whose children will be replaced
htmlText - the string to be parsed and assigned to elem
Throws:
IllegalStateException - if an HTMLEditorKit.Parser has not been set
BadLocationException
IOException
Since:
1.3

insertAfterStart

public void insertAfterStart(Element elem,
                             String htmlText)
                      throws BadLocationException,
                             IOException
Inserts the HTML specified as a string at the start of the element.

For this to work correcty, the document must have an HTMLEditorKit.Parser set. This will be the case if the document was created from an HTMLEditorKit via the createDefaultDocument method.

Parameters:
elem - the branch element to be the root for the new text
htmlText - the string to be parsed and assigned to elem
Throws:
IllegalStateException - if an HTMLEditorKit.Parser has not been set on the document
BadLocationException
IOException
Since:
1.3

insertBeforeEnd

public void insertBeforeEnd(Element elem,
                            String htmlText)
                     throws BadLocationException,
                            IOException
Inserts the HTML specified as a string at the end of the element.

If elem's children are leaves, and the character at a elem.getEndOffset() - 1 is a newline, this will insert before the newline so that there isn't text after the newline.

For this to work correcty, the document must have an HTMLEditorKit.Parser set. This will be the case if the document was created from an HTMLEditorKit via the createDefaultDocument method.

Parameters:
elem - the element to be the root for the new text
htmlText - the string to be parsed and assigned to elem
Throws:
IllegalStateException - if an HTMLEditorKit.Parser has not been set on the document
BadLocationException
IOException
Since:
1.3

insertBeforeStart

public void insertBeforeStart(Element elem,
                              String htmlText)
                       throws BadLocationException,
                              IOException
Inserts the HTML specified as a string before the start of the given element.

For this to work correcty, the document must have an HTMLEditorKit.Parser set. This will be the case if the document was created from an HTMLEditorKit via the createDefaultDocument method.

Parameters:
elem - the element to be the root for the new text
htmlText - the string to be parsed and assigned to elem
Throws:
IllegalStateException - if an HTMLEditorKit.Parser has not been set on the document
BadLocationException
IOException
Since:
1.3

insertAfterEnd

public void insertAfterEnd(Element elem,
                           String htmlText)
                    throws BadLocationException,
                           IOException
Inserts the HTML specified as a string after the the end of the given element.

For this to work correcty, the document must have an HTMLEditorKit.Parser set. This will be the case if the document was created from an HTMLEditorKit via the createDefaultDocument method.

Parameters:
elem - the element to be the root for the new text
htmlText - the string to be parsed and assigned to elem
Throws:
IllegalStateException - if an HTMLEditorKit.Parser has not been set on the document
BadLocationException
IOException
Since:
1.3

getElement

public Element getElement(String id)
Returns the element that has the given id Attribute. If the element can't be found, null is returned. Note that this method works on an Attribute, not a character tag. In the following HTML snippet: <a id="HelloThere"> the attribute is 'id' and the character tag is 'a'. This is a convenience method for getElement(RootElement, HTML.Attribute.id, id). This is not thread-safe.

Parameters:
id - the string representing the desired Attribute
Returns:
the element with the specified Attribute or null if it can't be found, or null if id is null
Since:
1.3
See Also:
HTML.Attribute

getElement

public Element getElement(Element e,
                          Object attribute,
                          Object value)
Returns the child element of e that contains the attribute, attribute with value value, or null if one isn't found. This is not thread-safe.

Parameters:
e - the root element where the search begins
attribute - the desired Attribute
value - the values for the specified Attribute
Returns:
the element with the specified Attribute and the specified value, or null if it can't be found
Since:
1.3
See Also:
HTML.Attribute

fireChangedUpdate

protected void fireChangedUpdate(DocumentEvent e)
Notifies all listeners that have registered interest for notification on this event type. The event instance is lazily created using the parameters passed into the fire method.

Overrides:
fireChangedUpdate in class AbstractDocument
Parameters:
e - the event
See Also:
EventListenerList

fireUndoableEditUpdate

protected void fireUndoableEditUpdate(UndoableEditEvent e)
Notifies all listeners that have registered interest for notification on this event type. The event instance is lazily created using the parameters passed into the fire method.

Overrides:
fireUndoableEditUpdate in class AbstractDocument
Parameters:
e - the event
See Also:
EventListenerList
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


HTMLDocument.BlockElement (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class HTMLDocument.BlockElement

java.lang.Object
    extended by javax.swing.text.AbstractDocument.AbstractElement
        extended by javax.swing.text.AbstractDocument.BranchElement
            extended by javax.swing.text.html.HTMLDocument.BlockElement
All Implemented Interfaces:
AttributeSet, Element, MutableAttributeSet, Serializable, TreeNode
Enclosing class:
HTMLDocument
public class HTMLDocument.BlockElement
extends AbstractDocument.BranchElement

An element that represents a structural block of HTML.

Nested Class Summary
Nested classes inherited from class javax.swing.text.AttributeSet
AttributeSet.CharacterAttribute, AttributeSet.ColorAttribute, AttributeSet.FontAttribute, AttributeSet.ParagraphAttribute
Field Summary
Fields inherited from interface javax.swing.text.AttributeSet
NameAttribute, ResolveAttribute
Constructor Summary
HTMLDocument.BlockElement(Element parent, AttributeSet a)
Constructs a composite element that initially contains no children.
Method Summary
String | getName() Gets the name of the element.
AttributeSet | getResolveParent() Gets the resolving parent.
Methods inherited from class javax.swing.text.AbstractDocument.BranchElement
children, getAllowsChildren, getElement, getElementCount, getElementIndex, getEndOffset, getStartOffset, isLeaf, positionToElement, replace, toString
Methods inherited from class javax.swing.text.AbstractDocument.AbstractElement
addAttribute, addAttributes, containsAttribute, containsAttributes, copyAttributes, dump, getAttribute, getAttributeCount, getAttributeNames, getAttributes, getChildAt, getChildCount, getDocument, getIndex, getParent, getParentElement, isDefined, isEqual, removeAttribute, removeAttributes, removeAttributes, setResolveParent
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

HTMLDocument.BlockElement

public HTMLDocument.BlockElement(Element parent,
                                 AttributeSet a)
Constructs a composite element that initially contains no children.

Parameters:
parent - the parent element
a - the attributes for the element
Method Detail

getName

public String getName()
Gets the name of the element.

Specified by:
getName in interface Element
Overrides:
getName in class AbstractDocument.BranchElement
Returns:
the name, null if none

getResolveParent

public AttributeSet getResolveParent()
Gets the resolving parent. HTML attributes are not inherited at the model level so we override this to return null.

Specified by:
getResolveParent in interface AttributeSet
Overrides:
getResolveParent in class AbstractDocument.AbstractElement
Returns:
null, there are none
See Also:
AttributeSet.getResolveParent()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


HTMLDocument.HTMLReader (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class HTMLDocument.HTMLReader

java.lang.Object
    extended by javax.swing.text.html.HTMLEditorKit.ParserCallback
        extended by javax.swing.text.html.HTMLDocument.HTMLReader
Enclosing class:
HTMLDocument
public class HTMLDocument.HTMLReader
extends HTMLEditorKit.ParserCallback

An HTML reader to load an HTML document with an HTML element structure. This is a set of callbacks from the parser, implemented to create a set of elements tagged with attributes. The parse builds up tokens (ElementSpec) that describe the element subtree desired, and burst it into the document under the protection of a write lock using the insert method on the document outer class.

The reader can be configured by registering actions (of type HTMLDocument.HTMLReader.TagAction) that describe how to handle the action. The idea behind the actions provided is that the most natural text editing operations can be provided if the element structure boils down to paragraphs with runs of some kind of style in them. Some things are more naturally specified structurally, so arbitrary structure should be allowed above the paragraphs, but will need to be edited with structural actions. The implication of this is that some of the HTML elements specified in the stream being parsed will be collapsed into attributes, and in some cases paragraphs will be synthesized. When HTML elements have been converted to attributes, the attribute key will be of type HTML.Tag, and the value will be of type AttributeSet so that no information is lost. This enables many of the existing actions to work so that the user can type input, hit the return key, backspace, delete, etc and have a reasonable result. Selections can be created, and attributes applied or removed, etc. With this in mind, the work done by the reader can be categorized into the following kinds of tasks:

Block
Build the structure like it's specified in the stream. This produces elements that contain other elements.
Paragraph
Like block except that it's expected that the element will be used with a paragraph view so a paragraph element won't need to be synthesized.
Character
Contribute the element as an attribute that will start and stop at arbitrary text locations. This will ultimately be mixed into a run of text, with all of the currently flattened HTML character elements.
Special
Produce an embedded graphical element.
Form
Produce an element that is like the embedded graphical element, except that it also has a component model associated with it.
Hidden
Create an element that is hidden from view when the document is being viewed read-only, and visible when the document is being edited. This is useful to keep the model from losing information, and used to store things like comments and unrecognized tags.

Currently, <APPLET>, <PARAM>, <MAP>, <AREA>, <LINK>, <SCRIPT> and <STYLE> are unsupported.

The assignment of the actions described is shown in the following table for the tags defined in HTML.Tag.

Tag | Action
HTML.Tag.A | CharacterAction
HTML.Tag.ADDRESS | CharacterAction
HTML.Tag.APPLET | HiddenAction
HTML.Tag.AREA | AreaAction
HTML.Tag.B | CharacterAction
HTML.Tag.BASE | BaseAction
HTML.Tag.BASEFONT | CharacterAction
HTML.Tag.BIG | CharacterAction
HTML.Tag.BLOCKQUOTE | BlockAction
HTML.Tag.BODY | BlockAction
HTML.Tag.BR | SpecialAction
HTML.Tag.CAPTION | BlockAction
HTML.Tag.CENTER | BlockAction
HTML.Tag.CITE | CharacterAction
HTML.Tag.CODE | CharacterAction
HTML.Tag.DD | BlockAction
HTML.Tag.DFN | CharacterAction
HTML.Tag.DIR | BlockAction
HTML.Tag.DIV | BlockAction
HTML.Tag.DL | BlockAction
HTML.Tag.DT | ParagraphAction
HTML.Tag.EM | CharacterAction
HTML.Tag.FONT | CharacterAction
HTML.Tag.FORM | As of 1.4 a BlockAction
HTML.Tag.FRAME | SpecialAction
HTML.Tag.FRAMESET | BlockAction
HTML.Tag.H1 | ParagraphAction
HTML.Tag.H2 | ParagraphAction
HTML.Tag.H3 | ParagraphAction
HTML.Tag.H4 | ParagraphAction
HTML.Tag.H5 | ParagraphAction
HTML.Tag.H6 | ParagraphAction
HTML.Tag.HEAD | HeadAction
HTML.Tag.HR | SpecialAction
HTML.Tag.HTML | BlockAction
HTML.Tag.I | CharacterAction
HTML.Tag.IMG | SpecialAction
HTML.Tag.INPUT | FormAction
HTML.Tag.ISINDEX | IsndexAction
HTML.Tag.KBD | CharacterAction
HTML.Tag.LI | BlockAction
HTML.Tag.LINK | LinkAction
HTML.Tag.MAP | MapAction
HTML.Tag.MENU | BlockAction
HTML.Tag.META | MetaAction
HTML.Tag.NOFRAMES | BlockAction
HTML.Tag.OBJECT | SpecialAction
HTML.Tag.OL | BlockAction
HTML.Tag.OPTION | FormAction
HTML.Tag.P | ParagraphAction
HTML.Tag.PARAM | HiddenAction
HTML.Tag.PRE | PreAction
HTML.Tag.SAMP | CharacterAction
HTML.Tag.SCRIPT | HiddenAction
HTML.Tag.SELECT | FormAction
HTML.Tag.SMALL | CharacterAction
HTML.Tag.STRIKE | CharacterAction
HTML.Tag.S | CharacterAction
HTML.Tag.STRONG | CharacterAction
HTML.Tag.STYLE | StyleAction
HTML.Tag.SUB | CharacterAction
HTML.Tag.SUP | CharacterAction
HTML.Tag.TABLE | BlockAction
HTML.Tag.TD | BlockAction
HTML.Tag.TEXTAREA | FormAction
HTML.Tag.TH | BlockAction
HTML.Tag.TITLE | TitleAction
HTML.Tag.TR | BlockAction
HTML.Tag.TT | CharacterAction
HTML.Tag.U | CharacterAction
HTML.Tag.UL | BlockAction
HTML.Tag.VAR | CharacterAction

Once </html> is encountered, the Actions are no longer notified.

Nested Class Summary
class | HTMLDocument.HTMLReader.BlockAction
class | HTMLDocument.HTMLReader.CharacterAction
class | HTMLDocument.HTMLReader.FormAction Action to support forms by building all of the elements used to represent form controls.
class | HTMLDocument.HTMLReader.HiddenAction
class | HTMLDocument.HTMLReader.IsindexAction
class | HTMLDocument.HTMLReader.ParagraphAction
class | HTMLDocument.HTMLReader.PreAction
class | HTMLDocument.HTMLReader.SpecialAction
class | HTMLDocument.HTMLReader.TagAction An action to be performed in response to parsing a tag.
Field Summary
protected MutableAttributeSet | charAttr
protected Vector | parseBuffer
Fields inherited from class javax.swing.text.html.HTMLEditorKit.ParserCallback
IMPLIED
Constructor Summary
HTMLDocument.HTMLReader(int offset)
HTMLDocument.HTMLReader(int offset, int popDepth, int pushDepth, HTML.Tag insertTag)
Method Summary
protected void | addContent(char[] data, int offs, int length) Adds some text with the current character attributes.
protected void | addContent(char[] data, int offs, int length, boolean generateImpliedPIfNecessary) Adds some text with the current character attributes.
protected void | addSpecialElement(HTML.Tag t, MutableAttributeSet a) Adds content that is basically specified entirely in the attribute set.
protected void | blockClose(HTML.Tag t) Adds an instruction to the parse buffer to close out a block element of the given type.
protected void | blockOpen(HTML.Tag t, MutableAttributeSet attr) Adds an instruction to the parse buffer to create a block element with the given attributes.
void | flush() The last method called on the reader.
void | handleComment(char[] data, int pos)
void | handleEndOfLineString(String eol) This is invoked after the stream has been parsed, but before flush.
void | handleEndTag(HTML.Tag t, int pos) Callback from the parser.
void | handleSimpleTag(HTML.Tag t, MutableAttributeSet a, int pos) Callback from the parser.
void | handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos) Callback from the parser.
void | handleText(char[] data, int pos) Called by the parser to indicate a block of text was encountered.
protected void | popCharacterStyle() Pops a previously pushed character style off the stack to return to a previous style.
protected void | preContent(char[] data) Adds the given content that was encountered in a PRE element.
protected void | pushCharacterStyle() Pushes the current character style on a stack in preparation for forming a new nested character style.
protected void | registerTag(HTML.Tag t, HTMLDocument.HTMLReader.TagAction a) Registers a handler for the given tag.
protected void | textAreaContent(char[] data) Adds the given content to the textarea document.
Methods inherited from class javax.swing.text.html.HTMLEditorKit.ParserCallback
handleError
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

parseBuffer

protected Vector parseBuffer

charAttr

protected MutableAttributeSet charAttr
Constructor Detail

HTMLDocument.HTMLReader

public HTMLDocument.HTMLReader(int offset)

HTMLDocument.HTMLReader

public HTMLDocument.HTMLReader(int offset,
                               int popDepth,
                               int pushDepth,
                               HTML.Tag insertTag)
Method Detail

flush

public void flush()
           throws BadLocationException
The last method called on the reader. It allows any pending changes to be flushed into the document. Since this is currently loading synchronously, the entire set of changes are pushed in at this point.

Overrides:
flush in class HTMLEditorKit.ParserCallback
Throws:
BadLocationException

handleText

public void handleText(char[] data,
                       int pos)
Called by the parser to indicate a block of text was encountered.

Overrides:
handleText in class HTMLEditorKit.ParserCallback

handleStartTag

public void handleStartTag(HTML.Tag t,
                           MutableAttributeSet a,
                           int pos)
Callback from the parser. Route to the appropriate handler for the tag.

Overrides:
handleStartTag in class HTMLEditorKit.ParserCallback

handleComment

public void handleComment(char[] data,
                          int pos)
Overrides:
handleComment in class HTMLEditorKit.ParserCallback

handleEndTag

public void handleEndTag(HTML.Tag t,
                         int pos)
Callback from the parser. Route to the appropriate handler for the tag.

Overrides:
handleEndTag in class HTMLEditorKit.ParserCallback

handleSimpleTag

public void handleSimpleTag(HTML.Tag t,
                            MutableAttributeSet a,
                            int pos)
Callback from the parser. Route to the appropriate handler for the tag.

Overrides:
handleSimpleTag in class HTMLEditorKit.ParserCallback

handleEndOfLineString

public void handleEndOfLineString(String eol)
This is invoked after the stream has been parsed, but before flush. eol will be one of \n, \r or \r\n, which ever is encountered the most in parsing the stream.

Overrides:
handleEndOfLineString in class HTMLEditorKit.ParserCallback
Since:
1.3

registerTag

protected void registerTag(HTML.Tag t,
                           HTMLDocument.HTMLReader.TagAction a)
Registers a handler for the given tag. By default all of the well-known tags will have been registered. This can be used to change the handling of a particular tag or to add support for custom tags.

pushCharacterStyle

protected void pushCharacterStyle()
Pushes the current character style on a stack in preparation for forming a new nested character style.

popCharacterStyle

protected void popCharacterStyle()
Pops a previously pushed character style off the stack to return to a previous style.

textAreaContent

protected void textAreaContent(char[] data)
Adds the given content to the textarea document. This method gets called when we are in a textarea context. Therefore all text that is seen belongs to the text area and is hence added to the TextAreaDocument associated with the text area.

preContent

protected void preContent(char[] data)
Adds the given content that was encountered in a PRE element. This synthesizes lines to hold the runs of text, and makes calls to addContent to actually add the text.

blockOpen

protected void blockOpen(HTML.Tag t,
                         MutableAttributeSet attr)
Adds an instruction to the parse buffer to create a block element with the given attributes.

blockClose

protected void blockClose(HTML.Tag t)
Adds an instruction to the parse buffer to close out a block element of the given type.

addContent

protected void addContent(char[] data,
                          int offs,
                          int length)
Adds some text with the current character attributes.

Parameters:
data - text to be added
offs - location to insert text in the Document
length - length of new text

addContent

protected void addContent(char[] data,
                          int offs,
                          int length,
                          boolean generateImpliedPIfNecessary)
Adds some text with the current character attributes.

Parameters:
data - text to be added
offs - location to insert text in the Document
length - length of new text
generateImpliedPIfNecessary - If false, the text is added as is. If true and the current Element is not a valid Element to contain textual content, a paragraph will be created to contain the text.

addSpecialElement

protected void addSpecialElement(HTML.Tag t,
                                 MutableAttributeSet a)
Adds content that is basically specified entirely in the attribute set.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


HTMLDocument.HTMLReader.BlockAction (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class HTMLDocument.HTMLReader.BlockAction

java.lang.Object
    extended by javax.swing.text.html.HTMLDocument.HTMLReader.TagAction
        extended by javax.swing.text.html.HTMLDocument.HTMLReader.BlockAction
Direct Known Subclasses:
HTMLDocument.HTMLReader.ParagraphAction, HTMLDocument.HTMLReader.PreAction
Enclosing class:
HTMLDocument.HTMLReader
public class HTMLDocument.HTMLReader.BlockAction
extends HTMLDocument.HTMLReader.TagAction

Constructor Summary
HTMLDocument.HTMLReader.BlockAction()
Method Summary
void | end(HTML.Tag t) Called when an end tag is seen for the type of tag this action was registered to.
void | start(HTML.Tag t, MutableAttributeSet attr) Called when a start tag is seen for the type of tag this action was registered to.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

HTMLDocument.HTMLReader.BlockAction

public HTMLDocument.HTMLReader.BlockAction()
Method Detail

start

public void start(HTML.Tag t,
                  MutableAttributeSet attr)
Description copied from class: HTMLDocument.HTMLReader.TagAction
Called when a start tag is seen for the type of tag this action was registered to. The tag argument indicates the actual tag for those actions that are shared across many tags. By default this does nothing and completely ignores the tag.

Overrides:
start in class HTMLDocument.HTMLReader.TagAction

end

public void end(HTML.Tag t)
Description copied from class: HTMLDocument.HTMLReader.TagAction
Called when an end tag is seen for the type of tag this action was registered to. The tag argument indicates the actual tag for those actions that are shared across many tags. By default this does nothing and completely ignores the tag.

Overrides:
end in class HTMLDocument.HTMLReader.TagAction
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


HTMLDocument.HTMLReader.CharacterAction (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class HTMLDocument.HTMLReader.CharacterAction

java.lang.Object
    extended by javax.swing.text.html.HTMLDocument.HTMLReader.TagAction
        extended by javax.swing.text.html.HTMLDocument.HTMLReader.CharacterAction
Enclosing class:
HTMLDocument.HTMLReader
public class HTMLDocument.HTMLReader.CharacterAction
extends HTMLDocument.HTMLReader.TagAction

Constructor Summary
HTMLDocument.HTMLReader.CharacterAction()
Method Summary
void | end(HTML.Tag t) Called when an end tag is seen for the type of tag this action was registered to.
void | start(HTML.Tag t, MutableAttributeSet attr) Called when a start tag is seen for the type of tag this action was registered to.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

HTMLDocument.HTMLReader.CharacterAction

public HTMLDocument.HTMLReader.CharacterAction()
Method Detail

start

public void start(HTML.Tag t,
                  MutableAttributeSet attr)
Description copied from class: HTMLDocument.HTMLReader.TagAction
Called when a start tag is seen for the type of tag this action was registered to. The tag argument indicates the actual tag for those actions that are shared across many tags. By default this does nothing and completely ignores the tag.

Overrides:
start in class HTMLDocument.HTMLReader.TagAction

end

public void end(HTML.Tag t)
Description copied from class: HTMLDocument.HTMLReader.TagAction
Called when an end tag is seen for the type of tag this action was registered to. The tag argument indicates the actual tag for those actions that are shared across many tags. By default this does nothing and completely ignores the tag.

Overrides:
end in class HTMLDocument.HTMLReader.TagAction
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


HTMLDocument.HTMLReader.FormAction (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class HTMLDocument.HTMLReader.FormAction

java.lang.Object
    extended by javax.swing.text.html.HTMLDocument.HTMLReader.TagAction
        extended by javax.swing.text.html.HTMLDocument.HTMLReader.SpecialAction
            extended by javax.swing.text.html.HTMLDocument.HTMLReader.FormAction
Enclosing class:
HTMLDocument.HTMLReader
public class HTMLDocument.HTMLReader.FormAction
extends HTMLDocument.HTMLReader.SpecialAction

Action to support forms by building all of the elements used to represent form controls. This will process the <INPUT>, <TEXTAREA>, <SELECT>, and <OPTION> tags. The element created by this action is expected to have the attribute StyleConstants.ModelAttribute set to the model that holds the state for the form control. This enables multiple views, and allows document to be iterated over picking up the data of the form. The following are the model assignments for the various type of form elements.

Element Type | Model Type
input, type button | DefaultButtonModel
input, type checkbox | JToggleButton.ToggleButtonModel
input, type image | DefaultButtonModel
input, type password | PlainDocument
input, type radio | JToggleButton.ToggleButtonModel
input, type reset | DefaultButtonModel
input, type submit | DefaultButtonModel
input, type text or type is null. | PlainDocument
select | OptionComboBoxModel or an OptionListBoxModel, with an item type of Option
textarea | TextAreaDocument

Constructor Summary
HTMLDocument.HTMLReader.FormAction()
Method Summary
void | end(HTML.Tag t) Called when an end tag is seen for the type of tag this action was registered to.
void | start(HTML.Tag t, MutableAttributeSet attr) Called when a start tag is seen for the type of tag this action was registered to.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

HTMLDocument.HTMLReader.FormAction

public HTMLDocument.HTMLReader.FormAction()
Method Detail

start

public void start(HTML.Tag t,
                  MutableAttributeSet attr)
Description copied from class: HTMLDocument.HTMLReader.TagAction
Called when a start tag is seen for the type of tag this action was registered to. The tag argument indicates the actual tag for those actions that are shared across many tags. By default this does nothing and completely ignores the tag.

Overrides:
start in class HTMLDocument.HTMLReader.SpecialAction

end

public void end(HTML.Tag t)
Description copied from class: HTMLDocument.HTMLReader.TagAction
Called when an end tag is seen for the type of tag this action was registered to. The tag argument indicates the actual tag for those actions that are shared across many tags. By default this does nothing and completely ignores the tag.

Overrides:
end in class HTMLDocument.HTMLReader.TagAction
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


HTMLDocument.HTMLReader.HiddenAction (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class HTMLDocument.HTMLReader.HiddenAction

java.lang.Object
    extended by javax.swing.text.html.HTMLDocument.HTMLReader.TagAction
        extended by javax.swing.text.html.HTMLDocument.HTMLReader.HiddenAction
Enclosing class:
HTMLDocument.HTMLReader
public class HTMLDocument.HTMLReader.HiddenAction
extends HTMLDocument.HTMLReader.TagAction

Constructor Summary
HTMLDocument.HTMLReader.HiddenAction()
Method Summary
void | end(HTML.Tag t) Called when an end tag is seen for the type of tag this action was registered to.
void | start(HTML.Tag t, MutableAttributeSet a) Called when a start tag is seen for the type of tag this action was registered to.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

HTMLDocument.HTMLReader.HiddenAction

public HTMLDocument.HTMLReader.HiddenAction()
Method Detail

start

public void start(HTML.Tag t,
                  MutableAttributeSet a)
Description copied from class: HTMLDocument.HTMLReader.TagAction
Called when a start tag is seen for the type of tag this action was registered to. The tag argument indicates the actual tag for those actions that are shared across many tags. By default this does nothing and completely ignores the tag.

Overrides:
start in class HTMLDocument.HTMLReader.TagAction

end

public void end(HTML.Tag t)
Description copied from class: HTMLDocument.HTMLReader.TagAction
Called when an end tag is seen for the type of tag this action was registered to. The tag argument indicates the actual tag for those actions that are shared across many tags. By default this does nothing and completely ignores the tag.

Overrides:
end in class HTMLDocument.HTMLReader.TagAction
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


HTMLDocument.HTMLReader.IsindexAction (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class HTMLDocument.HTMLReader.IsindexAction

java.lang.Object
    extended by javax.swing.text.html.HTMLDocument.HTMLReader.TagAction
        extended by javax.swing.text.html.HTMLDocument.HTMLReader.IsindexAction
Enclosing class:
HTMLDocument.HTMLReader
public class HTMLDocument.HTMLReader.IsindexAction
extends HTMLDocument.HTMLReader.TagAction

Constructor Summary
HTMLDocument.HTMLReader.IsindexAction()
Method Summary
 void start(HTML.Tag t, MutableAttributeSet a)
Called when a start tag is seen for the type of tag this action was registered to.
Methods inherited from class javax.swing.text.html.HTMLDocument.HTMLReader.TagAction
end
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

HTMLDocument.HTMLReader.IsindexAction

public HTMLDocument.HTMLReader.IsindexAction()
Method Detail

start

public void start(HTML.Tag t,
                  MutableAttributeSet a)
Description copied from class: HTMLDocument.HTMLReader.TagAction
Called when a start tag is seen for the type of tag this action was registered to. The tag argument indicates the actual tag for those actions that are shared across many tags. By default this does nothing and completely ignores the tag.

Overrides:
start in class HTMLDocument.HTMLReader.TagAction
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


HTMLDocument.HTMLReader.ParagraphAction (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class HTMLDocument.HTMLReader.ParagraphAction

java.lang.Object
    extended by javax.swing.text.html.HTMLDocument.HTMLReader.TagAction
        extended by javax.swing.text.html.HTMLDocument.HTMLReader.BlockAction
            extended by javax.swing.text.html.HTMLDocument.HTMLReader.ParagraphAction
Enclosing class:
HTMLDocument.HTMLReader
public class HTMLDocument.HTMLReader.ParagraphAction
extends HTMLDocument.HTMLReader.BlockAction

Constructor Summary
HTMLDocument.HTMLReader.ParagraphAction()
Method Summary
void | end(HTML.Tag t) Called when an end tag is seen for the type of tag this action was registered to.
void | start(HTML.Tag t, MutableAttributeSet a) Called when a start tag is seen for the type of tag this action was registered to.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

HTMLDocument.HTMLReader.ParagraphAction

public HTMLDocument.HTMLReader.ParagraphAction()
Method Detail

start

public void start(HTML.Tag t,
                  MutableAttributeSet a)
Description copied from class: HTMLDocument.HTMLReader.TagAction
Called when a start tag is seen for the type of tag this action was registered to. The tag argument indicates the actual tag for those actions that are shared across many tags. By default this does nothing and completely ignores the tag.

Overrides:
start in class HTMLDocument.HTMLReader.BlockAction

end

public void end(HTML.Tag t)
Description copied from class: HTMLDocument.HTMLReader.TagAction
Called when an end tag is seen for the type of tag this action was registered to. The tag argument indicates the actual tag for those actions that are shared across many tags. By default this does nothing and completely ignores the tag.

Overrides:
end in class HTMLDocument.HTMLReader.BlockAction
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


HTMLDocument.HTMLReader.PreAction (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class HTMLDocument.HTMLReader.PreAction

java.lang.Object
    extended by javax.swing.text.html.HTMLDocument.HTMLReader.TagAction
        extended by javax.swing.text.html.HTMLDocument.HTMLReader.BlockAction
            extended by javax.swing.text.html.HTMLDocument.HTMLReader.PreAction
Enclosing class:
HTMLDocument.HTMLReader
public class HTMLDocument.HTMLReader.PreAction
extends HTMLDocument.HTMLReader.BlockAction

Constructor Summary
HTMLDocument.HTMLReader.PreAction()
Method Summary
void | end(HTML.Tag t) Called when an end tag is seen for the type of tag this action was registered to.
void | start(HTML.Tag t, MutableAttributeSet attr) Called when a start tag is seen for the type of tag this action was registered to.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

HTMLDocument.HTMLReader.PreAction

public HTMLDocument.HTMLReader.PreAction()
Method Detail

start

public void start(HTML.Tag t,
                  MutableAttributeSet attr)
Description copied from class: HTMLDocument.HTMLReader.TagAction
Called when a start tag is seen for the type of tag this action was registered to. The tag argument indicates the actual tag for those actions that are shared across many tags. By default this does nothing and completely ignores the tag.

Overrides:
start in class HTMLDocument.HTMLReader.BlockAction

end

public void end(HTML.Tag t)
Description copied from class: HTMLDocument.HTMLReader.TagAction
Called when an end tag is seen for the type of tag this action was registered to. The tag argument indicates the actual tag for those actions that are shared across many tags. By default this does nothing and completely ignores the tag.

Overrides:
end in class HTMLDocument.HTMLReader.BlockAction
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


HTMLDocument.HTMLReader.SpecialAction (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class HTMLDocument.HTMLReader.SpecialAction

java.lang.Object
    extended by javax.swing.text.html.HTMLDocument.HTMLReader.TagAction
        extended by javax.swing.text.html.HTMLDocument.HTMLReader.SpecialAction
Direct Known Subclasses:
HTMLDocument.HTMLReader.FormAction
Enclosing class:
HTMLDocument.HTMLReader
public class HTMLDocument.HTMLReader.SpecialAction
extends HTMLDocument.HTMLReader.TagAction

Constructor Summary
HTMLDocument.HTMLReader.SpecialAction()
Method Summary
 void start(HTML.Tag t, MutableAttributeSet a)
Called when a start tag is seen for the type of tag this action was registered to.
Methods inherited from class javax.swing.text.html.HTMLDocument.HTMLReader.TagAction
end
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

HTMLDocument.HTMLReader.SpecialAction

public HTMLDocument.HTMLReader.SpecialAction()
Method Detail

start

public void start(HTML.Tag t,
                  MutableAttributeSet a)
Description copied from class: HTMLDocument.HTMLReader.TagAction
Called when a start tag is seen for the type of tag this action was registered to. The tag argument indicates the actual tag for those actions that are shared across many tags. By default this does nothing and completely ignores the tag.

Overrides:
start in class HTMLDocument.HTMLReader.TagAction
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


HTMLDocument.HTMLReader.TagAction (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class HTMLDocument.HTMLReader.TagAction

java.lang.Object
    extended by javax.swing.text.html.HTMLDocument.HTMLReader.TagAction
Direct Known Subclasses:
HTMLDocument.HTMLReader.BlockAction, HTMLDocument.HTMLReader.CharacterAction, HTMLDocument.HTMLReader.HiddenAction, HTMLDocument.HTMLReader.IsindexAction, HTMLDocument.HTMLReader.SpecialAction
Enclosing class:
HTMLDocument.HTMLReader
public class HTMLDocument.HTMLReader.TagAction
extends Object

An action to be performed in response to parsing a tag. This allows customization of how each tag is handled and avoids a large switch statement.

Constructor Summary
HTMLDocument.HTMLReader.TagAction()
Method Summary
void | end(HTML.Tag t) Called when an end tag is seen for the type of tag this action was registered to.
void | start(HTML.Tag t, MutableAttributeSet a) Called when a start tag is seen for the type of tag this action was registered to.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

HTMLDocument.HTMLReader.TagAction

public HTMLDocument.HTMLReader.TagAction()
Method Detail

start

public void start(HTML.Tag t,
                  MutableAttributeSet a)
Called when a start tag is seen for the type of tag this action was registered to. The tag argument indicates the actual tag for those actions that are shared across many tags. By default this does nothing and completely ignores the tag.

end

public void end(HTML.Tag t)
Called when an end tag is seen for the type of tag this action was registered to. The tag argument indicates the actual tag for those actions that are shared across many tags. By default this does nothing and completely ignores the tag.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


HTMLDocument.Iterator (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class HTMLDocument.Iterator

java.lang.Object
    extended by javax.swing.text.html.HTMLDocument.Iterator
Enclosing class:
HTMLDocument
public abstract static class HTMLDocument.Iterator
extends Object

An iterator to iterate over a particular type of tag. The iterator is not thread safe. If reliable access to the document is not already ensured by the context under which the iterator is being used, its use should be performed under the protection of Document.render.

Constructor Summary
HTMLDocument.Iterator()
Method Summary
abstract AttributeSet | getAttributes() Return the attributes for this tag.
abstract int | getEndOffset() Returns the end of the range for which the current occurrence of the tag is defined and has the same attributes.
abstract int | getStartOffset() Returns the start of the range for which the current occurrence of the tag is defined and has the same attributes.
abstract HTML.Tag | getTag() Type of tag this iterator represents.
abstract boolean | isValid() Indicates if the iterator is currently representing an occurrence of a tag.
abstract void | next() Move the iterator forward to the next occurrence of the tag it represents.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

HTMLDocument.Iterator

public HTMLDocument.Iterator()
Method Detail

getAttributes

public abstract AttributeSet getAttributes()
Return the attributes for this tag.

Returns:
the AttributeSet for this tag, or null if none can be found

getStartOffset

public abstract int getStartOffset()
Returns the start of the range for which the current occurrence of the tag is defined and has the same attributes.

Returns:
the start of the range, or -1 if it can't be found

getEndOffset

public abstract int getEndOffset()
Returns the end of the range for which the current occurrence of the tag is defined and has the same attributes.

Returns:
the end of the range

next

public abstract void next()
Move the iterator forward to the next occurrence of the tag it represents.

isValid

public abstract boolean isValid()
Indicates if the iterator is currently representing an occurrence of a tag. If false there are no more tags for this iterator.

Returns:
true if the iterator is currently representing an occurrence of a tag, otherwise returns false

getTag

public abstract HTML.Tag getTag()
Type of tag this iterator represents.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


HTMLDocument.RunElement (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class HTMLDocument.RunElement

java.lang.Object
    extended by javax.swing.text.AbstractDocument.AbstractElement
        extended by javax.swing.text.AbstractDocument.LeafElement
            extended by javax.swing.text.html.HTMLDocument.RunElement
All Implemented Interfaces:
AttributeSet, Element, MutableAttributeSet, Serializable, TreeNode
Enclosing class:
HTMLDocument
public class HTMLDocument.RunElement
extends AbstractDocument.LeafElement

An element that represents a chunk of text that has a set of HTML character level attributes assigned to it.

Nested Class Summary
Nested classes inherited from class javax.swing.text.AttributeSet
AttributeSet.CharacterAttribute, AttributeSet.ColorAttribute, AttributeSet.FontAttribute, AttributeSet.ParagraphAttribute
Field Summary
Fields inherited from interface javax.swing.text.AttributeSet
NameAttribute, ResolveAttribute
Constructor Summary
HTMLDocument.RunElement(Element parent, AttributeSet a, int offs0, int offs1)
Constructs an element that represents content within the document (has no children).
Method Summary
String | getName() Gets the name of the element.
AttributeSet | getResolveParent() Gets the resolving parent.
Methods inherited from class javax.swing.text.AbstractDocument.LeafElement
children, getAllowsChildren, getElement, getElementCount, getElementIndex, getEndOffset, getStartOffset, isLeaf, toString
Methods inherited from class javax.swing.text.AbstractDocument.AbstractElement
addAttribute, addAttributes, containsAttribute, containsAttributes, copyAttributes, dump, getAttribute, getAttributeCount, getAttributeNames, getAttributes, getChildAt, getChildCount, getDocument, getIndex, getParent, getParentElement, isDefined, isEqual, removeAttribute, removeAttributes, removeAttributes, setResolveParent
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

HTMLDocument.RunElement

public HTMLDocument.RunElement(Element parent,
                               AttributeSet a,
                               int offs0,
                               int offs1)
Constructs an element that represents content within the document (has no children).

Parameters:
parent - the parent element
a - the element attributes
offs0 - the start offset (must be at least 0)
offs1 - the end offset (must be at least offs0)
Method Detail

getName

public String getName()
Gets the name of the element.

Specified by:
getName in interface Element
Overrides:
getName in class AbstractDocument.LeafElement
Returns:
the name, null if none

getResolveParent

public AttributeSet getResolveParent()
Gets the resolving parent. HTML attributes are not inherited at the model level so we override this to return null.

Specified by:
getResolveParent in interface AttributeSet
Overrides:
getResolveParent in class AbstractDocument.AbstractElement
Returns:
null, there are none
See Also:
AttributeSet.getResolveParent()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


HTMLEditorKit (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class HTMLEditorKit

java.lang.Object
    extended by javax.swing.text.EditorKit
        extended by javax.swing.text.DefaultEditorKit
            extended by javax.swing.text.StyledEditorKit
                extended by javax.swing.text.html.HTMLEditorKit
All Implemented Interfaces:
Accessible, Cloneable, Serializable
public class HTMLEditorKit
extends StyledEditorKit
implements Accessible

The Swing JEditorPane text component supports different kinds of content via a plug-in mechanism called an EditorKit. Because HTML is a very popular format of content, some support is provided by default. The default support is provided by this class, which supports HTML version 3.2 (with some extensions), and is migrating toward version 4.0. The <applet> tag is not supported, but some support is provided for the <object> tag.

There are several goals of the HTML EditorKit provided, that have an effect upon the way that HTML is modeled. These have influenced its design in a substantial way.

Support editing
It might seem fairly obvious that a plug-in for JEditorPane should provide editing support, but that fact has several design considerations. There are a substantial number of HTML documents that don't properly conform to an HTML specification. These must be normalized somewhat into a correct form if one is to edit them. Additionally, users don't like to be presented with an excessive amount of structure editing, so using traditional text editing gestures is preferred over using the HTML structure exactly as defined in the HTML document.

The modeling of HTML is provided by the class HTMLDocument. Its documention describes the details of how the HTML is modeled. The editing support leverages heavily off of the text package.

Extendable/Scalable
To maximize the usefulness of this kit, a great deal of effort has gone into making it extendable. These are some of the features.
  1. The parser is replacable. The default parser is the Hot Java parser which is DTD based. A different DTD can be used, or an entirely different parser can be used. To change the parser, reimplement the getParser method. The default parser is dynamically loaded when first asked for, so the class files will never be loaded if an alternative parser is used. The default parser is in a separate package called parser below this package.
  2. The parser drives the ParserCallback, which is provided by HTMLDocument. To change the callback, subclass HTMLDocument and reimplement the createDefaultDocument method to return document that produces a different reader. The reader controls how the document is structured. Although the Document provides HTML support by default, there is nothing preventing support of non-HTML tags that result in alternative element structures.
  3. The default view of the models are provided as a hierarchy of View implementations, so one can easily customize how a particular element is displayed or add capabilities for new kinds of elements by providing new View implementations. The default set of views are provided by the HTMLFactory class. This can be easily changed by subclassing or replacing the HTMLFactory and reimplementing the getViewFactory method to return the alternative factory.
  4. The View implementations work primarily off of CSS attributes, which are kept in the views. This makes it possible to have multiple views mapped over the same model that appear substantially different. This can be especially useful for printing. For most HTML attributes, the HTML attributes are converted to CSS attributes for display. This helps make the View implementations more general purpose

Asynchronous Loading
Larger documents involve a lot of parsing and take some time to load. By default, this kit produces documents that will be loaded asynchronously if loaded using JEditorPane.setPage. This is controlled by a property on the document. The method createDefaultDocument can be overriden to change this. The batching of work is done by the HTMLDocument.HTMLReader class. The actual work is done by the DefaultStyledDocument and AbstractDocument classes in the text package.

Customization from current LAF
HTML provides a well known set of features without exactly specifying the display characteristics. Swing has a theme mechanism for its look-and-feel implementations. It is desirable for the look-and-feel to feed display characteristics into the HTML views. An user with poor vision for example would want high contrast and larger than typical fonts.

The support for this is provided by the StyleSheet class. The presentation of the HTML can be heavily influenced by the setting of the StyleSheet property on the EditorKit.

Not lossy
An EditorKit has the ability to be read and save documents. It is generally the most pleasing to users if there is no loss of data between the two operation. The policy of the HTMLEditorKit will be to store things not recognized or not necessarily visible so they can be subsequently written out. The model of the HTML document should therefore contain all information discovered while reading the document. This is constrained in some ways by the need to support editing (i.e. incorrect documents sometimes must be normalized). The guiding principle is that information shouldn't be lost, but some might be synthesized to produce a more correct model or it might be rearranged.

Nested Class Summary
static class | HTMLEditorKit.HTMLFactory A factory to build views for HTML.
static class | HTMLEditorKit.HTMLTextAction An abstract Action providing some convenience methods that may be useful in inserting HTML into an existing document.
static class | HTMLEditorKit.InsertHTMLTextAction InsertHTMLTextAction can be used to insert an arbitrary string of HTML into an existing HTML document.
static class | HTMLEditorKit.LinkController Class to watch the associated component and fire hyperlink events on it when appropriate.
static class | HTMLEditorKit.Parser Interface to be supported by the parser.
static class | HTMLEditorKit.ParserCallback The result of parsing drives these callback methods.
Nested classes inherited from class javax.swing.text.StyledEditorKit
StyledEditorKit.AlignmentAction, StyledEditorKit.BoldAction, StyledEditorKit.FontFamilyAction, StyledEditorKit.FontSizeAction, StyledEditorKit.ForegroundAction, StyledEditorKit.ItalicAction, StyledEditorKit.StyledTextAction, StyledEditorKit.UnderlineAction
Nested classes inherited from class javax.swing.text.DefaultEditorKit
DefaultEditorKit.BeepAction, DefaultEditorKit.CopyAction, DefaultEditorKit.CutAction, DefaultEditorKit.DefaultKeyTypedAction, DefaultEditorKit.InsertBreakAction, DefaultEditorKit.InsertContentAction, DefaultEditorKit.InsertTabAction, DefaultEditorKit.PasteAction
Field Summary
static String | BOLD_ACTION The bold action identifier
static String | COLOR_ACTION The Color choice action identifier The color is passed as an argument
static String | DEFAULT_CSS Default Cascading Style Sheet file that sets up the tag views.
static String | FONT_CHANGE_BIGGER The font size increase to next value action identifier
static String | FONT_CHANGE_SMALLER The font size decrease to next value action identifier
static String | IMG_ALIGN_BOTTOM Align images at the bottom.
static String | IMG_ALIGN_MIDDLE Align images in the middle.
static String | IMG_ALIGN_TOP Align images at the top.
static String | IMG_BORDER Align images at the border.
static String | ITALIC_ACTION The italic action identifier
static String | LOGICAL_STYLE_ACTION The logical style choice action identifier The logical style is passed in as an argument
static String | PARA_INDENT_LEFT The paragraph left indent action identifier
static String | PARA_INDENT_RIGHT The paragraph right indent action identifier
Fields inherited from class javax.swing.text.DefaultEditorKit
backwardAction, beepAction, beginAction, beginLineAction, beginParagraphAction, beginWordAction, copyAction, cutAction, defaultKeyTypedAction, deleteNextCharAction, deletePrevCharAction, downAction, endAction, endLineAction, EndOfLineStringProperty, endParagraphAction, endWordAction, forwardAction, insertBreakAction, insertContentAction, insertTabAction, nextWordAction, pageDownAction, pageUpAction, pasteAction, previousWordAction, readOnlyAction, selectAllAction, selectionBackwardAction, selectionBeginAction, selectionBeginLineAction, selectionBeginParagraphAction, selectionBeginWordAction, selectionDownAction, selectionEndAction, selectionEndLineAction, selectionEndParagraphAction, selectionEndWordAction, selectionForwardAction, selectionNextWordAction, selectionPreviousWordAction, selectionUpAction, selectLineAction, selectParagraphAction, selectWordAction, upAction, writableAction
Constructor Summary
HTMLEditorKit()
Constructs an HTMLEditorKit, creates a StyleContext, and loads the style sheet.
Method Summary
Object | clone() Creates a copy of the editor kit.
Document | createDefaultDocument() Create an uninitialized text storage model that is appropriate for this type of editor.
protected void | createInputAttributes(Element element, MutableAttributeSet set) Copies the key/values in elements AttributeSet into set.
void | deinstall(JEditorPane c) Called when the kit is being removed from the JEditorPane.
AccessibleContext | getAccessibleContext() returns the AccessibleContext associated with this editor kit
Action[] | getActions() Fetches the command list for the editor.
String | getContentType() Get the MIME type of the data that this kit represents support for.
Cursor | getDefaultCursor() Returns the default cursor.
MutableAttributeSet | getInputAttributes() Gets the input attributes used for the styled editing actions.
Cursor | getLinkCursor() Returns the cursor to use over hyper links.
protected HTMLEditorKit.Parser | getParser() Fetch the parser to use for reading HTML streams.
StyleSheet | getStyleSheet() Get the set of styles currently being used to render the HTML elements.
ViewFactory | getViewFactory() Fetch a factory that is suitable for producing views of any models that are produced by this kit.
void | insertHTML(HTMLDocument doc, int offset, String html, int popDepth, int pushDepth, HTML.Tag insertTag) Inserts HTML into an existing document.
void | install(JEditorPane c) Called when the kit is being installed into the a JEditorPane.
void | read(Reader in, Document doc, int pos) Inserts content from the given stream.
void | setDefaultCursor(Cursor cursor) Sets the default cursor.
void | setLinkCursor(Cursor cursor) Sets the cursor to use over links.
void | setStyleSheet(StyleSheet s) Set the set of styles to be used to render the various HTML elements.
void | write(Writer out, Document doc, int pos, int len) Write content from a document to the given stream in a format appropriate for this kind of content handler.
Methods inherited from class javax.swing.text.StyledEditorKit
getCharacterAttributeRun
Methods inherited from class javax.swing.text.DefaultEditorKit
createCaret, read, write
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

DEFAULT_CSS

public static final String DEFAULT_CSS
Default Cascading Style Sheet file that sets up the tag views.

See Also:
Constant Field Values

BOLD_ACTION

public static final String BOLD_ACTION
The bold action identifier

See Also:
Constant Field Values

ITALIC_ACTION

public static final String ITALIC_ACTION
The italic action identifier

See Also:
Constant Field Values

PARA_INDENT_LEFT

public static final String PARA_INDENT_LEFT
The paragraph left indent action identifier

See Also:
Constant Field Values

PARA_INDENT_RIGHT

public static final String PARA_INDENT_RIGHT
The paragraph right indent action identifier

See Also:
Constant Field Values

FONT_CHANGE_BIGGER

public static final String FONT_CHANGE_BIGGER
The font size increase to next value action identifier

See Also:
Constant Field Values

FONT_CHANGE_SMALLER

public static final String FONT_CHANGE_SMALLER
The font size decrease to next value action identifier

See Also:
Constant Field Values

COLOR_ACTION

public static final String COLOR_ACTION
The Color choice action identifier The color is passed as an argument

See Also:
Constant Field Values

LOGICAL_STYLE_ACTION

public static final String LOGICAL_STYLE_ACTION
The logical style choice action identifier The logical style is passed in as an argument

See Also:
Constant Field Values

IMG_ALIGN_TOP

public static final String IMG_ALIGN_TOP
Align images at the top.

See Also:
Constant Field Values

IMG_ALIGN_MIDDLE

public static final String IMG_ALIGN_MIDDLE
Align images in the middle.

See Also:
Constant Field Values

IMG_ALIGN_BOTTOM

public static final String IMG_ALIGN_BOTTOM
Align images at the bottom.

See Also:
Constant Field Values

IMG_BORDER

public static final String IMG_BORDER
Align images at the border.

See Also:
Constant Field Values
Constructor Detail

HTMLEditorKit

public HTMLEditorKit()
Constructs an HTMLEditorKit, creates a StyleContext, and loads the style sheet.

Method Detail

getContentType

public String getContentType()
Get the MIME type of the data that this kit represents support for. This kit supports the type text/html.

Overrides:
getContentType in class DefaultEditorKit
Returns:
the type

getViewFactory

public ViewFactory getViewFactory()
Fetch a factory that is suitable for producing views of any models that are produced by this kit.

Overrides:
getViewFactory in class StyledEditorKit
Returns:
the factory

createDefaultDocument

public Document createDefaultDocument()
Create an uninitialized text storage model that is appropriate for this type of editor.

Overrides:
createDefaultDocument in class StyledEditorKit
Returns:
the model

read

public void read(Reader in,
                 Document doc,
                 int pos)
          throws IOException,
                 BadLocationException
Inserts content from the given stream. If doc is an instance of HTMLDocument, this will read HTML 3.2 text. Inserting HTML into a non-empty document must be inside the body Element, if you do not insert into the body an exception will be thrown. When inserting into a non-empty document all tags outside of the body (head, title) will be dropped.

Overrides:
read in class DefaultEditorKit
Parameters:
in - the stream to read from
doc - the destination for the insertion
pos - the location in the document to place the content
Throws:
IOException - on any I/O error
BadLocationException - if pos represents an invalid location within the document
RuntimeException - (will eventually be a BadLocationException) if pos is invalid

insertHTML

public void insertHTML(HTMLDocument doc,
                       int offset,
                       String html,
                       int popDepth,
                       int pushDepth,
                       HTML.Tag insertTag)
                throws BadLocationException,
                       IOException
Inserts HTML into an existing document.

Parameters:
doc - the document to insert into
offset - the offset to insert HTML at
popDepth - the number of ElementSpec.EndTagTypes to generate before inserting
pushDepth - the number of ElementSpec.StartTagTypes with a direction of ElementSpec.JoinNextDirection that should be generated before inserting, but after the end tags have been generated
insertTag - the first tag to start inserting into document
Throws:
RuntimeException - (will eventually be a BadLocationException) if pos is invalid
BadLocationException
IOException

write

public void write(Writer out,
                  Document doc,
                  int pos,
                  int len)
           throws IOException,
                  BadLocationException
Write content from a document to the given stream in a format appropriate for this kind of content handler.

Overrides:
write in class DefaultEditorKit
Parameters:
out - the stream to write to
doc - the source for the write
pos - the location in the document to fetch the content
len - the amount to write out
Throws:
IOException - on any I/O error
BadLocationException - if pos represents an invalid location within the document

install

public void install(JEditorPane c)
Called when the kit is being installed into the a JEditorPane.

Overrides:
install in class StyledEditorKit
Parameters:
c - the JEditorPane

deinstall

public void deinstall(JEditorPane c)
Called when the kit is being removed from the JEditorPane. This is used to unregister any listeners that were attached.

Overrides:
deinstall in class StyledEditorKit
Parameters:
c - the JEditorPane

setStyleSheet

public void setStyleSheet(StyleSheet s)
Set the set of styles to be used to render the various HTML elements. These styles are specified in terms of CSS specifications. Each document produced by the kit will have a copy of the sheet which it can add the document specific styles to. By default, the StyleSheet specified is shared by all HTMLEditorKit instances. This should be reimplemented to provide a finer granularity if desired.

getStyleSheet

public StyleSheet getStyleSheet()
Get the set of styles currently being used to render the HTML elements. By default the resource specified by DEFAULT_CSS gets loaded, and is shared by all HTMLEditorKit instances.

getActions

public Action[] getActions()
Fetches the command list for the editor. This is the list of commands supported by the superclass augmented by the collection of commands defined locally for style operations.

Overrides:
getActions in class StyledEditorKit
Returns:
the command list

createInputAttributes

protected void createInputAttributes(Element element,
                                     MutableAttributeSet set)
Copies the key/values in elements AttributeSet into set. This does not copy component, icon, or element names attributes. Subclasses may wish to refine what is and what isn't copied here. But be sure to first remove all the attributes that are in set.

This is called anytime the caret moves over a different location.

Overrides:
createInputAttributes in class StyledEditorKit

getInputAttributes

public MutableAttributeSet getInputAttributes()
Gets the input attributes used for the styled editing actions.

Overrides:
getInputAttributes in class StyledEditorKit
Returns:
the attribute set

setDefaultCursor

public void setDefaultCursor(Cursor cursor)
Sets the default cursor.

Since:
1.3

getDefaultCursor

public Cursor getDefaultCursor()
Returns the default cursor.

Since:
1.3

setLinkCursor

public void setLinkCursor(Cursor cursor)
Sets the cursor to use over links.

Since:
1.3

getLinkCursor

public Cursor getLinkCursor()
Returns the cursor to use over hyper links.

clone

public Object clone()
Creates a copy of the editor kit.

Overrides:
clone in class StyledEditorKit
Returns:
the copy

getParser

protected HTMLEditorKit.Parser getParser()
Fetch the parser to use for reading HTML streams. This can be reimplemented to provide a different parser. The default implementation is loaded dynamically to avoid the overhead of loading the default parser if it's not used. The default parser is the HotJava parser using an HTML 3.2 DTD.

getAccessibleContext

public AccessibleContext getAccessibleContext()
returns the AccessibleContext associated with this editor kit

Specified by:
getAccessibleContext in interface Accessible
Returns:
the AccessibleContext associated with this editor kit
Since:
1.4
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


HTMLEditorKit.HTMLFactory (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class HTMLEditorKit.HTMLFactory

java.lang.Object
    extended by javax.swing.text.html.HTMLEditorKit.HTMLFactory
All Implemented Interfaces:
ViewFactory
Enclosing class:
HTMLEditorKit
public static class HTMLEditorKit.HTMLFactory
extends Object
implements ViewFactory

A factory to build views for HTML. The following table describes what this factory will build by default.

Tag | View created
HTML.Tag.CONTENT | InlineView
HTML.Tag.IMPLIED | javax.swing.text.html.ParagraphView
HTML.Tag.P | javax.swing.text.html.ParagraphView
HTML.Tag.H1 | javax.swing.text.html.ParagraphView
HTML.Tag.H2 | javax.swing.text.html.ParagraphView
HTML.Tag.H3 | javax.swing.text.html.ParagraphView
HTML.Tag.H4 | javax.swing.text.html.ParagraphView
HTML.Tag.H5 | javax.swing.text.html.ParagraphView
HTML.Tag.H6 | javax.swing.text.html.ParagraphView
HTML.Tag.DT | javax.swing.text.html.ParagraphView
HTML.Tag.MENU | ListView
HTML.Tag.DIR | ListView
HTML.Tag.UL | ListView
HTML.Tag.OL | ListView
HTML.Tag.LI | BlockView
HTML.Tag.DL | BlockView
HTML.Tag.DD | BlockView
HTML.Tag.BODY | BlockView
HTML.Tag.HTML | BlockView
HTML.Tag.CENTER | BlockView
HTML.Tag.DIV | BlockView
HTML.Tag.BLOCKQUOTE | BlockView
HTML.Tag.PRE | BlockView
HTML.Tag.BLOCKQUOTE | BlockView
HTML.Tag.PRE | BlockView
HTML.Tag.IMG | ImageView
HTML.Tag.HR | HRuleView
HTML.Tag.BR | BRView
HTML.Tag.TABLE | javax.swing.text.html.TableView
HTML.Tag.INPUT | FormView
HTML.Tag.SELECT | FormView
HTML.Tag.TEXTAREA | FormView
HTML.Tag.OBJECT | ObjectView
HTML.Tag.FRAMESET | FrameSetView
HTML.Tag.FRAME | FrameView

Constructor Summary
HTMLEditorKit.HTMLFactory()
Method Summary
 View create(Element elem)
Creates a view from an element.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

HTMLEditorKit.HTMLFactory

public HTMLEditorKit.HTMLFactory()
Method Detail

create

public View create(Element elem)
Creates a view from an element.

Specified by:
create in interface ViewFactory
Parameters:
elem - the element
Returns:
the view
See Also:
View
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


HTMLEditorKit.HTMLTextAction (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class HTMLEditorKit.HTMLTextAction

java.lang.Object
    extended by javax.swing.AbstractAction
        extended by javax.swing.text.TextAction
            extended by javax.swing.text.StyledEditorKit.StyledTextAction
                extended by javax.swing.text.html.HTMLEditorKit.HTMLTextAction
All Implemented Interfaces:
Action, ActionListener, Cloneable, EventListener, Serializable
Direct Known Subclasses:
HTMLEditorKit.InsertHTMLTextAction
Enclosing class:
HTMLEditorKit
public abstract static class HTMLEditorKit.HTMLTextAction
extends StyledEditorKit.StyledTextAction

An abstract Action providing some convenience methods that may be useful in inserting HTML into an existing document.

NOTE: None of the convenience methods obtain a lock on the document. If you have another thread modifying the text these methods may have inconsistent behavior, or return the wrong thing.

Field Summary
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SHORT_DESCRIPTION, SMALL_ICON
Constructor Summary
HTMLEditorKit.HTMLTextAction(String name)
Method Summary
protected int | elementCountToTag(HTMLDocument doc, int offset, HTML.Tag tag) Returns number of elements, starting at the deepest leaf, needed to get to an element representing tag.
protected Element | findElementMatchingTag(HTMLDocument doc, int offset, HTML.Tag tag) Returns the deepest element at offset matching tag.
protected Element[] | getElementsAt(HTMLDocument doc, int offset) Returns an array of the Elements that contain offset.
protected HTMLDocument | getHTMLDocument(JEditorPane e)
protected HTMLEditorKit | getHTMLEditorKit(JEditorPane e)
Methods inherited from class javax.swing.text.StyledEditorKit.StyledTextAction
getEditor, getStyledDocument, getStyledEditorKit, setCharacterAttributes, setParagraphAttributes
Methods inherited from class javax.swing.text.TextAction
augmentList, getFocusedComponent, getTextComponent
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Methods inherited from interface java.awt.event.ActionListener
actionPerformed

Constructor Detail

HTMLEditorKit.HTMLTextAction

public HTMLEditorKit.HTMLTextAction(String name)
Method Detail

getHTMLDocument

protected HTMLDocument getHTMLDocument(JEditorPane e)
Returns:
HTMLDocument of e.

getHTMLEditorKit

protected HTMLEditorKit getHTMLEditorKit(JEditorPane e)
Returns:
HTMLEditorKit for e.

getElementsAt

protected Element[] getElementsAt(HTMLDocument doc,
                                  int offset)
Returns an array of the Elements that contain offset. The first elements corresponds to the root.

elementCountToTag

protected int elementCountToTag(HTMLDocument doc,
                                int offset,
                                HTML.Tag tag)
Returns number of elements, starting at the deepest leaf, needed to get to an element representing tag. This will return -1 if no elements is found representing tag, or 0 if the parent of the leaf at offset represents tag.

findElementMatchingTag

protected Element findElementMatchingTag(HTMLDocument doc,
                                         int offset,
                                         HTML.Tag tag)
Returns the deepest element at offset matching tag.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


HTMLEditorKit.InsertHTMLTextAction (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class HTMLEditorKit.InsertHTMLTextAction

java.lang.Object
    extended by javax.swing.AbstractAction
        extended by javax.swing.text.TextAction
            extended by javax.swing.text.StyledEditorKit.StyledTextAction
                extended by javax.swing.text.html.HTMLEditorKit.HTMLTextAction
                    extended by javax.swing.text.html.HTMLEditorKit.InsertHTMLTextAction
All Implemented Interfaces:
Action, ActionListener, Cloneable, EventListener, Serializable
Enclosing class:
HTMLEditorKit
public static class HTMLEditorKit.InsertHTMLTextAction
extends HTMLEditorKit.HTMLTextAction

InsertHTMLTextAction can be used to insert an arbitrary string of HTML into an existing HTML document. At least two HTML.Tags need to be supplied. The first Tag, parentTag, identifies the parent in the document to add the elements to. The second tag, addTag, identifies the first tag that should be added to the document as seen in the HTML string. One important thing to remember, is that the parser is going to generate all the appropriate tags, even if they aren't in the HTML string passed in.

For example, lets say you wanted to create an action to insert a table into the body. The parentTag would be HTML.Tag.BODY, addTag would be HTML.Tag.TABLE, and the string could be something like <table><tr><td></td></tr></table>.

There is also an option to supply an alternate parentTag and addTag. These will be checked for if there is no parentTag at offset.

Field Summary
protected HTML.Tag | addTag Tag in HTML to start adding tags from.
protected HTML.Tag | alternateAddTag Alternate tag in HTML to start adding tags from if parentTag is not found and alternateParentTag is found.
protected HTML.Tag | alternateParentTag Alternate Tag to check for in the document if parentTag is not found.
protected String | html HTML to insert.
protected HTML.Tag | parentTag Tag to check for in the document.
Fields inherited from class javax.swing.AbstractAction
changeSupport, enabled
Fields inherited from interface javax.swing.Action
ACCELERATOR_KEY, ACTION_COMMAND_KEY, DEFAULT, LONG_DESCRIPTION, MNEMONIC_KEY, NAME, SHORT_DESCRIPTION, SMALL_ICON
Constructor Summary
HTMLEditorKit.InsertHTMLTextAction(String name, String html, HTML.Tag parentTag, HTML.Tag addTag)
HTMLEditorKit.InsertHTMLTextAction(String name, String html, HTML.Tag parentTag, HTML.Tag addTag, HTML.Tag alternateParentTag, HTML.Tag alternateAddTag)
Method Summary
void | actionPerformed(ActionEvent ae) Inserts the HTML into the document.
protected void | insertAtBoundary(JEditorPane editor, HTMLDocument doc, int offset, Element insertElement, String html, HTML.Tag parentTag, HTML.Tag addTag) This is invoked when inserting at a boundary.
protected void | insertAtBoundry(JEditorPane editor, HTMLDocument doc, int offset, Element insertElement, String html, HTML.Tag parentTag, HTML.Tag addTag) Deprecated. As of Java 2 platform v1.3, use insertAtBoundary
protected void | insertHTML(JEditorPane editor, HTMLDocument doc, int offset, String html, int popDepth, int pushDepth, HTML.Tag addTag) A cover for HTMLEditorKit.insertHTML.
Methods inherited from class javax.swing.text.html.HTMLEditorKit.HTMLTextAction
elementCountToTag, findElementMatchingTag, getElementsAt, getHTMLDocument, getHTMLEditorKit
Methods inherited from class javax.swing.text.StyledEditorKit.StyledTextAction
getEditor, getStyledDocument, getStyledEditorKit, setCharacterAttributes, setParagraphAttributes
Methods inherited from class javax.swing.text.TextAction
augmentList, getFocusedComponent, getTextComponent
Methods inherited from class javax.swing.AbstractAction
addPropertyChangeListener, clone, firePropertyChange, getKeys, getPropertyChangeListeners, getValue, isEnabled, putValue, removePropertyChangeListener, setEnabled
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

html

protected String html
HTML to insert.

parentTag

protected HTML.Tag parentTag
Tag to check for in the document.

addTag

protected HTML.Tag addTag
Tag in HTML to start adding tags from.

alternateParentTag

protected HTML.Tag alternateParentTag
Alternate Tag to check for in the document if parentTag is not found.

alternateAddTag

protected HTML.Tag alternateAddTag
Alternate tag in HTML to start adding tags from if parentTag is not found and alternateParentTag is found.

Constructor Detail

HTMLEditorKit.InsertHTMLTextAction

public HTMLEditorKit.InsertHTMLTextAction(String name,
                                          String html,
                                          HTML.Tag parentTag,
                                          HTML.Tag addTag)

HTMLEditorKit.InsertHTMLTextAction

public HTMLEditorKit.InsertHTMLTextAction(String name,
                                          String html,
                                          HTML.Tag parentTag,
                                          HTML.Tag addTag,
                                          HTML.Tag alternateParentTag,
                                          HTML.Tag alternateAddTag)
Method Detail

insertHTML

protected void insertHTML(JEditorPane editor,
                          HTMLDocument doc,
                          int offset,
                          String html,
                          int popDepth,
                          int pushDepth,
                          HTML.Tag addTag)
A cover for HTMLEditorKit.insertHTML. If an exception it thrown it is wrapped in a RuntimeException and thrown.

insertAtBoundary

protected void insertAtBoundary(JEditorPane editor,
                                HTMLDocument doc,
                                int offset,
                                Element insertElement,
                                String html,
                                HTML.Tag parentTag,
                                HTML.Tag addTag)
This is invoked when inserting at a boundary. It determines the number of pops, and then the number of pushes that need to be performed, and then invokes insertHTML.

Since:
1.3

insertAtBoundry

protected void insertAtBoundry(JEditorPane editor,
                               HTMLDocument doc,
                               int offset,
                               Element insertElement,
                               String html,
                               HTML.Tag parentTag,
                               HTML.Tag addTag)
Deprecated. As of Java 2 platform v1.3, use insertAtBoundary

This is invoked when inserting at a boundary. It determines the number of pops, and then the number of pushes that need to be performed, and then invokes insertHTML.

actionPerformed

public void actionPerformed(ActionEvent ae)
Inserts the HTML into the document.

Parameters:
ae - the event
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


HTMLEditorKit.LinkController (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class HTMLEditorKit.LinkController

java.lang.Object
    extended by java.awt.event.MouseAdapter
        extended by javax.swing.text.html.HTMLEditorKit.LinkController
All Implemented Interfaces:
EventListener, MouseListener, MouseMotionListener, Serializable
Enclosing class:
HTMLEditorKit
public static class HTMLEditorKit.LinkController
extends MouseAdapter
implements MouseMotionListener, Serializable

Class to watch the associated component and fire hyperlink events on it when appropriate.

Constructor Summary
HTMLEditorKit.LinkController()
Method Summary
protected void | activateLink(int pos, JEditorPane editor) Calls linkActivated on the associated JEditorPane if the given position represents a link.
void | mouseClicked(MouseEvent e) Called for a mouse click event.
void | mouseDragged(MouseEvent e) Invoked when a mouse button is pressed on a component and then dragged.
void | mouseMoved(MouseEvent e) Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed.
Methods inherited from class java.awt.event.MouseAdapter
mouseEntered, mouseExited, mousePressed, mouseReleased
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

HTMLEditorKit.LinkController

public HTMLEditorKit.LinkController()
Method Detail

mouseClicked

public void mouseClicked(MouseEvent e)
Called for a mouse click event. If the component is read-only (ie a browser) then the clicked event is used to drive an attempt to follow the reference specified by a link.

Specified by:
mouseClicked in interface MouseListener
Overrides:
mouseClicked in class MouseAdapter
Parameters:
e - the mouse event
See Also:
MouseListener.mouseClicked(java.awt.event.MouseEvent)

mouseDragged

public void mouseDragged(MouseEvent e)
Description copied from interface: MouseMotionListener
Invoked when a mouse button is pressed on a component and then dragged. MOUSE_DRAGGED events will continue to be delivered to the component where the drag originated until the mouse button is released (regardless of whether the mouse position is within the bounds of the component).

Due to platform-dependent Drag&Drop implementations, MOUSE_DRAGGED events may not be delivered during a native Drag&Drop operation.

Specified by:
mouseDragged in interface MouseMotionListener

mouseMoved

public void mouseMoved(MouseEvent e)
Description copied from interface: MouseMotionListener
Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed.

Specified by:
mouseMoved in interface MouseMotionListener

activateLink

protected void activateLink(int pos,
                            JEditorPane editor)
Calls linkActivated on the associated JEditorPane if the given position represents a link.

This is implemented to forward to the method with the same name, but with the following args both == -1.

Parameters:
pos - the position
editor - the editor pane
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


HTMLEditorKit.Parser (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class HTMLEditorKit.Parser

java.lang.Object
    extended by javax.swing.text.html.HTMLEditorKit.Parser
Direct Known Subclasses:
ParserDelegator
Enclosing class:
HTMLEditorKit
public abstract static class HTMLEditorKit.Parser
extends Object

Interface to be supported by the parser. This enables providing a different parser while reusing some of the implementation provided by this editor kit.

Constructor Summary
HTMLEditorKit.Parser()
Method Summary
abstract  void parse(Reader r, HTMLEditorKit.ParserCallback cb, boolean ignoreCharSet)
Parse the given stream and drive the given callback with the results of the parse.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

HTMLEditorKit.Parser

public HTMLEditorKit.Parser()
Method Detail

parse

public abstract void parse(Reader r,
                           HTMLEditorKit.ParserCallback cb,
                           boolean ignoreCharSet)
                    throws IOException
Parse the given stream and drive the given callback with the results of the parse. This method should be implemented to be thread-safe.

Throws:
IOException
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


HTMLEditorKit.ParserCallback (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class HTMLEditorKit.ParserCallback

java.lang.Object
    extended by javax.swing.text.html.HTMLEditorKit.ParserCallback
Direct Known Subclasses:
HTMLDocument.HTMLReader
Enclosing class:
HTMLEditorKit
public static class HTMLEditorKit.ParserCallback
extends Object

The result of parsing drives these callback methods. The open and close actions should be balanced. The flush method will be the last method called, to give the receiver a chance to flush any pending data into the document.

Refer to DocumentParser, the default parser used, for further information on the contents of the AttributeSets, the positions, and other info.

See Also:
DocumentParser

Field Summary
static Object IMPLIED
This is passed as an attribute in the attributeset to indicate the element is implied eg, the string '<>foo<\t>' contains an implied html element and an implied body element.
Constructor Summary
HTMLEditorKit.ParserCallback()
Method Summary
void | flush()
void | handleComment(char[] data, int pos)
void | handleEndOfLineString(String eol) This is invoked after the stream has been parsed, but before flush.
void | handleEndTag(HTML.Tag t, int pos)
void | handleError(String errorMsg, int pos)
void | handleSimpleTag(HTML.Tag t, MutableAttributeSet a, int pos)
void | handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos)
void | handleText(char[] data, int pos)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

IMPLIED

public static final Object IMPLIED
This is passed as an attribute in the attributeset to indicate the element is implied eg, the string '<>foo<\t>' contains an implied html element and an implied body element.

Since:
1.3
Constructor Detail

HTMLEditorKit.ParserCallback

public HTMLEditorKit.ParserCallback()
Method Detail

flush

public void flush()
           throws BadLocationException
Throws:
BadLocationException

handleText

public void handleText(char[] data,
                       int pos)

handleComment

public void handleComment(char[] data,
                          int pos)

handleStartTag

public void handleStartTag(HTML.Tag t,
                           MutableAttributeSet a,
                           int pos)

handleEndTag

public void handleEndTag(HTML.Tag t,
                         int pos)

handleSimpleTag

public void handleSimpleTag(HTML.Tag t,
                            MutableAttributeSet a,
                            int pos)

handleError

public void handleError(String errorMsg,
                        int pos)

handleEndOfLineString

public void handleEndOfLineString(String eol)
This is invoked after the stream has been parsed, but before flush. eol will be one of \n, \r or \r\n, which ever is encountered the most in parsing the stream.

Since:
1.3
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


HTMLFrameHyperlinkEvent (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class HTMLFrameHyperlinkEvent

java.lang.Object
    extended by java.util.EventObject
        extended by javax.swing.event.HyperlinkEvent
            extended by javax.swing.text.html.HTMLFrameHyperlinkEvent
All Implemented Interfaces:
Serializable
public class HTMLFrameHyperlinkEvent
extends HyperlinkEvent

HTMLFrameHyperlinkEvent is used to notify interested parties that link was activated in a frame.

Nested Class Summary
Nested classes inherited from class javax.swing.event.HyperlinkEvent
HyperlinkEvent.EventType
Field Summary
Fields inherited from class java.util.EventObject
source
Constructor Summary
HTMLFrameHyperlinkEvent(Object source, HyperlinkEvent.EventType type, URL targetURL, Element sourceElement, String targetFrame)
Creates a new object representing a hypertext link event.
HTMLFrameHyperlinkEvent(Object source, HyperlinkEvent.EventType type, URL targetURL, String targetFrame)
Creates a new object representing a html frame hypertext link event.
HTMLFrameHyperlinkEvent(Object source, HyperlinkEvent.EventType type, URL targetURL, String desc, Element sourceElement, String targetFrame)
Creates a new object representing a hypertext link event.
HTMLFrameHyperlinkEvent(Object source, HyperlinkEvent.EventType type, URL targetURL, String desc, String targetFrame)
Creates a new object representing a hypertext link event.
Method Summary
 String getTarget()
returns the target for the link.
Methods inherited from class javax.swing.event.HyperlinkEvent
getDescription, getEventType, getSourceElement, getURL
Methods inherited from class java.util.EventObject
getSource, toString
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

HTMLFrameHyperlinkEvent

public HTMLFrameHyperlinkEvent(Object source,
                               HyperlinkEvent.EventType type,
                               URL targetURL,
                               String targetFrame)
Creates a new object representing a html frame hypertext link event.

Parameters:
source - the object responsible for the event
type - the event type
targetURL - the affected URL
targetFrame - the Frame to display the document in

HTMLFrameHyperlinkEvent

public HTMLFrameHyperlinkEvent(Object source,
                               HyperlinkEvent.EventType type,
                               URL targetURL,
                               String desc,
                               String targetFrame)
Creates a new object representing a hypertext link event.

Parameters:
source - the object responsible for the event
type - the event type
targetURL - the affected URL
desc - a description
targetFrame - the Frame to display the document in

HTMLFrameHyperlinkEvent

public HTMLFrameHyperlinkEvent(Object source,
                               HyperlinkEvent.EventType type,
                               URL targetURL,
                               Element sourceElement,
                               String targetFrame)
Creates a new object representing a hypertext link event.

Parameters:
source - the object responsible for the event
type - the event type
targetURL - the affected URL
sourceElement - the element that corresponds to the source of the event
targetFrame - the Frame to display the document in

HTMLFrameHyperlinkEvent

public HTMLFrameHyperlinkEvent(Object source,
                               HyperlinkEvent.EventType type,
                               URL targetURL,
                               String desc,
                               Element sourceElement,
                               String targetFrame)
Creates a new object representing a hypertext link event.

Parameters:
source - the object responsible for the event
type - the event type
targetURL - the affected URL
desc - a desription
sourceElement - the element that corresponds to the source of the event
targetFrame - the Frame to display the document in
Method Detail

getTarget

public String getTarget()
returns the target for the link.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


HTMLWriter (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class HTMLWriter

java.lang.Object
    extended by javax.swing.text.AbstractWriter
        extended by javax.swing.text.html.HTMLWriter
public class HTMLWriter
extends AbstractWriter

This is a writer for HTMLDocuments.

Field Summary
Fields inherited from class javax.swing.text.AbstractWriter
NEWLINE
Constructor Summary
HTMLWriter(Writer w, HTMLDocument doc)
Creates a new HTMLWriter.
HTMLWriter(Writer w, HTMLDocument doc, int pos, int len)
Creates a new HTMLWriter.
Method Summary
protected void | closeOutUnwantedEmbeddedTags(AttributeSet attr) Searches the attribute set and for each tag that is stored in the tag vector.
protected void | comment(Element elem) Writes out comments.
protected void | emptyTag(Element elem) Writes out all empty elements (all tags that have no corresponding end tag).
protected void | endTag(Element elem) Writes out an end tag for the element.
protected boolean | isBlockTag(AttributeSet attr) Determines if the HTML.Tag associated with the element is a block tag.
protected boolean | matchNameAttribute(AttributeSet attr, HTML.Tag tag) Returns true if the StyleConstants.NameAttribute is equal to the tag that is passed in as a parameter.
protected void | output(char[] chars, int start, int length) This method is overriden to map any character entities, such as < to &lt;.
protected void | selectContent(AttributeSet attr) Writes out the content of the SELECT form element.
protected void | startTag(Element elem) Writes out a start tag for the element.
protected boolean | synthesizedElement(Element elem) Returns true if the element is a synthesized element.
protected void | text(Element elem) Writes out text.
protected void | textAreaContent(AttributeSet attr) Writes out text that is contained in a TEXTAREA form element.
void | write() Iterates over the Element tree and controls the writing out of all the tags and its attributes.
protected void | writeAttributes(AttributeSet attr) Writes out the attribute set.
protected void | writeEmbeddedTags(AttributeSet attr) Searches for embedded tags in the AttributeSet and writes them out.
protected void | writeLineSeparator() Writes the line separator.
protected void | writeOption(Option option) Writes out the content of the Option form element.
Methods inherited from class javax.swing.text.AbstractWriter
decrIndent, getCanWrapLines, getCurrentLineLength, getDocument, getElementIterator, getEndOffset, getIndentLevel, getIndentSpace, getLineLength, getLineSeparator, getStartOffset, getText, getWriter, incrIndent, indent, inRange, isLineEmpty, setCanWrapLines, setCurrentLineLength, setIndentSpace, setLineLength, setLineSeparator, write, write, write
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

HTMLWriter

public HTMLWriter(Writer w,
                  HTMLDocument doc)
Creates a new HTMLWriter.

Parameters:
w - a Writer
doc - an HTMLDocument

HTMLWriter

public HTMLWriter(Writer w,
                  HTMLDocument doc,
                  int pos,
                  int len)
Creates a new HTMLWriter.

Parameters:
w - a Writer
doc - an HTMLDocument
pos - the document location from which to fetch the content
len - the amount to write out
Method Detail

write

public void write()
           throws IOException,
                  BadLocationException
Iterates over the Element tree and controls the writing out of all the tags and its attributes.

Specified by:
write in class AbstractWriter
Throws:
IOException - on any I/O error
BadLocationException - if pos represents an invalid location within the document.

writeAttributes

protected void writeAttributes(AttributeSet attr)
                        throws IOException
Writes out the attribute set. Ignores all attributes with a key of type HTML.Tag, attributes with a key of type StyleConstants, and attributes with a key of type HTML.Attribute.ENDTAG.

Overrides:
writeAttributes in class AbstractWriter
Parameters:
attr - an AttributeSet
Throws:
IOException - on any I/O error

emptyTag

protected void emptyTag(Element elem)
                 throws BadLocationException,
                        IOException
Writes out all empty elements (all tags that have no corresponding end tag).

Parameters:
elem - an Element
Throws:
IOException - on any I/O error
BadLocationException - if pos represents an invalid location within the document.

isBlockTag

protected boolean isBlockTag(AttributeSet attr)
Determines if the HTML.Tag associated with the element is a block tag.

Parameters:
attr - an AttributeSet
Returns:
true if tag is block tag, false otherwise.

startTag

protected void startTag(Element elem)
                 throws IOException,
                        BadLocationException
Writes out a start tag for the element. Ignores all synthesized elements.

Parameters:
elem - an Element
Throws:
IOException - on any I/O error
BadLocationException

textAreaContent

protected void textAreaContent(AttributeSet attr)
                        throws BadLocationException,
                               IOException
Writes out text that is contained in a TEXTAREA form element.

Parameters:
attr - an AttributeSet
Throws:
IOException - on any I/O error
BadLocationException - if pos represents an invalid location within the document.

text

protected void text(Element elem)
             throws BadLocationException,
                    IOException
Writes out text. If a range is specified when the constructor is invoked, then only the appropriate range of text is written out.

Overrides:
text in class AbstractWriter
Parameters:
elem - an Element
Throws:
IOException - on any I/O error
BadLocationException - if pos represents an invalid location within the document.

selectContent

protected void selectContent(AttributeSet attr)
                      throws IOException
Writes out the content of the SELECT form element.

Parameters:
attr - the AttributeSet associated with the form element
Throws:
IOException - on any I/O error

writeOption

protected void writeOption(Option option)
                    throws IOException
Writes out the content of the Option form element.

Parameters:
option - an Option
Throws:
IOException - on any I/O error

endTag

protected void endTag(Element elem)
               throws IOException
Writes out an end tag for the element.

Parameters:
elem - an Element
Throws:
IOException - on any I/O error

comment

protected void comment(Element elem)
                throws BadLocationException,
                       IOException
Writes out comments.

Parameters:
elem - an Element
Throws:
IOException - on any I/O error
BadLocationException - if pos represents an invalid location within the document.

synthesizedElement

protected boolean synthesizedElement(Element elem)
Returns true if the element is a synthesized element. Currently we are only testing for the p-implied tag.

matchNameAttribute

protected boolean matchNameAttribute(AttributeSet attr,
                                     HTML.Tag tag)
Returns true if the StyleConstants.NameAttribute is equal to the tag that is passed in as a parameter.

writeEmbeddedTags

protected void writeEmbeddedTags(AttributeSet attr)
                          throws IOException
Searches for embedded tags in the AttributeSet and writes them out. It also stores these tags in a vector so that when appropriate the corresponding end tags can be written out.

Throws:
IOException - on any I/O error

closeOutUnwantedEmbeddedTags

protected void closeOutUnwantedEmbeddedTags(AttributeSet attr)
                                     throws IOException
Searches the attribute set and for each tag that is stored in the tag vector. If the tag isnt found, then the tag is removed from the vector and a corresponding end tag is written out.

Throws:
IOException - on any I/O error

writeLineSeparator

protected void writeLineSeparator()
                           throws IOException
Writes the line separator. This is overriden to make sure we don't replace the newline content in case it is outside normal ascii.

Overrides:
writeLineSeparator in class AbstractWriter
Throws:
IOException

output

protected void output(char[] chars,
                      int start,
                      int length)
               throws IOException
This method is overriden to map any character entities, such as < to &lt;. super.output will be invoked to write the content.

Overrides:
output in class AbstractWriter
Throws:
IOException
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ImageView (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class ImageView

java.lang.Object
    extended by javax.swing.text.View
        extended by javax.swing.text.html.ImageView
All Implemented Interfaces:
SwingConstants
public class ImageView
extends View

View of an Image, intended to support the HTML <IMG> tag. Supports scaling via the HEIGHT and WIDTH attributes of the tag. If the image is unable to be loaded any text specified via the ALT attribute will be rendered.

While this class has been part of swing for a while now, it is public as of 1.4.

Since:
1.4
See Also:
IconView

Field Summary
Fields inherited from class javax.swing.text.View
BadBreakWeight, ExcellentBreakWeight, ForcedBreakWeight, GoodBreakWeight, X_AXIS, Y_AXIS
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
Constructor Summary
ImageView(Element elem)
Creates a new view that represents an IMG element.
Method Summary
void | changedUpdate(DocumentEvent e, Shape a, ViewFactory f) Invoked when the Elements attributes have changed.
float | getAlignment(int axis) Determines the desired alignment for this view along an axis.
String | getAltText() Returns the text to display if the image can't be loaded.
AttributeSet | getAttributes() Fetches the attributes to use when rendering.
Image | getImage() Returns the image to render.
URL | getImageURL() Return a URL for the image source, or null if it could not be determined.
Icon | getLoadingImageIcon() Returns the icon to use while in the process of loading the image.
boolean | getLoadsSynchronously() Returns true if the image should be loaded when first asked for.
Icon | getNoImageIcon() Returns the icon to use if the image couldn't be found.
float | getPreferredSpan(int axis) Determines the preferred span for this view along an axis.
protected StyleSheet | getStyleSheet() Convenience method to get the StyleSheet.
String | getToolTipText(float x, float y, Shape allocation) For images the tooltip text comes from text specified with the ALT attribute.
Shape | modelToView(int pos, Shape a, Position.Bias b) Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
void | paint(Graphics g, Shape a) Paints the View.
void | setLoadsSynchronously(boolean newValue) Sets how the image is loaded.
void | setParent(View parent) Establishes the parent view for this view.
protected void | setPropertiesFromAttributes() Update any cached values that come from attributes.
void | setSize(float width, float height) Sets the size of the view.
int | viewToModel(float x, float y, Shape a, Position.Bias[] bias) Provides a mapping from the view coordinate space to the logical coordinate space of the model.
Methods inherited from class javax.swing.text.View
append, breakView, createFragment, forwardUpdate, forwardUpdateToView, getBreakWeight, getChildAllocation, getContainer, getDocument, getElement, getEndOffset, getGraphics, getMaximumSpan, getMinimumSpan, getNextVisualPositionFrom, getParent, getResizeWeight, getStartOffset, getView, getViewCount, getViewFactory, getViewIndex, getViewIndex, insert, insertUpdate, isVisible, modelToView, modelToView, preferenceChanged, remove, removeAll, removeUpdate, replace, updateChildren, updateLayout, viewToModel
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ImageView

public ImageView(Element elem)
Creates a new view that represents an IMG element.

Parameters:
elem - the element to create a view for
Method Detail

getAltText

public String getAltText()
Returns the text to display if the image can't be loaded. This is obtained from the Elements attribute set with the attribute name HTML.Attribute.ALT.

getImageURL

public URL getImageURL()
Return a URL for the image source, or null if it could not be determined.

getNoImageIcon

public Icon getNoImageIcon()
Returns the icon to use if the image couldn't be found.

getLoadingImageIcon

public Icon getLoadingImageIcon()
Returns the icon to use while in the process of loading the image.

getImage

public Image getImage()
Returns the image to render.

setLoadsSynchronously

public void setLoadsSynchronously(boolean newValue)
Sets how the image is loaded. If newValue is true, the image we be loaded when first asked for, otherwise it will be loaded asynchronously. The default is to not load synchronously, that is to load the image asynchronously.

getLoadsSynchronously

public boolean getLoadsSynchronously()
Returns true if the image should be loaded when first asked for.

getStyleSheet

protected StyleSheet getStyleSheet()
Convenience method to get the StyleSheet.

getAttributes

public AttributeSet getAttributes()
Fetches the attributes to use when rendering. This is implemented to multiplex the attributes specified in the model with a StyleSheet.

Overrides:
getAttributes in class View

getToolTipText

public String getToolTipText(float x,
                             float y,
                             Shape allocation)
For images the tooltip text comes from text specified with the ALT attribute. This is overriden to return getAltText.

Overrides:
getToolTipText in class View
See Also:
JTextComponent.getToolTipText(java.awt.event.MouseEvent)

setPropertiesFromAttributes

protected void setPropertiesFromAttributes()
Update any cached values that come from attributes.

setParent

public void setParent(View parent)
Establishes the parent view for this view. Seize this moment to cache the AWT Container I'm in.

Overrides:
setParent in class View
Parameters:
parent - the new parent, or null if the view is being removed from a parent

changedUpdate

public void changedUpdate(DocumentEvent e,
                          Shape a,
                          ViewFactory f)
Invoked when the Elements attributes have changed. Recreates the image.

Overrides:
changedUpdate in class View
Parameters:
e - the change information from the associated document
a - the current allocation of the view
f - the factory to use to rebuild if the view has children
See Also:
View.changedUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory)

paint

public void paint(Graphics g,
                  Shape a)
Paints the View.

Specified by:
paint in class View
Parameters:
g - the rendering surface to use
a - the allocated region to render into
See Also:
View.paint(java.awt.Graphics, java.awt.Shape)

getPreferredSpan

public float getPreferredSpan(int axis)
Determines the preferred span for this view along an axis.

Specified by:
getPreferredSpan in class View
Parameters:
axis - may be either X_AXIS or Y_AXIS
Returns:
the span the view would like to be rendered into; typically the view is told to render into the span that is returned, although there is no guarantee; the parent may choose to resize or break the view
See Also:
View.getPreferredSpan(int)

getAlignment

public float getAlignment(int axis)
Determines the desired alignment for this view along an axis. This is implemented to give the alignment to the bottom of the icon along the y axis, and the default along the x axis.

Overrides:
getAlignment in class View
Parameters:
axis - may be either X_AXIS or Y_AXIS
Returns:
the desired alignment; this should be a value between 0.0 and 1.0 where 0 indicates alignment at the origin and 1.0 indicates alignment to the full span away from the origin; an alignment of 0.5 would be the center of the view

modelToView

public Shape modelToView(int pos,
                         Shape a,
                         Position.Bias b)
                  throws BadLocationException
Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.

Specified by:
modelToView in class View
Parameters:
pos - the position to convert
a - the allocated region to render into
b - the bias toward the previous character or the next character represented by the offset, in case the position is a boundary of two views; b will have one of these values:
  • Position.Bias.Forward
  • Position.Bias.Backward
Returns:
the bounding box of the given position
Throws:
BadLocationException - if the given position does not represent a valid location in the associated document
See Also:
View.modelToView(int, java.awt.Shape, javax.swing.text.Position.Bias)

viewToModel

public int viewToModel(float x,
                       float y,
                       Shape a,
                       Position.Bias[] bias)
Provides a mapping from the view coordinate space to the logical coordinate space of the model.

Specified by:
viewToModel in class View
Parameters:
x - the X coordinate
y - the Y coordinate
a - the allocated region to render into
Returns:
the location within the model that best represents the given point of view
See Also:
View.viewToModel(float, float, java.awt.Shape, javax.swing.text.Position.Bias[])

setSize

public void setSize(float width,
                    float height)
Sets the size of the view. This should cause layout of the view if it has any layout duties.

Overrides:
setSize in class View
Parameters:
width - the width >= 0
height - the height >= 0
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


InlineView (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class InlineView

java.lang.Object
    extended by javax.swing.text.View
        extended by javax.swing.text.GlyphView
            extended by javax.swing.text.LabelView
                extended by javax.swing.text.html.InlineView
All Implemented Interfaces:
Cloneable, SwingConstants, TabableView
public class InlineView
extends LabelView

Displays the inline element styles based upon css attributes.

Nested Class Summary
Nested classes inherited from class javax.swing.text.GlyphView
GlyphView.GlyphPainter
Field Summary
Fields inherited from class javax.swing.text.View
BadBreakWeight, ExcellentBreakWeight, ForcedBreakWeight, GoodBreakWeight, X_AXIS, Y_AXIS
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
Constructor Summary
InlineView(Element elem)
Constructs a new view wrapped on an element.
Method Summary
void | changedUpdate(DocumentEvent e, Shape a, ViewFactory f) Gives notification from the document that attributes were changed in a location that this view is responsible for.
AttributeSet | getAttributes() Fetches the attributes to use when rendering.
int | getBreakWeight(int axis, float pos, float len) Determines how attractive a break opportunity in this view is.
protected StyleSheet | getStyleSheet()
protected void | setPropertiesFromAttributes() Set the cached properties from the attributes.
Methods inherited from class javax.swing.text.LabelView
getBackground, getFont, getFontMetrics, getForeground, isStrikeThrough, isSubscript, isSuperscript, isUnderline, setStrikeThrough, setSubscript, setSuperscript, setUnderline
Methods inherited from class javax.swing.text.GlyphView
breakView, checkPainter, clone, createFragment, getAlignment, getEndOffset, getGlyphPainter, getNextVisualPositionFrom, getPartialSpan, getPreferredSpan, getStartOffset, getTabbedSpan, getTabExpander, getText, insertUpdate, modelToView, paint, removeUpdate, setGlyphPainter, viewToModel
Methods inherited from class javax.swing.text.View
append, forwardUpdate, forwardUpdateToView, getChildAllocation, getContainer, getDocument, getElement, getGraphics, getMaximumSpan, getMinimumSpan, getParent, getResizeWeight, getToolTipText, getView, getViewCount, getViewFactory, getViewIndex, getViewIndex, insert, isVisible, modelToView, modelToView, preferenceChanged, remove, removeAll, replace, setParent, setSize, updateChildren, updateLayout, viewToModel
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Methods inherited from interface javax.swing.text.TabableView
getPartialSpan, getTabbedSpan

Constructor Detail

InlineView

public InlineView(Element elem)
Constructs a new view wrapped on an element.

Parameters:
elem - the element
Method Detail

changedUpdate

public void changedUpdate(DocumentEvent e,
                          Shape a,
                          ViewFactory f)
Gives notification from the document that attributes were changed in a location that this view is responsible for.

Overrides:
changedUpdate in class LabelView
Parameters:
e - the change information from the associated document
a - the current allocation of the view
f - the factory to use to rebuild if the view has children
See Also:
View.changedUpdate(javax.swing.event.DocumentEvent, java.awt.Shape, javax.swing.text.ViewFactory)

getAttributes

public AttributeSet getAttributes()
Fetches the attributes to use when rendering. This is implemented to multiplex the attributes specified in the model with a StyleSheet.

Overrides:
getAttributes in class View

getBreakWeight

public int getBreakWeight(int axis,
                          float pos,
                          float len)
Determines how attractive a break opportunity in this view is. This can be used for determining which view is the most attractive to call breakView on in the process of formatting. A view that represents text that has whitespace in it might be more attractive than a view that has no whitespace, for example. The higher the weight, the more attractive the break. A value equal to or lower than BadBreakWeight should not be considered for a break. A value greater than or equal to ForcedBreakWeight should be broken.

This is implemented to provide the default behavior of returning BadBreakWeight unless the length is greater than the length of the view in which case the entire view represents the fragment. Unless a view has been written to support breaking behavior, it is not attractive to try and break the view. An example of a view that does support breaking is LabelView. An example of a view that uses break weight is ParagraphView.

Overrides:
getBreakWeight in class GlyphView
Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
pos - the potential location of the start of the broken view >= 0. This may be useful for calculating tab positions.
len - specifies the relative length from pos where a potential break is desired >= 0.
Returns:
the weight, which should be a value between ForcedBreakWeight and BadBreakWeight.
See Also:
LabelView, ParagraphView, View.BadBreakWeight, View.GoodBreakWeight, View.ExcellentBreakWeight, View.ForcedBreakWeight

setPropertiesFromAttributes

protected void setPropertiesFromAttributes()
Set the cached properties from the attributes.

Overrides:
setPropertiesFromAttributes in class LabelView

getStyleSheet

protected StyleSheet getStyleSheet()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ListView (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class ListView

java.lang.Object
    extended by javax.swing.text.View
        extended by javax.swing.text.CompositeView
            extended by javax.swing.text.BoxView
                extended by javax.swing.text.html.BlockView
                    extended by javax.swing.text.html.ListView
All Implemented Interfaces:
SwingConstants
public class ListView
extends BlockView

A view implementation to display an html list

Field Summary
Fields inherited from class javax.swing.text.View
BadBreakWeight, ExcellentBreakWeight, ForcedBreakWeight, GoodBreakWeight, X_AXIS, Y_AXIS
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
Constructor Summary
ListView(Element elem)
Creates a new view that represents a list element.
Method Summary
 float getAlignment(int axis)
Calculates the desired shape of the list.
 void paint(Graphics g, Shape allocation)
Renders using the given rendering surface and area on that surface.
protected  void paintChild(Graphics g, Rectangle alloc, int index)
Paints one of the children; called by paint().
protected  void setPropertiesFromAttributes()
Update any cached values that come from attributes.
Methods inherited from class javax.swing.text.html.BlockView
calculateMajorAxisRequirements, calculateMinorAxisRequirements, changedUpdate, getAttributes, getMaximumSpan, getMinimumSpan, getPreferredSpan, getResizeWeight, getStyleSheet, layoutMinorAxis, setParent
Methods inherited from class javax.swing.text.BoxView
baselineLayout, baselineRequirements, childAllocation, flipEastAndWestAtEnds, forwardUpdate, getAxis, getChildAllocation, getHeight, getOffset, getSpan, getViewAtPoint, getWidth, isAfter, isAllocationValid, isBefore, isLayoutValid, layout, layoutChanged, layoutMajorAxis, modelToView, preferenceChanged, replace, setAxis, setSize, viewToModel
Methods inherited from class javax.swing.text.CompositeView
getBottomInset, getInsideAllocation, getLeftInset, getNextEastWestVisualPositionFrom, getNextNorthSouthVisualPositionFrom, getNextVisualPositionFrom, getRightInset, getTopInset, getView, getViewAtPosition, getViewCount, getViewIndex, getViewIndexAtPosition, loadChildren, modelToView, setInsets, setParagraphInsets
Methods inherited from class javax.swing.text.View
append, breakView, createFragment, forwardUpdateToView, getBreakWeight, getContainer, getDocument, getElement, getEndOffset, getGraphics, getParent, getStartOffset, getToolTipText, getViewFactory, getViewIndex, insert, insertUpdate, isVisible, modelToView, remove, removeAll, removeUpdate, updateChildren, updateLayout, viewToModel
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ListView

public ListView(Element elem)
Creates a new view that represents a list element.

Parameters:
elem - the element to create a view for
Method Detail

getAlignment

public float getAlignment(int axis)
Calculates the desired shape of the list.

Overrides:
getAlignment in class BlockView
Parameters:
axis - may be either X_AXIS or Y_AXIS
Returns:
the desired span
See Also:
View.getPreferredSpan(int)

paint

public void paint(Graphics g,
                  Shape allocation)
Renders using the given rendering surface and area on that surface.

Overrides:
paint in class BlockView
Parameters:
g - the rendering surface to use
allocation - the allocated region to render into
See Also:
View.paint(java.awt.Graphics, java.awt.Shape)

paintChild

protected void paintChild(Graphics g,
                          Rectangle alloc,
                          int index)
Paints one of the children; called by paint(). By default that is all it does, but a subclass can use this to paint things relative to the child.

Overrides:
paintChild in class BoxView
Parameters:
g - the graphics context
alloc - the allocated region to render the child into
index - the index of the child

setPropertiesFromAttributes

protected void setPropertiesFromAttributes()
Description copied from class: BlockView
Update any cached values that come from attributes.

Overrides:
setPropertiesFromAttributes in class BlockView
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MinimalHTMLWriter (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class MinimalHTMLWriter

java.lang.Object
    extended by javax.swing.text.AbstractWriter
        extended by javax.swing.text.html.MinimalHTMLWriter
public class MinimalHTMLWriter
extends AbstractWriter

MinimalHTMLWriter is a fallback writer used by the HTMLEditorKit to write out HTML for a document that is a not produced by the EditorKit. The format for the document is:

 <html>
   <head>
     <style>
        <!-- list of named styles
         p.normal {
            font-family: SansSerif;
          margin-height: 0;
          font-size: 14
       }
        -->
      </style>
   </head>
   <body>
    <p style=normal>
        Bold, italic, and underline attributes
        of the run are emitted as HTML tags.
        The remaining attributes are emitted as
        part of the style attribute of a <span> tag.
        The syntax is similar to inline styles.
    </p>
   </body>
 </html>

Field Summary
Fields inherited from class javax.swing.text.AbstractWriter
NEWLINE
Constructor Summary
MinimalHTMLWriter(Writer w, StyledDocument doc)
Creates a new MinimalHTMLWriter.
MinimalHTMLWriter(Writer w, StyledDocument doc, int pos, int len)
Creates a new MinimalHTMLWriter.
Method Summary
protected  void endFontTag()
This is no longer used, instead <span> will be written out.
protected  boolean inFontTag()
Returns true if we are currently in a <font> tag.
protected  boolean isText(Element elem)
Returns true if the element is a text element.
protected  void startFontTag(String style)
This is no longer used, instead <span> will be written out.
protected  void text(Element elem)
Writes out text.
 void write()
Generates HTML output from a StyledDocument.
protected  void writeAttributes(AttributeSet attr)
Writes out all the attributes for the following types: StyleConstants.ParagraphConstants, StyleConstants.CharacterConstants, StyleConstants.FontConstants, StyleConstants.ColorConstants.
protected  void writeBody()
Iterates over the elements in the document and processes elements based on whether they are branch elements or leaf elements.
protected  void writeComponent(Element elem)
Responsible for handling Component Elements; deliberately unimplemented.
protected  void writeContent(Element elem, boolean needsIndenting)
Writes out the attribute set in an HTML-compliant manner.
protected  void writeEndParagraph()
Emits an end tag for a <p> tag.
protected  void writeEndTag(String endTag)
Writes out an end tag appropriately indented.
protected  void writeHeader()
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.
protected  void writeHTMLTags(AttributeSet attr)
Generates bold <b>, italic <i>, and <u> tags for the text based on its attribute settings.
protected  void writeImage(Element elem)
Responsible for handling Icon Elements; deliberately unimplemented.
protected  void writeLeaf(Element elem)
Responsible for writing out other non-text leaf elements.
protected  void writeNonHTMLAttributes(AttributeSet attr)
Writes out the remaining character-level attributes (attributes other than bold, italic, and underline) in an HTML-compliant way.
protected  void writeStartParagraph(Element elem)
Emits the start tag for a paragraph.
protected  void writeStartTag(String tag)
Writes out a start tag appropriately indented.
protected  void writeStyles()
Writes out all the named styles as the content of the <style> tag.
Methods inherited from class javax.swing.text.AbstractWriter
decrIndent, getCanWrapLines, getCurrentLineLength, getDocument, getElementIterator, getEndOffset, getIndentLevel, getIndentSpace, getLineLength, getLineSeparator, getStartOffset, getText, getWriter, incrIndent, indent, inRange, isLineEmpty, output, setCanWrapLines, setCurrentLineLength, setIndentSpace, setLineLength, setLineSeparator, write, write, write, writeLineSeparator
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

MinimalHTMLWriter

public MinimalHTMLWriter(Writer w,
                         StyledDocument doc)
Creates a new MinimalHTMLWriter.

Parameters:
w - Writer
doc - StyledDocument

MinimalHTMLWriter

public MinimalHTMLWriter(Writer w,
                         StyledDocument doc,
                         int pos,
                         int len)
Creates a new MinimalHTMLWriter.

Parameters:
w - Writer
doc - StyledDocument
pos - The location in the document to fetch the content.
len - The amount to write out.
Method Detail

write

public void write()
           throws IOException,
                  BadLocationException
Generates HTML output from a StyledDocument.

Specified by:
write in class AbstractWriter
Throws:
IOException - on any I/O error
BadLocationException - if pos represents an invalid location within the document.

writeAttributes

protected void writeAttributes(AttributeSet attr)
                        throws IOException
Writes out all the attributes for the following types: StyleConstants.ParagraphConstants, StyleConstants.CharacterConstants, StyleConstants.FontConstants, StyleConstants.ColorConstants. The attribute name and value are separated by a colon. Each pair is separated by a semicolon.

Overrides:
writeAttributes in class AbstractWriter
Parameters:
attr - an AttributeSet.
Throws:
IOException - on any I/O error

text

protected void text(Element elem)
             throws IOException,
                    BadLocationException
Writes out text.

Overrides:
text in class AbstractWriter
Parameters:
elem - an Element.
Throws:
IOException - on any I/O error
BadLocationException - if pos represents an invalid location within the document.

writeStartTag

protected void writeStartTag(String tag)
                      throws IOException
Writes out a start tag appropriately indented. Also increments the indent level.

Throws:
IOException - on any I/O error

writeEndTag

protected void writeEndTag(String endTag)
                    throws IOException
Writes out an end tag appropriately indented. Also decrements the indent level.

Throws:
IOException - on any I/O error

writeHeader

protected void writeHeader()
                    throws IOException
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. The content is surrounded by valid HTML comment markers to ensure that the document is viewable in applications/browsers that do not support the tag.

Throws:
IOException - on any I/O error

writeStyles

protected void writeStyles()
                    throws IOException
Writes out all the named styles as the content of the <style> tag.

Throws:
IOException - on any I/O error

writeBody

protected void writeBody()
                  throws IOException,
                         BadLocationException
Iterates over the elements in the document and processes elements based on whether they are branch elements or leaf elements. This method specially handles leaf elements that are text.

Throws:
IOException - on any I/O error
BadLocationException

writeEndParagraph

protected void writeEndParagraph()
                          throws IOException
Emits an end tag for a <p> tag. Before writing out the tag, this method ensures that all other tags that have been opened are appropriately closed off.

Throws:
IOException - on any I/O error

writeStartParagraph

protected void writeStartParagraph(Element elem)
                            throws IOException
Emits the start tag for a paragraph. If the paragraph has a named style associated with it, then this method also generates a class attribute for the <p> tag and sets its value to be the name of the style.

Throws:
IOException - on any I/O error

writeLeaf

protected void writeLeaf(Element elem)
                  throws IOException
Responsible for writing out other non-text leaf elements.

Throws:
IOException - on any I/O error

writeImage

protected void writeImage(Element elem)
                   throws IOException
Responsible for handling Icon Elements; deliberately unimplemented. How to implement this method is an issue of policy. For example, if you're generating an <img> tag, how should you represent the src attribute (the location of the image)? In certain cases it could be a URL, in others it could be read from a stream.

Parameters:
elem - element of type StyleConstants.IconElementName
Throws:
IOException

writeComponent

protected void writeComponent(Element elem)
                       throws IOException
Responsible for handling Component Elements; deliberately unimplemented. How this method is implemented is a matter of policy.

Throws:
IOException

isText

protected boolean isText(Element elem)
Returns true if the element is a text element.

writeContent

protected void writeContent(Element elem,
                            boolean needsIndenting)
                     throws IOException,
                            BadLocationException
Writes out the attribute set in an HTML-compliant manner.

Throws:
IOException - on any I/O error
BadLocationException - if pos represents an invalid location within the document.

writeHTMLTags

protected void writeHTMLTags(AttributeSet attr)
                      throws IOException
Generates bold <b>, italic <i>, and <u> tags for the text based on its attribute settings.

Throws:
IOException - on any I/O error

writeNonHTMLAttributes

protected void writeNonHTMLAttributes(AttributeSet attr)
                               throws IOException
Writes out the remaining character-level attributes (attributes other than bold, italic, and underline) in an HTML-compliant way. Given that attributes such as font family and font size have no direct mapping to HTML tags, a <span> tag is generated and its style attribute is set to contain the list of remaining attributes just like inline styles.

Throws:
IOException - on any I/O error

inFontTag

protected boolean inFontTag()
Returns true if we are currently in a <font> tag.

endFontTag

protected void endFontTag()
                   throws IOException
This is no longer used, instead <span> will be written out.

Writes out an end tag for the <font> tag.

Throws:
IOException - on any I/O error

startFontTag

protected void startFontTag(String style)
                     throws IOException
This is no longer used, instead <span> will be written out.

Writes out a start tag for the <font> tag. Because font tags cannot be nested, this method closes out any enclosing font tag before writing out a new start tag.

Throws:
IOException - on any I/O error
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ObjectView (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class ObjectView

java.lang.Object
    extended by javax.swing.text.View
        extended by javax.swing.text.ComponentView
            extended by javax.swing.text.html.ObjectView
All Implemented Interfaces:
SwingConstants
public class ObjectView
extends ComponentView

Component decorator that implements the view interface for <object> elements.

This view will try to load the class specified by the classid attribute. If possible, the Classloader used to load the associated Document is used. This would typically be the same as the ClassLoader used to load the EditorKit. If the documents ClassLoader is null, Class.forName is used.

If the class can successfully be loaded, an attempt will be made to create an instance of it by calling Class.newInstance. An attempt will be made to narrow the instance to type java.awt.Component to display the object.

This view can also manage a set of parameters with limitations. The parameters to the <object> element are expected to be present on the associated elements attribute set as simple strings. Each bean property will be queried as a key on the AttributeSet, with the expectation that a non-null value (of type String) will be present if there was a parameter specification for the property. Reflection is used to set the parameter. Currently, this is limited to a very simple single parameter of type String.

A simple example html invocation is:

Field Summary
Fields inherited from class javax.swing.text.View
BadBreakWeight, ExcellentBreakWeight, ForcedBreakWeight, GoodBreakWeight, X_AXIS, Y_AXIS
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
Constructor Summary
ObjectView(Element elem)
Creates a new ObjectView object.
Method Summary
protected  Component createComponent()
Create the component.
Methods inherited from class javax.swing.text.ComponentView
getAlignment, getComponent, getMaximumSpan, getMinimumSpan, getPreferredSpan, modelToView, paint, setParent, viewToModel
Methods inherited from class javax.swing.text.View
append, breakView, changedUpdate, createFragment, forwardUpdate, forwardUpdateToView, getAttributes, getBreakWeight, getChildAllocation, getContainer, getDocument, getElement, getEndOffset, getGraphics, getNextVisualPositionFrom, getParent, getResizeWeight, getStartOffset, getToolTipText, getView, getViewCount, getViewFactory, getViewIndex, getViewIndex, insert, insertUpdate, isVisible, modelToView, modelToView, preferenceChanged, remove, removeAll, removeUpdate, replace, setSize, updateChildren, updateLayout, viewToModel
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ObjectView

public ObjectView(Element elem)
Creates a new ObjectView object.

Parameters:
elem - the element to decorate
Method Detail

createComponent

protected Component createComponent()
Create the component. The classid is used as a specification of the classname, which we try to load.

Overrides:
createComponent in class ComponentView
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Option (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class Option

java.lang.Object
    extended by javax.swing.text.html.Option
public class Option
extends Object

Value for the ListModel used to represent <option> elements. This is the object installed as items of the DefaultComboBoxModel used to represent the <select> element.

Constructor Summary
Option(AttributeSet attr)
Creates a new Option object.
Method Summary
AttributeSet | getAttributes() Fetch the attributes associated with this option.
String | getLabel() Fetch the label associated with the option.
String | getValue() Convenience method to return the string associated with the value attribute.
boolean | isSelected() Fetches the selection state associated with this option.
void | setLabel(String label) Sets the label to be used for the option.
protected void | setSelection(boolean state) Sets the selected state.
String | toString() String representation is the label.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

Option

public Option(AttributeSet attr)
Creates a new Option object.

Parameters:
attr - the attributes associated with the option element. The attributes are copied to ensure they won't change.
Method Detail

setLabel

public void setLabel(String label)
Sets the label to be used for the option.

getLabel

public String getLabel()
Fetch the label associated with the option.

getAttributes

public AttributeSet getAttributes()
Fetch the attributes associated with this option.

toString

public String toString()
String representation is the label.

Overrides:
toString in class Object
Returns:
a string representation of the object.

setSelection

protected void setSelection(boolean state)
Sets the selected state.

isSelected

public boolean isSelected()
Fetches the selection state associated with this option.

getValue

public String getValue()
Convenience method to return the string associated with the value attribute. If the value has not been specified, the label will be returned.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


javax.swing.text.html (Java 2 Platform SE v1.4.2)

 javax.swing.text.html
Classes
BlockView
CSS
CSS.Attribute
FormView
HTML
HTML.Attribute
HTML.Tag
HTML.UnknownTag
HTMLDocument
HTMLDocument.Iterator
HTMLEditorKit
HTMLEditorKit.HTMLFactory
HTMLEditorKit.HTMLTextAction
HTMLEditorKit.InsertHTMLTextAction
HTMLEditorKit.LinkController
HTMLEditorKit.Parser
HTMLEditorKit.ParserCallback
HTMLFrameHyperlinkEvent
HTMLWriter
ImageView
InlineView
ListView
MinimalHTMLWriter
ObjectView
Option
ParagraphView
StyleSheet
StyleSheet.BoxPainter
StyleSheet.ListPainter


javax.swing.text.html (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package javax.swing.text.html

Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

See:
Description

Class Summary
BlockView | A view implementation to display a block (as a box) with CSS specifications.
CSS | Defines a set of CSS attributes as a typesafe enumeration.
CSS.Attribute | Definitions to be used as a key on AttributeSet's that might hold CSS attributes.
FormView | Component decorator that implements the view interface for form elements, <input>, <textarea>, and <select>.
HTML | Constants used in the HTMLDocument.
HTML.Attribute | Typesafe enumeration representing an HTML attribute.
HTML.Tag | Typesafe enumeration for an HTML tag.
HTML.UnknownTag |
HTMLDocument | A document that models HTML.
HTMLDocument.Iterator | An iterator to iterate over a particular type of tag.
HTMLEditorKit | The Swing JEditorPane text component supports different kinds of content via a plug-in mechanism called an EditorKit.
HTMLEditorKit.HTMLFactory | A factory to build views for HTML.
HTMLEditorKit.HTMLTextAction | An abstract Action providing some convenience methods that may be useful in inserting HTML into an existing document.
HTMLEditorKit.InsertHTMLTextAction | InsertHTMLTextAction can be used to insert an arbitrary string of HTML into an existing HTML document.
HTMLEditorKit.LinkController | Class to watch the associated component and fire hyperlink events on it when appropriate.
HTMLEditorKit.Parser | Interface to be supported by the parser.
HTMLEditorKit.ParserCallback | The result of parsing drives these callback methods.
HTMLFrameHyperlinkEvent | HTMLFrameHyperlinkEvent is used to notify interested parties that link was activated in a frame.
HTMLWriter | This is a writer for HTMLDocuments.
ImageView | View of an Image, intended to support the HTML <IMG> tag.
InlineView | Displays the inline element styles based upon css attributes.
ListView | A view implementation to display an html list
MinimalHTMLWriter | MinimalHTMLWriter is a fallback writer used by the HTMLEditorKit to write out HTML for a document that is a not produced by the EditorKit.
ObjectView | Component decorator that implements the view interface for <object> elements.
Option | Value for the ListModel used to represent <option> elements.
ParagraphView | Displays the a paragraph, and uses css attributes for its configuration.
StyleSheet | Support for defining the visual characteristics of HTML views being rendered.
StyleSheet.BoxPainter | Class to carry out some of the duties of CSS formatting.
StyleSheet.ListPainter | Class to carry out some of the duties of CSS list formatting.

Package javax.swing.text.html Description

Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Note: Most of the Swing API is not thread safe. For details, see Threads and Swing, a section in The Java Tutorial.

Package Specification

  • HTML 3.2 Reference Specification - The HTML specification on which HTMLEditorKit is based.

Since:
1.2
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


javax.swing.text.html Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package javax.swing.text.html

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class javax.swing.AbstractAction (implements javax.swing.Action, java.lang.Cloneable, java.io.Serializable)
      • class javax.swing.text.TextAction
        • class javax.swing.text.StyledEditorKit.StyledTextAction
          • class javax.swing.text.html.HTMLEditorKit.HTMLTextAction
            • class javax.swing.text.html.HTMLEditorKit.InsertHTMLTextAction
    • class javax.swing.text.AbstractDocument (implements javax.swing.text.Document, java.io.Serializable)
      • class javax.swing.text.DefaultStyledDocument (implements javax.swing.text.StyledDocument)
        • class javax.swing.text.html.HTMLDocument
    • class javax.swing.text.AbstractDocument.AbstractElement (implements javax.swing.text.Element, javax.swing.text.MutableAttributeSet, java.io.Serializable, javax.swing.tree.TreeNode)
      • class javax.swing.text.AbstractDocument.BranchElement
        • class javax.swing.text.html.HTMLDocument.BlockElement
      • class javax.swing.text.AbstractDocument.LeafElement
        • class javax.swing.text.html.HTMLDocument.RunElement
    • class javax.swing.text.AbstractWriter
      • class javax.swing.text.html.HTMLWriter
      • class javax.swing.text.html.MinimalHTMLWriter
    • class javax.swing.text.html.CSS (implements java.io.Serializable)
    • class javax.swing.text.html.CSS.Attribute
    • class javax.swing.text.EditorKit (implements java.lang.Cloneable, java.io.Serializable)
      • class javax.swing.text.DefaultEditorKit
        • class javax.swing.text.StyledEditorKit
          • class javax.swing.text.html.HTMLEditorKit (implements javax.accessibility.Accessible)
    • class java.util.EventObject (implements java.io.Serializable)
      • class javax.swing.event.HyperlinkEvent
        • class javax.swing.text.html.HTMLFrameHyperlinkEvent
    • class javax.swing.text.html.HTML
    • class javax.swing.text.html.HTML.Attribute
    • class javax.swing.text.html.HTML.Tag
      • class javax.swing.text.html.HTML.UnknownTag (implements java.io.Serializable)
    • class javax.swing.text.html.HTMLDocument.HTMLReader.TagAction
      • class javax.swing.text.html.HTMLDocument.HTMLReader.BlockAction
        • class javax.swing.text.html.HTMLDocument.HTMLReader.ParagraphAction
        • class javax.swing.text.html.HTMLDocument.HTMLReader.PreAction
      • class javax.swing.text.html.HTMLDocument.HTMLReader.CharacterAction
      • class javax.swing.text.html.HTMLDocument.HTMLReader.HiddenAction
      • class javax.swing.text.html.HTMLDocument.HTMLReader.IsindexAction
      • class javax.swing.text.html.HTMLDocument.HTMLReader.SpecialAction
        • class javax.swing.text.html.HTMLDocument.HTMLReader.FormAction
    • class javax.swing.text.html.HTMLDocument.Iterator
    • class javax.swing.text.html.HTMLEditorKit.HTMLFactory (implements javax.swing.text.ViewFactory)
    • class javax.swing.text.html.HTMLEditorKit.Parser
    • class javax.swing.text.html.HTMLEditorKit.ParserCallback
      • class javax.swing.text.html.HTMLDocument.HTMLReader
    • class java.awt.event.MouseAdapter (implements java.awt.event.MouseListener)
      • class javax.swing.text.html.FormView.MouseEventListener
      • class javax.swing.text.html.HTMLEditorKit.LinkController (implements java.awt.event.MouseMotionListener, java.io.Serializable)
    • class javax.swing.text.html.Option
    • class javax.swing.text.StyleContext (implements javax.swing.text.AbstractDocument.AttributeContext, java.io.Serializable)
      • class javax.swing.text.html.StyleSheet
    • class javax.swing.text.html.StyleSheet.BoxPainter (implements java.io.Serializable)
    • class javax.swing.text.html.StyleSheet.ListPainter (implements java.io.Serializable)
    • class javax.swing.text.View (implements javax.swing.SwingConstants)
      • class javax.swing.text.ComponentView
        • class javax.swing.text.html.FormView (implements java.awt.event.ActionListener)
        • class javax.swing.text.html.ObjectView
      • class javax.swing.text.CompositeView
        • class javax.swing.text.BoxView
          • class javax.swing.text.html.BlockView
            • class javax.swing.text.html.ListView
          • class javax.swing.text.FlowView
            • class javax.swing.text.ParagraphView (implements javax.swing.text.TabExpander)
              • class javax.swing.text.html.ParagraphView
      • class javax.swing.text.GlyphView (implements java.lang.Cloneable, javax.swing.text.TabableView)
        • class javax.swing.text.LabelView (implements javax.swing.text.TabableView)
          • class javax.swing.text.html.InlineView
      • class javax.swing.text.html.ImageView
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package javax.swing.text.html (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
javax.swing.text.html

Packages that use javax.swing.text.html
javax.swing.text.html | Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.
javax.swing.text.html.parser | Provides the default HTML parser, along with support classes.

Classes in javax.swing.text.html used by javax.swing.text.html
BlockView
A view implementation to display a block (as a box) with CSS specifications.
CSS.Attribute
Definitions to be used as a key on AttributeSet's that might hold CSS attributes.
HTML.Attribute
Typesafe enumeration representing an HTML attribute.
HTML.Tag
Typesafe enumeration for an HTML tag.
HTMLDocument
A document that models HTML.
HTMLDocument.HTMLReader.BlockAction
HTMLDocument.HTMLReader.SpecialAction
HTMLDocument.HTMLReader.TagAction
An action to be performed in response to parsing a tag.
HTMLDocument.Iterator
An iterator to iterate over a particular type of tag.
HTMLEditorKit
The Swing JEditorPane text component supports different kinds of content via a plug-in mechanism called an EditorKit.
HTMLEditorKit.HTMLTextAction
An abstract Action providing some convenience methods that may be useful in inserting HTML into an existing document.
HTMLEditorKit.Parser
Interface to be supported by the parser.
HTMLEditorKit.ParserCallback
The result of parsing drives these callback methods.
HTMLFrameHyperlinkEvent
HTMLFrameHyperlinkEvent is used to notify interested parties that link was activated in a frame.
Option
Value for the ListModel used to represent <option> elements.
StyleSheet
Support for defining the visual characteristics of HTML views being rendered.
StyleSheet.BoxPainter
Class to carry out some of the duties of CSS formatting.
StyleSheet.ListPainter
Class to carry out some of the duties of CSS list formatting.

Classes in javax.swing.text.html used by javax.swing.text.html.parser
HTML.Tag
Typesafe enumeration for an HTML tag.
HTMLEditorKit.Parser
Interface to be supported by the parser.
HTMLEditorKit.ParserCallback
The result of parsing drives these callback methods.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


ParagraphView (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class ParagraphView

java.lang.Object
    extended by javax.swing.text.View
        extended by javax.swing.text.CompositeView
            extended by javax.swing.text.BoxView
                extended by javax.swing.text.FlowView
                    extended by javax.swing.text.ParagraphView
                        extended by javax.swing.text.html.ParagraphView
All Implemented Interfaces:
SwingConstants, TabExpander
public class ParagraphView
extends ParagraphView

Displays the a paragraph, and uses css attributes for its configuration.

Nested Class Summary
Nested classes inherited from class javax.swing.text.FlowView
FlowView.FlowStrategy
Field Summary
Fields inherited from class javax.swing.text.ParagraphView
firstLineIndent
Fields inherited from class javax.swing.text.FlowView
layoutPool, layoutSpan, strategy
Fields inherited from class javax.swing.text.View
BadBreakWeight, ExcellentBreakWeight, ForcedBreakWeight, GoodBreakWeight, X_AXIS, Y_AXIS
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
Constructor Summary
ParagraphView(Element elem)
Constructs a ParagraphView for the given element.
Method Summary
protected SizeRequirements | calculateMinorAxisRequirements(int axis, SizeRequirements r) Calculate the needs for the paragraph along the minor axis.
AttributeSet | getAttributes() Fetches the attributes to use when rendering.
float | getMaximumSpan(int axis) Determines the maximum span for this view along an axis.
float | getMinimumSpan(int axis) Determines the minimum span for this view along an axis.
float | getPreferredSpan(int axis) Determines the preferred span for this view.
protected StyleSheet | getStyleSheet()
boolean | isVisible() Indicates whether or not this view should be displayed.
void | paint(Graphics g, Shape a) Renders using the given rendering surface and area on that surface.
void | setParent(View parent) Establishes the parent view for this view.
protected void | setPropertiesFromAttributes() Sets up the paragraph from css attributes instead of the values found in StyleConstants (i.e.
Methods inherited from class javax.swing.text.ParagraphView
adjustRow, breakView, changedUpdate, createRow, findOffsetToCharactersInString, flipEastAndWestAtEnds, getAlignment, getBreakWeight, getClosestPositionTo, getFlowSpan, getFlowStart, getLayoutView, getLayoutViewCount, getNextNorthSouthVisualPositionFrom, getPartialSize, getTabBase, getTabSet, nextTabStop, setFirstLineIndent, setJustification, setLineSpacing
Methods inherited from class javax.swing.text.FlowView
getFlowAxis, getViewIndexAtPosition, insertUpdate, layout, loadChildren, removeUpdate
Methods inherited from class javax.swing.text.BoxView
baselineLayout, baselineRequirements, calculateMajorAxisRequirements, childAllocation, forwardUpdate, getAxis, getChildAllocation, getHeight, getOffset, getResizeWeight, getSpan, getViewAtPoint, getWidth, isAfter, isAllocationValid, isBefore, isLayoutValid, layoutChanged, layoutMajorAxis, layoutMinorAxis, modelToView, paintChild, preferenceChanged, replace, setAxis, setSize, viewToModel
Methods inherited from class javax.swing.text.CompositeView
getBottomInset, getInsideAllocation, getLeftInset, getNextEastWestVisualPositionFrom, getNextVisualPositionFrom, getRightInset, getTopInset, getView, getViewAtPosition, getViewCount, getViewIndex, modelToView, setInsets, setParagraphInsets
Methods inherited from class javax.swing.text.View
append, breakView, createFragment, forwardUpdateToView, getBreakWeight, getContainer, getDocument, getElement, getEndOffset, getGraphics, getParent, getStartOffset, getToolTipText, getViewFactory, getViewIndex, insert, modelToView, remove, removeAll, updateChildren, updateLayout, viewToModel
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ParagraphView

public ParagraphView(Element elem)
Constructs a ParagraphView for the given element.

Parameters:
elem - the element that this view is responsible for
Method Detail

setParent

public void setParent(View parent)
Establishes the parent view for this view. This is guaranteed to be called before any other methods if the parent view is functioning properly.

This is implemented to forward to the superclass as well as call the setPropertiesFromAttributes method to set the paragraph properties from the css attributes. The call is made at this time to ensure the ability to resolve upward through the parents view attributes.

Overrides:
setParent in class CompositeView
Parameters:
parent - the new parent, or null if the view is being removed from a parent it was previously added to

getAttributes

public AttributeSet getAttributes()
Fetches the attributes to use when rendering. This is implemented to multiplex the attributes specified in the model with a StyleSheet.

Overrides:
getAttributes in class View

setPropertiesFromAttributes

protected void setPropertiesFromAttributes()
Sets up the paragraph from css attributes instead of the values found in StyleConstants (i.e. which are used by the superclass). Since

Overrides:
setPropertiesFromAttributes in class ParagraphView

getStyleSheet

protected StyleSheet getStyleSheet()

calculateMinorAxisRequirements

protected SizeRequirements calculateMinorAxisRequirements(int axis,
                                                          SizeRequirements r)
Calculate the needs for the paragraph along the minor axis. This implemented to use the requirements of the superclass, modified slightly to set a minimum span allowed. Typical html rendering doesn't let the view size shrink smaller than the length of the longest word.

Overrides:
calculateMinorAxisRequirements in class FlowView

isVisible

public boolean isVisible()
Indicates whether or not this view should be displayed. If none of the children wish to be displayed and the only visible child is the break that ends the paragraph, the paragraph will not be considered visible. Otherwise, it will be considered visible and return true.

Overrides:
isVisible in class View
Returns:
true if the paragraph should be displayed

paint

public void paint(Graphics g,
                  Shape a)
Renders using the given rendering surface and area on that surface. This is implemented to delgate to the superclass after stashing the base coordinate for tab calculations.

Overrides:
paint in class ParagraphView
Parameters:
g - the rendering surface to use
a - the allocated region to render into
See Also:
View.paint(java.awt.Graphics, java.awt.Shape)

getPreferredSpan

public float getPreferredSpan(int axis)
Determines the preferred span for this view. Returns 0 if the view is not visible, otherwise it calls the superclass method to get the preferred span. axis.

Overrides:
getPreferredSpan in class BoxView
Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
Returns:
the span the view would like to be rendered into; typically the view is told to render into the span that is returned, although there is no guarantee; the parent may choose to resize or break the view
See Also:
BoxView.getPreferredSpan(int)

getMinimumSpan

public float getMinimumSpan(int axis)
Determines the minimum span for this view along an axis. Returns 0 if the view is not visible, otherwise it calls the superclass method to get the minimum span.

Overrides:
getMinimumSpan in class BoxView
Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
Returns:
the minimum span the view can be rendered into
See Also:
BoxView.getMinimumSpan(int)

getMaximumSpan

public float getMaximumSpan(int axis)
Determines the maximum span for this view along an axis. Returns 0 if the view is not visible, otherwise it calls the superclass method ot get the maximum span.

Overrides:
getMaximumSpan in class BoxView
Parameters:
axis - may be either View.X_AXIS or View.Y_AXIS
Returns:
the maximum span the view can be rendered into
See Also:
BoxView.getMaximumSpan(int)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


StyleSheet (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class StyleSheet

java.lang.Object
    extended by javax.swing.text.StyleContext
        extended by javax.swing.text.html.StyleSheet
All Implemented Interfaces:
AbstractDocument.AttributeContext, Serializable
public class StyleSheet
extends StyleContext

Support for defining the visual characteristics of HTML views being rendered. The StyleSheet is used to translate the HTML model into visual characteristics. This enables views to be customized by a look-and-feel, multiple views over the same model can be rendered differently, etc. This can be thought of as a CSS rule repository. The key for CSS attributes is an object of type CSS.Attribute. The type of the value is up to the StyleSheet implementation, but the toString method is required to return a string representation of CSS value.

The primary entry point for HTML View implementations to get their attributes is the getViewAttributes method. This should be implemented to establish the desired policy used to associate attributes with the view. Each HTMLEditorKit (i.e. and therefore each associated JEditorPane) can have its own StyleSheet, but by default one sheet will be shared by all of the HTMLEditorKit instances. HTMLDocument instance can also have a StyleSheet, which holds the document-specific CSS specifications.

In order for Views to store less state and therefore be more lightweight, the StyleSheet can act as a factory for painters that handle some of the rendering tasks. This allows implementations to determine what they want to cache and have the sharing potentially at the level that a selector is common to multiple views. Since the StyleSheet may be used by views over multiple documents and typically the HTML attributes don't effect the selector being used, the potential for sharing is significant.

The rules are stored as named styles, and other information is stored to translate the context of an element to a rule quickly. The following code fragment will display the named styles, and therefore the CSS rules contained.

   import java.util.*;
   import javax.swing.text.*;
   import javax.swing.text.html.*;

   public class ShowStyles {

       public static void main(String[] args) {
       HTMLEditorKit kit = new HTMLEditorKit();
       HTMLDocument doc = (HTMLDocument) kit.createDefaultDocument();
       StyleSheet styles = doc.getStyleSheet();

       Enumeration rules = styles.getStyleNames();
       while (rules.hasMoreElements()) {
           String name = (String) rules.nextElement();
           Style rule = styles.getStyle(name);
           System.out.println(rule.toString());
       }
       System.exit(0);
       }
   }

The semantics for when a CSS style should overide visual attributes defined by an element are not well defined. For example, the html <body bgcolor=red> makes the body have a red background. But if the html file also contains the CSS rule body { background: blue } it becomes less clear as to what color the background of the body should be. The current implemention gives visual attributes defined in the element the highest precedence, that is they are always checked before any styles. Therefore, in the previous example the background would have a red color as the body element defines the background color to be red.

As already mentioned this supports CSS. We don't support the full CSS spec. Refer to the javadoc of the CSS class to see what properties we support. The two major CSS parsing related concepts we do not currently support are pseudo selectors, such as A:link { color: red }, and the important modifier.

Note: This implementation is currently incomplete. It can be replaced with alternative implementations that are complete. Future versions of this class will provide better CSS support.

Nested Class Summary
static class | StyleSheet.BoxPainter Class to carry out some of the duties of CSS formatting.
static class | StyleSheet.ListPainter Class to carry out some of the duties of CSS list formatting.
Nested classes inherited from class javax.swing.text.StyleContext
StyleContext.NamedStyle, StyleContext.SmallAttributeSet
Field Summary
Fields inherited from class javax.swing.text.StyleContext
DEFAULT_STYLE
Constructor Summary
StyleSheet()
Construct a StyleSheet
Method Summary
AttributeSet | addAttribute(AttributeSet old, Object key, Object value) Adds an attribute to the given set, and returns the new representative set.
AttributeSet | addAttributes(AttributeSet old, AttributeSet attr) Adds a set of attributes to the element.
void | addCSSAttribute(MutableAttributeSet attr, CSS.Attribute key, String value) Adds a CSS attribute to the given set.
boolean | addCSSAttributeFromHTML(MutableAttributeSet attr, CSS.Attribute key, String value) Adds a CSS attribute to the given set.
void | addRule(String rule) Adds a set of rules to the sheet.
void | addStyleSheet(StyleSheet ss) Adds the rules from the StyleSheet ss to those of the receiver.
protected MutableAttributeSet | createLargeAttributeSet(AttributeSet a) Creates a large set of attributes that should trade off space for time.
protected StyleContext.SmallAttributeSet | createSmallAttributeSet(AttributeSet a) Creates a compact set of attributes that might be shared.
Color | getBackground(AttributeSet a) Takes a set of attributes and turn it into a background color specification.
URL | getBase() Returns the base.
StyleSheet.BoxPainter | getBoxPainter(AttributeSet a) Fetches the box formatter to use for the given set of CSS attributes.
AttributeSet | getDeclaration(String decl) Translates a CSS declaration to an AttributeSet that represents the CSS declaration.
Font | getFont(AttributeSet a) Fetches the font to use for the given set of attributes.
Color | getForeground(AttributeSet a) Takes a set of attributes and turn it into a foreground color specification.
static int | getIndexOfSize(float pt)
StyleSheet.ListPainter | getListPainter(AttributeSet a) Fetches the list formatter to use for the given set of CSS attributes.
float | getPointSize(int index) Returns the point size, given a size index.
float | getPointSize(String size) Given a string such as "+2", "-2", or "2", returns a point size value.
Style | getRule(HTML.Tag t, Element e) Fetches the style to use to render the given type of HTML tag.
Style | getRule(String selector) Fetches the rule that best matches the selector given in string form.
StyleSheet[] | getStyleSheets() Returns an array of the linked StyleSheets.
AttributeSet | getViewAttributes(View v) Fetches a set of attributes to use in the view for displaying.
void | importStyleSheet(URL url) Imports a style sheet from url.
void | loadRules(Reader in, URL ref) Loads a set of rules that have been specified in terms of CSS1 grammar.
AttributeSet | removeAttribute(AttributeSet old, Object key) Removes an attribute from the set.
AttributeSet | removeAttributes(AttributeSet old, AttributeSet attrs) Removes a set of attributes.
AttributeSet | removeAttributes(AttributeSet old, Enumeration names) Removes a set of attributes for the element.
void | removeStyle(String nm) Removes a named style previously added to the document.
void | removeStyleSheet(StyleSheet ss) Removes the StyleSheet ss from those of the receiver.
void | setBase(URL base) Sets the base.
void | setBaseFontSize(int sz) Sets the base font size, with valid values between 1 and 7.
void | setBaseFontSize(String size) Sets the base font size from the passed in String.
Color | stringToColor(String string) Converts a color string such as "RED" or "#NNNNNN" to a Color.
AttributeSet | translateHTMLToCSS(AttributeSet htmlAttrSet) Converts a set of HTML attributes to an equivalent set of CSS attributes.
Methods inherited from class javax.swing.text.StyleContext
addChangeListener, addStyle, getChangeListeners, getCompressionThreshold, getDefaultStyleContext, getEmptySet, getFont, getFontMetrics, getStaticAttribute, getStaticAttributeKey, getStyle, getStyleNames, readAttributes, readAttributeSet, reclaim, registerStaticAttributeKey, removeChangeListener, toString, writeAttributes, writeAttributeSet
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

StyleSheet

public StyleSheet()
Construct a StyleSheet

Method Detail

getRule

public Style getRule(HTML.Tag t,
                     Element e)
Fetches the style to use to render the given type of HTML tag. The element given is representing the tag and can be used to determine the nesting for situations where the attributes will differ if nesting inside of elements.

Parameters:
t - the type to translate to visual attributes
e - the element representing the tag; the element can be used to determine the nesting for situations where the attributes will differ if nested inside of other elements
Returns:
the set of CSS attributes to use to render the tag

getRule

public Style getRule(String selector)
Fetches the rule that best matches the selector given in string form. Where selector is a space separated String of the element names. For example, selector might be 'html body tr td''

The attributes of the returned Style will change as rules are added and removed. That is if you to ask for a rule with a selector "table p" and a new rule was added with a selector of "p" the returned Style would include the new attributes from the rule "p".

addRule

public void addRule(String rule)
Adds a set of rules to the sheet. The rules are expected to be in valid CSS format. Typically this would be called as a result of parsing a <style> tag.

getDeclaration

public AttributeSet getDeclaration(String decl)
Translates a CSS declaration to an AttributeSet that represents the CSS declaration. Typically this would be called as a result of encountering an HTML style attribute.

loadRules

public void loadRules(Reader in,
                      URL ref)
               throws IOException
Loads a set of rules that have been specified in terms of CSS1 grammar. If there are collisions with existing rules, the newly specified rule will win.

Parameters:
in - the stream to read the CSS grammar from
ref - the reference URL. This value represents the location of the stream and may be null. All relative URLs specified in the stream will be based upon this parameter.
Throws:
IOException

getViewAttributes

public AttributeSet getViewAttributes(View v)
Fetches a set of attributes to use in the view for displaying. This is basically a set of attributes that can be used for View.getAttributes.

removeStyle

public void removeStyle(String nm)
Removes a named style previously added to the document.

Overrides:
removeStyle in class StyleContext
Parameters:
nm - the name of the style to remove

addStyleSheet

public void addStyleSheet(StyleSheet ss)
Adds the rules from the StyleSheet ss to those of the receiver. ss's rules will override the rules of any previously added style sheets. An added StyleSheet will never override the rules of the receiving style sheet.

Since:
1.3

removeStyleSheet

public void removeStyleSheet(StyleSheet ss)
Removes the StyleSheet ss from those of the receiver.

Since:
1.3

getStyleSheets

public StyleSheet[] getStyleSheets()
Returns an array of the linked StyleSheets. Will return null if there are no linked StyleSheets.

Since:
1.3

importStyleSheet

public void importStyleSheet(URL url)
Imports a style sheet from url. The resulting rules are directly added to the receiver. If you do not want the rules to become part of the receiver, create a new StyleSheet and use addStyleSheet to link it in.

Since:
1.3

setBase

public void setBase(URL base)
Sets the base. All import statements that are relative, will be relative to base.

Since:
1.3

getBase

public URL getBase()
Returns the base.

Since:
1.3

addCSSAttribute

public void addCSSAttribute(MutableAttributeSet attr,
                            CSS.Attribute key,
                            String value)
Adds a CSS attribute to the given set.

Since:
1.3

addCSSAttributeFromHTML

public boolean addCSSAttributeFromHTML(MutableAttributeSet attr,
                                       CSS.Attribute key,
                                       String value)
Adds a CSS attribute to the given set.

Since:
1.3

translateHTMLToCSS

public AttributeSet translateHTMLToCSS(AttributeSet htmlAttrSet)
Converts a set of HTML attributes to an equivalent set of CSS attributes.

Parameters:
htmlAttrSet - AttributeSet containing the HTML attributes.

addAttribute

public AttributeSet addAttribute(AttributeSet old,
                                 Object key,
                                 Object value)
Adds an attribute to the given set, and returns the new representative set. This is reimplemented to convert StyleConstant attributes to CSS prior to forwarding to the superclass behavior. The StyleConstants attribute has no corresponding CSS entry, the StyleConstants attribute is stored (but will likely be unused).

Specified by:
addAttribute in interface AbstractDocument.AttributeContext
Overrides:
addAttribute in class StyleContext
Parameters:
old - the old attribute set
key - the non-null attribute key
value - the attribute value
Returns:
the updated attribute set
See Also:
MutableAttributeSet.addAttribute(java.lang.Object, java.lang.Object)

addAttributes

public AttributeSet addAttributes(AttributeSet old,
                                  AttributeSet attr)
Adds a set of attributes to the element. If any of these attributes are StyleConstants attributes, they will be converted to CSS prior to forwarding to the superclass behavior.

Specified by:
addAttributes in interface AbstractDocument.AttributeContext
Overrides:
addAttributes in class StyleContext
Parameters:
old - the old attribute set
attr - the attributes to add
Returns:
the updated attribute set
See Also:
MutableAttributeSet.addAttribute(java.lang.Object, java.lang.Object)

removeAttribute

public AttributeSet removeAttribute(AttributeSet old,
                                    Object key)
Removes an attribute from the set. If the attribute is a StyleConstants attribute, the request will be converted to a CSS attribute prior to forwarding to the superclass behavior.

Specified by:
removeAttribute in interface AbstractDocument.AttributeContext
Overrides:
removeAttribute in class StyleContext
Parameters:
old - the old set of attributes
key - the non-null attribute name
Returns:
the updated attribute set
See Also:
MutableAttributeSet.removeAttribute(java.lang.Object)

removeAttributes

public AttributeSet removeAttributes(AttributeSet old,
                                     Enumeration names)
Removes a set of attributes for the element. If any of the attributes is a StyleConstants attribute, the request will be converted to a CSS attribute prior to forwarding to the superclass behavior.

Specified by:
removeAttributes in interface AbstractDocument.AttributeContext
Overrides:
removeAttributes in class StyleContext
Parameters:
old - the old attribute set
names - the attribute names
Returns:
the updated attribute set
See Also:
MutableAttributeSet.removeAttributes(java.util.Enumeration)

removeAttributes

public AttributeSet removeAttributes(AttributeSet old,
                                     AttributeSet attrs)
Removes a set of attributes. If any of the attributes is a StyleConstants attribute, the request will be converted to a CSS attribute prior to forwarding to the superclass behavior.

Specified by:
removeAttributes in interface AbstractDocument.AttributeContext
Overrides:
removeAttributes in class StyleContext
Parameters:
old - the old attribute set
attrs - the attributes
Returns:
the updated attribute set
See Also:
MutableAttributeSet.removeAttributes(java.util.Enumeration)

createSmallAttributeSet

protected StyleContext.SmallAttributeSet createSmallAttributeSet(AttributeSet a)
Creates a compact set of attributes that might be shared. This is a hook for subclasses that want to alter the behavior of SmallAttributeSet. This can be reimplemented to return an AttributeSet that provides some sort of attribute conversion.

Overrides:
createSmallAttributeSet in class StyleContext
Parameters:
a - The set of attributes to be represented in the the compact form.

createLargeAttributeSet

protected MutableAttributeSet createLargeAttributeSet(AttributeSet a)
Creates a large set of attributes that should trade off space for time. This set will not be shared. This is a hook for subclasses that want to alter the behavior of the larger attribute storage format (which is SimpleAttributeSet by default). This can be reimplemented to return a MutableAttributeSet that provides some sort of attribute conversion.

Overrides:
createLargeAttributeSet in class StyleContext
Parameters:
a - The set of attributes to be represented in the the larger form.

getFont

public Font getFont(AttributeSet a)
Fetches the font to use for the given set of attributes.

Overrides:
getFont in class StyleContext
Parameters:
a - the attribute set
Returns:
the font

getForeground

public Color getForeground(AttributeSet a)
Takes a set of attributes and turn it into a foreground color specification. This might be used to specify things like brighter, more hue, etc.

Overrides:
getForeground in class StyleContext
Parameters:
a - the set of attributes
Returns:
the color

getBackground

public Color getBackground(AttributeSet a)
Takes a set of attributes and turn it into a background color specification. This might be used to specify things like brighter, more hue, etc.

Overrides:
getBackground in class StyleContext
Parameters:
a - the set of attributes
Returns:
the color

getBoxPainter

public StyleSheet.BoxPainter getBoxPainter(AttributeSet a)
Fetches the box formatter to use for the given set of CSS attributes.

getListPainter

public StyleSheet.ListPainter getListPainter(AttributeSet a)
Fetches the list formatter to use for the given set of CSS attributes.

setBaseFontSize

public void setBaseFontSize(int sz)
Sets the base font size, with valid values between 1 and 7.

setBaseFontSize

public void setBaseFontSize(String size)
Sets the base font size from the passed in String. The string can either identify a specific font size, with legal values between 1 and 7, or identifiy a relative font size such as +1 or -2.

getIndexOfSize

public static int getIndexOfSize(float pt)

getPointSize

public float getPointSize(int index)
Returns the point size, given a size index.

getPointSize

public float getPointSize(String size)
Given a string such as "+2", "-2", or "2", returns a point size value.

stringToColor

public Color stringToColor(String string)
Converts a color string such as "RED" or "#NNNNNN" to a Color. Note: This will only convert the HTML3.2 color strings or a string of length 7; otherwise, it will return null.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


StyleSheet.BoxPainter (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class StyleSheet.BoxPainter

java.lang.Object
    extended by javax.swing.text.html.StyleSheet.BoxPainter
All Implemented Interfaces:
Serializable
Enclosing class:
StyleSheet
public static class StyleSheet.BoxPainter
extends Object
implements Serializable

Class to carry out some of the duties of CSS formatting. Implementations of this class enable views to present the CSS formatting while not knowing anything about how the CSS values are being cached.

As a delegate of Views, this object is responsible for the insets of a View and making sure the background is maintained according to the CSS attributes.

Method Summary
float | getInset(int side, View v) Fetches the inset needed on a given side to account for the margin, border, and padding.
void | paint(Graphics g, float x, float y, float w, float h, View v) Paints the CSS box according to the attributes given.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Method Detail

getInset

public float getInset(int side,
                      View v)
Fetches the inset needed on a given side to account for the margin, border, and padding.

Parameters:
side - The size of the box to fetch the inset for. This can be View.TOP, View.LEFT, View.BOTTOM, or View.RIGHT.
v - the view making the request. This is used to get the AttributeSet, and may be used to resolve percentage arguments.
Throws:
IllegalArgumentException - for an invalid direction

paint

public void paint(Graphics g,
                  float x,
                  float y,
                  float w,
                  float h,
                  View v)
Paints the CSS box according to the attributes given. This should paint the border, padding, and background.

Parameters:
g - the rendering surface.
x - the x coordinate of the allocated area to render into.
y - the y coordinate of the allocated area to render into.
w - the width of the allocated area to render into.
h - the height of the allocated area to render into.
v - the view making the request. This is used to get the AttributeSet, and may be used to resolve percentage arguments.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


StyleSheet.ListPainter (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html
Class StyleSheet.ListPainter

java.lang.Object
    extended by javax.swing.text.html.StyleSheet.ListPainter
All Implemented Interfaces:
Serializable
Enclosing class:
StyleSheet
public static class StyleSheet.ListPainter
extends Object
implements Serializable

Class to carry out some of the duties of CSS list formatting. Implementations of this class enable views to present the CSS formatting while not knowing anything about how the CSS values are being cached.

Method Summary
 void paint(Graphics g, float x, float y, float w, float h, View v, int item)
Paints the CSS list decoration according to the attributes given.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Method Detail

paint

public void paint(Graphics g,
                  float x,
                  float y,
                  float w,
                  float h,
                  View v,
                  int item)
Paints the CSS list decoration according to the attributes given.

Parameters:
g - the rendering surface.
x - the x coordinate of the list item allocation
y - the y coordinate of the list item allocation
w - the width of the list item allocation
h - the height of the list item allocation
v - the allocated area to paint into.
item - which list item is being painted. This is a number greater than or equal to 0.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Uses of Class javax.swing.text.html.BlockView (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.BlockView

Packages that use BlockView
javax.swing.text.html Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of BlockView in javax.swing.text.html

Subclasses of BlockView in javax.swing.text.html
 class ListView
A view implementation to display an html list

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.CSS (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.CSS

No usage of javax.swing.text.html.CSS

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.CSS.Attribute (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.CSS.Attribute

Packages that use CSS.Attribute
javax.swing.text.html Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of CSS.Attribute in javax.swing.text.html

Fields in javax.swing.text.html declared as CSS.Attribute
static CSS.Attribute | CSS.Attribute.BACKGROUND
static CSS.Attribute | CSS.Attribute.BACKGROUND_ATTACHMENT
static CSS.Attribute | CSS.Attribute.BACKGROUND_COLOR
static CSS.Attribute | CSS.Attribute.BACKGROUND_IMAGE
static CSS.Attribute | CSS.Attribute.BACKGROUND_POSITION
static CSS.Attribute | CSS.Attribute.BACKGROUND_REPEAT
static CSS.Attribute | CSS.Attribute.BORDER
static CSS.Attribute | CSS.Attribute.BORDER_BOTTOM
static CSS.Attribute | CSS.Attribute.BORDER_BOTTOM_WIDTH
static CSS.Attribute | CSS.Attribute.BORDER_COLOR
static CSS.Attribute | CSS.Attribute.BORDER_LEFT
static CSS.Attribute | CSS.Attribute.BORDER_LEFT_WIDTH
static CSS.Attribute | CSS.Attribute.BORDER_RIGHT
static CSS.Attribute | CSS.Attribute.BORDER_RIGHT_WIDTH
static CSS.Attribute | CSS.Attribute.BORDER_STYLE
static CSS.Attribute | CSS.Attribute.BORDER_TOP
static CSS.Attribute | CSS.Attribute.BORDER_TOP_WIDTH
static CSS.Attribute | CSS.Attribute.BORDER_WIDTH
static CSS.Attribute | CSS.Attribute.CLEAR
static CSS.Attribute | CSS.Attribute.COLOR
static CSS.Attribute | CSS.Attribute.DISPLAY
static CSS.Attribute | CSS.Attribute.FLOAT
static CSS.Attribute | CSS.Attribute.FONT
static CSS.Attribute | CSS.Attribute.FONT_FAMILY
static CSS.Attribute | CSS.Attribute.FONT_SIZE
static CSS.Attribute | CSS.Attribute.FONT_STYLE
static CSS.Attribute | CSS.Attribute.FONT_VARIANT
static CSS.Attribute | CSS.Attribute.FONT_WEIGHT
static CSS.Attribute | CSS.Attribute.HEIGHT
static CSS.Attribute | CSS.Attribute.LETTER_SPACING
static CSS.Attribute | CSS.Attribute.LINE_HEIGHT
static CSS.Attribute | CSS.Attribute.LIST_STYLE
static CSS.Attribute | CSS.Attribute.LIST_STYLE_IMAGE
static CSS.Attribute | CSS.Attribute.LIST_STYLE_POSITION
static CSS.Attribute | CSS.Attribute.LIST_STYLE_TYPE
static CSS.Attribute | CSS.Attribute.MARGIN
static CSS.Attribute | CSS.Attribute.MARGIN_BOTTOM
static CSS.Attribute | CSS.Attribute.MARGIN_LEFT
static CSS.Attribute | CSS.Attribute.MARGIN_RIGHT
static CSS.Attribute | CSS.Attribute.MARGIN_TOP
static CSS.Attribute | CSS.Attribute.PADDING
static CSS.Attribute | CSS.Attribute.PADDING_BOTTOM
static CSS.Attribute | CSS.Attribute.PADDING_LEFT
static CSS.Attribute | CSS.Attribute.PADDING_RIGHT
static CSS.Attribute | CSS.Attribute.PADDING_TOP
static CSS.Attribute | CSS.Attribute.TEXT_ALIGN
static CSS.Attribute | CSS.Attribute.TEXT_DECORATION
static CSS.Attribute | CSS.Attribute.TEXT_INDENT
static CSS.Attribute | CSS.Attribute.TEXT_TRANSFORM
static CSS.Attribute | CSS.Attribute.VERTICAL_ALIGN
static CSS.Attribute | CSS.Attribute.WORD_SPACING
static CSS.Attribute | CSS.Attribute.WHITE_SPACE
static CSS.Attribute | CSS.Attribute.WIDTH

Methods in javax.swing.text.html that return CSS.Attribute
static CSS.Attribute[] | CSS.getAllAttributeKeys() Return the set of all possible CSS attribute keys.
static CSS.Attribute | CSS.getAttribute(String name) Translates a string to a CSS.Attribute object.

Methods in javax.swing.text.html with parameters of type CSS.Attribute
void | StyleSheet.addCSSAttribute(MutableAttributeSet attr, CSS.Attribute key, String value) Adds a CSS attribute to the given set.
boolean | StyleSheet.addCSSAttributeFromHTML(MutableAttributeSet attr, CSS.Attribute key, String value) Adds a CSS attribute to the given set.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.FormView (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.FormView

No usage of javax.swing.text.html.FormView

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.FormView.MouseEventListener (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.FormView.MouseEventListener

No usage of javax.swing.text.html.FormView.MouseEventListener

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.HTML (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.HTML

No usage of javax.swing.text.html.HTML

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.HTML.Attribute (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.HTML.Attribute

Packages that use HTML.Attribute
javax.swing.text.html Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of HTML.Attribute in javax.swing.text.html

Fields in javax.swing.text.html declared as HTML.Attribute
static HTML.Attribute | HTML.Attribute.SIZE
static HTML.Attribute | HTML.Attribute.COLOR
static HTML.Attribute | HTML.Attribute.CLEAR
static HTML.Attribute | HTML.Attribute.BACKGROUND
static HTML.Attribute | HTML.Attribute.BGCOLOR
static HTML.Attribute | HTML.Attribute.TEXT
static HTML.Attribute | HTML.Attribute.LINK
static HTML.Attribute | HTML.Attribute.VLINK
static HTML.Attribute | HTML.Attribute.ALINK
static HTML.Attribute | HTML.Attribute.WIDTH
static HTML.Attribute | HTML.Attribute.HEIGHT
static HTML.Attribute | HTML.Attribute.ALIGN
static HTML.Attribute | HTML.Attribute.NAME
static HTML.Attribute | HTML.Attribute.HREF
static HTML.Attribute | HTML.Attribute.REL
static HTML.Attribute | HTML.Attribute.REV
static HTML.Attribute | HTML.Attribute.TITLE
static HTML.Attribute | HTML.Attribute.TARGET
static HTML.Attribute | HTML.Attribute.SHAPE
static HTML.Attribute | HTML.Attribute.COORDS
static HTML.Attribute | HTML.Attribute.ISMAP
static HTML.Attribute | HTML.Attribute.NOHREF
static HTML.Attribute | HTML.Attribute.ALT
static HTML.Attribute | HTML.Attribute.ID
static HTML.Attribute | HTML.Attribute.SRC
static HTML.Attribute | HTML.Attribute.HSPACE
static HTML.Attribute | HTML.Attribute.VSPACE
static HTML.Attribute | HTML.Attribute.USEMAP
static HTML.Attribute | HTML.Attribute.LOWSRC
static HTML.Attribute | HTML.Attribute.CODEBASE
static HTML.Attribute | HTML.Attribute.CODE
static HTML.Attribute | HTML.Attribute.ARCHIVE
static HTML.Attribute | HTML.Attribute.VALUE
static HTML.Attribute | HTML.Attribute.VALUETYPE
static HTML.Attribute | HTML.Attribute.TYPE
static HTML.Attribute | HTML.Attribute.CLASS
static HTML.Attribute | HTML.Attribute.STYLE
static HTML.Attribute | HTML.Attribute.LANG
static HTML.Attribute | HTML.Attribute.FACE
static HTML.Attribute | HTML.Attribute.DIR
static HTML.Attribute | HTML.Attribute.DECLARE
static HTML.Attribute | HTML.Attribute.CLASSID
static HTML.Attribute | HTML.Attribute.DATA
static HTML.Attribute | HTML.Attribute.CODETYPE
static HTML.Attribute | HTML.Attribute.STANDBY
static HTML.Attribute | HTML.Attribute.BORDER
static HTML.Attribute | HTML.Attribute.SHAPES
static HTML.Attribute | HTML.Attribute.NOSHADE
static HTML.Attribute | HTML.Attribute.COMPACT
static HTML.Attribute | HTML.Attribute.START
static HTML.Attribute | HTML.Attribute.ACTION
static HTML.Attribute | HTML.Attribute.METHOD
static HTML.Attribute | HTML.Attribute.ENCTYPE
static HTML.Attribute | HTML.Attribute.CHECKED
static HTML.Attribute | HTML.Attribute.MAXLENGTH
static HTML.Attribute | HTML.Attribute.MULTIPLE
static HTML.Attribute | HTML.Attribute.SELECTED
static HTML.Attribute | HTML.Attribute.ROWS
static HTML.Attribute | HTML.Attribute.COLS
static HTML.Attribute | HTML.Attribute.DUMMY
static HTML.Attribute | HTML.Attribute.CELLSPACING
static HTML.Attribute | HTML.Attribute.CELLPADDING
static HTML.Attribute | HTML.Attribute.VALIGN
static HTML.Attribute | HTML.Attribute.HALIGN
static HTML.Attribute | HTML.Attribute.NOWRAP
static HTML.Attribute | HTML.Attribute.ROWSPAN
static HTML.Attribute | HTML.Attribute.COLSPAN
static HTML.Attribute | HTML.Attribute.PROMPT
static HTML.Attribute | HTML.Attribute.HTTPEQUIV
static HTML.Attribute | HTML.Attribute.CONTENT
static HTML.Attribute | HTML.Attribute.LANGUAGE
static HTML.Attribute | HTML.Attribute.VERSION
static HTML.Attribute | HTML.Attribute.N
static HTML.Attribute | HTML.Attribute.FRAMEBORDER
static HTML.Attribute | HTML.Attribute.MARGINWIDTH
static HTML.Attribute | HTML.Attribute.MARGINHEIGHT
static HTML.Attribute | HTML.Attribute.SCROLLING
static HTML.Attribute | HTML.Attribute.NORESIZE
static HTML.Attribute | HTML.Attribute.ENDTAG
static HTML.Attribute | HTML.Attribute.COMMENT

Methods in javax.swing.text.html that return HTML.Attribute
static HTML.Attribute[] | HTML.getAllAttributeKeys() Returns the set of HTML attributes recognized.
static HTML.Attribute | HTML.getAttributeKey(String attName) Fetches an attribute constant for a well-known attribute name (i.e.

Methods in javax.swing.text.html with parameters of type HTML.Attribute
static int HTML.getIntegerAttributeValue(AttributeSet attr, HTML.Attribute key, int def)
Fetches an integer attribute value.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.HTML.Tag (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.HTML.Tag

Packages that use HTML.Tag
javax.swing.text.html | Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.
javax.swing.text.html.parser | Provides the default HTML parser, along with support classes.

Uses of HTML.Tag in javax.swing.text.html

Subclasses of HTML.Tag in javax.swing.text.html
static class HTML.UnknownTag

Fields in javax.swing.text.html declared as HTML.Tag
static HTML.Tag | HTML.Tag.A
static HTML.Tag | HTML.Tag.ADDRESS
static HTML.Tag | HTML.Tag.APPLET
static HTML.Tag | HTML.Tag.AREA
static HTML.Tag | HTML.Tag.B
static HTML.Tag | HTML.Tag.BASE
static HTML.Tag | HTML.Tag.BASEFONT
static HTML.Tag | HTML.Tag.BIG
static HTML.Tag | HTML.Tag.BLOCKQUOTE
static HTML.Tag | HTML.Tag.BODY
static HTML.Tag | HTML.Tag.BR
static HTML.Tag | HTML.Tag.CAPTION
static HTML.Tag | HTML.Tag.CENTER
static HTML.Tag | HTML.Tag.CITE
static HTML.Tag | HTML.Tag.CODE
static HTML.Tag | HTML.Tag.DD
static HTML.Tag | HTML.Tag.DFN
static HTML.Tag | HTML.Tag.DIR
static HTML.Tag | HTML.Tag.DIV
static HTML.Tag | HTML.Tag.DL
static HTML.Tag | HTML.Tag.DT
static HTML.Tag | HTML.Tag.EM
static HTML.Tag | HTML.Tag.FONT
static HTML.Tag | HTML.Tag.FORM
static HTML.Tag | HTML.Tag.FRAME
static HTML.Tag | HTML.Tag.FRAMESET
static HTML.Tag | HTML.Tag.H1
static HTML.Tag | HTML.Tag.H2
static HTML.Tag | HTML.Tag.H3
static HTML.Tag | HTML.Tag.H4
static HTML.Tag | HTML.Tag.H5
static HTML.Tag | HTML.Tag.H6
static HTML.Tag | HTML.Tag.HEAD
static HTML.Tag | HTML.Tag.HR
static HTML.Tag | HTML.Tag.HTML
static HTML.Tag | HTML.Tag.I
static HTML.Tag | HTML.Tag.IMG
static HTML.Tag | HTML.Tag.INPUT
static HTML.Tag | HTML.Tag.ISINDEX
static HTML.Tag | HTML.Tag.KBD
static HTML.Tag | HTML.Tag.LI
static HTML.Tag | HTML.Tag.LINK
static HTML.Tag | HTML.Tag.MAP
static HTML.Tag | HTML.Tag.MENU
static HTML.Tag | HTML.Tag.META
static HTML.Tag | HTML.Tag.NOFRAMES
static HTML.Tag | HTML.Tag.OBJECT
static HTML.Tag | HTML.Tag.OL
static HTML.Tag | HTML.Tag.OPTION
static HTML.Tag | HTML.Tag.P
static HTML.Tag | HTML.Tag.PARAM
static HTML.Tag | HTML.Tag.PRE
static HTML.Tag | HTML.Tag.SAMP
static HTML.Tag | HTML.Tag.SCRIPT
static HTML.Tag | HTML.Tag.SELECT
static HTML.Tag | HTML.Tag.SMALL
static HTML.Tag | HTML.Tag.SPAN
static HTML.Tag | HTML.Tag.STRIKE
static HTML.Tag | HTML.Tag.S
static HTML.Tag | HTML.Tag.STRONG
static HTML.Tag | HTML.Tag.STYLE
static HTML.Tag | HTML.Tag.SUB
static HTML.Tag | HTML.Tag.SUP
static HTML.Tag | HTML.Tag.TABLE
static HTML.Tag | HTML.Tag.TD
static HTML.Tag | HTML.Tag.TEXTAREA
static HTML.Tag | HTML.Tag.TH
static HTML.Tag | HTML.Tag.TITLE
static HTML.Tag | HTML.Tag.TR
static HTML.Tag | HTML.Tag.TT
static HTML.Tag | HTML.Tag.U
static HTML.Tag | HTML.Tag.UL
static HTML.Tag | HTML.Tag.VAR
static HTML.Tag | HTML.Tag.IMPLIED All text content must be in a paragraph element.
static HTML.Tag | HTML.Tag.CONTENT All text content is labeled with this tag.
static HTML.Tag | HTML.Tag.COMMENT All comments are labeled with this tag.
protected HTML.Tag | HTMLEditorKit.InsertHTMLTextAction.parentTag Tag to check for in the document.
protected HTML.Tag | HTMLEditorKit.InsertHTMLTextAction.addTag Tag in HTML to start adding tags from.
protected HTML.Tag | HTMLEditorKit.InsertHTMLTextAction.alternateParentTag Alternate Tag to check for in the document if parentTag is not found.
protected HTML.Tag | HTMLEditorKit.InsertHTMLTextAction.alternateAddTag Alternate tag in HTML to start adding tags from if parentTag is not found and alternateParentTag is found.

Methods in javax.swing.text.html that return HTML.Tag
static HTML.Tag[] | HTML.getAllTags() Returns the set of actual HTML tags that are recognized by the default HTML reader.
static HTML.Tag | HTML.getTag(String tagName) Fetches a tag constant for a well-known tag name (i.e.
abstract HTML.Tag | HTMLDocument.Iterator.getTag() Type of tag this iterator represents.

Methods in javax.swing.text.html with parameters of type HTML.Tag
protected boolean | HTMLWriter.matchNameAttribute(AttributeSet attr, HTML.Tag tag) Returns true if the StyleConstants.NameAttribute is equal to the tag that is passed in as a parameter.
void | HTMLEditorKit.insertHTML(HTMLDocument doc, int offset, String html, int popDepth, int pushDepth, HTML.Tag insertTag) Inserts HTML into an existing document.
void | HTMLEditorKit.ParserCallback.handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos)
void | HTMLEditorKit.ParserCallback.handleEndTag(HTML.Tag t, int pos)
void | HTMLEditorKit.ParserCallback.handleSimpleTag(HTML.Tag t, MutableAttributeSet a, int pos)
protected int | HTMLEditorKit.HTMLTextAction.elementCountToTag(HTMLDocument doc, int offset, HTML.Tag tag) Returns number of elements, starting at the deepest leaf, needed to get to an element representing tag.
protected Element | HTMLEditorKit.HTMLTextAction.findElementMatchingTag(HTMLDocument doc, int offset, HTML.Tag tag) Returns the deepest element at offset matching tag.
protected void | HTMLEditorKit.InsertHTMLTextAction.insertHTML(JEditorPane editor, HTMLDocument doc, int offset, String html, int popDepth, int pushDepth, HTML.Tag addTag) A cover for HTMLEditorKit.insertHTML.
protected void | HTMLEditorKit.InsertHTMLTextAction.insertAtBoundary(JEditorPane editor, HTMLDocument doc, int offset, Element insertElement, String html, HTML.Tag parentTag, HTML.Tag addTag) This is invoked when inserting at a boundary.
protected void | HTMLEditorKit.InsertHTMLTextAction.insertAtBoundry(JEditorPane editor, HTMLDocument doc, int offset, Element insertElement, String html, HTML.Tag parentTag, HTML.Tag addTag) Deprecated. As of Java 2 platform v1.3, use insertAtBoundary
Style | StyleSheet.getRule(HTML.Tag t, Element e) Fetches the style to use to render the given type of HTML tag.
HTMLEditorKit.ParserCallback | HTMLDocument.getReader(int pos, int popDepth, int pushDepth, HTML.Tag insertTag) Returns the reader for the parser to use to load the document with HTML.
HTMLDocument.Iterator | HTMLDocument.getIterator(HTML.Tag t) Fetches an iterator for the specified HTML tag.
void | HTMLDocument.HTMLReader.handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos) Callback from the parser.
void | HTMLDocument.HTMLReader.handleEndTag(HTML.Tag t, int pos) Callback from the parser.
void | HTMLDocument.HTMLReader.handleSimpleTag(HTML.Tag t, MutableAttributeSet a, int pos) Callback from the parser.
protected void | HTMLDocument.HTMLReader.registerTag(HTML.Tag t, HTMLDocument.HTMLReader.TagAction a) Registers a handler for the given tag.
protected void | HTMLDocument.HTMLReader.blockOpen(HTML.Tag t, MutableAttributeSet attr) Adds an instruction to the parse buffer to create a block element with the given attributes.
protected void | HTMLDocument.HTMLReader.blockClose(HTML.Tag t) Adds an instruction to the parse buffer to close out a block element of the given type.
protected void | HTMLDocument.HTMLReader.addSpecialElement(HTML.Tag t, MutableAttributeSet a) Adds content that is basically specified entirely in the attribute set.
void | HTMLDocument.HTMLReader.TagAction.start(HTML.Tag t, MutableAttributeSet a) Called when a start tag is seen for the type of tag this action was registered to.
void | HTMLDocument.HTMLReader.TagAction.end(HTML.Tag t) Called when an end tag is seen for the type of tag this action was registered to.
void | HTMLDocument.HTMLReader.BlockAction.start(HTML.Tag t, MutableAttributeSet attr)
void | HTMLDocument.HTMLReader.BlockAction.end(HTML.Tag t)
void | HTMLDocument.HTMLReader.ParagraphAction.start(HTML.Tag t, MutableAttributeSet a)
void | HTMLDocument.HTMLReader.ParagraphAction.end(HTML.Tag t)
void | HTMLDocument.HTMLReader.SpecialAction.start(HTML.Tag t, MutableAttributeSet a)
void | HTMLDocument.HTMLReader.IsindexAction.start(HTML.Tag t, MutableAttributeSet a)
void | HTMLDocument.HTMLReader.HiddenAction.start(HTML.Tag t, MutableAttributeSet a)
void | HTMLDocument.HTMLReader.HiddenAction.end(HTML.Tag t)
void | HTMLDocument.HTMLReader.PreAction.start(HTML.Tag t, MutableAttributeSet attr)
void | HTMLDocument.HTMLReader.PreAction.end(HTML.Tag t)
void | HTMLDocument.HTMLReader.CharacterAction.start(HTML.Tag t, MutableAttributeSet attr)
void | HTMLDocument.HTMLReader.CharacterAction.end(HTML.Tag t)
void | HTMLDocument.HTMLReader.FormAction.start(HTML.Tag t, MutableAttributeSet attr)
void | HTMLDocument.HTMLReader.FormAction.end(HTML.Tag t)

Constructors in javax.swing.text.html with parameters of type HTML.Tag
HTMLEditorKit.InsertHTMLTextAction(String name, String html, HTML.Tag parentTag, HTML.Tag addTag)
HTMLEditorKit.InsertHTMLTextAction(String name, String html, HTML.Tag parentTag, HTML.Tag addTag, HTML.Tag alternateParentTag, HTML.Tag alternateAddTag)
HTMLDocument.HTMLReader(int offset, int popDepth, int pushDepth, HTML.Tag insertTag)

Uses of HTML.Tag in javax.swing.text.html.parser

Methods in javax.swing.text.html.parser that return HTML.Tag
 HTML.Tag TagElement.getHTMLTag()

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.HTML.UnknownTag (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.HTML.UnknownTag

No usage of javax.swing.text.html.HTML.UnknownTag

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.HTMLDocument (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.HTMLDocument

Packages that use HTMLDocument
javax.swing.text.html Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of HTMLDocument in javax.swing.text.html

Methods in javax.swing.text.html that return HTMLDocument
protected  HTMLDocument HTMLEditorKit.HTMLTextAction.getHTMLDocument(JEditorPane e)

Methods in javax.swing.text.html with parameters of type HTMLDocument
void | HTMLEditorKit.insertHTML(HTMLDocument doc, int offset, String html, int popDepth, int pushDepth, HTML.Tag insertTag) Inserts HTML into an existing document.
protected Element[] | HTMLEditorKit.HTMLTextAction.getElementsAt(HTMLDocument doc, int offset) Returns an array of the Elements that contain offset.
protected int | HTMLEditorKit.HTMLTextAction.elementCountToTag(HTMLDocument doc, int offset, HTML.Tag tag) Returns number of elements, starting at the deepest leaf, needed to get to an element representing tag.
protected Element | HTMLEditorKit.HTMLTextAction.findElementMatchingTag(HTMLDocument doc, int offset, HTML.Tag tag) Returns the deepest element at offset matching tag.
protected void | HTMLEditorKit.InsertHTMLTextAction.insertHTML(JEditorPane editor, HTMLDocument doc, int offset, String html, int popDepth, int pushDepth, HTML.Tag addTag) A cover for HTMLEditorKit.insertHTML.
protected void | HTMLEditorKit.InsertHTMLTextAction.insertAtBoundary(JEditorPane editor, HTMLDocument doc, int offset, Element insertElement, String html, HTML.Tag parentTag, HTML.Tag addTag) This is invoked when inserting at a boundary.
protected void | HTMLEditorKit.InsertHTMLTextAction.insertAtBoundry(JEditorPane editor, HTMLDocument doc, int offset, Element insertElement, String html, HTML.Tag parentTag, HTML.Tag addTag) Deprecated. As of Java 2 platform v1.3, use insertAtBoundary

Constructors in javax.swing.text.html with parameters of type HTMLDocument
HTMLWriter(Writer w, HTMLDocument doc)
Creates a new HTMLWriter.
HTMLWriter(Writer w, HTMLDocument doc, int pos, int len)
Creates a new HTMLWriter.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.HTMLDocument.BlockElement (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.HTMLDocument.BlockElement

No usage of javax.swing.text.html.HTMLDocument.BlockElement

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.HTMLDocument.HTMLReader (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.HTMLDocument.HTMLReader

No usage of javax.swing.text.html.HTMLDocument.HTMLReader

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.HTMLDocument.HTMLReader.BlockAction (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.HTMLDocument.HTMLReader.BlockAction

Packages that use HTMLDocument.HTMLReader.BlockAction
javax.swing.text.html Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of HTMLDocument.HTMLReader.BlockAction in javax.swing.text.html

Subclasses of HTMLDocument.HTMLReader.BlockAction in javax.swing.text.html
class | HTMLDocument.HTMLReader.ParagraphAction
class | HTMLDocument.HTMLReader.PreAction

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.HTMLDocument.HTMLReader.CharacterAction (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.HTMLDocument.HTMLReader.CharacterAction

No usage of javax.swing.text.html.HTMLDocument.HTMLReader.CharacterAction

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.HTMLDocument.HTMLReader.FormAction (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.HTMLDocument.HTMLReader.FormAction

No usage of javax.swing.text.html.HTMLDocument.HTMLReader.FormAction

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.HTMLDocument.HTMLReader.HiddenAction (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.HTMLDocument.HTMLReader.HiddenAction

No usage of javax.swing.text.html.HTMLDocument.HTMLReader.HiddenAction

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.HTMLDocument.HTMLReader.IsindexAction (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.HTMLDocument.HTMLReader.IsindexAction

No usage of javax.swing.text.html.HTMLDocument.HTMLReader.IsindexAction

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.HTMLDocument.HTMLReader.ParagraphAction (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.HTMLDocument.HTMLReader.ParagraphAction

No usage of javax.swing.text.html.HTMLDocument.HTMLReader.ParagraphAction

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.HTMLDocument.HTMLReader.PreAction (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.HTMLDocument.HTMLReader.PreAction

No usage of javax.swing.text.html.HTMLDocument.HTMLReader.PreAction

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.HTMLDocument.HTMLReader.SpecialAction (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.HTMLDocument.HTMLReader.SpecialAction

Packages that use HTMLDocument.HTMLReader.SpecialAction
javax.swing.text.html Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of HTMLDocument.HTMLReader.SpecialAction in javax.swing.text.html

Subclasses of HTMLDocument.HTMLReader.SpecialAction in javax.swing.text.html
 class HTMLDocument.HTMLReader.FormAction
Action to support forms by building all of the elements used to represent form controls.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.HTMLDocument.HTMLReader.TagAction (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.HTMLDocument.HTMLReader.TagAction

Packages that use HTMLDocument.HTMLReader.TagAction
javax.swing.text.html Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of HTMLDocument.HTMLReader.TagAction in javax.swing.text.html

Subclasses of HTMLDocument.HTMLReader.TagAction in javax.swing.text.html
class | HTMLDocument.HTMLReader.BlockAction
class | HTMLDocument.HTMLReader.CharacterAction
class | HTMLDocument.HTMLReader.FormAction Action to support forms by building all of the elements used to represent form controls.
class | HTMLDocument.HTMLReader.HiddenAction
class | HTMLDocument.HTMLReader.IsindexAction
class | HTMLDocument.HTMLReader.ParagraphAction
class | HTMLDocument.HTMLReader.PreAction
class | HTMLDocument.HTMLReader.SpecialAction

Methods in javax.swing.text.html with parameters of type HTMLDocument.HTMLReader.TagAction
protected  void HTMLDocument.HTMLReader.registerTag(HTML.Tag t, HTMLDocument.HTMLReader.TagAction a)
Registers a handler for the given tag.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.HTMLDocument.Iterator (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.HTMLDocument.Iterator

Packages that use HTMLDocument.Iterator
javax.swing.text.html Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of HTMLDocument.Iterator in javax.swing.text.html

Methods in javax.swing.text.html that return HTMLDocument.Iterator
 HTMLDocument.Iterator HTMLDocument.getIterator(HTML.Tag t)
Fetches an iterator for the specified HTML tag.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.HTMLDocument.RunElement (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.HTMLDocument.RunElement

No usage of javax.swing.text.html.HTMLDocument.RunElement

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.HTMLEditorKit (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.HTMLEditorKit

Packages that use HTMLEditorKit
javax.swing.text.html Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of HTMLEditorKit in javax.swing.text.html

Methods in javax.swing.text.html that return HTMLEditorKit
protected  HTMLEditorKit HTMLEditorKit.HTMLTextAction.getHTMLEditorKit(JEditorPane e)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.HTMLEditorKit.HTMLFactory (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.HTMLEditorKit.HTMLFactory

No usage of javax.swing.text.html.HTMLEditorKit.HTMLFactory

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.HTMLEditorKit.HTMLTextAction (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.HTMLEditorKit.HTMLTextAction

Packages that use HTMLEditorKit.HTMLTextAction
javax.swing.text.html Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of HTMLEditorKit.HTMLTextAction in javax.swing.text.html

Subclasses of HTMLEditorKit.HTMLTextAction in javax.swing.text.html
static class HTMLEditorKit.InsertHTMLTextAction
InsertHTMLTextAction can be used to insert an arbitrary string of HTML into an existing HTML document.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.HTMLEditorKit.InsertHTMLTextAction (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.HTMLEditorKit.InsertHTMLTextAction

No usage of javax.swing.text.html.HTMLEditorKit.InsertHTMLTextAction

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.HTMLEditorKit.LinkController (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.HTMLEditorKit.LinkController

No usage of javax.swing.text.html.HTMLEditorKit.LinkController

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.HTMLEditorKit.Parser (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.HTMLEditorKit.Parser

Packages that use HTMLEditorKit.Parser
javax.swing.text.html | Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.
javax.swing.text.html.parser | Provides the default HTML parser, along with support classes.

Uses of HTMLEditorKit.Parser in javax.swing.text.html

Methods in javax.swing.text.html that return HTMLEditorKit.Parser
protected HTMLEditorKit.Parser | HTMLEditorKit.getParser() Fetch the parser to use for reading HTML streams.
HTMLEditorKit.Parser | HTMLDocument.getParser() Returns the parser that is used when inserting HTML into the existing document.

Methods in javax.swing.text.html with parameters of type HTMLEditorKit.Parser
 void HTMLDocument.setParser(HTMLEditorKit.Parser parser)
Sets the parser that is used by the methods that insert html into the existing document, such as setInnerHTML, and setOuterHTML.

Uses of HTMLEditorKit.Parser in javax.swing.text.html.parser

Subclasses of HTMLEditorKit.Parser in javax.swing.text.html.parser
 class ParserDelegator
Responsible for starting up a new DocumentParser each time its parse method is invoked.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.HTMLEditorKit.ParserCallback (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.HTMLEditorKit.ParserCallback

Packages that use HTMLEditorKit.ParserCallback
javax.swing.text.html | Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.
javax.swing.text.html.parser | Provides the default HTML parser, along with support classes.

Uses of HTMLEditorKit.ParserCallback in javax.swing.text.html

Subclasses of HTMLEditorKit.ParserCallback in javax.swing.text.html
 class HTMLDocument.HTMLReader
An HTML reader to load an HTML document with an HTML element structure.

Methods in javax.swing.text.html that return HTMLEditorKit.ParserCallback
HTMLEditorKit.ParserCallback | HTMLDocument.getReader(int pos) Fetches the reader for the parser to use when loading the document with HTML.
HTMLEditorKit.ParserCallback | HTMLDocument.getReader(int pos, int popDepth, int pushDepth, HTML.Tag insertTag) Returns the reader for the parser to use to load the document with HTML.

Methods in javax.swing.text.html with parameters of type HTMLEditorKit.ParserCallback
abstract  void HTMLEditorKit.Parser.parse(Reader r, HTMLEditorKit.ParserCallback cb, boolean ignoreCharSet)
Parse the given stream and drive the given callback with the results of the parse.

Uses of HTMLEditorKit.ParserCallback in javax.swing.text.html.parser

Methods in javax.swing.text.html.parser with parameters of type HTMLEditorKit.ParserCallback
void | ParserDelegator.parse(Reader r, HTMLEditorKit.ParserCallback cb, boolean ignoreCharSet)
void | DocumentParser.parse(Reader in, HTMLEditorKit.ParserCallback callback, boolean ignoreCharSet)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.HTMLFrameHyperlinkEvent (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.HTMLFrameHyperlinkEvent

Packages that use HTMLFrameHyperlinkEvent
javax.swing.text.html Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of HTMLFrameHyperlinkEvent in javax.swing.text.html

Methods in javax.swing.text.html with parameters of type HTMLFrameHyperlinkEvent
 void HTMLDocument.processHTMLFrameHyperlinkEvent(HTMLFrameHyperlinkEvent e)
Processes HyperlinkEvents that are generated by documents in an HTML frame.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.HTMLWriter (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.HTMLWriter

No usage of javax.swing.text.html.HTMLWriter

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.ImageView (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.ImageView

No usage of javax.swing.text.html.ImageView

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.InlineView (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.InlineView

No usage of javax.swing.text.html.InlineView

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.ListView (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.ListView

No usage of javax.swing.text.html.ListView

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.MinimalHTMLWriter (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.MinimalHTMLWriter

No usage of javax.swing.text.html.MinimalHTMLWriter

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.ObjectView (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.ObjectView

No usage of javax.swing.text.html.ObjectView

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.Option (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.Option

Packages that use Option
javax.swing.text.html Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of Option in javax.swing.text.html

Methods in javax.swing.text.html with parameters of type Option
protected  void HTMLWriter.writeOption(Option option)
Writes out the content of the Option form element.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.ParagraphView (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.ParagraphView

No usage of javax.swing.text.html.ParagraphView

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.StyleSheet (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.StyleSheet

Packages that use StyleSheet
javax.swing.text.html Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of StyleSheet in javax.swing.text.html

Methods in javax.swing.text.html that return StyleSheet
protected StyleSheet | ImageView.getStyleSheet() Convenience method to get the StyleSheet.
protected StyleSheet | ParagraphView.getStyleSheet()
protected StyleSheet | InlineView.getStyleSheet()
protected StyleSheet | BlockView.getStyleSheet()
StyleSheet | HTMLEditorKit.getStyleSheet() Get the set of styles currently being used to render the HTML elements.
StyleSheet[] | StyleSheet.getStyleSheets() Returns an array of the linked StyleSheets.
StyleSheet | HTMLDocument.getStyleSheet() Fetches the StyleSheet with the document-specific display rules (CSS) that were specified in the HTML document itself.

Methods in javax.swing.text.html with parameters of type StyleSheet
void | HTMLEditorKit.setStyleSheet(StyleSheet s) Set the set of styles to be used to render the various HTML elements.
void | StyleSheet.addStyleSheet(StyleSheet ss) Adds the rules from the StyleSheet ss to those of the receiver.
void | StyleSheet.removeStyleSheet(StyleSheet ss) Removes the StyleSheet ss from those of the receiver.

Constructors in javax.swing.text.html with parameters of type StyleSheet
HTMLDocument(StyleSheet styles)
Constructs an HTML document with the default content storage implementation and the specified style/attribute storage mechanism.
HTMLDocument(AbstractDocument.Content c, StyleSheet styles)
Constructs an HTML document with the given content storage implementation and the given style/attribute storage mechanism.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.StyleSheet.BoxPainter (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.StyleSheet.BoxPainter

Packages that use StyleSheet.BoxPainter
javax.swing.text.html Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of StyleSheet.BoxPainter in javax.swing.text.html

Methods in javax.swing.text.html that return StyleSheet.BoxPainter
 StyleSheet.BoxPainter StyleSheet.getBoxPainter(AttributeSet a)
Fetches the box formatter to use for the given set of CSS attributes.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.StyleSheet.ListPainter (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.StyleSheet.ListPainter

Packages that use StyleSheet.ListPainter
javax.swing.text.html Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.

Uses of StyleSheet.ListPainter in javax.swing.text.html

Methods in javax.swing.text.html that return StyleSheet.ListPainter
 StyleSheet.ListPainter StyleSheet.getListPainter(AttributeSet a)
Fetches the list formatter to use for the given set of CSS attributes.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


AttributeList (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html.parser
Class AttributeList

java.lang.Object
    extended by javax.swing.text.html.parser.AttributeList
All Implemented Interfaces:
DTDConstants, Serializable
public final class AttributeList
extends Object
implements DTDConstants, Serializable

This class defines the attributes of an SGML element as described in a DTD using the ATTLIST construct. An AttributeList can be obtained from the Element class using the getAttributes() method.

It is actually an element in a linked list. Use the getNext() method repeatedly to enumerate all the attributes of an element.

See Also:
Element

Field Summary
int | modifier
String | name
AttributeList | next
int | type
String | value
Vector | values
Fields inherited from interface javax.swing.text.html.parser.DTDConstants
ANY, CDATA, CONREF, CURRENT, DEFAULT, EMPTY, ENDTAG, ENTITIES, ENTITY, FIXED, GENERAL, ID, IDREF, IDREFS, IMPLIED, MD, MODEL, MS, NAME, NAMES, NMTOKEN, NMTOKENS, NOTATION, NUMBER, NUMBERS, NUTOKEN, NUTOKENS, PARAMETER, PI, PUBLIC, RCDATA, REQUIRED, SDATA, STARTTAG, SYSTEM
Constructor Summary
AttributeList(String name)
Create an attribute list element.
AttributeList(String name, int type, int modifier, String value, Vector values, AttributeList next)
Create an attribute list element.
Method Summary
int | getModifier()
String | getName()
AttributeList | getNext()
int | getType()
String | getValue()
Enumeration | getValues()
static int | name2type(String nm)
String | toString() Returns a string representation of the object.
static String | type2name(int tp)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

name

public String name

type

public int type

values

public Vector values

modifier

public int modifier

value

public String value

next

public AttributeList next
Constructor Detail

AttributeList

public AttributeList(String name)
Create an attribute list element.

AttributeList

public AttributeList(String name,
                     int type,
                     int modifier,
                     String value,
                     Vector values,
                     AttributeList next)
Create an attribute list element.

Method Detail

getName

public String getName()
Returns:
attribute name

getType

public int getType()
Returns:
attribute type
See Also:
DTDConstants

getModifier

public int getModifier()
Returns:
attribute modifier
See Also:
DTDConstants

getValues

public Enumeration getValues()
Returns:
possible attribute values

getValue

public String getValue()
Returns:
default attribute value

getNext

public AttributeList getNext()
Returns:
the next attribute in the list

toString

public String toString()
Description copied from class: Object
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

 getClass().getName() + '@' + Integer.toHexString(hashCode())

Overrides:
toString in class Object
Returns:
string representation

name2type

public static int name2type(String nm)

type2name

public static String type2name(int tp)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


ContentModel (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html.parser
Class ContentModel

java.lang.Object
    extended by javax.swing.text.html.parser.ContentModel
All Implemented Interfaces:
Serializable
public final class ContentModel
extends Object
implements Serializable

A representation of a content model. A content model is basically a restricted BNF expression. It is restricted in the sense that it must be deterministic. This means that you don't have to represent it as a finite state automata.

See Annex H on page 556 of the SGML handbook for more information.

Field Summary
Object | content The content.
ContentModel | next The next content model (in a ',', '|' or '&' expression).
int | type Type.
Constructor Summary
ContentModel()
ContentModel(Element content)
Create a content model for an element.
ContentModel(int type, ContentModel content)
Create a content model of a particular type.
ContentModel(int type, Object content, ContentModel next)
Create a content model of a particular type.
Method Summary
boolean | empty() Return true if the content model could match an empty input stream.
Element | first() Return the element that must be next.
boolean | first(Object token) Return true if the token could potentially be the first token in the input stream.
void | getElements(Vector elemVec) Update elemVec with the list of elements that are part of the this contentModel.
String | toString() Convert to a string.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

type

public int type
Type. Either '*', '?', '+', ',', '|', '&'.

content

public Object content
The content. Either an Element or a ContentModel.

next

public ContentModel next
The next content model (in a ',', '|' or '&' expression).

Constructor Detail

ContentModel

public ContentModel()

ContentModel

public ContentModel(Element content)
Create a content model for an element.

ContentModel

public ContentModel(int type,
                    ContentModel content)
Create a content model of a particular type.

ContentModel

public ContentModel(int type,
                    Object content,
                    ContentModel next)
Create a content model of a particular type.

Method Detail

empty

public boolean empty()
Return true if the content model could match an empty input stream.

getElements

public void getElements(Vector elemVec)
Update elemVec with the list of elements that are part of the this contentModel.

first

public boolean first(Object token)
Return true if the token could potentially be the first token in the input stream.

first

public Element first()
Return the element that must be next.

toString

public String toString()
Convert to a string.

Overrides:
toString in class Object
Returns:
a string representation of the object.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DocumentParser (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html.parser
Class DocumentParser

java.lang.Object
    extended by javax.swing.text.html.parser.Parser
        extended by javax.swing.text.html.parser.DocumentParser
All Implemented Interfaces:
DTDConstants
public class DocumentParser
extends Parser

A Parser for HTML Documents (actually, you can specify a DTD, but you should really only use this class with the html dtd in swing). Reads an InputStream of HTML and invokes the appropriate methods in the ParserCallback class. This is the default parser used by HTMLEditorKit to parse HTML url's.

This will message the callback for all valid tags, as well as tags that are implied but not explicitly specified. For example, the html string (<p>blah) only has a p tag defined. The callback will see the following methods:

  1. handleStartTag(html, ...)
  2. handleStartTag(head, ...)
  3. handleEndTag(head)
  4. handleStartTag(body, ...)
  5. handleStartTag(p, ...)
  6. handleText(...)
  7. handleEndTag(p)
  8. handleEndTag(body)
  9. handleEndTag(html)
The items in italic are implied, that is, although they were not explicitly specified, to be correct html they should have been present (head isn't necessary, but it is still generated). For tags that are implied, the AttributeSet argument will have a value of Boolean.TRUE for the key HTMLEditorKit.ParserCallback.IMPLIED.

HTML.Attributes defines a type safe enumeration of html attributes. If an attribute key of a tag is defined in HTML.Attribute, the HTML.Attribute will be used as the key, otherwise a String will be used. For example <p foo=bar class=neat> has two attributes. foo is not defined in HTML.Attribute, where as class is, therefore the AttributeSet will have two values in it, HTML.Attribute.CLASS with a String value of 'neat' and the String key 'foo' with a String value of 'bar'.

The position argument will indicate the start of the tag, comment or text. Similiar to arrays, the first character in the stream has a position of 0. For tags that are implied the position will indicate the location of the next encountered tag. In the first example, the implied start body and html tags will have the same position as the p tag, and the implied end p, html and body tags will all have the same position.

As html skips whitespace the position for text will be the position of the first valid character, eg in the string '\n\n\nblah' the text 'blah' will have a position of 3, the newlines are skipped.

For attributes that do not have a value, eg in the html string <foo blah> the attribute blah does not have a value, there are two possible values that will be placed in the AttributeSet's value:

  • If the DTD does not contain an definition for the element, or the definition does not have an explicit value then the value in the AttributeSet will be HTML.NULL_ATTRIBUTE_VALUE.
  • If the DTD contains an explicit value, as in: <!ATTLIST OPTION selected (selected) #IMPLIED> this value from the dtd (in this case selected) will be used.

Once the stream has been parsed, the callback is notified of the most likely end of line string. The end of line string will be one of \n, \r or \r\n, which ever is encountered the most in parsing the stream.

Field Summary
Fields inherited from class javax.swing.text.html.parser.Parser
dtd, strict
Fields inherited from interface javax.swing.text.html.parser.DTDConstants
ANY, CDATA, CONREF, CURRENT, DEFAULT, EMPTY, ENDTAG, ENTITIES, ENTITY, FIXED, GENERAL, ID, IDREF, IDREFS, IMPLIED, MD, MODEL, MS, NAME, NAMES, NMTOKEN, NMTOKENS, NOTATION, NUMBER, NUMBERS, NUTOKEN, NUTOKENS, PARAMETER, PI, PUBLIC, RCDATA, REQUIRED, SDATA, STARTTAG, SYSTEM
Constructor Summary
DocumentParser(DTD dtd)
Method Summary
protected void | handleComment(char[] text) Called when an HTML comment is encountered.
protected void | handleEmptyTag(TagElement tag) Handle Empty Tag.
protected void | handleEndTag(TagElement tag) Handle End Tag.
protected void | handleError(int ln, String errorMsg) An error has occurred.
protected void | handleStartTag(TagElement tag) Handle Start Tag.
protected void | handleText(char[] data) Handle Text.
void | parse(Reader in, HTMLEditorKit.ParserCallback callback, boolean ignoreCharSet)
Methods inherited from class javax.swing.text.html.parser.Parser
endTag, error, error, error, error, flushAttributes, getAttributes, getCurrentLine, getCurrentPos, handleEOFInComment, handleTitle, makeTag, makeTag, markFirstTime, parse, parseDTDMarkup, parseMarkupDeclarations, startTag
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DocumentParser

public DocumentParser(DTD dtd)
Method Detail

parse

public void parse(Reader in,
                  HTMLEditorKit.ParserCallback callback,
                  boolean ignoreCharSet)
           throws IOException
Throws:
IOException

handleStartTag

protected void handleStartTag(TagElement tag)
Handle Start Tag.

Overrides:
handleStartTag in class Parser

handleComment

protected void handleComment(char[] text)
Description copied from class: Parser
Called when an HTML comment is encountered.

Overrides:
handleComment in class Parser

handleEmptyTag

protected void handleEmptyTag(TagElement tag)
                       throws ChangedCharSetException
Handle Empty Tag.

Overrides:
handleEmptyTag in class Parser
Throws:
ChangedCharSetException

handleEndTag

protected void handleEndTag(TagElement tag)
Handle End Tag.

Overrides:
handleEndTag in class Parser

handleText

protected void handleText(char[] data)
Handle Text.

Overrides:
handleText in class Parser

handleError

protected void handleError(int ln,
                           String errorMsg)
Description copied from class: Parser
An error has occurred.

Overrides:
handleError in class Parser
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DTD (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html.parser
Class DTD

java.lang.Object
    extended by javax.swing.text.html.parser.DTD
All Implemented Interfaces:
DTDConstants
public class DTD
extends Object
implements DTDConstants

The representation of an SGML DTD. DTD describes a document syntax and is used in parsing of HTML documents. It contains a list of elements and their attributes as well as a list of entities defined in the DTD.

See Also:
Element, AttributeList, ContentModel, Parser

Field Summary
Element | applet
Element | base
Element | body
Hashtable | elementHash
Vector | elements
Hashtable | entityHash
static int | FILE_VERSION
Element | head
Element | html
Element | isindex
Element | meta
String | name
Element | p
Element | param
Element | pcdata
Element | title
Fields inherited from interface javax.swing.text.html.parser.DTDConstants
ANY, CDATA, CONREF, CURRENT, DEFAULT, EMPTY, ENDTAG, ENTITIES, ENTITY, FIXED, GENERAL, ID, IDREF, IDREFS, IMPLIED, MD, MODEL, MS, NAME, NAMES, NMTOKEN, NMTOKENS, NOTATION, NUMBER, NUMBERS, NUTOKEN, NUTOKENS, PARAMETER, PI, PUBLIC, RCDATA, REQUIRED, SDATA, STARTTAG, SYSTEM
Constructor Summary
protected DTD(String name)
Creates a new DTD with the specified name.
Method Summary
protected AttributeList | defAttributeList(String name, int type, int modifier, String value, String values, AttributeList atts) Creates and returns an AttributeList.
protected ContentModel | defContentModel(int type, Object obj, ContentModel next) Creates and returns a new content model.
protected Element | defElement(String name, int type, boolean omitStart, boolean omitEnd, ContentModel content, String[] exclusions, String[] inclusions, AttributeList atts) Creates and returns an Element.
Entity | defEntity(String name, int type, int ch) Creates and returns a character Entity.
protected Entity | defEntity(String name, int type, String str) Creates and returns an Entity.
void | defineAttributes(String name, AttributeList atts) Returns the Element which matches the specified AttributeList.
Element | defineElement(String name, int type, boolean omitStart, boolean omitEnd, ContentModel content, BitSet exclusions, BitSet inclusions, AttributeList atts) Returns the Element which matches the specified parameters.
Entity | defineEntity(String name, int type, char[] data) Defines an entity.
static DTD | getDTD(String name) Returns a DTD with the specified name.
Element | getElement(int index) Gets an element by index.
Element | getElement(String name) Gets an element by name.
Entity | getEntity(int ch) Gets a character entity.
Entity | getEntity(String name) Gets an entity by name.
String | getName() Gets the name of the DTD.
static void | putDTDHash(String name, DTD dtd)
void | read(DataInputStream in) Recreates a DTD from an archived format.
String | toString() Returns a string representation of this DTD.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

name

public String name

elements

public Vector elements

elementHash

public Hashtable elementHash

entityHash

public Hashtable entityHash

pcdata

public final Element pcdata

html

public final Element html

meta

public final Element meta

base

public final Element base

isindex

public final Element isindex

head

public final Element head

body

public final Element body

applet

public final Element applet

param

public final Element param

p

public final Element p

title

public final Element title

FILE_VERSION

public static int FILE_VERSION
Constructor Detail

DTD

protected DTD(String name)
Creates a new DTD with the specified name.

Parameters:
name - the name, as a String of the new DTD
Method Detail

getName

public String getName()
Gets the name of the DTD.

Returns:
the name of the DTD

getEntity

public Entity getEntity(String name)
Gets an entity by name.

Returns:
the Entity corresponding to the name String

getEntity

public Entity getEntity(int ch)
Gets a character entity.

Returns:
the Entity corresponding to the ch character

getElement

public Element getElement(String name)
Gets an element by name. A new element is created if the element doesn't exist.

Parameters:
name - the requested String
Returns:
the Element corresponding to name, which may be newly created

getElement

public Element getElement(int index)
Gets an element by index.

Parameters:
index - the requested index
Returns:
the Element corresponding to index

defineEntity

public Entity defineEntity(String name,
                           int type,
                           char[] data)
Defines an entity. If the Entity specified by name, type, and data exists, it is returned; otherwise a new Entity is created and is returned.

Parameters:
name - the name of the Entity as a String
type - the type of the Entity
data - the Entity's data
Returns:
the Entity requested or a new Entity if not found

defineElement

public Element defineElement(String name,
                             int type,
                             boolean omitStart,
                             boolean omitEnd,
                             ContentModel content,
                             BitSet exclusions,
                             BitSet inclusions,
                             AttributeList atts)
Returns the Element which matches the specified parameters. If one doesn't exist, a new one is created and returned.

Parameters:
name - the name of the Element
type - the type of the Element
omitStart - trueomitEnd - true if end should be omitted
content - the ContentModel
atts - the AttributeList specifying the Element
Returns:
the Element specified

defineAttributes

public void defineAttributes(String name,
                             AttributeList atts)
Returns the Element which matches the specified AttributeList. If one doesn't exist, a new one is created and returned.

Parameters:
name - the name of the Element
atts - the AttributeList specifying the Element
Returns:
the Element specified

defEntity

public Entity defEntity(String name,
                        int type,
                        int ch)
Creates and returns a character Entity.

Parameters:
name - the entity's name
Returns:
the new character Entity

defEntity

protected Entity defEntity(String name,
                           int type,
                           String str)
Creates and returns an Entity.

Parameters:
name - the entity's name
Returns:
the new Entity

defElement

protected Element defElement(String name,
                             int type,
                             boolean omitStart,
                             boolean omitEnd,
                             ContentModel content,
                             String[] exclusions,
                             String[] inclusions,
                             AttributeList atts)
Creates and returns an Element.

Parameters:
name - the element's name
Returns:
the new Element

defAttributeList

protected AttributeList defAttributeList(String name,
                                         int type,
                                         int modifier,
                                         String value,
                                         String values,
                                         AttributeList atts)
Creates and returns an AttributeList.

Parameters:
name - the attribute list's name
Returns:
the new AttributeList

defContentModel

protected ContentModel defContentModel(int type,
                                       Object obj,
                                       ContentModel next)
Creates and returns a new content model.

Parameters:
type - the type of the new content model
Returns:
the new ContentModel

toString

public String toString()
Returns a string representation of this DTD.

Overrides:
toString in class Object
Returns:
the string representation of this DTD

putDTDHash

public static void putDTDHash(String name,
                              DTD dtd)

getDTD

public static DTD getDTD(String name)
                  throws IOException
Returns a DTD with the specified name. If a DTD with that name doesn't exist, one is created and returned. Any uppercase characters in the name are converted to lowercase.

Parameters:
name - the name of the DTD
Returns:
the DTD which corresponds to name
Throws:
IOException

read

public void read(DataInputStream in)
          throws IOException
Recreates a DTD from an archived format.

Parameters:
in - the DataInputStream to read from
Throws:
IOException
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DTDConstants (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html.parser
Interface DTDConstants

All Known Implementing Classes:
AttributeList, DTD, Element, Entity, Parser
public interface DTDConstants

SGML constants used in a DTD. The names of the constants correspond the the equivalent SGML constructs as described in "The SGML Handbook" by Charles F. Goldfarb.

See Also:
DTD, Element

Field Summary
static int | ANY
static int | CDATA
static int | CONREF
static int | CURRENT
static int | DEFAULT
static int | EMPTY
static int | ENDTAG
static int | ENTITIES
static int | ENTITY
static int | FIXED
static int | GENERAL
static int | ID
static int | IDREF
static int | IDREFS
static int | IMPLIED
static int | MD
static int | MODEL
static int | MS
static int | NAME
static int | NAMES
static int | NMTOKEN
static int | NMTOKENS
static int | NOTATION
static int | NUMBER
static int | NUMBERS
static int | NUTOKEN
static int | NUTOKENS
static int | PARAMETER
static int | PI
static int | PUBLIC
static int | RCDATA
static int | REQUIRED
static int | SDATA
static int | STARTTAG
static int | SYSTEM

Field Detail

CDATA

public static final int CDATA
See Also:
Constant Field Values

ENTITY

public static final int ENTITY
See Also:
Constant Field Values

ENTITIES

public static final int ENTITIES
See Also:
Constant Field Values

ID

public static final int ID
See Also:
Constant Field Values

IDREF

public static final int IDREF
See Also:
Constant Field Values

IDREFS

public static final int IDREFS
See Also:
Constant Field Values

NAME

public static final int NAME
See Also:
Constant Field Values

NAMES

public static final int NAMES
See Also:
Constant Field Values

NMTOKEN

public static final int NMTOKEN
See Also:
Constant Field Values

NMTOKENS

public static final int NMTOKENS
See Also:
Constant Field Values

NOTATION

public static final int NOTATION
See Also:
Constant Field Values

NUMBER

public static final int NUMBER
See Also:
Constant Field Values

NUMBERS

public static final int NUMBERS
See Also:
Constant Field Values

NUTOKEN

public static final int NUTOKEN
See Also:
Constant Field Values

NUTOKENS

public static final int NUTOKENS
See Also:
Constant Field Values

RCDATA

public static final int RCDATA
See Also:
Constant Field Values

EMPTY

public static final int EMPTY
See Also:
Constant Field Values

MODEL

public static final int MODEL
See Also:
Constant Field Values

ANY

public static final int ANY
See Also:
Constant Field Values

FIXED

public static final int FIXED
See Also:
Constant Field Values

REQUIRED

public static final int REQUIRED
See Also:
Constant Field Values

CURRENT

public static final int CURRENT
See Also:
Constant Field Values

CONREF

public static final int CONREF
See Also:
Constant Field Values

IMPLIED

public static final int IMPLIED
See Also:
Constant Field Values

PUBLIC

public static final int PUBLIC
See Also:
Constant Field Values

SDATA

public static final int SDATA
See Also:
Constant Field Values

PI

public static final int PI
See Also:
Constant Field Values

STARTTAG

public static final int STARTTAG
See Also:
Constant Field Values

ENDTAG

public static final int ENDTAG
See Also:
Constant Field Values

MS

public static final int MS
See Also:
Constant Field Values

MD

public static final int MD
See Also:
Constant Field Values

SYSTEM

public static final int SYSTEM
See Also:
Constant Field Values

GENERAL

public static final int GENERAL
See Also:
Constant Field Values

DEFAULT

public static final int DEFAULT
See Also:
Constant Field Values

PARAMETER

public static final int PARAMETER
See Also:
Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Element (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html.parser
Class Element

java.lang.Object
    extended by javax.swing.text.html.parser.Element
All Implemented Interfaces:
DTDConstants, Serializable
public final class Element
extends Object
implements DTDConstants, Serializable

An element as described in a DTD using the ELEMENT construct. This is essentiall the description of a tag. It describes the type, content model, attributes, attribute types etc. It is used to correctly parse a document by the Parser.

See Also:
DTD, AttributeList

Field Summary
AttributeList | atts
ContentModel | content
Object | data A field to store user data.
BitSet | exclusions
BitSet | inclusions
int | index
String | name
boolean | oEnd
boolean | oStart
int | type
Fields inherited from interface javax.swing.text.html.parser.DTDConstants
ANY, CDATA, CONREF, CURRENT, DEFAULT, EMPTY, ENDTAG, ENTITIES, ENTITY, FIXED, GENERAL, ID, IDREF, IDREFS, IMPLIED, MD, MODEL, MS, NAME, NAMES, NMTOKEN, NMTOKENS, NOTATION, NUMBER, NUMBERS, NUTOKEN, NUTOKENS, PARAMETER, PI, PUBLIC, RCDATA, REQUIRED, SDATA, STARTTAG, SYSTEM
Method Summary
AttributeList | getAttribute(String name) Get an attribute by name.
AttributeList | getAttributeByValue(String name) Get an attribute by value.
AttributeList | getAttributes() Get the attributes.
ContentModel | getContent() Get content model
int | getIndex() Get index.
String | getName() Get the name of the element.
int | getType() Get type.
boolean | isEmpty() Check if empty
static int | name2type(String nm)
boolean | omitEnd() Return true if the end tag can be omitted.
boolean | omitStart() Return true if the start tag can be omitted.
String | toString() Convert to a string.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

index

public int index

name

public String name

oStart

public boolean oStart

oEnd

public boolean oEnd

inclusions

public BitSet inclusions

exclusions

public BitSet exclusions

type

public int type

content

public ContentModel content

atts

public AttributeList atts

data

public Object data
A field to store user data. Mostly used to store style sheets.

Method Detail

getName

public String getName()
Get the name of the element.

omitStart

public boolean omitStart()
Return true if the start tag can be omitted.

omitEnd

public boolean omitEnd()
Return true if the end tag can be omitted.

getType

public int getType()
Get type.

getContent

public ContentModel getContent()
Get content model

getAttributes

public AttributeList getAttributes()
Get the attributes.

getIndex

public int getIndex()
Get index.

isEmpty

public boolean isEmpty()
Check if empty

toString

public String toString()
Convert to a string.

Overrides:
toString in class Object
Returns:
a string representation of the object.

getAttribute

public AttributeList getAttribute(String name)
Get an attribute by name.

getAttributeByValue

public AttributeList getAttributeByValue(String name)
Get an attribute by value.

name2type

public static int name2type(String nm)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Entity (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html.parser
Class Entity

java.lang.Object
    extended by javax.swing.text.html.parser.Entity
All Implemented Interfaces:
DTDConstants
public final class Entity
extends Object
implements DTDConstants

An entity is described in a DTD using the ENTITY construct. It defines the type and value of the the entity.

See Also:
DTD

Field Summary
char[] | data
String | name
int | type
Fields inherited from interface javax.swing.text.html.parser.DTDConstants
ANY, CDATA, CONREF, CURRENT, DEFAULT, EMPTY, ENDTAG, ENTITIES, ENTITY, FIXED, GENERAL, ID, IDREF, IDREFS, IMPLIED, MD, MODEL, MS, NAME, NAMES, NMTOKEN, NMTOKENS, NOTATION, NUMBER, NUMBERS, NUTOKEN, NUTOKENS, PARAMETER, PI, PUBLIC, RCDATA, REQUIRED, SDATA, STARTTAG, SYSTEM
Constructor Summary
Entity(String name, int type, char[] data)
Creates an entity.
Method Summary
char[] | getData() Returns the data.
String | getName() Gets the name of the entity.
String | getString() Returns the data as a String.
int | getType() Gets the type of the entity.
boolean | isGeneral() Returns true if it is a general entity.
boolean | isParameter() Returns true if it is a parameter entity.
static int | name2type(String nm) Converts nm string to the corresponding entity type.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

name

public String name

type

public int type

data

public char[] data
Constructor Detail

Entity

public Entity(String name,
              int type,
              char[] data)
Creates an entity.

Parameters:
name - the name of the entity
type - the type of the entity
data - the char array of data
Method Detail

getName

public String getName()
Gets the name of the entity.

Returns:
the name of the entity, as a String

getType

public int getType()
Gets the type of the entity.

Returns:
the type of the entity

isParameter

public boolean isParameter()
Returns true if it is a parameter entity.

Returns:
true if it is a parameter entity

isGeneral

public boolean isGeneral()
Returns true if it is a general entity.

Returns:
true if it is a general entity

getData

public char[] getData()
Returns the data.

Returns:
the data

getString

public String getString()
Returns the data as a String.

Returns:
the data as a String

name2type

public static int name2type(String nm)
Converts nm string to the corresponding entity type. If the string does not have a corresponding entity type, returns the type corresponding to "CDATA". Valid entity types are: "PUBLIC", "CDATA", "SDATA", "PI", "STARTTAG", "ENDTAG", "MS", "MD", "SYSTEM".

Parameters:
nm - the string to be converted
Returns:
the corresponding entity type, or the type corresponding to "CDATA", if none exists
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


javax.swing.text.html.parser (Java 2 Platform SE v1.4.2)

 javax.swing.text.html.parser
Interfaces
DTDConstants
Classes
AttributeList
ContentModel
DocumentParser
DTD
Element
Entity
Parser
ParserDelegator
TagElement


javax.swing.text.html.parser (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package javax.swing.text.html.parser

Provides the default HTML parser, along with support classes.

See:
Description

Interface Summary
DTDConstants SGML constants used in a DTD.

Class Summary
AttributeList | This class defines the attributes of an SGML element as described in a DTD using the ATTLIST construct.
ContentModel | A representation of a content model.
DocumentParser | A Parser for HTML Documents (actually, you can specify a DTD, but you should really only use this class with the html dtd in swing).
DTD | The representation of an SGML DTD.
Element | An element as described in a DTD using the ELEMENT construct.
Entity | An entity is described in a DTD using the ENTITY construct.
Parser | A simple DTD-driven HTML parser.
ParserDelegator | Responsible for starting up a new DocumentParser each time its parse method is invoked.
TagElement | A generic HTML TagElement class.

Package javax.swing.text.html.parser Description

Provides the default HTML parser, along with support classes. As the stream is parsed, the parser notifies a delegate, which must implement the HTMLEditorKit.ParserCallback interface.

Note: Most of the Swing API is not thread safe. For details, see Threads and Swing, a section in The Java Tutorial.

Since:
1.2
See Also:
HTMLEditorKit.ParserCallback
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


javax.swing.text.html.parser Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package javax.swing.text.html.parser

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class javax.swing.text.html.parser.AttributeList (implements javax.swing.text.html.parser.DTDConstants, java.io.Serializable)
    • class javax.swing.text.html.parser.ContentModel (implements java.io.Serializable)
    • class javax.swing.text.html.parser.DTD (implements javax.swing.text.html.parser.DTDConstants)
    • class javax.swing.text.html.parser.Element (implements javax.swing.text.html.parser.DTDConstants, java.io.Serializable)
    • class javax.swing.text.html.parser.Entity (implements javax.swing.text.html.parser.DTDConstants)
    • class javax.swing.text.html.HTMLEditorKit.Parser
      • class javax.swing.text.html.parser.ParserDelegator (implements java.io.Serializable)
    • class javax.swing.text.html.parser.Parser (implements javax.swing.text.html.parser.DTDConstants)
      • class javax.swing.text.html.parser.DocumentParser
    • class javax.swing.text.html.parser.TagElement

Interface Hierarchy

  • interface javax.swing.text.html.parser.DTDConstants
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package javax.swing.text.html.parser (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
javax.swing.text.html.parser

Packages that use javax.swing.text.html.parser
javax.swing.text.html.parser Provides the default HTML parser, along with support classes.

Classes in javax.swing.text.html.parser used by javax.swing.text.html.parser
AttributeList
This class defines the attributes of an SGML element as described in a DTD using the ATTLIST construct.
ContentModel
A representation of a content model.
DTD
The representation of an SGML DTD.
DTDConstants
SGML constants used in a DTD.
Element
An element as described in a DTD using the ELEMENT construct.
Entity
An entity is described in a DTD using the ENTITY construct.
Parser
A simple DTD-driven HTML parser.
TagElement
A generic HTML TagElement class.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Parser (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html.parser
Class Parser

java.lang.Object
    extended by javax.swing.text.html.parser.Parser
All Implemented Interfaces:
DTDConstants
Direct Known Subclasses:
DocumentParser
public class Parser
extends Object
implements DTDConstants

A simple DTD-driven HTML parser. The parser reads an HTML file from an InputStream and calls various methods (which should be overridden in a subclass) when tags and data are encountered.

Unfortunately there are many badly implemented HTML parsers out there, and as a result there are many badly formatted HTML files. This parser attempts to parse most HTML files. This means that the implementation sometimes deviates from the SGML specification in favor of HTML.

The parser treats \r and \r\n as \n. Newlines after starttags and before end tags are ignored just as specified in the SGML/HTML specification.

The html spec does not specify how spaces are to be coalesced very well. Specifically, the following scenarios are not discussed (note that a space should be used here, but I am using &nbsp to force the space to be displayed):

'<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>'

If strict is false, when a tag that breaks flow, (TagElement.breaksFlows) or trailing whitespace is encountered, all whitespace will be ignored until a non whitespace character is encountered. This appears to give behavior closer to the popular browsers.

See Also:
DTD, TagElement, SimpleAttributeSet

Field Summary
protected DTD | dtd
protected boolean | strict This flag determines whether or not the Parser will be strict in enforcing SGML compatibility.
Fields inherited from interface javax.swing.text.html.parser.DTDConstants
ANY, CDATA, CONREF, CURRENT, DEFAULT, EMPTY, ENDTAG, ENTITIES, ENTITY, FIXED, GENERAL, ID, IDREF, IDREFS, IMPLIED, MD, MODEL, MS, NAME, NAMES, NMTOKEN, NMTOKENS, NOTATION, NUMBER, NUMBERS, NUTOKEN, NUTOKENS, PARAMETER, PI, PUBLIC, RCDATA, REQUIRED, SDATA, STARTTAG, SYSTEM
Constructor Summary
Parser(DTD dtd)
Method Summary
protected void | endTag(boolean omitted) Handle an end tag.
protected void | error(String err)
protected void | error(String err, String arg1)
protected void | error(String err, String arg1, String arg2)
protected void | error(String err, String arg1, String arg2, String arg3) Invoke the error handler.
protected void | flushAttributes()
protected SimpleAttributeSet | getAttributes()
protected int | getCurrentLine()
protected int | getCurrentPos()
protected void | handleComment(char[] text) Called when an HTML comment is encountered.
protected void | handleEmptyTag(TagElement tag) Called when an empty tag is encountered.
protected void | handleEndTag(TagElement tag) Called when an end tag is encountered.
protected void | handleEOFInComment()
protected void | handleError(int ln, String msg) An error has occurred.
protected void | handleStartTag(TagElement tag) Called when a start tag is encountered.
protected void | handleText(char[] text) Called when PCDATA is encountered.
protected void | handleTitle(char[] text) Called when an HTML title tag is encountered.
protected TagElement | makeTag(Element elem)
protected TagElement | makeTag(Element elem, boolean fictional) Makes a TagElement.
protected void | markFirstTime(Element elem) Marks the first time a tag has been seen in a document
void | parse(Reader in) Parse an HTML stream, given a DTD.
String | parseDTDMarkup() Parses th Document Declaration Type markup declaration.
protected boolean | parseMarkupDeclarations(StringBuffer strBuff) Parse markup declarations.
protected void | startTag(TagElement tag) Handle a start tag.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

dtd

protected DTD dtd

strict

protected boolean strict
This flag determines whether or not the Parser will be strict in enforcing SGML compatibility. If false, it will be lenient with certain common classes of erroneous HTML constructs. Strict or not, in either case an error will be recorded.

Constructor Detail

Parser

public Parser(DTD dtd)
Method Detail

getCurrentLine

protected int getCurrentLine()
Returns:
the line number of the line currently being parsed

makeTag

protected TagElement makeTag(Element elem,
                             boolean fictional)
Makes a TagElement.

makeTag

protected TagElement makeTag(Element elem)

getAttributes

protected SimpleAttributeSet getAttributes()

flushAttributes

protected void flushAttributes()

handleText

protected void handleText(char[] text)
Called when PCDATA is encountered.

handleTitle

protected void handleTitle(char[] text)
Called when an HTML title tag is encountered.

handleComment

protected void handleComment(char[] text)
Called when an HTML comment is encountered.

handleEOFInComment

protected void handleEOFInComment()

handleEmptyTag

protected void handleEmptyTag(TagElement tag)
                       throws ChangedCharSetException
Called when an empty tag is encountered.

Throws:
ChangedCharSetException

handleStartTag

protected void handleStartTag(TagElement tag)
Called when a start tag is encountered.

handleEndTag

protected void handleEndTag(TagElement tag)
Called when an end tag is encountered.

handleError

protected void handleError(int ln,
                           String msg)
An error has occurred.

error

protected void error(String err,
                     String arg1,
                     String arg2,
                     String arg3)
Invoke the error handler.

error

protected void error(String err,
                     String arg1,
                     String arg2)

error

protected void error(String err,
                     String arg1)

error

protected void error(String err)

startTag

protected void startTag(TagElement tag)
                 throws ChangedCharSetException
Handle a start tag. The new tag is pushed onto the tag stack. The attribute list is checked for required attributes.

Throws:
ChangedCharSetException

endTag

protected void endTag(boolean omitted)
Handle an end tag. The end tag is popped from the tag stack.

markFirstTime

protected void markFirstTime(Element elem)
Marks the first time a tag has been seen in a document

parseDTDMarkup

public String parseDTDMarkup()
                      throws IOException
Parses th Document Declaration Type markup declaration. Currently ignores it.

Throws:
IOException

parseMarkupDeclarations

protected boolean parseMarkupDeclarations(StringBuffer strBuff)
                                   throws IOException
Parse markup declarations. Currently only handles the Document Type Declaration markup. Returns true if it is a markup declaration false otherwise.

Throws:
IOException

parse

public void parse(Reader in)
           throws IOException
Parse an HTML stream, given a DTD.

Throws:
IOException

getCurrentPos

protected int getCurrentPos()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ParserDelegator (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html.parser
Class ParserDelegator

java.lang.Object
    extended by javax.swing.text.html.HTMLEditorKit.Parser
        extended by javax.swing.text.html.parser.ParserDelegator
All Implemented Interfaces:
Serializable
public class ParserDelegator
extends HTMLEditorKit.Parser
implements Serializable

Responsible for starting up a new DocumentParser each time its parse method is invoked. Stores a reference to the dtd.

Constructor Summary
ParserDelegator()
Method Summary
protected static DTD | createDTD(DTD dtd, String name)
void | parse(Reader r, HTMLEditorKit.ParserCallback cb, boolean ignoreCharSet) Parse the given stream and drive the given callback with the results of the parse.
protected static void | setDefaultDTD()
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ParserDelegator

public ParserDelegator()
Method Detail

setDefaultDTD

protected static void setDefaultDTD()

createDTD

protected static DTD createDTD(DTD dtd,
                               String name)

parse

public void parse(Reader r,
                  HTMLEditorKit.ParserCallback cb,
                  boolean ignoreCharSet)
           throws IOException
Description copied from class: HTMLEditorKit.Parser
Parse the given stream and drive the given callback with the results of the parse. This method should be implemented to be thread-safe.

Specified by:
parse in class HTMLEditorKit.Parser
Throws:
IOException
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TagElement (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html.parser
Class TagElement

java.lang.Object
    extended by javax.swing.text.html.parser.TagElement
public class TagElement
extends Object

A generic HTML TagElement class. The methods define how white space is interpreted around the tag.

Constructor Summary
TagElement(Element elem)
TagElement(Element elem, boolean fictional)
Method Summary
boolean | breaksFlow()
boolean | fictional()
Element | getElement()
HTML.Tag | getHTMLTag()
boolean | isPreformatted()
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

TagElement

public TagElement(Element elem)

TagElement

public TagElement(Element elem,
                  boolean fictional)
Method Detail

breaksFlow

public boolean breaksFlow()

isPreformatted

public boolean isPreformatted()

getElement

public Element getElement()

getHTMLTag

public HTML.Tag getHTMLTag()

fictional

public boolean fictional()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Uses of Class javax.swing.text.html.parser.AttributeList (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.parser.AttributeList

Packages that use AttributeList
javax.swing.text.html.parser Provides the default HTML parser, along with support classes.

Uses of AttributeList in javax.swing.text.html.parser

Fields in javax.swing.text.html.parser declared as AttributeList
AttributeList | Element.atts
AttributeList | AttributeList.next

Methods in javax.swing.text.html.parser that return AttributeList
protected AttributeList | DTD.defAttributeList(String name, int type, int modifier, String value, String values, AttributeList atts) Creates and returns an AttributeList.
AttributeList | Element.getAttributes() Get the attributes.
AttributeList | Element.getAttribute(String name) Get an attribute by name.
AttributeList | Element.getAttributeByValue(String name) Get an attribute by value.
AttributeList | AttributeList.getNext()

Methods in javax.swing.text.html.parser with parameters of type AttributeList
Element | DTD.defineElement(String name, int type, boolean omitStart, boolean omitEnd, ContentModel content, BitSet exclusions, BitSet inclusions, AttributeList atts) Returns the Element which matches the specified parameters.
void | DTD.defineAttributes(String name, AttributeList atts) Returns the Element which matches the specified AttributeList.
protected Element | DTD.defElement(String name, int type, boolean omitStart, boolean omitEnd, ContentModel content, String[] exclusions, String[] inclusions, AttributeList atts) Creates and returns an Element.
protected AttributeList | DTD.defAttributeList(String name, int type, int modifier, String value, String values, AttributeList atts) Creates and returns an AttributeList.

Constructors in javax.swing.text.html.parser with parameters of type AttributeList
AttributeList(String name, int type, int modifier, String value, Vector values, AttributeList next)
Create an attribute list element.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.parser.ContentModel (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.parser.ContentModel

Packages that use ContentModel
javax.swing.text.html.parser Provides the default HTML parser, along with support classes.

Uses of ContentModel in javax.swing.text.html.parser

Fields in javax.swing.text.html.parser declared as ContentModel
ContentModel | Element.content
ContentModel | ContentModel.next The next content model (in a ',', '|' or '&' expression).

Methods in javax.swing.text.html.parser that return ContentModel
protected ContentModel | DTD.defContentModel(int type, Object obj, ContentModel next) Creates and returns a new content model.
ContentModel | Element.getContent() Get content model

Methods in javax.swing.text.html.parser with parameters of type ContentModel
Element | DTD.defineElement(String name, int type, boolean omitStart, boolean omitEnd, ContentModel content, BitSet exclusions, BitSet inclusions, AttributeList atts) Returns the Element which matches the specified parameters.
protected Element | DTD.defElement(String name, int type, boolean omitStart, boolean omitEnd, ContentModel content, String[] exclusions, String[] inclusions, AttributeList atts) Creates and returns an Element.
protected ContentModel | DTD.defContentModel(int type, Object obj, ContentModel next) Creates and returns a new content model.

Constructors in javax.swing.text.html.parser with parameters of type ContentModel
ContentModel(int type, ContentModel content)
Create a content model of a particular type.
ContentModel(int type, Object content, ContentModel next)
Create a content model of a particular type.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.parser.DocumentParser (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.parser.DocumentParser

No usage of javax.swing.text.html.parser.DocumentParser

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.parser.DTD (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.parser.DTD

Packages that use DTD
javax.swing.text.html.parser Provides the default HTML parser, along with support classes.

Uses of DTD in javax.swing.text.html.parser

Fields in javax.swing.text.html.parser declared as DTD
protected  DTD Parser.dtd

Methods in javax.swing.text.html.parser that return DTD
protected static DTD | ParserDelegator.createDTD(DTD dtd, String name)
static DTD | DTD.getDTD(String name) Returns a DTD with the specified name.

Methods in javax.swing.text.html.parser with parameters of type DTD
protected static DTD | ParserDelegator.createDTD(DTD dtd, String name)
static void | DTD.putDTDHash(String name, DTD dtd)

Constructors in javax.swing.text.html.parser with parameters of type DTD
Parser(DTD dtd)
DocumentParser(DTD dtd)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.swing.text.html.parser.DTDConstants (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.swing.text.html.parser.DTDConstants

Packages that use DTDConstants
javax.swing.text.html.parser Provides the default HTML parser, along with support classes.

Uses of DTDConstants in javax.swing.text.html.parser

Classes in javax.swing.text.html.parser that implement DTDConstants
class | AttributeList This class defines the attributes of an SGML element as described in a DTD using the ATTLIST construct.
class | DocumentParser A Parser for HTML Documents (actually, you can specify a DTD, but you should really only use this class with the html dtd in swing).
class | DTD The representation of an SGML DTD.
class | Element An element as described in a DTD using the ELEMENT construct.
class | Entity An entity is described in a DTD using the ENTITY construct.
class | Parser A simple DTD-driven HTML parser.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.parser.Element (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.parser.Element

Packages that use Element
javax.swing.text.html.parser Provides the default HTML parser, along with support classes.

Uses of Element in javax.swing.text.html.parser

Fields in javax.swing.text.html.parser declared as Element
Element | DTD.pcdata
Element | DTD.html
Element | DTD.meta
Element | DTD.base
Element | DTD.isindex
Element | DTD.head
Element | DTD.body
Element | DTD.applet
Element | DTD.param
Element | DTD.p
Element | DTD.title

Methods in javax.swing.text.html.parser that return Element
Element | TagElement.getElement()
Element | DTD.getElement(String name) Gets an element by name.
Element | DTD.getElement(int index) Gets an element by index.
Element | DTD.defineElement(String name, int type, boolean omitStart, boolean omitEnd, ContentModel content, BitSet exclusions, BitSet inclusions, AttributeList atts) Returns the Element which matches the specified parameters.
protected Element | DTD.defElement(String name, int type, boolean omitStart, boolean omitEnd, ContentModel content, String[] exclusions, String[] inclusions, AttributeList atts) Creates and returns an Element.
Element | ContentModel.first() Return the element that must be next.

Methods in javax.swing.text.html.parser with parameters of type Element
protected TagElement | Parser.makeTag(Element elem, boolean fictional) Makes a TagElement.
protected TagElement | Parser.makeTag(Element elem)
protected void | Parser.markFirstTime(Element elem) Marks the first time a tag has been seen in a document

Constructors in javax.swing.text.html.parser with parameters of type Element
TagElement(Element elem)
TagElement(Element elem, boolean fictional)
ContentModel(Element content)
Create a content model for an element.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.parser.Entity (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.parser.Entity

Packages that use Entity
javax.swing.text.html.parser Provides the default HTML parser, along with support classes.

Uses of Entity in javax.swing.text.html.parser

Methods in javax.swing.text.html.parser that return Entity
Entity | DTD.getEntity(String name) Gets an entity by name.
Entity | DTD.getEntity(int ch) Gets a character entity.
Entity | DTD.defineEntity(String name, int type, char[] data) Defines an entity.
Entity | DTD.defEntity(String name, int type, int ch) Creates and returns a character Entity.
protected Entity | DTD.defEntity(String name, int type, String str) Creates and returns an Entity.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.parser.Parser (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.parser.Parser

Packages that use Parser
javax.swing.text.html.parser Provides the default HTML parser, along with support classes.

Uses of Parser in javax.swing.text.html.parser

Subclasses of Parser in javax.swing.text.html.parser
 class DocumentParser
A Parser for HTML Documents (actually, you can specify a DTD, but you should really only use this class with the html dtd in swing).

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.parser.ParserDelegator (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.parser.ParserDelegator

No usage of javax.swing.text.html.parser.ParserDelegator

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.text.html.parser.TagElement (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.html.parser.TagElement

Packages that use TagElement
javax.swing.text.html.parser Provides the default HTML parser, along with support classes.

Uses of TagElement in javax.swing.text.html.parser

Methods in javax.swing.text.html.parser that return TagElement
protected TagElement | Parser.makeTag(Element elem, boolean fictional) Makes a TagElement.
protected TagElement | Parser.makeTag(Element elem)

Methods in javax.swing.text.html.parser with parameters of type TagElement
protected void | Parser.handleEmptyTag(TagElement tag) Called when an empty tag is encountered.
protected void | Parser.handleStartTag(TagElement tag) Called when a start tag is encountered.
protected void | Parser.handleEndTag(TagElement tag) Called when an end tag is encountered.
protected void | Parser.startTag(TagElement tag) Handle a start tag.
protected void | DocumentParser.handleStartTag(TagElement tag) Handle Start Tag.
protected void | DocumentParser.handleEmptyTag(TagElement tag) Handle Empty Tag.
protected void | DocumentParser.handleEndTag(TagElement tag) Handle End Tag.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


javax.swing.text.rtf (Java 2 Platform SE v1.4.2)

 javax.swing.text.rtf
Classes
RTFEditorKit


javax.swing.text.rtf (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package javax.swing.text.rtf

Provides a class (RTFEditorKit) for creating Rich-Text-Format text editors.

See:
Description

Class Summary
RTFEditorKit This is the default implementation of RTF editing functionality.

Package javax.swing.text.rtf Description

Provides a class (RTFEditorKit) for creating Rich-Text-Format text editors.

Note: Most of the Swing API is not thread safe. For details, see Threads and Swing, a section in The Java Tutorial.

Since:
1.2
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


javax.swing.text.rtf Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package javax.swing.text.rtf

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class javax.swing.text.EditorKit (implements java.lang.Cloneable, java.io.Serializable)
      • class javax.swing.text.DefaultEditorKit
        • class javax.swing.text.StyledEditorKit
          • class javax.swing.text.rtf.RTFEditorKit
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package javax.swing.text.rtf (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
javax.swing.text.rtf

No usage of javax.swing.text.rtf

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


RTFEditorKit (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.rtf
Class RTFEditorKit

java.lang.Object
    extended by javax.swing.text.EditorKit
        extended by javax.swing.text.DefaultEditorKit
            extended by javax.swing.text.StyledEditorKit
                extended by javax.swing.text.rtf.RTFEditorKit
All Implemented Interfaces:
Cloneable, Serializable
public class RTFEditorKit
extends StyledEditorKit

This is the default implementation of RTF editing functionality. The RTF support was not written by the Swing team. In the future we hope to improve the support provided.

Nested Class Summary
Nested classes inherited from class javax.swing.text.StyledEditorKit
StyledEditorKit.AlignmentAction, StyledEditorKit.BoldAction, StyledEditorKit.FontFamilyAction, StyledEditorKit.FontSizeAction, StyledEditorKit.ForegroundAction, StyledEditorKit.ItalicAction, StyledEditorKit.StyledTextAction, StyledEditorKit.UnderlineAction
Nested classes inherited from class javax.swing.text.DefaultEditorKit
DefaultEditorKit.BeepAction, DefaultEditorKit.CopyAction, DefaultEditorKit.CutAction, DefaultEditorKit.DefaultKeyTypedAction, DefaultEditorKit.InsertBreakAction, DefaultEditorKit.InsertContentAction, DefaultEditorKit.InsertTabAction, DefaultEditorKit.PasteAction
Field Summary
Fields inherited from class javax.swing.text.DefaultEditorKit
backwardAction, beepAction, beginAction, beginLineAction, beginParagraphAction, beginWordAction, copyAction, cutAction, defaultKeyTypedAction, deleteNextCharAction, deletePrevCharAction, downAction, endAction, endLineAction, EndOfLineStringProperty, endParagraphAction, endWordAction, forwardAction, insertBreakAction, insertContentAction, insertTabAction, nextWordAction, pageDownAction, pageUpAction, pasteAction, previousWordAction, readOnlyAction, selectAllAction, selectionBackwardAction, selectionBeginAction, selectionBeginLineAction, selectionBeginParagraphAction, selectionBeginWordAction, selectionDownAction, selectionEndAction, selectionEndLineAction, selectionEndParagraphAction, selectionEndWordAction, selectionForwardAction, selectionNextWordAction, selectionPreviousWordAction, selectionUpAction, selectLineAction, selectParagraphAction, selectWordAction, upAction, writableAction
Constructor Summary
RTFEditorKit()
Constructs an RTFEditorKit.
Method Summary
String | getContentType() Get the MIME type of the data that this kit represents support for.
void | read(InputStream in, Document doc, int pos) Insert content from the given stream which is expected to be in a format appropriate for this kind of content handler.
void | read(Reader in, Document doc, int pos) Insert content from the given stream, which will be treated as plain text.
void | write(OutputStream out, Document doc, int pos, int len) Write content from a document to the given stream in a format appropriate for this kind of content handler.
void | write(Writer out, Document doc, int pos, int len) Write content from a document to the given stream as plain text.
Methods inherited from class javax.swing.text.StyledEditorKit
clone, createDefaultDocument, createInputAttributes, deinstall, getActions, getCharacterAttributeRun, getInputAttributes, getViewFactory, install
Methods inherited from class javax.swing.text.DefaultEditorKit
createCaret
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

RTFEditorKit

public RTFEditorKit()
Constructs an RTFEditorKit.

Method Detail

getContentType

public String getContentType()
Get the MIME type of the data that this kit represents support for. This kit supports the type text/rtf.

Overrides:
getContentType in class DefaultEditorKit
Returns:
the type

read

public void read(InputStream in,
                 Document doc,
                 int pos)
          throws IOException,
                 BadLocationException
Insert content from the given stream which is expected to be in a format appropriate for this kind of content handler.

Overrides:
read in class DefaultEditorKit
Parameters:
in - The stream to read from
doc - The destination for the insertion.
pos - The location in the document to place the content.
Throws:
IOException - on any I/O error
BadLocationException - if pos represents an invalid location within the document.

write

public void write(OutputStream out,
                  Document doc,
                  int pos,
                  int len)
           throws IOException,
                  BadLocationException
Write content from a document to the given stream in a format appropriate for this kind of content handler.

Overrides:
write in class DefaultEditorKit
Parameters:
out - The stream to write to
doc - The source for the write.
pos - The location in the document to fetch the content.
len - The amount to write out.
Throws:
IOException - on any I/O error
BadLocationException - if pos represents an invalid location within the document.

read

public void read(Reader in,
                 Document doc,
                 int pos)
          throws IOException,
                 BadLocationException
Insert content from the given stream, which will be treated as plain text.

Overrides:
read in class DefaultEditorKit
Parameters:
in - The stream to read from
doc - The destination for the insertion.
pos - The location in the document to place the content.
Throws:
IOException - on any I/O error
BadLocationException - if pos represents an invalid location within the document.

write

public void write(Writer out,
                  Document doc,
                  int pos,
                  int len)
           throws IOException,
                  BadLocationException
Write content from a document to the given stream as plain text.

Overrides:
write in class DefaultEditorKit
Parameters:
out - The stream to write to
doc - The source for the write.
pos - The location in the document to fetch the content.
len - The amount to write out.
Throws:
IOException - on any I/O error
BadLocationException - if pos represents an invalid location within the document.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Uses of Class javax.swing.text.rtf.RTFEditorKit (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.text.rtf.RTFEditorKit

No usage of javax.swing.text.rtf.RTFEditorKit

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


AbstractLayoutCache (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.swing.tree
Class AbstractLayoutCache

java.lang.Object
    extended by javax.swing.tree.AbstractLayoutCache
All Implemented Interfaces:
RowMapper
Direct Known Subclasses:
FixedHeightLayoutCache, VariableHeightLayoutCache
public abstract class AbstractLayoutCache
extends Object
implements RowMapper

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Nested Class Summary
static class AbstractLayoutCache.NodeDimensions
Used by AbstractLayoutCache to determine the size and x origin of a particular node.
Field Summary
protected AbstractLayoutCache.NodeDimensions | nodeDimensions Object responsible for getting the size of a node.
protected boolean | rootVisible True if the root node is displayed, false if its children are the highest visible nodes.
protected int | rowHeight Height to use for each row.
protected TreeModel | treeModel Model providing information.
protected TreeSelectionModel | treeSelectionModel Selection model.
Constructor Summary
AbstractLayoutCache()
Method Summary
abstract Rectangle | getBounds(TreePath path, Rectangle placeIn) Returns a rectangle giving the bounds needed to draw path.
abstract boolean | getExpandedState(TreePath path) Returns true if the path is expanded, and visible.
TreeModel | getModel() Returns the TreeModel that is providing the data.
AbstractLayoutCache.NodeDimensions | getNodeDimensions() Returns the object that renders nodes in the tree, and which is responsible for calculating the dimensions of individual nodes.
protected Rectangle | getNodeDimensions(Object value, int row, int depth, boolean expanded, Rectangle placeIn) Returns, by reference in placeIn, the size needed to represent value.
abstract TreePath | getPathClosestTo(int x, int y) Returns the path to the node that is closest to x,y.
abstract TreePath | getPathForRow(int row) Returns the path for passed in row.
int | getPreferredHeight() Returns the preferred height.
int | getPreferredWidth(Rectangle bounds) Returns the preferred width for the passed in region.
abstract int | getRowCount() Number of rows being displayed.
abstract int | getRowForPath(TreePath path) Returns the row that the last item identified in path is visible at.
int | getRowHeight() Returns the height of each row.
int[] | getRowsForPaths(TreePath[] paths) Returns the rows that the TreePath instances in path are being displayed at.
TreeSelectionModel | getSelectionModel() Returns the model used to maintain the selection.
abstract int | getVisibleChildCount(TreePath path) Returns the number of visible children for row.
abstract Enumeration | getVisiblePathsFrom(TreePath path) Returns an Enumerator that increments over the visible paths starting at the passed in location.
abstract void | invalidatePathBounds(TreePath path) Instructs the LayoutCache that the bounds for path are invalid, and need to be updated.
abstract void | invalidateSizes() Informs the TreeState that it needs to recalculate all the sizes it is referencing.
abstract boolean | isExpanded(TreePath path) Returns true if the value identified by row is currently expanded.
protected boolean | isFixedRowHeight() Returns true if the height of each row is a fixed size.
boolean | isRootVisible() Returns true if the root node of the tree is displayed.
abstract void | setExpandedState(TreePath path, boolean isExpanded) Marks the path path expanded state to isExpanded.
void | setModel(TreeModel newModel) Sets the TreeModel that will provide the data.
void | setNodeDimensions(AbstractLayoutCache.NodeDimensions nd) Sets the renderer that is responsible for drawing nodes in the tree and which is threfore responsible for calculating the dimensions of individual nodes.
void | setRootVisible(boolean rootVisible) Determines whether or not the root node from the TreeModel is visible.
void | setRowHeight(int rowHeight) Sets the height of each cell.
void | setSelectionModel(TreeSelectionModel newLSM) Sets the TreeSelectionModel used to manage the selection to new LSM.
abstract void | treeNodesChanged(TreeModelEvent e) Invoked after a node (or a set of siblings) has changed in some way.
abstract void | treeNodesInserted(TreeModelEvent e) Invoked after nodes have been inserted into the tree.
abstract void | treeNodesRemoved(TreeModelEvent e) Invoked after nodes have been removed from the tree.
abstract void | treeStructureChanged(TreeModelEvent e) Invoked after the tree has drastically changed structure from a given node down.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

nodeDimensions

protected AbstractLayoutCache.NodeDimensions nodeDimensions
Object responsible for getting the size of a node.

treeModel

protected TreeModel treeModel
Model providing information.

treeSelectionModel

protected TreeSelectionModel treeSelectionModel
Selection model.

rootVisible

protected boolean rootVisible
True if the root node is displayed, false if its children are the highest visible nodes.

rowHeight

protected int rowHeight
Height to use for each row. If this is <= 0 the renderer will be used to determine the height for each row.

Constructor Detail

AbstractLayoutCache

public AbstractLayoutCache()
Method Detail

setNodeDimensions

public void setNodeDimensions(AbstractLayoutCache.NodeDimensions nd)
Sets the renderer that is responsible for drawing nodes in the tree and which is threfore responsible for calculating the dimensions of individual nodes.

Parameters:
nd - a NodeDimensions object

getNodeDimensions

public AbstractLayoutCache.NodeDimensions getNodeDimensions()
Returns the object that renders nodes in the tree, and which is responsible for calculating the dimensions of individual nodes.

Returns:
the NodeDimensions object

setModel

public void setModel(TreeModel newModel)
Sets the TreeModel that will provide the data.

Parameters:
newModel - the TreeModel that is to provide the data

getModel

public TreeModel getModel()
Returns the TreeModel that is providing the data.

Returns:
the TreeModel that is providing the data

setRootVisible

public void setRootVisible(boolean rootVisible)
Determines whether or not the root node from the TreeModel is visible.

Parameters:
rootVisible - true if the root node of the tree is to be displayed
See Also:
rootVisible

isRootVisible

public boolean isRootVisible()
Returns true if the root node of the tree is displayed.

Returns:
true if the root node of the tree is displayed
See Also:
rootVisible

setRowHeight

public void setRowHeight(int rowHeight)
Sets the height of each cell. If the specified value is less than or equal to zero the current cell renderer is queried for each row's height.

Parameters:
rowHeight - the height of each cell, in pixels

getRowHeight

public int getRowHeight()
Returns the height of each row. If the returned value is less than or equal to 0 the height for each row is determined by the renderer.

setSelectionModel

public void setSelectionModel(TreeSelectionModel newLSM)
Sets the TreeSelectionModel used to manage the selection to new LSM.

Parameters:
newLSM - the new TreeSelectionModel

getSelectionModel

public TreeSelectionModel getSelectionModel()
Returns the model used to maintain the selection.

Returns:
the treeSelectionModel

getPreferredHeight

public int getPreferredHeight()
Returns the preferred height.

Returns:
the preferred height

getPreferredWidth

public int getPreferredWidth(Rectangle bounds)
Returns the preferred width for the passed in region. The region is defined by the path closest to (bounds.x, bounds.y) and ends at bounds.height + bounds.y. If bounds is null, the preferred width for all the nodes will be returned (and this may be a VERY expensive computation).

Parameters:
bounds - the region being queried
Returns:
the preferred width for the passed in region

isExpanded

public abstract boolean isExpanded(TreePath path)
Returns true if the value identified by row is currently expanded.

getBounds

public abstract Rectangle getBounds(TreePath path,
                                    Rectangle placeIn)
Returns a rectangle giving the bounds needed to draw path.

Parameters:
path - a TreePath specifying a node
placeIn - a Rectangle object giving the available space
Returns:
a Rectangle object specifying the space to be used

getPathForRow

public abstract TreePath getPathForRow(int row)
Returns the path for passed in row. If row is not visible null is returned.

Parameters:
row - the row being queried
Returns:
the TreePath for the given row

getRowForPath

public abstract int getRowForPath(TreePath path)
Returns the row that the last item identified in path is visible at. Will return -1 if any of the elements in path are not currently visible.

Parameters:
path - the TreePath being queried
Returns:
the row where the last item in path is visible or -1 if any elements in path aren't currently visible

getPathClosestTo

public abstract TreePath getPathClosestTo(int x,
                                          int y)
Returns the path to the node that is closest to x,y. If there is nothing currently visible this will return null, otherwise it'll always return a valid path. If you need to test if the returned object is exactly at x, y you should get the bounds for the returned path and test x, y against that.

Parameters:
x - the horizontal component of the desired location
y - the vertical component of the desired location
Returns:
the TreePath closest to the specified point

getVisiblePathsFrom

public abstract Enumeration getVisiblePathsFrom(TreePath path)
Returns an Enumerator that increments over the visible paths starting at the passed in location. The ordering of the enumeration is based on how the paths are displayed. The first element of the returned enumeration will be path, unless it isn't visible, in which case null will be returned.

Parameters:
path - the starting location for the enumeration
Returns:
the Enumerator starting at the desired location

getVisibleChildCount

public abstract int getVisibleChildCount(TreePath path)
Returns the number of visible children for row.

Parameters:
path - the path being queried
Returns:
the number of visible children for the specified path

setExpandedState

public abstract void setExpandedState(TreePath path,
                                      boolean isExpanded)
Marks the path path expanded state to isExpanded.

Parameters:
path - the path being expanded or collapsed
isExpanded - true if the path should be expanded, false otherwise

getExpandedState

public abstract boolean getExpandedState(TreePath path)
Returns true if the path is expanded, and visible.

Parameters:
path - the path being queried
Returns:
true if the path is expanded and visible, false otherwise

getRowCount

public abstract int getRowCount()
Number of rows being displayed.

Returns:
the number of rows being displayed

invalidateSizes

public abstract void invalidateSizes()
Informs the TreeState that it needs to recalculate all the sizes it is referencing.

invalidatePathBounds

public abstract void invalidatePathBounds(TreePath path)
Instructs the LayoutCache that the bounds for path are invalid, and need to be updated.

Parameters:
path - the path being updated

treeNodesChanged

public abstract void treeNodesChanged(TreeModelEvent e)

Invoked after a node (or a set of siblings) has changed in some way. The node(s) have not changed locations in the tree or altered their children arrays, but other attributes have changed and may affect presentation. Example: the name of a file has changed, but it is in the same location in the file system.

e.path() returns the path the parent of the changed node(s).

e.childIndices() returns the index(es) of the changed node(s).

Parameters:
e - the TreeModelEvent

treeNodesInserted

public abstract void treeNodesInserted(TreeModelEvent e)

Invoked after nodes have been inserted into the tree.

e.path() returns the parent of the new nodes

e.childIndices() returns the indices of the new nodes in ascending order.

Parameters:
e - the TreeModelEvent

treeNodesRemoved

public abstract void treeNodesRemoved(TreeModelEvent e)

Invoked after nodes have been removed from the tree. Note that if a subtree is removed from the tree, this method may only be invoked once for the root of the removed subtree, not once for each individual set of siblings removed.

e.path() returns the former parent of the deleted nodes.

e.childIndices() returns the indices the nodes had before they were deleted in ascending order.

Parameters:
e - the TreeModelEvent

treeStructureChanged

public abstract void treeStructureChanged(TreeModelEvent e)

Invoked after the tree has drastically changed structure from a given node down. If the path returned by e.getPath() is of length one and the first element does not identify the current root node the first element should become the new root of the tree.

e.path() holds the path to the node.

e.childIndices() returns null.

Parameters:
e - the TreeModelEvent

getRowsForPaths

public int[] getRowsForPaths(TreePath[] paths)
Returns the rows that the TreePath instances in path are being displayed at. This method should return an array of the same length as that passed in, and if one of the TreePaths in path is not valid its entry in the array should be set to -1.

Specified by:
getRowsForPaths in interface RowMapper
Parameters:
paths - the array of TreePaths being queried
Returns:
an array of the same length that is passed in containing the rows that each corresponding where each TreePath is displayed; if paths is null, null is returned

getNodeDimensions

protected Rectangle getNodeDimensions(Object value,
                                      int row,
                                      int depth,
                                      boolean expanded,
                                      Rectangle placeIn)
Returns, by reference in placeIn, the size needed to represent value. If inPlace is null, a newly created Rectangle should be returned, otherwise the value should be placed in inPlace and returned. This will return null if there is no renderer.

Parameters:
value - the value to be represented
row - row being queried
depth - the depth of the row
expanded - true if row is expanded, false otherwise
placeIn - a Rectangle containing the size needed to represent value
Returns:
a Rectangle containing the node dimensions, or null if node has no dimension

isFixedRowHeight

protected boolean isFixedRowHeight()
Returns true if the height of each row is a fixed size.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


AbstractLayoutCache.NodeDimensions (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.tree
Class AbstractLayoutCache.NodeDimensions

java.lang.Object
    extended by javax.swing.tree.AbstractLayoutCache.NodeDimensions
Direct Known Subclasses:
BasicTreeUI.NodeDimensionsHandler
Enclosing class:
AbstractLayoutCache
public abstract static class AbstractLayoutCache.NodeDimensions
extends Object

Used by AbstractLayoutCache to determine the size and x origin of a particular node.

Constructor Summary
AbstractLayoutCache.NodeDimensions()
Method Summary
abstract  Rectangle getNodeDimensions(Object value, int row, int depth, boolean expanded, Rectangle bounds)
Returns, by reference in bounds, the size and x origin to place value at.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

AbstractLayoutCache.NodeDimensions

public AbstractLayoutCache.NodeDimensions()
Method Detail

getNodeDimensions

public abstract Rectangle getNodeDimensions(Object value,
                                            int row,
                                            int depth,
                                            boolean expanded,
                                            Rectangle bounds)
Returns, by reference in bounds, the size and x origin to place value at. The calling method is responsible for determining the Y location. If bounds is null, a newly created Rectangle should be returned, otherwise the value should be placed in bounds and returned.

Parameters:
value - the value to be represented
row - row being queried
depth - the depth of the row
expanded - true if row is expanded, false otherwise
bounds - a Rectangle containing the size needed to represent value
Returns:
a Rectangle containing the node dimensions, or null if node has no dimension
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DefaultMutableTreeNode (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.tree
Class DefaultMutableTreeNode

java.lang.Object
    extended by javax.swing.tree.DefaultMutableTreeNode
All Implemented Interfaces:
Cloneable, MutableTreeNode, Serializable, TreeNode
Direct Known Subclasses:
JTree.DynamicUtilTreeNode
public class DefaultMutableTreeNode
extends Object
implements Cloneable, MutableTreeNode, Serializable

A DefaultMutableTreeNode is a general-purpose node in a tree data structure. For examples of using default mutable tree nodes, see How to Use Trees in The Java Tutorial.

A tree node may have at most one parent and 0 or more children. DefaultMutableTreeNode provides operations for examining and modifying a node's parent and children and also operations for examining the tree that the node is a part of. A node's tree is the set of all nodes that can be reached by starting at the node and following all the possible links to parents and children. A node with no parent is the root of its tree; a node with no children is a leaf. A tree may consist of many subtrees, each node acting as the root for its own subtree.

This class provides enumerations for efficiently traversing a tree or subtree in various orders or for following the path between two nodes. A DefaultMutableTreeNode may also hold a reference to a user object, the use of which is left to the user. Asking a DefaultMutableTreeNode for its string representation with toString() returns the string representation of its user object.

This is not a thread safe class.If you intend to use a DefaultMutableTreeNode (or a tree of TreeNodes) in more than one thread, you need to do your own synchronizing. A good convention to adopt is synchronizing on the root node of a tree.

While DefaultMutableTreeNode implements the MutableTreeNode interface and will allow you to add in any implementation of MutableTreeNode not all of the methods in DefaultMutableTreeNode will be applicable to all MutableTreeNodes implementations. Especially with some of the enumerations that are provided, using some of these methods assumes the DefaultMutableTreeNode contains only DefaultMutableNode instances. All of the TreeNode/MutableTreeNode methods will behave as defined no matter what implementations are added.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

See Also:
MutableTreeNode

Field Summary
protected boolean | allowsChildren true if the node is able to have children
protected Vector | children array of children, may be null if this node has no children
static Enumeration | EMPTY_ENUMERATION An enumeration that is always empty.
protected MutableTreeNode | parent this node's parent, or null if this node has no parent
protected Object | userObject optional user object
Constructor Summary
DefaultMutableTreeNode()
Creates a tree node that has no parent and no children, but which allows children.
DefaultMutableTreeNode(Object userObject)
Creates a tree node with no parent, no children, but which allows children, and initializes it with the specified user object.
DefaultMutableTreeNode(Object userObject, boolean allowsChildren)
Creates a tree node with no parent, no children, initialized with the specified user object, and that allows children only if specified.
Method Summary
 void add(MutableTreeNode newChild)
Removes newChild from its parent and makes it a child of this node by adding it to the end of this node's child array.
 Enumeration breadthFirstEnumeration()
Creates and returns an enumeration that traverses the subtree rooted at this node in breadth-first order.
 Enumeration children()
Creates and returns a forward-order enumeration of this node's children.
 Object clone()
Overridden to make clone public.
 Enumeration depthFirstEnumeration()
Creates and returns an enumeration that traverses the subtree rooted at this node in depth-first order.
 boolean getAllowsChildren()
Returns true if this node is allowed to have children.
 TreeNode getChildAfter(TreeNode aChild)
Returns the child in this node's child array that immediately follows aChild, which must be a child of this node.
 TreeNode getChildAt(int index)
Returns the child at the specified index in this node's child array.
 TreeNode getChildBefore(TreeNode aChild)
Returns the child in this node's child array that immediately precedes aChild, which must be a child of this node.
 int getChildCount()
Returns the number of children of this node.
 int getDepth()
Returns the depth of the tree rooted at this node -- the longest distance from this node to a leaf.
 TreeNode getFirstChild()
Returns this node's first child.
 DefaultMutableTreeNode getFirstLeaf()
Finds and returns the first leaf that is a descendant of this node -- either this node or its first child's first leaf.
 int getIndex(TreeNode aChild)
Returns the index of the specified child in this node's child array.
 TreeNode getLastChild()
Returns this node's last child.
 DefaultMutableTreeNode getLastLeaf()
Finds and returns the last leaf that is a descendant of this node -- either this node or its last child's last leaf.
 int getLeafCount()
Returns the total number of leaves that are descendants of this node.
 int getLevel()
Returns the number of levels above this node -- the distance from the root to this node.
 DefaultMutableTreeNode getNextLeaf()
Returns the leaf after this node or null if this node is the last leaf in the tree.
 DefaultMutableTreeNode getNextNode()
Returns the node that follows this node in a preorder traversal of this node's tree.
 DefaultMutableTreeNode getNextSibling()
Returns the next sibling of this node in the parent's children array.
 TreeNode getParent()
Returns this node's parent or null if this node has no parent.
 TreeNode[] getPath()
Returns the path from the root, to get to this node.
protected  TreeNode[] getPathToRoot(TreeNode aNode, int depth)
Builds the parents of node up to and including the root node, where the original node is the last element in the returned array.
 DefaultMutableTreeNode getPreviousLeaf()
Returns the leaf before this node or null if this node is the first leaf in the tree.
 DefaultMutableTreeNode getPreviousNode()
Returns the node that precedes this node in a preorder traversal of this node's tree.
 DefaultMutableTreeNode getPreviousSibling()
Returns the previous sibling of this node in the parent's children array.
 TreeNode getRoot()
Returns the root of the tree that contains this node.
 TreeNode getSharedAncestor(DefaultMutableTreeNode aNode)
Returns the nearest common ancestor to this node and aNode.
 int getSiblingCount()
Returns the number of siblings of this node.
 Object getUserObject()
Returns this node's user object.
 Object[] getUserObjectPath()
Returns the user object path, from the root, to get to this node.
 void insert(MutableTreeNode newChild, int childIndex)
Removes newChild from its present parent (if it has a parent), sets the child's parent to this node, and then adds the child to this node's child array at index childIndex.
 boolean isLeaf()
Returns true if this node has no children.
 boolean isNodeAncestor(TreeNode anotherNode)
Returns true if anotherNode is an ancestor of this node -- if it is this node, this node's parent, or an ancestor of this node's parent.
 boolean isNodeChild(TreeNode aNode)
Returns true if aNode is a child of this node.
 boolean isNodeDescendant(DefaultMutableTreeNode anotherNode)
Returns true if anotherNode is a descendant of this node -- if it is this node, one of this node's children, or a descendant of one of this node's children.
 boolean isNodeRelated(DefaultMutableTreeNode aNode)
Returns true if and only if aNode is in the same tree as this node.
 boolean isNodeSibling(TreeNode anotherNode)
Returns true if anotherNode is a sibling of (has the same parent as) this node.
 boolean isRoot()
Returns true if this node is the root of the tree.
 Enumeration pathFromAncestorEnumeration(TreeNode ancestor)
Creates and returns an enumeration that follows the path from ancestor to this node.
 Enumeration postorderEnumeration()
Creates and returns an enumeration that traverses the subtree rooted at this node in postorder.
 Enumeration preorderEnumeration()
Creates and returns an enumeration that traverses the subtree rooted at this node in preorder.
 void remove(int childIndex)
Removes the child at the specified index from this node's children and sets that node's parent to null.
 void remove(MutableTreeNode aChild)
Removes aChild from this node's child array, giving it a null parent.
 void removeAllChildren()
Removes all of this node's children, setting their parents to null.
 void removeFromParent()
Removes the subtree rooted at this node from the tree, giving this node a null parent.
 void setAllowsChildren(boolean allows)
Determines whether or not this node is allowed to have children.
 void setParent(MutableTreeNode newParent)
Sets this node's parent to newParent but does not change the parent's child array.
 void setUserObject(Object userObject)
Sets the user object for this node to userObject.
 String toString()
Returns the result of sending toString() to this node's user object, or null if this node has no user object.
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

EMPTY_ENUMERATION

public static final Enumeration EMPTY_ENUMERATION
An enumeration that is always empty. This is used when an enumeration of a leaf node's children is requested.

parent

protected MutableTreeNode parent
this node's parent, or null if this node has no parent

children

protected Vector children
array of children, may be null if this node has no children

userObject

protected transient Object userObject
optional user object

allowsChildren

protected boolean allowsChildren
true if the node is able to have children

Constructor Detail

DefaultMutableTreeNode

public DefaultMutableTreeNode()
Creates a tree node that has no parent and no children, but which allows children.

DefaultMutableTreeNode

public DefaultMutableTreeNode(Object userObject)
Creates a tree node with no parent, no children, but which allows children, and initializes it with the specified user object.

Parameters:
userObject - an Object provided by the user that constitutes the node's data

DefaultMutableTreeNode

public DefaultMutableTreeNode(Object userObject,
                              boolean allowsChildren)
Creates a tree node with no parent, no children, initialized with the specified user object, and that allows children only if specified.

Parameters:
userObject - an Object provided by the user that constitutes the node's data
allowsChildren - if true, the node is allowed to have child nodes -- otherwise, it is always a leaf node
Method Detail

insert

public void insert(MutableTreeNode newChild,
                   int childIndex)
Removes newChild from its present parent (if it has a parent), sets the child's parent to this node, and then adds the child to this node's child array at index childIndex. newChild must not be null and must not be an ancestor of this node.

Specified by:
insert in interface MutableTreeNode
Parameters:
newChild - the MutableTreeNode to insert under this node
childIndex - the index in this node's child array where this node is to be inserted
Throws:
ArrayIndexOutOfBoundsException - if childIndex is out of bounds
IllegalArgumentException - if newChild is null or is an ancestor of this node
IllegalStateException - if this node does not allow children
See Also:
isNodeDescendant(javax.swing.tree.DefaultMutableTreeNode)

remove

public void remove(int childIndex)
Removes the child at the specified index from this node's children and sets that node's parent to null. The child node to remove must be a MutableTreeNode.

Specified by:
remove in interface MutableTreeNode
Parameters:
childIndex - the index in this node's child array of the child to remove
Throws:
ArrayIndexOutOfBoundsException - if childIndex is out of bounds

setParent

public void setParent(MutableTreeNode newParent)
Sets this node's parent to newParent but does not change the parent's child array. This method is called from insert() and remove() to reassign a child's parent, it should not be messaged from anywhere else.

Specified by:
setParent in interface MutableTreeNode
Parameters:
newParent - this node's new parent

getParent

public TreeNode getParent()
Returns this node's parent or null if this node has no parent.

Specified by:
getParent in interface TreeNode
Returns:
this node's parent TreeNode, or null if this node has no parent

getChildAt

public TreeNode getChildAt(int index)
Returns the child at the specified index in this node's child array.

Specified by:
getChildAt in interface TreeNode
Parameters:
index - an index into this node's child array
Returns:
the TreeNode in this node's child array at the specified index
Throws:
ArrayIndexOutOfBoundsException - if index is out of bounds

getChildCount

public int getChildCount()
Returns the number of children of this node.

Specified by:
getChildCount in interface TreeNode
Returns:
an int giving the number of children of this node

getIndex

public int getIndex(TreeNode aChild)
Returns the index of the specified child in this node's child array. If the specified node is not a child of this node, returns -1. This method performs a linear search and is O(n) where n is the number of children.

Specified by:
getIndex in interface TreeNode
Parameters:
aChild - the TreeNode to search for among this node's children
Returns:
an int giving the index of the node in this node's child array, or -1 if the specified node is a not a child of this node
Throws:
IllegalArgumentException - if aChild is null

children

public Enumeration children()
Creates and returns a forward-order enumeration of this node's children. Modifying this node's child array invalidates any child enumerations created before the modification.

Specified by:
children in interface TreeNode
Returns:
an Enumeration of this node's children

setAllowsChildren

public void setAllowsChildren(boolean allows)
Determines whether or not this node is allowed to have children. If allows is false, all of this node's children are removed.

Note: By default, a node allows children.

Parameters:
allows - true if this node is allowed to have children

getAllowsChildren

public boolean getAllowsChildren()
Returns true if this node is allowed to have children.

Specified by:
getAllowsChildren in interface TreeNode
Returns:
true if this node allows children, else false

setUserObject

public void setUserObject(Object userObject)
Sets the user object for this node to userObject.

Specified by:
setUserObject in interface MutableTreeNode
Parameters:
userObject - the Object that constitutes this node's user-specified data
See Also:
getUserObject(), toString()

getUserObject

public Object getUserObject()
Returns this node's user object.

Returns:
the Object stored at this node by the user
See Also:
setUserObject(java.lang.Object), toString()

removeFromParent

public void removeFromParent()
Removes the subtree rooted at this node from the tree, giving this node a null parent. Does nothing if this node is the root of its tree.

Specified by:
removeFromParent in interface MutableTreeNode

remove

public void remove(MutableTreeNode aChild)
Removes aChild from this node's child array, giving it a null parent.

Specified by:
remove in interface MutableTreeNode
Parameters:
aChild - a child of this node to remove
Throws:
IllegalArgumentException - if aChild is null or is not a child of this node

removeAllChildren

public void removeAllChildren()
Removes all of this node's children, setting their parents to null. If this node has no children, this method does nothing.

add

public void add(MutableTreeNode newChild)
Removes newChild from its parent and makes it a child of this node by adding it to the end of this node's child array.

Parameters:
newChild - node to add as a child of this node
Throws:
IllegalArgumentException - if newChild is null
IllegalStateException - if this node does not allow children
See Also:
insert(javax.swing.tree.MutableTreeNode, int)

isNodeAncestor

public boolean isNodeAncestor(TreeNode anotherNode)
Returns true if anotherNode is an ancestor of this node -- if it is this node, this node's parent, or an ancestor of this node's parent. (Note that a node is considered an ancestor of itself.) If anotherNode is null, this method returns false. This operation is at worst O(h) where h is the distance from the root to this node.

Parameters:
anotherNode - node to test as an ancestor of this node
Returns:
true if this node is a descendant of anotherNode
See Also:
isNodeDescendant(javax.swing.tree.DefaultMutableTreeNode), getSharedAncestor(javax.swing.tree.DefaultMutableTreeNode)

isNodeDescendant

public boolean isNodeDescendant(DefaultMutableTreeNode anotherNode)
Returns true if anotherNode is a descendant of this node -- if it is this node, one of this node's children, or a descendant of one of this node's children. Note that a node is considered a descendant of itself. If anotherNode is null, returns false. This operation is at worst O(h) where h is the distance from the root to anotherNode.

Parameters:
anotherNode - node to test as descendant of this node
Returns:
true if this node is an ancestor of anotherNode
See Also:
isNodeAncestor(javax.swing.tree.TreeNode), getSharedAncestor(javax.swing.tree.DefaultMutableTreeNode)

getSharedAncestor

public TreeNode getSharedAncestor(DefaultMutableTreeNode aNode)
Returns the nearest common ancestor to this node and aNode. Returns null, if no such ancestor exists -- if this node and aNode are in different trees or if aNode is null. A node is considered an ancestor of itself.

Parameters:
aNode - node to find common ancestor with
Returns:
nearest ancestor common to this node and aNode, or null if none
See Also:
isNodeAncestor(javax.swing.tree.TreeNode), isNodeDescendant(javax.swing.tree.DefaultMutableTreeNode)

isNodeRelated

public boolean isNodeRelated(DefaultMutableTreeNode aNode)
Returns true if and only if aNode is in the same tree as this node. Returns false if aNode is null.

Returns:
true if aNode is in the same tree as this node; false if aNode is null
See Also:
getSharedAncestor(javax.swing.tree.DefaultMutableTreeNode), getRoot()

getDepth

public int getDepth()
Returns the depth of the tree rooted at this node -- the longest distance from this node to a leaf. If this node has no children, returns 0. This operation is much more expensive than getLevel() because it must effectively traverse the entire tree rooted at this node.

Returns:
the depth of the tree whose root is this node
See Also:
getLevel()

getLevel

public int getLevel()
Returns the number of levels above this node -- the distance from the root to this node. If this node is the root, returns 0.

Returns:
the number of levels above this node
See Also:
getDepth()

getPath

public TreeNode[] getPath()
Returns the path from the root, to get to this node. The last element in the path is this node.

Returns:
an array of TreeNode objects giving the path, where the first element in the path is the root and the last element is this node.

getPathToRoot

protected TreeNode[] getPathToRoot(TreeNode aNode,
                                   int depth)
Builds the parents of node up to and including the root node, where the original node is the last element in the returned array. The length of the returned array gives the node's depth in the tree.

Parameters:
aNode - the TreeNode to get the path for
depth - an int giving the number of steps already taken towards the root (on recursive calls), used to size the returned array
Returns:
an array of TreeNodes giving the path from the root to the specified node

getUserObjectPath

public Object[] getUserObjectPath()
Returns the user object path, from the root, to get to this node. If some of the TreeNodes in the path have null user objects, the returned path will contain nulls.

getRoot

public TreeNode getRoot()
Returns the root of the tree that contains this node. The root is the ancestor with a null parent.

Returns:
the root of the tree that contains this node
See Also:
isNodeAncestor(javax.swing.tree.TreeNode)

isRoot

public boolean isRoot()
Returns true if this node is the root of the tree. The root is the only node in the tree with a null parent; every tree has exactly one root.

Returns:
true if this node is the root of its tree

getNextNode

public DefaultMutableTreeNode getNextNode()
Returns the node that follows this node in a preorder traversal of this node's tree. Returns null if this node is the last node of the traversal. This is an inefficient way to traverse the entire tree; use an enumeration, instead.

Returns:
the node that follows this node in a preorder traversal, or null if this node is last
See Also:
preorderEnumeration()

getPreviousNode

public DefaultMutableTreeNode getPreviousNode()
Returns the node that precedes this node in a preorder traversal of this node's tree. Returns null if this node is the first node of the traversal -- the root of the tree. This is an inefficient way to traverse the entire tree; use an enumeration, instead.

Returns:
the node that precedes this node in a preorder traversal, or null if this node is the first
See Also:
preorderEnumeration()

preorderEnumeration

public Enumeration preorderEnumeration()
Creates and returns an enumeration that traverses the subtree rooted at this node in preorder. The first node returned by the enumeration's nextElement() method is this node.

Modifying the tree by inserting, removing, or moving a node invalidates any enumerations created before the modification.

Returns:
an enumeration for traversing the tree in preorder
See Also:
postorderEnumeration()

postorderEnumeration

public Enumeration postorderEnumeration()
Creates and returns an enumeration that traverses the subtree rooted at this node in postorder. The first node returned by the enumeration's nextElement() method is the leftmost leaf. This is the same as a depth-first traversal.

Modifying the tree by inserting, removing, or moving a node invalidates any enumerations created before the modification.

Returns:
an enumeration for traversing the tree in postorder
See Also:
depthFirstEnumeration(), preorderEnumeration()

breadthFirstEnumeration

public Enumeration breadthFirstEnumeration()
Creates and returns an enumeration that traverses the subtree rooted at this node in breadth-first order. The first node returned by the enumeration's nextElement() method is this node.

Modifying the tree by inserting, removing, or moving a node invalidates any enumerations created before the modification.

Returns:
an enumeration for traversing the tree in breadth-first order
See Also:
depthFirstEnumeration()

depthFirstEnumeration

public Enumeration depthFirstEnumeration()
Creates and returns an enumeration that traverses the subtree rooted at this node in depth-first order. The first node returned by the enumeration's nextElement() method is the leftmost leaf. This is the same as a postorder traversal.

Modifying the tree by inserting, removing, or moving a node invalidates any enumerations created before the modification.

Returns:
an enumeration for traversing the tree in depth-first order
See Also:
breadthFirstEnumeration(), postorderEnumeration()

pathFromAncestorEnumeration

public Enumeration pathFromAncestorEnumeration(TreeNode ancestor)
Creates and returns an enumeration that follows the path from ancestor to this node. The enumeration's nextElement() method first returns ancestor, then the child of ancestor that is an ancestor of this node, and so on, and finally returns this node. Creation of the enumeration is O(m) where m is the number of nodes between this node and ancestor, inclusive. Each nextElement() message is O(1).

Modifying the tree by inserting, removing, or moving a node invalidates any enumerations created before the modification.

Returns:
an enumeration for following the path from an ancestor of this node to this one
Throws:
IllegalArgumentException - if ancestor is not an ancestor of this node
See Also:
isNodeAncestor(javax.swing.tree.TreeNode), isNodeDescendant(javax.swing.tree.DefaultMutableTreeNode)

isNodeChild

public boolean isNodeChild(TreeNode aNode)
Returns true if aNode is a child of this node. If aNode is null, this method returns false.

Returns:
true if aNode is a child of this node; false if aNode is null

getFirstChild

public TreeNode getFirstChild()
Returns this node's first child. If this node has no children, throws NoSuchElementException.

Returns:
the first child of this node
Throws:
NoSuchElementException - if this node has no children

getLastChild

public TreeNode getLastChild()
Returns this node's last child. If this node has no children, throws NoSuchElementException.

Returns:
the last child of this node
Throws:
NoSuchElementException - if this node has no children

getChildAfter

public TreeNode getChildAfter(TreeNode aChild)
Returns the child in this node's child array that immediately follows aChild, which must be a child of this node. If aChild is the last child, returns null. This method performs a linear search of this node's children for aChild and is O(n) where n is the number of children; to traverse the entire array of children, use an enumeration instead.

Returns:
the child of this node that immediately follows aChild
Throws:
IllegalArgumentException - if aChild is null or is not a child of this node
See Also:
children

getChildBefore

public TreeNode getChildBefore(TreeNode aChild)
Returns the child in this node's child array that immediately precedes aChild, which must be a child of this node. If aChild is the first child, returns null. This method performs a linear search of this node's children for aChild and is O(n) where n is the number of children.

Returns:
the child of this node that immediately precedes aChild
Throws:
IllegalArgumentException - if aChild is null or is not a child of this node

isNodeSibling

public boolean isNodeSibling(TreeNode anotherNode)
Returns true if anotherNode is a sibling of (has the same parent as) this node. A node is its own sibling. If anotherNode is null, returns false.

Parameters:
anotherNode - node to test as sibling of this node
Returns:
true if anotherNode is a sibling of this node

getSiblingCount

public int getSiblingCount()
Returns the number of siblings of this node. A node is its own sibling (if it has no parent or no siblings, this method returns 1).

Returns:
the number of siblings of this node

getNextSibling

public DefaultMutableTreeNode getNextSibling()
Returns the next sibling of this node in the parent's children array. Returns null if this node has no parent or is the parent's last child. This method performs a linear search that is O(n) where n is the number of children; to traverse the entire array, use the parent's child enumeration instead.

Returns:
the sibling of this node that immediately follows this node
See Also:
children

getPreviousSibling

public DefaultMutableTreeNode getPreviousSibling()
Returns the previous sibling of this node in the parent's children array. Returns null if this node has no parent or is the parent's first child. This method performs a linear search that is O(n) where n is the number of children.

Returns:
the sibling of this node that immediately precedes this node

isLeaf

public boolean isLeaf()
Returns true if this node has no children. To distinguish between nodes that have no children and nodes that cannot have children (e.g. to distinguish files from empty directories), use this method in conjunction with getAllowsChildren

Specified by:
isLeaf in interface TreeNode
Returns:
true if this node has no children
See Also:
getAllowsChildren()

getFirstLeaf

public DefaultMutableTreeNode getFirstLeaf()
Finds and returns the first leaf that is a descendant of this node -- either this node or its first child's first leaf. Returns this node if it is a leaf.

Returns:
the first leaf in the subtree rooted at this node
See Also:
isLeaf(), isNodeDescendant(javax.swing.tree.DefaultMutableTreeNode)

getLastLeaf

public DefaultMutableTreeNode getLastLeaf()
Finds and returns the last leaf that is a descendant of this node -- either this node or its last child's last leaf. Returns this node if it is a leaf.

Returns:
the last leaf in the subtree rooted at this node
See Also:
isLeaf(), isNodeDescendant(javax.swing.tree.DefaultMutableTreeNode)

getNextLeaf

public DefaultMutableTreeNode getNextLeaf()
Returns the leaf after this node or null if this node is the last leaf in the tree.

In this implementation of the MutableNode interface, this operation is very inefficient. In order to determine the next node, this method first performs a linear search in the parent's child-list in order to find the current node.

That implementation makes the operation suitable for short traversals from a known position. But to traverse all of the leaves in the tree, you should use depthFirstEnumeration to enumerate the nodes in the tree and use isLeaf on each node to determine which are leaves.

Returns:
returns the next leaf past this node
See Also:
depthFirstEnumeration(), isLeaf()

getPreviousLeaf

public DefaultMutableTreeNode getPreviousLeaf()
Returns the leaf before this node or null if this node is the first leaf in the tree.

In this implementation of the MutableNode interface, this operation is very inefficient. In order to determine the previous node, this method first performs a linear search in the parent's child-list in order to find the current node.

That implementation makes the operation suitable for short traversals from a known position. But to traverse all of the leaves in the tree, you should use depthFirstEnumeration to enumerate the nodes in the tree and use isLeaf on each node to determine which are leaves.

Returns:
returns the leaf before this node
See Also:
depthFirstEnumeration(), isLeaf()

getLeafCount

public int getLeafCount()
Returns the total number of leaves that are descendants of this node. If this node is a leaf, returns 1. This method is O(n) where n is the number of descendants of this node.

Returns:
the number of leaves beneath this node
See Also:
isNodeAncestor(javax.swing.tree.TreeNode)

toString

public String toString()
Returns the result of sending toString() to this node's user object, or null if this node has no user object.

Overrides:
toString in class Object
Returns:
a string representation of the object.
See Also:
getUserObject()

clone

public Object clone()
Overridden to make clone public. Returns a shallow copy of this node; the new node has no parent or children and has a reference to the same user object, if any.

Overrides:
clone in class Object
Returns:
a copy of this node
See Also:
Cloneable
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DefaultTreeCellEditor (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.tree
Class DefaultTreeCellEditor

java.lang.Object
    extended by javax.swing.tree.DefaultTreeCellEditor
All Implemented Interfaces:
ActionListener, CellEditor, EventListener, TreeCellEditor, TreeSelectionListener
public class DefaultTreeCellEditor
extends Object
implements ActionListener, TreeCellEditor, TreeSelectionListener

A TreeCellEditor. You need to supply an instance of DefaultTreeCellRenderer so that the icons can be obtained. You can optionally supply a TreeCellEditor that will be layed out according to the icon in the DefaultTreeCellRenderer. If you do not supply a TreeCellEditor, a TextField will be used. Editing is started on a triple mouse click, or after a click, pause, click and a delay of 1200 miliseconds.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

See Also:
JTree

Nested Class Summary
class | DefaultTreeCellEditor.DefaultTextField TextField used when no editor is supplied.
class | DefaultTreeCellEditor.EditorContainer Container responsible for placing the editingComponent.
Field Summary
protected Color | borderSelectionColor True if the border selection color should be drawn.
protected boolean | canEdit As of Java 2 platform v1.4 this field should no longer be used.
protected Component | editingComponent Component used in editing, obtained from the editingContainer.
protected Container | editingContainer Editing container, will contain the editorComponent.
protected Icon | editingIcon Icon to use when editing.
protected Font | font Font to paint with, null indicates font of renderer is to be used.
protected TreePath | lastPath Last path that was selected.
protected int | lastRow Row that was last passed into getTreeCellEditorComponent.
protected int | offset Used in editing.
protected TreeCellEditor | realEditor Editor handling the editing.
protected DefaultTreeCellRenderer | renderer Renderer, used to get border and offsets from.
protected Timer | timer Used before starting the editing session.
protected JTree | tree JTree instance listening too.
Constructor Summary
DefaultTreeCellEditor(JTree tree, DefaultTreeCellRenderer renderer)
Constructs a DefaultTreeCellEditor object for a JTree using the specified renderer and a default editor.
DefaultTreeCellEditor(JTree tree, DefaultTreeCellRenderer renderer, TreeCellEditor editor)
Constructs a DefaultTreeCellEditor object for a JTree using the specified renderer and the specified editor.
Method Summary
 void actionPerformed(ActionEvent e)
Messaged when the timer fires, this will start the editing session.
 void addCellEditorListener(CellEditorListener l)
Adds the CellEditorListener.
 void cancelCellEditing()
Messages cancelCellEditing to the realEditor and removes it from this instance.
protected  boolean canEditImmediately(EventObject event)
Returns true if event is null, or it is a MouseEvent with a click count > 2 and inHitRegion returns true.
protected  Container createContainer()
Creates the container to manage placement of editingComponent.
protected  TreeCellEditor createTreeCellEditor()
This is invoked if a TreeCellEditor is not supplied in the constructor.
protected  void determineOffset(JTree tree, Object value, boolean isSelected, boolean expanded, boolean leaf, int row)
 Color getBorderSelectionColor()
Returns the color the border is drawn.
 CellEditorListener[] getCellEditorListeners()
Returns an array of all the CellEditorListeners added to this DefaultTreeCellEditor with addCellEditorListener().
 Object getCellEditorValue()
Returns the value currently being edited.
 Font getFont()
Gets the font used for editing.
 Component getTreeCellEditorComponent(JTree tree, Object value, boolean isSelected, boolean expanded, boolean leaf, int row)
Configures the editor.
protected  boolean inHitRegion(int x, int y)
Returns true if the passed in location is a valid mouse location to start editing from.
 boolean isCellEditable(EventObject event)
If the realEditor returns true to this message, prepareForEditing is messaged and true is returned.
protected  void prepareForEditing()
Invoked just before editing is to start.
 void removeCellEditorListener(CellEditorListener l)
Removes the previously added CellEditorListener.
 void setBorderSelectionColor(Color newColor)
Sets the color to use for the border.
 void setFont(Font font)
Sets the font to edit with.
protected  void setTree(JTree newTree)
Sets the tree currently editing for.
 boolean shouldSelectCell(EventObject event)
Messages the realEditor for the return value.
protected  boolean shouldStartEditingTimer(EventObject event)
Returns true if event is a MouseEvent and the click count is 1.
protected  void startEditingTimer()
Starts the editing timer.
 boolean stopCellEditing()
If the realEditor will allow editing to stop, the realEditor is removed and true is returned, otherwise false is returned.
 void valueChanged(TreeSelectionEvent e)
Resets lastPath.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

realEditor

protected TreeCellEditor realEditor
Editor handling the editing.

renderer

protected DefaultTreeCellRenderer renderer
Renderer, used to get border and offsets from.

editingContainer

protected Container editingContainer
Editing container, will contain the editorComponent.

editingComponent

protected transient Component editingComponent
Component used in editing, obtained from the editingContainer.

canEdit

protected boolean canEdit
As of Java 2 platform v1.4 this field should no longer be used. If you wish to provide similar behavior you should directly override isCellEditable.

offset

protected transient int offset
Used in editing. Indicates x position to place editingComponent.

tree

protected transient JTree tree
JTree instance listening too.

lastPath

protected transient TreePath lastPath
Last path that was selected.

timer

protected transient Timer timer
Used before starting the editing session.

lastRow

protected transient int lastRow
Row that was last passed into getTreeCellEditorComponent.

borderSelectionColor

protected Color borderSelectionColor
True if the border selection color should be drawn.

editingIcon

protected transient Icon editingIcon
Icon to use when editing.

font

protected Font font
Font to paint with, null indicates font of renderer is to be used.

Constructor Detail

DefaultTreeCellEditor

public DefaultTreeCellEditor(JTree tree,
                             DefaultTreeCellRenderer renderer)
Constructs a DefaultTreeCellEditor object for a JTree using the specified renderer and a default editor. (Use this constructor for normal editing.)

Parameters:
tree - a JTree object
renderer - a DefaultTreeCellRenderer object

DefaultTreeCellEditor

public DefaultTreeCellEditor(JTree tree,
                             DefaultTreeCellRenderer renderer,
                             TreeCellEditor editor)
Constructs a DefaultTreeCellEditor object for a JTree using the specified renderer and the specified editor. (Use this constructor for specialized editing.)

Parameters:
tree - a JTree object
renderer - a DefaultTreeCellRenderer object
editor - a TreeCellEditor object
Method Detail

setBorderSelectionColor

public void setBorderSelectionColor(Color newColor)
Sets the color to use for the border.

Parameters:
newColor - the new border color

getBorderSelectionColor

public Color getBorderSelectionColor()
Returns the color the border is drawn.

Returns:
the border selection color

setFont

public void setFont(Font font)
Sets the font to edit with. null indicates the renderers font should be used. This will NOT override any font you have set in the editor the receiver was instantied with. If null for an editor was passed in a default editor will be created that will pick up this font.

Parameters:
font - the editing Font
See Also:
getFont()

getFont

public Font getFont()
Gets the font used for editing.

Returns:
the editing Font
See Also:
setFont(java.awt.Font)

getTreeCellEditorComponent

public Component getTreeCellEditorComponent(JTree tree,
                                            Object value,
                                            boolean isSelected,
                                            boolean expanded,
                                            boolean leaf,
                                            int row)
Configures the editor. Passed onto the realEditor.

Specified by:
getTreeCellEditorComponent in interface TreeCellEditor
Parameters:
tree - the JTree that is asking the editor to edit; this parameter can be null
value - the value of the cell to be edited
isSelected - true is the cell is to be renderer with selection highlighting
expanded - true if the node is expanded
leaf - true if the node is a leaf node
row - the row index of the node being edited
Returns:
the component for editing

getCellEditorValue

public Object getCellEditorValue()
Returns the value currently being edited.

Specified by:
getCellEditorValue in interface CellEditor
Returns:
the value currently being edited

isCellEditable

public boolean isCellEditable(EventObject event)
If the realEditor returns true to this message, prepareForEditing is messaged and true is returned.

Specified by:
isCellEditable in interface CellEditor
Parameters:
event - the event the editor should use to consider whether to begin editing or not
Returns:
true if editing can be started
See Also:
CellEditor.shouldSelectCell(java.util.EventObject)

shouldSelectCell

public boolean shouldSelectCell(EventObject event)
Messages the realEditor for the return value.

Specified by:
shouldSelectCell in interface CellEditor
Parameters:
event - the event the editor should use to start editing
Returns:
true if the editor would like the editing cell to be selected; otherwise returns false
See Also:
CellEditor.isCellEditable(java.util.EventObject)

stopCellEditing

public boolean stopCellEditing()
If the realEditor will allow editing to stop, the realEditor is removed and true is returned, otherwise false is returned.

Specified by:
stopCellEditing in interface CellEditor
Returns:
true if editing was stopped; false otherwise

cancelCellEditing

public void cancelCellEditing()
Messages cancelCellEditing to the realEditor and removes it from this instance.

Specified by:
cancelCellEditing in interface CellEditor

addCellEditorListener

public void addCellEditorListener(CellEditorListener l)
Adds the CellEditorListener.

Specified by:
addCellEditorListener in interface CellEditor
Parameters:
l - the listener to be added

removeCellEditorListener

public void removeCellEditorListener(CellEditorListener l)
Removes the previously added CellEditorListener.

Specified by:
removeCellEditorListener in interface CellEditor
Parameters:
l - the listener to be removed

getCellEditorListeners

public CellEditorListener[] getCellEditorListeners()
Returns an array of all the CellEditorListeners added to this DefaultTreeCellEditor with addCellEditorListener().

Returns:
all of the CellEditorListeners added or an empty array if no listeners have been added
Since:
1.4

valueChanged

public void valueChanged(TreeSelectionEvent e)
Resets lastPath.

Specified by:
valueChanged in interface TreeSelectionListener
Parameters:
e - the event that characterizes the change.

actionPerformed

public void actionPerformed(ActionEvent e)
Messaged when the timer fires, this will start the editing session.

Specified by:
actionPerformed in interface ActionListener

setTree

protected void setTree(JTree newTree)
Sets the tree currently editing for. This is needed to add a selection listener.

Parameters:
newTree - the new tree to be edited

shouldStartEditingTimer

protected boolean shouldStartEditingTimer(EventObject event)
Returns true if event is a MouseEvent and the click count is 1.

Parameters:
event - the event being studied

startEditingTimer

protected void startEditingTimer()
Starts the editing timer.

canEditImmediately

protected boolean canEditImmediately(EventObject event)
Returns true if event is null, or it is a MouseEvent with a click count > 2 and inHitRegion returns true.

Parameters:
event - the event being studied

inHitRegion

protected boolean inHitRegion(int x,
                              int y)
Returns true if the passed in location is a valid mouse location to start editing from. This is implemented to return false if x is <= the width of the icon and icon gap displayed by the renderer. In other words this returns true if the user clicks over the text part displayed by the renderer, and false otherwise.

Parameters:
x - the x-coordinate of the point
y - the y-coordinate of the point
Returns:
true if the passed in location is a valid mouse location

determineOffset

protected void determineOffset(JTree tree,
                               Object value,
                               boolean isSelected,
                               boolean expanded,
                               boolean leaf,
                               int row)

prepareForEditing

protected void prepareForEditing()
Invoked just before editing is to start. Will add the editingComponent to the editingContainer.

createContainer

protected Container createContainer()
Creates the container to manage placement of editingComponent.

createTreeCellEditor

protected TreeCellEditor createTreeCellEditor()
This is invoked if a TreeCellEditor is not supplied in the constructor. It returns a TextField editor.

Returns:
a new TextField editor
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DefaultTreeCellEditor.DefaultTextField (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.tree
Class DefaultTreeCellEditor.DefaultTextField

java.lang.Object
    extended by java.awt.Component
        extended by java.awt.Container
            extended by javax.swing.JComponent
                extended by javax.swing.text.JTextComponent
                    extended by javax.swing.JTextField
                        extended by javax.swing.tree.DefaultTreeCellEditor.DefaultTextField
All Implemented Interfaces:
Accessible, ImageObserver, MenuContainer, Scrollable, Serializable, SwingConstants
Enclosing class:
DefaultTreeCellEditor
public class DefaultTreeCellEditor.DefaultTextField
extends JTextField

TextField used when no editor is supplied. This textfield locks into the border it is constructed with. It also prefers its parents font over its font. And if the renderer is not null and no font has been specified the preferred height is that of the renderer.

Nested Class Summary
Nested classes inherited from class javax.swing.JTextField
JTextField.AccessibleJTextField
Nested classes inherited from class javax.swing.text.JTextComponent
JTextComponent.AccessibleJTextComponent, JTextComponent.KeyBinding
Nested classes inherited from class javax.swing.JComponent
JComponent.AccessibleJComponent
Nested classes inherited from class java.awt.Container
Container.AccessibleAWTContainer
Nested classes inherited from class java.awt.Component
Component.AccessibleAWTComponent, Component.BltBufferStrategy, Component.FlipBufferStrategy
Field Summary
protected  Border border
Border to use.
Fields inherited from class javax.swing.JTextField
notifyAction
Fields inherited from class javax.swing.text.JTextComponent
DEFAULT_KEYMAP, FOCUS_ACCELERATOR_KEY
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
Constructor Summary
DefaultTreeCellEditor.DefaultTextField(Border border)
Constructs a DefaultTreeCellEditor.DefaultTextField object.
Method Summary
Border | getBorder() Overrides JComponent.getBorder to returns the current border.
Font | getFont() Gets the font of this component.
Dimension | getPreferredSize() Overrides JTextField.getPreferredSize to return the preferred size based on current font, if set, or else use renderer's font.
void | setBorder(Border border) Sets the border of this component.
Methods inherited from class javax.swing.JTextField
addActionListener, configurePropertiesFromAction, createActionPropertyChangeListener, createDefaultModel, fireActionPerformed, getAccessibleContext, getAction, getActionListeners, getActions, getColumns, getColumnWidth, getHorizontalAlignment, getHorizontalVisibility, getScrollOffset, getUIClassID, isValidateRoot, paramString, postActionEvent, removeActionListener, scrollRectToVisible, setAction, setActionCommand, setColumns, setDocument, setFont, setHorizontalAlignment, setScrollOffset
Methods inherited from class javax.swing.text.JTextComponent
addCaretListener, addInputMethodListener, addKeymap, copy, cut, fireCaretUpdate, getCaret, getCaretColor, getCaretListeners, getCaretPosition, getDisabledTextColor, getDocument, getDragEnabled, getFocusAccelerator, getHighlighter, getInputMethodRequests, getKeymap, getKeymap, getMargin, getNavigationFilter, getPreferredScrollableViewportSize, getScrollableBlockIncrement, getScrollableTracksViewportHeight, getScrollableTracksViewportWidth, getScrollableUnitIncrement, getSelectedText, getSelectedTextColor, getSelectionColor, getSelectionEnd, getSelectionStart, getText, getText, getToolTipText, getUI, isEditable, loadKeymap, modelToView, moveCaretPosition, paste, processInputMethodEvent, read, removeCaretListener, removeKeymap, removeNotify, replaceSelection, select, selectAll, setCaret, setCaretColor, setCaretPosition, setComponentOrientation, setDisabledTextColor, setDragEnabled, setEditable, setFocusAccelerator, setHighlighter, setKeymap, setMargin, setNavigationFilter, setSelectedTextColor, setSelectionColor, setSelectionEnd, setSelectionStart, setText, setUI, updateUI, viewToModel, write
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addPropertyChangeListener, addPropertyChangeListener, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBounds, getClientProperty, getComponentGraphics, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getGraphics, getHeight, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPropertyChangeListeners, getPropertyChangeListeners, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isMaximumSizeSet, isMinimumSizeSet, isOpaque, isOptimizedDrawingEnabled, isPaintingTile, isPreferredSizeSet, isRequestFocusEnabled, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removePropertyChangeListener, removePropertyChangeListener, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setForeground, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setFocusCycleRoot, setFocusTraversalKeys, setFocusTraversalPolicy, setLayout, transferFocusBackward, transferFocusDownCycle, validate, validateTree
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFontMetrics, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMouseWheelListeners, getName, getParent, getPeer, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processMouseEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

border

protected Border border
Border to use.

Constructor Detail

DefaultTreeCellEditor.DefaultTextField

public DefaultTreeCellEditor.DefaultTextField(Border border)
Constructs a DefaultTreeCellEditor.DefaultTextField object.

Parameters:
border - a Border object
Method Detail

setBorder

public void setBorder(Border border)
Sets the border of this component.

This is a bound property.

Overrides:
setBorder in class JComponent
Parameters:
border - the border to be rendered for this component
See Also:
Border, CompoundBorder

getBorder

public Border getBorder()
Overrides JComponent.getBorder to returns the current border.

Overrides:
getBorder in class JComponent
Returns:
the border object for this component
See Also:
JComponent.setBorder(javax.swing.border.Border)

getFont

public Font getFont()
Description copied from class: Component
Gets the font of this component.

Specified by:
getFont in interface MenuContainer
Overrides:
getFont in class Component
Returns:
this component's font; if a font has not been set for this component, the font of its parent is returned
See Also:
Component.setFont(java.awt.Font)

getPreferredSize

public Dimension getPreferredSize()
Overrides JTextField.getPreferredSize to return the preferred size based on current font, if set, or else use renderer's font.

Overrides:
getPreferredSize in class JTextField
Returns:
a Dimension object containing the preferred size
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DefaultTreeCellEditor.EditorContainer (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.tree
Class DefaultTreeCellEditor.EditorContainer

java.lang.Object
    extended by java.awt.Component
        extended by java.awt.Container
            extended by javax.swing.tree.DefaultTreeCellEditor.EditorContainer
All Implemented Interfaces:
ImageObserver, MenuContainer, Serializable
Enclosing class:
DefaultTreeCellEditor
public class DefaultTreeCellEditor.EditorContainer
extends Container

Container responsible for placing the editingComponent.

Nested Class Summary
Nested classes inherited from class java.awt.Container
Container.AccessibleAWTContainer
Nested classes inherited from class java.awt.Component
Component.AccessibleAWTComponent, Component.BltBufferStrategy, Component.FlipBufferStrategy
Field Summary
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
Constructor Summary
DefaultTreeCellEditor.EditorContainer()
Constructs an EditorContainer object.
Method Summary
void | doLayout() Lays out this Container.
void | EditorContainer()
Dimension | getPreferredSize() Returns the preferred size for the Container.
void | paint(Graphics g) Overrides Container.paint to paint the node's icon and use the selection color for the background.
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, addNotify, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, findComponentAt, findComponentAt, getAlignmentX, getAlignmentY, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getInsets, getLayout, getListeners, getMaximumSize, getMinimumSize, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, paramString, preferredSize, print, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, removeNotify, setFocusCycleRoot, setFocusTraversalKeys, setFocusTraversalPolicy, setFont, setLayout, transferFocusBackward, transferFocusDownCycle, update, validate, validateTree
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, contains, createImage, createImage, createVolatileImage, createVolatileImage, disable, disableEvents, dispatchEvent, enable, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, getAccessibleContext, getBackground, getBounds, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getFontMetrics, getForeground, getGraphics, getGraphicsConfiguration, getHeight, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getSize, getToolkit, getTreeLock, getWidth, getX, getY, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isDoubleBuffered, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isOpaque, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, printAll, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processKeyEvent, processMouseEvent, processMouseMotionEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, repaint, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, reshape, resize, resize, setBackground, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setEnabled, setFocusable, setFocusTraversalKeysEnabled, setForeground, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, setVisible, show, show, size, toString, transferFocus, transferFocusUpCycle
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

DefaultTreeCellEditor.EditorContainer

public DefaultTreeCellEditor.EditorContainer()
Constructs an EditorContainer object.

Method Detail

EditorContainer

public void EditorContainer()

paint

public void paint(Graphics g)
Overrides Container.paint to paint the node's icon and use the selection color for the background.

Overrides:
paint in class Container
Parameters:
g - the specified Graphics window
See Also:
Component.update(Graphics)

doLayout

public void doLayout()
Lays out this Container. If editing, the editor will be placed at offset in the x direction and 0 for y.

Overrides:
doLayout in class Container
See Also:
LayoutManager.layoutContainer(java.awt.Container),
Container.setLayout(java.awt.LayoutManager),
Container.validate()

getPreferredSize

public Dimension getPreferredSize()
Returns the preferred size for the Container. This will be at least preferred size of the editor plus offset.

Overrides:
getPreferredSize in class Container
Returns:
a Dimension containing the preferred size for the Container; if editingComponent is null the Dimension returned is 0, 0
See Also:
Container.getMinimumSize(),
Container.getLayout(),
LayoutManager.preferredLayoutSize(Container),
Component.getPreferredSize()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DefaultTreeCellRenderer (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.tree
Class DefaultTreeCellRenderer

java.lang.Object
    extended by java.awt.Component
        extended by java.awt.Container
            extended by javax.swing.JComponent
                extended by javax.swing.JLabel
                    extended by javax.swing.tree.DefaultTreeCellRenderer
All Implemented Interfaces:
Accessible, ImageObserver, MenuContainer, Serializable, SwingConstants, TreeCellRenderer
public class DefaultTreeCellRenderer
extends JLabel
implements TreeCellRenderer

Displays an entry in a tree. See How to Use Trees in The Java Tutorial for examples of customizing node display using this class.

Implementation Note: This class overrides validate, revalidate, repaint, and firePropertyChange solely to improve performance. If not overridden, these frequently called methods would execute code paths that are unnecessary for the default tree cell renderer. If you write your own renderer, take care to weigh the benefits and drawbacks of overriding these methods.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Nested Class Summary
Nested classes inherited from class javax.swing.JLabel
JLabel.AccessibleJLabel
Nested classes inherited from class javax.swing.JComponent
JComponent.AccessibleJComponent
Nested classes inherited from class java.awt.Container
Container.AccessibleAWTContainer
Nested classes inherited from class java.awt.Component
Component.AccessibleAWTComponent, Component.BltBufferStrategy, Component.FlipBufferStrategy
Field Summary
protected Color | backgroundNonSelectionColor Color to use for the background when the node isn't selected.
protected Color | backgroundSelectionColor Color to use for the background when a node is selected.
protected Color | borderSelectionColor Color to use for the focus indicator when the node has focus.
protected Icon | closedIcon Icon used to show non-leaf nodes that aren't expanded.
protected boolean | hasFocus True if has focus.
protected Icon | leafIcon Icon used to show leaf nodes.
protected Icon | openIcon Icon used to show non-leaf nodes that are expanded.
protected boolean | selected Is the value currently selected.
protected Color | textNonSelectionColor Color to use for the foreground for non-selected nodes.
protected Color | textSelectionColor Color to use for the foreground for selected nodes.
Fields inherited from class javax.swing.JLabel
labelFor
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
Fields inherited from interface javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
Constructor Summary
DefaultTreeCellRenderer()
Returns a new instance of DefaultTreeCellRenderer.
Method Summary
void | firePropertyChange(String propertyName, boolean oldValue, boolean newValue) Overridden for performance reasons.
void | firePropertyChange(String propertyName, byte oldValue, byte newValue) Overridden for performance reasons.
void | firePropertyChange(String propertyName, char oldValue, char newValue) Overridden for performance reasons.
void | firePropertyChange(String propertyName, double oldValue, double newValue) Overridden for performance reasons.
void | firePropertyChange(String propertyName, float oldValue, float newValue) Overridden for performance reasons.
void | firePropertyChange(String propertyName, int oldValue, int newValue) Overridden for performance reasons.
void | firePropertyChange(String propertyName, long oldValue, long newValue) Overridden for performance reasons.
protected void | firePropertyChange(String propertyName, Object oldValue, Object newValue) Overridden for performance reasons.
void | firePropertyChange(String propertyName, short oldValue, short newValue) Overridden for performance reasons.
Color | getBackgroundNonSelectionColor() Returns the background color to be used for non selected nodes.
Color | getBackgroundSelectionColor() Returns the color to use for the background if node is selected.
Color | getBorderSelectionColor() Returns the color the border is drawn.
Icon | getClosedIcon() Returns the icon used to represent non-leaf nodes that are not expanded.
Icon | getDefaultClosedIcon() Returns the default icon, for the current laf, that is used to represent non-leaf nodes that are not expanded.
Icon | getDefaultLeafIcon() Returns the default icon, for the current laf, that is used to represent leaf nodes.
Icon | getDefaultOpenIcon() Returns the default icon, for the current laf, that is used to represent non-leaf nodes that are expanded.
Font | getFont() Gets the font of this component.
Icon | getLeafIcon() Returns the icon used to represent leaf nodes.
Icon | getOpenIcon() Returns the icon used to represent non-leaf nodes that are expanded.
Dimension | getPreferredSize() Overrides JComponent.getPreferredSize to return slightly wider preferred size value.
Color | getTextNonSelectionColor() Returns the color the text is drawn with when the node isn't selected.
Color | getTextSelectionColor() Returns the color the text is drawn with when the node is selected.
Component | getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) Configures the renderer based on the passed in components.
void | paint(Graphics g) Paints the value.
void | repaint(long tm, int x, int y, int width, int height) Overridden for performance reasons.
void | repaint(Rectangle r) Overridden for performance reasons.
void | revalidate() Overridden for performance reasons.
void | setBackground(Color color) Subclassed to map ColorUIResources to null.
void | setBackgroundNonSelectionColor(Color newColor) Sets the background color to be used for non selected nodes.
void | setBackgroundSelectionColor(Color newColor) Sets the color to use for the background if node is selected.
void | setBorderSelectionColor(Color newColor) Sets the color to use for the border.
void | setClosedIcon(Icon newIcon) Sets the icon used to represent non-leaf nodes that are not expanded.
void | setFont(Font font) Subclassed to map FontUIResources to null.
void | setLeafIcon(Icon newIcon) Sets the icon used to represent leaf nodes.
void | setOpenIcon(Icon newIcon) Sets the icon used to represent non-leaf nodes that are expanded.
void | setTextNonSelectionColor(Color newColor) Sets the color the text is drawn with when the node isn't selected.
void | setTextSelectionColor(Color newColor) Sets the color the text is drawn with when the node is selected.
void | validate() Overridden for performance reasons.
Methods inherited from class javax.swing.JLabel
checkHorizontalKey, checkVerticalKey, getAccessibleContext, getDisabledIcon, getDisplayedMnemonic, getDisplayedMnemonicIndex, getHorizontalAlignment, getHorizontalTextPosition, getIcon, getIconTextGap, getLabelFor, getText, getUI, getUIClassID, getVerticalAlignment, getVerticalTextPosition, imageUpdate, paramString, setDisabledIcon, setDisplayedMnemonic, setDisplayedMnemonic, setDisplayedMnemonicIndex, setHorizontalAlignment, setHorizontalTextPosition, setIcon, setIconTextGap, setLabelFor, setText, setUI, setVerticalAlignment, setVerticalTextPosition, updateUI
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addPropertyChangeListener, addPropertyChangeListener, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBorder, getBounds, getClientProperty, getComponentGraphics, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getGraphics, getHeight, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPropertyChangeListeners, getPropertyChangeListeners, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isMaximumSizeSet, isMinimumSizeSet, isOpaque, isOptimizedDrawingEnabled, isPaintingTile, isPreferredSizeSet, isRequestFocusEnabled, isValidateRoot, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removePropertyChangeListener, removePropertyChangeListener, removeVetoableChangeListener, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBorder, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setForeground, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setFocusCycleRoot, setFocusTraversalKeys, setFocusTraversalPolicy, setLayout, transferFocusBackward, transferFocusDownCycle, validateTree
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFontMetrics, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMouseWheelListeners, getName, getParent, getPeer, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

selected

protected boolean selected
Is the value currently selected.

hasFocus

protected boolean hasFocus
True if has focus.

closedIcon

protected transient Icon closedIcon
Icon used to show non-leaf nodes that aren't expanded.

leafIcon

protected transient Icon leafIcon
Icon used to show leaf nodes.

openIcon

protected transient Icon openIcon
Icon used to show non-leaf nodes that are expanded.

textSelectionColor

protected Color textSelectionColor
Color to use for the foreground for selected nodes.

textNonSelectionColor

protected Color textNonSelectionColor
Color to use for the foreground for non-selected nodes.

backgroundSelectionColor

protected Color backgroundSelectionColor
Color to use for the background when a node is selected.

backgroundNonSelectionColor

protected Color backgroundNonSelectionColor
Color to use for the background when the node isn't selected.

borderSelectionColor

protected Color borderSelectionColor
Color to use for the focus indicator when the node has focus.

Constructor Detail

DefaultTreeCellRenderer

public DefaultTreeCellRenderer()
Returns a new instance of DefaultTreeCellRenderer. Alignment is set to left aligned. Icons and text color are determined from the UIManager.

Method Detail

getDefaultOpenIcon

public Icon getDefaultOpenIcon()
Returns the default icon, for the current laf, that is used to represent non-leaf nodes that are expanded.

getDefaultClosedIcon

public Icon getDefaultClosedIcon()
Returns the default icon, for the current laf, that is used to represent non-leaf nodes that are not expanded.

getDefaultLeafIcon

public Icon getDefaultLeafIcon()
Returns the default icon, for the current laf, that is used to represent leaf nodes.

setOpenIcon

public void setOpenIcon(Icon newIcon)
Sets the icon used to represent non-leaf nodes that are expanded.

getOpenIcon

public Icon getOpenIcon()
Returns the icon used to represent non-leaf nodes that are expanded.

setClosedIcon

public void setClosedIcon(Icon newIcon)
Sets the icon used to represent non-leaf nodes that are not expanded.

getClosedIcon

public Icon getClosedIcon()
Returns the icon used to represent non-leaf nodes that are not expanded.

setLeafIcon

public void setLeafIcon(Icon newIcon)
Sets the icon used to represent leaf nodes.

getLeafIcon

public Icon getLeafIcon()
Returns the icon used to represent leaf nodes.

setTextSelectionColor

public void setTextSelectionColor(Color newColor)
Sets the color the text is drawn with when the node is selected.

getTextSelectionColor

public Color getTextSelectionColor()
Returns the color the text is drawn with when the node is selected.

setTextNonSelectionColor

public void setTextNonSelectionColor(Color newColor)
Sets the color the text is drawn with when the node isn't selected.

getTextNonSelectionColor

public Color getTextNonSelectionColor()
Returns the color the text is drawn with when the node isn't selected.

setBackgroundSelectionColor

public void setBackgroundSelectionColor(Color newColor)
Sets the color to use for the background if node is selected.

getBackgroundSelectionColor

public Color getBackgroundSelectionColor()
Returns the color to use for the background if node is selected.

setBackgroundNonSelectionColor

public void setBackgroundNonSelectionColor(Color newColor)
Sets the background color to be used for non selected nodes.

getBackgroundNonSelectionColor

public Color getBackgroundNonSelectionColor()
Returns the background color to be used for non selected nodes.

setBorderSelectionColor

public void setBorderSelectionColor(Color newColor)
Sets the color to use for the border.

getBorderSelectionColor

public Color getBorderSelectionColor()
Returns the color the border is drawn.

setFont

public void setFont(Font font)
Subclassed to map FontUIResources to null. If font is null, or a FontUIResource, this has the effect of letting the font of the JTree show through. On the other hand, if font is non-null, and not a FontUIResource, the font becomes font.

Overrides:
setFont in class JComponent
Parameters:
font - the desired Font for this component
See Also:
Component.getFont()

getFont

public Font getFont()
Gets the font of this component.

Specified by:
getFont in interface MenuContainer
Overrides:
getFont in class Component
Returns:
this component's font; if a font has not been set for this component, the font of its parent is returned
See Also:
Component.setFont(java.awt.Font)

setBackground

public void setBackground(Color color)
Subclassed to map ColorUIResources to null. If color is null, or a ColorUIResource, this has the effect of letting the background color of the JTree show through. On the other hand, if color is non-null, and not a ColorUIResource, the background becomes color.

Overrides:
setBackground in class JComponent
Parameters:
color - the desired background Color
See Also:
Component.getBackground()

getTreeCellRendererComponent

public Component getTreeCellRendererComponent(JTree tree,
                                              Object value,
                                              boolean sel,
                                              boolean expanded,
                                              boolean leaf,
                                              int row,
                                              boolean hasFocus)
Configures the renderer based on the passed in components. The value is set from messaging the tree with convertValueToText, which ultimately invokes toString on value. The foreground color is set based on the selection and the icon is set based on on leaf and expanded.

Specified by:
getTreeCellRendererComponent in interface TreeCellRenderer
Returns:
the Component that the renderer uses to draw the value

paint

public void paint(Graphics g)
Paints the value. The background is filled based on selected.

Overrides:
paint in class JComponent
Parameters:
g - the Graphics context in which to paint
See Also:
JComponent.paintComponent(java.awt.Graphics),
JComponent.paintBorder(java.awt.Graphics),
JComponent.paintChildren(java.awt.Graphics),
JComponent.getComponentGraphics(java.awt.Graphics),
JComponent.repaint(long, int, int, int, int)

getPreferredSize

public Dimension getPreferredSize()
Overrides JComponent.getPreferredSize to return slightly wider preferred size value.

Overrides:
getPreferredSize in class JComponent
Returns:
the value of the preferredSize property
See Also:
JComponent.setPreferredSize(java.awt.Dimension), ComponentUI

validate

public void validate()
Overridden for performance reasons. See the Implementation Note for more information.

Overrides:
validate in class Container
See Also:
Container.add(java.awt.Component),
Component.invalidate(),
JComponent.revalidate()

revalidate

public void revalidate()
Overridden for performance reasons. See the Implementation Note for more information.

Overrides:
revalidate in class JComponent
See Also:
Component.invalidate(),
Container.validate(),
JComponent.isValidateRoot(),
RepaintManager.addInvalidComponent(javax.swing.JComponent)

repaint

public void repaint(long tm,
                    int x,
                    int y,
                    int width,
                    int height)
Overridden for performance reasons. See the Implementation Note for more information.

Overrides:
repaint in class JComponent
Parameters:
tm - this parameter is not used
x - the x value of the dirty region
y - the y value of the dirty region
width - the width of the dirty region
height - the height of the dirty region
See Also:
Component.isShowing(), RepaintManager.addDirtyRegion(javax.swing.JComponent, int, int, int, int)

repaint

public void repaint(Rectangle r)
Overridden for performance reasons. See the Implementation Note for more information.

Overrides:
repaint in class JComponent
Parameters:
r - a Rectangle containing the dirty region
See Also:
Component.isShowing(), RepaintManager.addDirtyRegion(javax.swing.JComponent, int, int, int, int)

firePropertyChange

protected void firePropertyChange(String propertyName,
                                  Object oldValue,
                                  Object newValue)
Overridden for performance reasons. See the Implementation Note for more information.

Overrides:
firePropertyChange in class JComponent
Parameters:
propertyName - the programmatic name of the property that was changed
oldValue - the old value of the property (as an Object)
newValue - the new value of the property (as an Object)
See Also:
PropertyChangeSupport

firePropertyChange

public void firePropertyChange(String propertyName,
                               byte oldValue,
                               byte newValue)
Overridden for performance reasons. See the Implementation Note for more information.

Overrides:
firePropertyChange in class JComponent
Parameters:
propertyName - the programmatic name of the property that was changed
oldValue - the old value of the property (as a byte)
newValue - the new value of the property (as a byte)
See Also:
JComponent.firePropertyChange(java.lang.String, java.lang.Object, java.lang.Object)

firePropertyChange

public void firePropertyChange(String propertyName,
                               char oldValue,
                               char newValue)
Overridden for performance reasons. See the Implementation Note for more information.

Overrides:
firePropertyChange in class JComponent
Parameters:
propertyName - the programmatic name of the property that was changed
oldValue - the old value of the property (as a char)
newValue - the new value of the property (as a char)
See Also:
JComponent.firePropertyChange(java.lang.String, java.lang.Object, java.lang.Object)

firePropertyChange

public void firePropertyChange(String propertyName,
                               short oldValue,
                               short newValue)
Overridden for performance reasons. See the Implementation Note for more information.

Overrides:
firePropertyChange in class JComponent
Parameters:
propertyName - the programmatic name of the property that was changed
oldValue - the old value of the property (as a short)
newValue - the old value of the property (as a short)
See Also:
JComponent.firePropertyChange(java.lang.String, java.lang.Object, java.lang.Object)

firePropertyChange

public void firePropertyChange(String propertyName,
                               int oldValue,
                               int newValue)
Overridden for performance reasons. See the Implementation Note for more information.

Overrides:
firePropertyChange in class JComponent
Parameters:
propertyName - the programmatic name of the property that was changed
oldValue - the old value of the property (as an int)
newValue - the new value of the property (as an int)
See Also:
JComponent.firePropertyChange(java.lang.String, java.lang.Object, java.lang.Object)

firePropertyChange

public void firePropertyChange(String propertyName,
                               long oldValue,
                               long newValue)
Overridden for performance reasons. See the Implementation Note for more information.

Overrides:
firePropertyChange in class JComponent
Parameters:
propertyName - the programmatic name of the property that was changed
oldValue - the old value of the property (as a long)
newValue - the new value of the property (as a long)
See Also:
JComponent.firePropertyChange(java.lang.String, java.lang.Object, java.lang.Object)

firePropertyChange

public void firePropertyChange(String propertyName,
                               float oldValue,
                               float newValue)
Overridden for performance reasons. See the Implementation Note for more information.

Overrides:
firePropertyChange in class JComponent
Parameters:
propertyName - the programmatic name of the property that was changed
oldValue - the old value of the property (as a float)
newValue - the new value of the property (as a float)
See Also:
JComponent.firePropertyChange(java.lang.String, java.lang.Object, java.lang.Object)

firePropertyChange

public void firePropertyChange(String propertyName,
                               double oldValue,
                               double newValue)
Overridden for performance reasons. See the Implementation Note for more information.

Overrides:
firePropertyChange in class JComponent
Parameters:
propertyName - the programmatic name of the property that was changed
oldValue - the old value of the property (as a double)
newValue - the new value of the property (as a double)
See Also:
JComponent.firePropertyChange(java.lang.String, java.lang.Object, java.lang.Object)

firePropertyChange

public void firePropertyChange(String propertyName,
                               boolean oldValue,
                               boolean newValue)
Overridden for performance reasons. See the Implementation Note for more information.

Overrides:
firePropertyChange in class JComponent
Parameters:
propertyName - the programmatic name of the property that was changed
oldValue - the old value of the property (as a boolean)
newValue - the new value of the property (as a boolean)
See Also:
JComponent.firePropertyChange(java.lang.String, java.lang.Object, java.lang.Object)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DefaultTreeModel (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.tree
Class DefaultTreeModel

java.lang.Object
    extended by javax.swing.tree.DefaultTreeModel
All Implemented Interfaces:
Serializable, TreeModel
public class DefaultTreeModel
extends Object
implements Serializable, TreeModel

A simple tree data model that uses TreeNodes. For further information and examples that use DefaultTreeModel, see How to Use Trees in The Java Tutorial.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Field Summary
protected boolean | asksAllowsChildren Determines how the isLeaf method figures out if a node is a leaf node.
protected EventListenerList | listenerList Listeners.
protected TreeNode | root Root of the tree.
Constructor Summary
DefaultTreeModel(TreeNode root)
Creates a tree in which any node can have children.
DefaultTreeModel(TreeNode root, boolean asksAllowsChildren)
Creates a tree specifying whether any node can have children, or whether only certain nodes can have children.
Method Summary
void | addTreeModelListener(TreeModelListener l) Adds a listener for the TreeModelEvent posted after the tree changes.
boolean | asksAllowsChildren() Tells how leaf nodes are determined.
protected void | fireTreeNodesChanged(Object source, Object[] path, int[] childIndices, Object[] children) Notifies all listeners that have registered interest for notification on this event type.
protected void | fireTreeNodesInserted(Object source, Object[] path, int[] childIndices, Object[] children) Notifies all listeners that have registered interest for notification on this event type.
protected void | fireTreeNodesRemoved(Object source, Object[] path, int[] childIndices, Object[] children) Notifies all listeners that have registered interest for notification on this event type.
protected void | fireTreeStructureChanged(Object source, Object[] path, int[] childIndices, Object[] children) Notifies all listeners that have registered interest for notification on this event type.
Object | getChild(Object parent, int index) Returns the child of parent at index index in the parent's child array.
int | getChildCount(Object parent) Returns the number of children of parent.
int | getIndexOfChild(Object parent, Object child) Returns the index of child in parent.
EventListener[] | getListeners(Class listenerType) Returns an array of all the objects currently registered as FooListeners upon this model.
TreeNode[] | getPathToRoot(TreeNode aNode) Builds the parents of node up to and including the root node, where the original node is the last element in the returned array.
protected TreeNode[] | getPathToRoot(TreeNode aNode, int depth) Builds the parents of node up to and including the root node, where the original node is the last element in the returned array.
Object | getRoot() Returns the root of the tree.
TreeModelListener[] | getTreeModelListeners() Returns an array of all the tree model listeners registered on this model.
void | insertNodeInto(MutableTreeNode newChild, MutableTreeNode parent, int index) Invoked this to insert newChild at location index in parents children.
boolean | isLeaf(Object node) Returns whether the specified node is a leaf node.
void | nodeChanged(TreeNode node) Invoke this method after you've changed how node is to be represented in the tree.
void | nodesChanged(TreeNode node, int[] childIndices) Invoke this method after you've changed how the children identified by childIndicies are to be represented in the tree.
void | nodeStructureChanged(TreeNode node) Invoke this method if you've totally changed the children of node and its childrens children...
void | nodesWereInserted(TreeNode node, int[] childIndices) Invoke this method after you've inserted some TreeNodes into node.
void | nodesWereRemoved(TreeNode node, int[] childIndices, Object[] removedChildren) Invoke this method after you've removed some TreeNodes from node.
void | reload() Invoke this method if you've modified the TreeNodes upon which this model depends.
void | reload(TreeNode node) Invoke this method if you've modified the TreeNodes upon which this model depends.
void | removeNodeFromParent(MutableTreeNode node) Message this to remove node from its parent.
void | removeTreeModelListener(TreeModelListener l) Removes a listener previously added with addTreeModelListener().
void | setAsksAllowsChildren(boolean newValue) Sets whether or not to test leafness by asking getAllowsChildren() or isLeaf() to the TreeNodes.
void | setRoot(TreeNode root) Sets the root to root.
void | valueForPathChanged(TreePath path, Object newValue) This sets the user object of the TreeNode identified by path and posts a node changed.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

root

protected TreeNode root
Root of the tree.

listenerList

protected EventListenerList listenerList
Listeners.

asksAllowsChildren

protected boolean asksAllowsChildren
Determines how the isLeaf method figures out if a node is a leaf node. If true, a node is a leaf node if it does not allow children. (If it allows children, it is not a leaf node, even if no children are present.) That lets you distinguish between folder nodes and file nodes in a file system, for example.

If this value is false, then any node which has no children is a leaf node, and any node may acquire children.

See Also:
TreeNode.getAllowsChildren(),
TreeModel.isLeaf(java.lang.Object),
setAsksAllowsChildren(boolean)
Constructor Detail

DefaultTreeModel

public DefaultTreeModel(TreeNode root)
Creates a tree in which any node can have children.

Parameters:
root - a TreeNode object that is the root of the tree
See Also:
DefaultTreeModel(TreeNode, boolean)

DefaultTreeModel

public DefaultTreeModel(TreeNode root,
                        boolean asksAllowsChildren)
Creates a tree specifying whether any node can have children, or whether only certain nodes can have children.

Parameters:
root - a TreeNode object that is the root of the tree
asksAllowsChildren - a boolean, false if any node can have children, true if each node is asked to see if it can have children
See Also:
asksAllowsChildren
Method Detail

setAsksAllowsChildren

public void setAsksAllowsChildren(boolean newValue)
Sets whether or not to test leafness by asking getAllowsChildren() or isLeaf() to the TreeNodes. If newvalue is true, getAllowsChildren() is messaged, otherwise isLeaf() is messaged.

asksAllowsChildren

public boolean asksAllowsChildren()
Tells how leaf nodes are determined.

Returns:
true if only nodes which do not allow children are leaf nodes, false if nodes which have no children (even if allowed) are leaf nodes
See Also:
asksAllowsChildren

setRoot

public void setRoot(TreeNode root)
Sets the root to root. A null root implies the tree is to display nothing, and is legal.

getRoot

public Object getRoot()
Returns the root of the tree. Returns null only if the tree has no nodes.

Specified by:
getRoot in interface TreeModel
Returns:
the root of the tree

getIndexOfChild

public int getIndexOfChild(Object parent,
                           Object child)
Returns the index of child in parent. If either the parent or child is null, returns -1.

Specified by:
getIndexOfChild in interface TreeModel
Parameters:
parent - a note in the tree, obtained from this data source
child - the node we are interested in
Returns:
the index of the child in the parent, or -1 if either the parent or the child is null

getChild

public Object getChild(Object parent,
                       int index)
Returns the child of parent at index index in the parent's child array. parent must be a node previously obtained from this data source. This should not return null if index is a valid index for parent (that is index >= 0 && index < getChildCount(parent)).

Specified by:
getChild in interface TreeModel
Parameters:
parent - a node in the tree, obtained from this data source
Returns:
the child of parent at index index

getChildCount

public int getChildCount(Object parent)
Returns the number of children of parent. Returns 0 if the node is a leaf or if it has no children. parent must be a node previously obtained from this data source.

Specified by:
getChildCount in interface TreeModel
Parameters:
parent - a node in the tree, obtained from this data source
Returns:
the number of children of the node parent

isLeaf

public boolean isLeaf(Object node)
Returns whether the specified node is a leaf node. The way the test is performed depends on the askAllowsChildren setting.

Specified by:
isLeaf in interface TreeModel
Parameters:
node - the node to check
Returns:
true if the node is a leaf node
See Also:
asksAllowsChildren, TreeModel.isLeaf(java.lang.Object)

reload

public void reload()
Invoke this method if you've modified the TreeNodes upon which this model depends. The model will notify all of its listeners that the model has changed.

valueForPathChanged

public void valueForPathChanged(TreePath path,
                                Object newValue)
This sets the user object of the TreeNode identified by path and posts a node changed. If you use custom user objects in the TreeModel you're going to need to subclass this and set the user object of the changed node to something meaningful.

Specified by:
valueForPathChanged in interface TreeModel
Parameters:
path - path to the node that the user has altered
newValue - the new value from the TreeCellEditor

insertNodeInto

public void insertNodeInto(MutableTreeNode newChild,
                           MutableTreeNode parent,
                           int index)
Invoked this to insert newChild at location index in parents children. This will then message nodesWereInserted to create the appropriate event. This is the preferred way to add children as it will create the appropriate event.

removeNodeFromParent

public void removeNodeFromParent(MutableTreeNode node)
Message this to remove node from its parent. This will message nodesWereRemoved to create the appropriate event. This is the preferred way to remove a node as it handles the event creation for you.

nodeChanged

public void nodeChanged(TreeNode node)
Invoke this method after you've changed how node is to be represented in the tree.

reload

public void reload(TreeNode node)
Invoke this method if you've modified the TreeNodes upon which this model depends. The model will notify all of its listeners that the model has changed below the node node (PENDING).

nodesWereInserted

public void nodesWereInserted(TreeNode node,
                              int[] childIndices)
Invoke this method after you've inserted some TreeNodes into node. childIndices should be the index of the new elements and must be sorted in ascending order.

nodesWereRemoved

public void nodesWereRemoved(TreeNode node,
                             int[] childIndices,
                             Object[] removedChildren)
Invoke this method after you've removed some TreeNodes from node. childIndices should be the index of the removed elements and must be sorted in ascending order. And removedChildren should be the array of the children objects that were removed.

nodesChanged

public void nodesChanged(TreeNode node,
                         int[] childIndices)
Invoke this method after you've changed how the children identified by childIndicies are to be represented in the tree.

nodeStructureChanged

public void nodeStructureChanged(TreeNode node)
Invoke this method if you've totally changed the children of node and its childrens children... This will post a treeStructureChanged event.

getPathToRoot

public TreeNode[] getPathToRoot(TreeNode aNode)
Builds the parents of node up to and including the root node, where the original node is the last element in the returned array. The length of the returned array gives the node's depth in the tree.

Parameters:
aNode - the TreeNode to get the path for

getPathToRoot

protected TreeNode[] getPathToRoot(TreeNode aNode,
                                   int depth)
Builds the parents of node up to and including the root node, where the original node is the last element in the returned array. The length of the returned array gives the node's depth in the tree.

Parameters:
aNode - the TreeNode to get the path for
depth - an int giving the number of steps already taken towards the root (on recursive calls), used to size the returned array
Returns:
an array of TreeNodes giving the path from the root to the specified node

addTreeModelListener

public void addTreeModelListener(TreeModelListener l)
Adds a listener for the TreeModelEvent posted after the tree changes.

Specified by:
addTreeModelListener in interface TreeModel
Parameters:
l - the listener to add
See Also:
removeTreeModelListener(javax.swing.event.TreeModelListener)

removeTreeModelListener

public void removeTreeModelListener(TreeModelListener l)
Removes a listener previously added with addTreeModelListener().

Specified by:
removeTreeModelListener in interface TreeModel
Parameters:
l - the listener to remove
See Also:
addTreeModelListener(javax.swing.event.TreeModelListener)

getTreeModelListeners

public TreeModelListener[] getTreeModelListeners()
Returns an array of all the tree model listeners registered on this model.

Returns:
all of this model's TreeModelListeners or an empty array if no tree model listeners are currently registered
Since:
1.4
See Also:
addTreeModelListener(javax.swing.event.TreeModelListener), removeTreeModelListener(javax.swing.event.TreeModelListener)

fireTreeNodesChanged

protected void fireTreeNodesChanged(Object source,
                                    Object[] path,
                                    int[] childIndices,
                                    Object[] children)
Notifies all listeners that have registered interest for notification on this event type. The event instance is lazily created using the parameters passed into the fire method.

Parameters:
source - the node being changed
path - the path to the root node
childIndices - the indices of the changed elements
children - the changed elements
See Also:
EventListenerList

fireTreeNodesInserted

protected void fireTreeNodesInserted(Object source,
                                     Object[] path,
                                     int[] childIndices,
                                     Object[] children)
Notifies all listeners that have registered interest for notification on this event type. The event instance is lazily created using the parameters passed into the fire method.

Parameters:
source - the node where new elements are being inserted
path - the path to the root node
childIndices - the indices of the new elements
children - the new elements
See Also:
EventListenerList

fireTreeNodesRemoved

protected void fireTreeNodesRemoved(Object source,
                                    Object[] path,
                                    int[] childIndices,
                                    Object[] children)
Notifies all listeners that have registered interest for notification on this event type. The event instance is lazily created using the parameters passed into the fire method.

Parameters:
source - the node where elements are being removed
path - the path to the root node
childIndices - the indices of the removed elements
children - the removed elements
See Also:
EventListenerList

fireTreeStructureChanged

protected void fireTreeStructureChanged(Object source,
                                        Object[] path,
                                        int[] childIndices,
                                        Object[] children)
Notifies all listeners that have registered interest for notification on this event type. The event instance is lazily created using the parameters passed into the fire method.

Parameters:
source - the node where the tree model has changed
path - the path to the root node
childIndices - the indices of the affected elements
children - the affected elements
See Also:
EventListenerList

getListeners

public EventListener[] getListeners(Class listenerType)
Returns an array of all the objects currently registered as FooListeners upon this model. FooListeners are registered using the addFooListener method.

You can specify the listenerType argument with a class literal, such as FooListener.class. For example, you can query a DefaultTreeModel m for its tree model listeners with the following code:

TreeModelListener[] tmls = (TreeModelListener[])(m.getListeners(TreeModelListener.class));
If no such listeners exist, this method returns an empty array.

Parameters:
listenerType - the type of listeners requested; this parameter should specify an interface that descends from java.util.EventListener
Returns:
an array of all objects registered as FooListeners on this component, or an empty array if no such listeners have been added
Throws:
ClassCastException - if listenerType doesn't specify a class or interface that implements java.util.EventListener
Since:
1.3
See Also:
getTreeModelListeners()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DefaultTreeSelectionModel (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.tree
Class DefaultTreeSelectionModel

java.lang.Object
    extended by javax.swing.tree.DefaultTreeSelectionModel
All Implemented Interfaces:
Cloneable, Serializable, TreeSelectionModel
Direct Known Subclasses:
JTree.EmptySelectionModel
public class DefaultTreeSelectionModel
extends Object
implements Cloneable, Serializable, TreeSelectionModel

Default implementation of TreeSelectionModel. Listeners are notified whenever the paths in the selection change, not the rows. In order to be able to track row changes you may wish to become a listener for expansion events on the tree and test for changes from there.

resetRowSelection is called from any of the methods that update the selected paths. If you subclass any of these methods to filter what is allowed to be selected, be sure and message resetRowSelection if you do not message super.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

See Also:
JTree

Field Summary
protected SwingPropertyChangeSupport | changeSupport Used to messaged registered listeners.
protected int | leadIndex Index of the lead path in selection.
protected TreePath | leadPath Last path that was added.
protected int | leadRow Lead row.
protected EventListenerList | listenerList Event listener list.
protected DefaultListSelectionModel | listSelectionModel Handles maintaining the list selection model.
protected RowMapper | rowMapper Provides a row for a given path.
protected TreePath[] | selection Paths that are currently selected.
static String | SELECTION_MODE_PROPERTY Property name for selectionMode.
protected int | selectionMode Mode for the selection, will be either SINGLE_TREE_SELECTION, CONTIGUOUS_TREE_SELECTION or DISCONTIGUOUS_TREE_SELECTION.
Fields inherited from interface javax.swing.tree.TreeSelectionModel
CONTIGUOUS_TREE_SELECTION, DISCONTIGUOUS_TREE_SELECTION, SINGLE_TREE_SELECTION
Constructor Summary
DefaultTreeSelectionModel()
Creates a new instance of DefaultTreeSelectionModel that is empty, with a selection mode of DISCONTIGUOUS_TREE_SELECTION.
Method Summary
void | addPropertyChangeListener(PropertyChangeListener listener) Adds a PropertyChangeListener to the listener list.
void | addSelectionPath(TreePath path) Adds path to the current selection.
void | addSelectionPaths(TreePath[] paths) Adds paths to the current selection.
void | addTreeSelectionListener(TreeSelectionListener x) Adds x to the list of listeners that are notified each time the set of selected TreePaths changes.
protected boolean | arePathsContiguous(TreePath[] paths) Returns true if the paths are contiguous, or this object has no RowMapper.
protected boolean | canPathsBeAdded(TreePath[] paths) Used to test if a particular set of TreePaths can be added.
protected boolean | canPathsBeRemoved(TreePath[] paths) Returns true if the paths can be removed without breaking the continuity of the model.
void | clearSelection() Empties the current selection.
Object | clone() Returns a clone of this object with the same selection.
protected void | fireValueChanged(TreeSelectionEvent e) Notifies all listeners that are registered for tree selection events on this object.
TreePath | getLeadSelectionPath() Returns the last path that was added.
int | getLeadSelectionRow() Returns the lead selection index.
EventListener[] | getListeners(Class listenerType) Returns an array of all the objects currently registered as FooListeners upon this model.
int | getMaxSelectionRow() Returns the largest value obtained from the RowMapper for the current set of selected TreePaths.
int | getMinSelectionRow() Returns the smallest value obtained from the RowMapper for the current set of selected TreePaths.
PropertyChangeListener[] | getPropertyChangeListeners() Returns an array of all the property change listeners registered on this DefaultTreeSelectionModel.
RowMapper | getRowMapper() Returns the RowMapper instance that is able to map a TreePath to a row.
int | getSelectionCount() Returns the number of paths that are selected.
int | getSelectionMode() Returns the selection mode, one of SINGLE_TREE_SELECTION, DISCONTIGUOUS_TREE_SELECTION or CONTIGUOUS_TREE_SELECTION.
TreePath | getSelectionPath() Returns the first path in the selection.
TreePath[] | getSelectionPaths() Returns the paths in the selection.
int[] | getSelectionRows() Returns all of the currently selected rows.
TreeSelectionListener[] | getTreeSelectionListeners() Returns an array of all the tree selection listeners registered on this model.
protected void | insureRowContinuity() Makes sure the currently selected TreePaths are valid for the current selection mode.
protected void | insureUniqueness() This method is obsolete and its implementation is now a noop.
boolean | isPathSelected(TreePath path) Returns true if the path, path, is in the current selection.
boolean | isRowSelected(int row) Returns true if the row identified by row is selected.
boolean | isSelectionEmpty() Returns true if the selection is currently empty.
protected void | notifyPathChange(Vector changedPaths, TreePath oldLeadSelection) Notifies listeners of a change in path.
void | removePropertyChangeListener(PropertyChangeListener listener) Removes a PropertyChangeListener from the listener list.
void | removeSelectionPath(TreePath path) Removes path from the selection.
void | removeSelectionPaths(TreePath[] paths) Removes paths from the selection.
void | removeTreeSelectionListener(TreeSelectionListener x) Removes x from the list of listeners that are notified each time the set of selected TreePaths changes.
void | resetRowSelection() Updates this object's mapping from TreePath to rows.
void | setRowMapper(RowMapper newMapper) Sets the RowMapper instance.
void | setSelectionMode(int mode) Sets the selection model, which must be one of SINGLE_TREE_SELECTION, CONTIGUOUS_TREE_SELECTION or DISCONTIGUOUS_TREE_SELECTION.
void | setSelectionPath(TreePath path) Sets the selection to path.
void | setSelectionPaths(TreePath[] pPaths) Sets the selection to the paths in paths.
String | toString() Returns a string that displays and identifies this object's properties.
protected void | updateLeadIndex() Updates the leadIndex instance variable.
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

SELECTION_MODE_PROPERTY

public static final String SELECTION_MODE_PROPERTY
Property name for selectionMode.

See Also:
Constant Field Values

changeSupport

protected SwingPropertyChangeSupport changeSupport
Used to messaged registered listeners.

selection

protected TreePath[] selection
Paths that are currently selected. Will be null if nothing is currently selected.

listenerList

protected EventListenerList listenerList
Event listener list.

rowMapper

protected transient RowMapper rowMapper
Provides a row for a given path.

listSelectionModel

protected DefaultListSelectionModel listSelectionModel
Handles maintaining the list selection model. The RowMapper is used to map from a TreePath to a row, and the value is then placed here.

selectionMode

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

leadPath

protected TreePath leadPath
Last path that was added.

leadIndex

protected int leadIndex
Index of the lead path in selection.

leadRow

protected int leadRow
Lead row.

Constructor Detail

DefaultTreeSelectionModel

public DefaultTreeSelectionModel()
Creates a new instance of DefaultTreeSelectionModel that is empty, with a selection mode of DISCONTIGUOUS_TREE_SELECTION.

Method Detail

setRowMapper

public void setRowMapper(RowMapper newMapper)
Sets the RowMapper instance. This instance is used to determine the row for a particular TreePath.

Specified by:
setRowMapper in interface TreeSelectionModel

getRowMapper

public RowMapper getRowMapper()
Returns the RowMapper instance that is able to map a TreePath to a row.

Specified by:
getRowMapper in interface TreeSelectionModel

setSelectionMode

public void setSelectionMode(int mode)
Sets the selection model, which must be one of SINGLE_TREE_SELECTION, CONTIGUOUS_TREE_SELECTION or DISCONTIGUOUS_TREE_SELECTION. If mode is not one of the defined value, DISCONTIGUOUS_TREE_SELECTION is assumed.

This may change the selection if the current selection is not valid for the new mode. For example, if three TreePaths are selected when the mode is changed to SINGLE_TREE_SELECTION, only one TreePath will remain selected. It is up to the particular implementation to decide what TreePath remains selected.

Setting the mode to something other than the defined types will result in the mode becoming DISCONTIGUOUS_TREE_SELECTION.

Specified by:
setSelectionMode in interface TreeSelectionModel

getSelectionMode

public int getSelectionMode()
Returns the selection mode, one of SINGLE_TREE_SELECTION, DISCONTIGUOUS_TREE_SELECTION or CONTIGUOUS_TREE_SELECTION.

Specified by:
getSelectionMode in interface TreeSelectionModel

setSelectionPath

public void setSelectionPath(TreePath path)
Sets the selection to path. If this represents a change, then the TreeSelectionListeners are notified. If path is null, this has the same effect as invoking clearSelection.

Specified by:
setSelectionPath in interface TreeSelectionModel
Parameters:
path - new path to select

setSelectionPaths

public void setSelectionPaths(TreePath[] pPaths)
Sets the selection to the paths in paths. If this represents a change the TreeSelectionListeners are notified. Potentially paths will be held by this object; in other words don't change any of the objects in the array once passed in.

If paths is null, this has the same effect as invoking clearSelection.

The lead path is set to the last path in pPaths.

If the selection mode is CONTIGUOUS_TREE_SELECTION, and adding the new paths would make the selection discontiguous, the selection is reset to the first TreePath in paths.

Specified by:
setSelectionPaths in interface TreeSelectionModel
Parameters:
pPaths - new selection

addSelectionPath

public void addSelectionPath(TreePath path)
Adds path to the current selection. If path is not currently in the selection the TreeSelectionListeners are notified. This has no effect if path is null.

Specified by:
addSelectionPath in interface TreeSelectionModel
Parameters:
path - the new path to add to the current selection

addSelectionPaths

public void addSelectionPaths(TreePath[] paths)
Adds paths to the current selection. If any of the paths in paths are not currently in the selection the TreeSelectionListeners are notified. This has no effect if paths is null.

The lead path is set to the last element in paths.

If the selection mode is CONTIGUOUS_TREE_SELECTION, and adding the new paths would make the selection discontiguous. Then two things can result: if the TreePaths in paths are contiguous, then the selection becomes these TreePaths, otherwise the TreePaths aren't contiguous and the selection becomes the first TreePath in paths.

Specified by:
addSelectionPaths in interface TreeSelectionModel
Parameters:
paths - the new path to add to the current selection

removeSelectionPath

public void removeSelectionPath(TreePath path)
Removes path from the selection. If path is in the selection The TreeSelectionListeners are notified. This has no effect if path is null.

Specified by:
removeSelectionPath in interface TreeSelectionModel
Parameters:
path - the path to remove from the selection

removeSelectionPaths

public void removeSelectionPaths(TreePath[] paths)
Removes paths from the selection. If any of the paths in paths are in the selection the TreeSelectionListeners are notified. This has no effect if paths is null.

Specified by:
removeSelectionPaths in interface TreeSelectionModel
Parameters:
paths - the paths to remove from the selection

getSelectionPath

public TreePath getSelectionPath()
Returns the first path in the selection. This is useful if there if only one item currently selected.

Specified by:
getSelectionPath in interface TreeSelectionModel

getSelectionPaths

public TreePath[] getSelectionPaths()
Returns the paths in the selection. This will return null (or an empty array) if nothing is currently selected.

Specified by:
getSelectionPaths in interface TreeSelectionModel

getSelectionCount

public int getSelectionCount()
Returns the number of paths that are selected.

Specified by:
getSelectionCount in interface TreeSelectionModel

isPathSelected

public boolean isPathSelected(TreePath path)
Returns true if the path, path, is in the current selection.

Specified by:
isPathSelected in interface TreeSelectionModel

isSelectionEmpty

public boolean isSelectionEmpty()
Returns true if the selection is currently empty.

Specified by:
isSelectionEmpty in interface TreeSelectionModel

clearSelection

public void clearSelection()
Empties the current selection. If this represents a change in the current selection, the selection listeners are notified.

Specified by:
clearSelection in interface TreeSelectionModel

addTreeSelectionListener

public void addTreeSelectionListener(TreeSelectionListener x)
Adds x to the list of listeners that are notified each time the set of selected TreePaths changes.

Specified by:
addTreeSelectionListener in interface TreeSelectionModel
Parameters:
x - the new listener to be added

removeTreeSelectionListener

public void removeTreeSelectionListener(TreeSelectionListener x)
Removes x from the list of listeners that are notified each time the set of selected TreePaths changes.

Specified by:
removeTreeSelectionListener in interface TreeSelectionModel
Parameters:
x - the listener to remove

getTreeSelectionListeners

public TreeSelectionListener[] getTreeSelectionListeners()
Returns an array of all the tree selection listeners registered on this model.

Returns:
all of this model's TreeSelectionListeners or an empty array if no tree selection listeners are currently registered
Since:
1.4
See Also:
addTreeSelectionListener(javax.swing.event.TreeSelectionListener), removeTreeSelectionListener(javax.swing.event.TreeSelectionListener)

fireValueChanged

protected void fireValueChanged(TreeSelectionEvent e)
Notifies all listeners that are registered for tree selection events on this object.

See Also:
addTreeSelectionListener(javax.swing.event.TreeSelectionListener), EventListenerList

getListeners

public EventListener[] getListeners(Class listenerType)
Returns an array of all the objects currently registered as FooListeners upon this model. FooListeners are registered using the addFooListener method.

You can specify the listenerType argument with a class literal, such as FooListener.class. For example, you can query a DefaultTreeSelectionModel m for its tree selection listeners with the following code:

TreeSelectionListener[] tsls = (TreeSelectionListener[])(m.getListeners(TreeSelectionListener.class));
If no such listeners exist, this method returns an empty array.

Parameters:
listenerType - the type of listeners requested; this parameter should specify an interface that descends from java.util.EventListener
Returns:
an array of all objects registered as FooListeners on this component, or an empty array if no such listeners have been added
Throws:
ClassCastException - if listenerType doesn't specify a class or interface that implements java.util.EventListener
Since:
1.3
See Also:
getTreeSelectionListeners(), getPropertyChangeListeners()

getSelectionRows

public int[] getSelectionRows()
Returns all of the currently selected rows. This will return null (or an empty array) if there are no selected TreePaths or a RowMapper has not been set. This may return an array of length less that than of the selected TreePaths if some of the rows are not visible (that is the RowMapper returned -1 for the row corresponding to the TreePath).

Specified by:
getSelectionRows in interface TreeSelectionModel

getMinSelectionRow

public int getMinSelectionRow()
Returns the smallest value obtained from the RowMapper for the current set of selected TreePaths. If nothing is selected, or there is no RowMapper, this will return -1.

Specified by:
getMinSelectionRow in interface TreeSelectionModel

getMaxSelectionRow

public int getMaxSelectionRow()
Returns the largest value obtained from the RowMapper for the current set of selected TreePaths. If nothing is selected, or there is no RowMapper, this will return -1.

Specified by:
getMaxSelectionRow in interface TreeSelectionModel

isRowSelected

public boolean isRowSelected(int row)
Returns true if the row identified by row is selected.

Specified by:
isRowSelected in interface TreeSelectionModel

resetRowSelection

public void resetRowSelection()
Updates this object's mapping from TreePath to rows. This should be invoked when the mapping from TreePaths to integers has changed (for example, a node has been expanded).

You do not normally have to call this, JTree and its associated Listeners will invoke this for you. If you are implementing your own View class, then you will have to invoke this.

This will invoke insureRowContinuity to make sure the currently selected TreePaths are still valid based on the selection mode.

Specified by:
resetRowSelection in interface TreeSelectionModel

getLeadSelectionRow

public int getLeadSelectionRow()
Returns the lead selection index. That is the last index that was added.

Specified by:
getLeadSelectionRow in interface TreeSelectionModel

getLeadSelectionPath

public TreePath getLeadSelectionPath()
Returns the last path that was added. This may differ from the leadSelectionPath property maintained by the JTree.

Specified by:
getLeadSelectionPath in interface TreeSelectionModel

addPropertyChangeListener

public void addPropertyChangeListener(PropertyChangeListener listener)
Adds a PropertyChangeListener to the listener list. The listener is registered for all properties.

A PropertyChangeEvent will get fired when the selection mode changes.

Specified by:
addPropertyChangeListener in interface TreeSelectionModel
Parameters:
listener - the PropertyChangeListener to be added

removePropertyChangeListener

public void removePropertyChangeListener(PropertyChangeListener listener)
Removes a PropertyChangeListener from the listener list. This removes a PropertyChangeListener that was registered for all properties.

Specified by:
removePropertyChangeListener in interface TreeSelectionModel
Parameters:
listener - the PropertyChangeListener to be removed

getPropertyChangeListeners

public PropertyChangeListener[] getPropertyChangeListeners()
Returns an array of all the property change listeners registered on this DefaultTreeSelectionModel.

Returns:
all of this model's PropertyChangeListeners or an empty array if no property change listeners are currently registered
Since:
1.4
See Also:
addPropertyChangeListener(java.beans.PropertyChangeListener), removePropertyChangeListener(java.beans.PropertyChangeListener)

insureRowContinuity

protected void insureRowContinuity()
Makes sure the currently selected TreePaths are valid for the current selection mode. If the selection mode is CONTIGUOUS_TREE_SELECTION and a RowMapper exists, this will make sure all the rows are contiguous. If the selection isn't contiguous, the selection is reset to contain the first set of contiguous paths.

If the selection mode is SINGLE_TREE_SELECTION and more than one TreePath is selected, the selection is reset to contain the first path currently selected.

arePathsContiguous

protected boolean arePathsContiguous(TreePath[] paths)
Returns true if the paths are contiguous, or this object has no RowMapper.

canPathsBeAdded

protected boolean canPathsBeAdded(TreePath[] paths)
Used to test if a particular set of TreePaths can be added. This will return true if paths is null (or empty), or this object has no RowMapper, or nothing is currently selected, or the selection mode is DISCONTIGUOUS_TREE_SELECTION, or adding the paths to the current selection still results in a contiguous set of TreePaths.

canPathsBeRemoved

protected boolean canPathsBeRemoved(TreePath[] paths)
Returns true if the paths can be removed without breaking the continuity of the model. This is rather expensive.

notifyPathChange

protected void notifyPathChange(Vector changedPaths,
                                TreePath oldLeadSelection)
Notifies listeners of a change in path. changePaths should contain instances of PathPlaceHolder.

updateLeadIndex

protected void updateLeadIndex()
Updates the leadIndex instance variable.

insureUniqueness

protected void insureUniqueness()
This method is obsolete and its implementation is now a noop. It's still called by setSelectionPaths and addSelectionPaths, but only for backwards compatability.

toString

public String toString()
Returns a string that displays and identifies this object's properties.

Overrides:
toString in class Object
Returns:
a String representation of this object

clone

public Object clone()
             throws CloneNotSupportedException
Returns a clone of this object with the same selection. This method does not duplicate selection listeners and property listeners.

Overrides:
clone in class Object
Returns:
a clone of this instance.
Throws:
CloneNotSupportedException - never thrown by instances of this class
See Also:
Cloneable
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ExpandVetoException (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.swing.tree
Class ExpandVetoException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by javax.swing.tree.ExpandVetoException
All Implemented Interfaces:
Serializable
public class ExpandVetoException
extends Exception

Exception used to stop and expand/collapse from happening. See How to Write a Tree-Will-Expand Listener in The Java Tutorial for further information and examples.

Field Summary
protected  TreeExpansionEvent event
The event that the exception was created for.
Constructor Summary
ExpandVetoException(TreeExpansionEvent event)
Constructs an ExpandVetoException object with no message.
ExpandVetoException(TreeExpansionEvent event, String message)
Constructs an ExpandVetoException object with the specified message.
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

event

protected TreeExpansionEvent event
The event that the exception was created for.

Constructor Detail

ExpandVetoException

public ExpandVetoException(TreeExpansionEvent event)
Constructs an ExpandVetoException object with no message.

Parameters:
event - a TreeExpansionEvent object

ExpandVetoException

public ExpandVetoException(TreeExpansionEvent event,
                           String message)
Constructs an ExpandVetoException object with the specified message.

Parameters:
event - a TreeExpansionEvent object
message - a String containing the message
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


FixedHeightLayoutCache (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.tree
Class FixedHeightLayoutCache

java.lang.Object
    extended by javax.swing.tree.AbstractLayoutCache
        extended by javax.swing.tree.FixedHeightLayoutCache
All Implemented Interfaces:
RowMapper
public class FixedHeightLayoutCache
extends AbstractLayoutCache

NOTE: This will become more open in a future release.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Nested Class Summary
Nested classes inherited from class javax.swing.tree.AbstractLayoutCache
AbstractLayoutCache.NodeDimensions
Field Summary
Fields inherited from class javax.swing.tree.AbstractLayoutCache
nodeDimensions, rootVisible, rowHeight, treeModel, treeSelectionModel
Constructor Summary
FixedHeightLayoutCache()
Method Summary
Rectangle | getBounds(TreePath path, Rectangle placeIn) Returns a rectangle giving the bounds needed to draw path.
boolean | getExpandedState(TreePath path) Returns true if the path is expanded, and visible.
TreePath | getPathClosestTo(int x, int y) Returns the path to the node that is closest to x,y.
TreePath | getPathForRow(int row) Returns the path for passed in row.
int | getRowCount() Returns the number of visible rows.
int | getRowForPath(TreePath path) Returns the row that the last item identified in path is visible at.
int | getVisibleChildCount(TreePath path) Returns the number of visible children for row.
Enumeration | getVisiblePathsFrom(TreePath path) Returns an Enumerator that increments over the visible paths starting at the passed in location.
void | invalidatePathBounds(TreePath path) Does nothing, FixedHeightLayoutCache doesn't cache width, and that is all that could change.
void | invalidateSizes() Informs the TreeState that it needs to recalculate all the sizes it is referencing.
boolean | isExpanded(TreePath path) Returns true if the value identified by row is currently expanded.
void | setExpandedState(TreePath path, boolean isExpanded) Marks the path path expanded state to isExpanded.
void | setModel(TreeModel newModel) Sets the TreeModel that will provide the data.
void | setRootVisible(boolean rootVisible) Determines whether or not the root node from the TreeModel is visible.
void | setRowHeight(int rowHeight) Sets the height of each cell.
void | treeNodesChanged(TreeModelEvent e) Invoked after a node (or a set of siblings) has changed in some way.
void | treeNodesInserted(TreeModelEvent e) Invoked after nodes have been inserted into the tree.
void | treeNodesRemoved(TreeModelEvent e) Invoked after nodes have been removed from the tree.
void | treeStructureChanged(TreeModelEvent e) Invoked after the tree has drastically changed structure from a given node down.
Methods inherited from class javax.swing.tree.AbstractLayoutCache
getModel, getNodeDimensions, getNodeDimensions, getPreferredHeight, getPreferredWidth, getRowHeight, getRowsForPaths, getSelectionModel, isFixedRowHeight, isRootVisible, setNodeDimensions, setSelectionModel
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

FixedHeightLayoutCache

public FixedHeightLayoutCache()
Method Detail

setModel

public void setModel(TreeModel newModel)
Sets the TreeModel that will provide the data.

Overrides:
setModel in class AbstractLayoutCache
Parameters:
newModel - the TreeModel that is to provide the data

setRootVisible

public void setRootVisible(boolean rootVisible)
Determines whether or not the root node from the TreeModel is visible.

Overrides:
setRootVisible in class AbstractLayoutCache
Parameters:
rootVisible - true if the root node of the tree is to be displayed
See Also:
AbstractLayoutCache.rootVisible

setRowHeight

public void setRowHeight(int rowHeight)
Sets the height of each cell. If rowHeight is less than or equal to 0 this will throw an IllegalArgumentException.

Overrides:
setRowHeight in class AbstractLayoutCache
Parameters:
rowHeight - the height of each cell, in pixels

getRowCount

public int getRowCount()
Returns the number of visible rows.

Specified by:
getRowCount in class AbstractLayoutCache
Returns:
the number of rows being displayed

invalidatePathBounds

public void invalidatePathBounds(TreePath path)
Does nothing, FixedHeightLayoutCache doesn't cache width, and that is all that could change.

Specified by:
invalidatePathBounds in class AbstractLayoutCache
Parameters:
path - the path being updated

invalidateSizes

public void invalidateSizes()
Informs the TreeState that it needs to recalculate all the sizes it is referencing.

Specified by:
invalidateSizes in class AbstractLayoutCache

isExpanded

public boolean isExpanded(TreePath path)
Returns true if the value identified by row is currently expanded.

Specified by:
isExpanded in class AbstractLayoutCache

getBounds

public Rectangle getBounds(TreePath path,
                           Rectangle placeIn)
Returns a rectangle giving the bounds needed to draw path.

Specified by:
getBounds in class AbstractLayoutCache
Parameters:
path - a TreePath specifying a node
placeIn - a Rectangle object giving the available space
Returns:
a Rectangle object specifying the space to be used

getPathForRow

public TreePath getPathForRow(int row)
Returns the path for passed in row. If row is not visible null is returned.

Specified by:
getPathForRow in class AbstractLayoutCache
Parameters:
row - the row being queried
Returns:
the TreePath for the given row

getRowForPath

public int getRowForPath(TreePath path)
Returns the row that the last item identified in path is visible at. Will return -1 if any of the elements in path are not currently visible.

Specified by:
getRowForPath in class AbstractLayoutCache
Parameters:
path - the TreePath being queried
Returns:
the row where the last item in path is visible or -1 if any elements in path aren't currently visible

getPathClosestTo

public TreePath getPathClosestTo(int x,
                                 int y)
Returns the path to the node that is closest to x,y. If there is nothing currently visible this will return null, otherwise it'll always return a valid path. If you need to test if the returned object is exactly at x, y you should get the bounds for the returned path and test x, y against that.

Specified by:
getPathClosestTo in class AbstractLayoutCache
Parameters:
x - the horizontal component of the desired location
y - the vertical component of the desired location
Returns:
the TreePath closest to the specified point

getVisibleChildCount

public int getVisibleChildCount(TreePath path)
Returns the number of visible children for row.

Specified by:
getVisibleChildCount in class AbstractLayoutCache
Parameters:
path - the path being queried
Returns:
the number of visible children for the specified path

getVisiblePathsFrom

public Enumeration getVisiblePathsFrom(TreePath path)
Returns an Enumerator that increments over the visible paths starting at the passed in location. The ordering of the enumeration is based on how the paths are displayed.

Specified by:
getVisiblePathsFrom in class AbstractLayoutCache
Parameters:
path - the starting location for the enumeration
Returns:
the Enumerator starting at the desired location

setExpandedState

public void setExpandedState(TreePath path,
                             boolean isExpanded)
Marks the path path expanded state to isExpanded.

Specified by:
setExpandedState in class AbstractLayoutCache
Parameters:
path - the path being expanded or collapsed
isExpanded - true if the path should be expanded, false otherwise

getExpandedState

public boolean getExpandedState(TreePath path)
Returns true if the path is expanded, and visible.

Specified by:
getExpandedState in class AbstractLayoutCache
Parameters:
path - the path being queried
Returns:
true if the path is expanded and visible, false otherwise

treeNodesChanged

public void treeNodesChanged(TreeModelEvent e)

Invoked after a node (or a set of siblings) has changed in some way. The node(s) have not changed locations in the tree or altered their children arrays, but other attributes have changed and may affect presentation. Example: the name of a file has changed, but it is in the same location in the file system.

e.path() returns the path the parent of the changed node(s).

e.childIndices() returns the index(es) of the changed node(s).

Specified by:
treeNodesChanged in class AbstractLayoutCache
Parameters:
e - the TreeModelEvent

treeNodesInserted

public void treeNodesInserted(TreeModelEvent e)

Invoked after nodes have been inserted into the tree.

e.path() returns the parent of the new nodes

e.childIndices() returns the indices of the new nodes in ascending order.

Specified by:
treeNodesInserted in class AbstractLayoutCache
Parameters:
e - the TreeModelEvent

treeNodesRemoved

public void treeNodesRemoved(TreeModelEvent e)

Invoked after nodes have been removed from the tree. Note that if a subtree is removed from the tree, this method may only be invoked once for the root of the removed subtree, not once for each individual set of siblings removed.

e.path() returns the former parent of the deleted nodes.

e.childIndices() returns the indices the nodes had before they were deleted in ascending order.

Specified by:
treeNodesRemoved in class AbstractLayoutCache
Parameters:
e - the TreeModelEvent

treeStructureChanged

public void treeStructureChanged(TreeModelEvent e)

Invoked after the tree has drastically changed structure from a given node down. If the path returned by e.getPath() is of length one and the first element does not identify the current root node the first element should become the new root of the tree.

e.path() holds the path to the node.

e.childIndices() returns null.

Specified by:
treeStructureChanged in class AbstractLayoutCache
Parameters:
e - the TreeModelEvent
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MutableTreeNode (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.swing.tree
Interface MutableTreeNode

All Superinterfaces:
TreeNode
All Known Implementing Classes:
DefaultMutableTreeNode
public interface MutableTreeNode
extends TreeNode

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.

See Also:
DefaultMutableTreeNode, JTree

Method Summary
void | insert(MutableTreeNode child, int index) Adds child to the receiver at index.
void | remove(int index) Removes the child at index from the receiver.
void | remove(MutableTreeNode node) Removes node from the receiver.
void | removeFromParent() Removes the receiver from its parent.
void | setParent(MutableTreeNode newParent) Sets the parent of the receiver to newParent.
void | setUserObject(Object object) Resets the user object of the receiver to object.
Methods inherited from interface javax.swing.tree.TreeNode
children, getAllowsChildren, getChildAt, getChildCount, getIndex, getParent, isLeaf

Method Detail

insert

public void insert(MutableTreeNode child,
                   int index)
Adds child to the receiver at index. child will be messaged with setParent.

remove

public void remove(int index)
Removes the child at index from the receiver.

remove

public void remove(MutableTreeNode node)
Removes node from the receiver. setParent will be messaged on node.

setUserObject

public void setUserObject(Object object)
Resets the user object of the receiver to object.

removeFromParent

public void removeFromParent()
Removes the receiver from its parent.

setParent

public void setParent(MutableTreeNode newParent)
Sets the parent of the receiver to newParent.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


javax.swing.tree (Java 2 Platform SE v1.4.2)

 javax.swing.tree
Interfaces
MutableTreeNode
RowMapper
TreeCellEditor
TreeCellRenderer
TreeModel
TreeNode
TreeSelectionModel
Classes
AbstractLayoutCache
AbstractLayoutCache.NodeDimensions
DefaultMutableTreeNode
DefaultTreeCellEditor
DefaultTreeCellRenderer
DefaultTreeModel
DefaultTreeSelectionModel
FixedHeightLayoutCache
TreePath
VariableHeightLayoutCache
Exceptions
ExpandVetoException


javax.swing.tree (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package javax.swing.tree

Provides classes and interfaces for dealing with javax.swing.JTree.

See:
Description

Interface Summary
MutableTreeNode | 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.
RowMapper | Defines the requirements for an object that translates paths in the tree into display rows.
TreeCellEditor | Adds to CellEditor the extensions necessary to configure an editor in a tree.
TreeCellRenderer | Defines the requirements for an object that displays a tree node.
TreeModel | The interface that defines a suitable data model for a JTree.
TreeNode | Defines the requirements for an object that can be used as a tree node in a JTree.
TreeSelectionModel | This interface represents the current state of the selection for the tree component.

Class Summary
AbstractLayoutCache | Warning: Serialized objects of this class will not be compatible with future Swing releases.
AbstractLayoutCache.NodeDimensions | Used by AbstractLayoutCache to determine the size and x origin of a particular node.
DefaultMutableTreeNode | A DefaultMutableTreeNode is a general-purpose node in a tree data structure.
DefaultTreeCellEditor | A TreeCellEditor.
DefaultTreeCellRenderer | Displays an entry in a tree.
DefaultTreeModel | A simple tree data model that uses TreeNodes.
DefaultTreeSelectionModel | Default implementation of TreeSelectionModel.
FixedHeightLayoutCache | NOTE: This will become more open in a future release.
TreePath | Represents a path to a node.
VariableHeightLayoutCache | NOTE: This will become more open in a future release.

Exception Summary
ExpandVetoException Exception used to stop and expand/collapse from happening.

Package javax.swing.tree Description

Provides classes and interfaces for dealing with javax.swing.JTree. You use these classes and interfaces if you want control over how trees are constructed, updated, and rendered, as well as how data associated with the tree nodes are viewed and managed.

Note: Most of the Swing API is not thread safe. For details, see Threads and Swing, a section in The Java Tutorial.

Related Documentation

For overviews, tutorials, examples, guides, and tool documentation, please see:
  • How to Use Trees, a section in The Java Tutorial

Since:
1.2
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


javax.swing.tree Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package javax.swing.tree

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class javax.swing.tree.AbstractLayoutCache (implements javax.swing.tree.RowMapper)
      • class javax.swing.tree.FixedHeightLayoutCache
      • class javax.swing.tree.VariableHeightLayoutCache
    • class javax.swing.tree.AbstractLayoutCache.NodeDimensions
    • class java.awt.Component (implements java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable)
      • class java.awt.Container
        • class javax.swing.tree.DefaultTreeCellEditor.EditorContainer
        • class javax.swing.JComponent (implements java.io.Serializable)
          • class javax.swing.JLabel (implements javax.accessibility.Accessible, javax.swing.SwingConstants)
            • class javax.swing.tree.DefaultTreeCellRenderer (implements javax.swing.tree.TreeCellRenderer)
          • class javax.swing.text.JTextComponent (implements javax.accessibility.Accessible, javax.swing.Scrollable)
            • class javax.swing.JTextField (implements javax.swing.SwingConstants)
              • class javax.swing.tree.DefaultTreeCellEditor.DefaultTextField
    • class javax.swing.tree.DefaultMutableTreeNode (implements java.lang.Cloneable, javax.swing.tree.MutableTreeNode, java.io.Serializable)
    • class javax.swing.tree.DefaultTreeCellEditor (implements java.awt.event.ActionListener, javax.swing.tree.TreeCellEditor, javax.swing.event.TreeSelectionListener)
    • class javax.swing.tree.DefaultTreeModel (implements java.io.Serializable, javax.swing.tree.TreeModel)
    • class javax.swing.tree.DefaultTreeSelectionModel (implements java.lang.Cloneable, java.io.Serializable, javax.swing.tree.TreeSelectionModel)
    • class java.lang.Throwable (implements java.io.Serializable)
      • class java.lang.Exception
        • class javax.swing.tree.ExpandVetoException
    • class javax.swing.tree.TreePath (implements java.io.Serializable)

Interface Hierarchy

  • interface javax.swing.CellEditor
    • interface javax.swing.tree.TreeCellEditor
  • interface javax.swing.tree.RowMapper
  • interface javax.swing.tree.TreeCellRenderer
  • interface javax.swing.tree.TreeModel
  • interface javax.swing.tree.TreeNode
    • interface javax.swing.tree.MutableTreeNode
  • interface javax.swing.tree.TreeSelectionModel
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package javax.swing.tree (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
javax.swing.tree

Packages that use javax.swing.tree
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.event | Provides for events fired by Swing components.
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 | Provides user interface objects built according to the Basic look and feel.
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 | Provides user interface objects that combine two or more look and feels.
javax.swing.text | Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.text.html | Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.
javax.swing.tree | Provides classes and interfaces for dealing with javax.swing.JTree.

Classes in javax.swing.tree used by javax.swing
DefaultMutableTreeNode
A DefaultMutableTreeNode is a general-purpose node in a tree data structure.
DefaultTreeSelectionModel
Default implementation of TreeSelectionModel.
ExpandVetoException
Exception used to stop and expand/collapse from happening.
MutableTreeNode
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.
TreeCellEditor
Adds to CellEditor the extensions necessary to configure an editor in a tree.
TreeCellRenderer
Defines the requirements for an object that displays a tree node.
TreeModel
The interface that defines a suitable data model for a JTree.
TreeNode
Defines the requirements for an object that can be used as a tree node in a JTree.
TreePath
Represents a path to a node.
TreeSelectionModel
This interface represents the current state of the selection for the tree component.

Classes in javax.swing.tree used by javax.swing.event
ExpandVetoException
Exception used to stop and expand/collapse from happening.
TreePath
Represents a path to a node.

Classes in javax.swing.tree used by javax.swing.plaf
TreePath
Represents a path to a node.

Classes in javax.swing.tree used by javax.swing.plaf.basic
AbstractLayoutCache
Warning: Serialized objects of this class will not be compatible with future Swing releases.
AbstractLayoutCache.NodeDimensions
Used by AbstractLayoutCache to determine the size and x origin of a particular node.
TreeCellEditor
Adds to CellEditor the extensions necessary to configure an editor in a tree.
TreeCellRenderer
Defines the requirements for an object that displays a tree node.
TreeModel
The interface that defines a suitable data model for a JTree.
TreePath
Represents a path to a node.
TreeSelectionModel
This interface represents the current state of the selection for the tree component.

Classes in javax.swing.tree used by javax.swing.plaf.metal
TreePath
Represents a path to a node.

Classes in javax.swing.tree used by javax.swing.plaf.multi
TreePath
Represents a path to a node.

Classes in javax.swing.tree used by javax.swing.text
TreeNode
Defines the requirements for an object that can be used as a tree node in a JTree.

Classes in javax.swing.tree used by javax.swing.text.html
TreeNode
Defines the requirements for an object that can be used as a tree node in a JTree.

Classes in javax.swing.tree used by javax.swing.tree
AbstractLayoutCache
Warning: Serialized objects of this class will not be compatible with future Swing releases.
AbstractLayoutCache.NodeDimensions
Used by AbstractLayoutCache to determine the size and x origin of a particular node.
DefaultMutableTreeNode
A DefaultMutableTreeNode is a general-purpose node in a tree data structure.
DefaultTreeCellRenderer
Displays an entry in a tree.
MutableTreeNode
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.
RowMapper
Defines the requirements for an object that translates paths in the tree into display rows.
TreeCellEditor
Adds to CellEditor the extensions necessary to configure an editor in a tree.
TreeCellRenderer
Defines the requirements for an object that displays a tree node.
TreeModel
The interface that defines a suitable data model for a JTree.
TreeNode
Defines the requirements for an object that can be used as a tree node in a JTree.
TreePath
Represents a path to a node.
TreeSelectionModel
This interface represents the current state of the selection for the tree component.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


RowMapper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.tree
Interface RowMapper

All Known Implementing Classes:
AbstractLayoutCache
public interface RowMapper

Defines the requirements for an object that translates paths in the tree into display rows.

Method Summary
 int[] getRowsForPaths(TreePath[] path)
Returns the rows that the TreePath instances in path are being displayed at.

Method Detail

getRowsForPaths

public int[] getRowsForPaths(TreePath[] path)
Returns the rows that the TreePath instances in path are being displayed at. The receiver should return an array of the same length as that passed in, and if one of the TreePaths in path is not valid its entry in the array should be set to -1.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TreeCellEditor (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.tree
Interface TreeCellEditor

All Superinterfaces:
CellEditor
All Known Implementing Classes:
DefaultCellEditor, DefaultTreeCellEditor
public interface TreeCellEditor
extends CellEditor

Adds to CellEditor the extensions necessary to configure an editor in a tree.

See Also:
JTree

Method Summary
 Component getTreeCellEditorComponent(JTree tree, Object value, boolean isSelected, boolean expanded, boolean leaf, int row)
Sets an initial value for the editor.
Methods inherited from interface javax.swing.CellEditor
addCellEditorListener, cancelCellEditing, getCellEditorValue, isCellEditable, removeCellEditorListener, shouldSelectCell, stopCellEditing

Method Detail

getTreeCellEditorComponent

public Component getTreeCellEditorComponent(JTree tree,
                                            Object value,
                                            boolean isSelected,
                                            boolean expanded,
                                            boolean leaf,
                                            int row)
Sets an initial value for the editor. This will cause the editor to stopEditing and lose any partially edited value if the editor is editing when this method is called.

Returns the component that should be added to the client's Component hierarchy. Once installed in the client's hierarchy this component will then be able to draw and receive user input.

Parameters:
tree - the JTree that is asking the editor to edit; this parameter can be null
value - the value of the cell to be edited
isSelected - true is the cell is to be renderer with selection highlighting
expanded - true if the node is expanded
leaf - true if the node is a leaf node
row - the row index of the node being edited
Returns:
the component for editing
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TreeCellRenderer (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.tree
Interface TreeCellRenderer

All Known Implementing Classes:
DefaultTreeCellRenderer
public interface TreeCellRenderer

Defines the requirements for an object that displays a tree node. See How to Use Trees in The Java Tutorial for an example of implementing a tree cell renderer that displays custom icons.

Method Summary
 Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus)
Sets the value of the current tree cell to value.

Method Detail

getTreeCellRendererComponent

public Component getTreeCellRendererComponent(JTree tree,
                                              Object value,
                                              boolean selected,
                                              boolean expanded,
                                              boolean leaf,
                                              int row,
                                              boolean hasFocus)
Sets the value of the current tree cell to value. If selected is true, the cell will be drawn as if selected. If expanded is true the node is currently expanded and if leaf is true the node represets a leaf and if hasFocus is true the node currently has focus. tree is the JTree the receiver is being configured for. Returns the Component that the renderer uses to draw the value.

Returns:
the Component that the renderer uses to draw the value
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TreeModel (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.tree
Interface TreeModel

All Known Implementing Classes:
DefaultTreeModel
public interface TreeModel

The interface that defines a suitable data model for a JTree. For further information on tree models, including an example of a custom implementation, see How to Use Trees in The Java Tutorial.

JTree and its related classes make extensive use of TreePaths for indentifying nodes in the TreeModel. If a TreeModel returns the same object, as compared by equals, at two different indices under the same parent than the resulting TreePath objects will be considered equal as well. Some implementations may assume that if two TreePaths are equal, they identify the same node. If this condition is not met, painting problems and other oddities may result. In other words, if getChild for a given parent returns the same Object (as determined by equals) problems may result, and it is recommended you avoid doing this.

See Also:
TreePath

Method Summary
void | addTreeModelListener(TreeModelListener l) Adds a listener for the TreeModelEvent posted after the tree changes.
Object | getChild(Object parent, int index) Returns the child of parent at index index in the parent's child array.
int | getChildCount(Object parent) Returns the number of children of parent.
int | getIndexOfChild(Object parent, Object child) Returns the index of child in parent.
Object | getRoot() Returns the root of the tree.
boolean | isLeaf(Object node) Returns true if node is a leaf.
void | removeTreeModelListener(TreeModelListener l) Removes a listener previously added with addTreeModelListener.
void | valueForPathChanged(TreePath path, Object newValue) Messaged when the user has altered the value for the item identified by path to newValue.

Method Detail

getRoot

public Object getRoot()
Returns the root of the tree. Returns null only if the tree has no nodes.

Returns:
the root of the tree

getChild

public Object getChild(Object parent,
                       int index)
Returns the child of parent at index index in the parent's child array. parent must be a node previously obtained from this data source. This should not return null if index is a valid index for parent (that is index >= 0 && index < getChildCount(parent)).

Parameters:
parent - a node in the tree, obtained from this data source
Returns:
the child of parent at index index

getChildCount

public int getChildCount(Object parent)
Returns the number of children of parent. Returns 0 if the node is a leaf or if it has no children. parent must be a node previously obtained from this data source.

Parameters:
parent - a node in the tree, obtained from this data source
Returns:
the number of children of the node parent

isLeaf

public boolean isLeaf(Object node)
Returns true if node is a leaf. It is possible for this method to return false even if node has no children. A directory in a filesystem, for example, may contain no files; the node representing the directory is not a leaf, but it also has no children.

Parameters:
node - a node in the tree, obtained from this data source
Returns:
true if node is a leaf

valueForPathChanged

public void valueForPathChanged(TreePath path,
                                Object newValue)
Messaged when the user has altered the value for the item identified by path to newValue. If newValue signifies a truly new value the model should post a treeNodesChanged event.

Parameters:
path - path to the node that the user has altered
newValue - the new value from the TreeCellEditor

getIndexOfChild

public int getIndexOfChild(Object parent,
                           Object child)
Returns the index of child in parent. If parent is null or child is null, returns -1.

Parameters:
parent - a note in the tree, obtained from this data source
child - the node we are interested in
Returns:
the index of the child in the parent, or -1 if either child or parent are null

addTreeModelListener

public void addTreeModelListener(TreeModelListener l)
Adds a listener for the TreeModelEvent posted after the tree changes.

Parameters:
l - the listener to add
See Also:
removeTreeModelListener(javax.swing.event.TreeModelListener)

removeTreeModelListener

public void removeTreeModelListener(TreeModelListener l)
Removes a listener previously added with addTreeModelListener.

Parameters:
l - the listener to remove
See Also:
addTreeModelListener(javax.swing.event.TreeModelListener)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TreeNode (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.tree
Interface TreeNode

All Known Subinterfaces:
MutableTreeNode
All Known Implementing Classes:
AbstractDocument.AbstractElement, DefaultMutableTreeNode
public interface TreeNode

Defines the requirements for an object that can be used as a tree node in a JTree.

For further information and examples of using tree nodes, see How to Use Tree Nodes in The Java Tutorial.

Method Summary
Enumeration | children() Returns the children of the receiver as an Enumeration.
boolean | getAllowsChildren() Returns true if the receiver allows children.
TreeNode | getChildAt(int childIndex) Returns the child TreeNode at index childIndex.
int | getChildCount() Returns the number of children TreeNodes the receiver contains.
int | getIndex(TreeNode node) Returns the index of node in the receivers children.
TreeNode | getParent() Returns the parent TreeNode of the receiver.
boolean | isLeaf() Returns true if the receiver is a leaf.

Method Detail

getChildAt

public TreeNode getChildAt(int childIndex)
Returns the child TreeNode at index childIndex.

getChildCount

public int getChildCount()
Returns the number of children TreeNodes the receiver contains.

getParent

public TreeNode getParent()
Returns the parent TreeNode of the receiver.

getIndex

public int getIndex(TreeNode node)
Returns the index of node in the receivers children. If the receiver does not contain node, -1 will be returned.

getAllowsChildren

public boolean getAllowsChildren()
Returns true if the receiver allows children.

isLeaf

public boolean isLeaf()
Returns true if the receiver is a leaf.

children

public Enumeration children()
Returns the children of the receiver as an Enumeration.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TreePath (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.tree
Class TreePath

java.lang.Object
    extended by javax.swing.tree.TreePath
All Implemented Interfaces:
Serializable
public class TreePath
extends Object
implements Serializable

Represents a path to a node. A TreePath is an array of Objects that are vended from a TreeModel. The elements of the array are ordered such that the root is always the first element (index 0) of the array. TreePath is Serializable, but if any components of the path are not serializable, it will not be written out.

For further information and examples of using tree paths, see How to Use Trees in The Java Tutorial.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Constructor Summary
protected | TreePath() Primarily provided for subclasses that represent paths in a different manner.
 | TreePath(Object singlePath) Constructs a TreePath containing only a single element.
 | TreePath(Object[] path) Constructs a path from an array of Objects, uniquely identifying the path from the root of the tree to a specific node, as returned by the tree's data model.
protected | TreePath(Object[] path, int length) Constructs a new TreePath with the identified path components of length length.
protected | TreePath(TreePath parent, Object lastElement) Constructs a new TreePath, which is the path identified by parent ending in lastElement.
Method Summary
boolean | equals(Object o) Tests two TreePaths for equality by checking each element of the paths for equality.
Object | getLastPathComponent() Returns the last component of this path.
TreePath | getParentPath() Returns a path containing all the elements of this object, except the last path component.
Object[] | getPath() Returns an ordered array of Objects containing the components of this TreePath.
Object | getPathComponent(int element) Returns the path component at the specified index.
int | getPathCount() Returns the number of elements in the path.
int | hashCode() Returns the hashCode for the object.
boolean | isDescendant(TreePath aTreePath) Returns true if aTreePath is a descendant of this TreePath.
TreePath | pathByAddingChild(Object child) Returns a new path containing all the elements of this object plus child.
String | toString() Returns a string that displays and identifies this object's properties.
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait

Constructor Detail

TreePath

public TreePath(Object[] path)
Constructs a path from an array of Objects, uniquely identifying the path from the root of the tree to a specific node, as returned by the tree's data model.

The model is free to return an array of any Objects it needs to represent the path. The DefaultTreeModel returns an array of TreeNode objects. The first TreeNode in the path is the root of the tree, the last TreeNode is the node identified by the path.

Parameters:
path - an array of Objects representing the path to a node

TreePath

public TreePath(Object singlePath)
Constructs a TreePath containing only a single element. This is usually used to construct a TreePath for the the root of the TreeModel.

Parameters:
singlePath - an Object representing the path to a node
See Also:
TreePath(Object[])

TreePath

protected TreePath(TreePath parent,
                   Object lastElement)
Constructs a new TreePath, which is the path identified by parent ending in lastElement.

TreePath

protected TreePath(Object[] path,
                   int length)
Constructs a new TreePath with the identified path components of length length.

TreePath

protected TreePath()
Primarily provided for subclasses that represent paths in a different manner. If a subclass uses this constructor, it should also override the getPath, getPathCount, and getPathComponent methods, and possibly the equals method.

Method Detail

getPath

public Object[] getPath()
Returns an ordered array of Objects containing the components of this TreePath. The first element (index 0) is the root.

Returns:
an array of Objects representing the TreePath
See Also:
TreePath(Object[])

getLastPathComponent

public Object getLastPathComponent()
Returns the last component of this path. For a path returned by DefaultTreeModel this will return an instance of TreeNode.

Returns:
the Object at the end of the path
See Also:
TreePath(Object[])

getPathCount

public int getPathCount()
Returns the number of elements in the path.

Returns:
an int giving a count of items the path

getPathComponent

public Object getPathComponent(int element)
Returns the path component at the specified index.

Parameters:
element - an int specifying an element in the path, where 0 is the first element in the path
Returns:
the Object at that index location
Throws:
IllegalArgumentException - if the index is beyond the length of the path
See Also:
TreePath(Object[])

equals

public boolean equals(Object o)
Tests two TreePaths for equality by checking each element of the paths for equality. Two paths are considered equal if they are of the same length, and contain the same elements (.equals).

Overrides:
equals in class Object
Parameters:
o - the Object to compare
Returns:
true if this object is the same as the obj argument; false otherwise.
See Also:
Object.hashCode(), Hashtable

hashCode

public int hashCode()
Returns the hashCode for the object. The hash code of a TreePath is defined to be the hash code of the last component in the path.

Overrides:
hashCode in class Object
Returns:
the hashCode for the object
See Also:
Object.equals(java.lang.Object), Hashtable

isDescendant

public boolean isDescendant(TreePath aTreePath)
Returns true if aTreePath is a descendant of this TreePath. A TreePath P1 is a descendent of a TreePath P2 if P1 contains all of the components that make up P2's path. For example, if this object has the path [a, b], and aTreePath has the path [a, b, c], then aTreePath is a descendant of this object. However, if aTreePath has the path [a], then it is not a descendant of this object.

Returns:
true if aTreePath is a descendant of this path

pathByAddingChild

public TreePath pathByAddingChild(Object child)
Returns a new path containing all the elements of this object plus child. child will be the last element of the newly created TreePath. This will throw a NullPointerException if child is null.

getParentPath

public TreePath getParentPath()
Returns a path containing all the elements of this object, except the last path component.

toString

public String toString()
Returns a string that displays and identifies this object's properties.

Overrides:
toString in class Object
Returns:
a String representation of this object
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TreeSelectionModel (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.swing.tree
Interface TreeSelectionModel

All Known Implementing Classes:
DefaultTreeSelectionModel
public interface TreeSelectionModel

This interface represents the current state of the selection for the tree component. For information and examples of using tree selection models, see How to Use Trees in The Java Tutorial.

The state of the tree selection is characterized by a set of TreePaths, and optionally a set of integers. The mapping from TreePath to integer is done by way of an instance of RowMapper. It is not necessary for a TreeSelectionModel to have a RowMapper to correctly operate, but without a RowMapper getSelectionRows will return null.

A TreeSelectionModel can be configured to allow only one path (SINGLE_TREE_SELECTION) a number of continguous paths (CONTIGUOUS_TREE_SELECTION) or a number of discontiguous paths (DISCONTIGUOUS_TREE_SELECTION). A RowMapper is used to determine if TreePaths are contiguous. In the absence of a RowMapper CONTIGUOUS_TREE_SELECTION and DISCONTIGUOUS_TREE_SELECTION behave the same, that is they allow any number of paths to be contained in the TreeSelectionModel.

For a selection model of CONTIGUOUS_TREE_SELECTION any time the paths are changed (setSelectionPath, addSelectionPath ...) the TreePaths are again checked to make they are contiguous. A check of the TreePaths can also be forced by invoking resetRowSelection. How a set of discontiguous TreePaths is mapped to a contiguous set is left to implementors of this interface to enforce a particular policy.

Implementations should combine duplicate TreePaths that are added to the selection. For example, the following code

   TreePath[] paths = new TreePath[] { treePath, treePath };
   treeSelectionModel.setSelectionPaths(paths);
should result in only one path being selected: treePath, and not two copies of treePath.

The lead TreePath is the last path that was added (or set). The lead row is then the row that corresponds to the TreePath as determined from the RowMapper.

Field Summary
static int | CONTIGUOUS_TREE_SELECTION Selection can only be contiguous.
static int | DISCONTIGUOUS_TREE_SELECTION Selection can contain any number of items that are not necessarily contiguous.
static int | SINGLE_TREE_SELECTION Selection can only contain one path at a time.
Method Summary
void | addPropertyChangeListener(PropertyChangeListener listener) Adds a PropertyChangeListener to the listener list.
void | addSelectionPath(TreePath path) Adds path to the current selection.
void | addSelectionPaths(TreePath[] paths) Adds paths to the current selection.
void | addTreeSelectionListener(TreeSelectionListener x) Adds x to the list of listeners that are notified each time the set of selected TreePaths changes.
void | clearSelection() Empties the current selection.
TreePath | getLeadSelectionPath() Returns the last path that was added.
int | getLeadSelectionRow() Returns the lead selection index.
int | getMaxSelectionRow() Returns the largest value obtained from the RowMapper for the current set of selected TreePaths.
int | getMinSelectionRow() Returns the smallest value obtained from the RowMapper for the current set of selected TreePaths.
RowMapper | getRowMapper() Returns the RowMapper instance that is able to map a TreePath to a row.
int | getSelectionCount() Returns the number of paths that are selected.
int | getSelectionMode() Returns the current selection mode, one of SINGLE_TREE_SELECTION, CONTIGUOUS_TREE_SELECTION or DISCONTIGUOUS_TREE_SELECTION.
TreePath | getSelectionPath() Returns the first path in the selection.
TreePath[] | getSelectionPaths() Returns the paths in the selection.
int[] | getSelectionRows() Returns all of the currently selected rows.
boolean | isPathSelected(TreePath path) Returns true if the path, path, is in the current selection.
boolean | isRowSelected(int row) Returns true if the row identified by row is selected.
boolean | isSelectionEmpty() Returns true if the selection is currently empty.
void | removePropertyChangeListener(PropertyChangeListener listener) Removes a PropertyChangeListener from the listener list.
void | removeSelectionPath(TreePath path) Removes path from the selection.
void | removeSelectionPaths(TreePath[] paths) Removes paths from the selection.
void | removeTreeSelectionListener(TreeSelectionListener x) Removes x from the list of listeners that are notified each time the set of selected TreePaths changes.
void | resetRowSelection() Updates this object's mapping from TreePaths to rows.
void | setRowMapper(RowMapper newMapper) Sets the RowMapper instance.
void | setSelectionMode(int mode) Sets the selection model, which must be one of SINGLE_TREE_SELECTION, CONTIGUOUS_TREE_SELECTION or DISCONTIGUOUS_TREE_SELECTION.
void | setSelectionPath(TreePath path) Sets the selection to path.
void | setSelectionPaths(TreePath[] paths) Sets the selection to path.

Field Detail

SINGLE_TREE_SELECTION

public static final int SINGLE_TREE_SELECTION
Selection can only contain one path at a time.

See Also:
Constant Field Values

CONTIGUOUS_TREE_SELECTION

public static final int CONTIGUOUS_TREE_SELECTION
Selection can only be contiguous. This will only be enforced if a RowMapper instance is provided. That is, if no RowMapper is set this behaves the same as DISCONTIGUOUS_TREE_SELECTION.

See Also:
Constant Field Values

DISCONTIGUOUS_TREE_SELECTION

public static final int DISCONTIGUOUS_TREE_SELECTION
Selection can contain any number of items that are not necessarily contiguous.

See Also:
Constant Field Values
Method Detail

setSelectionMode

public void setSelectionMode(int mode)
Sets the selection model, which must be one of SINGLE_TREE_SELECTION, CONTIGUOUS_TREE_SELECTION or DISCONTIGUOUS_TREE_SELECTION.

This may change the selection if the current selection is not valid for the new mode. For example, if three TreePaths are selected when the mode is changed to SINGLE_TREE_SELECTION, only one TreePath will remain selected. It is up to the particular implementation to decide what TreePath remains selected.

getSelectionMode

public int getSelectionMode()
Returns the current selection mode, one of SINGLE_TREE_SELECTION, CONTIGUOUS_TREE_SELECTION or DISCONTIGUOUS_TREE_SELECTION.

setSelectionPath

public void setSelectionPath(TreePath path)
Sets the selection to path. If this represents a change, then the TreeSelectionListeners are notified. If path is null, this has the same effect as invoking clearSelection.

Parameters:
path - new path to select

setSelectionPaths

public void setSelectionPaths(TreePath[] paths)
Sets the selection to path. If this represents a change, then the TreeSelectionListeners are notified. If paths is null, this has the same effect as invoking clearSelection.

Parameters:
paths - new selection

addSelectionPath

public void addSelectionPath(TreePath path)
Adds path to the current selection. If path is not currently in the selection the TreeSelectionListeners are notified. This has no effect if path is null.

Parameters:
path - the new path to add to the current selection

addSelectionPaths

public void addSelectionPaths(TreePath[] paths)
Adds paths to the current selection. If any of the paths in paths are not currently in the selection the TreeSelectionListeners are notified. This has no effect if paths is null.

Parameters:
paths - the new paths to add to the current selection

removeSelectionPath

public void removeSelectionPath(TreePath path)
Removes path from the selection. If path is in the selection The TreeSelectionListeners are notified. This has no effect if path is null.

Parameters:
path - the path to remove from the selection

removeSelectionPaths

public void removeSelectionPaths(TreePath[] paths)
Removes paths from the selection. If any of the paths in paths are in the selection, the TreeSelectionListeners are notified. This method has no effect if paths is null.

Parameters:
paths - the path to remove from the selection

getSelectionPath

public TreePath getSelectionPath()
Returns the first path in the selection. How first is defined is up to implementors, and may not necessarily be the TreePath with the smallest integer value as determined from the RowMapper.

getSelectionPaths

public TreePath[] getSelectionPaths()
Returns the paths in the selection. This will return null (or an empty array) if nothing is currently selected.

getSelectionCount

public int getSelectionCount()
Returns the number of paths that are selected.

isPathSelected

public boolean isPathSelected(TreePath path)
Returns true if the path, path, is in the current selection.

isSelectionEmpty

public boolean isSelectionEmpty()
Returns true if the selection is currently empty.

clearSelection

public void clearSelection()
Empties the current selection. If this represents a change in the current selection, the selection listeners are notified.

setRowMapper

public void setRowMapper(RowMapper newMapper)
Sets the RowMapper instance. This instance is used to determine the row for a particular TreePath.

getRowMapper

public RowMapper getRowMapper()
Returns the RowMapper instance that is able to map a TreePath to a row.

getSelectionRows

public int[] getSelectionRows()
Returns all of the currently selected rows. This will return null (or an empty array) if there are no selected TreePaths or a RowMapper has not been set.

getMinSelectionRow

public int getMinSelectionRow()
Returns the smallest value obtained from the RowMapper for the current set of selected TreePaths. If nothing is selected, or there is no RowMapper, this will return -1.

getMaxSelectionRow

public int getMaxSelectionRow()
Returns the largest value obtained from the RowMapper for the current set of selected TreePaths. If nothing is selected, or there is no RowMapper, this will return -1.

isRowSelected

public boolean isRowSelected(int row)
Returns true if the row identified by row is selected.

resetRowSelection

public void resetRowSelection()
Updates this object's mapping from TreePaths to rows. This should be invoked when the mapping from TreePaths to integers has changed (for example, a node has been expanded).

You do not normally have to call this; JTree and its associated listeners will invoke this for you. If you are implementing your own view class, then you will have to invoke this.

getLeadSelectionRow

public int getLeadSelectionRow()
Returns the lead selection index. That is the last index that was added.

getLeadSelectionPath

public TreePath getLeadSelectionPath()
Returns the last path that was added. This may differ from the leadSelectionPath property maintained by the JTree.

addPropertyChangeListener

public void addPropertyChangeListener(PropertyChangeListener listener)
Adds a PropertyChangeListener to the listener list. The listener is registered for all properties.

A PropertyChangeEvent will get fired when the selection mode changes.

Parameters:
listener - the PropertyChangeListener to be added

removePropertyChangeListener

public void removePropertyChangeListener(PropertyChangeListener listener)
Removes a PropertyChangeListener from the listener list. This removes a PropertyChangeListener that was registered for all properties.

Parameters:
listener - the PropertyChangeListener to be removed

addTreeSelectionListener

public void addTreeSelectionListener(TreeSelectionListener x)
Adds x to the list of listeners that are notified each time the set of selected TreePaths changes.

Parameters:
x - the new listener to be added

removeTreeSelectionListener

public void removeTreeSelectionListener(TreeSelectionListener x)
Removes x from the list of listeners that are notified each time the set of selected TreePaths changes.

Parameters:
x - the listener to remove
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


VariableHeightLayoutCache (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.swing.tree
Class VariableHeightLayoutCache

java.lang.Object
    extended by javax.swing.tree.AbstractLayoutCache
        extended by javax.swing.tree.VariableHeightLayoutCache
All Implemented Interfaces:
RowMapper
public class VariableHeightLayoutCache
extends AbstractLayoutCache

NOTE: This will become more open in a future release.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Nested Class Summary
Nested classes inherited from class javax.swing.tree.AbstractLayoutCache
AbstractLayoutCache.NodeDimensions
Field Summary
Fields inherited from class javax.swing.tree.AbstractLayoutCache
nodeDimensions, rootVisible, rowHeight, treeModel, treeSelectionModel
Constructor Summary
VariableHeightLayoutCache()
Method Summary
Rectangle | getBounds(TreePath path, Rectangle placeIn) Returns the Rectangle enclosing the label portion into which the item identified by path will be drawn.
boolean | getExpandedState(TreePath path) Returns true if the path is expanded, and visible.
TreePath | getPathClosestTo(int x, int y) Returns the path to the node that is closest to x,y.
TreePath | getPathForRow(int row) Returns the path for row.
int | getPreferredHeight() Returns the preferred height.
int | getPreferredWidth(Rectangle bounds) Returns the preferred width and height for the region in visibleRegion.
int | getRowCount() Returns the number of visible rows.
int | getRowForPath(TreePath path) Returns the row where the last item identified in path is visible.
int | getVisibleChildCount(TreePath path) Returns the number of visible children for path.
Enumeration | getVisiblePathsFrom(TreePath path) Returns an Enumerator that increments over the visible paths starting at the passed in location.
void | invalidatePathBounds(TreePath path) Instructs the LayoutCache that the bounds for path are invalid, and need to be updated.
void | invalidateSizes() Informs the TreeState that it needs to recalculate all the sizes it is referencing.
boolean | isExpanded(TreePath path) Returns true if the value identified by path is currently expanded.
void | setExpandedState(TreePath path, boolean isExpanded) Marks the path path expanded state to isExpanded.
void | setModel(TreeModel newModel) Sets the TreeModel that will provide the data.
void | setNodeDimensions(AbstractLayoutCache.NodeDimensions nd) Sets the renderer that is responsible for drawing nodes in the tree.
void | setRootVisible(boolean rootVisible) Determines whether or not the root node from the TreeModel is visible.
void | setRowHeight(int rowHeight) Sets the height of each cell.
void | treeNodesChanged(TreeModelEvent e) Invoked after a node (or a set of siblings) has changed in some way.
void | treeNodesInserted(TreeModelEvent e) Invoked after nodes have been inserted into the tree.
void | treeNodesRemoved(TreeModelEvent e) Invoked after nodes have been removed from the tree.
void | treeStructureChanged(TreeModelEvent e) Invoked after the tree has drastically changed structure from a given node down.
Methods inherited from class javax.swing.tree.AbstractLayoutCache
getModel, getNodeDimensions, getNodeDimensions, getRowHeight, getRowsForPaths, getSelectionModel, isFixedRowHeight, isRootVisible, setSelectionModel
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

VariableHeightLayoutCache

public VariableHeightLayoutCache()
Method Detail

setModel

public void setModel(TreeModel newModel)
Sets the TreeModel that will provide the data.

Overrides:
setModel in class AbstractLayoutCache
Parameters:
newModel - the TreeModel that is to provide the data

setRootVisible

public void setRootVisible(boolean rootVisible)
Determines whether or not the root node from the TreeModel is visible.

Overrides:
setRootVisible in class AbstractLayoutCache
Parameters:
rootVisible - true if the root node of the tree is to be displayed
See Also:
AbstractLayoutCache.rootVisible

setRowHeight

public void setRowHeight(int rowHeight)
Sets the height of each cell. If the specified value is less than or equal to zero the current cell renderer is queried for each row's height.

Overrides:
setRowHeight in class AbstractLayoutCache
Parameters:
rowHeight - the height of each cell, in pixels

setNodeDimensions

public void setNodeDimensions(AbstractLayoutCache.NodeDimensions nd)
Sets the renderer that is responsible for drawing nodes in the tree.

Overrides:
setNodeDimensions in class AbstractLayoutCache
Parameters:
nd - the renderer

setExpandedState

public void setExpandedState(TreePath path,
                             boolean isExpanded)
Marks the path path expanded state to isExpanded.

Specified by:
setExpandedState in class AbstractLayoutCache
Parameters:
path - the TreePath of interest
isExpanded - true if the path should be expanded, otherwise false

getExpandedState

public boolean getExpandedState(TreePath path)
Returns true if the path is expanded, and visible.

Specified by:
getExpandedState in class AbstractLayoutCache
Parameters:
path - the path being queried
Returns:
true if the path is expanded and visible, otherwise false

getBounds

public Rectangle getBounds(TreePath path,
                           Rectangle placeIn)
Returns the Rectangle enclosing the label portion into which the item identified by path will be drawn.

Specified by:
getBounds in class AbstractLayoutCache
Parameters:
path - the path to be drawn
placeIn - the bounds of the enclosing rectangle
Returns:
the bounds of the enclosing rectangle or null if the node could not be ascertained

getPathForRow

public TreePath getPathForRow(int row)
Returns the path for row. If row is not visible, null is returned.

Specified by:
getPathForRow in class AbstractLayoutCache
Parameters:
row - the location of interest
Returns:
the path for row, or null if row is not visible

getRowForPath

public int getRowForPath(TreePath path)
Returns the row where the last item identified in path is visible. Will return -1 if any of the elements in path are not currently visible.

Specified by:
getRowForPath in class AbstractLayoutCache
Parameters:
path - the TreePath of interest
Returns:
the row where the last item in path is visible

getRowCount

public int getRowCount()
Returns the number of visible rows.

Specified by:
getRowCount in class AbstractLayoutCache
Returns:
the number of visible rows

invalidatePathBounds

public void invalidatePathBounds(TreePath path)
Instructs the LayoutCache that the bounds for path are invalid, and need to be updated.

Specified by:
invalidatePathBounds in class AbstractLayoutCache
Parameters:
path - the TreePath which is now invalid

getPreferredHeight

public int getPreferredHeight()
Returns the preferred height.

Overrides:
getPreferredHeight in class AbstractLayoutCache
Returns:
the preferred height

getPreferredWidth

public int getPreferredWidth(Rectangle bounds)
Returns the preferred width and height for the region in visibleRegion.

Overrides:
getPreferredWidth in class AbstractLayoutCache
Parameters:
bounds - the region being queried
Returns:
the preferred width for the passed in region

getPathClosestTo

public TreePath getPathClosestTo(int x,
                                 int y)
Returns the path to the node that is closest to x,y. If there is nothing currently visible this will return null, otherwise it will always return a valid path. If you need to test if the returned object is exactly at x, y you should get the bounds for the returned path and test x, y against that.

Specified by:
getPathClosestTo in class AbstractLayoutCache
Parameters:
x - the x-coordinate
y - the y-coordinate
Returns:
the path to the node that is closest to x, y

getVisiblePathsFrom

public Enumeration getVisiblePathsFrom(TreePath path)
Returns an Enumerator that increments over the visible paths starting at the passed in location. The ordering of the enumeration is based on how the paths are displayed.

Specified by:
getVisiblePathsFrom in class AbstractLayoutCache
Parameters:
path - the location in the TreePath to start
Returns:
an Enumerator that increments over the visible paths

getVisibleChildCount

public int getVisibleChildCount(TreePath path)
Returns the number of visible children for path.

Specified by:
getVisibleChildCount in class AbstractLayoutCache
Parameters:
path - the path being queried
Returns:
the number of visible children for path

invalidateSizes

public void invalidateSizes()
Informs the TreeState that it needs to recalculate all the sizes it is referencing.

Specified by:
invalidateSizes in class AbstractLayoutCache

isExpanded

public boolean isExpanded(TreePath path)
Returns true if the value identified by path is currently expanded.

Specified by:
isExpanded in class AbstractLayoutCache
Returns:
true if the value identified by path is currently expanded

treeNodesChanged

public void treeNodesChanged(TreeModelEvent e)
Invoked after a node (or a set of siblings) has changed in some way. The node(s) have not changed locations in the tree or altered their children arrays, but other attributes have changed and may affect presentation. Example: the name of a file has changed, but it is in the same location in the file system.

e.path returns the path the parent of the changed node(s).

e.childIndices returns the index(es) of the changed node(s).

Specified by:
treeNodesChanged in class AbstractLayoutCache
Parameters:
e - the TreeModelEvent of interest

treeNodesInserted

public void treeNodesInserted(TreeModelEvent e)
Invoked after nodes have been inserted into the tree.

e.path returns the parent of the new nodes.

e.childIndices returns the indices of the new nodes in ascending order.

Specified by:
treeNodesInserted in class AbstractLayoutCache
Parameters:
e - the TreeModelEvent of interest

treeNodesRemoved

public void treeNodesRemoved(TreeModelEvent e)
Invoked after nodes have been removed from the tree. Note that if a subtree is removed from the tree, this method may only be invoked once for the root of the removed subtree, not once for each individual set of siblings removed.

e.path returns the former parent of the deleted nodes.

e.childIndices returns the indices the nodes had before they were deleted in ascending order.

Specified by:
treeNodesRemoved in class AbstractLayoutCache
Parameters:
e - the TreeModelEvent of interest

treeStructureChanged

public void treeStructureChanged(TreeModelEvent e)
Invoked after the tree has drastically changed structure from a given node down. If the path returned by e.getPath is of length one and the first element does not identify the current root node the first element should become the new root of the tree.

e.path holds the path to the node.

e.childIndices returns null.

Specified by:
treeStructureChanged in class AbstractLayoutCache
Parameters:
e - the TreeModelEvent of interest
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Uses of Class javax.swing.tree.AbstractLayoutCache (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.tree.AbstractLayoutCache

Packages that use AbstractLayoutCache
javax.swing.plaf.basic | Provides user interface objects built according to the Basic look and feel.
javax.swing.tree | Provides classes and interfaces for dealing with javax.swing.JTree.

Uses of AbstractLayoutCache in javax.swing.plaf.basic

Fields in javax.swing.plaf.basic declared as AbstractLayoutCache
protected  AbstractLayoutCache BasicTreeUI.treeState
Object responsible for handling sizing and expanded issues.

Methods in javax.swing.plaf.basic that return AbstractLayoutCache
protected  AbstractLayoutCache BasicTreeUI.createLayoutCache()
Creates the object responsible for managing what is expanded, as well as the size of nodes.

Uses of AbstractLayoutCache in javax.swing.tree

Subclasses of AbstractLayoutCache in javax.swing.tree
class | FixedHeightLayoutCache NOTE: This will become more open in a future release.
class | VariableHeightLayoutCache NOTE: This will become more open in a future release.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.tree.AbstractLayoutCache.NodeDimensions (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.tree.AbstractLayoutCache.NodeDimensions

Packages that use AbstractLayoutCache.NodeDimensions
javax.swing.plaf.basic | Provides user interface objects built according to the Basic look and feel.
javax.swing.tree | Provides classes and interfaces for dealing with javax.swing.JTree.

Uses of AbstractLayoutCache.NodeDimensions in javax.swing.plaf.basic

Subclasses of AbstractLayoutCache.NodeDimensions in javax.swing.plaf.basic
 class BasicTreeUI.NodeDimensionsHandler
Class responsible for getting size of node, method is forwarded to BasicTreeUI method.

Fields in javax.swing.plaf.basic declared as AbstractLayoutCache.NodeDimensions
protected  AbstractLayoutCache.NodeDimensions BasicTreeUI.nodeDimensions
Reponsible for telling the TreeState the size needed for a node.

Methods in javax.swing.plaf.basic that return AbstractLayoutCache.NodeDimensions
protected  AbstractLayoutCache.NodeDimensions BasicTreeUI.createNodeDimensions()
Creates an instance of NodeDimensions that is able to determine the size of a given node in the tree.

Uses of AbstractLayoutCache.NodeDimensions in javax.swing.tree

Fields in javax.swing.tree declared as AbstractLayoutCache.NodeDimensions
protected  AbstractLayoutCache.NodeDimensions AbstractLayoutCache.nodeDimensions
Object responsible for getting the size of a node.

Methods in javax.swing.tree that return AbstractLayoutCache.NodeDimensions
 AbstractLayoutCache.NodeDimensions AbstractLayoutCache.getNodeDimensions()
Returns the object that renders nodes in the tree, and which is responsible for calculating the dimensions of individual nodes.

Methods in javax.swing.tree with parameters of type AbstractLayoutCache.NodeDimensions
void | VariableHeightLayoutCache.setNodeDimensions(AbstractLayoutCache.NodeDimensions nd) Sets the renderer that is responsible for drawing nodes in the tree.
void | AbstractLayoutCache.setNodeDimensions(AbstractLayoutCache.NodeDimensions nd) Sets the renderer that is responsible for drawing nodes in the tree and which is threfore responsible for calculating the dimensions of individual nodes.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.tree.DefaultMutableTreeNode (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.tree.DefaultMutableTreeNode

Packages that use DefaultMutableTreeNode
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.tree | Provides classes and interfaces for dealing with javax.swing.JTree.

Uses of DefaultMutableTreeNode in javax.swing

Subclasses of DefaultMutableTreeNode in javax.swing
static class JTree.DynamicUtilTreeNode
DynamicUtilTreeNode can wrap vectors/hashtables/arrays/strings and create the appropriate children tree nodes as necessary.

Methods in javax.swing with parameters of type DefaultMutableTreeNode
static void JTree.DynamicUtilTreeNode.createChildren(DefaultMutableTreeNode parent, Object children)
Adds to parent all the children in children.

Uses of DefaultMutableTreeNode in javax.swing.tree

Methods in javax.swing.tree that return DefaultMutableTreeNode
DefaultMutableTreeNode | DefaultMutableTreeNode.getNextNode() Returns the node that follows this node in a preorder traversal of this node's tree.
DefaultMutableTreeNode | DefaultMutableTreeNode.getPreviousNode() Returns the node that precedes this node in a preorder traversal of this node's tree.
DefaultMutableTreeNode | DefaultMutableTreeNode.getNextSibling() Returns the next sibling of this node in the parent's children array.
DefaultMutableTreeNode | DefaultMutableTreeNode.getPreviousSibling() Returns the previous sibling of this node in the parent's children array.
DefaultMutableTreeNode | DefaultMutableTreeNode.getFirstLeaf() Finds and returns the first leaf that is a descendant of this node -- either this node or its first child's first leaf.
DefaultMutableTreeNode | DefaultMutableTreeNode.getLastLeaf() Finds and returns the last leaf that is a descendant of this node -- either this node or its last child's last leaf.
DefaultMutableTreeNode | DefaultMutableTreeNode.getNextLeaf() Returns the leaf after this node or null if this node is the last leaf in the tree.
DefaultMutableTreeNode | DefaultMutableTreeNode.getPreviousLeaf() Returns the leaf before this node or null if this node is the first leaf in the tree.

Methods in javax.swing.tree with parameters of type DefaultMutableTreeNode
boolean | DefaultMutableTreeNode.isNodeDescendant(DefaultMutableTreeNode anotherNode) Returns true if anotherNode is a descendant of this node -- if it is this node, one of this node's children, or a descendant of one of this node's children.
TreeNode | DefaultMutableTreeNode.getSharedAncestor(DefaultMutableTreeNode aNode) Returns the nearest common ancestor to this node and aNode.
boolean | DefaultMutableTreeNode.isNodeRelated(DefaultMutableTreeNode aNode) Returns true if and only if aNode is in the same tree as this node.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.tree.DefaultTreeCellEditor (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.tree.DefaultTreeCellEditor

No usage of javax.swing.tree.DefaultTreeCellEditor

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.tree.DefaultTreeCellEditor.DefaultTextField (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.tree.DefaultTreeCellEditor.DefaultTextField

No usage of javax.swing.tree.DefaultTreeCellEditor.DefaultTextField

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.tree.DefaultTreeCellEditor.EditorContainer (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.tree.DefaultTreeCellEditor.EditorContainer

No usage of javax.swing.tree.DefaultTreeCellEditor.EditorContainer

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.tree.DefaultTreeCellRenderer (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.tree.DefaultTreeCellRenderer

Packages that use DefaultTreeCellRenderer
javax.swing.tree Provides classes and interfaces for dealing with javax.swing.JTree.

Uses of DefaultTreeCellRenderer in javax.swing.tree

Fields in javax.swing.tree declared as DefaultTreeCellRenderer
protected  DefaultTreeCellRenderer DefaultTreeCellEditor.renderer
Renderer, used to get border and offsets from.

Constructors in javax.swing.tree with parameters of type DefaultTreeCellRenderer
DefaultTreeCellEditor(JTree tree, DefaultTreeCellRenderer renderer)
Constructs a DefaultTreeCellEditor object for a JTree using the specified renderer and a default editor.
DefaultTreeCellEditor(JTree tree, DefaultTreeCellRenderer renderer, TreeCellEditor editor)
Constructs a DefaultTreeCellEditor object for a JTree using the specified renderer and the specified editor.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.tree.DefaultTreeModel (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.tree.DefaultTreeModel

No usage of javax.swing.tree.DefaultTreeModel

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.tree.DefaultTreeSelectionModel (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.tree.DefaultTreeSelectionModel

Packages that use DefaultTreeSelectionModel
javax.swing Provides a set of "lightweight" (all-Java language) components that, to the maximum degree possible, work the same on all platforms.

Uses of DefaultTreeSelectionModel in javax.swing

Subclasses of DefaultTreeSelectionModel in javax.swing
protected static class JTree.EmptySelectionModel
EmptySelectionModel is a TreeSelectionModel that does not allow anything to be selected.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.tree.ExpandVetoException (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.tree.ExpandVetoException

Packages that use ExpandVetoException
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.event | Provides for events fired by Swing components.

Uses of ExpandVetoException in javax.swing

Methods in javax.swing that throw ExpandVetoException
void | JTree.fireTreeWillExpand(TreePath path) Notifies all listeners that have registered interest for notification on this event type.
void | JTree.fireTreeWillCollapse(TreePath path) Notifies all listeners that have registered interest for notification on this event type.

Uses of ExpandVetoException in javax.swing.event

Methods in javax.swing.event that throw ExpandVetoException
void | TreeWillExpandListener.treeWillExpand(TreeExpansionEvent event) Invoked whenever a node in the tree is about to be expanded.
void | TreeWillExpandListener.treeWillCollapse(TreeExpansionEvent event) Invoked whenever a node in the tree is about to be collapsed.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.tree.FixedHeightLayoutCache (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.tree.FixedHeightLayoutCache

No usage of javax.swing.tree.FixedHeightLayoutCache

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.swing.tree.MutableTreeNode (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.swing.tree.MutableTreeNode

Packages that use MutableTreeNode
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.tree | Provides classes and interfaces for dealing with javax.swing.JTree.

Uses of MutableTreeNode in javax.swing

Classes in javax.swing that implement MutableTreeNode
static class JTree.DynamicUtilTreeNode
DynamicUtilTreeNode can wrap vectors/hashtables/arrays/strings and create the appropriate children tree nodes as necessary.

Uses of MutableTreeNode in javax.swing.tree

Classes in javax.swing.tree that implement MutableTreeNode
 class DefaultMutableTreeNode
A DefaultMutableTreeNode is a general-purpose node in a tree data structure.

Fields in javax.swing.tree declared as MutableTreeNode
protected  MutableTreeNode DefaultMutableTreeNode.parent
this node's parent, or null if this node has no parent

Methods in javax.swing.tree with parameters of type MutableTreeNode
void | DefaultTreeModel.insertNodeInto(MutableTreeNode newChild, MutableTreeNode parent, int index) Invoked this to insert newChild at location index in parents children.
void | DefaultTreeModel.removeNodeFromParent(MutableTreeNode node) Message this to remove node from its parent.
void | MutableTreeNode.insert(MutableTreeNode child, int index) Adds child to the receiver at index.
void | MutableTreeNode.remove(MutableTreeNode node) Removes node from the receiver.
void | MutableTreeNode.setParent(MutableTreeNode newParent) Sets the parent of the receiver to newParent.
void | DefaultMutableTreeNode.insert(MutableTreeNode newChild, int childIndex) Removes newChild from its present parent (if it has a parent), sets the child's parent to this node, and then adds the child to this node's child array at index childIndex.
void | DefaultMutableTreeNode.setParent(MutableTreeNode newParent) Sets this node's parent to newParent but does not change the parent's child array.
void | DefaultMutableTreeNode.remove(MutableTreeNode aChild) Removes aChild from this node's child array, giving it a null parent.
void | DefaultMutableTreeNode.add(MutableTreeNode newChild) Removes newChild from its parent and makes it a child of this node by adding it to the end of this node's child array.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.swing.tree.RowMapper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.swing.tree.RowMapper

Packages that use RowMapper
javax.swing.tree Provides classes and interfaces for dealing with javax.swing.JTree.

Uses of RowMapper in javax.swing.tree

Classes in javax.swing.tree that implement RowMapper
class | AbstractLayoutCache Warning: Serialized objects of this class will not be compatible with future Swing releases.
class | FixedHeightLayoutCache NOTE: This will become more open in a future release.
class | VariableHeightLayoutCache NOTE: This will become more open in a future release.

Fields in javax.swing.tree declared as RowMapper
protected  RowMapper DefaultTreeSelectionModel.rowMapper
Provides a row for a given path.

Methods in javax.swing.tree that return RowMapper
RowMapper | DefaultTreeSelectionModel.getRowMapper() Returns the RowMapper instance that is able to map a TreePath to a row.
RowMapper | TreeSelectionModel.getRowMapper() Returns the RowMapper instance that is able to map a TreePath to a row.

Methods in javax.swing.tree with parameters of type RowMapper
void | DefaultTreeSelectionModel.setRowMapper(RowMapper newMapper) Sets the RowMapper instance.
void | TreeSelectionModel.setRowMapper(RowMapper newMapper) Sets the RowMapper instance.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.swing.tree.TreeCellEditor (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.swing.tree.TreeCellEditor

Packages that use TreeCellEditor
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.plaf.basic | Provides user interface objects built according to the Basic look and feel.
javax.swing.tree | Provides classes and interfaces for dealing with javax.swing.JTree.

Uses of TreeCellEditor in javax.swing

Classes in javax.swing that implement TreeCellEditor
 class DefaultCellEditor
The default editor for table and tree cells.

Fields in javax.swing declared as TreeCellEditor
protected  TreeCellEditor JTree.cellEditor
Editor for the entries.

Methods in javax.swing that return TreeCellEditor
 TreeCellEditor JTree.getCellEditor()
Returns the editor used to edit entries in the tree.

Methods in javax.swing with parameters of type TreeCellEditor
 void JTree.setCellEditor(TreeCellEditor cellEditor)
Sets the cell editor.

Uses of TreeCellEditor in javax.swing.plaf.basic

Fields in javax.swing.plaf.basic declared as TreeCellEditor
protected  TreeCellEditor BasicTreeUI.cellEditor
Editor for the tree.

Methods in javax.swing.plaf.basic that return TreeCellEditor
protected TreeCellEditor | BasicTreeUI.getCellEditor()
protected TreeCellEditor | BasicTreeUI.createDefaultCellEditor() Creates a default cell editor.

Methods in javax.swing.plaf.basic with parameters of type TreeCellEditor
protected  void BasicTreeUI.setCellEditor(TreeCellEditor editor)
Sets the cell editor.

Uses of TreeCellEditor in javax.swing.tree

Classes in javax.swing.tree that implement TreeCellEditor
 class DefaultTreeCellEditor
A TreeCellEditor.

Fields in javax.swing.tree declared as TreeCellEditor
protected  TreeCellEditor DefaultTreeCellEditor.realEditor
Editor handling the editing.

Methods in javax.swing.tree that return TreeCellEditor
protected  TreeCellEditor DefaultTreeCellEditor.createTreeCellEditor()
This is invoked if a TreeCellEditor is not supplied in the constructor.

Constructors in javax.swing.tree with parameters of type TreeCellEditor
DefaultTreeCellEditor(JTree tree, DefaultTreeCellRenderer renderer, TreeCellEditor editor)
Constructs a DefaultTreeCellEditor object for a JTree using the specified renderer and the specified editor.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.swing.tree.TreeCellRenderer (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.swing.tree.TreeCellRenderer

Packages that use TreeCellRenderer
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.plaf.basic | Provides user interface objects built according to the Basic look and feel.
javax.swing.tree | Provides classes and interfaces for dealing with javax.swing.JTree.

Uses of TreeCellRenderer in javax.swing

Fields in javax.swing declared as TreeCellRenderer
protected  TreeCellRenderer JTree.cellRenderer
The cell used to draw nodes.

Methods in javax.swing that return TreeCellRenderer
 TreeCellRenderer JTree.getCellRenderer()
Returns the current TreeCellRenderer that is rendering each cell.

Methods in javax.swing with parameters of type TreeCellRenderer
 void JTree.setCellRenderer(TreeCellRenderer x)
Sets the TreeCellRenderer that will be used to draw each cell.

Uses of TreeCellRenderer in javax.swing.plaf.basic

Fields in javax.swing.plaf.basic declared as TreeCellRenderer
protected  TreeCellRenderer BasicTreeUI.currentCellRenderer
Renderer that is being used to do the actual cell drawing.

Methods in javax.swing.plaf.basic that return TreeCellRenderer
protected TreeCellRenderer | BasicTreeUI.getCellRenderer() Return currentCellRenderer, which will either be the trees renderer, or defaultCellRenderer, which ever wasn't null.
protected TreeCellRenderer | BasicTreeUI.createDefaultCellRenderer() Returns the default cell renderer that is used to do the stamping of each node.

Methods in javax.swing.plaf.basic with parameters of type TreeCellRenderer
protected  void BasicTreeUI.setCellRenderer(TreeCellRenderer tcr)
Sets the TreeCellRenderer to tcr.

Uses of TreeCellRenderer in javax.swing.tree

Classes in javax.swing.tree that implement TreeCellRenderer
 class DefaultTreeCellRenderer
Displays an entry in a tree.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.swing.tree.TreeModel (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.swing.tree.TreeModel

Packages that use TreeModel
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.plaf.basic | Provides user interface objects built according to the Basic look and feel.
javax.swing.tree | Provides classes and interfaces for dealing with javax.swing.JTree.

Uses of TreeModel in javax.swing

Fields in javax.swing declared as TreeModel
protected  TreeModel JTree.treeModel
The model that defines the tree displayed by this object.

Methods in javax.swing that return TreeModel
protected static TreeModel | JTree.getDefaultTreeModel() Creates and returns a sample TreeModel.
protected static TreeModel | JTree.createTreeModel(Object value) Returns a TreeModel wrapping the specified object.
TreeModel | JTree.getModel() Returns the TreeModel that is providing the data.

Methods in javax.swing with parameters of type TreeModel
 void JTree.setModel(TreeModel newModel)
Sets the TreeModel that will provide the data.

Constructors in javax.swing with parameters of type TreeModel
JTree(TreeModel newModel)
Returns an instance of JTree which displays the root node -- the tree is created using the specified data model.

Uses of TreeModel in javax.swing.plaf.basic

Fields in javax.swing.plaf.basic declared as TreeModel
protected  TreeModel BasicTreeUI.treeModel
Used to determine what to display.

Methods in javax.swing.plaf.basic that return TreeModel
protected  TreeModel BasicTreeUI.getModel()

Methods in javax.swing.plaf.basic with parameters of type TreeModel
protected  void BasicTreeUI.setModel(TreeModel model)
Sets the TreeModel.

Uses of TreeModel in javax.swing.tree

Classes in javax.swing.tree that implement TreeModel
 class DefaultTreeModel
A simple tree data model that uses TreeNodes.

Fields in javax.swing.tree declared as TreeModel
protected  TreeModel AbstractLayoutCache.treeModel
Model providing information.

Methods in javax.swing.tree that return TreeModel
 TreeModel AbstractLayoutCache.getModel()
Returns the TreeModel that is providing the data.

Methods in javax.swing.tree with parameters of type TreeModel
void | VariableHeightLayoutCache.setModel(TreeModel newModel) Sets the TreeModel that will provide the data.
void | FixedHeightLayoutCache.setModel(TreeModel newModel) Sets the TreeModel that will provide the data.
void | AbstractLayoutCache.setModel(TreeModel newModel) Sets the TreeModel that will provide the data.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.swing.tree.TreeNode (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.swing.tree.TreeNode

Packages that use TreeNode
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.text | Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.text.html | Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.
javax.swing.tree | Provides classes and interfaces for dealing with javax.swing.JTree.

Uses of TreeNode in javax.swing

Classes in javax.swing that implement TreeNode
static class JTree.DynamicUtilTreeNode
DynamicUtilTreeNode can wrap vectors/hashtables/arrays/strings and create the appropriate children tree nodes as necessary.

Methods in javax.swing that return TreeNode
 TreeNode JTree.DynamicUtilTreeNode.getChildAt(int index)
Subclassed to load the children, if necessary.

Constructors in javax.swing with parameters of type TreeNode
JTree(TreeNode root)
Returns a JTree with the specified TreeNode as its root, which displays the root node.
JTree(TreeNode root, boolean asksAllowsChildren)
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.

Uses of TreeNode in javax.swing.text

Classes in javax.swing.text that implement TreeNode
class | AbstractDocument.AbstractElement Implements the abstract part of an element.
class | AbstractDocument.BranchElement Implements a composite element that contains other elements.
class | AbstractDocument.LeafElement Implements an element that directly represents content of some kind.
protected class | DefaultStyledDocument.SectionElement Default root element for a document...

Methods in javax.swing.text that return TreeNode
TreeNode | AbstractDocument.AbstractElement.getChildAt(int childIndex) Returns the child TreeNode at index childIndex.
TreeNode | AbstractDocument.AbstractElement.getParent() Returns the parent TreeNode of the receiver.

Methods in javax.swing.text with parameters of type TreeNode
 int AbstractDocument.AbstractElement.getIndex(TreeNode node)
Returns the index of node in the receivers children.

Uses of TreeNode in javax.swing.text.html

Classes in javax.swing.text.html that implement TreeNode
class | HTMLDocument.BlockElement An element that represents a structural block of HTML.
class | HTMLDocument.RunElement An element that represents a chunk of text that has a set of HTML character level attributes assigned to it.

Uses of TreeNode in javax.swing.tree

Subinterfaces of TreeNode in javax.swing.tree
 interface MutableTreeNode
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.

Classes in javax.swing.tree that implement TreeNode
 class DefaultMutableTreeNode
A DefaultMutableTreeNode is a general-purpose node in a tree data structure.

Fields in javax.swing.tree declared as TreeNode
protected  TreeNode DefaultTreeModel.root
Root of the tree.

Methods in javax.swing.tree that return TreeNode
TreeNode[] | DefaultTreeModel.getPathToRoot(TreeNode aNode) Builds the parents of node up to and including the root node, where the original node is the last element in the returned array.
protected TreeNode[] | DefaultTreeModel.getPathToRoot(TreeNode aNode, int depth) Builds the parents of node up to and including the root node, where the original node is the last element in the returned array.
TreeNode | DefaultMutableTreeNode.getParent() Returns this node's parent or null if this node has no parent.
TreeNode | DefaultMutableTreeNode.getChildAt(int index) Returns the child at the specified index in this node's child array.
TreeNode | DefaultMutableTreeNode.getSharedAncestor(DefaultMutableTreeNode aNode) Returns the nearest common ancestor to this node and aNode.
TreeNode[] | DefaultMutableTreeNode.getPath() Returns the path from the root, to get to this node.
protected TreeNode[] | DefaultMutableTreeNode.getPathToRoot(TreeNode aNode, int depth) Builds the parents of node up to and including the root node, where the original node is the last element in the returned array.
TreeNode | DefaultMutableTreeNode.getRoot() Returns the root of the tree that contains this node.
TreeNode | DefaultMutableTreeNode.getFirstChild() Returns this node's first child.
TreeNode | DefaultMutableTreeNode.getLastChild() Returns this node's last child.
TreeNode | DefaultMutableTreeNode.getChildAfter(TreeNode aChild) Returns the child in this node's child array that immediately follows aChild, which must be a child of this node.
TreeNode | DefaultMutableTreeNode.getChildBefore(TreeNode aChild) Returns the child in this node's child array that immediately precedes aChild, which must be a child of this node.
TreeNode | TreeNode.getChildAt(int childIndex) Returns the child TreeNode at index childIndex.
TreeNode | TreeNode.getParent() Returns the parent TreeNode of the receiver.

Methods in javax.swing.tree with parameters of type TreeNode
void | DefaultTreeModel.setRoot(TreeNode root) Sets the root to root.
void | DefaultTreeModel.nodeChanged(TreeNode node) Invoke this method after you've changed how node is to be represented in the tree.
void | DefaultTreeModel.reload(TreeNode node) Invoke this method if you've modified the TreeNodes upon which this model depends.
void | DefaultTreeModel.nodesWereInserted(TreeNode node, int[] childIndices) Invoke this method after you've inserted some TreeNodes into node.
void | DefaultTreeModel.nodesWereRemoved(TreeNode node, int[] childIndices, Object[] removedChildren) Invoke this method after you've removed some TreeNodes from node.
void | DefaultTreeModel.nodesChanged(TreeNode node, int[] childIndices) Invoke this method after you've changed how the children identified by childIndicies are to be represented in the tree.
void | DefaultTreeModel.nodeStructureChanged(TreeNode node) Invoke this method if you've totally changed the children of node and its childrens children...
TreeNode[] | DefaultTreeModel.getPathToRoot(TreeNode aNode) Builds the parents of node up to and including the root node, where the original node is the last element in the returned array.
protected TreeNode[] | DefaultTreeModel.getPathToRoot(TreeNode aNode, int depth) Builds the parents of node up to and including the root node, where the original node is the last element in the returned array.
int | DefaultMutableTreeNode.getIndex(TreeNode aChild) Returns the index of the specified child in this node's child array.
boolean | DefaultMutableTreeNode.isNodeAncestor(TreeNode anotherNode) Returns true if anotherNode is an ancestor of this node -- if it is this node, this node's parent, or an ancestor of this node's parent.
protected TreeNode[] | DefaultMutableTreeNode.getPathToRoot(TreeNode aNode, int depth) Builds the parents of node up to and including the root node, where the original node is the last element in the returned array.
Enumeration | DefaultMutableTreeNode.pathFromAncestorEnumeration(TreeNode ancestor) Creates and returns an enumeration that follows the path from ancestor to this node.
boolean | DefaultMutableTreeNode.isNodeChild(TreeNode aNode) Returns true if aNode is a child of this node.
TreeNode | DefaultMutableTreeNode.getChildAfter(TreeNode aChild) Returns the child in this node's child array that immediately follows aChild, which must be a child of this node.
TreeNode | DefaultMutableTreeNode.getChildBefore(TreeNode aChild) Returns the child in this node's child array that immediately precedes aChild, which must be a child of this node.
boolean | DefaultMutableTreeNode.isNodeSibling(TreeNode anotherNode) Returns true if anotherNode is a sibling of (has the same parent as) this node.
int | TreeNode.getIndex(TreeNode node) Returns the index of node in the receivers children.

Constructors in javax.swing.tree with parameters of type TreeNode
DefaultTreeModel(TreeNode root)
Creates a tree in which any node can have children.
DefaultTreeModel(TreeNode root, boolean asksAllowsChildren)
Creates a tree specifying whether any node can have children, or whether only certain nodes can have children.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.tree.TreePath (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.tree.TreePath

Packages that use TreePath
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.event | Provides for events fired by Swing components.
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 | Provides user interface objects built according to the Basic look and feel.
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 | Provides user interface objects that combine two or more look and feels.
javax.swing.tree | Provides classes and interfaces for dealing with javax.swing.JTree.

Uses of TreePath in javax.swing

Methods in javax.swing that return TreePath
TreePath | JTree.getLeadSelectionPath() Returns the path identified as the lead.
TreePath | JTree.getAnchorSelectionPath() Returns the path identified as the anchor.
TreePath | JTree.getSelectionPath() Returns the path to the first selected node.
TreePath[] | JTree.getSelectionPaths() Returns the paths of all selected values.
TreePath | JTree.getPathForRow(int row) Returns the path for the specified row.
TreePath | JTree.getPathForLocation(int x, int y) Returns the path for the node at the specified location.
TreePath | JTree.getClosestPathForLocation(int x, int y) Returns the path to the node that is closest to x,y.
TreePath | JTree.getEditingPath() Returns the path to the element that is currently being edited.
protected TreePath[] | JTree.getPathBetweenRows(int index0, int index1) Returns JTreePath instances representing the path between index0 and index1 (including index1).
TreePath | JTree.getNextMatch(String prefix, int startingRow, Position.Bias bias) Returns the TreePath to the next tree element that begins with a prefix.

Methods in javax.swing with parameters of type TreePath
boolean | JTree.isPathEditable(TreePath path) Returns isEditable.
void | JTree.setSelectionPath(TreePath path) Selects the node identified by the specified path.
void | JTree.setSelectionPaths(TreePath[] paths) Selects the nodes identified by the specified array of paths.
void | JTree.setLeadSelectionPath(TreePath newPath) Sets the path identifies as the lead.
void | JTree.setAnchorSelectionPath(TreePath newPath) Sets the path identified as the anchor.
void | JTree.addSelectionPath(TreePath path) Adds the node identified by the specified TreePath to the current selection.
void | JTree.addSelectionPaths(TreePath[] paths) Adds each path in the array of paths to the current selection.
boolean | JTree.isPathSelected(TreePath path) Returns true if the item identified by the path is currently selected.
Enumeration | JTree.getExpandedDescendants(TreePath parent) Returns an Enumeration of the descendants of the path parent that are currently expanded.
boolean | JTree.hasBeenExpanded(TreePath path) Returns true if the node identified by the path has ever been expanded.
boolean | JTree.isExpanded(TreePath path) Returns true if the node identified by the path is currently expanded,
boolean | JTree.isCollapsed(TreePath path) Returns true if the value identified by path is currently collapsed, this will return false if any of the values in path are currently not being displayed.
void | JTree.makeVisible(TreePath path) Ensures that the node identified by path is currently viewable.
boolean | JTree.isVisible(TreePath path) Returns true if the value identified by path is currently viewable, which means it is either the root or all of its parents are expanded.
Rectangle | JTree.getPathBounds(TreePath path) Returns the Rectangle that the specified node will be drawn into.
void | JTree.scrollPathToVisible(TreePath path) 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.
int | JTree.getRowForPath(TreePath path) Returns the row that displays the node identified by the specified path.
void | JTree.expandPath(TreePath path) Ensures that the node identified by the specified path is expanded and viewable.
void | JTree.collapsePath(TreePath path) Ensures that the node identified by the specified path is collapsed and viewable.
void | JTree.startEditingAtPath(TreePath path) Selects the node identified by the specified path and initiates editing.
void | JTree.removeSelectionPath(TreePath path) Removes the node identified by the specified path from the current selection.
void | JTree.removeSelectionPaths(TreePath[] paths) Removes the nodes identified by the specified paths from the current selection.
void | JTree.fireTreeExpanded(TreePath path) Notifies all listeners that have registered interest for notification on this event type.
void | JTree.fireTreeCollapsed(TreePath path) Notifies all listeners that have registered interest for notification on this event type.
void | JTree.fireTreeWillExpand(TreePath path) Notifies all listeners that have registered interest for notification on this event type.
void | JTree.fireTreeWillCollapse(TreePath path) Notifies all listeners that have registered interest for notification on this event type.
protected void | JTree.setExpandedState(TreePath path, boolean state) Sets the expanded state of this JTree.
protected Enumeration | JTree.getDescendantToggledPaths(TreePath parent) Returns an Enumeration of TreePaths that have been expanded that are descendants of parent.
protected boolean | JTree.removeDescendantSelectedPaths(TreePath path, boolean includePath) Removes any paths in the selection that are descendants of path.
void | JTree.EmptySelectionModel.setSelectionPaths(TreePath[] pPaths) A null implementation that selects nothing.
void | JTree.EmptySelectionModel.addSelectionPaths(TreePath[] paths) A null implementation that adds nothing.
void | JTree.EmptySelectionModel.removeSelectionPaths(TreePath[] paths) A null implementation that removes nothing.

Constructors in javax.swing with parameters of type TreePath
JTree.AccessibleJTree.AccessibleJTreeNode(JTree t, TreePath p, Accessible ap)
Constructs an AccessibleJTreeNode

Uses of TreePath in javax.swing.event

Fields in javax.swing.event declared as TreePath
protected TreePath | TreeExpansionEvent.path Path to the value this event represents.
protected TreePath | TreeModelEvent.path Path to the parent of the nodes that have changed.
protected TreePath[] | TreeSelectionEvent.paths Paths this event represents.
protected TreePath | TreeSelectionEvent.oldLeadSelectionPath leadSelectionPath before the paths changed, may be null.
protected TreePath | TreeSelectionEvent.newLeadSelectionPath leadSelectionPath after the paths changed, may be null.

Methods in javax.swing.event that return TreePath
TreePath | TreeExpansionEvent.getPath() Returns the path to the value that has been expanded/collapsed.
TreePath | TreeModelEvent.getTreePath() For all events, except treeStructureChanged, returns the parent of the changed nodes.
TreePath[] | TreeSelectionEvent.getPaths() Returns the paths that have been added or removed from the selection.
TreePath | TreeSelectionEvent.getPath() Returns the first path element.
TreePath | TreeSelectionEvent.getOldLeadSelectionPath() Returns the path that was previously the lead path.
TreePath | TreeSelectionEvent.getNewLeadSelectionPath() Returns the current lead path.

Methods in javax.swing.event with parameters of type TreePath
 boolean TreeSelectionEvent.isAddedPath(TreePath path)
Returns true if the path identified by path was added to the selection.

Constructors in javax.swing.event with parameters of type TreePath
TreeExpansionEvent(Object source, TreePath path)
Constructs a TreeExpansionEvent object.
TreeModelEvent(Object source, TreePath path, int[] childIndices, Object[] children)
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 source, TreePath path)
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.
TreeSelectionEvent(Object source, TreePath[] paths, boolean[] areNew, TreePath oldLeadSelectionPath, TreePath newLeadSelectionPath)
Represents a change in the selection of a TreeSelectionModel.
TreeSelectionEvent(Object source, TreePath path, boolean isNew, TreePath oldLeadSelectionPath, TreePath newLeadSelectionPath)
Represents a change in the selection of a TreeSelectionModel.

Uses of TreePath in javax.swing.plaf

Methods in javax.swing.plaf that return TreePath
abstract TreePath | TreeUI.getPathForRow(JTree tree, int row) Returns the path for passed in row.
abstract TreePath | TreeUI.getClosestPathForLocation(JTree tree, int x, int y) Returns the path to the node that is closest to x,y.
abstract TreePath | TreeUI.getEditingPath(JTree tree) Returns the path to the element that is being edited.

Methods in javax.swing.plaf with parameters of type TreePath
abstract Rectangle | TreeUI.getPathBounds(JTree tree, TreePath path) Returns the Rectangle enclosing the label portion that the last item in path will be drawn into.
abstract int | TreeUI.getRowForPath(JTree tree, TreePath path) Returns the row that the last item identified in path is visible at.
abstract void | TreeUI.startEditingAtPath(JTree tree, TreePath path) Selects the last item in path and tries to edit it.

Uses of TreePath in javax.swing.plaf.basic

Fields in javax.swing.plaf.basic declared as TreePath
protected  TreePath BasicTreeUI.editingPath
Path that is being edited.

Methods in javax.swing.plaf.basic that return TreePath
TreePath | BasicTreeUI.getPathForRow(JTree tree, int row) Returns the path for passed in row.
TreePath | BasicTreeUI.getClosestPathForLocation(JTree tree, int x, int y) Returns the path to the node that is closest to x,y.
TreePath | BasicTreeUI.getEditingPath(JTree tree) Returns the path to the element that is being edited.
protected TreePath | BasicTreeUI.getLastChildPath(TreePath parent) Returns a path to the last child of parent.

Methods in javax.swing.plaf.basic with parameters of type TreePath
Rectangle | BasicTreeUI.getPathBounds(JTree tree, TreePath path) Returns the Rectangle enclosing the label portion that the last item in path will be drawn into.
int | BasicTreeUI.getRowForPath(JTree tree, TreePath path) Returns the row that the last item identified in path is visible at.
void | BasicTreeUI.startEditingAtPath(JTree tree, TreePath path) Selects the last item in path and tries to edit it.
protected void | BasicTreeUI.paintHorizontalPartOfLeg(Graphics g, Rectangle clipBounds, Insets insets, Rectangle bounds, TreePath path, int row, boolean isExpanded, boolean hasBeenExpanded, boolean isLeaf) Paints the horizontal part of the leg.
protected void | BasicTreeUI.paintVerticalPartOfLeg(Graphics g, Rectangle clipBounds, Insets insets, TreePath path) Paints the vertical part of the leg.
protected void | BasicTreeUI.paintExpandControl(Graphics g, Rectangle clipBounds, Insets insets, Rectangle bounds, TreePath path, int row, boolean isExpanded, boolean hasBeenExpanded, boolean isLeaf) Paints the expand (toggle) part of a row.
protected void | BasicTreeUI.paintRow(Graphics g, Rectangle clipBounds, Insets insets, Rectangle bounds, TreePath path, int row, boolean isExpanded, boolean hasBeenExpanded, boolean isLeaf) Paints the renderer part of a row.
protected boolean | BasicTreeUI.shouldPaintExpandControl(TreePath path, int row, boolean isExpanded, boolean hasBeenExpanded, boolean isLeaf) Returns true if the expand (toggle) control should be drawn for the specified row.
protected void | BasicTreeUI.updateExpandedDescendants(TreePath path) Updates the expanded state of all the descendants of path by getting the expanded descendants from the tree and forwarding to the tree state.
protected TreePath | BasicTreeUI.getLastChildPath(TreePath parent) Returns a path to the last child of parent.
protected void | BasicTreeUI.pathWasExpanded(TreePath path) Messaged from the VisibleTreeNode after it has been expanded.
protected void | BasicTreeUI.pathWasCollapsed(TreePath path) Messaged from the VisibleTreeNode after it has collapsed.
protected boolean | BasicTreeUI.startEditing(TreePath path, MouseEvent event) Will start editing for node if there is a cellEditor and shouldSelectCell returns true.
protected void | BasicTreeUI.checkForClickInExpandControl(TreePath path, int mouseX, int mouseY) If the mouseX and mouseY are in the expand/collapse region of the row, this will toggle the row.
protected boolean | BasicTreeUI.isLocationInExpandControl(TreePath path, int mouseX, int mouseY) Returns true if mouseX and mouseY fall in the area of row that is used to expand/collapse the node and the node at row does not represent a leaf.
protected void | BasicTreeUI.handleExpandControlClick(TreePath path, int mouseX, int mouseY) Messaged when the user clicks the particular row, this invokes toggleExpandState.
protected void | BasicTreeUI.toggleExpandState(TreePath path) Expands path if it is not expanded, or collapses row if it is expanded.
protected void | BasicTreeUI.selectPathForEvent(TreePath path, MouseEvent event) Messaged to update the selection based on a MouseEvent over a particular row.

Uses of TreePath in javax.swing.plaf.metal

Methods in javax.swing.plaf.metal with parameters of type TreePath
protected void | MetalTreeUI.paintVerticalPartOfLeg(Graphics g, Rectangle clipBounds, Insets insets, TreePath path)
protected void | MetalTreeUI.paintHorizontalPartOfLeg(Graphics g, Rectangle clipBounds, Insets insets, Rectangle bounds, TreePath path, int row, boolean isExpanded, boolean hasBeenExpanded, boolean isLeaf)

Uses of TreePath in javax.swing.plaf.multi

Methods in javax.swing.plaf.multi that return TreePath
TreePath | MultiTreeUI.getPathForRow(JTree a, int b) Invokes the getPathForRow method on each UI handled by this object.
TreePath | MultiTreeUI.getClosestPathForLocation(JTree a, int b, int c) Invokes the getClosestPathForLocation method on each UI handled by this object.
TreePath | MultiTreeUI.getEditingPath(JTree a) Invokes the getEditingPath method on each UI handled by this object.

Methods in javax.swing.plaf.multi with parameters of type TreePath
Rectangle | MultiTreeUI.getPathBounds(JTree a, TreePath b) Invokes the getPathBounds method on each UI handled by this object.
int | MultiTreeUI.getRowForPath(JTree a, TreePath b) Invokes the getRowForPath method on each UI handled by this object.
void | MultiTreeUI.startEditingAtPath(JTree a, TreePath b) Invokes the startEditingAtPath method on each UI handled by this object.

Uses of TreePath in javax.swing.tree

Fields in javax.swing.tree declared as TreePath
protected TreePath | DefaultTreeCellEditor.lastPath Last path that was selected.
protected TreePath[] | DefaultTreeSelectionModel.selection Paths that are currently selected.
protected TreePath | DefaultTreeSelectionModel.leadPath Last path that was added.

Methods in javax.swing.tree that return TreePath
TreePath | VariableHeightLayoutCache.getPathForRow(int row) Returns the path for row.
TreePath | VariableHeightLayoutCache.getPathClosestTo(int x, int y) Returns the path to the node that is closest to x,y.
TreePath | FixedHeightLayoutCache.getPathForRow(int row) Returns the path for passed in row.
TreePath | FixedHeightLayoutCache.getPathClosestTo(int x, int y) Returns the path to the node that is closest to x,y.
abstract TreePath | AbstractLayoutCache.getPathForRow(int row) Returns the path for passed in row.
abstract TreePath | AbstractLayoutCache.getPathClosestTo(int x, int y) Returns the path to the node that is closest to x,y.
TreePath | DefaultTreeSelectionModel.getSelectionPath() Returns the first path in the selection.
TreePath[] | DefaultTreeSelectionModel.getSelectionPaths() Returns the paths in the selection.
TreePath | DefaultTreeSelectionModel.getLeadSelectionPath() Returns the last path that was added.
TreePath | TreePath.pathByAddingChild(Object child) Returns a new path containing all the elements of this object plus child.
TreePath | TreePath.getParentPath() Returns a path containing all the elements of this object, except the last path component.
TreePath | TreeSelectionModel.getSelectionPath() Returns the first path in the selection.
TreePath[] | TreeSelectionModel.getSelectionPaths() Returns the paths in the selection.
TreePath | TreeSelectionModel.getLeadSelectionPath() Returns the last path that was added.

Methods in javax.swing.tree with parameters of type TreePath
void | VariableHeightLayoutCache.setExpandedState(TreePath path, boolean isExpanded) Marks the path path expanded state to isExpanded.
boolean | VariableHeightLayoutCache.getExpandedState(TreePath path) Returns true if the path is expanded, and visible.
Rectangle | VariableHeightLayoutCache.getBounds(TreePath path, Rectangle placeIn) Returns the Rectangle enclosing the label portion into which the item identified by path will be drawn.
int | VariableHeightLayoutCache.getRowForPath(TreePath path) Returns the row where the last item identified in path is visible.
void | VariableHeightLayoutCache.invalidatePathBounds(TreePath path) Instructs the LayoutCache that the bounds for path are invalid, and need to be updated.
Enumeration | VariableHeightLayoutCache.getVisiblePathsFrom(TreePath path) Returns an Enumerator that increments over the visible paths starting at the passed in location.
int | VariableHeightLayoutCache.getVisibleChildCount(TreePath path) Returns the number of visible children for path.
boolean | VariableHeightLayoutCache.isExpanded(TreePath path) Returns true if the value identified by path is currently expanded.
void | FixedHeightLayoutCache.invalidatePathBounds(TreePath path) Does nothing, FixedHeightLayoutCache doesn't cache width, and that is all that could change.
boolean | FixedHeightLayoutCache.isExpanded(TreePath path) Returns true if the value identified by row is currently expanded.
Rectangle | FixedHeightLayoutCache.getBounds(TreePath path, Rectangle placeIn) Returns a rectangle giving the bounds needed to draw path.
int | FixedHeightLayoutCache.getRowForPath(TreePath path) Returns the row that the last item identified in path is visible at.
int | FixedHeightLayoutCache.getVisibleChildCount(TreePath path) Returns the number of visible children for row.
Enumeration | FixedHeightLayoutCache.getVisiblePathsFrom(TreePath path) Returns an Enumerator that increments over the visible paths starting at the passed in location.
void | FixedHeightLayoutCache.setExpandedState(TreePath path, boolean isExpanded) Marks the path path expanded state to isExpanded.
boolean | FixedHeightLayoutCache.getExpandedState(TreePath path) Returns true if the path is expanded, and visible.
abstract boolean | AbstractLayoutCache.isExpanded(TreePath path) Returns true if the value identified by row is currently expanded.
abstract Rectangle | AbstractLayoutCache.getBounds(TreePath path, Rectangle placeIn) Returns a rectangle giving the bounds needed to draw path.
abstract int | AbstractLayoutCache.getRowForPath(TreePath path) Returns the row that the last item identified in path is visible at.
abstract Enumeration | AbstractLayoutCache.getVisiblePathsFrom(TreePath path) Returns an Enumerator that increments over the visible paths starting at the passed in location.
abstract int | AbstractLayoutCache.getVisibleChildCount(TreePath path) Returns the number of visible children for row.
abstract void | AbstractLayoutCache.setExpandedState(TreePath path, boolean isExpanded) Marks the path path expanded state to isExpanded.
abstract boolean | AbstractLayoutCache.getExpandedState(TreePath path) Returns true if the path is expanded, and visible.
abstract void | AbstractLayoutCache.invalidatePathBounds(TreePath path) Instructs the LayoutCache that the bounds for path are invalid, and need to be updated.
int[] | AbstractLayoutCache.getRowsForPaths(TreePath[] paths) Returns the rows that the TreePath instances in path are being displayed at.
void | DefaultTreeModel.valueForPathChanged(TreePath path, Object newValue) This sets the user object of the TreeNode identified by path and posts a node changed.
void | DefaultTreeSelectionModel.setSelectionPath(TreePath path) Sets the selection to path.
void | DefaultTreeSelectionModel.setSelectionPaths(TreePath[] pPaths) Sets the selection to the paths in paths.
void | DefaultTreeSelectionModel.addSelectionPath(TreePath path) Adds path to the current selection.
void | DefaultTreeSelectionModel.addSelectionPaths(TreePath[] paths) Adds paths to the current selection.
void | DefaultTreeSelectionModel.removeSelectionPath(TreePath path) Removes path from the selection.
void | DefaultTreeSelectionModel.removeSelectionPaths(TreePath[] paths) Removes paths from the selection.
boolean | DefaultTreeSelectionModel.isPathSelected(TreePath path) Returns true if the path, path, is in the current selection.
protected boolean | DefaultTreeSelectionModel.arePathsContiguous(TreePath[] paths) Returns true if the paths are contiguous, or this object has no RowMapper.
protected boolean | DefaultTreeSelectionModel.canPathsBeAdded(TreePath[] paths) Used to test if a particular set of TreePaths can be added.
protected boolean | DefaultTreeSelectionModel.canPathsBeRemoved(TreePath[] paths) Returns true if the paths can be removed without breaking the continuity of the model.
protected void | DefaultTreeSelectionModel.notifyPathChange(Vector changedPaths, TreePath oldLeadSelection) Notifies listeners of a change in path.
int[] | RowMapper.getRowsForPaths(TreePath[] path) Returns the rows that the TreePath instances in path are being displayed at.
boolean | TreePath.isDescendant(TreePath aTreePath) Returns true if aTreePath is a descendant of this TreePath.
void | TreeSelectionModel.setSelectionPath(TreePath path) Sets the selection to path.
void | TreeSelectionModel.setSelectionPaths(TreePath[] paths) Sets the selection to path.
void | TreeSelectionModel.addSelectionPath(TreePath path) Adds path to the current selection.
void | TreeSelectionModel.addSelectionPaths(TreePath[] paths) Adds paths to the current selection.
void | TreeSelectionModel.removeSelectionPath(TreePath path) Removes path from the selection.
void | TreeSelectionModel.removeSelectionPaths(TreePath[] paths) Removes paths from the selection.
boolean | TreeSelectionModel.isPathSelected(TreePath path) Returns true if the path, path, is in the current selection.
void | TreeModel.valueForPathChanged(TreePath path, Object newValue) Messaged when the user has altered the value for the item identified by path to newValue.

Constructors in javax.swing.tree with parameters of type TreePath
TreePath(TreePath parent, Object lastElement)
Constructs a new TreePath, which is the path identified by parent ending in lastElement.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.swing.tree.TreeSelectionModel (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.swing.tree.TreeSelectionModel

Packages that use TreeSelectionModel
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.plaf.basic | Provides user interface objects built according to the Basic look and feel.
javax.swing.tree | Provides classes and interfaces for dealing with javax.swing.JTree.

Uses of TreeSelectionModel in javax.swing

Classes in javax.swing that implement TreeSelectionModel
protected static class JTree.EmptySelectionModel
EmptySelectionModel is a TreeSelectionModel that does not allow anything to be selected.

Fields in javax.swing declared as TreeSelectionModel
protected  TreeSelectionModel JTree.selectionModel
Models the set of selected nodes in this tree.

Methods in javax.swing that return TreeSelectionModel
 TreeSelectionModel JTree.getSelectionModel()
Returns the model for selections.

Methods in javax.swing with parameters of type TreeSelectionModel
 void JTree.setSelectionModel(TreeSelectionModel selectionModel)
Sets the tree's selection model.

Uses of TreeSelectionModel in javax.swing.plaf.basic

Fields in javax.swing.plaf.basic declared as TreeSelectionModel
protected  TreeSelectionModel BasicTreeUI.treeSelectionModel
Model maintaing the selection.

Methods in javax.swing.plaf.basic that return TreeSelectionModel
protected  TreeSelectionModel BasicTreeUI.getSelectionModel()

Methods in javax.swing.plaf.basic with parameters of type TreeSelectionModel
protected  void BasicTreeUI.setSelectionModel(TreeSelectionModel newLSM)
Resets the selection model.

Uses of TreeSelectionModel in javax.swing.tree

Classes in javax.swing.tree that implement TreeSelectionModel
 class DefaultTreeSelectionModel
Default implementation of TreeSelectionModel.

Fields in javax.swing.tree declared as TreeSelectionModel
protected  TreeSelectionModel AbstractLayoutCache.treeSelectionModel
Selection model.

Methods in javax.swing.tree that return TreeSelectionModel
 TreeSelectionModel AbstractLayoutCache.getSelectionModel()
Returns the model used to maintain the selection.

Methods in javax.swing.tree with parameters of type TreeSelectionModel
 void AbstractLayoutCache.setSelectionModel(TreeSelectionModel newLSM)
Sets the TreeSelectionModel used to manage the selection to new LSM.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.tree.VariableHeightLayoutCache (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.tree.VariableHeightLayoutCache

No usage of javax.swing.tree.VariableHeightLayoutCache

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


AbstractUndoableEdit (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.swing.undo
Class AbstractUndoableEdit

java.lang.Object
    extended by javax.swing.undo.AbstractUndoableEdit
All Implemented Interfaces:
Serializable, UndoableEdit
Direct Known Subclasses:
AbstractDocument.ElementEdit, CompoundEdit, DefaultStyledDocument.AttributeUndoableEdit, StateEdit
public class AbstractUndoableEdit
extends Object
implements UndoableEdit, Serializable

An abstract implementation of UndoableEdit, implementing simple responses to all boolean methods in that interface.

Field Summary
protected static String | RedoName String returned by getRedoPresentationName; as of Java 2 platform v1.3.1 this field is no longer used.
protected static String | UndoName String returned by getUndoPresentationName; as of Java 2 platform v1.3.1 this field is no longer used.
Constructor Summary
AbstractUndoableEdit()
Creates an AbstractUndoableEdit which defaults and alive to true.
Method Summary
boolean | addEdit(UndoableEdit anEdit) This default implementation returns false.
boolean | canRedo() Returns true if this edit is alive and hasBeenDone is false.
boolean | canUndo() Returns true if this edit is alive and hasBeenDone is true.
void | die() Sets alive to false.
String | getPresentationName() This default implementation returns "".
String | getRedoPresentationName() Retreives the value from the defaults table with key AbstractUndoableEdit.redoText and returns that value followed by a space, followed by getPresentationName.
String | getUndoPresentationName() Retreives the value from the defaults table with key AbstractUndoableEdit.undoText and returns that value followed by a space, followed by getPresentationName.
boolean | isSignificant() This default implementation returns true.
void | redo() Throws CannotRedoException if canRedo returns false.
boolean | replaceEdit(UndoableEdit anEdit) This default implementation returns false.
String | toString() Returns a string that displays and identifies this object's properties.
void | undo() Throws CannotUndoException if canUndo returns false.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

UndoName

protected static final String UndoName
String returned by getUndoPresentationName; as of Java 2 platform v1.3.1 this field is no longer used. This value is now localized and comes from the defaults table with key AbstractUndoableEdit.undoText.

See Also:
UIDefaults, Constant Field Values

RedoName

protected static final String RedoName
String returned by getRedoPresentationName; as of Java 2 platform v1.3.1 this field is no longer used. This value is now localized and comes from the defaults table with key AbstractUndoableEdit.redoText.

See Also:
UIDefaults, Constant Field Values
Constructor Detail

AbstractUndoableEdit

public AbstractUndoableEdit()
Creates an AbstractUndoableEdit which defaults and alive to true.

Method Detail

die

public void die()
Sets alive to false. Note that this is a one way operation; dead edits cannot be resurrected. Sending undo or redo to a dead edit results in an exception being thrown.

Typically an edit is killed when it is consolidated by another edit's addEdit or replaceEdit method, or when it is dequeued from an UndoManager.

Specified by:
die in interface UndoableEdit
See Also:
CompoundEdit.die()

undo

public void undo()
          throws CannotUndoException
Throws CannotUndoException if canUndo returns false. Sets hasBeenDone to false. Subclasses should override to undo the operation represented by this edit. Override should begin with a call to super.

Specified by:
undo in interface UndoableEdit
Throws:
CannotUndoException - if canUndo returns false
See Also:
canUndo()

canUndo

public boolean canUndo()
Returns true if this edit is alive and hasBeenDone is true.

Specified by:
canUndo in interface UndoableEdit
Returns:
true if this edit is alive and hasBeenDone is true
See Also:
die(),
undo(),
redo()

redo

public void redo()
          throws CannotRedoException
Throws CannotRedoException if canRedo returns false. Sets hasBeenDone to true. Subclasses should override to redo the operation represented by this edit. Override should begin with a call to super.

Specified by:
redo in interface UndoableEdit
Throws:
CannotRedoException - if canRedo returns false
See Also:
canRedo()

canRedo

public boolean canRedo()
Returns true if this edit is alive and hasBeenDone is false.

Specified by:
canRedo in interface UndoableEdit
Returns:
true if this edit is alive and hasBeenDone is false
See Also:
die(),
undo(),
redo()

addEdit

public boolean addEdit(UndoableEdit anEdit)
This default implementation returns false.

Specified by:
addEdit in interface UndoableEdit
Parameters:
anEdit - the edit to be added
Returns:
false
See Also:
UndoableEdit.addEdit(javax.swing.undo.UndoableEdit)

replaceEdit

public boolean replaceEdit(UndoableEdit anEdit)
This default implementation returns false.

Specified by:
replaceEdit in interface UndoableEdit
Parameters:
anEdit - the edit to replace
Returns:
false
See Also:
UndoableEdit.replaceEdit(javax.swing.undo.UndoableEdit)

isSignificant

public boolean isSignificant()
This default implementation returns true.

Specified by:
isSignificant in interface UndoableEdit
Returns:
true
See Also:
UndoableEdit.isSignificant()

getPresentationName

public String getPresentationName()
This default implementation returns "". Used by getUndoPresentationName and getRedoPresentationName to construct the strings they return. Subclasses should override to return an appropriate description of the operation this edit represents.

Specified by:
getPresentationName in interface UndoableEdit
Returns:
the empty string ""
See Also:
getUndoPresentationName(), getRedoPresentationName()

getUndoPresentationName

public String getUndoPresentationName()
Retreives the value from the defaults table with key AbstractUndoableEdit.undoText and returns that value followed by a space, followed by getPresentationName. If getPresentationName returns "", then the defaults value is returned alone.

Specified by:
getUndoPresentationName in interface UndoableEdit
Returns:
the value from the defaults table with key AbstractUndoableEdit.undoText, followed by a space, followed by getPresentationName unless getPresentationName is "" in which case, the defaults value is returned alone.
See Also:
getPresentationName()

getRedoPresentationName

public String getRedoPresentationName()
Retreives the value from the defaults table with key AbstractUndoableEdit.redoText and returns that value followed by a space, followed by getPresentationName. If getPresentationName returns "", then the defaults value is returned alone.

Specified by:
getRedoPresentationName in interface UndoableEdit
Returns:
the value from the defaults table with key AbstractUndoableEdit.redoText, followed by a space, followed by getPresentationName unless getPresentationName is "" in which case, the defaults value is returned alone.
See Also:
getPresentationName()

toString

public String toString()
Returns a string that displays and identifies this object's properties.

Overrides:
toString in class Object
Returns:
a String representation of this object
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


CannotRedoException (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.swing.undo
Class CannotRedoException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by javax.swing.undo.CannotRedoException
All Implemented Interfaces:
Serializable
public class CannotRedoException
extends RuntimeException

Thrown when an UndoableEdit is told to redo() and can't.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Constructor Summary
CannotRedoException()
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

CannotRedoException

public CannotRedoException()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


CannotUndoException (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.swing.undo
Class CannotUndoException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by javax.swing.undo.CannotUndoException
All Implemented Interfaces:
Serializable
public class CannotUndoException
extends RuntimeException

Thrown when an UndoableEdit is told to undo() and can't.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Constructor Summary
CannotUndoException()
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

CannotUndoException

public CannotUndoException()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


CompoundEdit (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.undo
Class CompoundEdit

java.lang.Object
    extended by javax.swing.undo.AbstractUndoableEdit
        extended by javax.swing.undo.CompoundEdit
All Implemented Interfaces:
Serializable, UndoableEdit
Direct Known Subclasses:
AbstractDocument.DefaultDocumentEvent, UndoManager
public class CompoundEdit
extends AbstractUndoableEdit

A concrete subclass of AbstractUndoableEdit, used to assemble little UndoableEdits into great big ones.

Field Summary
protected  Vector edits
The collection of UndoableEdits undone/redone en masse by this CompoundEdit.
Fields inherited from class javax.swing.undo.AbstractUndoableEdit
RedoName, UndoName
Constructor Summary
CompoundEdit()
Method Summary
boolean | addEdit(UndoableEdit anEdit) If this edit is inProgress, accepts anEdit and returns true.
boolean | canRedo() Returns false if isInProgress or if super returns false.
boolean | canUndo() Returns false if isInProgress or if super returns false.
void | die() Sends die to each subedit, in the reverse of the order that they were added.
void | end() Sets inProgress to false.
String | getPresentationName() Returns getPresentationName from the last UndoableEdit added to edits.
String | getRedoPresentationName() Returns getRedoPresentationName from the last UndoableEdit added to edits.
String | getUndoPresentationName() Returns getUndoPresentationName from the last UndoableEdit added to edits.
boolean | isInProgress() Returns true if this edit is in progress--that is, it has not received end.
boolean | isSignificant() Returns true if any of the UndoableEdits in edits do.
protected UndoableEdit | lastEdit() Returns the last UndoableEdit in edits, or null if edits is empty.
void | redo() Sends redo to all contained UndoableEdits in the order in which they were added.
String | toString() Returns a string that displays and identifies this object's properties.
void | undo() Sends undo to all contained UndoableEdits in the reverse of the order in which they were added.
Methods inherited from class javax.swing.undo.AbstractUndoableEdit
replaceEdit
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

edits

protected Vector edits
The collection of UndoableEdits undone/redone en masse by this CompoundEdit.

Constructor Detail

CompoundEdit

public CompoundEdit()
Method Detail

undo

public void undo()
          throws CannotUndoException
Sends undo to all contained UndoableEdits in the reverse of the order in which they were added.

Specified by:
undo in interface UndoableEdit
Overrides:
undo in class AbstractUndoableEdit
Throws:
CannotUndoException - if canUndo returns false
See Also:
AbstractUndoableEdit.canUndo()

redo

public void redo()
          throws CannotRedoException
Sends redo to all contained UndoableEdits in the order in which they were added.

Specified by:
redo in interface UndoableEdit
Overrides:
redo in class AbstractUndoableEdit
Throws:
CannotRedoException - if canRedo returns false
See Also:
AbstractUndoableEdit.canRedo()

lastEdit

protected UndoableEdit lastEdit()
Returns the last UndoableEdit in edits, or null if edits is empty.

die

public void die()
Sends die to each subedit, in the reverse of the order that they were added.

Specified by:
die in interface UndoableEdit
Overrides:
die in class AbstractUndoableEdit

addEdit

public boolean addEdit(UndoableEdit anEdit)
If this edit is inProgress, accepts anEdit and returns true.

The last edit added to this CompoundEdit is given a chance to addEdit(anEdit). If it refuses (returns false), anEdit is given a chance to replaceEdit the last edit. If anEdit returns false here, it is added to edits.

Specified by:
addEdit in interface UndoableEdit
Overrides:
addEdit in class AbstractUndoableEdit
Parameters:
anEdit - the edit to be added
Returns:
true if the edit is inProgress; otherwise returns false
See Also:
UndoableEdit.addEdit(javax.swing.undo.UndoableEdit)

end

public void end()
Sets inProgress to false.

See Also:
canUndo(), canRedo()

canUndo

public boolean canUndo()
Returns false if isInProgress or if super returns false.

Specified by:
canUndo in interface UndoableEdit
Overrides:
canUndo in class AbstractUndoableEdit
Returns:
true if this edit is alive and hasBeenDone is true
See Also:
isInProgress()

canRedo

public boolean canRedo()
Returns false if isInProgress or if super returns false.

Specified by:
canRedo in interface UndoableEdit
Overrides:
canRedo in class AbstractUndoableEdit
Returns:
true if this edit is alive and hasBeenDone is false
See Also:
isInProgress()

isInProgress

public boolean isInProgress()
Returns true if this edit is in progress--that is, it has not received end. This generally means that edits are still being added to it.

See Also:
end()

isSignificant

public boolean isSignificant()
Returns true if any of the UndoableEdits in edits do. Returns false if they all return false.

Specified by:
isSignificant in interface UndoableEdit
Overrides:
isSignificant in class AbstractUndoableEdit
Returns:
true
See Also:
UndoableEdit.isSignificant()

getPresentationName

public String getPresentationName()
Returns getPresentationName from the last UndoableEdit added to edits. If edits is empty, calls super.

Specified by:
getPresentationName in interface UndoableEdit
Overrides:
getPresentationName in class AbstractUndoableEdit
Returns:
the empty string ""
See Also:
AbstractUndoableEdit.getUndoPresentationName(), AbstractUndoableEdit.getRedoPresentationName()

getUndoPresentationName

public String getUndoPresentationName()
Returns getUndoPresentationName from the last UndoableEdit added to edits. If edits is empty, calls super.

Specified by:
getUndoPresentationName in interface UndoableEdit
Overrides:
getUndoPresentationName in class AbstractUndoableEdit
Returns:
the value from the defaults table with key AbstractUndoableEdit.undoText, followed by a space, followed by getPresentationName unless getPresentationName is "" in which case, the defaults value is returned alone.
See Also:
AbstractUndoableEdit.getPresentationName()

getRedoPresentationName

public String getRedoPresentationName()
Returns getRedoPresentationName from the last UndoableEdit added to edits. If edits is empty, calls super.

Specified by:
getRedoPresentationName in interface UndoableEdit
Overrides:
getRedoPresentationName in class AbstractUndoableEdit
Returns:
the value from the defaults table with key AbstractUndoableEdit.redoText, followed by a space, followed by getPresentationName unless getPresentationName is "" in which case, the defaults value is returned alone.
See Also:
AbstractUndoableEdit.getPresentationName()

toString

public String toString()
Returns a string that displays and identifies this object's properties.

Overrides:
toString in class AbstractUndoableEdit
Returns:
a String representation of this object
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


javax.swing.undo (Java 2 Platform SE v1.4.2)

 javax.swing.undo
Interfaces
StateEditable
UndoableEdit
Classes
AbstractUndoableEdit
CompoundEdit
StateEdit
UndoableEditSupport
UndoManager
Exceptions
CannotRedoException
CannotUndoException


javax.swing.undo (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package javax.swing.undo

Allows developers to provide support for undo/redo in applications such as text editors.

See:
Description

Interface Summary
StateEditable | StateEditable defines the interface for objects that can have their state undone/redone by a StateEdit.
UndoableEdit | An object representing an edit that has been done, and that can be undone and redone.

Class Summary
AbstractUndoableEdit | An abstract implementation of UndoableEdit, implementing simple responses to all boolean methods in that interface.
CompoundEdit | A concrete subclass of AbstractUndoableEdit, used to assemble little UndoableEdits into great big ones.
StateEdit | StateEdit is a general edit for objects that change state.
UndoableEditSupport | A support class used for managing UndoableEdit listeners.
UndoManager | Concrete subclass of CompoundEdit which can serve as a UndoableEditListener, consolidating the UndoableEditEvents from a variety of sources, and undoing or redoing them one at a time.

Exception Summary
CannotRedoException | Thrown when an UndoableEdit is told to redo() and can't.
CannotUndoException | Thrown when an UndoableEdit is told to undo() and can't.

Package javax.swing.undo Description

Allows developers to provide support for undo/redo in applications such as text editors.

Note: Most of the Swing API is not thread safe. For details, see Threads and Swing, a section in The Java Tutorial.

Related Documentation

For overviews, tutorials, examples, guides, and tool documentation, please see:
  • Implementing Undo and Redo, a section in The Java Tutorial

Since:
1.2
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


javax.swing.undo Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package javax.swing.undo

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class javax.swing.undo.AbstractUndoableEdit (implements java.io.Serializable, javax.swing.undo.UndoableEdit)
      • class javax.swing.undo.CompoundEdit
        • class javax.swing.undo.UndoManager (implements javax.swing.event.UndoableEditListener)
      • class javax.swing.undo.StateEdit
    • class java.lang.Throwable (implements java.io.Serializable)
      • class java.lang.Exception
        • class java.lang.RuntimeException
          • class javax.swing.undo.CannotRedoException
          • class javax.swing.undo.CannotUndoException
    • class javax.swing.undo.UndoableEditSupport

Interface Hierarchy

  • interface javax.swing.undo.StateEditable
  • interface javax.swing.undo.UndoableEdit
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package javax.swing.undo (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
javax.swing.undo

Packages that use javax.swing.undo
javax.swing.event | Provides for events fired by Swing components.
javax.swing.text | Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.undo | Allows developers to provide support for undo/redo in applications such as text editors.

Classes in javax.swing.undo used by javax.swing.event
UndoableEdit
An object representing an edit that has been done, and that can be undone and redone.

Classes in javax.swing.undo used by javax.swing.text
AbstractUndoableEdit
An abstract implementation of UndoableEdit, implementing simple responses to all boolean methods in that interface.
CannotRedoException
Thrown when an UndoableEdit is told to redo() and can't.
CannotUndoException
Thrown when an UndoableEdit is told to undo() and can't.
CompoundEdit
A concrete subclass of AbstractUndoableEdit, used to assemble little UndoableEdits into great big ones.
UndoableEdit
An object representing an edit that has been done, and that can be undone and redone.

Classes in javax.swing.undo used by javax.swing.undo
AbstractUndoableEdit
An abstract implementation of UndoableEdit, implementing simple responses to all boolean methods in that interface.
CannotRedoException
Thrown when an UndoableEdit is told to redo() and can't.
CannotUndoException
Thrown when an UndoableEdit is told to undo() and can't.
CompoundEdit
A concrete subclass of AbstractUndoableEdit, used to assemble little UndoableEdits into great big ones.
StateEditable
StateEditable defines the interface for objects that can have their state undone/redone by a StateEdit.
UndoableEdit
An object representing an edit that has been done, and that can be undone and redone.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


StateEdit (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.undo
Class StateEdit

java.lang.Object
    extended by javax.swing.undo.AbstractUndoableEdit
        extended by javax.swing.undo.StateEdit
All Implemented Interfaces:
Serializable, UndoableEdit
public class StateEdit
extends AbstractUndoableEdit

StateEdit is a general edit for objects that change state. Objects being edited must conform to the StateEditable interface.

This edit class works by asking an object to store it's state in Hashtables before and after editing occurs. Upon undo or redo the object is told to restore it's state from these Hashtables.

A state edit is used as follows:
    // Create the edit during the "before" state of the object
    StateEdit newEdit = new StateEdit(myObject);
    // Modify the object
    myObject.someStateModifyingMethod();
    // "end" the edit when you are done modifying the object
    newEdit.end();

Note that when a StateEdit ends, it removes redundant state from the Hashtables - A state Hashtable is not guaranteed to contain all keys/values placed into it when the state is stored!

See Also:
StateEditable

Field Summary
protected StateEditable | object The object being edited
protected Hashtable | postState The state information after the edit
protected Hashtable | preState The state information prior to the edit
protected static String | RCSID
protected String | undoRedoName The undo/redo presentation name
Fields inherited from class javax.swing.undo.AbstractUndoableEdit
RedoName, UndoName
Constructor Summary
StateEdit(StateEditable anObject)
Create and return a new StateEdit.
StateEdit(StateEditable anObject, String name)
Create and return a new StateEdit with a presentation name.
Method Summary
void | end() Gets the post-edit state of the StateEditable object and ends the edit.
String | getPresentationName() Gets the presentation name for this edit
protected void | init(StateEditable anObject, String name)
void | redo() Tells the edited object to apply the state after the edit
protected void | removeRedundantState() Remove redundant key/values in state hashtables.
void | undo() Tells the edited object to apply the state prior to the edit
Methods inherited from class javax.swing.undo.AbstractUndoableEdit
addEdit, canRedo, canUndo, die, getRedoPresentationName, getUndoPresentationName, isSignificant, replaceEdit, toString
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

RCSID

protected static final String RCSID
See Also:
Constant Field Values

object

protected StateEditable object
The object being edited

preState

protected Hashtable preState
The state information prior to the edit

postState

protected Hashtable postState
The state information after the edit

undoRedoName

protected String undoRedoName
The undo/redo presentation name

Constructor Detail

StateEdit

public StateEdit(StateEditable anObject)
Create and return a new StateEdit.

Parameters:
anObject - The object to watch for changing state
See Also:
StateEdit

StateEdit

public StateEdit(StateEditable anObject,
                 String name)
Create and return a new StateEdit with a presentation name.

Parameters:
anObject - The object to watch for changing state
name - The presentation name to be used for this edit
See Also:
StateEdit
Method Detail

init

protected void init(StateEditable anObject,
                    String name)

end

public void end()
Gets the post-edit state of the StateEditable object and ends the edit.

undo

public void undo()
Tells the edited object to apply the state prior to the edit

Specified by:
undo in interface UndoableEdit
Overrides:
undo in class AbstractUndoableEdit
See Also:
AbstractUndoableEdit.canUndo()

redo

public void redo()
Tells the edited object to apply the state after the edit

Specified by:
redo in interface UndoableEdit
Overrides:
redo in class AbstractUndoableEdit
See Also:
AbstractUndoableEdit.canRedo()

getPresentationName

public String getPresentationName()
Gets the presentation name for this edit

Specified by:
getPresentationName in interface UndoableEdit
Overrides:
getPresentationName in class AbstractUndoableEdit
Returns:
the empty string ""
See Also:
AbstractUndoableEdit.getUndoPresentationName(), AbstractUndoableEdit.getRedoPresentationName()

removeRedundantState

protected void removeRedundantState()
Remove redundant key/values in state hashtables.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


StateEditable (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.swing.undo
Interface StateEditable

public interface StateEditable

StateEditable defines the interface for objects that can have their state undone/redone by a StateEdit.

See Also:
StateEdit

Field Summary
static String RCSID
Resource ID for this class.
Method Summary
void | restoreState(Hashtable state) Upon receiving this message the receiver should extract any relevant state out of state.
void | storeState(Hashtable state) Upon receiving this message the receiver should place any relevant state into state.

Field Detail

RCSID

public static final String RCSID
Resource ID for this class.

See Also:
Constant Field Values
Method Detail

storeState

public void storeState(Hashtable state)
Upon receiving this message the receiver should place any relevant state into state.

restoreState

public void restoreState(Hashtable state)
Upon receiving this message the receiver should extract any relevant state out of state.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


UndoableEdit (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.swing.undo
Interface UndoableEdit

All Known Implementing Classes:
AbstractUndoableEdit
public interface UndoableEdit

An object representing an edit that has been done, and that can be undone and redone.

Method Summary
boolean | addEdit(UndoableEdit anEdit) This UndoableEdit should absorb anEdit if it can.
boolean | canRedo() True if it is still possible to redo this operation.
boolean | canUndo() True if it is still possible to undo this operation.
void | die() May be sent to inform an edit that it should no longer be used.
String | getPresentationName() Provides a localized, human readable description of this edit suitable for use in, say, a change log.
String | getRedoPresentationName() Provides a localized, human readable description of the redoable form of this edit, e.g.
String | getUndoPresentationName() Provides a localized, human readable description of the undoable form of this edit, e.g.
boolean | isSignificant() Returns false if this edit is insignificant--for example one that maintains the user's selection, but does not change any model state.
void | redo() Re-apply the edit, assuming that it has been undone.
boolean | replaceEdit(UndoableEdit anEdit) Returns true if this UndoableEdit should replace anEdit.
void | undo() Undo the edit that was made.

Method Detail

undo

public void undo()
          throws CannotUndoException
Undo the edit that was made.

Throws:
CannotUndoException

canUndo

public boolean canUndo()
True if it is still possible to undo this operation.

redo

public void redo()
          throws CannotRedoException
Re-apply the edit, assuming that it has been undone.

Throws:
CannotRedoException

canRedo

public boolean canRedo()
True if it is still possible to redo this operation.

die

public void die()
May be sent to inform an edit that it should no longer be used. This is a useful hook for cleaning up state no longer needed once undoing or redoing is impossible--for example, deleting file resources used by objects that can no longer be undeleted. UndoManager calls this before it dequeues edits. Note that this is a one-way operation. There is no "un-die" method.

See Also:
CompoundEdit.die()

addEdit

public boolean addEdit(UndoableEdit anEdit)
This UndoableEdit should absorb anEdit if it can. Returns true if has been incorporated, false if it has not.

Typically the receiver is already in the queue of a UndoManager (or other UndoableEditListener), and is being given a chance to incorporate anEdit rather than letting it be added to the queue in turn.

If true is returned, from now on anEdit must return false from canUndo and canRedo, and must throw the appropriate exception on undo or redo.

Parameters:
anEdit - the edit to be added

replaceEdit

public boolean replaceEdit(UndoableEdit anEdit)
Returns true if this UndoableEdit should replace anEdit. The receiver should incorporate anEdit's state before returning true.

This message is the opposite of addEdit--anEdit has typically already been queued in a UndoManager (or other UndoableEditListener), and the receiver is being given a chance to take its place.

If true is returned, from now on anEdit must return false from canUndo() and canRedo(), and must throw the appropriate exception on undo() or redo().

isSignificant

public boolean isSignificant()
Returns false if this edit is insignificant--for example one that maintains the user's selection, but does not change any model state. This status can be used by an UndoableEditListener (like UndoManager) when deciding which UndoableEdits to present to the user as Undo/Redo options, and which to perform as side effects of undoing or redoing other events.

getPresentationName

public String getPresentationName()
Provides a localized, human readable description of this edit suitable for use in, say, a change log.

getUndoPresentationName

public String getUndoPresentationName()
Provides a localized, human readable description of the undoable form of this edit, e.g. for use as an Undo menu item. Typically derived from getDescription.

getRedoPresentationName

public String getRedoPresentationName()
Provides a localized, human readable description of the redoable form of this edit, e.g. for use as a Redo menu item. Typically derived from getPresentationName.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


UndoableEditSupport (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.swing.undo
Class UndoableEditSupport

java.lang.Object
    extended by javax.swing.undo.UndoableEditSupport
public class UndoableEditSupport
extends Object

A support class used for managing UndoableEdit listeners.

Field Summary
protected CompoundEdit | compoundEdit
protected Vector | listeners
protected Object | realSource
protected int | updateLevel
Constructor Summary
UndoableEditSupport()
Constructs an UndoableEditSupport object.
UndoableEditSupport(Object r)
Constructs an UndoableEditSupport object.
Method Summary
protected  void _postEdit(UndoableEdit e)
Called only from postEdit and endUpdate.
 void addUndoableEditListener(UndoableEditListener l)
Registers an UndoableEditListener.
 void beginUpdate()
protected  CompoundEdit createCompoundEdit()
Called only from beginUpdate.
 void endUpdate()
DEADLOCK WARNING: Calling this method may call undoableEditHappened in all listeners.
 UndoableEditListener[] getUndoableEditListeners()
Returns an array of all the UndoableEditListeners added to this UndoableEditSupport with addUndoableEditListener().
 int getUpdateLevel()
Returns the update level value.
 void postEdit(UndoableEdit e)
DEADLOCK WARNING: Calling this method may call undoableEditHappened in all listeners.
 void removeUndoableEditListener(UndoableEditListener l)
Removes an UndoableEditListener.
 String toString()
Returns a string that displays and identifies this object's properties.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

updateLevel

protected int updateLevel

compoundEdit

protected CompoundEdit compoundEdit

listeners

protected Vector listeners

realSource

protected Object realSource
Constructor Detail

UndoableEditSupport

public UndoableEditSupport()
Constructs an UndoableEditSupport object.

UndoableEditSupport

public UndoableEditSupport(Object r)
Constructs an UndoableEditSupport object.

Parameters:
r - an Object
Method Detail

addUndoableEditListener

public void addUndoableEditListener(UndoableEditListener l)
Registers an UndoableEditListener. The listener is notified whenever an edit occurs which can be undone.

Parameters:
l - an UndoableEditListener object
See Also:
removeUndoableEditListener(javax.swing.event.UndoableEditListener)

removeUndoableEditListener

public void removeUndoableEditListener(UndoableEditListener l)
Removes an UndoableEditListener.

Parameters:
l - the UndoableEditListener object to be removed
See Also:
addUndoableEditListener(javax.swing.event.UndoableEditListener)

getUndoableEditListeners

public UndoableEditListener[] getUndoableEditListeners()
Returns an array of all the UndoableEditListeners added to this UndoableEditSupport with addUndoableEditListener().

Returns:
all of the UndoableEditListeners added or an empty array if no listeners have been added
Since:
1.4

_postEdit

protected void _postEdit(UndoableEdit e)
Called only from postEdit and endUpdate. Calls undoableEditHappened in all listeners. No synchronization is performed here, since the two calling methods are synchronized.

postEdit

public void postEdit(UndoableEdit e)
DEADLOCK WARNING: Calling this method may call undoableEditHappened in all listeners. It is unwise to call this method from one of its listeners.

getUpdateLevel

public int getUpdateLevel()
Returns the update level value.

Returns:
an integer representing the update level

beginUpdate

public void beginUpdate()

createCompoundEdit

protected CompoundEdit createCompoundEdit()
Called only from beginUpdate. Exposed here for subclasses' use.

endUpdate

public void endUpdate()
DEADLOCK WARNING: Calling this method may call undoableEditHappened in all listeners. It is unwise to call this method from one of its listeners.

toString

public String toString()
Returns a string that displays and identifies this object's properties.

Overrides:
toString in class Object
Returns:
a String representation of this object
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


UndoManager (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.swing.undo
Class UndoManager

java.lang.Object
    extended by javax.swing.undo.AbstractUndoableEdit
        extended by javax.swing.undo.CompoundEdit
            extended by javax.swing.undo.UndoManager
All Implemented Interfaces:
EventListener, Serializable, UndoableEdit, UndoableEditListener
public class UndoManager
extends CompoundEdit
implements UndoableEditListener

Concrete subclass of CompoundEdit which can serve as a UndoableEditListener, consolidating the UndoableEditEvents from a variety of sources, and undoing or redoing them one at a time. Unlike AbstractUndoableEdit and CompoundEdit, the public methods of this class are synchronized, and should be safe to call from multiple threads. This should make UndoManager a convenient marshall for sets of undoable JavaBeans.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Field Summary
Fields inherited from class javax.swing.undo.CompoundEdit
edits
Fields inherited from class javax.swing.undo.AbstractUndoableEdit
RedoName, UndoName
Constructor Summary
UndoManager()
Method Summary
 boolean addEdit(UndoableEdit anEdit)
If inProgress, inserts anEdit at indexOfNextAdd, and removes any old edits that were at indexOfNextAdd or later.
 boolean canRedo()
Overridden to preserve usual semantics: returns true if a redo operation would be successful now, false otherwise
 boolean canUndo()
Overridden to preserve usual semantics: returns true if an undo operation would be successful now, false otherwise
 boolean canUndoOrRedo()
Return true if calling undoOrRedo will undo or redo.
 void discardAllEdits()
Empty the undo manager, sending each edit a die message in the process.
protected  UndoableEdit editToBeRedone()
Returns the the next significant edit to be redone if redo is called.
protected  UndoableEdit editToBeUndone()
Returns the the next significant edit to be undone if undo is called.
 void end()
Sending end() to an UndoManager turns it into a plain old (ended) CompoundEdit.
 int getLimit()
Returns the maximum number of edits this UndoManager will hold.
 String getRedoPresentationName()
If inProgress, returns getRedoPresentationName of the significant edit that will be redone when redo() is invoked.
 String getUndoOrRedoPresentationName()
Return the appropriate name for a command that toggles between undo and redo.
 String getUndoPresentationName()
If inProgress, returns getUndoPresentationName of the significant edit that will be undone when undo() is invoked.
 void redo()
If this UndoManager is inProgress, redoes the last significant UndoableEdit at indexOfNextAdd or after, and all insignificant edits up to it.
protected  void redoTo(UndoableEdit edit)
Redoes all changes from indexOfNextAdd to edit.
 void setLimit(int l)
Set the maximum number of edits this UndoManager will hold.
 String toString()
Returns a string that displays and identifies this object's properties.
protected  void trimEdits(int from, int to)
Tell the edits in the given range (inclusive) to die, and remove them from edits.
protected  void trimForLimit()
Reduce the number of queued edits to a range of size limit, centered on indexOfNextAdd.
 void undo()
If this UndoManager is inProgress, undo the last significant UndoableEdit before indexOfNextAdd, and all insignificant edits back to it.
 void undoableEditHappened(UndoableEditEvent e)
Called by the UndoabledEdit sources this UndoManager listens to.
 void undoOrRedo()
Undo or redo as appropriate.
protected  void undoTo(UndoableEdit edit)
Undoes all changes from indexOfNextAdd to edit.
Methods inherited from class javax.swing.undo.CompoundEdit
die, getPresentationName, isInProgress, isSignificant, lastEdit
Methods inherited from class javax.swing.undo.AbstractUndoableEdit
replaceEdit
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

UndoManager

public UndoManager()
Method Detail

getLimit

public int getLimit()
Returns the maximum number of edits this UndoManager will hold. Default value is 100.

See Also:
addEdit(javax.swing.undo.UndoableEdit), setLimit(int)

discardAllEdits

public void discardAllEdits()
Empty the undo manager, sending each edit a die message in the process.

trimForLimit

protected void trimForLimit()
Reduce the number of queued edits to a range of size limit, centered on indexOfNextAdd.

trimEdits

protected void trimEdits(int from,
                         int to)
Tell the edits in the given range (inclusive) to die, and remove them from edits. from > to is a no-op.

setLimit

public void setLimit(int l)
Set the maximum number of edits this UndoManager will hold. If edits need to be discarded to shrink the limit, they will be told to die in the reverse of the order that they were added.

See Also:
addEdit(javax.swing.undo.UndoableEdit), getLimit()

editToBeUndone

protected UndoableEdit editToBeUndone()
Returns the the next significant edit to be undone if undo is called. May return null

editToBeRedone

protected UndoableEdit editToBeRedone()
Returns the the next significant edit to be redone if redo is called. May return null

undoTo

protected void undoTo(UndoableEdit edit)
               throws CannotUndoException
Undoes all changes from indexOfNextAdd to edit. Updates indexOfNextAdd accordingly.

Throws:
CannotUndoException

redoTo

protected void redoTo(UndoableEdit edit)
               throws CannotRedoException
Redoes all changes from indexOfNextAdd to edit. Updates indexOfNextAdd accordingly.

Throws:
CannotRedoException

undoOrRedo

public void undoOrRedo()
                throws CannotRedoException,
                       CannotUndoException
Undo or redo as appropriate. Suitable for binding to an action that toggles between these two functions. Only makes sense to send this if limit == 1.

Throws:
CannotRedoException
CannotUndoException
See Also:
canUndoOrRedo(), getUndoOrRedoPresentationName()

canUndoOrRedo

public boolean canUndoOrRedo()
Return true if calling undoOrRedo will undo or redo. Suitable for deciding to enable a command that toggles between the two functions, which only makes sense to use if limit == 1.

See Also:
undoOrRedo()

undo

public void undo()
          throws CannotUndoException
If this UndoManager is inProgress, undo the last significant UndoableEdit before indexOfNextAdd, and all insignificant edits back to it. Updates indexOfNextAdd accordingly.

If not inProgress, indexOfNextAdd is ignored and super's routine is called.

Specified by:
undo in interface UndoableEdit
Overrides:
undo in class CompoundEdit
Throws:
CannotUndoException
See Also:
CompoundEdit.end()

canUndo

public boolean canUndo()
Overridden to preserve usual semantics: returns true if an undo operation would be successful now, false otherwise

Specified by:
canUndo in interface UndoableEdit
Overrides:
canUndo in class CompoundEdit
See Also:
CompoundEdit.isInProgress()

redo

public void redo()
          throws CannotRedoException
If this UndoManager is inProgress, redoes the last significant UndoableEdit at indexOfNextAdd or after, and all insignificant edits up to it. Updates indexOfNextAdd accordingly.

If not inProgress, indexOfNextAdd is ignored and super's routine is called.

Specified by:
redo in interface UndoableEdit
Overrides:
redo in class CompoundEdit
Throws:
CannotRedoException
See Also:
CompoundEdit.end()

canRedo

public boolean canRedo()
Overridden to preserve usual semantics: returns true if a redo operation would be successful now, false otherwise

Specified by:
canRedo in interface UndoableEdit
Overrides:
canRedo in class CompoundEdit
See Also:
CompoundEdit.isInProgress()

addEdit

public boolean addEdit(UndoableEdit anEdit)
If inProgress, inserts anEdit at indexOfNextAdd, and removes any old edits that were at indexOfNextAdd or later. The die method is called on each edit that is removed is sent, in the reverse of the order the edits were added. Updates indexOfNextAdd.

If not inProgress, acts as a CompoundEdit.

Specified by:
addEdit in interface UndoableEdit
Overrides:
addEdit in class CompoundEdit
Parameters:
anEdit - the edit to be added
Returns:
true if the edit is inProgress; otherwise returns false
See Also:
CompoundEdit.end(), CompoundEdit.addEdit(javax.swing.undo.UndoableEdit)

end

public void end()
Sending end() to an UndoManager turns it into a plain old (ended) CompoundEdit.

Calls super's end() method (making inProgress false), then sends die() to the unreachable edits at indexOfNextAdd and beyond, in the reverse of the order in which they were added.

Overrides:
end in class CompoundEdit
See Also:
CompoundEdit.end()

getUndoOrRedoPresentationName

public String getUndoOrRedoPresentationName()
Return the appropriate name for a command that toggles between undo and redo. Only makes sense to use such a command if limit == 1 and we're not in progress.

getUndoPresentationName

public String getUndoPresentationName()
If inProgress, returns getUndoPresentationName of the significant edit that will be undone when undo() is invoked. If there is none, returns AbstractUndoableEdit.undoText from the defaults table.

If not inProgress, acts as a CompoundEdit

Specified by:
getUndoPresentationName in interface UndoableEdit
Overrides:
getUndoPresentationName in class CompoundEdit
See Also:
undo(), CompoundEdit.getUndoPresentationName()

getRedoPresentationName

public String getRedoPresentationName()
If inProgress, returns getRedoPresentationName of the significant edit that will be redone when redo() is invoked. If there is none, returns AbstractUndoableEdit.redoText from the defaults table.

If not inProgress, acts as a CompoundEdit

Specified by:
getRedoPresentationName in interface UndoableEdit
Overrides:
getRedoPresentationName in class CompoundEdit
See Also:
redo(), CompoundEdit.getUndoPresentationName()

undoableEditHappened

public void undoableEditHappened(UndoableEditEvent e)
Called by the UndoabledEdit sources this UndoManager listens to. Calls addEdit with e.getEdit().

Specified by:
undoableEditHappened in interface UndoableEditListener
See Also:
addEdit(javax.swing.undo.UndoableEdit)

toString

public String toString()
Returns a string that displays and identifies this object's properties.

Overrides:
toString in class CompoundEdit
Returns:
a String representation of this object
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Uses of Class javax.swing.undo.AbstractUndoableEdit (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.undo.AbstractUndoableEdit

Packages that use AbstractUndoableEdit
javax.swing.text | Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.undo | Allows developers to provide support for undo/redo in applications such as text editors.

Uses of AbstractUndoableEdit in javax.swing.text

Subclasses of AbstractUndoableEdit in javax.swing.text
class | AbstractDocument.DefaultDocumentEvent Stores document changes as the document is being modified.
static class | AbstractDocument.ElementEdit An implementation of ElementChange that can be added to the document event.
static class | DefaultStyledDocument.AttributeUndoableEdit An UndoableEdit used to remember AttributeSet changes to an Element.

Uses of AbstractUndoableEdit in javax.swing.undo

Subclasses of AbstractUndoableEdit in javax.swing.undo
class | CompoundEdit A concrete subclass of AbstractUndoableEdit, used to assemble little UndoableEdits into great big ones.
class | StateEdit StateEdit is a general edit for objects that change state.
class | UndoManager Concrete subclass of CompoundEdit which can serve as a UndoableEditListener, consolidating the UndoableEditEvents from a variety of sources, and undoing or redoing them one at a time.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.undo.CannotRedoException (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.undo.CannotRedoException

Packages that use CannotRedoException
javax.swing.text | Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.undo | Allows developers to provide support for undo/redo in applications such as text editors.

Uses of CannotRedoException in javax.swing.text

Methods in javax.swing.text that throw CannotRedoException
void | DefaultStyledDocument.AttributeUndoableEdit.redo() Redoes a change.
void | AbstractDocument.DefaultDocumentEvent.redo() Redoes a change.
void | AbstractDocument.ElementEdit.redo() Redoes a change.

Uses of CannotRedoException in javax.swing.undo

Methods in javax.swing.undo that throw CannotRedoException
protected void | UndoManager.redoTo(UndoableEdit edit) Redoes all changes from indexOfNextAdd to edit.
void | UndoManager.undoOrRedo() Undo or redo as appropriate.
void | UndoManager.redo() If this UndoManager is inProgress, redoes the last significant UndoableEdit at indexOfNextAdd or after, and all insignificant edits up to it.
void | AbstractUndoableEdit.redo() Throws CannotRedoException if canRedo returns false.
void | CompoundEdit.redo() Sends redo to all contained UndoableEdits in the order in which they were added.
void | UndoableEdit.redo() Re-apply the edit, assuming that it has been undone.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.undo.CannotUndoException (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.undo.CannotUndoException

Packages that use CannotUndoException
javax.swing.text | Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.undo | Allows developers to provide support for undo/redo in applications such as text editors.

Uses of CannotUndoException in javax.swing.text

Methods in javax.swing.text that throw CannotUndoException
void | DefaultStyledDocument.AttributeUndoableEdit.undo() Undoes a change.
void | AbstractDocument.DefaultDocumentEvent.undo() Undoes a change.
void | AbstractDocument.ElementEdit.undo() Undoes a change.

Uses of CannotUndoException in javax.swing.undo

Methods in javax.swing.undo that throw CannotUndoException
protected void | UndoManager.undoTo(UndoableEdit edit) Undoes all changes from indexOfNextAdd to edit.
void | UndoManager.undoOrRedo() Undo or redo as appropriate.
void | UndoManager.undo() If this UndoManager is inProgress, undo the last significant UndoableEdit before indexOfNextAdd, and all insignificant edits back to it.
void | AbstractUndoableEdit.undo() Throws CannotUndoException if canUndo returns false.
void | CompoundEdit.undo() Sends undo to all contained UndoableEdits in the reverse of the order in which they were added.
void | UndoableEdit.undo() Undo the edit that was made.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.undo.CompoundEdit (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.undo.CompoundEdit

Packages that use CompoundEdit
javax.swing.text | Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.undo | Allows developers to provide support for undo/redo in applications such as text editors.

Uses of CompoundEdit in javax.swing.text

Subclasses of CompoundEdit in javax.swing.text
 class AbstractDocument.DefaultDocumentEvent
Stores document changes as the document is being modified.

Uses of CompoundEdit in javax.swing.undo

Subclasses of CompoundEdit in javax.swing.undo
 class UndoManager
Concrete subclass of CompoundEdit which can serve as a UndoableEditListener, consolidating the UndoableEditEvents from a variety of sources, and undoing or redoing them one at a time.

Fields in javax.swing.undo declared as CompoundEdit
protected  CompoundEdit UndoableEditSupport.compoundEdit

Methods in javax.swing.undo that return CompoundEdit
protected  CompoundEdit UndoableEditSupport.createCompoundEdit()
Called only from beginUpdate.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.undo.StateEdit (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.undo.StateEdit

No usage of javax.swing.undo.StateEdit

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.swing.undo.StateEditable (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.swing.undo.StateEditable

Packages that use StateEditable
javax.swing.undo Allows developers to provide support for undo/redo in applications such as text editors.

Uses of StateEditable in javax.swing.undo

Fields in javax.swing.undo declared as StateEditable
protected  StateEditable StateEdit.object
The object being edited

Methods in javax.swing.undo with parameters of type StateEditable
protected  void StateEdit.init(StateEditable anObject, String name)

Constructors in javax.swing.undo with parameters of type StateEditable
StateEdit(StateEditable anObject)
Create and return a new StateEdit.
StateEdit(StateEditable anObject, String name)
Create and return a new StateEdit with a presentation name.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.swing.undo.UndoableEdit (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.swing.undo.UndoableEdit

Packages that use UndoableEdit
javax.swing.event | Provides for events fired by Swing components.
javax.swing.text | Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.undo | Allows developers to provide support for undo/redo in applications such as text editors.

Uses of UndoableEdit in javax.swing.event

Methods in javax.swing.event that return UndoableEdit
 UndoableEdit UndoableEditEvent.getEdit()
Returns the edit value.

Constructors in javax.swing.event with parameters of type UndoableEdit
UndoableEditEvent(Object source, UndoableEdit edit)
Constructs an UndoableEditEvent object.

Uses of UndoableEdit in javax.swing.text

Classes in javax.swing.text that implement UndoableEdit
class | AbstractDocument.DefaultDocumentEvent Stores document changes as the document is being modified.
static class | AbstractDocument.ElementEdit An implementation of ElementChange that can be added to the document event.
static class | DefaultStyledDocument.AttributeUndoableEdit An UndoableEdit used to remember AttributeSet changes to an Element.

Methods in javax.swing.text that return UndoableEdit
UndoableEdit | StringContent.insertString(int where, String str) Inserts a string into the content.
UndoableEdit | StringContent.remove(int where, int nitems) Removes part of the content.
UndoableEdit | GapContent.insertString(int where, String str) Inserts a string into the content.
UndoableEdit | GapContent.remove(int where, int nitems) Removes part of the content.
UndoableEdit | AbstractDocument.Content.insertString(int where, String str) Inserts a string of characters into the sequence.
UndoableEdit | AbstractDocument.Content.remove(int where, int nitems) Removes some portion of the sequence.

Methods in javax.swing.text with parameters of type UndoableEdit
 boolean AbstractDocument.DefaultDocumentEvent.addEdit(UndoableEdit anEdit)
Adds a document edit.

Uses of UndoableEdit in javax.swing.undo

Classes in javax.swing.undo that implement UndoableEdit
class | AbstractUndoableEdit An abstract implementation of UndoableEdit, implementing simple responses to all boolean methods in that interface.
class | CompoundEdit A concrete subclass of AbstractUndoableEdit, used to assemble little UndoableEdits into great big ones.
class | StateEdit StateEdit is a general edit for objects that change state.
class | UndoManager Concrete subclass of CompoundEdit which can serve as a UndoableEditListener, consolidating the UndoableEditEvents from a variety of sources, and undoing or redoing them one at a time.

Methods in javax.swing.undo that return UndoableEdit
protected UndoableEdit | UndoManager.editToBeUndone() Returns the the next significant edit to be undone if undo is called.
protected UndoableEdit | UndoManager.editToBeRedone() Returns the the next significant edit to be redone if redo is called.
protected UndoableEdit | CompoundEdit.lastEdit() Returns the last UndoableEdit in edits, or null if edits is empty.

Methods in javax.swing.undo with parameters of type UndoableEdit
protected void | UndoableEditSupport._postEdit(UndoableEdit e) Called only from postEdit and endUpdate.
void | UndoableEditSupport.postEdit(UndoableEdit e) DEADLOCK WARNING: Calling this method may call undoableEditHappened in all listeners.
protected void | UndoManager.undoTo(UndoableEdit edit) Undoes all changes from indexOfNextAdd to edit.
protected void | UndoManager.redoTo(UndoableEdit edit) Redoes all changes from indexOfNextAdd to edit.
boolean | UndoManager.addEdit(UndoableEdit anEdit) If inProgress, inserts anEdit at indexOfNextAdd, and removes any old edits that were at indexOfNextAdd or later.
boolean | AbstractUndoableEdit.addEdit(UndoableEdit anEdit) This default implementation returns false.
boolean | AbstractUndoableEdit.replaceEdit(UndoableEdit anEdit) This default implementation returns false.
boolean | CompoundEdit.addEdit(UndoableEdit anEdit) If this edit is inProgress, accepts anEdit and returns true.
boolean | UndoableEdit.addEdit(UndoableEdit anEdit) This UndoableEdit should absorb anEdit if it can.
boolean | UndoableEdit.replaceEdit(UndoableEdit anEdit) Returns true if this UndoableEdit should replace anEdit.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.undo.UndoableEditSupport (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.undo.UndoableEditSupport

No usage of javax.swing.undo.UndoableEditSupport

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.swing.undo.UndoManager (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.swing.undo.UndoManager

No usage of javax.swing.undo.UndoManager

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


InvalidTransactionException (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.transaction
Class InvalidTransactionException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.io.IOException
                extended by java.rmi.RemoteException
                    extended by javax.transaction.InvalidTransactionException
All Implemented Interfaces:
Serializable
public class InvalidTransactionException
extends RemoteException

This exception indicates that the request carried an invalid transaction context. For example, this exception could be raised if an error occured when trying to register a resource.

See Also:
Serialized Form

Field Summary
Fields inherited from class java.rmi.RemoteException
detail
Constructor Summary
InvalidTransactionException()
InvalidTransactionException(String msg)
Methods inherited from class java.rmi.RemoteException
getCause, getMessage
Methods inherited from class java.lang.Throwable
fillInStackTrace, getLocalizedMessage, getStackTrace, 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

InvalidTransactionException

public InvalidTransactionException()

InvalidTransactionException

public InvalidTransactionException(String msg)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


javax.transaction (Java 2 Platform SE v1.4.2)

 javax.transaction
Exceptions
InvalidTransactionException
TransactionRequiredException
TransactionRolledbackException


javax.transaction (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package javax.transaction

Contains three exceptions thrown by the ORB machinery during unmarshalling.

See:
Description

Exception Summary
InvalidTransactionException | This exception indicates that the request carried an invalid transaction context.
TransactionRequiredException | This exception indicates that a request carried a null transaction context, but the target object requires an activate transaction.
TransactionRolledbackException | This exception indicates that the transaction associated with processing of the request has been rolled back, or marked to roll back.

Package javax.transaction Description

Contains three exceptions thrown by the ORB machinery during unmarshalling.

Since:
1.3
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


javax.transaction Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package javax.transaction

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class java.lang.Throwable (implements java.io.Serializable)
      • class java.lang.Exception
        • class java.io.IOException
          • class java.rmi.RemoteException
            • class javax.transaction.InvalidTransactionException
            • class javax.transaction.TransactionRequiredException
            • class javax.transaction.TransactionRolledbackException
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package javax.transaction (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
javax.transaction

No usage of javax.transaction

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


TransactionRequiredException (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.transaction
Class TransactionRequiredException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.io.IOException
                extended by java.rmi.RemoteException
                    extended by javax.transaction.TransactionRequiredException
All Implemented Interfaces:
Serializable
public class TransactionRequiredException
extends RemoteException

This exception indicates that a request carried a null transaction context, but the target object requires an activate transaction.

See Also:
Serialized Form

Field Summary
Fields inherited from class java.rmi.RemoteException
detail
Constructor Summary
TransactionRequiredException()
TransactionRequiredException(String msg)
Methods inherited from class java.rmi.RemoteException
getCause, getMessage
Methods inherited from class java.lang.Throwable
fillInStackTrace, getLocalizedMessage, getStackTrace, 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

TransactionRequiredException

public TransactionRequiredException()

TransactionRequiredException

public TransactionRequiredException(String msg)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TransactionRolledbackException (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.transaction
Class TransactionRolledbackException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.io.IOException
                extended by java.rmi.RemoteException
                    extended by javax.transaction.TransactionRolledbackException
All Implemented Interfaces:
Serializable
public class TransactionRolledbackException
extends RemoteException

This exception indicates that the transaction associated with processing of the request has been rolled back, or marked to roll back. Thus the requested operation either could not be performed or was not performed because further computation on behalf of the transaction would be fruitless

See Also:
Serialized Form

Field Summary
Fields inherited from class java.rmi.RemoteException
detail
Constructor Summary
TransactionRolledbackException()
TransactionRolledbackException(String msg)
Methods inherited from class java.rmi.RemoteException
getCause, getMessage
Methods inherited from class java.lang.Throwable
fillInStackTrace, getLocalizedMessage, getStackTrace, 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

TransactionRolledbackException

public TransactionRolledbackException()

TransactionRolledbackException

public TransactionRolledbackException(String msg)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Uses of Class javax.transaction.InvalidTransactionException (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.transaction.InvalidTransactionException

No usage of javax.transaction.InvalidTransactionException

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.transaction.TransactionRequiredException (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.transaction.TransactionRequiredException

No usage of javax.transaction.TransactionRequiredException

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.transaction.TransactionRolledbackException (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.transaction.TransactionRolledbackException

No usage of javax.transaction.TransactionRolledbackException

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


javax.transaction.xa (Java 2 Platform SE v1.4.2)

 javax.transaction.xa
Interfaces
XAResource
Xid
Exceptions
XAException


javax.transaction.xa (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

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.

See:
Description

Interface Summary
XAResource | 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 | The Xid interface is a Java mapping of the X/Open transaction identifier XID structure.

Exception Summary
XAException The XAException is thrown by the Resource Manager (RM) to inform the Transaction Manager of an error encountered by the involved transaction.

Package javax.transaction.xa Description

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. The driver vendor for a specific resource manager provides the implementation of this API.

Since:
1.4
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


javax.transaction.xa Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package javax.transaction.xa

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class java.lang.Throwable (implements java.io.Serializable)
      • class java.lang.Exception
        • class javax.transaction.xa.XAException

Interface Hierarchy

  • interface javax.transaction.xa.XAResource
  • interface javax.transaction.xa.Xid
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package javax.transaction.xa (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
javax.transaction.xa

Packages that use javax.transaction.xa
javax.sql | Provides the API for server side data source access and processing from the JavaTM programming language.
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.

Classes in javax.transaction.xa used by javax.sql
XAResource
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).

Classes in javax.transaction.xa used by javax.transaction.xa
XAException
The XAException is thrown by the Resource Manager (RM) to inform the Transaction Manager of an error encountered by the involved transaction.
XAResource
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
The Xid interface is a Java mapping of the X/Open transaction identifier XID structure.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


XAException (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.transaction.xa
Class XAException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by javax.transaction.xa.XAException
All Implemented Interfaces:
Serializable
public class XAException
extends Exception

The XAException is thrown by the Resource Manager (RM) to inform the Transaction Manager of an error encountered by the involved transaction.

See Also:
Serialized Form

Field Summary
int | errorCode The error code with which to create the SystemException.
static int | XA_HEURCOM The transaction branch has been heuristically committed.
static int | XA_HEURHAZ The transaction branch may have been heuristically completed.
static int | XA_HEURMIX The transaction branch has been heuristically committed and rolled back.
static int | XA_HEURRB The transaction branch has been heuristically rolled back.
static int | XA_NOMIGRATE Resumption must occur where the suspension occurred.
static int | XA_RBBASE The inclusive lower bound of the rollback codes.
static int | XA_RBCOMMFAIL Indicates that the rollback was caused by a communication failure.
static int | XA_RBDEADLOCK A deadlock was detected.
static int | XA_RBEND The inclusive upper bound of the rollback error code.
static int | XA_RBINTEGRITY A condition that violates the integrity of the resource was detected.
static int | XA_RBOTHER The resource manager rolled back the transaction branch for a reason not on this list.
static int | XA_RBPROTO A protocol error occurred in the resource manager.
static int | XA_RBROLLBACK Indicates that the rollback was caused by an unspecified reason.
static int | XA_RBTIMEOUT A transaction branch took too long.
static int | XA_RBTRANSIENT May retry the transaction branch.
static int | XA_RDONLY The transaction branch was read-only and has been committed.
static int | XA_RETRY Routine returned with no effect and may be reissued.
static int | XAER_ASYNC There is an asynchronous operation already outstanding.
static int | XAER_DUPID The XID already exists.
static int | XAER_INVAL Invalid arguments were given.
static int | XAER_NOTA The XID is not valid.
static int | XAER_OUTSIDE The resource manager is doing work outside a global transaction.
static int | XAER_PROTO Routine was invoked in an inproper context.
static int | XAER_RMERR A resource manager error has occurred in the transaction branch.
static int | XAER_RMFAIL Resource manager is unavailable.
Constructor Summary
XAException()
Create an XAException.
XAException(int errcode)
Create an XAException with a given error code.
XAException(String s)
Create an XAException with a given string.
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

errorCode

public int errorCode
The error code with which to create the SystemException.

XA_RBBASE

public static final int XA_RBBASE
The inclusive lower bound of the rollback codes.

See Also:
Constant Field Values

XA_RBROLLBACK

public static final int XA_RBROLLBACK
Indicates that the rollback was caused by an unspecified reason.

See Also:
Constant Field Values

XA_RBCOMMFAIL

public static final int XA_RBCOMMFAIL
Indicates that the rollback was caused by a communication failure.

See Also:
Constant Field Values

XA_RBDEADLOCK

public static final int XA_RBDEADLOCK
A deadlock was detected.

See Also:
Constant Field Values

XA_RBINTEGRITY

public static final int XA_RBINTEGRITY
A condition that violates the integrity of the resource was detected.

See Also:
Constant Field Values

XA_RBOTHER

public static final int XA_RBOTHER
The resource manager rolled back the transaction branch for a reason not on this list.

See Also:
Constant Field Values

XA_RBPROTO

public static final int XA_RBPROTO
A protocol error occurred in the resource manager.

See Also:
Constant Field Values

XA_RBTIMEOUT

public static final int XA_RBTIMEOUT
A transaction branch took too long.

See Also:
Constant Field Values

XA_RBTRANSIENT

public static final int XA_RBTRANSIENT
May retry the transaction branch.

See Also:
Constant Field Values

XA_RBEND

public static final int XA_RBEND
The inclusive upper bound of the rollback error code.

See Also:
Constant Field Values

XA_NOMIGRATE

public static final int XA_NOMIGRATE
Resumption must occur where the suspension occurred.

See Also:
Constant Field Values

XA_HEURHAZ

public static final int XA_HEURHAZ
The transaction branch may have been heuristically completed.

See Also:
Constant Field Values

XA_HEURCOM

public static final int XA_HEURCOM
The transaction branch has been heuristically committed.

See Also:
Constant Field Values

XA_HEURRB

public static final int XA_HEURRB
The transaction branch has been heuristically rolled back.

See Also:
Constant Field Values

XA_HEURMIX

public static final int XA_HEURMIX
The transaction branch has been heuristically committed and rolled back.

See Also:
Constant Field Values

XA_RETRY

public static final int XA_RETRY
Routine returned with no effect and may be reissued.

See Also:
Constant Field Values

XA_RDONLY

public static final int XA_RDONLY
The transaction branch was read-only and has been committed.

See Also:
Constant Field Values

XAER_ASYNC

public static final int XAER_ASYNC
There is an asynchronous operation already outstanding.

See Also:
Constant Field Values

XAER_RMERR

public static final int XAER_RMERR
A resource manager error has occurred in the transaction branch.

See Also:
Constant Field Values

XAER_NOTA

public static final int XAER_NOTA
The XID is not valid.

See Also:
Constant Field Values

XAER_INVAL

public static final int XAER_INVAL
Invalid arguments were given.

See Also:
Constant Field Values

XAER_PROTO

public static final int XAER_PROTO
Routine was invoked in an inproper context.

See Also:
Constant Field Values

XAER_RMFAIL

public static final int XAER_RMFAIL
Resource manager is unavailable.

See Also:
Constant Field Values

XAER_DUPID

public static final int XAER_DUPID
The XID already exists.

See Also:
Constant Field Values

XAER_OUTSIDE

public static final int XAER_OUTSIDE
The resource manager is doing work outside a global transaction.

See Also:
Constant Field Values
Constructor Detail

XAException

public XAException()
Create an XAException.

XAException

public XAException(String s)
Create an XAException with a given string.

Parameters:
s - The String object containing the exception message.

XAException

public XAException(int errcode)
Create an XAException with a given error code.

Parameters:
errcode - The error code identifying the exception.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


XAResource (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.transaction.xa
Interface XAResource

public interface XAResource

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).

The XA interface defines the contract between a Resource Manager and a Transaction Manager in a distributed transaction processing (DTP) environment. A JDBC driver or a JMS provider implements this interface to support the association between a global transaction and a database or message service connection.

The XAResource interface can be supported by any transactional resource that is intended to be used by application programs in an environment where transactions are controlled by an external transaction manager. An example of such a resource is a database management system. An application may access data through multiple database connections. Each database connection is enlisted with the transaction manager as a transactional resource. The transaction manager obtains an XAResource for each connection participating in a global transaction. The transaction manager uses the start method to associate the global transaction with the resource, and it uses the end method to disassociate the transaction from the resource. The resource manager is responsible for associating the global transaction to all work performed on its data between the start and end method invocations.

At transaction commit time, the resource managers are informed by the transaction manager to prepare, commit, or rollback a transaction according to the two-phase commit protocol.

Field Summary
static int | TMENDRSCAN Ends a recovery scan.
static int | TMFAIL Disassociates the caller and marks the transaction branch rollback-only.
static int | TMJOIN Caller is joining existing transaction branch.
static int | TMNOFLAGS Use TMNOFLAGS to indicate no flags value is selected.
static int | TMONEPHASE Caller is using one-phase optimization.
static int | TMRESUME Caller is resuming association with a suspended transaction branch.
static int | TMSTARTRSCAN Starts a recovery scan.
static int | TMSUCCESS Disassociates caller from a transaction branch.
static int | TMSUSPEND Caller is suspending (not ending) its association with a transaction branch.
static int | XA_OK The transaction work has been prepared normally.
static int | XA_RDONLY The transaction branch has been read-only and has been committed.
Method Summary
void | commit(Xid xid, boolean onePhase) Commits the global transaction specified by xid.
void | end(Xid xid, int flags) Ends the work performed on behalf of a transaction branch.
void | forget(Xid xid) Tells the resource manager to forget about a heuristically completed transaction branch.
int | getTransactionTimeout() Obtains the current transaction timeout value set for this XAResource instance.
boolean | isSameRM(XAResource xares) This method is called to determine if the resource manager instance represented by the target object is the same as the resouce manager instance represented by the parameter xares.
int | prepare(Xid xid) Ask the resource manager to prepare for a transaction commit of the transaction specified in xid.
Xid[] | recover(int flag) Obtains a list of prepared transaction branches from a resource manager.
void | rollback(Xid xid) Informs the resource manager to roll back work done on behalf of a transaction branch.
boolean | setTransactionTimeout(int seconds) Sets the current transaction timeout value for this XAResource instance.
void | start(Xid xid, int flags) Starts work on behalf of a transaction branch specified in xid.

Field Detail

TMENDRSCAN

public static final int TMENDRSCAN
Ends a recovery scan.

See Also:
Constant Field Values

TMFAIL

public static final int TMFAIL
Disassociates the caller and marks the transaction branch rollback-only.

See Also:
Constant Field Values

TMJOIN

public static final int TMJOIN
Caller is joining existing transaction branch.

See Also:
Constant Field Values

TMNOFLAGS

public static final int TMNOFLAGS
Use TMNOFLAGS to indicate no flags value is selected.

See Also:
Constant Field Values

TMONEPHASE

public static final int TMONEPHASE
Caller is using one-phase optimization.

See Also:
Constant Field Values

TMRESUME

public static final int TMRESUME
Caller is resuming association with a suspended transaction branch.

See Also:
Constant Field Values

TMSTARTRSCAN

public static final int TMSTARTRSCAN
Starts a recovery scan.

See Also:
Constant Field Values

TMSUCCESS

public static final int TMSUCCESS
Disassociates caller from a transaction branch.

See Also:
Constant Field Values

TMSUSPEND

public static final int TMSUSPEND
Caller is suspending (not ending) its association with a transaction branch.

See Also:
Constant Field Values

XA_RDONLY

public static final int XA_RDONLY
The transaction branch has been read-only and has been committed.

See Also:
Constant Field Values

XA_OK

public static final int XA_OK
The transaction work has been prepared normally.

See Also:
Constant Field Values
Method Detail

commit

public void commit(Xid xid,
                   boolean onePhase)
            throws XAException
Commits the global transaction specified by xid.

Parameters:
xid - A global transaction identifier
onePhase - If true, the resource manager should use a one-phase commit protocol to commit the work done on behalf of xid.
Throws:
XAException - An error has occurred. Possible XAExceptions are XA_HEURHAZ, XA_HEURCOM, XA_HEURRB, XA_HEURMIX, XAER_RMERR, XAER_RMFAIL, XAER_NOTA, XAER_INVAL, or XAER_PROTO.

If the resource manager did not commit the transaction and the paramether onePhase is set to true, the resource manager may throw one of the XA_RB* exceptions. Upon return, the resource manager has rolled back the branch's work and has released all held resources.

end

public void end(Xid xid,
                int flags)
         throws XAException
Ends the work performed on behalf of a transaction branch. The resource manager disassociates the XA resource from the transaction branch specified and lets the transaction complete.

If TMSUSPEND is specified in the flags, the transaction branch is temporarily suspended in an incomplete state. The transaction context is in a suspended state and must be resumed via the start method with TMRESUME specified.

If TMFAIL is specified, the portion of work has failed. The resource manager may mark the transaction as rollback-only

If TMSUCCESS is specified, the portion of work has completed successfully.

Parameters:
xid - A global transaction identifier that is the same as the identifier used previously in the start method.
flags - One of TMSUCCESS, TMFAIL, or TMSUSPEND.
Throws:
XAException - An error has occurred. Possible XAException values are XAER_RMERR, XAER_RMFAILED, XAER_NOTA, XAER_INVAL, XAER_PROTO, or XA_RB*.

forget

public void forget(Xid xid)
            throws XAException
Tells the resource manager to forget about a heuristically completed transaction branch.

Parameters:
xid - A global transaction identifier.
Throws:
XAException - An error has occurred. Possible exception values are XAER_RMERR, XAER_RMFAIL, XAER_NOTA, XAER_INVAL, or XAER_PROTO.

getTransactionTimeout

public int getTransactionTimeout()
                          throws XAException
Obtains the current transaction timeout value set for this XAResource instance. If XAResource.setTransactionTimeout was not used prior to invoking this method, the return value is the default timeout set for the resource manager; otherwise, the value used in the previous setTransactionTimeout call is returned.

Returns:
the transaction timeout value in seconds.
Throws:
XAException - An error has occurred. Possible exception values are XAER_RMERR and XAER_RMFAIL.

isSameRM

public boolean isSameRM(XAResource xares)
                 throws XAException
This method is called to determine if the resource manager instance represented by the target object is the same as the resouce manager instance represented by the parameter xares.

Parameters:
xares - An XAResource object whose resource manager instance is to be compared with the resource manager instance of the target object.
Returns:
true if it's the same RM instance; otherwise false.
Throws:
XAException - An error has occurred. Possible exception values are XAER_RMERR and XAER_RMFAIL.

prepare

public int prepare(Xid xid)
            throws XAException
Ask the resource manager to prepare for a transaction commit of the transaction specified in xid.

Parameters:
xid - A global transaction identifier.
Returns:
A value indicating the resource manager's vote on the outcome of the transaction. The possible values are: XA_RDONLY or XA_OK. If the resource manager wants to roll back the transaction, it should do so by raising an appropriate XAException in the prepare method.
Throws:
XAException - An error has occurred. Possible exception values are: XA_RB*, XAER_RMERR, XAER_RMFAIL, XAER_NOTA, XAER_INVAL, or XAER_PROTO.

recover

public Xid[] recover(int flag)
              throws XAException
Obtains a list of prepared transaction branches from a resource manager. The transaction manager calls this method during recovery to obtain the list of transaction branches that are currently in prepared or heuristically completed states.

Parameters:
flag - One of TMSTARTRSCAN, TMENDRSCAN, TMNOFLAGS. TMNOFLAGS must be used when no other flags are set in the parameter.
Returns:
The resource manager returns zero or more XIDs of the transaction branches that are currently in a prepared or heuristically completed state. If an error occurs during the operation, the resource manager should throw the appropriate XAException.
Throws:
XAException - An error has occurred. Possible values are XAER_RMERR, XAER_RMFAIL, XAER_INVAL, and XAER_PROTO.

rollback

public void rollback(Xid xid)
              throws XAException
Informs the resource manager to roll back work done on behalf of a transaction branch.

Parameters:
xid - A global transaction identifier.
Throws:
XAException - An error has occurred.

setTransactionTimeout

public boolean setTransactionTimeout(int seconds)
                              throws XAException

Sets the current transaction timeout value for this XAResource instance. Once set, this timeout value is effective until setTransactionTimeout is invoked again with a different value. To reset the timeout value to the default value used by the resource manager, set the value to zero. If the timeout operation is performed successfully, the method returns true; otherwise false. If a resource manager does not support explicitly setting the transaction timeout value, this method returns false.

Parameters:
seconds - The transaction timeout value in seconds.
Returns:
true if the transaction timeout value is set successfully; otherwise false.
Throws:
XAException - An error has occurred. Possible exception values are XAER_RMERR, XAER_RMFAIL, or XAER_INVAL.

start

public void start(Xid xid,
                  int flags)
           throws XAException
Starts work on behalf of a transaction branch specified in xid. If TMJOIN is specified, the start applies to joining a transaction previously seen by the resource manager. If TMRESUME is specified, the start applies to resuming a suspended transaction specified in the parameter xid. If neither TMJOIN nor TMRESUME is specified and the transaction specified by xid has previously been seen by the resource manager, the resource manager throws the XAException exception with XAER_DUPID error code.

Parameters:
xid - A global transaction identifier to be associated with the resource.
flags - One of TMNOFLAGS, TMJOIN, or TMRESUME.
Throws:
XAException - An error has occurred. Possible exceptions are XA_RB*, XAER_RMERR, XAER_RMFAIL, XAER_DUPID, XAER_OUTSIDE, XAER_NOTA, XAER_INVAL, or XAER_PROTO.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Xid (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.transaction.xa
Interface Xid

public interface Xid

The Xid interface is a Java mapping of the X/Open transaction identifier XID structure. This interface specifies three accessor methods to retrieve a global transaction format ID, global transaction ID, and branch qualifier. The Xid interface is used by the transaction manager and the resource managers. This interface is not visible to the application programs.

Field Summary
static int | MAXBQUALSIZE Maximum number of bytes returned by getBqual.
static int | MAXGTRIDSIZE Maximum number of bytes returned by getGtrid.
Method Summary
byte[] | getBranchQualifier() Obtain the transaction branch identifier part of XID as an array of bytes.
int | getFormatId() Obtain the format identifier part of the XID.
byte[] | getGlobalTransactionId() Obtain the global transaction identifier part of XID as an array of bytes.

Field Detail

MAXGTRIDSIZE

public static final int MAXGTRIDSIZE
Maximum number of bytes returned by getGtrid.

See Also:
Constant Field Values

MAXBQUALSIZE

public static final int MAXBQUALSIZE
Maximum number of bytes returned by getBqual.

See Also:
Constant Field Values
Method Detail

getFormatId

public int getFormatId()
Obtain the format identifier part of the XID.

Returns:
Format identifier. O means the OSI CCR format.

getGlobalTransactionId

public byte[] getGlobalTransactionId()
Obtain the global transaction identifier part of XID as an array of bytes.

Returns:
Global transaction identifier.

getBranchQualifier

public byte[] getBranchQualifier()
Obtain the transaction branch identifier part of XID as an array of bytes.

Returns:
Global transaction identifier.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Uses of Class javax.transaction.xa.XAException (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.transaction.xa.XAException

Packages that use XAException
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.

Uses of XAException in javax.transaction.xa

Methods in javax.transaction.xa that throw XAException
void | XAResource.commit(Xid xid, boolean onePhase) Commits the global transaction specified by xid.
void | XAResource.end(Xid xid, int flags) Ends the work performed on behalf of a transaction branch.
void | XAResource.forget(Xid xid) Tells the resource manager to forget about a heuristically completed transaction branch.
int | XAResource.getTransactionTimeout() Obtains the current transaction timeout value set for this XAResource instance.
boolean | XAResource.isSameRM(XAResource xares) This method is called to determine if the resource manager instance represented by the target object is the same as the resouce manager instance represented by the parameter xares.
int | XAResource.prepare(Xid xid) Ask the resource manager to prepare for a transaction commit of the transaction specified in xid.
Xid[] | XAResource.recover(int flag) Obtains a list of prepared transaction branches from a resource manager.
void | XAResource.rollback(Xid xid) Informs the resource manager to roll back work done on behalf of a transaction branch.
boolean | XAResource.setTransactionTimeout(int seconds) Sets the current transaction timeout value for this XAResource instance.
void | XAResource.start(Xid xid, int flags) Starts work on behalf of a transaction branch specified in xid.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.transaction.xa.XAResource (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.transaction.xa.XAResource

Packages that use XAResource
javax.sql | Provides the API for server side data source access and processing from the JavaTM programming language.
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.

Uses of XAResource in javax.sql

Methods in javax.sql that return XAResource
 XAResource XAConnection.getXAResource()
Retrieves an XAResource object that the transaction manager will use to manage this XAConnection object's participation in a distributed transaction.

Uses of XAResource in javax.transaction.xa

Methods in javax.transaction.xa with parameters of type XAResource
 boolean XAResource.isSameRM(XAResource xares)
This method is called to determine if the resource manager instance represented by the target object is the same as the resouce manager instance represented by the parameter xares.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.transaction.xa.Xid (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.transaction.xa.Xid

Packages that use Xid
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.

Uses of Xid in javax.transaction.xa

Methods in javax.transaction.xa that return Xid
 Xid[] XAResource.recover(int flag)
Obtains a list of prepared transaction branches from a resource manager.

Methods in javax.transaction.xa with parameters of type Xid
void | XAResource.commit(Xid xid, boolean onePhase) Commits the global transaction specified by xid.
void | XAResource.end(Xid xid, int flags) Ends the work performed on behalf of a transaction branch.
void | XAResource.forget(Xid xid) Tells the resource manager to forget about a heuristically completed transaction branch.
int | XAResource.prepare(Xid xid) Ask the resource manager to prepare for a transaction commit of the transaction specified in xid.
void | XAResource.rollback(Xid xid) Informs the resource manager to roll back work done on behalf of a transaction branch.
void | XAResource.start(Xid xid, int flags) Starts work on behalf of a transaction branch specified in xid.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


DocumentBuilder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.xml.parsers
Class DocumentBuilder

java.lang.Object
    extended by javax.xml.parsers.DocumentBuilder
public abstract class DocumentBuilder
extends Object

Defines the API to obtain DOM Document instances from an XML document. Using this class, an application programmer can obtain a Document from XML.

An instance of this class can be obtained from the DocumentBuilderFactory.newDocumentBuilder method. Once an instance of this class is obtained, XML can be parsed from a variety of input sources. These input sources are InputStreams, Files, URLs, and SAX InputSources.

Note that this class reuses several classes from the SAX API. This does not require that the implementor of the underlying DOM implementation use a SAX parser to parse XML document into a Document. It merely requires that the implementation communicate with the application using these existing APIs.

An implementation of DocumentBuilder is NOT guaranteed to behave as per the specification if it is used concurrently by two or more threads. It is recommended to have one instance of the DocumentBuilder per thread or it is upto the application to make sure about the use of DocumentBuilder from more than one thread.

Since:
JAXP 1.0

Constructor Summary
protected DocumentBuilder()
Method Summary
abstract DOMImplementation | getDOMImplementation() Obtain an instance of a DOMImplementation object.
abstract boolean | isNamespaceAware() Indicates whether or not this parser is configured to understand namespaces.
abstract boolean | isValidating() Indicates whether or not this parser is configured to validate XML documents.
abstract Document | newDocument() Obtain a new instance of a DOM Document object to build a DOM tree with.
Document | parse(File f) Parse the content of the given file as an XML document and return a new DOM Document object.
abstract Document | parse(InputSource is) Parse the content of the given input source as an XML document and return a new DOM Document object.
Document | parse(InputStream is) Parse the content of the given InputStream as an XML document and return a new DOM Document object.
Document | parse(InputStream is, String systemId) Parse the content of the given InputStream as an XML document and return a new DOM Document object.
Document | parse(String uri) Parse the content of the given URI as an XML document and return a new DOM Document object.
abstract void | setEntityResolver(EntityResolver er) Specify the EntityResolver to be used to resolve entities present in the XML document to be parsed.
abstract void | setErrorHandler(ErrorHandler eh) Specify the ErrorHandler to be used to report errors present in the XML document to be parsed.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DocumentBuilder

protected DocumentBuilder()
Method Detail

parse

public Document parse(InputStream is)
               throws SAXException,
                      IOException
Parse the content of the given InputStream as an XML document and return a new DOM Document object.

Parameters:
is - InputStream containing the content to be parsed.
Throws:
IOException - If any IO errors occur.
SAXException - If any parse errors occur.
IllegalArgumentException - If the InputStream is null
See Also:
DocumentHandler

parse

public Document parse(InputStream is,
                      String systemId)
               throws SAXException,
                      IOException
Parse the content of the given InputStream as an XML document and return a new DOM Document object.

Parameters:
is - InputStream containing the content to be parsed.
systemId - Provide a base for resolving relative URIs.
Returns:
A new DOM Document object.
Throws:
IOException - If any IO errors occur.
SAXException - If any parse errors occur.
IllegalArgumentException - If the InputStream is null.
See Also:
DocumentHandler

parse

public Document parse(String uri)
               throws SAXException,
                      IOException
Parse the content of the given URI as an XML document and return a new DOM Document object.

Parameters:
uri - The location of the content to be parsed.
Returns:
A new DOM Document object.
Throws:
IOException - If any IO errors occur.
SAXException - If any parse errors occur.
IllegalArgumentException - If the URI is null.
See Also:
DocumentHandler

parse

public Document parse(File f)
               throws SAXException,
                      IOException
Parse the content of the given file as an XML document and return a new DOM Document object.

Parameters:
f - The file containing the XML to parse.
Returns:
A new DOM Document object.
Throws:
IOException - If any IO errors occur.
SAXException - If any parse errors occur.
IllegalArgumentException - If the file is null.
See Also:
DocumentHandler

parse

public abstract Document parse(InputSource is)
                        throws SAXException,
                               IOException
Parse the content of the given input source as an XML document and return a new DOM Document object.

Parameters:
is - InputSource containing the content to be parsed.
Returns:
A new DOM Document object.
Throws:
IOException - If any IO errors occur.
SAXException - If any parse errors occur.
IllegalArgumentException - If the InputSource is null.
See Also:
DocumentHandler

isNamespaceAware

public abstract boolean isNamespaceAware()
Indicates whether or not this parser is configured to understand namespaces.

Returns:
true if this parser is configured to understand namespaces; false otherwise.

isValidating

public abstract boolean isValidating()
Indicates whether or not this parser is configured to validate XML documents.

Returns:
true if this parser is configured to validate XML documents; false otherwise.

setEntityResolver

public abstract void setEntityResolver(EntityResolver er)
Specify the EntityResolver to be used to resolve entities present in the XML document to be parsed. Setting this to null will result in the underlying implementation using it's own default implementation and behavior.

Parameters:
er - The EntityResolver to be used to resolve entities present in the XML document to be parsed.

setErrorHandler

public abstract void setErrorHandler(ErrorHandler eh)
Specify the ErrorHandler to be used to report errors present in the XML document to be parsed. Setting this to null will result in the underlying implementation using it's own default implementation and behavior.

Parameters:
eh - The ErrorHandler to be used to report errors present in the XML document to be parsed.

newDocument

public abstract Document newDocument()
Obtain a new instance of a DOM Document object to build a DOM tree with. An alternative way to create a DOM Document object is to use the getDOMImplementation method to get a DOM Level 2 DOMImplementation object and then use DOM Level 2 methods on that object to create a DOM Document object.

Returns:
A new instance of a DOM Document object.

getDOMImplementation

public abstract DOMImplementation getDOMImplementation()
Obtain an instance of a DOMImplementation object.

Returns:
A new instance of a DOMImplementation.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


DocumentBuilderFactory (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.xml.parsers
Class DocumentBuilderFactory

java.lang.Object
    extended by javax.xml.parsers.DocumentBuilderFactory
public abstract class DocumentBuilderFactory
extends Object

Defines a factory API that enables applications to obtain a parser that produces DOM object trees from XML documents. An implementation of the DocumentBuilderFactory class is NOT guaranteed to be thread safe. It is up to the user application to make sure about the use of the DocumentBuilderFactory from more than one thread. Alternatively the application can have one instance of the DocumentBuilderFactory per thread. An application can use the same instance of the factory to obtain one or more instances of the DocumentBuilder provided the instance of the factory isn't being used in more than one thread at a time.

Since:
JAXP 1.0

Constructor Summary
protected DocumentBuilderFactory()
Method Summary
abstract Object | getAttribute(String name) Allows the user to retrieve specific attributes on the underlying implementation.
boolean | isCoalescing() Indicates whether or not the factory is configured to produce parsers which converts CDATA nodes to Text nodes and appends it to the adjacent (if any) Text node.
boolean | isExpandEntityReferences() Indicates whether or not the factory is configured to produce parsers which expand entity reference nodes.
boolean | isIgnoringComments() Indicates whether or not the factory is configured to produce parsers which ignores comments.
boolean | isIgnoringElementContentWhitespace() Indicates whether or not the factory is configured to produce parsers which ignore ignorable whitespace in element content.
boolean | isNamespaceAware() Indicates whether or not the factory is configured to produce parsers which are namespace aware.
boolean | isValidating() Indicates whether or not the factory is configured to produce parsers which validate the XML content during parse.
abstract DocumentBuilder | newDocumentBuilder() Creates a new instance of a DocumentBuilder using the currently configured parameters.
static DocumentBuilderFactory | newInstance() Obtain a new instance of a DocumentBuilderFactory.
abstract void | setAttribute(String name, Object value) Allows the user to set specific attributes on the underlying implementation.
void | setCoalescing(boolean coalescing) 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.
void | setExpandEntityReferences(boolean expandEntityRef) Specifies that the parser produced by this code will expand entity reference nodes.
void | setIgnoringComments(boolean ignoreComments) Specifies that the parser produced by this code will ignore comments.
void | setIgnoringElementContentWhitespace(boolean whitespace) 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).
void | setNamespaceAware(boolean awareness) Specifies that the parser produced by this code will provide support for XML namespaces.
void | setValidating(boolean validating) Specifies that the parser produced by this code will validate documents as they are parsed.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DocumentBuilderFactory

protected DocumentBuilderFactory()
Method Detail

newInstance

public static DocumentBuilderFactory newInstance()
                                          throws FactoryConfigurationError
Obtain a new instance of a DocumentBuilderFactory. This static method creates a new factory instance. This method uses the following ordered lookup procedure to determine the DocumentBuilderFactory implementation class to load:
  • Use the javax.xml.parsers.DocumentBuilderFactory system property.
  • Use the properties file "lib/jaxp.properties" in the JRE directory. This configuration file is in standard java.util.Properties format and contains the fully qualified name of the implementation class with the key being the system property defined above.
  • Use the Services API (as detailed in the JAR specification), if available, to determine the classname. The Services API will look for a classname in the file META-INF/services/javax.xml.parsers.DocumentBuilderFactory in jars available to the runtime.
  • Platform default DocumentBuilderFactory instance.
Once an application has obtained a reference to a DocumentBuilderFactory it can use the factory to configure and obtain parser instances.

Throws:
FactoryConfigurationError - if the implementation is not available or cannot be instantiated.

newDocumentBuilder

public abstract DocumentBuilder newDocumentBuilder()
                                            throws ParserConfigurationException
Creates a new instance of a DocumentBuilder using the currently configured parameters.

Returns:
A new instance of a DocumentBuilder.
Throws:
ParserConfigurationException - if a DocumentBuilder cannot be created which satisfies the configuration requested.

setNamespaceAware

public void setNamespaceAware(boolean awareness)
Specifies that the parser produced by this code will provide support for XML namespaces. By default the value of this is set to false

Parameters:
awareness - true if the parser produced will provide support for XML namespaces; false otherwise.

setValidating

public void setValidating(boolean validating)
Specifies that the parser produced by this code will validate documents as they are parsed. By default the value of this is set to false.

Parameters:
validating - true if the parser produced will validate documents as they are parsed; false otherwise.

setIgnoringElementContentWhitespace

public void setIgnoringElementContentWhitespace(boolean whitespace)
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). Note that only whitespace which is directly contained within element content that has an element only content model (see XML Rec 3.2.1) will be eliminated. Due to reliance on the content model this setting requires the parser to be in validating mode. By default the value of this is set to false.

Parameters:
whitespace - true if the parser created must eliminate whitespace in the element content when parsing XML documents; false otherwise.

setExpandEntityReferences

public void setExpandEntityReferences(boolean expandEntityRef)
Specifies that the parser produced by this code will expand entity reference nodes. By default the value of this is set to true

Parameters:
expandEntityRef - true if the parser produced will expand entity reference nodes; false otherwise.

setIgnoringComments

public void setIgnoringComments(boolean ignoreComments)
Specifies that the parser produced by this code will ignore comments. By default the value of this is set to false

setCoalescing

public void setCoalescing(boolean coalescing)
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. By default the value of this is set to false

Parameters:
coalescing - true if the parser produced will convert CDATA nodes to Text nodes and append it to the adjacent (if any) text node; false otherwise.

isNamespaceAware

public boolean isNamespaceAware()
Indicates whether or not the factory is configured to produce parsers which are namespace aware.

Returns:
true if the factory is configured to produce parsers which are namespace aware; false otherwise.

isValidating

public boolean isValidating()
Indicates whether or not the factory is configured to produce parsers which validate the XML content during parse.

Returns:
true if the factory is configured to produce parsers which validate the XML content during parse; false otherwise.

isIgnoringElementContentWhitespace

public boolean isIgnoringElementContentWhitespace()
Indicates whether or not the factory is configured to produce parsers which ignore ignorable whitespace in element content.

Returns:
true if the factory is configured to produce parsers which ignore ignorable whitespace in element content; false otherwise.

isExpandEntityReferences

public boolean isExpandEntityReferences()
Indicates whether or not the factory is configured to produce parsers which expand entity reference nodes.

Returns:
true if the factory is configured to produce parsers which expand entity reference nodes; false otherwise.

isIgnoringComments

public boolean isIgnoringComments()
Indicates whether or not the factory is configured to produce parsers which ignores comments.

Returns:
true if the factory is configured to produce parsers which ignores comments; false otherwise.

isCoalescing

public boolean isCoalescing()
Indicates whether or not the factory is configured to produce parsers which converts CDATA nodes to Text nodes and appends it to the adjacent (if any) Text node.

Returns:
true if the factory is configured to produce parsers which converts CDATA nodes to Text nodes and appends it to the adjacent (if any) Text node; false otherwise.

setAttribute

public abstract void setAttribute(String name,
                                  Object value)
                           throws IllegalArgumentException
Allows the user to set specific attributes on the underlying implementation.

Parameters:
name - The name of the attribute.
value - The value of the attribute.
Throws:
IllegalArgumentException - thrown if the underlying implementation doesn't recognize the attribute.

getAttribute

public abstract Object getAttribute(String name)
                             throws IllegalArgumentException
Allows the user to retrieve specific attributes on the underlying implementation.

Parameters:
name - The name of the attribute.
Returns:
value The value of the attribute.
Throws:
IllegalArgumentException - thrown if the underlying implementation doesn't recognize the attribute.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


FactoryConfigurationError (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.xml.parsers
Class FactoryConfigurationError

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Error
            extended by javax.xml.parsers.FactoryConfigurationError
All Implemented Interfaces:
Serializable
public class FactoryConfigurationError
extends Error

Thrown when a problem with configuration with the Parser Factories exists. This error will typically be thrown when the class of a parser factory specified in the system properties cannot be found or instantiated.

Since:
JAXP 1.0
See Also:
Serialized Form

Constructor Summary
FactoryConfigurationError()
Create a new FactoryConfigurationError with no detail mesage.
FactoryConfigurationError(Exception e)
Create a new FactoryConfigurationError with a given Exception base cause of the error.
FactoryConfigurationError(Exception e, String msg)
Create a new FactoryConfigurationError with the given Exception base cause and detail message.
FactoryConfigurationError(String msg)
Create a new FactoryConfigurationError with the String specified as an error message.
Method Summary
Exception | getException() Return the actual exception (if any) that caused this exception to be raised.
String | getMessage() Return the message (if any) for this error .
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getStackTrace, 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

FactoryConfigurationError

public FactoryConfigurationError()
Create a new FactoryConfigurationError with no detail mesage.

FactoryConfigurationError

public FactoryConfigurationError(String msg)
Create a new FactoryConfigurationError with the String specified as an error message.

Parameters:
msg - The error message for the exception.

FactoryConfigurationError

public FactoryConfigurationError(Exception e)
Create a new FactoryConfigurationError with a given Exception base cause of the error.

Parameters:
e - The exception to be encapsulated in a FactoryConfigurationError.

FactoryConfigurationError

public FactoryConfigurationError(Exception e,
                                 String msg)
Create a new FactoryConfigurationError with the given Exception base cause and detail message.

Parameters:
e - The exception to be encapsulated in a FactoryConfigurationError
msg - The detail message.
Method Detail

getMessage

public String getMessage()
Return the message (if any) for this error . If there is no message for the exception and there is an encapsulated exception then the message of that exception, if it exists will be returned. Else the name of the encapsulated exception will be returned.

Overrides:
getMessage in class Throwable
Returns:
The error message.

getException

public Exception getException()
Return the actual exception (if any) that caused this exception to be raised.

Returns:
The encapsulated exception, or null if there is none.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


javax.xml.parsers (Java 2 Platform SE v1.4.2)

 javax.xml.parsers
Classes
DocumentBuilder
DocumentBuilderFactory
SAXParser
SAXParserFactory
Exceptions
ParserConfigurationException
Errors
FactoryConfigurationError


javax.xml.parsers (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package javax.xml.parsers

Provides classes allowing the processing of XML documents.

See:
Description

Class Summary
DocumentBuilder | Defines the API to obtain DOM Document instances from an XML document.
DocumentBuilderFactory | Defines a factory API that enables applications to obtain a parser that produces DOM object trees from XML documents.
SAXParser | Defines the API that wraps an XMLReader implementation class.
SAXParserFactory | Defines a factory API that enables applications to configure and obtain a SAX based parser to parse XML documents.

Exception Summary
ParserConfigurationException Indicates a serious configuration error.

Error Summary
FactoryConfigurationError Thrown when a problem with configuration with the Parser Factories exists.

Package javax.xml.parsers Description

Provides classes allowing the processing of XML documents. Two types of plugable parsers are supported:

  • SAX (Simple API for XML)
  • DOM (Document Object Model)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


javax.xml.parsers Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package javax.xml.parsers

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class javax.xml.parsers.DocumentBuilder
    • class javax.xml.parsers.DocumentBuilderFactory
    • class javax.xml.parsers.SAXParser
    • class javax.xml.parsers.SAXParserFactory
    • class java.lang.Throwable (implements java.io.Serializable)
      • class java.lang.Error
        • class javax.xml.parsers.FactoryConfigurationError
      • class java.lang.Exception
        • class javax.xml.parsers.ParserConfigurationException
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package javax.xml.parsers (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
javax.xml.parsers

Packages that use javax.xml.parsers
javax.xml.parsers Provides classes allowing the processing of XML documents.

Classes in javax.xml.parsers used by javax.xml.parsers
DocumentBuilder
Defines the API to obtain DOM Document instances from an XML document.
DocumentBuilderFactory
Defines a factory API that enables applications to obtain a parser that produces DOM object trees from XML documents.
FactoryConfigurationError
Thrown when a problem with configuration with the Parser Factories exists.
ParserConfigurationException
Indicates a serious configuration error.
SAXParser
Defines the API that wraps an XMLReader implementation class.
SAXParserFactory
Defines a factory API that enables applications to configure and obtain a SAX based parser to parse XML documents.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


ParserConfigurationException (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.xml.parsers
Class ParserConfigurationException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by javax.xml.parsers.ParserConfigurationException
All Implemented Interfaces:
Serializable
public class ParserConfigurationException
extends Exception

Indicates a serious configuration error.

Since:
JAXP 1.0
See Also:
Serialized Form

Constructor Summary
ParserConfigurationException()
Create a new ParserConfigurationException with no detail mesage.
ParserConfigurationException(String msg)
Create a new ParserConfigurationException with the String specified as an error message.
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

ParserConfigurationException

public ParserConfigurationException()
Create a new ParserConfigurationException with no detail mesage.

ParserConfigurationException

public ParserConfigurationException(String msg)
Create a new ParserConfigurationException with the String specified as an error message.

Parameters:
msg - The error message for the exception.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


SAXParser (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.xml.parsers
Class SAXParser

java.lang.Object
    extended by javax.xml.parsers.SAXParser
public abstract class SAXParser
extends Object

Defines the API that wraps an XMLReader implementation class. In JAXP 1.0, this class wrapped the Parser interface, however this interface was replaced by the XMLReader. For ease of transition, this class continues to support the same name and interface as well as supporting new methods. An instance of this class can be obtained from the SAXParserFactory.newSAXParser() method. Once an instance of this class is obtained, XML can be parsed from a variety of input sources. These input sources are InputStreams, Files, URLs, and SAX InputSources.

As the content is parsed by the underlying parser, methods of the given HandlerBase or the DefaultHandler are called.

Implementors of this class which wrap an underlying implementation can consider using the ParserAdapter class to initially adapt their SAX1 impelemntation to work under this revised class.

An implementation of SAXParser is NOT guaranteed to behave as per the specification if it is used concurrently by two or more threads. It is recommended to have one instance of the SAXParser per thread or it is upto the application to make sure about the use of SAXParser from more than one thread.

Since:
JAXP 1.0

Constructor Summary
protected SAXParser()
Method Summary
abstract Parser | getParser() Returns the SAX parser that is encapsultated by the implementation of this class.
abstract Object | getProperty(String name) Returns the particular property requested for in the underlying implementation of XMLReader.
abstract XMLReader | getXMLReader() Returns the XMLReader that is encapsulated by the implementation of this class.
abstract boolean | isNamespaceAware() Indicates whether or not this parser is configured to understand namespaces.
abstract boolean | isValidating() Indicates whether or not this parser is configured to validate XML documents.
void | parse(File f, DefaultHandler dh) Parse the content of the file specified as XML using the specified DefaultHandler.
void | parse(File f, HandlerBase hb) Parse the content of the file specified as XML using the specified HandlerBase.
void | parse(InputSource is, DefaultHandler dh) Parse the content given InputSource as XML using the specified DefaultHandler.
void | parse(InputSource is, HandlerBase hb) Parse the content given InputSource as XML using the specified HandlerBase.
void | parse(InputStream is, DefaultHandler dh) Parse the content of the given InputStream instance as XML using the specified DefaultHandler.
void | parse(InputStream is, DefaultHandler dh, String systemId) Parse the content of the given InputStream instance as XML using the specified DefaultHandler.
void | parse(InputStream is, HandlerBase hb) Parse the content of the given InputStream instance as XML using the specified HandlerBase.
void | parse(InputStream is, HandlerBase hb, String systemId) Parse the content of the given InputStream instance as XML using the specified HandlerBase.
void | parse(String uri, DefaultHandler dh) Parse the content described by the giving Uniform Resource Identifier (URI) as XML using the specified DefaultHandler.
void | parse(String uri, HandlerBase hb) Parse the content described by the giving Uniform Resource Identifier (URI) as XML using the specified HandlerBase.
abstract void | setProperty(String name, Object value) Sets the particular property in the underlying implementation of XMLReader.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

SAXParser

protected SAXParser()
Method Detail

parse

public void parse(InputStream is,
                  HandlerBase hb)
           throws SAXException,
                  IOException
Parse the content of the given InputStream instance as XML using the specified HandlerBase. Use of the DefaultHandler version of this method is recommended as the HandlerBase class has been deprecated in SAX 2.0

Parameters:
is - InputStream containing the content to be parsed.
hb - The SAX HandlerBase to use.
Throws:
IOException - If any IO errors occur.
IllegalArgumentException - If the given InputStream is null.
SAXException - If the underlying parser throws a SAXException while parsing.
See Also:
DocumentHandler

parse

public void parse(InputStream is,
                  HandlerBase hb,
                  String systemId)
           throws SAXException,
                  IOException
Parse the content of the given InputStream instance as XML using the specified HandlerBase. Use of the DefaultHandler version of this method is recommended as the HandlerBase class has been deprecated in SAX 2.0

Parameters:
is - InputStream containing the content to be parsed.
hb - The SAX HandlerBase to use.
systemId - The systemId which is needed for resolving relative URIs.
Throws:
IOException - If any IO errors occur.
IllegalArgumentException - If the given InputStream is null.
SAXException - If the underlying parser throws a SAXException while parsing.
See Also:
version of this method instead.

parse

public void parse(InputStream is,
                  DefaultHandler dh)
           throws SAXException,
                  IOException
Parse the content of the given InputStream instance as XML using the specified DefaultHandler.

Parameters:
is - InputStream containing the content to be parsed.
dh - The SAX DefaultHandler to use.
Throws:
IOException - If any IO errors occur.
IllegalArgumentException - If the given InputStream is null.
SAXException - If the underlying parser throws a SAXException while parsing.
See Also:
DocumentHandler

parse

public void parse(InputStream is,
                  DefaultHandler dh,
                  String systemId)
           throws SAXException,
                  IOException
Parse the content of the given InputStream instance as XML using the specified DefaultHandler.

Parameters:
is - InputStream containing the content to be parsed.
dh - The SAX DefaultHandler to use.
systemId - The systemId which is needed for resolving relative URIs.
Throws:
IOException - If any IO errors occur.
IllegalArgumentException - If the given InputStream is null.
SAXException - If the underlying parser throws a SAXException while parsing.
See Also:
version of this method instead.

parse

public void parse(String uri,
                  HandlerBase hb)
           throws SAXException,
                  IOException
Parse the content described by the giving Uniform Resource Identifier (URI) as XML using the specified HandlerBase. Use of the DefaultHandler version of this method is recommended as the HandlerBase class has been deprecated in SAX 2.0

Parameters:
uri - The location of the content to be parsed.
hb - The SAX HandlerBase to use.
Throws:
IOException - If any IO errors occur.
IllegalArgumentException - If the uri is null.
SAXException - If the underlying parser throws a SAXException while parsing.
See Also:
DocumentHandler

parse

public void parse(String uri,
                  DefaultHandler dh)
           throws SAXException,
                  IOException
Parse the content described by the giving Uniform Resource Identifier (URI) as XML using the specified DefaultHandler.

Parameters:
uri - The location of the content to be parsed.
dh - The SAX DefaultHandler to use.
Throws:
IOException - If any IO errors occur.
IllegalArgumentException - If the uri is null.
SAXException - If the underlying parser throws a SAXException while parsing.
See Also:
DocumentHandler

parse

public void parse(File f,
                  HandlerBase hb)
           throws SAXException,
                  IOException
Parse the content of the file specified as XML using the specified HandlerBase. Use of the DefaultHandler version of this method is recommended as the HandlerBase class has been deprecated in SAX 2.0

Parameters:
f - The file containing the XML to parse
hb - The SAX HandlerBase to use.
Throws:
IOException - If any IO errors occur.
IllegalArgumentException - If the File object is null.
SAXException - If the underlying parser throws a SAXException while parsing.
See Also:
DocumentHandler

parse

public void parse(File f,
                  DefaultHandler dh)
           throws SAXException,
                  IOException
Parse the content of the file specified as XML using the specified DefaultHandler.

Parameters:
f - The file containing the XML to parse
dh - The SAX DefaultHandler to use.
Throws:
IOException - If any IO errors occur.
IllegalArgumentException - If the File object is null.
SAXException - If the underlying parser throws a SAXException while parsing.
See Also:
DocumentHandler

parse

public void parse(InputSource is,
                  HandlerBase hb)
           throws SAXException,
                  IOException
Parse the content given InputSource as XML using the specified HandlerBase. Use of the DefaultHandler version of this method is recommended as the HandlerBase class has been deprecated in SAX 2.0

Parameters:
is - The InputSource containing the content to be parsed.
hb - The SAX HandlerBase to use.
Throws:
IOException - If any IO errors occur.
IllegalArgumentException - If the InputSource is null.
SAXException - If the underlying parser throws a SAXException while parsing.
See Also:
DocumentHandler

parse

public void parse(InputSource is,
                  DefaultHandler dh)
           throws SAXException,
                  IOException
Parse the content given InputSource as XML using the specified DefaultHandler.

Parameters:
is - The InputSource containing the content to be parsed.
dh - The SAX DefaultHandler to use.
Throws:
IOException - If any IO errors occur.
IllegalArgumentException - If the InputSource is null.
SAXException - If the underlying parser throws a SAXException while parsing.
See Also:
DocumentHandler

getParser

public abstract Parser getParser()
                          throws SAXException
Returns the SAX parser that is encapsultated by the implementation of this class.

Returns:
The SAX parser that is encapsultated by the implementation of this class.
Throws:
SAXException

getXMLReader

public abstract XMLReader getXMLReader()
                                throws SAXException
Returns the XMLReader that is encapsulated by the implementation of this class.

Returns:
The XMLReader that is encapsulated by the implementation of this class.
Throws:
SAXException

isNamespaceAware

public abstract boolean isNamespaceAware()
Indicates whether or not this parser is configured to understand namespaces.

Returns:
true if this parser is configured to understand namespaces; false otherwise.

isValidating

public abstract boolean isValidating()
Indicates whether or not this parser is configured to validate XML documents.

Returns:
true if this parser is configured to validate XML documents; false otherwise.

setProperty

public abstract void setProperty(String name,
                                 Object value)
                          throws SAXNotRecognizedException,
                                 SAXNotSupportedException
Sets the particular property in the underlying implementation of XMLReader. A list of the core features and properties can be found at http://www.megginson.com/SAX/Java/features.html

Parameters:
name - The name of the property to be set.
value - The value of the property to be set.
Throws:
SAXNotRecognizedException - When the underlying XMLReader does not recognize the property name.
SAXNotSupportedException - When the underlying XMLReader recognizes the property name but doesn't support the property.
See Also:
XMLReader.setProperty(java.lang.String, java.lang.Object)

getProperty

public abstract Object getProperty(String name)
                            throws SAXNotRecognizedException,
                                   SAXNotSupportedException
Returns the particular property requested for in the underlying implementation of XMLReader.

Parameters:
name - The name of the property to be retrieved.
Returns:
Value of the requested property.
Throws:
SAXNotRecognizedException - When the underlying XMLReader does not recognize the property name.
SAXNotSupportedException - When the underlying XMLReader recognizes the property name but doesn't support the property.
See Also:
XMLReader.getProperty(java.lang.String)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


SAXParserFactory (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.xml.parsers
Class SAXParserFactory

java.lang.Object
    extended by javax.xml.parsers.SAXParserFactory
public abstract class SAXParserFactory
extends Object

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

An implementation of the SAXParserFactory class is NOT guaranteed to be thread safe. It is up to the user application to make sure about the use of the SAXParserFactory from more than one thread. Alternatively the application can have one instance of the SAXParserFactory per thread. An application can use the same instance of the factory to obtain one or more instances of the SAXParser provided the instance of the factory isn't being used in more than one thread at a time.

The static newInstance method returns a new concrete implementation of this class.

Since:
JAXP 1.0

Constructor Summary
protected SAXParserFactory()
Method Summary
abstract boolean | getFeature(String name) Returns the particular property requested for in the underlying implementation of org.xml.sax.XMLReader.
boolean | isNamespaceAware() Indicates whether or not the factory is configured to produce parsers which are namespace aware.
boolean | isValidating() Indicates whether or not the factory is configured to produce parsers which validate the XML content during parse.
static SAXParserFactory | newInstance() Obtain a new instance of a SAXParserFactory.
abstract SAXParser | newSAXParser() Creates a new instance of a SAXParser using the currently configured factory parameters.
abstract void | setFeature(String name, boolean value) Sets the particular feature in the underlying implementation of org.xml.sax.XMLReader.
void | setNamespaceAware(boolean awareness) Specifies that the parser produced by this code will provide support for XML namespaces.
void | setValidating(boolean validating) Specifies that the parser produced by this code will validate documents as they are parsed.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

SAXParserFactory

protected SAXParserFactory()
Method Detail

newInstance

public static SAXParserFactory newInstance()
                                    throws FactoryConfigurationError
Obtain a new instance of a SAXParserFactory. This static method creates a new factory instance This method uses the following ordered lookup procedure to determine the SAXParserFactory implementation class to load:
  • Use the javax.xml.parsers.SAXParserFactory system property.
  • Use the properties file "lib/jaxp.properties" in the JRE directory. This configuration file is in standard java.util.Properties format and contains the fully qualified name of the implementation class with the key being the system property defined above.
  • Use the Services API (as detailed in the JAR specification), if available, to determine the classname. The Services API will look for a classname in the file META-INF/services/javax.xml.parsers.SAXParserFactory in jars available to the runtime.
  • Platform default SAXParserFactory instance.
Once an application has obtained a reference to a SAXParserFactory it can use the factory to configure and obtain parser instances.

Returns:
A new instance of a SAXParserFactory.
Throws:
FactoryConfigurationError - if the implementation is not available or cannot be instantiated.

newSAXParser

public abstract SAXParser newSAXParser()
                                throws ParserConfigurationException,
                                       SAXException
Creates a new instance of a SAXParser using the currently configured factory parameters.

Returns:
A new instance of a SAXParser.
Throws:
ParserConfigurationException - if a parser cannot be created which satisfies the requested configuration.
SAXException

setNamespaceAware

public void setNamespaceAware(boolean awareness)
Specifies that the parser produced by this code will provide support for XML namespaces. By default the value of this is set to false.

Parameters:
awareness - true if the parser produced by this code will provide support for XML namespaces; false otherwise.

setValidating

public void setValidating(boolean validating)
Specifies that the parser produced by this code will validate documents as they are parsed. By default the value of this is set to false.

Parameters:
validating - true if the parser produced by this code will validate documents as they are parsed; false otherwise.

isNamespaceAware

public boolean isNamespaceAware()
Indicates whether or not the factory is configured to produce parsers which are namespace aware.

Returns:
true if the factory is configured to produce parsers which are namespace aware; false otherwise.

isValidating

public boolean isValidating()
Indicates whether or not the factory is configured to produce parsers which validate the XML content during parse.

Returns:
true if the factory is configured to produce parsers which validate the XML content during parse; false otherwise.

setFeature

public abstract void setFeature(String name,
                                boolean value)
                         throws ParserConfigurationException,
                                SAXNotRecognizedException,
                                SAXNotSupportedException
Sets the particular feature in the underlying implementation of org.xml.sax.XMLReader. A list of the core features and properties can be found at http://www.megginson.com/SAX/Java/features.html

Parameters:
name - The name of the feature to be set.
value - The value of the feature to be set.
Throws:
SAXNotRecognizedException - When the underlying XMLReader does not recognize the property name.
SAXNotSupportedException - When the underlying XMLReader recognizes the property name but doesn't support the property.
ParserConfigurationException
See Also:
XMLReader.setFeature(java.lang.String, boolean)

getFeature

public abstract boolean getFeature(String name)
                            throws ParserConfigurationException,
                                   SAXNotRecognizedException,
                                   SAXNotSupportedException
Returns the particular property requested for in the underlying implementation of org.xml.sax.XMLReader.

Parameters:
name - The name of the property to be retrieved.
Returns:
Value of the requested property.
Throws:
SAXNotRecognizedException - When the underlying XMLReader does not recognize the property name.
SAXNotSupportedException - When the underlying XMLReader recognizes the property name but doesn't support the property.
ParserConfigurationException
See Also:
XMLReader.getProperty(java.lang.String)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Uses of Class javax.xml.parsers.DocumentBuilder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.xml.parsers.DocumentBuilder

Packages that use DocumentBuilder
javax.xml.parsers Provides classes allowing the processing of XML documents.

Uses of DocumentBuilder in javax.xml.parsers

Methods in javax.xml.parsers that return DocumentBuilder
abstract  DocumentBuilder DocumentBuilderFactory.newDocumentBuilder()
Creates a new instance of a DocumentBuilder using the currently configured parameters.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.xml.parsers.DocumentBuilderFactory (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.xml.parsers.DocumentBuilderFactory

Packages that use DocumentBuilderFactory
javax.xml.parsers Provides classes allowing the processing of XML documents.

Uses of DocumentBuilderFactory in javax.xml.parsers

Methods in javax.xml.parsers that return DocumentBuilderFactory
static DocumentBuilderFactory DocumentBuilderFactory.newInstance()
Obtain a new instance of a DocumentBuilderFactory.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.xml.parsers.FactoryConfigurationError (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.xml.parsers.FactoryConfigurationError

Packages that use FactoryConfigurationError
javax.xml.parsers Provides classes allowing the processing of XML documents.

Uses of FactoryConfigurationError in javax.xml.parsers

Methods in javax.xml.parsers that throw FactoryConfigurationError
static SAXParserFactory | SAXParserFactory.newInstance() Obtain a new instance of a SAXParserFactory.
static DocumentBuilderFactory | DocumentBuilderFactory.newInstance() Obtain a new instance of a DocumentBuilderFactory.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.xml.parsers.ParserConfigurationException (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.xml.parsers.ParserConfigurationException

Packages that use ParserConfigurationException
javax.xml.parsers Provides classes allowing the processing of XML documents.

Uses of ParserConfigurationException in javax.xml.parsers

Methods in javax.xml.parsers that throw ParserConfigurationException
abstract SAXParser | SAXParserFactory.newSAXParser() Creates a new instance of a SAXParser using the currently configured factory parameters.
abstract void | SAXParserFactory.setFeature(String name, boolean value) Sets the particular feature in the underlying implementation of org.xml.sax.XMLReader.
abstract boolean | SAXParserFactory.getFeature(String name) Returns the particular property requested for in the underlying implementation of org.xml.sax.XMLReader.
abstract DocumentBuilder | DocumentBuilderFactory.newDocumentBuilder() Creates a new instance of a DocumentBuilder using the currently configured parameters.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.xml.parsers.SAXParser (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.xml.parsers.SAXParser

Packages that use SAXParser
javax.xml.parsers Provides classes allowing the processing of XML documents.

Uses of SAXParser in javax.xml.parsers

Methods in javax.xml.parsers that return SAXParser
abstract  SAXParser SAXParserFactory.newSAXParser()
Creates a new instance of a SAXParser using the currently configured factory parameters.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.xml.parsers.SAXParserFactory (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.xml.parsers.SAXParserFactory

Packages that use SAXParserFactory
javax.xml.parsers Provides classes allowing the processing of XML documents.

Uses of SAXParserFactory in javax.xml.parsers

Methods in javax.xml.parsers that return SAXParserFactory
static SAXParserFactory SAXParserFactory.newInstance()
Obtain a new instance of a SAXParserFactory.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


ErrorListener (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.xml.transform
Interface ErrorListener

public interface ErrorListener

To provide customized error handling, implement this interface and use the setErrorListener method to register an instance of the implmentation with the Transformer. The Transformer then reports all errors and warnings through this interface.

If an application does not register an ErrorListener, errors are reported to System.err.

For transformation errors, a Transformer must use this interface instead of throwing an exception: it is up to the application to decide whether to throw an exception for different types of errors and warnings. Note however that the Transformer is not required to continue with the transformation after a call to fatalError.

Transformers may use this mechanism to report XML parsing errors as well as transformation errors.

Method Summary
void | error(TransformerException exception) Receive notification of a recoverable error.
void | fatalError(TransformerException exception) Receive notification of a non-recoverable error.
void | warning(TransformerException exception) Receive notification of a warning.

Method Detail

warning

public void warning(TransformerException exception)
             throws TransformerException
Receive notification of a warning.

Transformer can use this method to report conditions that are not errors or fatal errors. The default behaviour is to take no action.

After invoking this method, the Transformer must continue with the transformation. It should still be possible for the application to process the document through to the end.

Parameters:
exception - The warning information encapsulated in a transformer exception.
Throws:
TransformerException - if the application chooses to discontinue the transformation.
See Also:
TransformerException

error

public void error(TransformerException exception)
           throws TransformerException
Receive notification of a recoverable error.

The transformer must continue to try and provide normal transformation after invoking this method. It should still be possible for the application to process the document through to the end if no other errors are encountered.

Parameters:
exception - The error information encapsulated in a transformer exception.
Throws:
TransformerException - if the application chooses to discontinue the transformation.
See Also:
TransformerException

fatalError

public void fatalError(TransformerException exception)
                throws TransformerException
Receive notification of a non-recoverable error.

The transformer must continue to try and provide normal transformation after invoking this method. It should still be possible for the application to process the document through to the end if no other errors are encountered, but there is no guarantee that the output will be useable.

Parameters:
exception - The error information encapsulated in a transformer exception.
Throws:
TransformerException - if the application chooses to discontinue the transformation.
See Also:
TransformerException
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


OutputKeys (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.xml.transform
Class OutputKeys

java.lang.Object
    extended by javax.xml.transform.OutputKeys
public class OutputKeys
extends Object

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.

A properties in this class are read-only.

See Also:
section 16 of the XSL Transformations (XSLT) W3C Recommendation

Field Summary
static String | CDATA_SECTION_ELEMENTS cdata-section-elements = expanded names.
static String | DOCTYPE_PUBLIC doctype-public = string.
static String | DOCTYPE_SYSTEM doctype-system = string.
static String | ENCODING encoding = string.
static String | INDENT indent = "yes" | "no".
static String | MEDIA_TYPE media-type = string.
static String | METHOD method = "xml" | "html" | "text" | expanded name.
static String | OMIT_XML_DECLARATION omit-xml-declaration = "yes" | "no".
static String | STANDALONE standalone = "yes" | "no".
static String | VERSION version = nmtoken.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

METHOD

public static final String METHOD
method = "xml" | "html" | "text" | expanded name.

The method attribute identifies the overall method that should be used for outputting the result tree. Other non-namespaced values may be used, such as "xhtml", but, if accepted, the handling of such values is implementation defined. If any of the method values are not accepted and are not namespace qualified, then Transformer.setOutputProperty(java.lang.String, java.lang.String) or Transformer.setOutputProperties(java.util.Properties) will throw a IllegalArgumentException.

See Also:
section 16 of the XSL Transformations (XSLT) W3C Recommendation, Constant Field Values

VERSION

public static final String VERSION
version = nmtoken.

version specifies the version of the output method.

When the output method is "xml", the version value specifies the version of XML to be used for outputting the result tree. The default value for the xml output method is 1.0. When the output method is "html", the version value indicates the version of the HTML. The default value for the xml output method is 4.0, which specifies that the result should be output as HTML conforming to the HTML 4.0 Recommendation [HTML]. If the output method is "text", the version property is ignored.

See Also:
section 16 of the XSL Transformations (XSLT) W3C Recommendation, Constant Field Values

ENCODING

public static final String ENCODING
encoding = string.

encoding specifies the preferred character encoding that the Transformer should use to encode sequences of characters as sequences of bytes. The value of the attribute should be treated case-insensitively. The value must only contain characters in the range #x21 to #x7E (i.e., printable ASCII characters). The value should either be a charset registered with the Internet Assigned Numbers Authority [IANA], [RFC2278] or start with X-.

See Also:
section 16 of the XSL Transformations (XSLT) W3C Recommendation, Constant Field Values

OMIT_XML_DECLARATION

public static final String OMIT_XML_DECLARATION
omit-xml-declaration = "yes" | "no".

omit-xml-declaration specifies whether the XSLT processor should output an XML declaration; the value must be yes or no.

See Also:
section 16 of the XSL Transformations (XSLT) W3C Recommendation, Constant Field Values

STANDALONE

public static final String STANDALONE
standalone = "yes" | "no".

standalone specifies whether the Transformer should output a standalone document declaration; the value must be yes or no.

See Also:
section 16 of the XSL Transformations (XSLT) W3C Recommendation, Constant Field Values

DOCTYPE_PUBLIC

public static final String DOCTYPE_PUBLIC
doctype-public = string.

See the documentation for the DOCTYPE_SYSTEM property for a description of what the value of the key should be.

See Also:
section 16 of the XSL Transformations (XSLT) W3C Recommendation, Constant Field Values

DOCTYPE_SYSTEM

public static final String DOCTYPE_SYSTEM
doctype-system = string.

doctype-public specifies the public identifier to be used in the document type declaration.

If the doctype-system property is specified, the xml output method should output a document type declaration immediately before the first element. The name following <!DOCTYPE should be the name of the first element. If doctype-public property is also specified, then the xml output method should output PUBLIC followed by the public identifier and then the system identifier; otherwise, it should output SYSTEM followed by the system identifier. The internal subset should be empty. The doctype-public attribute should be ignored unless the doctype-system attribute is specified.

If the doctype-public or doctype-system attributes are specified, then the html output method should output a document type declaration immediately before the first element. The name following <!DOCTYPE should be HTML or html. If the doctype-public attribute is specified, then the output method should output PUBLIC followed by the specified public identifier; if the doctype-system attribute is also specified, it should also output the specified system identifier following the public identifier. If the doctype-system attribute is specified but the doctype-public attribute is not specified, then the output method should output SYSTEM followed by the specified system identifier.

doctype-system specifies the system identifier to be used in the document type declaration.

See Also:
section 16 of the XSL Transformations (XSLT) W3C Recommendation, Constant Field Values

CDATA_SECTION_ELEMENTS

public static final String CDATA_SECTION_ELEMENTS
cdata-section-elements = expanded names.

cdata-section-elements specifies a whitespace delimited list of the names of elements whose text node children should be output using CDATA sections.

See Also:
section 16 of the XSL Transformations (XSLT) W3C Recommendation., Constant Field Values

INDENT

public static final String INDENT
indent = "yes" | "no".

indent specifies whether the Transformer may add additional whitespace when outputting the result tree; the value must be yes or no.

See Also:
section 16 of the XSL Transformations (XSLT) W3C Recommendation, Constant Field Values

MEDIA_TYPE

public static final String MEDIA_TYPE
media-type = string.

media-type specifies the media type (MIME content type) of the data that results from outputting the result tree. The charset parameter should not be specified explicitly; instead, when the top-level media type is text, a charset parameter should be added according to the character encoding actually used by the output method.

See Also:
section 16 of the XSL Transformations (XSLT) W3C Recommendation, Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


javax.xml.transform (Java 2 Platform SE v1.4.2)

 javax.xml.transform
Interfaces
ErrorListener
Result
Source
SourceLocator
Templates
URIResolver
Classes
OutputKeys
Transformer
TransformerFactory
Exceptions
TransformerConfigurationException
TransformerException
Errors
TransformerFactoryConfigurationError


javax.xml.transform (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package javax.xml.transform

This package defines the generic APIs for processing transformation instructions, and performing a transformation from source to result.

See:
Description

Interface Summary
ErrorListener | To provide customized error handling, implement this interface and use the setErrorListener method to register an instance of the implmentation with the Transformer.
Result | An object that implements this interface contains the information needed to build a transformation result tree.
Source | An object that implements this interface contains the information needed to act as source input (XML source or transformation instructions).
SourceLocator | This interface is primarily for the purposes of reporting where an error occurred in the XML source or transformation instructions.
Templates | An object that implements this interface is the runtime representation of processed transformation instructions.
URIResolver | 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.

Class Summary
OutputKeys | 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.
Transformer | An instance of this abstract class can transform a source tree into a result tree.
TransformerFactory | A TransformerFactory instance can be used to create Transformer and Templates objects.

Exception Summary
TransformerConfigurationException | Indicates a serious configuration error.
TransformerException | This class specifies an exceptional condition that occured during the transformation process.

Error Summary
TransformerFactoryConfigurationError Thrown when a problem with configuration with the Transformer Factories exists.

Package javax.xml.transform Description

This package defines the generic APIs for processing transformation instructions, and performing a transformation from source to result. These interfaces have no dependencies on SAX or the DOM standard, and try to make as few assumptions as possible about the details of the source and result of a transformation. It achieves this by defining Source and Result interfaces.

To define concrete classes for the user, the API defines specializations of the interfaces found at the root level. These interfaces are found in javax.xml.transform.sax, javax.xml.transform.dom, and javax.xml.transform.stream.

Creating Objects

The API allows a concrete TransformerFactory object to be created from the static function TransformerFactory.newInstance().

Specification of Inputs and Outputs

This API defines two interface objects called Source and Result. In order to pass Source and Result objects to the interfaces, concrete classes must be used. Three concrete representations are defined for each of these objects: StreamSource and StreamResult, SAXSource and SAXResult, and DOMSource and DOMResult. Each of these objects defines a FEATURE string (which is i the form of a URL), which can be passed into TransformerFactory.getFeature(java.lang.String) to see if the given type of Source or Result object is supported. For instance, to test if a DOMSource and a StreamResult is supported, you can apply the following test.

    TransformerFactory tfactory = TransformerFactory.newInstance();

    if (tfactory.getFeature(DOMSource.FEATURE) && tfactory.getFeature(StreamResult.FEATURE))
    {
       ...
    }

Qualified Name Representation

Namespaces present something of a problem area when dealing with XML objects. Qualified Names appear in XML markup as prefixed names. But the prefixes themselves do not hold identity. Rather, it is the URIs that they contextually map to that hold the identity. Therefore, when passing a Qualified Name like "xyz:foo" among Java programs, one must provide a means to map "xyz" to a namespace.

One solution has been to create a "QName" object that holds the namespace URI, as well as the prefix and local name, but this is not always an optimal solution, as when, for example, you want to use unique strings as keys in a dictionary object. Not having a string representation also makes it difficult to specify a namespaced identity outside the context of an XML document.

In order to pass namespaced values to transformations, for instance as a set of properties to the Serializer, this specification defines that a String "qname" object parameter be passed as two-part string, the namespace URI enclosed in curly braces ({}), followed by the local name. If the qname has a null URI, then the String object only contains the local name. An application can safely check for a non-null URI by testing to see if the first character of the name is a '{' character.

For example, if a URI and local name were obtained from an element defined with <xyz:foo xmlns:xyz="http://xyz.foo.com/yada/baz.html"/>, then the Qualified Name would be "{http://xyz.foo.com/yada/baz.html}foo". Note that the prefix is lost.

Result Tree Serialization

Serialization of the result tree to a stream can be controlled with the Transformer.setOutputProperties(java.util.Properties) and the Transformer.setOutputProperty(java.lang.String, java.lang.String) methods. Strings that match the XSLT specification for xsl:output attributes can be referenced from the OutputKeys class. Other strings can be specified as well. If the transformer does not recognize an output key, a IllegalArgumentException is thrown, unless the key name is namespace qualified. Output key names that are qualified by a namespace are ignored or passed on to the serializer mechanism.

If all that is desired is the simple identity transformation of a source to a result, then TransformerFactory provides a TransformerFactory.newTransformer() method with no arguments. This method creates a Transformer that effectively copies the source to the result. This method may be used to create a DOM from SAX events or to create an XML or HTML stream from a DOM or SAX events.

Exceptions and Error Reporting

The transformation API throw three types of specialized exceptions. A TransformerFactoryConfigurationError is parallel to the FactoryConfigurationError, and is thrown when a configuration problem with the TransformerFactory exists. This error will typically be thrown when the transformation factory class specified with the "javax.xml.transform.TransformerFactory" system property cannot be found or instantiated.

A TransformerConfigurationException may be thrown if for any reason a Transformer can not be created. A TransformerConfigurationException may be thrown if there is a syntax error in the transformation instructions, for example when TransformerFactory.newTransformer(javax.xml.transform.Source) is called.

TransformerException is a general exception that occurs during the course of a transformation. A transformer exception may wrap another exception, and if any of the TransformerException.printStackTrace() methods are called on it, it will produce a list of stack dumps, starting from the most recent. The transformer exception also provides a SourceLocator object which indicates where in the source tree or transformation instructions the error occurred. TransformerException.getMessageAndLocation() may be called to get an error message with location info, and TransformerException.getLocationAsString() may be called to get just the location string.

Transformation warnings and errors are normally first sent to a ErrorListener, at which point the implementor may decide to report the error or warning, and may decide to throw an exception for a non-fatal error. The error listener may be set via TransformerFactory.setErrorListener(javax.xml.transform.ErrorListener) for reporting errors that have to do with syntax errors in the transformation instructions, or via Transformer.setErrorListener(javax.xml.transform.ErrorListener) to report errors that occur during the transformation. The error listener on both objects should always be valid and non-null, whether set by the user or a default implementation provided by the processor.

Resolution of URIs within a transformation

The API provides a way for URIs referenced from within the stylesheet instructions or within the transformation to be resolved by the calling application. This can be done by creating a class that implements the URIResolver interface, with its one method, URIResolver.resolve(java.lang.String, java.lang.String), and use this class to set the URI resolution for the transformation instructions or transformation with TransformerFactory.setURIResolver(javax.xml.transform.URIResolver) or Transformer.setURIResolver(javax.xml.transform.URIResolver). The URIResolver.resolve method takes two String arguments, the URI found in the stylesheet instructions or built as part of the transformation process, and the base URI in effect when the URI passed as the first argument was encountered. The returned Source object must be usable by the transformer, as specified in its implemented features.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


javax.xml.transform Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package javax.xml.transform

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class javax.xml.transform.OutputKeys
    • class java.lang.Throwable (implements java.io.Serializable)
      • class java.lang.Error
        • class javax.xml.transform.TransformerFactoryConfigurationError
      • class java.lang.Exception
        • class javax.xml.transform.TransformerException
          • class javax.xml.transform.TransformerConfigurationException
    • class javax.xml.transform.Transformer
    • class javax.xml.transform.TransformerFactory

Interface Hierarchy

  • interface javax.xml.transform.ErrorListener
  • interface javax.xml.transform.Result
  • interface javax.xml.transform.Source
  • interface javax.xml.transform.SourceLocator
  • interface javax.xml.transform.Templates
  • interface javax.xml.transform.URIResolver
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package javax.xml.transform (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
javax.xml.transform

Packages that use javax.xml.transform
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 | This package implements DOM-specific transformation APIs.
javax.xml.transform.sax | This package implements SAX2-specific transformation APIs.
javax.xml.transform.stream | This package implements stream- and URI- specific transformation APIs.

Classes in javax.xml.transform used by javax.xml.transform
ErrorListener
To provide customized error handling, implement this interface and use the setErrorListener method to register an instance of the implmentation with the Transformer.
Result
An object that implements this interface contains the information needed to build a transformation result tree.
Source
An object that implements this interface contains the information needed to act as source input (XML source or transformation instructions).
SourceLocator
This interface is primarily for the purposes of reporting where an error occurred in the XML source or transformation instructions.
Templates
An object that implements this interface is the runtime representation of processed transformation instructions.
Transformer
An instance of this abstract class can transform a source tree into a result tree.
TransformerConfigurationException
Indicates a serious configuration error.
TransformerException
This class specifies an exceptional condition that occured during the transformation process.
TransformerFactory
A TransformerFactory instance can be used to create Transformer and Templates objects.
TransformerFactoryConfigurationError
Thrown when a problem with configuration with the Transformer Factories exists.
URIResolver
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.

Classes in javax.xml.transform used by javax.xml.transform.dom
Result
An object that implements this interface contains the information needed to build a transformation result tree.
Source
An object that implements this interface contains the information needed to act as source input (XML source or transformation instructions).
SourceLocator
This interface is primarily for the purposes of reporting where an error occurred in the XML source or transformation instructions.

Classes in javax.xml.transform used by javax.xml.transform.sax
Result
An object that implements this interface contains the information needed to build a transformation result tree.
Source
An object that implements this interface contains the information needed to act as source input (XML source or transformation instructions).
Templates
An object that implements this interface is the runtime representation of processed transformation instructions.
Transformer
An instance of this abstract class can transform a source tree into a result tree.
TransformerConfigurationException
Indicates a serious configuration error.
TransformerFactory
A TransformerFactory instance can be used to create Transformer and Templates objects.

Classes in javax.xml.transform used by javax.xml.transform.stream
Result
An object that implements this interface contains the information needed to build a transformation result tree.
Source
An object that implements this interface contains the information needed to act as source input (XML source or transformation instructions).

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Result (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.xml.transform
Interface Result

All Known Implementing Classes:
DOMResult, SAXResult, StreamResult
public interface Result

An object that implements this interface contains the information needed to build a transformation result tree.

Field Summary
static String | PI_DISABLE_OUTPUT_ESCAPING The name of the processing instruction that is sent if the result tree disables output escaping.
static String | PI_ENABLE_OUTPUT_ESCAPING 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.
Method Summary
String | getSystemId() Get the system identifier that was set with setSystemId.
void | setSystemId(String systemId) Set the system identifier for this Result.

Field Detail

PI_DISABLE_OUTPUT_ESCAPING

public static final String PI_DISABLE_OUTPUT_ESCAPING
The name of the processing instruction that is sent if the result tree disables output escaping.

Normally, result tree serialization escapes & and < (and possibly other characters) when outputting text nodes. This ensures that the output is well-formed XML. However, it is sometimes convenient to be able to produce output that is almost, but not quite well-formed XML; for example, the output may include ill-formed sections that will be transformed into well-formed XML by a subsequent non-XML aware process. If a processing instruction is sent with this name, serialization should be output without any escaping.

Result DOM trees may also have PI_DISABLE_OUTPUT_ESCAPING and PI_ENABLE_OUTPUT_ESCAPING inserted into the tree.

See Also:
disable-output-escaping in XSLT Specification, Constant Field Values

PI_ENABLE_OUTPUT_ESCAPING

public static final String PI_ENABLE_OUTPUT_ESCAPING
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.

See Also:
disable-output-escaping in XSLT Specification, Constant Field Values
Method Detail

setSystemId

public void setSystemId(String systemId)
Set the system identifier for this Result.

If the Result is not to be written to a file, the system identifier is optional. The application may still want to provide one, however, for use in error messages and warnings, or to resolve relative output identifiers.

Parameters:
systemId - The system identifier as a URI string.

getSystemId

public String getSystemId()
Get the system identifier that was set with setSystemId.

Returns:
The system identifier that was set with setSystemId, or null if setSystemId was not called.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Source (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.xml.transform
Interface Source

All Known Implementing Classes:
DOMSource, SAXSource, StreamSource
public interface Source

An object that implements this interface contains the information needed to act as source input (XML source or transformation instructions).

Method Summary
String | getSystemId() Get the system identifier that was set with setSystemId.
void | setSystemId(String systemId) Set the system identifier for this Source.

Method Detail

setSystemId

public void setSystemId(String systemId)
Set the system identifier for this Source.

The system identifier is optional if the source does not get its data from a URL, but it may still be useful to provide one. The application can use a system identifier, for example, to resolve relative URIs and to include in error messages and warnings.

Parameters:
systemId - The system identifier as a URL string.

getSystemId

public String getSystemId()
Get the system identifier that was set with setSystemId.

Returns:
The system identifier that was set with setSystemId, or null if setSystemId was not called.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


SourceLocator (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.xml.transform
Interface SourceLocator

All Known Subinterfaces:
DOMLocator
public interface SourceLocator

This interface is primarily for the purposes of reporting where an error occurred in the XML source or transformation instructions.

Method Summary
int | getColumnNumber() Return the character position where the current document event ends.
int | getLineNumber() Return the line number where the current document event ends.
String | getPublicId() Return the public identifier for the current document event.
String | getSystemId() Return the system identifier for the current document event.

Method Detail

getPublicId

public String getPublicId()
Return the public identifier for the current document event.

The return value is the public identifier of the document entity or of the external parsed entity in which the markup that triggered the event appears.

Returns:
A string containing the public identifier, or null if none is available.
See Also:
getSystemId()

getSystemId

public String getSystemId()
Return the system identifier for the current document event.

The return value is the system identifier of the document entity or of the external parsed entity in which the markup that triggered the event appears.

If the system identifier is a URL, the parser must resolve it fully before passing it to the application.

Returns:
A string containing the system identifier, or null if none is available.
See Also:
getPublicId()

getLineNumber

public int getLineNumber()
Return the line number where the current document event ends.

Warning: The return value from the method is intended only as an approximation for the sake of error reporting; it is not intended to provide sufficient information to edit the character content of the original XML document.

The return value is an approximation of the line number in the document entity or external parsed entity where the markup that triggered the event appears.

Returns:
The line number, or -1 if none is available.
See Also:
getColumnNumber()

getColumnNumber

public int getColumnNumber()
Return the character position where the current document event ends.

Warning: The return value from the method is intended only as an approximation for the sake of error reporting; it is not intended to provide sufficient information to edit the character content of the original XML document.

The return value is an approximation of the column number in the document entity or external parsed entity where the markup that triggered the event appears.

Returns:
The column number, or -1 if none is available.
See Also:
getLineNumber()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Templates (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.xml.transform
Interface Templates

public interface Templates

An object that implements this interface is the runtime representation of processed transformation instructions.

Templates must be threadsafe for a given instance over multiple threads running concurrently, and may be used multiple times in a given session.

Method Summary
Properties | getOutputProperties() Get the static properties for xsl:output.
Transformer | newTransformer() Create a new transformation context for this Templates object.

Method Detail

newTransformer

public Transformer newTransformer()
                           throws TransformerConfigurationException
Create a new transformation context for this Templates object.

Returns:
A valid non-null instance of a Transformer.
Throws:
TransformerConfigurationException - if a Transformer can not be created.

getOutputProperties

public Properties getOutputProperties()
Get the static properties for xsl:output. The object returned will be a clone of the internal values. Accordingly, it can be mutated without mutating the Templates object, and then handed in to Transformer.setOutputProperties(java.util.Properties).

The properties returned should contain properties set by the stylesheet, and these properties are "defaulted" by default properties specified by section 16 of the XSL Transformations (XSLT) W3C Recommendation. The properties that were specifically set by the stylesheet should be in the base Properties list, while the XSLT default properties that were not specifically set should be in the "default" Properties list. Thus, getOutputProperties().getProperty(String key) will obtain any property in that was set by the stylesheet, or the default properties, while getOutputProperties().get(String key) will only retrieve properties that were explicitly set in the stylesheet.

For XSLT, Attribute Value Templates attribute values will be returned unexpanded (since there is no context at this point). The namespace prefixes inside Attribute Value Templates will be unexpanded, so that they remain valid XPath values. (For XSLT 1.0, this is not a problem since Attribute Value Templates are not allowed for xsl:output attributes. However, the will be allowed in versions after 1.1.)

Returns:
A Properties object, never null.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Transformer (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.xml.transform
Class Transformer

java.lang.Object
    extended by javax.xml.transform.Transformer
public abstract class Transformer
extends Object

An instance of this abstract class can transform a source tree into a result tree.

An instance of this class can be obtained with the TransformerFactory.newTransformer method. This instance may then be used to process XML from a variety of sources and write the transformation output to a variety of sinks.

An object of this class may not be used in multiple threads running concurrently. Different Transformers may be used concurrently by different threads.

A Transformer may be used multiple times. Parameters and output properties are preserved across transformations.

Constructor Summary
protected Transformer()
Default constructor is protected on purpose.
Method Summary
abstract  void clearParameters()
Clear all parameters set with setParameter.
abstract  ErrorListener getErrorListener()
Get the error event handler in effect for the transformation.
abstract  Properties getOutputProperties()
Get a copy of the output properties for the transformation.
abstract  String getOutputProperty(String name)
Get an output property that is in effect for the transformation.
abstract  Object getParameter(String name)
Get a parameter that was explicitly set with setParameter or setParameters.
abstract  URIResolver getURIResolver()
Get an object that will be used to resolve URIs used in document(), etc.
abstract  void setErrorListener(ErrorListener listener)
Set the error event listener in effect for the transformation.
abstract  void setOutputProperties(Properties oformat)
Set the output properties for the transformation.
abstract  void setOutputProperty(String name, String value)
Set an output property that will be in effect for the transformation.
abstract  void setParameter(String name, Object value)
Add a parameter for the transformation.
abstract  void setURIResolver(URIResolver resolver)
Set an object that will be used to resolve URIs used in document().
abstract  void transform(Source xmlSource, Result outputTarget)
Process the source tree to the output result.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

Transformer

protected Transformer()
Default constructor is protected on purpose.

Method Detail

transform

public abstract void transform(Source xmlSource,
                               Result outputTarget)
                        throws TransformerException
Process the source tree to the output result.

Parameters:
xmlSource - The input for the source tree.
outputTarget - The output target.
Throws:
TransformerException - If an unrecoverable error occurs during the course of the transformation.

setParameter

public abstract void setParameter(String name,
                                  Object value)
Add a parameter for the transformation.

Pass a qualified name as a two-part string, the namespace URI enclosed in curly braces ({}), followed by the local name. If the name has a null URL, the String only contain the local name. An application can safely check for a non-null URI by testing to see if the first character of the name is a '{' character.

For example, if a URI and local name were obtained from an element defined with <xyz:foo xmlns:xyz="http://xyz.foo.com/yada/baz.html"/>, then the qualified name would be "{http://xyz.foo.com/yada/baz.html}foo". Note that no prefix is used.

Parameters:
name - The name of the parameter, which may begin with a namespace URI in curly braces ({}).
value - The value object. This can be any valid Java object. It is up to the processor to provide the proper object coersion or to simply pass the object on for use in an extension.

getParameter

public abstract Object getParameter(String name)
Get a parameter that was explicitly set with setParameter or setParameters.

This method does not return a default parameter value, which cannot be determined until the node context is evaluated during the transformation process.

Returns:
A parameter that has been set with setParameter.

clearParameters

public abstract void clearParameters()
Clear all parameters set with setParameter.

setURIResolver

public abstract void setURIResolver(URIResolver resolver)
Set an object that will be used to resolve URIs used in document().

If the resolver argument is null, the URIResolver value will be cleared, and the default behavior will be used.

Parameters:
resolver - An object that implements the URIResolver interface, or null.

getURIResolver

public abstract URIResolver getURIResolver()
Get an object that will be used to resolve URIs used in document(), etc.

Returns:
An object that implements the URIResolver interface, or null.

setOutputProperties

public abstract void setOutputProperties(Properties oformat)
                                  throws IllegalArgumentException
Set the output properties for the transformation. These properties will override properties set in the Templates with xsl:output.

If argument to this function is null, any properties previously set are removed, and the value will revert to the value defined in the templates object.

Pass a qualified property key name as a two-part string, the namespace URI enclosed in curly braces ({}), followed by the local name. If the name has a null URL, the String only contain the local name. An application can safely check for a non-null URI by testing to see if the first character of the name is a '{' character.

For example, if a URI and local name were obtained from an element defined with <xyz:foo xmlns:xyz="http://xyz.foo.com/yada/baz.html"/>, then the qualified name would be "{http://xyz.foo.com/yada/baz.html}foo". Note that no prefix is used.

Parameters:
oformat - A set of output properties that will be used to override any of the same properties in affect for the transformation.
Throws:
IllegalArgumentException - if any of the argument keys are not recognized and are not namespace qualified.
See Also:
OutputKeys, Properties

getOutputProperties

public abstract Properties getOutputProperties()
Get a copy of the output properties for the transformation.

The properties returned should contain properties set by the user, and properties set by the stylesheet, and these properties are "defaulted" by default properties specified by section 16 of the XSL Transformations (XSLT) W3C Recommendation. The properties that were specifically set by the user or the stylesheet should be in the base Properties list, while the XSLT default properties that were not specifically set should be the default Properties list. Thus, getOutputProperties().getProperty(String key) will obtain any property in that was set by setOutputProperty(java.lang.String, java.lang.String), setOutputProperties(java.util.Properties), in the stylesheet, or the default properties, while getOutputProperties().get(String key) will only retrieve properties that were explicitly set by setOutputProperty(java.lang.String, java.lang.String), setOutputProperties(java.util.Properties), or in the stylesheet.

Note that mutation of the Properties object returned will not effect the properties that the transformation contains.

If any of the argument keys are not recognized and are not namespace qualified, the property will be ignored. In other words the behaviour is not orthogonal with setOutputProperties.

See Also:
OutputKeys, Properties

setOutputProperty

public abstract void setOutputProperty(String name,
                                       String value)
                                throws IllegalArgumentException
Set an output property that will be in effect for the transformation.

Pass a qualified property name as a two-part string, the namespace URI enclosed in curly braces ({}), followed by the local name. If the name has a null URL, the String only contain the local name. An application can safely check for a non-null URI by testing to see if the first character of the name is a '{' character.

For example, if a URI and local name were obtained from an element defined with <xyz:foo xmlns:xyz="http://xyz.foo.com/yada/baz.html"/>, then the qualified name would be "{http://xyz.foo.com/yada/baz.html}foo". Note that no prefix is used.

The Properties object that was passed to setOutputProperties(java.util.Properties) won't be effected by calling this method.

Parameters:
name - A non-null String that specifies an output property name, which may be namespace qualified.
value - The non-null string value of the output property.
Throws:
IllegalArgumentException - If the property is not supported, and is not qualified with a namespace.
See Also:
OutputKeys

getOutputProperty

public abstract String getOutputProperty(String name)
                                  throws IllegalArgumentException
Get an output property that is in effect for the transformation. The property specified may be a property that was set with setOutputProperty, or it may be a property specified in the stylesheet.

Parameters:
name - A non-null String that specifies an output property name, which may be namespace qualified.
Returns:
The string value of the output property, or null if no property was found.
Throws:
IllegalArgumentException - If the property is not supported.
See Also:
OutputKeys

setErrorListener

public abstract void setErrorListener(ErrorListener listener)
                               throws IllegalArgumentException
Set the error event listener in effect for the transformation.

Parameters:
listener - The new error listener.
Throws:
IllegalArgumentException - if listener is null.

getErrorListener

public abstract ErrorListener getErrorListener()
Get the error event handler in effect for the transformation.

Returns:
The current error handler, which should never be null.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TransformerConfigurationException (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.xml.transform
Class TransformerConfigurationException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by javax.xml.transform.TransformerException
                extended by javax.xml.transform.TransformerConfigurationException
All Implemented Interfaces:
Serializable
public class TransformerConfigurationException
extends TransformerException

Indicates a serious configuration error.

See Also:
Serialized Form

Constructor Summary
TransformerConfigurationException()
Create a new TransformerConfigurationException with no detail mesage.
TransformerConfigurationException(String msg)
Create a new TransformerConfigurationException with the String specified as an error message.
TransformerConfigurationException(String message, SourceLocator locator)
Create a new TransformerConfigurationException from a message and a Locator.
TransformerConfigurationException(String message, SourceLocator locator, Throwable e)
Wrap an existing exception in a TransformerConfigurationException.
TransformerConfigurationException(String msg, Throwable e)
Create a new TransformerConfigurationException with the given Exception base cause and detail message.
TransformerConfigurationException(Throwable e)
Create a new TransformerConfigurationException with a given Exception base cause of the error.
Methods inherited from class javax.xml.transform.TransformerException
getCause, getException, getLocationAsString, getLocator, getMessageAndLocation, initCause, printStackTrace, printStackTrace, printStackTrace, setLocator
Methods inherited from class java.lang.Throwable
fillInStackTrace, getLocalizedMessage, getMessage, getStackTrace, setStackTrace, toString
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

TransformerConfigurationException

public TransformerConfigurationException()
Create a new TransformerConfigurationException with no detail mesage.

TransformerConfigurationException

public TransformerConfigurationException(String msg)
Create a new TransformerConfigurationException with the String specified as an error message.

Parameters:
msg - The error message for the exception.

TransformerConfigurationException

public TransformerConfigurationException(Throwable e)
Create a new TransformerConfigurationException with a given Exception base cause of the error.

Parameters:
e - The exception to be encapsulated in a TransformerConfigurationException.

TransformerConfigurationException

public TransformerConfigurationException(String msg,
                                         Throwable e)
Create a new TransformerConfigurationException with the given Exception base cause and detail message.

Parameters:
e - The exception to be encapsulated in a TransformerConfigurationException
msg - The detail message.

TransformerConfigurationException

public TransformerConfigurationException(String message,
                                         SourceLocator locator)
Create a new TransformerConfigurationException from a message and a Locator.

This constructor is especially useful when an application is creating its own exception from within a DocumentHandler callback.

Parameters:
message - The error or warning message.
locator - The locator object for the error or warning.

TransformerConfigurationException

public TransformerConfigurationException(String message,
                                         SourceLocator locator,
                                         Throwable e)
Wrap an existing exception in a TransformerConfigurationException.

Parameters:
message - The error or warning message, or null to use the message from the embedded exception.
locator - The locator object for the error or warning.
e - Any exception.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


TransformerException (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.xml.transform
Class TransformerException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by javax.xml.transform.TransformerException
All Implemented Interfaces:
Serializable
Direct Known Subclasses:
TransformerConfigurationException
public class TransformerException
extends Exception

This class specifies an exceptional condition that occured during the transformation process.

See Also:
Serialized Form

Constructor Summary
TransformerException(String message)
Create a new TransformerException.
TransformerException(String message, SourceLocator locator)
Create a new TransformerException from a message and a Locator.
TransformerException(String message, SourceLocator locator, Throwable e)
Wrap an existing exception in a TransformerException.
TransformerException(String message, Throwable e)
Wrap an existing exception in a TransformerException.
TransformerException(Throwable e)
Create a new TransformerException wrapping an existing exception.
Method Summary
Throwable | getCause() Returns the cause of this throwable or null if the cause is nonexistent or unknown.
Throwable | getException() This method retrieves an exception that this exception wraps.
String | getLocationAsString() Get the location information as a string.
SourceLocator | getLocator() Method getLocator retrieves an instance of a SourceLocator object that specifies where an error occured.
String | getMessageAndLocation() Get the error message with location information appended.
Throwable | initCause(Throwable cause) Initializes the cause of this throwable to the specified value.
void | printStackTrace() Print the the trace of methods from where the error originated.
void | printStackTrace(PrintStream s) Print the the trace of methods from where the error originated.
void | printStackTrace(PrintWriter s) Print the the trace of methods from where the error originated.
void | setLocator(SourceLocator location) Method setLocator sets an instance of a SourceLocator object that specifies where an error occured.
Methods inherited from class java.lang.Throwable
fillInStackTrace, getLocalizedMessage, getMessage, getStackTrace, setStackTrace, toString
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

TransformerException

public TransformerException(String message)
Create a new TransformerException.

Parameters:
message - The error or warning message.

TransformerException

public TransformerException(Throwable e)
Create a new TransformerException wrapping an existing exception.

Parameters:
e - The exception to be wrapped.

TransformerException

public TransformerException(String message,
                            Throwable e)
Wrap an existing exception in a TransformerException.

This is used for throwing processor exceptions before the processing has started.

Parameters:
message - The error or warning message, or null to use the message from the embedded exception.
e - Any exception

TransformerException

public TransformerException(String message,
                            SourceLocator locator)
Create a new TransformerException from a message and a Locator.

This constructor is especially useful when an application is creating its own exception from within a DocumentHandler callback.

Parameters:
message - The error or warning message.
locator - The locator object for the error or warning.

TransformerException

public TransformerException(String message,
                            SourceLocator locator,
                            Throwable e)
Wrap an existing exception in a TransformerException.

Parameters:
message - The error or warning message, or null to use the message from the embedded exception.
locator - The locator object for the error or warning.
e - Any exception
Method Detail

getLocator

public SourceLocator getLocator()
Method getLocator retrieves an instance of a SourceLocator object that specifies where an error occured.

Returns:
A SourceLocator object, or null if none was specified.

setLocator

public void setLocator(SourceLocator location)
Method setLocator sets an instance of a SourceLocator object that specifies where an error occured.

Parameters:
location - A SourceLocator object, or null to clear the location.

getException

public Throwable getException()
This method retrieves an exception that this exception wraps.

Returns:
An Throwable object, or null.
See Also:
getCause()

getCause

public Throwable getCause()
Returns the cause of this throwable or null if the cause is nonexistent or unknown. (The cause is the throwable that caused this throwable to get thrown.)

Overrides:
getCause in class Throwable
Returns:
the cause of this throwable or null if the cause is nonexistent or unknown.

initCause

public Throwable initCause(Throwable cause)
Initializes the cause of this throwable to the specified value. (The cause is the throwable that caused this throwable to get thrown.)

This method can be called at most once. It is generally called from within the constructor, or immediately after creating the throwable. If this throwable was created with TransformerException(Throwable) or TransformerException(String,Throwable), this method cannot be called even once.

Overrides:
initCause in class Throwable
Parameters:
cause - the cause (which is saved for later retrieval by the getCause() method). (A null value is permitted, and indicates that the cause is nonexistent or unknown.)
Returns:
a reference to this Throwable instance.
Throws:
IllegalArgumentException - if cause is this throwable. (A throwable cannot be its own cause.)
IllegalStateException - if this throwable was created with TransformerException(Throwable) or TransformerException(String,Throwable), or this method has already been called on this throwable.

getMessageAndLocation

public String getMessageAndLocation()
Get the error message with location information appended.

Returns:
A String representing the error message with location information appended.

getLocationAsString

public String getLocationAsString()
Get the location information as a string.

Returns:
A string with location info, or null if there is no location information.

printStackTrace

public void printStackTrace()
Print the the trace of methods from where the error originated. This will trace all nested exception objects, as well as this object.

Overrides:
printStackTrace in class Throwable

printStackTrace

public void printStackTrace(PrintStream s)
Print the the trace of methods from where the error originated. This will trace all nested exception objects, as well as this object.

Overrides:
printStackTrace in class Throwable
Parameters:
s - The stream where the dump will be sent to.

printStackTrace

public void printStackTrace(PrintWriter s)
Print the the trace of methods from where the error originated. This will trace all nested exception objects, as well as this object.

Overrides:
printStackTrace in class Throwable
Parameters:
s - The writer where the dump will be sent to.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


TransformerFactory (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.xml.transform
Class TransformerFactory

java.lang.Object
    extended by javax.xml.transform.TransformerFactory
Direct Known Subclasses:
SAXTransformerFactory
public abstract class TransformerFactory
extends Object

A TransformerFactory instance can be used to create Transformer and Templates objects.

The system property that determines which Factory implementation to create is named "javax.xml.transform.TransformerFactory". This property names a concrete subclass of the TransformerFactory abstract class. If the property is not defined, a platform default is be used.

An implementation of the TransformerFactory class is NOT guaranteed to be thread safe. It is up to the user application to make sure about the use of the TransformerFactory from more than one thread. Alternatively the application can have one instance of the TransformerFactory per thread. An application can use the same instance of the factory to obtain one or more instances of a Transformer or Templates provided the instance of the factory isn't being used in more than one thread at a time.

Constructor Summary
protected TransformerFactory()
Default constructor is protected on purpose.
Method Summary
abstract  Source getAssociatedStylesheet(Source source, String media, String title, String charset)
Get the stylesheet specification(s) associated via the xml-stylesheet processing instruction (see http://www.w3.org/TR/xml-stylesheet/) with the document document specified in the source parameter, and that match the given criteria.
abstract  Object getAttribute(String name)
Allows the user to retrieve specific attributes on the underlying implementation.
abstract  ErrorListener getErrorListener()
Get the error event handler for the TransformerFactory.
abstract  boolean getFeature(String name)
Look up the value of a feature.
abstract  URIResolver getURIResolver()
Get the object that is used by default during the transformation to resolve URIs used in document(), xsl:import, or xsl:include.
static TransformerFactory newInstance()
Obtain a new instance of a TransformerFactory.
abstract  Templates newTemplates(Source source)
Process the Source into a Templates object, which is a a compiled representation of the source.
abstract  Transformer newTransformer()
Create a new Transformer object that performs a copy of the source to the result.
abstract  Transformer newTransformer(Source source)
Process the Source into a Transformer object.
abstract  void setAttribute(String name, Object value)
Allows the user to set specific attributes on the underlying implementation.
abstract  void setErrorListener(ErrorListener listener)
Set the error event listener for the TransformerFactory, which is used for the processing of transformation instructions, and not for the transformation itself.
abstract  void setURIResolver(URIResolver resolver)
Set an object that is used by default during the transformation to resolve URIs used in xsl:import, or xsl:include.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

TransformerFactory

protected TransformerFactory()
Default constructor is protected on purpose.

Method Detail

newInstance

public static TransformerFactory newInstance()
                                      throws TransformerFactoryConfigurationError
Obtain a new instance of a TransformerFactory. This static method creates a new factory instance This method uses the following ordered lookup procedure to determine the TransformerFactory implementation class to load:
  • Use the javax.xml.transform.TransformerFactory system property.
  • Use the properties file "lib/jaxp.properties" in the JRE directory. This configuration file is in standard java.util.Properties format and contains the fully qualified name of the implementation class with the key being the system property defined above.
  • Use the Services API (as detailed in the JAR specification), if available, to determine the classname. The Services API will look for a classname in the file META-INF/services/javax.xml.transform.TransformerFactory in jars available to the runtime.
  • Platform default TransformerFactory instance.
Once an application has obtained a reference to a TransformerFactory it can use the factory to configure and obtain parser instances.

Returns:
new TransformerFactory instance, never null.
Throws:
TransformerFactoryConfigurationError - if the implmentation is not available or cannot be instantiated.

newTransformer

public abstract Transformer newTransformer(Source source)
                                    throws TransformerConfigurationException
Process the Source into a Transformer object. Care must be given not to use this object in multiple threads running concurrently. Different TransformerFactories can be used concurrently by different threads.

Parameters:
source - An object that holds a URI, input stream, etc.
Returns:
A Transformer object that may be used to perform a transformation in a single thread, never null.
Throws:
TransformerConfigurationException - May throw this during the parse when it is constructing the Templates object and fails.

newTransformer

public abstract Transformer newTransformer()
                                    throws TransformerConfigurationException
Create a new Transformer object that performs a copy of the source to the result.

Returns:
A Transformer object that may be used to perform a transformation in a single thread, never null.
Throws:
TransformerConfigurationException - May throw this during the parse when it is constructing the Templates object and fails.

newTemplates

public abstract Templates newTemplates(Source source)
                                throws TransformerConfigurationException
Process the Source into a Templates object, which is a a compiled representation of the source. This Templates object may then be used concurrently across multiple threads. Creating a Templates object allows the TransformerFactory to do detailed performance optimization of transformation instructions, without penalizing runtime transformation.

Parameters:
source - An object that holds a URL, input stream, etc.
Returns:
A Templates object capable of being used for transformation purposes, never null.
Throws:
TransformerConfigurationException - May throw this during the parse when it is constructing the Templates object and fails.

getAssociatedStylesheet

public abstract Source getAssociatedStylesheet(Source source,
                                               String media,
                                               String title,
                                               String charset)
                                        throws TransformerConfigurationException
Get the stylesheet specification(s) associated via the xml-stylesheet processing instruction (see http://www.w3.org/TR/xml-stylesheet/) with the document document specified in the source parameter, and that match the given criteria. Note that it is possible to return several stylesheets, in which case they are applied as if they were a list of imports or cascades in a single stylesheet.

Parameters:
source - The XML source document.
media - The media attribute to be matched. May be null, in which case the prefered templates will be used (i.e. alternate = no).
title - The value of the title attribute to match. May be null.
charset - The value of the charset attribute to match. May be null.
Returns:
A Source object suitable for passing to the TransformerFactory.
Throws:
TransformerConfigurationException.
TransformerConfigurationException

setURIResolver

public abstract void setURIResolver(URIResolver resolver)
Set an object that is used by default during the transformation to resolve URIs used in xsl:import, or xsl:include.

Parameters:
resolver - An object that implements the URIResolver interface, or null.

getURIResolver

public abstract URIResolver getURIResolver()
Get the object that is used by default during the transformation to resolve URIs used in document(), xsl:import, or xsl:include.

Returns:
The URIResolver that was set with setURIResolver.

getFeature

public abstract boolean getFeature(String name)
Look up the value of a feature.

The feature name is any absolute URI.

Parameters:
name - The feature name, which is an absolute URI.
Returns:
The current state of the feature (true or false).

setAttribute

public abstract void setAttribute(String name,
                                  Object value)
                           throws IllegalArgumentException
Allows the user to set specific attributes on the underlying implementation. An attribute in this context is defined to be an option that the implementation provides.

Parameters:
name - The name of the attribute.
value - The value of the attribute.
Throws:
IllegalArgumentException - thrown if the underlying implementation doesn't recognize the attribute.

getAttribute

public abstract Object getAttribute(String name)
                             throws IllegalArgumentException
Allows the user to retrieve specific attributes on the underlying implementation.

Parameters:
name - The name of the attribute.
Returns:
value The value of the attribute.
Throws:
IllegalArgumentException - thrown if the underlying implementation doesn't recognize the attribute.

setErrorListener

public abstract void setErrorListener(ErrorListener listener)
                               throws IllegalArgumentException
Set the error event listener for the TransformerFactory, which is used for the processing of transformation instructions, and not for the transformation itself.

Parameters:
listener - The new error listener.
Throws:
IllegalArgumentException - if listener is null.

getErrorListener

public abstract ErrorListener getErrorListener()
Get the error event handler for the TransformerFactory.

Returns:
The current error handler, which should never be null.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


TransformerFactoryConfigurationError (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.xml.transform
Class TransformerFactoryConfigurationError

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Error
            extended by javax.xml.transform.TransformerFactoryConfigurationError
All Implemented Interfaces:
Serializable
public class TransformerFactoryConfigurationError
extends Error

Thrown when a problem with configuration with the Transformer Factories exists. This error will typically be thrown when the class of a transformation factory specified in the system properties cannot be found or instantiated.

See Also:
Serialized Form

Constructor Summary
TransformerFactoryConfigurationError()
Create a new TransformerFactoryConfigurationError with no detail mesage.
TransformerFactoryConfigurationError(Exception e)
Create a new TransformerFactoryConfigurationError with a given Exception base cause of the error.
TransformerFactoryConfigurationError(Exception e, String msg)
Create a new TransformerFactoryConfigurationError with the given Exception base cause and detail message.
TransformerFactoryConfigurationError(String msg)
Create a new TransformerFactoryConfigurationError with the String specified as an error message.
Method Summary
Exception | getException() Return the actual exception (if any) that caused this exception to be raised.
String | getMessage() Return the message (if any) for this error .
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getStackTrace, 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

TransformerFactoryConfigurationError

public TransformerFactoryConfigurationError()
Create a new TransformerFactoryConfigurationError with no detail mesage.

TransformerFactoryConfigurationError

public TransformerFactoryConfigurationError(String msg)
Create a new TransformerFactoryConfigurationError with the String specified as an error message.

Parameters:
msg - The error message for the exception.

TransformerFactoryConfigurationError

public TransformerFactoryConfigurationError(Exception e)
Create a new TransformerFactoryConfigurationError with a given Exception base cause of the error.

Parameters:
e - The exception to be encapsulated in a TransformerFactoryConfigurationError.

TransformerFactoryConfigurationError

public TransformerFactoryConfigurationError(Exception e,
                                            String msg)
Create a new TransformerFactoryConfigurationError with the given Exception base cause and detail message.

Parameters:
e - The exception to be encapsulated in a TransformerFactoryConfigurationError
msg - The detail message.
Method Detail

getMessage

public String getMessage()
Return the message (if any) for this error . If there is no message for the exception and there is an encapsulated exception then the message of that exception will be returned.

Overrides:
getMessage in class Throwable
Returns:
The error message.

getException

public Exception getException()
Return the actual exception (if any) that caused this exception to be raised.

Returns:
The encapsulated exception, or null if there is none.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


URIResolver (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.xml.transform
Interface URIResolver

public interface URIResolver

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.

Method Summary
 Source resolve(String href, String base)
Called by the processor when it encounters an xsl:include, xsl:import, or document() function.

Method Detail

resolve

public Source resolve(String href,
                      String base)
               throws TransformerException
Called by the processor when it encounters an xsl:include, xsl:import, or document() function.

Parameters:
href - An href attribute, which may be relative or absolute.
base - The base URI in effect when the href attribute was encountered.
Returns:
A Source object, or null if the href cannot be resolved, and the processor should try to resolve the URI itself.
Throws:
TransformerException - if an error occurs when trying to resolve the URI.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Uses of Interface javax.xml.transform.ErrorListener (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.xml.transform.ErrorListener

Packages that use ErrorListener
javax.xml.transform This package defines the generic APIs for processing transformation instructions, and performing a transformation from source to result.

Uses of ErrorListener in javax.xml.transform

Methods in javax.xml.transform that return ErrorListener
abstract ErrorListener | TransformerFactory.getErrorListener() Get the error event handler for the TransformerFactory.
abstract ErrorListener | Transformer.getErrorListener() Get the error event handler in effect for the transformation.

Methods in javax.xml.transform with parameters of type ErrorListener
abstract void | TransformerFactory.setErrorListener(ErrorListener listener) Set the error event listener for the TransformerFactory, which is used for the processing of transformation instructions, and not for the transformation itself.
abstract void | Transformer.setErrorListener(ErrorListener listener) Set the error event listener in effect for the transformation.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.xml.transform.OutputKeys (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.xml.transform.OutputKeys

No usage of javax.xml.transform.OutputKeys

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.xml.transform.Result (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.xml.transform.Result

Packages that use Result
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 | This package implements DOM-specific transformation APIs.
javax.xml.transform.sax | This package implements SAX2-specific transformation APIs.
javax.xml.transform.stream | This package implements stream- and URI- specific transformation APIs.

Uses of Result in javax.xml.transform

Methods in javax.xml.transform with parameters of type Result
abstract  void Transformer.transform(Source xmlSource, Result outputTarget)
Process the source tree to the output result.

Uses of Result in javax.xml.transform.dom

Classes in javax.xml.transform.dom that implement Result
 class DOMResult
Acts as a holder for a transformation result tree, in the form of a Document Object Model (DOM) tree.

Uses of Result in javax.xml.transform.sax

Classes in javax.xml.transform.sax that implement Result
 class SAXResult
Acts as an holder for a transformation Result.

Methods in javax.xml.transform.sax with parameters of type Result
 void TransformerHandler.setResult(Result result)
Enables the user of the TransformerHandler to set the to set the Result for the transformation.

Uses of Result in javax.xml.transform.stream

Classes in javax.xml.transform.stream that implement Result
 class StreamResult
Acts as an holder for a transformation result, which may be XML, plain Text, HTML, or some other form of markup.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.xml.transform.Source (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.xml.transform.Source

Packages that use Source
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 | This package implements DOM-specific transformation APIs.
javax.xml.transform.sax | This package implements SAX2-specific transformation APIs.
javax.xml.transform.stream | This package implements stream- and URI- specific transformation APIs.

Uses of Source in javax.xml.transform

Methods in javax.xml.transform that return Source
abstract  Source TransformerFactory.getAssociatedStylesheet(Source source, String media, String title, String charset)
Get the stylesheet specification(s) associated via the xml-stylesheet processing instruction (see http://www.w3.org/TR/xml-stylesheet/) with the document document specified in the source parameter, and that match the given criteria.
 Source URIResolver.resolve(String href, String base)
Called by the processor when it encounters an xsl:include, xsl:import, or document() function.

Methods in javax.xml.transform with parameters of type Source
abstract Transformer | TransformerFactory.newTransformer(Source source) Process the Source into a Transformer object.
abstract Templates | TransformerFactory.newTemplates(Source source) Process the Source into a Templates object, which is a a compiled representation of the source.
abstract Source | TransformerFactory.getAssociatedStylesheet(Source source, String media, String title, String charset) Get the stylesheet specification(s) associated via the xml-stylesheet processing instruction (see http://www.w3.org/TR/xml-stylesheet/) with the document document specified in the source parameter, and that match the given criteria.
abstract void | Transformer.transform(Source xmlSource, Result outputTarget) Process the source tree to the output result.

Uses of Source in javax.xml.transform.dom

Classes in javax.xml.transform.dom that implement Source
 class DOMSource
Acts as a holder for a transformation Source tree in the form of a Document Object Model (DOM) tree.

Uses of Source in javax.xml.transform.sax

Classes in javax.xml.transform.sax that implement Source
 class SAXSource
Acts as an holder for SAX-style Source.

Methods in javax.xml.transform.sax with parameters of type Source
abstract TransformerHandler | SAXTransformerFactory.newTransformerHandler(Source src) Get a TransformerHandler object that can process SAX ContentHandler events into a Result, based on the transformation instructions specified by the argument.
abstract XMLFilter | SAXTransformerFactory.newXMLFilter(Source src) Create an XMLFilter that uses the given Source as the transformation instructions.
static InputSource | SAXSource.sourceToInputSource(Source source) Attempt to obtain a SAX InputSource object from a TrAX Source object.

Uses of Source in javax.xml.transform.stream

Classes in javax.xml.transform.stream that implement Source
 class StreamSource
Acts as an holder for a transformation Source in the form of a stream of XML markup.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.xml.transform.SourceLocator (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.xml.transform.SourceLocator

Packages that use SourceLocator
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 | This package implements DOM-specific transformation APIs.

Uses of SourceLocator in javax.xml.transform

Methods in javax.xml.transform that return SourceLocator
 SourceLocator TransformerException.getLocator()
Method getLocator retrieves an instance of a SourceLocator object that specifies where an error occured.

Methods in javax.xml.transform with parameters of type SourceLocator
 void TransformerException.setLocator(SourceLocator location)
Method setLocator sets an instance of a SourceLocator object that specifies where an error occured.

Constructors in javax.xml.transform with parameters of type SourceLocator
TransformerConfigurationException(String message, SourceLocator locator)
Create a new TransformerConfigurationException from a message and a Locator.
TransformerConfigurationException(String message, SourceLocator locator, Throwable e)
Wrap an existing exception in a TransformerConfigurationException.
TransformerException(String message, SourceLocator locator)
Create a new TransformerException from a message and a Locator.
TransformerException(String message, SourceLocator locator, Throwable e)
Wrap an existing exception in a TransformerException.

Uses of SourceLocator in javax.xml.transform.dom

Subinterfaces of SourceLocator in javax.xml.transform.dom
 interface DOMLocator
Indicates the position of a node in a source DOM, intended primarily for error reporting.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.xml.transform.Templates (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.xml.transform.Templates

Packages that use Templates
javax.xml.transform | This package defines the generic APIs for processing transformation instructions, and performing a transformation from source to result.
javax.xml.transform.sax | This package implements SAX2-specific transformation APIs.

Uses of Templates in javax.xml.transform

Methods in javax.xml.transform that return Templates
abstract  Templates TransformerFactory.newTemplates(Source source)
Process the Source into a Templates object, which is a a compiled representation of the source.

Uses of Templates in javax.xml.transform.sax

Methods in javax.xml.transform.sax that return Templates
 Templates TemplatesHandler.getTemplates()
When a TemplatesHandler object is used as a ContentHandler for the parsing of transformation instructions, it creates a Templates object, which the caller can get once the SAX events have been completed.

Methods in javax.xml.transform.sax with parameters of type Templates
abstract TransformerHandler | SAXTransformerFactory.newTransformerHandler(Templates templates) Get a TransformerHandler object that can process SAX ContentHandler events into a Result, based on the Templates argument.
abstract XMLFilter | SAXTransformerFactory.newXMLFilter(Templates templates) Create an XMLFilter, based on the Templates argument..

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.xml.transform.Transformer (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.xml.transform.Transformer

Packages that use Transformer
javax.xml.transform | This package defines the generic APIs for processing transformation instructions, and performing a transformation from source to result.
javax.xml.transform.sax | This package implements SAX2-specific transformation APIs.

Uses of Transformer in javax.xml.transform

Methods in javax.xml.transform that return Transformer
abstract Transformer | TransformerFactory.newTransformer(Source source) Process the Source into a Transformer object.
abstract Transformer | TransformerFactory.newTransformer() Create a new Transformer object that performs a copy of the source to the result.
Transformer | Templates.newTransformer() Create a new transformation context for this Templates object.

Uses of Transformer in javax.xml.transform.sax

Methods in javax.xml.transform.sax that return Transformer
 Transformer TransformerHandler.getTransformer()
Get the Transformer associated with this handler, which is needed in order to set parameters and output properties.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.xml.transform.TransformerConfigurationException (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.xml.transform.TransformerConfigurationException

Packages that use TransformerConfigurationException
javax.xml.transform | This package defines the generic APIs for processing transformation instructions, and performing a transformation from source to result.
javax.xml.transform.sax | This package implements SAX2-specific transformation APIs.

Uses of TransformerConfigurationException in javax.xml.transform

Methods in javax.xml.transform that throw TransformerConfigurationException
abstract Transformer | TransformerFactory.newTransformer(Source source) Process the Source into a Transformer object.
abstract Transformer | TransformerFactory.newTransformer() Create a new Transformer object that performs a copy of the source to the result.
abstract Templates | TransformerFactory.newTemplates(Source source) Process the Source into a Templates object, which is a a compiled representation of the source.
abstract Source | TransformerFactory.getAssociatedStylesheet(Source source, String media, String title, String charset) Get the stylesheet specification(s) associated via the xml-stylesheet processing instruction (see http://www.w3.org/TR/xml-stylesheet/) with the document document specified in the source parameter, and that match the given criteria.
Transformer | Templates.newTransformer() Create a new transformation context for this Templates object.

Uses of TransformerConfigurationException in javax.xml.transform.sax

Methods in javax.xml.transform.sax that throw TransformerConfigurationException
abstract TransformerHandler | SAXTransformerFactory.newTransformerHandler(Source src) Get a TransformerHandler object that can process SAX ContentHandler events into a Result, based on the transformation instructions specified by the argument.
abstract TransformerHandler | SAXTransformerFactory.newTransformerHandler(Templates templates) Get a TransformerHandler object that can process SAX ContentHandler events into a Result, based on the Templates argument.
abstract TransformerHandler | SAXTransformerFactory.newTransformerHandler() Get a TransformerHandler object that can process SAX ContentHandler events into a Result.
abstract TemplatesHandler | SAXTransformerFactory.newTemplatesHandler() Get a TemplatesHandler object that can process SAX ContentHandler events into a Templates object.
abstract XMLFilter | SAXTransformerFactory.newXMLFilter(Source src) Create an XMLFilter that uses the given Source as the transformation instructions.
abstract XMLFilter | SAXTransformerFactory.newXMLFilter(Templates templates) Create an XMLFilter, based on the Templates argument..

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.xml.transform.TransformerException (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.xml.transform.TransformerException

Packages that use TransformerException
javax.xml.transform This package defines the generic APIs for processing transformation instructions, and performing a transformation from source to result.

Uses of TransformerException in javax.xml.transform

Subclasses of TransformerException in javax.xml.transform
 class TransformerConfigurationException
Indicates a serious configuration error.

Methods in javax.xml.transform with parameters of type TransformerException
void | ErrorListener.warning(TransformerException exception) Receive notification of a warning.
void | ErrorListener.error(TransformerException exception) Receive notification of a recoverable error.
void | ErrorListener.fatalError(TransformerException exception) Receive notification of a non-recoverable error.

Methods in javax.xml.transform that throw TransformerException
 Source URIResolver.resolve(String href, String base)
Called by the processor when it encounters an xsl:include, xsl:import, or document() function.
abstract  void Transformer.transform(Source xmlSource, Result outputTarget)
Process the source tree to the output result.
 void ErrorListener.warning(TransformerException exception)
Receive notification of a warning.
 void ErrorListener.error(TransformerException exception)
Receive notification of a recoverable error.
 void ErrorListener.fatalError(TransformerException exception)
Receive notification of a non-recoverable error.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.xml.transform.TransformerFactory (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.xml.transform.TransformerFactory

Packages that use TransformerFactory
javax.xml.transform | This package defines the generic APIs for processing transformation instructions, and performing a transformation from source to result.
javax.xml.transform.sax | This package implements SAX2-specific transformation APIs.

Uses of TransformerFactory in javax.xml.transform

Methods in javax.xml.transform that return TransformerFactory
static TransformerFactory TransformerFactory.newInstance()
Obtain a new instance of a TransformerFactory.

Uses of TransformerFactory in javax.xml.transform.sax

Subclasses of TransformerFactory in javax.xml.transform.sax
 class SAXTransformerFactory
This class extends TransformerFactory to provide SAX-specific factory methods.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.xml.transform.TransformerFactoryConfigurationError (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.xml.transform.TransformerFactoryConfigurationError

Packages that use TransformerFactoryConfigurationError
javax.xml.transform This package defines the generic APIs for processing transformation instructions, and performing a transformation from source to result.

Uses of TransformerFactoryConfigurationError in javax.xml.transform

Methods in javax.xml.transform that throw TransformerFactoryConfigurationError
static TransformerFactory TransformerFactory.newInstance()
Obtain a new instance of a TransformerFactory.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.xml.transform.URIResolver (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.xml.transform.URIResolver

Packages that use URIResolver
javax.xml.transform This package defines the generic APIs for processing transformation instructions, and performing a transformation from source to result.

Uses of URIResolver in javax.xml.transform

Methods in javax.xml.transform that return URIResolver
abstract  URIResolver TransformerFactory.getURIResolver()
Get the object that is used by default during the transformation to resolve URIs used in document(), xsl:import, or xsl:include.
abstract  URIResolver Transformer.getURIResolver()
Get an object that will be used to resolve URIs used in document(), etc.

Methods in javax.xml.transform with parameters of type URIResolver
abstract  void TransformerFactory.setURIResolver(URIResolver resolver)
Set an object that is used by default during the transformation to resolve URIs used in xsl:import, or xsl:include.
abstract  void Transformer.setURIResolver(URIResolver resolver)
Set an object that will be used to resolve URIs used in document().

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


DOMLocator (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.xml.transform.dom
Interface DOMLocator

All Superinterfaces:
SourceLocator
public interface DOMLocator
extends SourceLocator

Indicates the position of a node in a source DOM, intended primarily for error reporting. To use a DOMLocator, the receiver of an error must downcast the SourceLocator object returned by an exception. A Transformer may use this object for purposes other than error reporting, for instance, to indicate the source node that originated a result node.

Method Summary
 Node getOriginatingNode()
Return the node where the event occurred.
Methods inherited from interface javax.xml.transform.SourceLocator
getColumnNumber, getLineNumber, getPublicId, getSystemId

Method Detail

getOriginatingNode

public Node getOriginatingNode()
Return the node where the event occurred.

Returns:
The node that is the location for the event.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


DOMResult (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.xml.transform.dom
Class DOMResult

java.lang.Object
    extended by javax.xml.transform.dom.DOMResult
All Implemented Interfaces:
Result
public class DOMResult
extends Object
implements Result

Acts as a holder for a transformation result tree, in the form of a Document Object Model (DOM) tree. If no output DOM source is set, the transformation will create a Document node as the holder for the result of the transformation, which may be retrieved with getNode.

Field Summary
static String FEATURE
If TransformerFactory.getFeature(java.lang.String) returns true when passed this value as an argument, the Transformer supports Result output of this type.
Fields inherited from interface javax.xml.transform.Result
PI_DISABLE_OUTPUT_ESCAPING, PI_ENABLE_OUTPUT_ESCAPING
Constructor Summary
DOMResult()
Zero-argument default constructor.
DOMResult(Node node)
Use a DOM node to create a new output target.
DOMResult(Node node, String systemID)
Create a new output target with a DOM node.
Method Summary
Node | getNode() Get the node that will contain the result DOM tree.
String | getSystemId() Get the system identifier that was set with setSystemId.
void | setNode(Node node) Set the node that will contain the result DOM tree.
void | setSystemId(String systemId) Method setSystemId Set the systemID that may be used in association with the node.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

FEATURE

public static final String FEATURE
If TransformerFactory.getFeature(java.lang.String) returns true when passed this value as an argument, the Transformer supports Result output of this type.

See Also:
Constant Field Values
Constructor Detail

DOMResult

public DOMResult()
Zero-argument default constructor.

DOMResult

public DOMResult(Node node)
Use a DOM node to create a new output target. In practice, the node should be a Document node, a DocumentFragment node, or a Element node. In other words, a node that accepts children.

DOMResult

public DOMResult(Node node,
                 String systemID)
Create a new output target with a DOM node. In practice, the node should be a Document node, a DocumentFragment node, or a Element node. In other words, a node that accepts children.

Parameters:
node - The DOM node that will contain the result tree.
systemID - The system identifier which may be used in association with this node.
Method Detail

setNode

public void setNode(Node node)
Set the node that will contain the result DOM tree. In practice, the node should be a Document node, a DocumentFragment node, or a Element node. In other words, a node that accepts children.

Parameters:
node - The node to which the transformation will be appended.

getNode

public Node getNode()
Get the node that will contain the result DOM tree. If no node was set via setNode, the node will be set by the transformation, and may be obtained from this method once the transformation is complete.

Returns:
The node to which the transformation will be appended.

setSystemId

public void setSystemId(String systemId)
Method setSystemId Set the systemID that may be used in association with the node.

Specified by:
setSystemId in interface Result
Parameters:
systemId - The system identifier as a URI string.

getSystemId

public String getSystemId()
Get the system identifier that was set with setSystemId.

Specified by:
getSystemId in interface Result
Returns:
The system identifier that was set with setSystemId, or null if setSystemId was not called.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


DOMSource (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.xml.transform.dom
Class DOMSource

java.lang.Object
    extended by javax.xml.transform.dom.DOMSource
All Implemented Interfaces:
Source
public class DOMSource
extends Object
implements Source

Acts as a holder for a transformation Source tree in the form of a Document Object Model (DOM) tree.

See Also:
Document Object Model (DOM) Level 2 Specification

Field Summary
static String FEATURE
If TransformerFactory.getFeature(java.lang.String) returns true when passed this value as an argument, the Transformer supports Source input of this type.
Constructor Summary
DOMSource()
Zero-argument default constructor.
DOMSource(Node n)
Create a new input source with a DOM node.
DOMSource(Node node, String systemID)
Create a new input source with a DOM node, and with the system ID also passed in as the base URI.
Method Summary
Node | getNode() Get the node that represents a Source DOM tree.
String | getSystemId() Get the base ID (URL or system ID) from where URLs will be resolved.
void | setNode(Node node) Set the node that will represents a Source DOM tree.
void | setSystemId(String baseID) Set the base ID (URL or system ID) from where URLs will be resolved.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

FEATURE

public static final String FEATURE
If TransformerFactory.getFeature(java.lang.String) returns true when passed this value as an argument, the Transformer supports Source input of this type.

See Also:
Constant Field Values
Constructor Detail

DOMSource

public DOMSource()
Zero-argument default constructor. If this is used, and no DOM source is set, then the Transformer will create an empty source Document using DocumentBuilder.newDocument().

DOMSource

public DOMSource(Node n)
Create a new input source with a DOM node. The operation will be applied to the subtree rooted at this node. In XSLT, a "/" pattern still means the root of the tree (not the subtree), and the evaluation of global variables and parameters is done from the root node also.

Parameters:
n - The DOM node that will contain the Source tree.

DOMSource

public DOMSource(Node node,
                 String systemID)
Create a new input source with a DOM node, and with the system ID also passed in as the base URI.

Parameters:
node - The DOM node that will contain the Source tree.
systemID - Specifies the base URI associated with node.
Method Detail

setNode

public void setNode(Node node)
Set the node that will represents a Source DOM tree.

Parameters:
node - The node that is to be transformed.

getNode

public Node getNode()
Get the node that represents a Source DOM tree.

Returns:
The node that is to be transformed.

setSystemId

public void setSystemId(String baseID)
Set the base ID (URL or system ID) from where URLs will be resolved.

Specified by:
setSystemId in interface Source
Parameters:
baseID - Base URL for this DOM tree.

getSystemId

public String getSystemId()
Get the base ID (URL or system ID) from where URLs will be resolved.

Specified by:
getSystemId in interface Source
Returns:
Base URL for this DOM tree.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


javax.xml.transform.dom (Java 2 Platform SE v1.4.2)

 javax.xml.transform.dom
Interfaces
DOMLocator
Classes
DOMResult
DOMSource


javax.xml.transform.dom (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package javax.xml.transform.dom

This package implements DOM-specific transformation APIs.

See:
Description

Interface Summary
DOMLocator Indicates the position of a node in a source DOM, intended primarily for error reporting.

Class Summary
DOMResult | Acts as a holder for a transformation result tree, in the form of a Document Object Model (DOM) tree.
DOMSource | Acts as a holder for a transformation Source tree in the form of a Document Object Model (DOM) tree.

Package javax.xml.transform.dom Description

This package implements DOM-specific transformation APIs.

The DOMSource class allows the client of the implementation of this API to specify a DOM Node as the source of the input tree. The model of how the Transformer deals with the DOM tree in terms of mismatches with the XSLT data model or other data models is beyond the scope of this document. Any of the nodes derived from Node are legal input.

The DOMResult class allows a Node to be specified to which result DOM nodes will be appended. If an output node is not specified, the transformer will use DocumentBuilder.newDocument() to create an output Document node. If a node is specified, it should be one of the following: Document, Element, or DocumentFragment. Specification of any other node type is implementation dependent and undefined by this API. If the result is a Document, the output of the transformation must have a single element root to set as the document element.

The DOMLocator node may be passed to TransformerException objects, and retrieved by trying to cast the result of the TransformerException.getLocator() method. The implementation has no responsibility to use a DOMLocator instead of a SourceLocator (though line numbers and the like do not make much sense for a DOM), so the result of getLocator must always be tested with an instanceof.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


javax.xml.transform.dom Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package javax.xml.transform.dom

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class javax.xml.transform.dom.DOMResult (implements javax.xml.transform.Result)
    • class javax.xml.transform.dom.DOMSource (implements javax.xml.transform.Source)

Interface Hierarchy

  • interface javax.xml.transform.SourceLocator
    • interface javax.xml.transform.dom.DOMLocator
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package javax.xml.transform.dom (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
javax.xml.transform.dom

No usage of javax.xml.transform.dom

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.xml.transform.dom.DOMLocator (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.xml.transform.dom.DOMLocator

No usage of javax.xml.transform.dom.DOMLocator

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.xml.transform.dom.DOMResult (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.xml.transform.dom.DOMResult

No usage of javax.xml.transform.dom.DOMResult

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.xml.transform.dom.DOMSource (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.xml.transform.dom.DOMSource

No usage of javax.xml.transform.dom.DOMSource

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


javax.xml.transform.sax (Java 2 Platform SE v1.4.2)

 javax.xml.transform.sax
Interfaces
TemplatesHandler
TransformerHandler
Classes
SAXResult
SAXSource
SAXTransformerFactory


javax.xml.transform.sax (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package javax.xml.transform.sax

This package implements SAX2-specific transformation APIs.

See:
Description

Interface Summary
TemplatesHandler | A SAX ContentHandler that may be used to process SAX parse events (parsing transformation instructions) into a Templates object.
TransformerHandler | A TransformerHandler listens for SAX ContentHandler parse events and transforms them to a Result.

Class Summary
SAXResult | Acts as an holder for a transformation Result.
SAXSource | Acts as an holder for SAX-style Source.
SAXTransformerFactory | This class extends TransformerFactory to provide SAX-specific factory methods.

Package javax.xml.transform.sax Description

This package implements SAX2-specific transformation APIs. It provides classes which allow input from ContentHandler events, and also classes that produce org.xml.sax.ContentHandler events. It also provides methods to set the input source as an XMLReader, or to use a InputSource as the source. It also allows the creation of a XMLFilter, which enables transformations to "pull" from other transformations, and lets the transformer to be used polymorphically as an XMLReader.

The SAXSource class allows the setting of an XMLReader to be used for "pulling" parse events, and an InputSource that may be used to specify the SAX source.

The SAXResult class allows the setting of a ContentHandler to be the receiver of SAX2 events from the transformation.

The SAXTransformerFactory extends TransformerFactory to provide factory methods for creating TemplatesHandler, TransformerHandler, and XMLReader instances.

To obtain a SAXTransformerFactory, the caller must cast the TransformerFactory instance returned from TransformerFactory.newInstance().

The TransformerHandler interface allows a transformation to be created from SAX2 parse events, which is a "push" model rather than the "pull" model that normally occurs for a transformation. Normal parse events are received through the ContentHandler interface, lexical events such as startCDATA and endCDATA are received through the LexicalHandler interface, and events that signal the start or end of disabling output escaping are received via ContentHandler.processingInstruction(java.lang.String, java.lang.String), with the target parameter being Result.PI_DISABLE_OUTPUT_ESCAPING and Result.PI_ENABLE_OUTPUT_ESCAPING. If parameters, output properties, or other features need to be set on the Transformer handler, a Transformer reference will need to be obtained from TransformerHandler.getTransformer(), and the methods invoked from that reference.

The TemplatesHandler interface allows the creation of Templates objects from SAX2 parse events. Once the ContentHandler events are complete, the Templates object may be obtained from TemplatesHandler.getTemplates(). Note that TemplatesHandler.setSystemId(java.lang.String) should normally be called in order to establish a base system ID from which relative URLs may be resolved.

The SAXTransformerFactory.newXMLFilter(javax.xml.transform.Source) method allows the creation of a XMLFilter, which encapsulates the SAX2 notion of a "pull" transformation. The following illustrates several transformations chained together. Each filter points to a parent XMLReader, and the final transformation is caused by invoking XMLReader.parse(org.xml.sax.InputSource) on the final reader in the chain.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


javax.xml.transform.sax Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package javax.xml.transform.sax

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class javax.xml.transform.sax.SAXResult (implements javax.xml.transform.Result)
    • class javax.xml.transform.sax.SAXSource (implements javax.xml.transform.Source)
    • class javax.xml.transform.TransformerFactory
      • class javax.xml.transform.sax.SAXTransformerFactory

Interface Hierarchy

  • interface org.xml.sax.ContentHandler
    • interface javax.xml.transform.sax.TemplatesHandler
    • interface javax.xml.transform.sax.TransformerHandler (also extends org.xml.sax.DTDHandler, org.xml.sax.ext.LexicalHandler)
  • interface org.xml.sax.DTDHandler
    • interface javax.xml.transform.sax.TransformerHandler (also extends org.xml.sax.ContentHandler, org.xml.sax.ext.LexicalHandler)
  • interface org.xml.sax.ext.LexicalHandler
    • interface javax.xml.transform.sax.TransformerHandler (also extends org.xml.sax.ContentHandler, org.xml.sax.DTDHandler)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package javax.xml.transform.sax (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
javax.xml.transform.sax

Packages that use javax.xml.transform.sax
javax.xml.transform.sax This package implements SAX2-specific transformation APIs.

Classes in javax.xml.transform.sax used by javax.xml.transform.sax
TemplatesHandler
A SAX ContentHandler that may be used to process SAX parse events (parsing transformation instructions) into a Templates object.
TransformerHandler
A TransformerHandler listens for SAX ContentHandler parse events and transforms them to a Result.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


SAXResult (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.xml.transform.sax
Class SAXResult

java.lang.Object
    extended by javax.xml.transform.sax.SAXResult
All Implemented Interfaces:
Result
public class SAXResult
extends Object
implements Result

Acts as an holder for a transformation Result.

Field Summary
static String FEATURE
If TransformerFactory.getFeature(java.lang.String) returns true when passed this value as an argument, the Transformer supports Result output of this type.
Fields inherited from interface javax.xml.transform.Result
PI_DISABLE_OUTPUT_ESCAPING, PI_ENABLE_OUTPUT_ESCAPING
Constructor Summary
SAXResult()
Zero-argument default constructor.
SAXResult(ContentHandler handler)
Create a SAXResult that targets a SAX2 ContentHandler.
Method Summary
ContentHandler | getHandler() Get the ContentHandler that is the Result.
LexicalHandler | getLexicalHandler() Get a SAX2 LexicalHandler for the output.
String | getSystemId() Get the system identifier that was set with setSystemId.
void | setHandler(ContentHandler handler) Set the target to be a SAX2 ContentHandler.
void | setLexicalHandler(LexicalHandler handler) Set the SAX2 LexicalHandler for the output.
void | setSystemId(String systemId) Method setSystemId Set the systemID that may be used in association with the ContentHandler.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

FEATURE

public static final String FEATURE
If TransformerFactory.getFeature(java.lang.String) returns true when passed this value as an argument, the Transformer supports Result output of this type.

See Also:
Constant Field Values
Constructor Detail

SAXResult

public SAXResult()
Zero-argument default constructor.

SAXResult

public SAXResult(ContentHandler handler)
Create a SAXResult that targets a SAX2 ContentHandler.

Parameters:
handler - Must be a non-null ContentHandler reference.
Method Detail

setHandler

public void setHandler(ContentHandler handler)
Set the target to be a SAX2 ContentHandler.

Parameters:
handler - Must be a non-null ContentHandler reference.

getHandler

public ContentHandler getHandler()
Get the ContentHandler that is the Result.

Returns:
The ContentHandler that is to be transformation output.

setLexicalHandler

public void setLexicalHandler(LexicalHandler handler)
Set the SAX2 LexicalHandler for the output.

This is needed to handle XML comments and the like. If the lexical handler is not set, an attempt should be made by the transformer to cast the ContentHandler to a LexicalHandler.

Parameters:
handler - A non-null LexicalHandler for handling lexical parse events.

getLexicalHandler

public LexicalHandler getLexicalHandler()
Get a SAX2 LexicalHandler for the output.

Returns:
A LexicalHandler, or null.

setSystemId

public void setSystemId(String systemId)
Method setSystemId Set the systemID that may be used in association with the ContentHandler.

Specified by:
setSystemId in interface Result
Parameters:
systemId - The system identifier as a URI string.

getSystemId

public String getSystemId()
Get the system identifier that was set with setSystemId.

Specified by:
getSystemId in interface Result
Returns:
The system identifier that was set with setSystemId, or null if setSystemId was not called.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


SAXSource (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.xml.transform.sax
Class SAXSource

java.lang.Object
    extended by javax.xml.transform.sax.SAXSource
All Implemented Interfaces:
Source
public class SAXSource
extends Object
implements Source

Acts as an holder for SAX-style Source.

Field Summary
static String FEATURE
If TransformerFactory.getFeature(java.lang.String) returns true when passed this value as an argument, the Transformer supports Source input of this type.
Constructor Summary
SAXSource()
Zero-argument default constructor.
SAXSource(InputSource inputSource)
Create a SAXSource, using a SAX InputSource.
SAXSource(XMLReader reader, InputSource inputSource)
Create a SAXSource, using an XMLReader and a SAX InputSource.
Method Summary
InputSource | getInputSource() Get the SAX InputSource to be used for the Source.
String | getSystemId() Get the base ID (URI or system ID) from where URIs will be resolved.
XMLReader | getXMLReader() Get the XMLReader to be used for the Source.
void | setInputSource(InputSource inputSource) Set the SAX InputSource to be used for the Source.
void | setSystemId(String systemId) Set the system identifier for this Source.
void | setXMLReader(XMLReader reader) Set the XMLReader to be used for the Source.
static InputSource | sourceToInputSource(Source source) Attempt to obtain a SAX InputSource object from a TrAX Source object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

FEATURE

public static final String FEATURE
If TransformerFactory.getFeature(java.lang.String) returns true when passed this value as an argument, the Transformer supports Source input of this type.

See Also:
Constant Field Values
Constructor Detail

SAXSource

public SAXSource()
Zero-argument default constructor. If this constructor is used, and no other method is called, the Transformer assumes an empty input tree, with a default root node.

SAXSource

public SAXSource(XMLReader reader,
                 InputSource inputSource)
Create a SAXSource, using an XMLReader and a SAX InputSource. The Transformer or SAXTransformerFactory will set itself to be the reader's ContentHandler, and then will call reader.parse(inputSource).

Parameters:
reader - An XMLReader to be used for the parse.
inputSource - A SAX input source reference that must be non-null and that will be passed to the reader parse method.

SAXSource

public SAXSource(InputSource inputSource)
Create a SAXSource, using a SAX InputSource. The Transformer or SAXTransformerFactory creates a reader via XMLReaderFactory (if setXMLReader is not used), sets itself as the reader's ContentHandler, and calls reader.parse(inputSource).

Parameters:
inputSource - An input source reference that must be non-null and that will be passed to the parse method of the reader.
Method Detail

setXMLReader

public void setXMLReader(XMLReader reader)
Set the XMLReader to be used for the Source.

Parameters:
reader - A valid XMLReader or XMLFilter reference.

getXMLReader

public XMLReader getXMLReader()
Get the XMLReader to be used for the Source.

Returns:
A valid XMLReader or XMLFilter reference, or null.

setInputSource

public void setInputSource(InputSource inputSource)
Set the SAX InputSource to be used for the Source.

Parameters:
inputSource - A valid InputSource reference.

getInputSource

public InputSource getInputSource()
Get the SAX InputSource to be used for the Source.

Returns:
A valid InputSource reference, or null.

setSystemId

public void setSystemId(String systemId)
Set the system identifier for this Source. If an input source has already been set, it will set the system ID or that input source, otherwise it will create a new input source.

The system identifier is optional if there is a byte stream or a character stream, but it is still useful to provide one, since the application can use it to resolve relative URIs and can include it in error messages and warnings (the parser will attempt to open a connection to the URI only if no byte stream or character stream is specified).

Specified by:
setSystemId in interface Source
Parameters:
systemId - The system identifier as a URI string.

getSystemId

public String getSystemId()
Get the base ID (URI or system ID) from where URIs will be resolved.

Specified by:
getSystemId in interface Source
Returns:
Base URL for the Source, or null.

sourceToInputSource

public static InputSource sourceToInputSource(Source source)
Attempt to obtain a SAX InputSource object from a TrAX Source object.

Parameters:
source - Must be a non-null Source reference.
Returns:
An InputSource, or null if Source can not be converted.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


SAXTransformerFactory (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.xml.transform.sax
Class SAXTransformerFactory

java.lang.Object
    extended by javax.xml.transform.TransformerFactory
        extended by javax.xml.transform.sax.SAXTransformerFactory
public abstract class SAXTransformerFactory
extends TransformerFactory

This class extends TransformerFactory to provide SAX-specific factory methods. It provides two types of ContentHandlers, one for creating Transformers, the other for creating Templates objects.

If an application wants to set the ErrorHandler or EntityResolver for an XMLReader used during a transformation, it should use a URIResolver to return the SAXSource which provides (with getXMLReader) a reference to the XMLReader.

Field Summary
static String | FEATURE If TransformerFactory.getFeature(java.lang.String) returns true when passed this value as an argument, the TransformerFactory returned from TransformerFactory.newInstance() may be safely cast to a SAXTransformerFactory.
static String | FEATURE_XMLFILTER If TransformerFactory.getFeature(java.lang.String) returns true when passed this value as an argument, the newXMLFilter(Source src) and newXMLFilter(Templates templates) methods are supported.
Constructor Summary
protected SAXTransformerFactory()
The default constructor is protected on purpose.
Method Summary
abstract TemplatesHandler | newTemplatesHandler() Get a TemplatesHandler object that can process SAX ContentHandler events into a Templates object.
abstract TransformerHandler | newTransformerHandler() Get a TransformerHandler object that can process SAX ContentHandler events into a Result.
abstract TransformerHandler | newTransformerHandler(Source src) Get a TransformerHandler object that can process SAX ContentHandler events into a Result, based on the transformation instructions specified by the argument.
abstract TransformerHandler | newTransformerHandler(Templates templates) Get a TransformerHandler object that can process SAX ContentHandler events into a Result, based on the Templates argument.
abstract XMLFilter | newXMLFilter(Source src) Create an XMLFilter that uses the given Source as the transformation instructions.
abstract XMLFilter | newXMLFilter(Templates templates) Create an XMLFilter, based on the Templates argument..
Methods inherited from class javax.xml.transform.TransformerFactory
getAssociatedStylesheet, getAttribute, getErrorListener, getFeature, getURIResolver, newInstance, newTemplates, newTransformer, newTransformer, setAttribute, setErrorListener, setURIResolver
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

FEATURE

public static final String FEATURE
If TransformerFactory.getFeature(java.lang.String) returns true when passed this value as an argument, the TransformerFactory returned from TransformerFactory.newInstance() may be safely cast to a SAXTransformerFactory.

See Also:
Constant Field Values

FEATURE_XMLFILTER

public static final String FEATURE_XMLFILTER
If TransformerFactory.getFeature(java.lang.String) returns true when passed this value as an argument, the newXMLFilter(Source src) and newXMLFilter(Templates templates) methods are supported.

See Also:
Constant Field Values
Constructor Detail

SAXTransformerFactory

protected SAXTransformerFactory()
The default constructor is protected on purpose.

Method Detail

newTransformerHandler

public abstract TransformerHandler newTransformerHandler(Source src)
                                                  throws TransformerConfigurationException
Get a TransformerHandler object that can process SAX ContentHandler events into a Result, based on the transformation instructions specified by the argument.

Parameters:
src - The Source of the transformation instructions.
Returns:
TransformerHandler ready to transform SAX events.
Throws:
TransformerConfigurationException - If for some reason the TransformerHandler can not be created.

newTransformerHandler

public abstract TransformerHandler newTransformerHandler(Templates templates)
                                                  throws TransformerConfigurationException
Get a TransformerHandler object that can process SAX ContentHandler events into a Result, based on the Templates argument.

Parameters:
templates - The compiled transformation instructions.
Returns:
TransformerHandler ready to transform SAX events.
Throws:
TransformerConfigurationException - If for some reason the TransformerHandler can not be created.

newTransformerHandler

public abstract TransformerHandler newTransformerHandler()
                                                  throws TransformerConfigurationException
Get a TransformerHandler object that can process SAX ContentHandler events into a Result. The transformation is defined as an identity (or copy) transformation, for example to copy a series of SAX parse events into a DOM tree.

Returns:
A non-null reference to a TransformerHandler, that may be used as a ContentHandler for SAX parse events.
Throws:
TransformerConfigurationException - If for some reason the TransformerHandler cannot be created.

newTemplatesHandler

public abstract TemplatesHandler newTemplatesHandler()
                                              throws TransformerConfigurationException
Get a TemplatesHandler object that can process SAX ContentHandler events into a Templates object.

Returns:
A non-null reference to a TransformerHandler, that may be used as a ContentHandler for SAX parse events.
Throws:
TransformerConfigurationException - If for some reason the TemplatesHandler cannot be created.

newXMLFilter

public abstract XMLFilter newXMLFilter(Source src)
                                throws TransformerConfigurationException
Create an XMLFilter that uses the given Source as the transformation instructions.

Parameters:
src - The Source of the transformation instructions.
Returns:
An XMLFilter object, or null if this feature is not supported.
Throws:
TransformerConfigurationException - If for some reason the TemplatesHandler cannot be created.

newXMLFilter

public abstract XMLFilter newXMLFilter(Templates templates)
                                throws TransformerConfigurationException
Create an XMLFilter, based on the Templates argument..

Parameters:
templates - The compiled transformation instructions.
Returns:
An XMLFilter object, or null if this feature is not supported.
Throws:
TransformerConfigurationException - If for some reason the TemplatesHandler cannot be created.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


TemplatesHandler (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.xml.transform.sax
Interface TemplatesHandler

All Superinterfaces:
ContentHandler
public interface TemplatesHandler
extends ContentHandler

A SAX ContentHandler that may be used to process SAX parse events (parsing transformation instructions) into a Templates object.

Note that TemplatesHandler does not need to implement LexicalHandler.

Method Summary
String | getSystemId() Get the base ID (URI or system ID) from where relative URLs will be resolved.
Templates | getTemplates() When a TemplatesHandler object is used as a ContentHandler for the parsing of transformation instructions, it creates a Templates object, which the caller can get once the SAX events have been completed.
void | setSystemId(String systemID) Set the base ID (URI or system ID) for the Templates object created by this builder.
Methods inherited from interface org.xml.sax.ContentHandler
characters, endDocument, endElement, endPrefixMapping, ignorableWhitespace, processingInstruction, setDocumentLocator, skippedEntity, startDocument, startElement, startPrefixMapping

Method Detail

getTemplates

public Templates getTemplates()
When a TemplatesHandler object is used as a ContentHandler for the parsing of transformation instructions, it creates a Templates object, which the caller can get once the SAX events have been completed.

Returns:
The Templates object that was created during the SAX event process, or null if no Templates object has been created.

setSystemId

public void setSystemId(String systemID)
Set the base ID (URI or system ID) for the Templates object created by this builder. This must be set in order to resolve relative URIs in the stylesheet. This must be called before the startDocument event.

getSystemId

public String getSystemId()
Get the base ID (URI or system ID) from where relative URLs will be resolved.

Returns:
The systemID that was set with setSystemId(java.lang.String).
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


TransformerHandler (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.xml.transform.sax
Interface TransformerHandler

All Superinterfaces:
ContentHandler, DTDHandler, LexicalHandler
public interface TransformerHandler
extends ContentHandler, LexicalHandler, DTDHandler

A TransformerHandler listens for SAX ContentHandler parse events and transforms them to a Result.

Method Summary
String | getSystemId() Get the base ID (URI or system ID) from where relative URLs will be resolved.
Transformer | getTransformer() Get the Transformer associated with this handler, which is needed in order to set parameters and output properties.
void | setResult(Result result) Enables the user of the TransformerHandler to set the to set the Result for the transformation.
void | setSystemId(String systemID) Set the base ID (URI or system ID) from where relative URLs will be resolved.
Methods inherited from interface org.xml.sax.ContentHandler
characters, endDocument, endElement, endPrefixMapping, ignorableWhitespace, processingInstruction, setDocumentLocator, skippedEntity, startDocument, startElement, startPrefixMapping
Methods inherited from interface org.xml.sax.ext.LexicalHandler
comment, endCDATA, endDTD, endEntity, startCDATA, startDTD, startEntity
Methods inherited from interface org.xml.sax.DTDHandler
notationDecl, unparsedEntityDecl

Method Detail

setResult

public void setResult(Result result)
               throws IllegalArgumentException
Enables the user of the TransformerHandler to set the to set the Result for the transformation.

Parameters:
result - A Result instance, should not be null.
Throws:
IllegalArgumentException - if result is invalid for some reason.

setSystemId

public void setSystemId(String systemID)
Set the base ID (URI or system ID) from where relative URLs will be resolved.

Parameters:
systemID - Base URI for the source tree.

getSystemId

public String getSystemId()
Get the base ID (URI or system ID) from where relative URLs will be resolved.

Returns:
The systemID that was set with setSystemId(java.lang.String).

getTransformer

public Transformer getTransformer()
Get the Transformer associated with this handler, which is needed in order to set parameters and output properties.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Uses of Class javax.xml.transform.sax.SAXResult (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.xml.transform.sax.SAXResult

No usage of javax.xml.transform.sax.SAXResult

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.xml.transform.sax.SAXSource (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.xml.transform.sax.SAXSource

No usage of javax.xml.transform.sax.SAXSource

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.xml.transform.sax.SAXTransformerFactory (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.xml.transform.sax.SAXTransformerFactory

No usage of javax.xml.transform.sax.SAXTransformerFactory

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.xml.transform.sax.TemplatesHandler (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.xml.transform.sax.TemplatesHandler

Packages that use TemplatesHandler
javax.xml.transform.sax This package implements SAX2-specific transformation APIs.

Uses of TemplatesHandler in javax.xml.transform.sax

Methods in javax.xml.transform.sax that return TemplatesHandler
abstract  TemplatesHandler SAXTransformerFactory.newTemplatesHandler()
Get a TemplatesHandler object that can process SAX ContentHandler events into a Templates object.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface javax.xml.transform.sax.TransformerHandler (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
javax.xml.transform.sax.TransformerHandler

Packages that use TransformerHandler
javax.xml.transform.sax This package implements SAX2-specific transformation APIs.

Uses of TransformerHandler in javax.xml.transform.sax

Methods in javax.xml.transform.sax that return TransformerHandler
abstract TransformerHandler | SAXTransformerFactory.newTransformerHandler(Source src) Get a TransformerHandler object that can process SAX ContentHandler events into a Result, based on the transformation instructions specified by the argument.
abstract TransformerHandler | SAXTransformerFactory.newTransformerHandler(Templates templates) Get a TransformerHandler object that can process SAX ContentHandler events into a Result, based on the Templates argument.
abstract TransformerHandler | SAXTransformerFactory.newTransformerHandler() Get a TransformerHandler object that can process SAX ContentHandler events into a Result.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


javax.xml.transform.stream (Java 2 Platform SE v1.4.2)

 javax.xml.transform.stream
Classes
StreamResult
StreamSource


javax.xml.transform.stream (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package javax.xml.transform.stream

This package implements stream- and URI- specific transformation APIs.

See:
Description

Class Summary
StreamResult | Acts as an holder for a transformation result, which may be XML, plain Text, HTML, or some other form of markup.
StreamSource | Acts as an holder for a transformation Source in the form of a stream of XML markup.

Package javax.xml.transform.stream Description

This package implements stream- and URI- specific transformation APIs.

The StreamSource class provides methods for specifying InputStream input, Reader input, and URL input in the form of strings. Even if an input stream or reader is specified as the source, StreamSource.setSystemId(java.lang.String) should still be called, so that the transformer can know from where it should resolve relative URIs. The public identifier is always optional: if the application writer includes one, it will be provided as part of the SourceLocator information.

The StreamResult class provides methods for specifying OutputStream, Writer, or an output system ID, as the output of the transformation result.

Normally streams should be used rather than readers or writers, for both the Source and Result, since readers and writers already have the encoding established to and from the internal Unicode format. However, there are times when it is useful to write to a character stream, such as when using a StringWriter in order to write to a String, or in the case of reading source XML from a StringReader.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


javax.xml.transform.stream Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package javax.xml.transform.stream

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class javax.xml.transform.stream.StreamResult (implements javax.xml.transform.Result)
    • class javax.xml.transform.stream.StreamSource (implements javax.xml.transform.Source)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package javax.xml.transform.stream (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
javax.xml.transform.stream

No usage of javax.xml.transform.stream

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


StreamResult (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.xml.transform.stream
Class StreamResult

java.lang.Object
    extended by javax.xml.transform.stream.StreamResult
All Implemented Interfaces:
Result
public class StreamResult
extends Object
implements Result

Acts as an holder for a transformation result, which may be XML, plain Text, HTML, or some other form of markup.

Field Summary
static String FEATURE
If TransformerFactory.getFeature(java.lang.String) returns true when passed this value as an argument, the Transformer supports Result output of this type.
Fields inherited from interface javax.xml.transform.Result
PI_DISABLE_OUTPUT_ESCAPING, PI_ENABLE_OUTPUT_ESCAPING
Constructor Summary
StreamResult()
Zero-argument default constructor.
StreamResult(File f)
Construct a StreamResult from a File.
StreamResult(OutputStream outputStream)
Construct a StreamResult from a byte stream.
StreamResult(String systemId)
Construct a StreamResult from a URL.
StreamResult(Writer writer)
Construct a StreamResult from a character stream.
Method Summary
OutputStream | getOutputStream() Get the byte stream that was set with setOutputStream.
String | getSystemId() Get the system identifier that was set with setSystemId.
Writer | getWriter() Get the character stream that was set with setWriter.
void | setOutputStream(OutputStream outputStream) Set the ByteStream that is to be written to.
void | setSystemId(File f) Set the system ID from a File reference.
void | setSystemId(String systemId) 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).
void | setWriter(Writer writer) Set the writer that is to receive the result.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

FEATURE

public static final String FEATURE
If TransformerFactory.getFeature(java.lang.String) returns true when passed this value as an argument, the Transformer supports Result output of this type.

See Also:
Constant Field Values
Constructor Detail

StreamResult

public StreamResult()
Zero-argument default constructor.

StreamResult

public StreamResult(OutputStream outputStream)
Construct a StreamResult from a byte stream. Normally, a stream should be used rather than a reader, so that the transformer may use instructions contained in the transformation instructions to control the encoding.

Parameters:
outputStream - A valid OutputStream reference.

StreamResult

public StreamResult(Writer writer)
Construct a StreamResult from a character stream. Normally, a stream should be used rather than a reader, so that the transformer may use instructions contained in the transformation instructions to control the encoding. However, there are times when it is useful to write to a character stream, such as when using a StringWriter.

Parameters:
writer - A valid Writer reference.

StreamResult

public StreamResult(String systemId)
Construct a StreamResult from a URL.

Parameters:
systemId - Must be a String that conforms to the URI syntax.

StreamResult

public StreamResult(File f)
Construct a StreamResult from a File.

Parameters:
f - Must a non-null File reference.
Method Detail

setOutputStream

public void setOutputStream(OutputStream outputStream)
Set the ByteStream that is to be written to. Normally, a stream should be used rather than a reader, so that the transformer may use instructions contained in the transformation instructions to control the encoding.

Parameters:
outputStream - A valid OutputStream reference.

getOutputStream

public OutputStream getOutputStream()
Get the byte stream that was set with setOutputStream.

Returns:
The byte stream that was set with setOutputStream, or null if setOutputStream or the ByteStream constructor was not called.

setWriter

public void setWriter(Writer writer)
Set the writer that is to receive the result. Normally, a stream should be used rather than a writer, so that the transformer may use instructions contained in the transformation instructions to control the encoding. However, there are times when it is useful to write to a writer, such as when using a StringWriter.

Parameters:
writer - A valid Writer reference.

getWriter

public Writer getWriter()
Get the character stream that was set with setWriter.

Returns:
The character stream that was set with setWriter, or null if setWriter or the Writer constructor was not called.

setSystemId

public void setSystemId(String systemId)
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).

Specified by:
setSystemId in interface Result
Parameters:
systemId - The system identifier as a URI string.

setSystemId

public void setSystemId(File f)
Set the system ID from a File reference.

Parameters:
f - Must a non-null File reference.

getSystemId

public String getSystemId()
Get the system identifier that was set with setSystemId.

Specified by:
getSystemId in interface Result
Returns:
The system identifier that was set with setSystemId, or null if setSystemId was not called.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


StreamSource (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.xml.transform.stream
Class StreamSource

java.lang.Object
    extended by javax.xml.transform.stream.StreamSource
All Implemented Interfaces:
Source
public class StreamSource
extends Object
implements Source

Acts as an holder for a transformation Source in the form of a stream of XML markup.

Field Summary
static String FEATURE
If TransformerFactory.getFeature(java.lang.String) returns true when passed this value as an argument, the Transformer supports Source input of this type.
Constructor Summary
StreamSource()
Zero-argument default constructor.
StreamSource(File f)
Construct a StreamSource from a File.
StreamSource(InputStream inputStream)
Construct a StreamSource from a byte stream.
StreamSource(InputStream inputStream, String systemId)
Construct a StreamSource from a byte stream.
StreamSource(Reader reader)
Construct a StreamSource from a character reader.
StreamSource(Reader reader, String systemId)
Construct a StreamSource from a character reader.
StreamSource(String systemId)
Construct a StreamSource from a URL.
Method Summary
InputStream | getInputStream() Get the byte stream that was set with setByteStream.
String | getPublicId() Get the public identifier that was set with setPublicId.
Reader | getReader() Get the character stream that was set with setReader.
String | getSystemId() Get the system identifier that was set with setSystemId.
void | setInputStream(InputStream inputStream) Set the byte stream to be used as input.
void | setPublicId(String publicId) Set the public identifier for this Source.
void | setReader(Reader reader) Set the input to be a character reader.
void | setSystemId(File f) Set the system ID from a File reference.
void | setSystemId(String systemId) Set the system identifier for this Source.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

FEATURE

public static final String FEATURE
If TransformerFactory.getFeature(java.lang.String) returns true when passed this value as an argument, the Transformer supports Source input of this type.

See Also:
Constant Field Values
Constructor Detail

StreamSource

public StreamSource()
Zero-argument default constructor. If this constructor is used, and no other method is called, the transformer will assume an empty input tree, with a default root node.

StreamSource

public StreamSource(InputStream inputStream)
Construct a StreamSource from a byte stream. Normally, a stream should be used rather than a reader, so the XML parser can resolve character encoding specified by the XML declaration.

If this constructor is used to process a stylesheet, normally setSystemId should also be called, so that relative URI references can be resolved.

Parameters:
inputStream - A valid InputStream reference to an XML stream.

StreamSource

public StreamSource(InputStream inputStream,
                    String systemId)
Construct a StreamSource from a byte stream. Normally, a stream should be used rather than a reader, so that the XML parser can resolve character encoding specified by the XML declaration.

This constructor allows the systemID to be set in addition to the input stream, which allows relative URIs to be processed.

Parameters:
inputStream - A valid InputStream reference to an XML stream.
systemId - Must be a String that conforms to the URI syntax.

StreamSource

public StreamSource(Reader reader)
Construct a StreamSource from a character reader. Normally, a stream should be used rather than a reader, so that the XML parser can resolve character encoding specified by the XML declaration. However, in many cases the encoding of the input stream is already resolved, as in the case of reading XML from a StringReader.

Parameters:
reader - A valid Reader reference to an XML character stream.

StreamSource

public StreamSource(Reader reader,
                    String systemId)
Construct a StreamSource from a character reader. Normally, a stream should be used rather than a reader, so that the XML parser may resolve character encoding specified by the XML declaration. However, in many cases the encoding of the input stream is already resolved, as in the case of reading XML from a StringReader.

Parameters:
reader - A valid Reader reference to an XML character stream.
systemId - Must be a String that conforms to the URI syntax.

StreamSource

public StreamSource(String systemId)
Construct a StreamSource from a URL.

Parameters:
systemId - Must be a String that conforms to the URI syntax.

StreamSource

public StreamSource(File f)
Construct a StreamSource from a File.

Parameters:
f - Must a non-null File reference.
Method Detail

setInputStream

public void setInputStream(InputStream inputStream)
Set the byte stream to be used as input. Normally, a stream should be used rather than a reader, so that the XML parser can resolve character encoding specified by the XML declaration.

If this Source object is used to process a stylesheet, normally setSystemId should also be called, so that relative URL references can be resolved.

Parameters:
inputStream - A valid InputStream reference to an XML stream.

getInputStream

public InputStream getInputStream()
Get the byte stream that was set with setByteStream.

Returns:
The byte stream that was set with setByteStream, or null if setByteStream or the ByteStream constructor was not called.

setReader

public void setReader(Reader reader)
Set the input to be a character reader. Normally, a stream should be used rather than a reader, so that the XML parser can resolve character encoding specified by the XML declaration. However, in many cases the encoding of the input stream is already resolved, as in the case of reading XML from a StringReader.

Parameters:
reader - A valid Reader reference to an XML CharacterStream.

getReader

public Reader getReader()
Get the character stream that was set with setReader.

Returns:
The character stream that was set with setReader, or null if setReader or the Reader constructor was not called.

setPublicId

public void setPublicId(String publicId)
Set the public identifier for this Source.

The public identifier is always optional: if the application writer includes one, it will be provided as part of the location information.

Parameters:
publicId - The public identifier as a string.

getPublicId

public String getPublicId()
Get the public identifier that was set with setPublicId.

Returns:
The public identifier that was set with setPublicId, or null if setPublicId was not called.

setSystemId

public void setSystemId(String systemId)
Set the system identifier for this Source.

The system identifier is optional if there is a byte stream or a character stream, but it is still useful to provide one, since the application can use it to resolve relative URIs and can include it in error messages and warnings (the parser will attempt to open a connection to the URI only if there is no byte stream or character stream specified).

Specified by:
setSystemId in interface Source
Parameters:
systemId - The system identifier as a URL string.

getSystemId

public String getSystemId()
Get the system identifier that was set with setSystemId.

Specified by:
getSystemId in interface Source
Returns:
The system identifier that was set with setSystemId, or null if setSystemId was not called.

setSystemId

public void setSystemId(File f)
Set the system ID from a File reference.

Parameters:
f - Must a non-null File reference.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Uses of Class javax.xml.transform.stream.StreamResult (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.xml.transform.stream.StreamResult

No usage of javax.xml.transform.stream.StreamResult

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class javax.xml.transform.stream.StreamSource (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
javax.xml.transform.stream.StreamSource

No usage of javax.xml.transform.stream.StreamSource

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


ChannelBinding (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.ietf.jgss
Class ChannelBinding

java.lang.Object
    extended by org.ietf.jgss.ChannelBinding
public class ChannelBinding
extends Object

This class encapsulates the concept of caller-provided channel binding information. Channel bindings are used to strengthen the quality with which peer entity authentication is provided during context establishment. They enable the GSS-API callers to bind the establishment of the security context to relevant characteristics like addresses or to application specific data.

The caller initiating the security context must determine the appropriate channel binding values to set in the GSSContext object. The acceptor must provide an identical binding in order to validate that received tokens possess correct channel-related characteristics.

Use of channel bindings is optional in GSS-API. ChannelBinding can be set for the GSSContext using the setChannelBinding method before the first call to initSecContext or acceptSecContext has been performed. Unless the setChannelBinding method has been used to set the ChannelBinding for a GSSContext object, null ChannelBinding will be assumed.

Conceptually, the GSS-API concatenates the initiator and acceptor address information, and the application supplied byte array to form an octet string. The mechanism calculates a MIC over this octet string and binds the MIC to the context establishment token emitted by initSecContext method of the GSSContext interface. The same bindings are set by the context acceptor for its GSSContext object and during processing of the acceptSecContext method a MIC is calculated in the same way. The calculated MIC is compared with that found in the token, and if the MICs differ, accept will throw a GSSException with the major code set to BAD_BINDINGS, and the context will not be established. Some mechanisms may include the actual channel binding data in the token (rather than just a MIC); applications should therefore not use confidential data as channel-binding components.

Individual mechanisms may impose additional constraints on addresses that may appear in channel bindings. For example, a mechanism may verify that the initiator address field of the channel binding contains the correct network address of the host system. Portable applications should therefore ensure that they either provide correct information for the address fields, or omit setting of the addressing information.

Since:
1.4

Constructor Summary
ChannelBinding(byte[] appData)
Creates a ChannelBinding object without any addressing information.
ChannelBinding(InetAddress initAddr, InetAddress acceptAddr, byte[] appData)
Create a ChannelBinding object with user supplied address information and data.
Method Summary
boolean | equals(Object obj) Compares two instances of ChannelBinding.
InetAddress | getAcceptorAddress() Get the acceptor's address for this channel binding.
byte[] | getApplicationData() Get the application specified data for this channel binding.
InetAddress | getInitiatorAddress() Get the initiator's address for this channel binding.
int | hashCode() Returns a hashcode value for this ChannelBinding object.
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ChannelBinding

public ChannelBinding(InetAddress initAddr,
                      InetAddress acceptAddr,
                      byte[] appData)
Create a ChannelBinding object with user supplied address information and data. null values can be used for any fields which the application does not want to specify.

Parameters:
initAddr - the address of the context initiator. null value can be supplied to indicate that the application does not want to set this value.
acceptAddr - the address of the context acceptor. null value can be supplied to indicate that the application does not want to set this value.
appData - application supplied data to be used as part of the channel bindings. null value can be supplied to indicate that the application does not want to set this value.

ChannelBinding

public ChannelBinding(byte[] appData)
Creates a ChannelBinding object without any addressing information.

Parameters:
appData - application supplied data to be used as part of the channel bindings.
Method Detail

getInitiatorAddress

public InetAddress getInitiatorAddress()
Get the initiator's address for this channel binding.

Returns:
the initiator's address. null is returned if the address has not been set.

getAcceptorAddress

public InetAddress getAcceptorAddress()
Get the acceptor's address for this channel binding.

Returns:
the acceptor's address. null is returned if the address has not been set.

getApplicationData

public byte[] getApplicationData()
Get the application specified data for this channel binding.

Returns:
the application data being used as part of the ChannelBinding. null is returned if no application data has been specified for the channel binding.

equals

public boolean equals(Object obj)
Compares two instances of ChannelBinding.

Overrides:
equals in class Object
Parameters:
obj - another ChannelBinding to compare this one with
Returns:
true if the two ChannelBinding's contain the same values for the initiator and acceptor addresses and the application data.
See Also:
Object.hashCode(), Hashtable

hashCode

public int hashCode()
Returns a hashcode value for this ChannelBinding object.

Overrides:
hashCode in class Object
Returns:
a hashCode value
See Also:
Object.equals(java.lang.Object), Hashtable
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


GSSContext (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.ietf.jgss
Interface GSSContext

public interface GSSContext

This interface encapsulates the GSS-API security context and provides the security services that are available over the context. Security contexts are established between peers using locally acquired credentials. Multiple contexts may exist simultaneously between a pair of peers, using the same or different set of credentials. GSS-API functions in a manner independent of the underlying transport protocol and depends on its calling application to transport the tokens that are generated by the security context between the peers.

If the caller instantiates the context using the default GSSManager instance, then the Kerberos v5 GSS-API mechanism is guaranteed to be available for context establishment. This mechanism is identified by the Oid "1.2.840.113554.1.2.2" and is defined in RFC 1964.

Before the context establishment phase is initiated, the context initiator may request specific characteristics desired of the established context. Not all underlying mechanisms support all characteristics that a caller might desire. After the context is established, the caller can check the actual characteristics and services offered by that context by means of various query methods. When using the Kerberos v5 GSS-API mechanism offered by the default GSSManager instance, all optional services will be available locally. They are mutual authentication, credential delegation, confidentiality and integrity protection, and per-message replay detection and sequencing. Note that in the GSS-API, message integrity is a prerequisite for message confidentiality.

The context establishment occurs in a loop where the initiator calls initSecContext and the acceptor calls acceptSecContext until the context is established. While in this loop the initSecContext and acceptSecContext methods produce tokens that the application sends over to the peer. The peer passes any such token as input to its acceptSecContext or initSecContext as the case may be.

During the context establishment phase, the isProtReady method may be called to determine if the context can be used for the per-message operations of wrap and getMIC. This allows applications to use per-message operations on contexts which aren't yet fully established.

After the context has been established or the isProtReady method returns true, the query routines can be invoked to determine the actual characteristics and services of the established context. The application can also start using the per-message methods of wrap and getMIC to obtain cryptographic operations on application supplied data.

When the context is no longer needed, the application should call dispose to release any system resources the context may be using.

A security context typically maintains sequencing and replay detection information about the tokens it processes. Therefore, the sequence in which any tokens are presented to this context for processing can be important. Also note that none of the methods in this interface are synchronized. Therefore, it is not advisable to share a GSSContext among several threads unless some application level synchronization is in place.

Finally, different mechanism providers might place different security restrictions on using GSS-API contexts. These will be documented by the mechanism provider. The application will need to ensure that it has the appropriate permissions if such checks are made in the mechanism layer.

The example code presented below demonstrates the usage of the GSSContext interface for the initiating peer. Different operations on the GSSContext object are presented, including: object instantiation, setting of desired flags, context establishment, query of actual context flags, per-message operations on application data, and finally context deletion.

    // Create a context using default credentials
    // and the implementation specific default mechanism
    GSSManager manager ...
    GSSName targetName ...
    GSSContext context = manager.createContext(targetName, null, null,
                                           GSSContext.INDEFINITE_LIFETIME);

    // set desired context options prior to context establishment
    context.requestConf(true);
    context.requestMutualAuth(true);
    context.requestReplayDet(true);
    context.requestSequenceDet(true);

    // establish a context between peers

    byte []inToken = new byte[0];

    // Loop while there still is a token to be processed

    while (!context.isEstablished()) {

        byte[] outToken
            = context.initSecContext(inToken, 0, inToken.length);

        // send the output token if generated
        if (outToken != null)
            sendToken(outToken);

        if (!context.isEstablished()) {
            inToken = readToken();
    }

     // display context information
     System.out.println("Remaining lifetime in seconds = "
                                          + context.getLifetime());
     System.out.println("Context mechanism = " + context.getMech());
     System.out.println("Initiator = " + context.getSrcName());
     System.out.println("Acceptor = " + context.getTargName());

     if (context.getConfState())
             System.out.println("Confidentiality (i.e., privacy) is available");

     if (context.getIntegState())
             System.out.println("Integrity is available");

     // perform wrap on an application supplied message, appMsg,
     // using QOP = 0, and requesting privacy service
     byte [] appMsg ...

     MessageProp mProp = new MessageProp(0, true);

     byte []tok = context.wrap(appMsg, 0, appMsg.length, mProp);

     sendToken(tok);

     // release the local-end of the context
     context.dispose();

Since:
1.4

Field Summary
static int | DEFAULT_LIFETIME A lifetime constant representing the default context lifetime.
static int | INDEFINITE_LIFETIME A lifetime constant representing indefinite context lifetime.
Method Summary
byte[] | acceptSecContext(byte[] inToken, int offset, int len) Called by the context acceptor upon receiving a token from the peer.
void | acceptSecContext(InputStream inStream, OutputStream outStream) Called by the context acceptor to process a token from the peer using streams.
void | dispose() Releases any system resources and cryptographic information stored in the context object and invalidates the context.
byte[] | export() Exports this context so that another process may import it..
boolean | getAnonymityState() Determines if the context initiator is anonymously authenticated to the context acceptor.
boolean | getConfState() Determines if data confidentiality is available over the context.
boolean | getCredDelegState() Determines if credential delegation is enabled on this context.
GSSCredential | getDelegCred() Obtains the credentials delegated by the context initiator to the context acceptor.
boolean | getIntegState() Determines if data integrity is available over the context.
int | getLifetime() Determines what the remaining lifetime for this context is.
Oid | getMech() Determines what mechanism is being used for this context.
byte[] | getMIC(byte[] inMsg, int offset, int len, MessageProp msgProp) Returns a token containing a cryptographic Message Integrity Code (MIC) for the supplied message, for transfer to the peer application.
void | getMIC(InputStream inStream, OutputStream outStream, MessageProp msgProp) Uses streams to produce a token containing a cryptographic MIC for the supplied message, for transfer to the peer application.
boolean | getMutualAuthState() Determines if mutual authentication is enabled on this context.
boolean | getReplayDetState() Determines if replay detection is enabled for the per-message security services from this context.
boolean | getSequenceDetState() Determines if sequence checking is enabled for the per-message security services from this context.
GSSName | getSrcName() Returns the name of the context initiator.
GSSName | getTargName() Returns the name of the context acceptor.
int | getWrapSizeLimit(int qop, boolean confReq, int maxTokenSize) Used to determine limits on the size of the message that can be passed to wrap.
byte[] | initSecContext(byte[] inputBuf, int offset, int len) Called by the context initiator to start the context creation phase and process any tokens generated by the peer's acceptSecContext method.
int | initSecContext(InputStream inStream, OutputStream outStream) Called by the context initiator to start the context creation phase and process any tokens generated by the peer's acceptSecContext method using streams.
boolean | isEstablished() Used during context establishment to determine the state of the context.
boolean | isInitiator() Determines if this is the context initiator.
boolean | isProtReady() Determines if the context is ready for per message operations to be used over it.
boolean | isTransferable() Determines if the context is transferable to other processes through the use of the export method.
void | requestAnonymity(boolean state) Requests that the initiator's identity not be disclosed to the acceptor.
void | requestConf(boolean state) Requests that data confidentiality be enabled for the wrap method.
void | requestCredDeleg(boolean state) Requests that the initiator's credentials be delegated to the acceptor during context establishment.
void | requestInteg(boolean state) Requests that data integrity be enabled for the wrap and getMICmethods.
void | requestLifetime(int lifetime) Requests a lifetime in seconds for the context.
void | requestMutualAuth(boolean state) Requests that mutual authentication be done during context establishment.
void | requestReplayDet(boolean state) Requests that replay detection be enabled for the per-message security services after context establishemnt.
void | requestSequenceDet(boolean state) Requests that sequence checking be enabled for the per-message security services after context establishemnt.
void | setChannelBinding(ChannelBinding cb) Sets the channel bindings to be used during context establishment.
byte[] | unwrap(byte[] inBuf, int offset, int len, MessageProp msgProp) Used to process tokens generated by the wrap method on the other side of the context.
void | unwrap(InputStream inStream, OutputStream outStream, MessageProp msgProp) Uses streams to process tokens generated by the wrap method on the other side of the context.
void | verifyMIC(byte[] inToken, int tokOffset, int tokLen, byte[] inMsg, int msgOffset, int msgLen, MessageProp msgProp) Verifies the cryptographic MIC, contained in the token parameter, over the supplied message.
void | verifyMIC(InputStream tokStream, InputStream msgStream, MessageProp msgProp) Uses streams to verify the cryptographic MIC, contained in the token parameter, over the supplied message.
byte[] | wrap(byte[] inBuf, int offset, int len, MessageProp msgProp) Applies per-message security services over the established security context.
void | wrap(InputStream inStream, OutputStream outStream, MessageProp msgProp) Applies per-message security services over the established security context using streams.

Field Detail

DEFAULT_LIFETIME

public static final int DEFAULT_LIFETIME
A lifetime constant representing the default context lifetime. This value is set to 0.

See Also:
Constant Field Values

INDEFINITE_LIFETIME

public static final int INDEFINITE_LIFETIME
A lifetime constant representing indefinite context lifetime. This value must is set to the maximum integer value in Java - Integer.MAX_VALUE.

See Also:
Constant Field Values
Method Detail

initSecContext

public byte[] initSecContext(byte[] inputBuf,
                             int offset,
                             int len)
                      throws GSSException
Called by the context initiator to start the context creation phase and process any tokens generated by the peer's acceptSecContext method. This method may return an output token which the application will need to send to the peer for processing by its acceptSecContext method. The application can call isEstablished to determine if the context establishment phase is complete on this side of the context. A return value of false from isEstablished indicates that more tokens are expected to be supplied to initSecContext. Upon completion of the context establishment, the available context options may be queried through the get methods.

Note that it is possible that the initSecContext method return a token for the peer, and isEstablished return true also. This indicates that the token needs to be sent to the peer, but the local end of the context is now fully established.

Some mechanism providers might require that the caller be granted permission to initiate a security context. A failed permission check might cause a SecurityException to be thrown from this method.

Parameters:
inputBuf - token generated by the peer. This parameter is ignored on the first call since no token has been received from the peer.
offset - the offset within the inputBuf where the token begins.
len - the length of the token.
Returns:
a byte[] containing the token to be sent to the peer. null indicates that no token is generated.
Throws:
GSSException - containing the following major error codes: GSSException.DEFECTIVE_TOKEN, GSSException.BAD_MIC, GSSException.NO_CRED, GSSException.CREDENTIALS_EXPIRED, GSSException.BAD_BINDINGS, GSSException.OLD_TOKEN, GSSException.DUPLICATE_TOKEN, GSSException.BAD_NAMETYPE, GSSException.BAD_MECH, GSSException.FAILURE

initSecContext

public int initSecContext(InputStream inStream,
                          OutputStream outStream)
                   throws GSSException
Called by the context initiator to start the context creation phase and process any tokens generated by the peer's acceptSecContext method using streams. This method may write an output token to the OutpuStream, which the application will need to send to the peer for processing by its acceptSecContext call. Typically, the application would ensure this by calling the flush method on an OutputStream that encapsulates the connection between the two peers. The application can determine if a token is written to the OutputStream from the return value of this method. A return value of 0 indicates that no token was written. The application can call isEstablished to determine if the context establishment phase is complete on this side of the context. A return value of false from isEstablished indicates that more tokens are expected to be supplied to initSecContext. Upon completion of the context establishment, the available context options may be queried through the get methods.

Note that it is possible that the initSecContext method return a token for the peer, and isEstablished return true also. This indicates that the token needs to be sent to the peer, but the local end of the context is now fully established.

The GSS-API authentication tokens contain a definitive start and end. This method will attempt to read one of these tokens per invocation, and may block on the stream if only part of the token is available. In all other respects this method is equivalent to the byte array based initSecContext.

Some mechanism providers might require that the caller be granted permission to initiate a security context. A failed permission check might cause a SecurityException to be thrown from this method.

The following example code demonstrates how this method might be used:

     InputStream is ...
     OutputStream os ...
     GSSContext context ...

     // Loop while there is still a token to be processed

     while (!context.isEstablished()) {

         context.initSecContext(is, os);

         // send output token if generated
         os.flush();
     }

Parameters:
inStream - an InputStream that contains the token generated by the peer. This parameter is ignored on the first call since no token has been or will be received from the peer at that point.
outStream - an OutputStream where the output token will be written. During the final stage of context establishment, there may be no bytes written.
Returns:
the number of bytes written to the OutputStream as part of the token to be sent to the peer. A value of 0 indicates that no token needs to be sent.
Throws:
GSSException - containing the following major error codes: GSSException.DEFECTIVE_TOKEN, GSSException.BAD_MIC, GSSException.NO_CRED, GSSException.CREDENTIALS_EXPIRED, GSSException.BAD_BINDINGS, GSSException.OLD_TOKEN, GSSException.DUPLICATE_TOKEN, GSSException.BAD_NAMETYPE, GSSException.BAD_MECH, GSSException.FAILURE

acceptSecContext

public byte[] acceptSecContext(byte[] inToken,
                               int offset,
                               int len)
                        throws GSSException
Called by the context acceptor upon receiving a token from the peer. This method may return an output token which the application will need to send to the peer for further processing by its initSecContext call.

The application can call isEstablished to determine if the context establishment phase is complete for this peer. A return value of false from isEstablished indicates that more tokens are expected to be supplied to this method. Upon completion of the context establishment, the available context options may be queried through the get methods.

Note that it is possible that acceptSecContext return a token for the peer, and isEstablished return true also. This indicates that the token needs to be sent to the peer, but the local end of the context is now fully established.

Some mechanism providers might require that the caller be granted permission to accept a security context. A failed permission check might cause a SecurityException to be thrown from this method.

The following example code demonstrates how this method might be used:

     byte[] inToken;
     byte[] outToken;
     GSSContext context ...

     // Loop while there is still a token to be processed

     while (!context.isEstablished()) {
         inToken = readToken();
         outToken = context.acceptSecContext(inToken, 0,
                                             inToken.length);
         // send output token if generated
         if (outToken != null)
             sendToken(outToken);
     }

Parameters:
inToken - token generated by the peer.
offset - the offset within the inToken where the token begins.
len - the length of the token.
Returns:
a byte[] containing the token to be sent to the peer. null indicates that no token is generated.
Throws:
GSSException - containing the following major error codes: GSSException.DEFECTIVE_TOKEN, GSSException.BAD_MIC, GSSException.NO_CRED, GSSException.CREDENTIALS_EXPIRED, GSSException.BAD_BINDINGS, GSSException.OLD_TOKEN, GSSException.DUPLICATE_TOKEN, GSSException.BAD_MECH, GSSException.FAILURE

acceptSecContext

public void acceptSecContext(InputStream inStream,
                             OutputStream outStream)
                      throws GSSException
Called by the context acceptor to process a token from the peer using streams. It may write an output token to the OutputStream, which the application will need to send to the peer for processing by its initSecContext method. Typically, the application would ensure this by calling the flush method on an OutputStream that encapsulates the connection between the two peers. The application can call isEstablished to determine if the context establishment phase is complete on this side of the context. A return value of false from isEstablished indicates that more tokens are expected to be supplied to acceptSecContext. Upon completion of the context establishment, the available context options may be queried through the get methods.

Note that it is possible that acceptSecContext return a token for the peer, and isEstablished return true also. This indicates that the token needs to be sent to the peer, but the local end of the context is now fully established.

The GSS-API authentication tokens contain a definitive start and end. This method will attempt to read one of these tokens per invocation, and may block on the stream if only part of the token is available. In all other respects this method is equivalent to the byte array based acceptSecContext.

Some mechanism providers might require that the caller be granted permission to accept a security context. A failed permission check might cause a SecurityException to be thrown from this method.

The following example code demonstrates how this method might be used:

     InputStream is ...
     OutputStream os ...
     GSSContext context ...

     // Loop while there is still a token to be processed

     while (!context.isEstablished()) {

         context.acceptSecContext(is, os);

         // send output token if generated
         os.flush();
     }

Parameters:
inStream - an InputStream that contains the token generated by the peer.
outStream - an OutputStream where the output token will be written. During the final stage of context establishment, there may be no bytes written.
Throws:
GSSException - containing the following major error codes: GSSException.DEFECTIVE_TOKEN, GSSException.BAD_MIC, GSSException.NO_CRED, GSSException.CREDENTIALS_EXPIRED, GSSException.BAD_BINDINGS, GSSException.OLD_TOKEN, GSSException.DUPLICATE_TOKEN, GSSException.BAD_MECH, GSSException.FAILURE

isEstablished

public boolean isEstablished()
Used during context establishment to determine the state of the context.

Returns:
true if this is a fully established context on the caller's side and no more tokens are needed from the peer.

dispose

public void dispose()
             throws GSSException
Releases any system resources and cryptographic information stored in the context object and invalidates the context.

Throws:
GSSException - containing the following major error codes: GSSException.FAILURE

getWrapSizeLimit

public int getWrapSizeLimit(int qop,
                            boolean confReq,
                            int maxTokenSize)
                     throws GSSException
Used to determine limits on the size of the message that can be passed to wrap. Returns the maximum message size that, if presented to the wrap method with the same confReq and qop parameters, will result in an output token containing no more than maxTokenSize bytes.

This call is intended for use by applications that communicate over protocols that impose a maximum message size. It enables the application to fragment messages prior to applying protection.

GSS-API implementations are recommended but not required to detect invalid QOP values when getWrapSizeLimit is called. This routine guarantees only a maximum message size, not the availability of specific QOP values for message protection.

Parameters:
qop - the level of protection wrap will be asked to provide.
confReq - true if wrap will be asked to provide privacy, false otherwise.
maxTokenSize - the desired maximum size of the token emitted by wrap.
Returns:
the maximum size of the input token for the given output token size
Throws:
GSSException - containing the following major error codes: GSSException.CONTEXT_EXPIRED, GSSException.BAD_QOP, GSSException.FAILURE

wrap

public byte[] wrap(byte[] inBuf,
                   int offset,
                   int len,
                   MessageProp msgProp)
            throws GSSException
Applies per-message security services over the established security context. The method will return a token with the application supplied data and a cryptographic MIC over it. The data may be encrypted if confidentiality (privacy) was requested.

The MessageProp object is instantiated by the application and used to specify a QOP value which selects cryptographic algorithms, and a privacy service to optionally encrypt the message. The underlying mechanism that is used in the call may not be able to provide the privacy service. It sets the actual privacy service that it does provide in this MessageProp object which the caller should then query upon return. If the mechanism is not able to provide the requested QOP, it throws a GSSException with the BAD_QOP code.

Since some application-level protocols may wish to use tokens emitted by wrap to provide "secure framing", implementations should support the wrapping of zero-length messages.

The application will be responsible for sending the token to the peer.

Parameters:
inBuf - application data to be protected.
offset - the offset within the inBuf where the data begins.
len - the length of the data
msgProp - instance of MessageProp that is used by the application to set the desired QOP and privacy state. Set the desired QOP to 0 to request the default QOP. Upon return from this method, this object will contain the the actual privacy state that was applied to the message by the underlying mechanism.
Returns:
a byte[] containing the token to be sent to the peer.
Throws:
GSSException - containing the following major error codes: GSSException.CONTEXT_EXPIRED, GSSException.BAD_QOP, GSSException.FAILURE

wrap

public void wrap(InputStream inStream,
                 OutputStream outStream,
                 MessageProp msgProp)
          throws GSSException
Applies per-message security services over the established security context using streams. The method will return a token with the application supplied data and a cryptographic MIC over it. The data may be encrypted if confidentiality (privacy) was requested. This method is equivalent to the byte array based wrap method.

The application will be responsible for sending the token to the peer. Typically, the application would ensure this by calling the flush method on an OutputStream that encapsulates the connection between the two peers.

The MessageProp object is instantiated by the application and used to specify a QOP value which selects cryptographic algorithms, and a privacy service to optionally encrypt the message. The underlying mechanism that is used in the call may not be able to provide the privacy service. It sets the actual privacy service that it does provide in this MessageProp object which the caller should then query upon return. If the mechanism is not able to provide the requested QOP, it throws a GSSException with the BAD_QOP code.

Since some application-level protocols may wish to use tokens emitted by wrap to provide "secure framing", implementations should support the wrapping of zero-length messages.

Parameters:
inStream - an InputStream containing the application data to be protected. All of the data that is available in inStream is used.
outStream - an OutputStream to write the protected message to.
msgProp - instance of MessageProp that is used by the application to set the desired QOP and privacy state. Set the desired QOP to 0 to request the default QOP. Upon return from this method, this object will contain the the actual privacy state that was applied to the message by the underlying mechanism.
Throws:
GSSException - containing the following major error codes: GSSException.CONTEXT_EXPIRED, GSSException.BAD_QOP, GSSException.FAILURE

unwrap

public byte[] unwrap(byte[] inBuf,
                     int offset,
                     int len,
                     MessageProp msgProp)
              throws GSSException
Used to process tokens generated by the wrap method on the other side of the context. The method will return the message supplied by the peer application to its wrap call, while at the same time verifying the embedded MIC for that message.

The MessageProp object is instantiated by the application and is used by the underlying mechanism to return information to the caller such as the QOP, whether confidentiality was applied to the message, and other supplementary message state information.

Since some application-level protocols may wish to use tokens emitted by wrap to provide "secure framing", implementations should support the wrapping and unwrapping of zero-length messages.

Parameters:
inBuf - a byte array containing the wrap token received from peer.
offset - the offset where the token begins.
len - the length of the token
msgProp - upon return from the method, this object will contain the applied QOP, the privacy state of the message, and supplementary information stating if the token was a duplicate, old, out of sequence or arriving after a gap.
Returns:
a byte[] containing the message unwrapped from the input token.
Throws:
GSSException - containing the following major error codes: GSSException.DEFECTIVE_TOKEN, GSSException.BAD_MIC, GSSException.CONTEXT_EXPIRED, GSSException.FAILURE

unwrap

public void unwrap(InputStream inStream,
                   OutputStream outStream,
                   MessageProp msgProp)
            throws GSSException
Uses streams to process tokens generated by the wrap method on the other side of the context. The method will return the message supplied by the peer application to its wrap call, while at the same time verifying the embedded MIC for that message.

The MessageProp object is instantiated by the application and is used by the underlying mechanism to return information to the caller such as the QOP, whether confidentiality was applied to the message, and other supplementary message state information.

Since some application-level protocols may wish to use tokens emitted by wrap to provide "secure framing", implementations should support the wrapping and unwrapping of zero-length messages.

The format of the input token that this method reads is defined in the specification for the underlying mechanism that will be used. This method will attempt to read one of these tokens per invocation. If the mechanism token contains a definitive start and end this method may block on the InputStream if only part of the token is available. If the start and end of the token are not definitive then the method will attempt to treat all available bytes as part of the token.

Other than the possible blocking behaviour described above, this method is equivalent to the byte array based unwrap method.

Parameters:
inStream - an InputStream that contains the wrap token generated by the peer.
outStream - an OutputStream to write the application message to.
msgProp - upon return from the method, this object will contain the applied QOP, the privacy state of the message, and supplementary information stating if the token was a duplicate, old, out of sequence or arriving after a gap.
Throws:
GSSException - containing the following major error codes: GSSException.DEFECTIVE_TOKEN, GSSException.BAD_MIC, GSSException.CONTEXT_EXPIRED, GSSException.FAILURE

getMIC

public byte[] getMIC(byte[] inMsg,
                     int offset,
                     int len,
                     MessageProp msgProp)
              throws GSSException
Returns a token containing a cryptographic Message Integrity Code (MIC) for the supplied message, for transfer to the peer application. Unlike wrap, which encapsulates the user message in the returned token, only the message MIC is returned in the output token.

Note that privacy can only be applied through the wrap call.

Since some application-level protocols may wish to use tokens emitted by getMIC to provide "secure framing", implementations should support derivation of MICs from zero-length messages.

Parameters:
inMsg - the message to generate the MIC over.
offset - offset within the inMsg where the message begins.
len - the length of the message
msgProp - an instance of MessageProp that is used by the application to set the desired QOP. Set the desired QOP to 0 in msgProp to request the default QOP. Alternatively pass in null for msgProp to request the default QOP.
Returns:
a byte[] containing the token to be sent to the peer.
Throws:
GSSException - containing the following major error codes: GSSException.CONTEXT_EXPIRED, GSSException.BAD_QOP, GSSException.FAILURE

getMIC

public void getMIC(InputStream inStream,
                   OutputStream outStream,
                   MessageProp msgProp)
            throws GSSException
Uses streams to produce a token containing a cryptographic MIC for the supplied message, for transfer to the peer application. Unlike wrap, which encapsulates the user message in the returned token, only the message MIC is produced in the output token. This method is equivalent to the byte array based getMIC method. Note that privacy can only be applied through the wrap call.

Since some application-level protocols may wish to use tokens emitted by getMIC to provide "secure framing", implementations should support derivation of MICs from zero-length messages.

Parameters:
inStream - an InputStream containing the message to generate the MIC over. All of the data that is available in inStream is used.
outStream - an OutputStream to write the output token to.
msgProp - an instance of MessageProp that is used by the application to set the desired QOP. Set the desired QOP to 0 in msgProp to request the default QOP. Alternatively pass in null for msgProp to request the default QOP.
Throws:
GSSException - containing the following major error codes: GSSException.CONTEXT_EXPIRED, GSSException.BAD_QOP, GSSException.FAILURE

verifyMIC

public void verifyMIC(byte[] inToken,
                      int tokOffset,
                      int tokLen,
                      byte[] inMsg,
                      int msgOffset,
                      int msgLen,
                      MessageProp msgProp)
               throws GSSException
Verifies the cryptographic MIC, contained in the token parameter, over the supplied message.

The MessageProp object is instantiated by the application and 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 and other supplementary message state information.

Since some application-level protocols may wish to use tokens emitted by getMIC to provide "secure framing", implementations should support the calculation and verification of MICs over zero-length messages.

Parameters:
inToken - the token generated by peer's getMIC method.
tokOffset - the offset within the inToken where the token begins.
tokLen - the length of the token.
inMsg - the application message to verify the cryptographic MIC over.
msgOffset - the offset in inMsg where the message begins.
msgLen - the length of the message.
msgProp - upon return from the method, this object will contain the applied QOP and supplementary information stating if the token was a duplicate, old, out of sequence or arriving after a gap.
Throws:
GSSException - containing the following major error codes: GSSException.DEFECTIVE_TOKEN GSSException.BAD_MIC GSSException.CONTEXT_EXPIRED GSSException.FAILURE

verifyMIC

public void verifyMIC(InputStream tokStream,
                      InputStream msgStream,
                      MessageProp msgProp)
               throws GSSException
Uses streams to verify the cryptographic MIC, contained in the token parameter, over the supplied message. This method is equivalent to the byte array based verifyMIC method. The MessageProp object is instantiated by the application and 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 and other supplementary message state information.

Since some application-level protocols may wish to use tokens emitted by getMIC to provide "secure framing", implementations should support the calculation and verification of MICs over zero-length messages.

The format of the input token that this method reads is defined in the specification for the underlying mechanism that will be used. This method will attempt to read one of these tokens per invocation. If the mechanism token contains a definitive start and end this method may block on the InputStream if only part of the token is available. If the start and end of the token are not definitive then the method will attempt to treat all available bytes as part of the token.

Other than the possible blocking behaviour described above, this method is equivalent to the byte array based verifyMIC method.

Parameters:
tokStream - an InputStream containing the token generated by the peer's getMIC method.
msgStream - an InputStream containing the application message to verify the cryptographic MIC over. All of the data that is available in msgStream is used.
msgProp - upon return from the method, this object will contain the applied QOP and supplementary information stating if the token was a duplicate, old, out of sequence or arriving after a gap.
Throws:
GSSException - containing the following major error codes: GSSException.DEFECTIVE_TOKEN GSSException.BAD_MIC GSSException.CONTEXT_EXPIRED GSSException.FAILURE

export

public byte[] export()
              throws GSSException
Exports this context so that another process may import it.. Provided to support the sharing of work between multiple processes. This routine will typically be used by the context-acceptor, in an application where a single process receives incoming connection requests and accepts security contexts over them, then passes the established context to one or more other processes for message exchange.

This method deactivates the security context and creates an interprocess token which, when passed to GSSManager.createContext in another process, will re-activate the context in the second process. Only a single instantiation of a given context may be active at any one time; a subsequent attempt by a context exporter to access the exported security context will fail.

The implementation may constrain the set of processes by which the interprocess token may be imported, either as a function of local security policy, or as a result of implementation decisions. For example, some implementations may constrain contexts to be passed only between processes that run under the same account, or which are part of the same process group.

The interprocess token may contain security-sensitive information (for example cryptographic keys). While mechanisms are encouraged to either avoid placing such sensitive information within interprocess tokens, or to encrypt the token before returning it to the application, in a typical GSS-API implementation this may not be possible. Thus the application must take care to protect the interprocess token, and ensure that any process to which the token is transferred is trustworthy.

Implementations are not required to support the inter-process transfer of security contexts. Calling the isTransferable method will indicate if the context object is transferable.

Calling this method on a context that is not exportable will result in this exception being thrown with the error code GSSException.UNAVAILABLE.

Returns:
a byte[] containing the exported context
Throws:
GSSException - containing the following major error codes: GSSException.UNAVAILABLE, GSSException.CONTEXT_EXPIRED, GSSException.NO_CONTEXT, GSSException.FAILURE
See Also:
GSSManager.createContext(byte[])

requestMutualAuth

public void requestMutualAuth(boolean state)
                       throws GSSException
Requests that mutual authentication be done during context establishment. This request can only be made on the context initiator's side and it has to be done prior to the first call to initSecContext.

Not all mechanisms support mutual authentication and some mechanisms might require mutual authentication even if the application doesn't. Therefore, the application should check to see if the request was honored with the getMutualAuthState method.

Parameters:
state - a boolean value indicating whether mutual authentication shouls be used or not.
Throws:
GSSException - containing the following major error codes: GSSException.FAILURE
See Also:
getMutualAuthState()

requestReplayDet

public void requestReplayDet(boolean state)
                      throws GSSException
Requests that replay detection be enabled for the per-message security services after context establishemnt. This request can only be made on the context initiator's side and it has to be done prior to the first call to initSecContext. During context establishment replay detection is not an option and is a function of the underlying mechanism's capabilities.

Not all mechanisms support replay detection and some mechanisms might require replay detection even if the application doesn't. Therefore, the application should check to see if the request was honored with the getReplayDetState method. If replay detection is enabled then the MessageProp.isDuplicateToken and MessageProp.isOldToken methods will return valid results for the MessageProp object that is passed in to the unwrap method or the verifyMIC method.

Parameters:
state - a boolean value indicating whether replay detection should be enabled over the established context or not.
Throws:
GSSException - containing the following major error codes: GSSException.FAILURE
See Also:
getReplayDetState()

requestSequenceDet

public void requestSequenceDet(boolean state)
                        throws GSSException
Requests that sequence checking be enabled for the per-message security services after context establishemnt. This request can only be made on the context initiator's side and it has to be done prior to the first call to initSecContext. During context establishment sequence checking is not an option and is a function of the underlying mechanism's capabilities.

Not all mechanisms support sequence checking and some mechanisms might require sequence checking even if the application doesn't. Therefore, the application should check to see if the request was honored with the getSequenceDetState method. If sequence checking is enabled then the MessageProp.isDuplicateToken, MessageProp.isOldToken, MessageProp.isUnseqToken, and MessageProp.isGapToken methods will return valid results for the MessageProp object that is passed in to the unwrap method or the verifyMIC method.

Parameters:
state - a boolean value indicating whether sequence checking should be enabled over the established context or not.
Throws:
GSSException - containing the following major error codes: GSSException.FAILURE
See Also:
getSequenceDetState()

requestCredDeleg

public void requestCredDeleg(boolean state)
                      throws GSSException
Requests that the initiator's credentials be delegated to the acceptor during context establishment. This request can only be made on the context initiator's side and it has to be done prior to the first call to initSecContext. Not all mechanisms support credential delegation. Therefore, an application that desires delegation should check to see if the request was honored with the getCredDelegState method. If the application indicates that delegation must not be used, then the mechanism will honor the request and delegation will not occur. This is an exception to the general rule that a mechanism may enable a service even if it is not requested.

Parameters:
state - a boolean value indicating whether the credentials should be delegated or not.
Throws:
GSSException - containing the following major error codes: GSSException.FAILURE
See Also:
getCredDelegState()

requestAnonymity

public void requestAnonymity(boolean state)
                      throws GSSException
Requests that the initiator's identity not be disclosed to the acceptor. This request can only be made on the context initiator's side and it has to be done prior to the first call to initSecContext. Not all mechanisms support anonymity for the initiator. Therefore, the application should check to see if the request was honored with the getAnonymityState method.

Parameters:
state - a boolean value indicating if the initiator should be authenticated to the acceptor as an anonymous principal.
Throws:
GSSException - containing the following major error codes: GSSException.FAILURE
See Also:
getAnonymityState()

requestConf

public void requestConf(boolean state)
                 throws GSSException
Requests that data confidentiality be enabled for the wrap method. This request can only be made on the context initiator's side and it has to be done prior to the first call to initSecContext. Not all mechanisms support confidentiality and other mechanisms might enable it even if the application doesn't request it. The application may check to see if the request was honored with the getConfState method. If confidentiality is enabled, only then will the mechanism honor a request for privacy in the MessageProp object that is passed in to the wrap method.

Enabling confidentiality will also automatically enable integrity.

Parameters:
state - a boolean value indicating whether confidentiality should be enabled or not.
Throws:
GSSException - containing the following major error codes: GSSException.FAILURE
See Also:
getConfState(), getIntegState(), requestInteg(boolean), MessageProp

requestInteg

public void requestInteg(boolean state)
                  throws GSSException
Requests that data integrity be enabled for the wrap and getMICmethods. This request can only be made on the context initiator's side and it has to be done prior to the first call to initSecContext. Not all mechanisms support integrity and other mechanisms might enable it even if the application doesn't request it. The application may check to see if the request was honored with the getIntegState method.

Disabling integrity will also automatically disable confidentiality.

Parameters:
state - a boolean value indicating whether integrity should be enabled or not.
Throws:
GSSException - containing the following major error codes: GSSException.FAILURE
See Also:
getIntegState()

requestLifetime

public void requestLifetime(int lifetime)
                     throws GSSException
Requests a lifetime in seconds for the context. This method can only be called on the context initiator's side and it has to be done prior to the first call to initSecContext.

The actual lifetime of the context will depend on the capabilites of the underlying mechanism and the application should call the getLifetime method to determine this.

Parameters:
lifetime - the desired context lifetime in seconds. Use INDEFINITE_LIFETIME to request an indefinite lifetime and DEFAULT_LIFETIME to request a default lifetime.
Throws:
GSSException - containing the following major error codes: GSSException.FAILURE
See Also:
getLifetime()

setChannelBinding

public void setChannelBinding(ChannelBinding cb)
                       throws GSSException
Sets the channel bindings to be used during context establishment. This method can be called on both the context initiator's and the context acceptor's side, but it must be called before context establishment begins. This means that an initiator must call it before the first call to initSecContext and the acceptor must call it before the first call to acceptSecContext.

Parameters:
cb - the channel bindings to use.
Throws:
GSSException - containing the following major error codes: GSSException.FAILURE

getCredDelegState

public boolean getCredDelegState()
Determines if credential delegation is enabled on this context. It can be called by both the context initiator and the context acceptor. For a definitive answer this method must be called only after context establishment is complete. Note that if an initiator requests that delegation not be allowed the requestCredDeleg method will honor that request and this method will return false on the initiator's side from that point onwards.

Returns:
true if delegation is enabled, false otherwise.
See Also:
requestCredDeleg(boolean)

getMutualAuthState

public boolean getMutualAuthState()
Determines if mutual authentication is enabled on this context. It can be called by both the context initiator and the context acceptor. For a definitive answer this method must be called only after context establishment is complete. An initiator that requests mutual authentication can call this method after context completion and dispose the context if its request was not honored.

Returns:
true if mutual authentication is enabled, false otherwise.
See Also:
requestMutualAuth(boolean)

getReplayDetState

public boolean getReplayDetState()
Determines if replay detection is enabled for the per-message security services from this context. It can be called by both the context initiator and the context acceptor. For a definitive answer this method must be called only after context establishment is complete. An initiator that requests replay detection can call this method after context completion and dispose the context if its request was not honored.

Returns:
true if replay detection is enabled, false otherwise.
See Also:
requestReplayDet(boolean)

getSequenceDetState

public boolean getSequenceDetState()
Determines if sequence checking is enabled for the per-message security services from this context. It can be called by both the context initiator and the context acceptor. For a definitive answer this method must be called only after context establishment is complete. An initiator that requests sequence checking can call this method after context completion and dispose the context if its request was not honored.

Returns:
true if sequence checking is enabled, false otherwise.
See Also:
requestSequenceDet(boolean)

getAnonymityState

public boolean getAnonymityState()
Determines if the context initiator is anonymously authenticated to the context acceptor. It can be called by both the context initiator and the context acceptor, and at any time. On the initiator side, a call to this method determines if the identity of the initiator has been disclosed in any of the context establishment tokens that might have been generated thus far by initSecContext. An initiator that absolutely must be authenticated anonymously should call this method after each call to initSecContext to determine if the generated token should be sent to the peer or the context aborted. On the acceptor side, a call to this method determines if any of the tokens processed by acceptSecContext thus far have divulged the identity of the initiator.

Returns:
true if the context initiator is still anonymous, false otherwise.
See Also:
requestAnonymity(boolean)

isTransferable

public boolean isTransferable()
                       throws GSSException
Determines if the context is transferable to other processes through the use of the export method. This call is only valid on fully established contexts.

Returns:
true if this context can be exported, false otherwise.
Throws:
GSSException - containing the following major error codes: GSSException.FAILURE

isProtReady

public boolean isProtReady()
Determines if the context is ready for per message operations to be used over it. Some mechanisms may allow the usage of the per-message operations before the context is fully established.

Returns:
true if methods like wrap, unwrap, getMIC, and verifyMIC can be used with this context at the current stage of context establishment, false otherwise.

getConfState

public boolean getConfState()
Determines if data confidentiality is available over the context. This method can be called by both the context initiator and the context acceptor, but only after one of isProtReady or isEstablished return true. If this method returns true, so will getIntegState

Returns:
true if confidentiality services are available, false otherwise.
See Also:
requestConf(boolean)

getIntegState

public boolean getIntegState()
Determines if data integrity is available over the context. This method can be called by both the context initiator and the context acceptor, but only after one of isProtReady or isEstablished return true. This method will always return true if getConfState returns true.

Returns:
true if integrity services are available, false otherwise.
See Also:
requestInteg(boolean)

getLifetime

public int getLifetime()
Determines what the remaining lifetime for this context is. It can be called by both the context initiator and the context acceptor, but for a definitive answer it should be called only after isEstablished returns true.

Returns:
the remaining lifetime in seconds
See Also:
requestLifetime(int)

getSrcName

public GSSName getSrcName()
                   throws GSSException
Returns the name of the context initiator. This call is valid only after one of isProtReady or isEstablished return true.

Returns:
a GSSName that is an MN containing the name of the context initiator.
Throws:
GSSException - containing the following major error codes: GSSException.FAILURE
See Also:
GSSName

getTargName

public GSSName getTargName()
                    throws GSSException
Returns the name of the context acceptor. This call is valid only after one of isProtReady or isEstablished return true.

Returns:
a GSSName that is an MN containing the name of the context acceptor.
Throws:
GSSException - containing the following major error codes: GSSException.FAILURE

getMech

public Oid getMech()
            throws GSSException
Determines what mechanism is being used for this context. This method may be called before the context is fully established, but the mechanism returned may change on successive calls in the negotiated mechanism case.

Returns:
the Oid of the mechanism being used
Throws:
GSSException - containing the following major error codes: GSSException.FAILURE

getDelegCred

public GSSCredential getDelegCred()
                           throws GSSException
Obtains the credentials delegated by the context initiator to the context acceptor. It should be called only on the context acceptor's side, and once the context is fully established. The caller can use the method getCredDelegState to determine if there are any delegated credentials.

Returns:
a GSSCredential containing the initiator's delegated credentials, or null is no credentials were delegated.
Throws:
GSSException - containing the following major error codes: GSSException.FAILURE

isInitiator

public boolean isInitiator()
                    throws GSSException
Determines if this is the context initiator. This can be called on both the context initiator's and context acceptor's side.

Returns:
true if this is the context initiator, false if it is the context acceptor.
Throws:
GSSException - containing the following major error codes: GSSException.FAILURE
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


GSSCredential (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.ietf.jgss
Interface GSSCredential

All Superinterfaces:
Cloneable
public interface GSSCredential
extends Cloneable

This interface encapsulates the GSS-API credentials for an entity. A credential contains all the necessary cryptographic information to enable the creation of a context on behalf of the entity that it represents. It may contain multiple, distinct, mechanism specific credential elements, each containing information for a specific security mechanism, but all referring to the same entity. A credential may be used to perform context initiation, acceptance, or both.

Credentials are instantiated using one of the createCredential methods in the GSSManager class. GSS-API credential creation is not intended to provide a "login to the network" function, as such a function would involve the creation of new credentials rather than merely acquiring a handle to existing credentials. The section on credential acquisition in the package level description describes how existing credentials are acquired in the Java 2 platform. GSS-API implementations must impose a local access-control policy on callers to prevent unauthorized callers from acquiring credentials to which they are not entitled.

Applications will create a credential object passing the desired parameters. The application can then use the query methods to obtain specific information about the instantiated credential object. When the credential is no longer needed, the application should call the dispose method to release any resources held by the credential object and to destroy any cryptographically sensitive information.

This example code demonstrates the creation of a GSSCredential implementation for a specific entity, querying of its fields, and its release when it is no longer needed:

    GSSManager manager = GSSManager.getInstance();

    // start by creating a name object for the entity
    GSSName name = manager.createName("myusername", GSSName.NT_USER_NAME);

    // now acquire credentials for the entity
    GSSCredential cred = manager.createCredential(name,
                    GSSCredential.ACCEPT_ONLY);

    // display credential information - name, remaining lifetime,
    // and the mechanisms it has been acquired over
    System.out.println(cred.getName().toString());
    System.out.println(cred.getRemainingLifetime());

    Oid [] mechs = cred.getMechs();
    if (mechs != null) {
            for (int i = 0; i < mechs.length; i++)
                    System.out.println(mechs[i].toString());
    }

    // release system resources held by the credential
    cred.dispose();

Since:
1.4
See Also:
GSSManager.createCredential(int),
GSSManager.createCredential(GSSName, int, Oid, int),
GSSManager.createCredential(GSSName, int, Oid[], int),
dispose()

Field Summary
static int | ACCEPT_ONLY Credential usage flag requesting that it be usable for context acceptance only.
static int | DEFAULT_LIFETIME A lifetime constant representing the default credential lifetime.
static int | INDEFINITE_LIFETIME A lifetime constant representing indefinite credential lifetime.
static int | INITIATE_AND_ACCEPT Credential usage flag requesting that it be usable for both context initiation and acceptance.
static int | INITIATE_ONLY Credential usage flag requesting that it be usable for context initiation only.
Method Summary
void | add(GSSName name, int initLifetime, int acceptLifetime, Oid mech, int usage) Adds a mechanism specific credential-element to an existing credential.
void | dispose() Releases any sensitive information that the GSSCredential object may be containing.
boolean | equals(Object another) Tests if this GSSCredential asserts the same entity as the supplied object.
Oid[] | getMechs() Returns a list of mechanisms supported by this credential.
GSSName | getName() Retrieves the name of the entity that the credential asserts.
GSSName | getName(Oid mech) Retrieves a Mechanism Name of the entity that the credential asserts.
int | getRemainingAcceptLifetime(Oid mech) Returns the lifetime in seconds for the credential to remain capable of accepting security contexts using the specified mechanism.
int | getRemainingInitLifetime(Oid mech) Returns the lifetime in seconds for the credential to remain capable of initiating security contexts using the specified mechanism.
int | getRemainingLifetime() Returns the remaining lifetime in seconds for a credential.
int | getUsage() Returns the credential usage mode.
int | getUsage(Oid mech) Returns the credential usage mode for a specific mechanism.
int | hashCode() Returns a hashcode value for this GSSCredential.

Field Detail

INITIATE_AND_ACCEPT

public static final int INITIATE_AND_ACCEPT
Credential usage flag requesting that it be usable for both context initiation and acceptance.

See Also:
Constant Field Values

INITIATE_ONLY

public static final int INITIATE_ONLY
Credential usage flag requesting that it be usable for context initiation only.

See Also:
Constant Field Values

ACCEPT_ONLY

public static final int ACCEPT_ONLY
Credential usage flag requesting that it be usable for context acceptance only.

See Also:
Constant Field Values

DEFAULT_LIFETIME

public static final int DEFAULT_LIFETIME
A lifetime constant representing the default credential lifetime. This value it set to 0.

See Also:
Constant Field Values

INDEFINITE_LIFETIME

public static final int INDEFINITE_LIFETIME
A lifetime constant representing indefinite credential lifetime. This value must is set to the maximum integer value in Java - Integer.MAX_VALUE.

See Also:
Constant Field Values
Method Detail

dispose

public void dispose()
             throws GSSException
Releases any sensitive information that the GSSCredential object may be containing. Applications should call this method as soon as the credential is no longer needed to minimize the time any sensitive information is maintained.

Throws:
GSSException - containing the following major error codes: GSSException.FAILURE

getName

public GSSName getName()
                throws GSSException
Retrieves the name of the entity that the credential asserts.

Returns:
a GSSName representing the entity
Throws:
GSSException - containing the following major error codes: GSSException.FAILURE

getName

public GSSName getName(Oid mech)
                throws GSSException
Retrieves a Mechanism Name of the entity that the credential asserts. This is equivalent to calling canonicalize on the value returned by the other form of getName.

Parameters:
mech - the Oid of the mechanism for which the Mechanism Name should be returned.
Returns:
a GSSName representing the entity canonicalized for the desired mechanism
Throws:
GSSException - containing the following major error codes: GSSException.BAD_MECH, GSSException.FAILURE

getRemainingLifetime

public int getRemainingLifetime()
                         throws GSSException
Returns the remaining lifetime in seconds for a credential. The remaining lifetime is the minimum lifetime amongst all of the underlying mechanism specific credential elements.

Returns:
the minimum remaining lifetime in seconds for this credential. A return value of INDEFINITE_LIFETIME indicates that the credential does not expire. A return value of 0 indicates that the credential is already expired.
Throws:
GSSException - containing the following major error codes: GSSException.FAILURE
See Also:
getRemainingInitLifetime(Oid), getRemainingAcceptLifetime(Oid)

getRemainingInitLifetime

public int getRemainingInitLifetime(Oid mech)
                             throws GSSException
Returns the lifetime in seconds for the credential to remain capable of initiating security contexts using the specified mechanism. This method queries the initiator credential element that belongs to the specified mechanism.

Parameters:
mech - the Oid of the mechanism whose intiator credential element should be queried.
Returns:
the number of seconds remaining in the life of this credential element. A return value of INDEFINITE_LIFETIME indicates that the credential element does not expire. A return value of 0 indicates that the credential element is already expired.
Throws:
GSSException - containing the following major error codes: GSSException.BAD_MECH, GSSException.FAILURE

getRemainingAcceptLifetime

public int getRemainingAcceptLifetime(Oid mech)
                               throws GSSException
Returns the lifetime in seconds for the credential to remain capable of accepting security contexts using the specified mechanism. This method queries the acceptor credential element that belongs to the specified mechanism.

Parameters:
mech - the Oid of the mechanism whose acceptor credential element should be queried.
Returns:
the number of seconds remaining in the life of this credential element. A return value of INDEFINITE_LIFETIME indicates that the credential element does not expire. A return value of 0 indicates that the credential element is already expired.
Throws:
GSSException - containing the following major error codes: GSSException.BAD_MECH, GSSException.FAILURE

getUsage

public int getUsage()
             throws GSSException
Returns the credential usage mode. In other words, it tells us if this credential can be used for initiating or accepting security contexts. It does not tell us which mechanism(s) has to be used in order to do so. It is expected that an application will allow the GSS-API to pick a default mechanism after calling this method.

Returns:
The return value will be one of INITIATE_ONLY, ACCEPT_ONLY, and INITIATE_AND_ACCEPT.
Throws:
GSSException - containing the following major error codes: GSSException.FAILURE

getUsage

public int getUsage(Oid mech)
             throws GSSException
Returns the credential usage mode for a specific mechanism. In other words, it tells us if this credential can be used for initiating or accepting security contexts with a given underlying mechanism.

Parameters:
mech - the Oid of the mechanism whose credentials usage mode is to be determined.
Returns:
The return value will be one of INITIATE_ONLY, ACCEPT_ONLY, and INITIATE_AND_ACCEPT.
Throws:
GSSException - containing the following major error codes: GSSException.BAD_MECH, GSSException.FAILURE

getMechs

public Oid[] getMechs()
               throws GSSException
Returns a list of mechanisms supported by this credential. It does not tell us which ones can be used to initiate contexts and which ones can be used to accept contexts. The application must call the getUsage method with each of the returned Oid's to determine the possible modes of usage.

Returns:
an array of Oid's corresponding to the supported mechanisms.
Throws:
GSSException - containing the following major error codes: GSSException.FAILURE

add

public void add(GSSName name,
                int initLifetime,
                int acceptLifetime,
                Oid mech,
                int usage)
         throws GSSException
Adds a mechanism specific credential-element to an existing credential. This method allows the construction of credentials, one mechanism at a time.

This routine is envisioned to be used mainly by context acceptors during the creation of acceptor credentials which are to be used with a variety of clients using different security mechanisms.

This routine adds the new credential element "in-place". To add the element in a new credential, first call clone to obtain a copy of this credential, then call its add method.

As always, GSS-API implementations must impose a local access-control policy on callers to prevent unauthorized callers from acquiring credentials to which they are not entitled. Non-default values for initLifetime and acceptLifetime cannot always be honored by the underlying mechanisms, thus callers should be prepared to call getRemainingInitLifetime and getRemainingAcceptLifetime on the credential.

Parameters:
name - the name of the principal for whom this credential is to be acquired. Use null to specify the default principal.
initLifetime - the number of seconds that the credential element should remain valid for initiating of security contexts. Use GSSCredential.INDEFINITE_LIFETIME to request that the credentials have the maximum permitted lifetime for this. Use GSSCredential.DEFAULT_LIFETIME to request default credential lifetime for this.
acceptLifetime - the number of seconds that the credential element should remain valid for accepting security contexts. Use GSSCredential.INDEFINITE_LIFETIME to request that the credentials have the maximum permitted lifetime for this. Use GSSCredential.DEFAULT_LIFETIME to request default credential lifetime for this.
mech - the mechanism over which the credential is to be acquired.
usage - the usage mode that this credential element should add to the credential. The value of this parameter must be one of: INITIATE_AND_ACCEPT, ACCEPT_ONLY, and INITIATE_ONLY.
Throws:
GSSException - containing the following major error codes: GSSException.DUPLICATE_ELEMENT, GSSException.BAD_MECH, GSSException.BAD_NAMETYPE, GSSException.NO_CRED, GSSException.CREDENTIALS_EXPIRED, GSSException.FAILURE

equals

public boolean equals(Object another)
Tests if this GSSCredential asserts the same entity as the supplied object. The two credentials must be acquired over the same mechanisms and must refer to the same principal.

Overrides:
equals in class Object
Parameters:
another - another GSSCredential for comparison to this one
Returns:
true if the two GSSCredentials assert the same entity; false otherwise.
See Also:
Object.hashCode(), Hashtable

hashCode

public int hashCode()
Returns a hashcode value for this GSSCredential.

Overrides:
hashCode in class Object
Returns:
a hashCode value
See Also:
Object.equals(java.lang.Object), Hashtable
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


GSSException (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.ietf.jgss
Class GSSException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.ietf.jgss.GSSException
All Implemented Interfaces:
Serializable
public class GSSException
extends Exception

This exception is thrown whenever a GSS-API error occurs, including any mechanism specific error. It may contain both the major and the minor GSS-API status codes. Major error codes are those defined at the GSS-API level in this class. Minor error codes are mechanism specific error codes that can provide additional information. The underlying mechanism implementation is responsible for setting appropriate minor status codes when throwing this exception. Aside from delivering the numeric error codes to the caller, this class performs the mapping from their numeric values to textual representations.

Since:
1.4
See Also:
Serialized Form

Field Summary
static int | BAD_BINDINGS Channel bindings mismatch.
static int | BAD_MECH Unsupported mechanism requested.
static int | BAD_MIC Token had invalid integrity check.
static int | BAD_NAME Invalid name provided.
static int | BAD_NAMETYPE Name of unsupported type provided.
static int | BAD_QOP Unsupported QOP value.
static int | BAD_STATUS Invalid status code.
static int | CONTEXT_EXPIRED Security context expired.
static int | CREDENTIALS_EXPIRED Expired credentials.
static int | DEFECTIVE_CREDENTIAL Defective credentials.
static int | DEFECTIVE_TOKEN Defective token.
static int | DUPLICATE_ELEMENT Duplicate credential element requested.
static int | DUPLICATE_TOKEN The token was a duplicate of an earlier token.
static int | FAILURE General failure, unspecified at GSS-API level.
static int | GAP_TOKEN An expected per-message token was not received.
static int | NAME_NOT_MN Name contains multi-mechanism elements.
static int | NO_CONTEXT Invalid security context.
static int | NO_CRED Invalid credentials.
static int | OLD_TOKEN The token's validity period has expired.
static int | UNAUTHORIZED Operation unauthorized.
static int | UNAVAILABLE Operation unavailable.
static int | UNSEQ_TOKEN A later token has already been processed.
Constructor Summary
GSSException(int majorCode)
Creates a GSSException object with a specified major code.
GSSException(int majorCode, int minorCode, String minorString)
Creates a GSSException object with the specified major code, minor code, and minor code textual explanation.
Method Summary
int | getMajor() Returns the GSS-API level major error code for the problem causing this exception to be thrown.
String | getMajorString() Returns a string explaining the GSS-API level major error code in this exception.
String | getMessage() Returns a textual representation of both the major and the minor status codes.
int | getMinor() Returns the mechanism level error code for the problem causing this exception to be thrown.
String | getMinorString() Returns a string explaining the mechanism specific error code.
void | setMinor(int minorCode, String message) Used by the exception thrower to set the mechanism level minor error code and its string explanation.
String | toString() Returns a textual representation of both the major and the minor status codes.
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

BAD_BINDINGS

public static final int BAD_BINDINGS
Channel bindings mismatch.

See Also:
Constant Field Values

BAD_MECH

public static final int BAD_MECH
Unsupported mechanism requested.

See Also:
Constant Field Values

BAD_NAME

public static final int BAD_NAME
Invalid name provided.

See Also:
Constant Field Values

BAD_NAMETYPE

public static final int BAD_NAMETYPE
Name of unsupported type provided.

See Also:
Constant Field Values

BAD_STATUS

public static final int BAD_STATUS
Invalid status code.

See Also:
Constant Field Values

BAD_MIC

public static final int BAD_MIC
Token had invalid integrity check.

See Also:
Constant Field Values

CONTEXT_EXPIRED

public static final int CONTEXT_EXPIRED
Security context expired.

See Also:
Constant Field Values

CREDENTIALS_EXPIRED

public static final int CREDENTIALS_EXPIRED
Expired credentials.

See Also:
Constant Field Values

DEFECTIVE_CREDENTIAL

public static final int DEFECTIVE_CREDENTIAL
Defective credentials.

See Also:
Constant Field Values

DEFECTIVE_TOKEN

public static final int DEFECTIVE_TOKEN
Defective token.

See Also:
Constant Field Values

FAILURE

public static final int FAILURE
General failure, unspecified at GSS-API level.

See Also:
Constant Field Values

NO_CONTEXT

public static final int NO_CONTEXT
Invalid security context.

See Also:
Constant Field Values

NO_CRED

public static final int NO_CRED
Invalid credentials.

See Also:
Constant Field Values

BAD_QOP

public static final int BAD_QOP
Unsupported QOP value.

See Also:
Constant Field Values

UNAUTHORIZED

public static final int UNAUTHORIZED
Operation unauthorized.

See Also:
Constant Field Values

UNAVAILABLE

public static final int UNAVAILABLE
Operation unavailable.

See Also:
Constant Field Values

DUPLICATE_ELEMENT

public static final int DUPLICATE_ELEMENT
Duplicate credential element requested.

See Also:
Constant Field Values

NAME_NOT_MN

public static final int NAME_NOT_MN
Name contains multi-mechanism elements.

See Also:
Constant Field Values

DUPLICATE_TOKEN

public static final int DUPLICATE_TOKEN
The token was a duplicate of an earlier token. This is a fatal error code that may occur during context establishment. It is not used to indicate supplementary status values. The MessageProp object is used for that purpose.

See Also:
Constant Field Values

OLD_TOKEN

public static final int OLD_TOKEN
The token's validity period has expired. This is a fatal error code that may occur during context establishment. It is not used to indicate supplementary status values. The MessageProp object is used for that purpose.

See Also:
Constant Field Values

UNSEQ_TOKEN

public static final int UNSEQ_TOKEN
A later token has already been processed. This is a fatal error code that may occur during context establishment. It is not used to indicate supplementary status values. The MessageProp object is used for that purpose.

See Also:
Constant Field Values

GAP_TOKEN

public static final int GAP_TOKEN
An expected per-message token was not received. This is a fatal error code that may occur during context establishment. It is not used to indicate supplementary status values. The MessageProp object is used for that purpose.

See Also:
Constant Field Values
Constructor Detail

GSSException

public GSSException(int majorCode)
Creates a GSSException object with a specified major code.

Parameters:
majorCode - the The GSS error code for the problem causing this exception to be thrown.

GSSException

public GSSException(int majorCode,
                    int minorCode,
                    String minorString)
Creates a GSSException object with the specified major code, minor code, and minor code textual explanation. This constructor is to be used when the exception is originating from the underlying mechanism level. It allows the setting of both the GSS code and the mechanism code.

Parameters:
majorCode - the GSS error code for the problem causing this exception to be thrown.
minorCode - the mechanism level error code for the problem causing this exception to be thrown.
minorString - the textual explanation of the mechanism error code.
Method Detail

getMajor

public int getMajor()
Returns the GSS-API level major error code for the problem causing this exception to be thrown. Major error codes are defined at the mechanism independent GSS-API level in this class. Mechanism specific error codes that might provide more information aer set as the minor error code.

Returns:
int the GSS-API level major error code causing this exception
See Also:
getMajorString(),
getMinor(),
getMinorString()

getMinor

public int getMinor()
Returns the mechanism level error code for the problem causing this exception to be thrown. The minor code is set by the underlying mechanism.

Returns:
int the mechanism error code; 0 indicates that it has not been set.
See Also:
getMinorString(), setMinor(int, java.lang.String)

getMajorString

public String getMajorString()
Returns a string explaining the GSS-API level major error code in this exception.

Returns:
String explanation string for the major error code
See Also:
getMajor(), toString()

getMinorString

public String getMinorString()
Returns a string explaining the mechanism specific error code. If the minor status code is 0, then no mechanism level error details will be available.

Returns:
String a textual explanation of mechanism error code
See Also:
getMinor(),
getMajorString(),
toString()

setMinor

public void setMinor(int minorCode,
                     String message)
Used by the exception thrower to set the mechanism level minor error code and its string explanation. This is used by mechanism providers to indicate error details.

Parameters:
minorCode - the mechanism specific error code
message - textual explanation of the mechanism error code
See Also:
getMinor()

toString

public String toString()
Returns a textual representation of both the major and the minor status codes.

Overrides:
toString in class Throwable
Returns:
a String with the error descriptions

getMessage

public String getMessage()
Returns a textual representation of both the major and the minor status codes.

Overrides:
getMessage in class Throwable
Returns:
a String with the error descriptions
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


GSSManager (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.ietf.jgss
Class GSSManager

java.lang.Object
    extended by org.ietf.jgss.GSSManager
public abstract class GSSManager
extends Object

This class serves as a factory for other important GSS-API classes and also provides information about the mechanisms that are supported. It can create instances of classes implementing the following three GSS-API interfaces: GSSName, GSSCredential, and GSSContext. It also has methods to query for the list of available mechanisms and the nametypes that each mechanism supports.

An instance of the default GSSManager subclass may be obtained through the static method getInstance, but applications are free to instantiate other subclasses of GSSManager. The default GSSManager instance will support the Kerberos v5 GSS-API mechanism in addition to any others. This mechanism is identified by the Oid "1.2.840.113554.1.2.2" and is defined in RFC 1964.

A subclass extending the GSSManager abstract class may be implemented as a modular provider based layer that utilizes some well known service provider specification. The GSSManager API allows the application to set provider preferences on such an implementation. These methods also allow the implementation to throw a well-defined exception in case provider based configuration is not supported. Applications that expect to be portable should be aware of this and recover cleanly by catching the exception.

It is envisioned that there will be three most common ways in which providers will be used:

  1. The application does not care about what provider is used (the default case).
  2. The application wants a particular provider to be used preferentially, either for a particular mechanism or all the time, irrespective of mechanism.
  3. The application wants to use the locally configured providers as far as possible but if support is missing for one or more mechanisms then it wants to fall back on its own provider.

The GSSManager class has two methods that enable these modes of usage: addProviderAtFront and addProviderAtEnd. These methods have the effect of creating an ordered list of <provider, oid> pairs where each pair indicates a preference of provider for a given oid.

It is important to note that there are certain interactions between the different GSS-API objects that are created by a GSSManager, where the provider that is used for a particular mechanism might need to be consistent across all objects. For instance, if a GSSCredential contains elements from a provider p for a mechanism m, it should generally be passed in to a GSSContext that will use provider p for the mechanism m. A simple rule of thumb that will maximize portability is that objects created from different GSSManager's should not be mixed, and if possible, a different GSSManager instance should be created if the application wants to invoke the addProviderAtFront method on a GSSManager that has already created an object.

Here is some sample code showing how the GSSManager might be used:

     GSSManager manager = GSSManager.getInstance();

     Oid krb5Mechanism = new Oid("1.2.840.113554.1.2.2");
     Oid krb5PrincipalNameType = new Oid("1.2.840.113554.1.2.2.1");

     // Identify who the client wishes to be
     GSSName userName = manager.createName("duke", GSSName.NT_USER_NAME);

     // Identify the name of the server. This uses a Kerberos specific
     // name format.
     GSSName serverName = manager.createName("nfs/foo.sun.com",
                                             krb5PrincipalNameType);

     // Acquire credentials for the user
     GSSCredential userCreds = manager.createCredential(userName,
                                             GSSCredential.DEFAULT_LIFETIME,
                                             krb5Mechanism,
                                             GSSCredential.INITIATE_ONLY);

     // Instantiate and initialize a security context that will be
     // established with the server
     GSSContext context = manager.createContext(serverName,
                                                krb5Mechanism,
                                                userCreds,
                                                GSSContext.DEFAULT_LIFETIME);

The server side might use the following variation of this source:

     // Acquire credentials for the server
     GSSCredential serverCreds = manager.createCredential(serverName,
                                             GSSCredential.DEFAULT_LIFETIME,
                                             krb5Mechanism,
                                             GSSCredential.ACCEPT_ONLY);

     // Instantiate and initialize a security context that will
     // wait for an establishment request token from the client
     GSSContext context = manager.createContext(serverCreds);

Since:
1.4
See Also:
GSSName, GSSCredential, GSSContext

Constructor Summary
GSSManager()
Method Summary
abstract void | addProviderAtEnd(Provider p, Oid mech) This method is used to indicate to the GSSManager that the application would like a particular provider to be used if no other provider can be found that supports the given mechanism.
abstract void | addProviderAtFront(Provider p, Oid mech) This method is used to indicate to the GSSManager that the application would like a particular provider to be used ahead of all others when support is desired for the given mechanism.
abstract GSSContext | createContext(byte[] interProcessToken) Factory method for creating a previously exported context.
abstract GSSContext | createContext(GSSCredential myCred) Factory method for creating a context on the acceptor' side.
abstract GSSContext | createContext(GSSName peer, Oid mech, GSSCredential myCred, int lifetime) Factory method for creating a context on the initiator's side.
abstract GSSCredential | createCredential(GSSName name, int lifetime, Oid[] mechs, int usage) Factory method for acquiring credentials over a set of mechanisms.
abstract GSSCredential | createCredential(GSSName name, int lifetime, Oid mech, int usage) Factory method for acquiring a single mechanism credential.
abstract GSSCredential | createCredential(int usage) Factory method for acquiring default credentials.
abstract GSSName | createName(byte[] name, Oid nameType) Factory method to convert a byte array containing a name from the specified namespace to a GSSName object.
abstract GSSName | createName(byte[] name, Oid nameType, Oid mech) Factory method to convert a byte array containing a name from the specified namespace to a GSSName object and canonicalize it at the same time for a mechanism.
abstract GSSName | createName(String nameStr, Oid nameType) Factory method to convert a string name from the specified namespace to a GSSName object.
abstract GSSName | createName(String nameStr, Oid nameType, Oid mech) Factory method to convert a string name from the specified namespace to a GSSName object and canonicalize it at the same time for a mechanism.
static GSSManager | getInstance() Returns the default GSSManager implementation.
abstract Oid[] | getMechs() Returns a list of mechanisms that are available to GSS-API callers through this GSSManager.
abstract Oid[] | getMechsForName(Oid nameType) Returns a list of mechanisms that support the indicated name type.
abstract Oid[] | getNamesForMech(Oid mech) Returns then name types supported by the indicated mechanism.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

GSSManager

public GSSManager()
Method Detail

getInstance

public static GSSManager getInstance()
Returns the default GSSManager implementation.

Returns:
a GSSManager implementation

getMechs

public abstract Oid[] getMechs()
Returns a list of mechanisms that are available to GSS-API callers through this GSSManager. The default GSSManager obtained from the getInstance() method includes the Oid "1.2.840.113554.1.2.2" in its list. This Oid identifies the Kerberos v5 GSS-API mechanism that is defined in RFC 1964.

Returns:
an array of Oid objects corresponding to the mechanisms that are available. A null value is returned when no mechanism are available (an example of this would be when mechanism are dynamically configured, and currently no mechanisms are installed).

getNamesForMech

public abstract Oid[] getNamesForMech(Oid mech)
                               throws GSSException
Returns then name types supported by the indicated mechanism.

The default GSSManager instance includes support for the Kerberos v5 mechanism. When this mechanism ("1.2.840.113554.1.2.2") is indicated, the returned list will contain at least the following nametypes: GSSName.NT_HOSTBASED_SERVICE, GSSName.NT_EXPORT_NAME, and the Kerberos v5 specific Oid "1.2.840.113554.1.2.2.1". The namespace for the Oid "1.2.840.113554.1.2.2.1" is defined in RFC 1964.

Parameters:
mech - the Oid of the mechanism to query
Returns:
an array of Oid objects corresponding to the name types that the mechanism supports.
Throws:
GSSException - containing the following major error codes: GSSException.BAD_MECH GSSException.FAILURE
See Also:
getMechsForName(Oid)

getMechsForName

public abstract Oid[] getMechsForName(Oid nameType)
Returns a list of mechanisms that support the indicated name type.

The Kerberos v5 mechanism ("1.2.840.113554.1.2.2") will always be returned in this list when the indicated nametype is one of GSSName.NT_HOSTBASED_SERVICE, GSSName.NT_EXPORT_NAME, or "1.2.840.113554.1.2.2.1".

Parameters:
nameType - the Oid of the name type to look for
Returns:
an array of Oid objects corresponding to the mechanisms that support the specified name type. null is returned when no mechanisms are found to support the specified name type.
See Also:
getNamesForMech(Oid)

createName

public abstract GSSName createName(String nameStr,
                                   Oid nameType)
                            throws GSSException
Factory method to convert a string name from the specified namespace to a GSSName object. In general, the GSSName object created will contain multiple representations of the name, one for each mechanism that is supported; two examples that are exceptions to this are when the namespace type parameter indicates NT_EXPORT_NAME or when the GSS-API implementation is not multi-mechanism. It is not recommended to use this method with a NT_EXPORT_NAME type because representing a previously exported name consisting of abitrary bytes as a String might cause problems with character encoding schemes. In such cases it is recommended that the bytes be passed in directly to the overloaded form of this method createName.

Parameters:
nameStr - the string representing a printable form of the name to create.
nameType - the Oid specifying the namespace of the printable name supplied. null can be used to specify that a mechanism specific default printable syntax should be assumed by each mechanism that examines nameStr. It is not advisable to use the nametype NT_EXPORT_NAME with this method.
Returns:
a GSSName representing the indicated principal
Throws:
GSSException - containing the following major error codes: GSSException.BAD_NAMETYPE, GSSException.BAD_NAME, GSSException.BAD_MECH, GSSException.FAILURE
See Also:
GSSName, GSSName.NT_EXPORT_NAME

createName

public abstract GSSName createName(byte[] name,
                                   Oid nameType)
                            throws GSSException
Factory method to convert a byte array containing a name from the specified namespace to a GSSName object. In general, the GSSName object created will contain multiple representations of the name, one for each mechanism that is supported; two examples that are exceptions to this are when the namespace type parameter indicates NT_EXPORT_NAME or when the GSS-API implementation is not multi-mechanism. The bytes that are passed in are interpreted by each underlying mechanism according to some encoding scheme of its choice for the given nametype.

Parameters:
name - the byte array containing the name to create
nameType - the Oid specifying the namespace of the name supplied in the byte array. null can be used to specify that a mechanism specific default syntax should be assumed by each mechanism that examines the byte array.
Returns:
a GSSName representing the indicated principal
Throws:
GSSException - containing the following major error codes: GSSException.BAD_NAMETYPE, GSSException.BAD_NAME, GSSException.BAD_MECH, GSSException.FAILURE
See Also:
GSSName, GSSName.NT_EXPORT_NAME

createName

public abstract GSSName createName(String nameStr,
                                   Oid nameType,
                                   Oid mech)
                            throws GSSException
Factory method to convert a string name from the specified namespace to a GSSName object and canonicalize it at the same time for a mechanism. In other words, this method is a utility that does the equivalent of two steps: the createName and then also the GSSName.canonicalize.

Parameters:
nameStr - the string representing a printable form of the name to create.
nameType - the Oid specifying the namespace of the printable name supplied. null can be used to specify that a mechanism specific default printable syntax should be assumed by each mechanism that examines nameStr. It is not advisable to use the nametype NT_EXPORT_NAME with this method.
mech - Oid specifying the mechanism for which the name should be canonicalized
Returns:
a GSSName representing the indicated principal
Throws:
GSSException - containing the following major error codes: GSSException.BAD_NAMETYPE, GSSException.BAD_NAME, GSSException.BAD_MECH, GSSException.FAILURE
See Also:
GSSName.canonicalize(Oid), GSSName.NT_EXPORT_NAME

createName

public abstract GSSName createName(byte[] name,
                                   Oid nameType,
                                   Oid mech)
                            throws GSSException
Factory method to convert a byte array containing a name from the specified namespace to a GSSName object and canonicalize it at the same time for a mechanism. In other words, this method is a utility that does the equivalent of two steps: the createName and then also GSSName.canonicalize.

Parameters:
name - the byte array containing the name to create
nameType - the Oid specifying the namespace of the name supplied in the byte array. null can be used to specify that a mechanism specific default syntax should be assumed by each mechanism that examines the byte array.
mech - Oid specifying the mechanism for which the name should be canonicalized
Returns:
a GSSName representing the indicated principal
Throws:
GSSException - containing the following major error codes: GSSException.BAD_NAMETYPE, GSSException.BAD_NAME, GSSException.BAD_MECH, GSSException.FAILURE
See Also:
GSSName.canonicalize(Oid), GSSName.NT_EXPORT_NAME

createCredential

public abstract GSSCredential createCredential(int usage)
                                        throws GSSException
Factory method for acquiring default credentials. This will cause the GSS-API to use system specific defaults for the set of mechanisms, name, and lifetime.

GSS-API mechanism providers must impose a local access-control policy on callers to prevent unauthorized callers from acquiring credentials to which they are not entitled. The kinds of permissions needed by different mechanism providers will be documented on a per-mechanism basis. A failed permission check might cause a SecurityException to be thrown from this method.

Parameters:
usage - The intended usage for this credential object. The value of this parameter must be one of: GSSCredential.INITIATE_AND_ACCEPT, GSSCredential.ACCEPT_ONLY, and GSSCredential.INITIATE_ONLY.
Returns:
a GSSCredential of the requested type.
Throws:
GSSException - containing the following major error codes: GSSException.BAD_MECH, GSSException.BAD_NAMETYPE, GSSException.BAD_NAME, GSSException.CREDENTIALS_EXPIRED, GSSException.NO_CRED, GSSException.FAILURE
See Also:
GSSCredential

createCredential

public abstract GSSCredential createCredential(GSSName name,
                                               int lifetime,
                                               Oid mech,
                                               int usage)
                                        throws GSSException
Factory method for acquiring a single mechanism credential.

GSS-API mechanism providers must impose a local access-control policy on callers to prevent unauthorized callers from acquiring credentials to which they are not entitled. The kinds of permissions needed by different mechanism providers will be documented on a per-mechanism basis. A failed permission check might cause a SecurityException to be thrown from this method.

Non-default values for lifetime cannot always be honored by the underlying mechanisms, thus applications should be prepared to call getRemainingLifetime on the returned credential.

Parameters:
name - the name of the principal for whom this credential is to be acquired. Use null to specify the default principal.
lifetime - The number of seconds that credentials should remain valid. Use GSSCredential.INDEFINITE_LIFETIME to request that the credentials have the maximum permitted lifetime. Use GSSCredential.DEFAULT_LIFETIME to request default credential lifetime.
mech - the Oid of the desired mechanism. Use (Oid) null to request the default mechanism.
usage - The intended usage for this credential object. The value of this parameter must be one of: GSSCredential.INITIATE_AND_ACCEPT, GSSCredential.ACCEPT_ONLY, and GSSCredential.INITIATE_ONLY.
Returns:
a GSSCredential of the requested type.
Throws:
GSSException - containing the following major error codes: GSSException.BAD_MECH, GSSException.BAD_NAMETYPE, GSSException.BAD_NAME, GSSException.CREDENTIALS_EXPIRED, GSSException.NO_CRED, GSSException.FAILURE
See Also:
GSSCredential

createCredential

public abstract GSSCredential createCredential(GSSName name,
                                               int lifetime,
                                               Oid[] mechs,
                                               int usage)
                                        throws GSSException
Factory method for acquiring credentials over a set of mechanisms. This method attempts to acquire credentials for each of the mechanisms specified in the array called mechs. To determine the list of mechanisms for which the acquisition of credentials succeeded, the caller should use the GSSCredential.getMechs method.

GSS-API mechanism providers must impose a local access-control policy on callers to prevent unauthorized callers from acquiring credentials to which they are not entitled. The kinds of permissions needed by different mechanism providers will be documented on a per-mechanism basis. A failed permission check might cause a SecurityException to be thrown from this method.

Non-default values for lifetime cannot always be honored by the underlying mechanisms, thus applications should be prepared to call getRemainingLifetime on the returned credential.

Parameters:
name - the name of the principal for whom this credential is to be acquired. Use null to specify the default principal.
lifetime - The number of seconds that credentials should remain valid. Use GSSCredential.INDEFINITE_LIFETIME to request that the credentials have the maximum permitted lifetime. Use GSSCredential.DEFAULT_LIFETIME to request default credential lifetime.
mechs - an array of Oid's indicating the mechanisms over which the credential is to be acquired. Use (Oid[]) null for requesting a system specific default set of mechanisms.
usage - The intended usage for this credential object. The value of this parameter must be one of: GSSCredential.INITIATE_AND_ACCEPT, GSSCredential.ACCEPT_ONLY, and GSSCredential.INITIATE_ONLY.
Returns:
a GSSCredential of the requested type.
Throws:
GSSException - containing the following major error codes: GSSException.BAD_MECH, GSSException.BAD_NAMETYPE, GSSException.BAD_NAME, GSSException.CREDENTIALS_EXPIRED, GSSException.NO_CRED, GSSException.FAILURE
See Also:
GSSCredential

createContext

public abstract GSSContext createContext(GSSName peer,
                                         Oid mech,
                                         GSSCredential myCred,
                                         int lifetime)
                                  throws GSSException
Factory method for creating a context on the initiator's side. Some mechanism providers might require that the caller be granted permission to initiate a security context. A failed permission check might cause a SecurityException to be thrown from this method.

Non-default values for lifetime cannot always be honored by the underlying mechanism, thus applications should be prepared to call getLifetime on the returned context.

Parameters:
peer - the name of the target peer.
mech - the Oid of the desired mechanism. Use null to request the default mechanism.
myCred - the credentials of the initiator. Use null to act as the default initiator principal.
lifetime - the lifetime, in seconds, requested for the context. Use GSSContext.INDEFINITE_LIFETIME to request that the context have the maximum permitted lifetime. Use GSSContext.DEFAULT_LIFETIME to request a default lifetime for the context.
Returns:
an unestablished GSSContext
Throws:
GSSException - containing the following major error codes: GSSException.NO_CRED GSSException.CREDENTIALS_EXPIRED GSSException.BAD_NAMETYPE GSSException.BAD_MECH GSSException.FAILURE
See Also:
GSSContext

createContext

public abstract GSSContext createContext(GSSCredential myCred)
                                  throws GSSException
Factory method for creating a context on the acceptor' side. The context's properties will be determined from the input token supplied to the accept method. Some mechanism providers might require that the caller be granted permission to accept a security context. A failed permission check might cause a SecurityException to be thrown from this method.

Parameters:
myCred - the credentials for the acceptor. Use null to act as a default acceptor principal.
Returns:
an unestablished GSSContext
Throws:
GSSException - containing the following major error codes: GSSException.NO_CRED GSSException.CREDENTIALS_EXPIRED GSSException.BAD_MECH GSSException.FAILURE
See Also:
GSSContext

createContext

public abstract GSSContext createContext(byte[] interProcessToken)
                                  throws GSSException
Factory method for creating a previously exported context. The context properties will be determined from the input token and cannot be modified through the set methods.

Implementations are not required to support the inter-process transfer of security contexts. Before exporting a context, calling the GSSContext.isTransferable will indicate if the context is transferable. Calling this method in an implementation that does not support it will result in a GSSException with the error code GSSException.UNAVAILABLE. Some mechanism providers might require that the caller be granted permission to initiate or accept a security context. A failed permission check might cause a SecurityException to be thrown from this method.

Parameters:
interProcessToken - the token previously emitted from the export method.
Returns:
the previously established GSSContext
Throws:
GSSException - containing the following major error codes: GSSException.NO_CONTEXT, GSSException.DEFECTIVE_TOKEN, GSSException.UNAVAILABLE, GSSException.UNAUTHORIZED, GSSException.FAILURE
See Also:
GSSContext

addProviderAtFront

public abstract void addProviderAtFront(Provider p,
                                        Oid mech)
                                 throws GSSException
This method is used to indicate to the GSSManager that the application would like a particular provider to be used ahead of all others when support is desired for the given mechanism. When a value of null is used instead of an Oid for the mechanism, the GSSManager must use the indicated provider ahead of all others no matter what the mechanism is. Only when the indicated provider does not support the needed mechanism should the GSSManager move on to a different provider.

Calling this method repeatedly preserves the older settings but lowers them in preference thus forming an ordered list of provider and Oid pairs that grows at the top.

Calling addProviderAtFront with a null Oid will remove all previous preferences that were set for this provider in the GSSManager instance. Calling addProviderAtFront with a non-null Oid will remove any previous preference that was set using this mechanism and this provider together.

If the GSSManager implementation does not support an SPI with a pluggable provider architecture it should throw a GSSException with the status code GSSException.UNAVAILABLE to indicate that the operation is unavailable.

Suppose an application desired that the provider A always be checked first when any mechanism is needed, it would call:

         GSSManager mgr = GSSManager.getInstance();
         // mgr may at this point have its own pre-configured list
         // of provider preferences. The following will prepend to
         // any such list:

         mgr.addProviderAtFront(A, null);
Now if it also desired that the mechanism of Oid m1 always be obtained from the provider B before the previously set A was checked, it would call:

         mgr.addProviderAtFront(B, m1);
The GSSManager would then first check with B if m1 was needed. In case B did not provide support for m1, the GSSManager would continue on to check with A. If any mechanism m2 is needed where m2 is different from m1 then the GSSManager would skip B and check with A directly.

Suppose at a later time the following call is made to the same GSSManager instance:

         mgr.addProviderAtFront(B, null)
then the previous setting with the pair (B, m1) is subsumed by this and should be removed. Effectively the list of preferences now becomes {(B, null), (A, null), ... //followed by the pre-configured list.

Please note, however, that the following call:

         mgr.addProviderAtFront(A, m3)
does not subsume the previous setting of (A, null) and the list will effectively become {(A, m3), (B, null), (A, null), ...}

Parameters:
p - the provider instance that should be used whenever support is needed for mech.
mech - the mechanism for which the provider is being set
Throws:
GSSException - containing the following major error codes: GSSException.UNAVAILABLE, GSSException.FAILURE

addProviderAtEnd

public abstract void addProviderAtEnd(Provider p,
                                      Oid mech)
                               throws GSSException
This method is used to indicate to the GSSManager that the application would like a particular provider to be used if no other provider can be found that supports the given mechanism. When a value of null is used instead of an Oid for the mechanism, the GSSManager must use the indicated provider for any mechanism.

Calling this method repeatedly preserves the older settings but raises them above newer ones in preference thus forming an ordered list of providers and Oid pairs that grows at the bottom. Thus the older provider settings will be utilized first before this one is.

If there are any previously existing preferences that conflict with the preference being set here, then the GSSManager should ignore this request.

If the GSSManager implementation does not support an SPI with a pluggable provider architecture it should throw a GSSException with the status code GSSException.UNAVAILABLE to indicate that the operation is unavailable.

Suppose an application desired that when a mechanism of Oid m1 is needed the system default providers always be checked first, and only when they do not support m1 should a provider A be checked. It would then make the call:

         GSSManager mgr = GSSManager.getInstance();
         mgr.addProviderAtEnd(A, m1);
Now, if it also desired that for all mechanisms the provider B be checked after all configured providers have been checked, it would then call:

         mgr.addProviderAtEnd(B, null);
Effectively the list of preferences now becomes {..., (A, m1), (B, null)}.

Suppose at a later time the following call is made to the same GSSManager instance:

         mgr.addProviderAtEnd(B, m2)
then the previous setting with the pair (B, null) subsumes this and therefore this request should be ignored. The same would happen if a request is made for the already existing pairs of (A, m1) or (B, null).

Please note, however, that the following call:

         mgr.addProviderAtEnd(A, null)
is not subsumed by the previous setting of (A, m1) and the list will effectively become {..., (A, m1), (B, null), (A, null)}

Parameters:
p - the provider instance that should be used whenever support is needed for mech.
mech - the mechanism for which the provider is being set
Throws:
GSSException - containing the following major error codes: GSSException.UNAVAILABLE, GSSException.FAILURE
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


GSSName (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.ietf.jgss
Interface GSSName

public interface GSSName

This interface encapsulates a single GSS-API principal entity. The application obtains an implementation of this interface through one of the createName methods that exist in the GSSManager class. Conceptually a GSSName contains many representations of the entity or many primitive name elements, one for each supported underlying mechanism. In GSS terminology, a GSSName that contains an element from just one mechanism is called a Mechanism Name (MN)

Since different authentication mechanisms may employ different namespaces for identifying their principals, GSS-API's naming support is necessarily complex in multi-mechanism environments (or even in some single-mechanism environments where the underlying mechanism supports multiple namespaces). Different name formats and their definitions are identified with Oid's and some standard types are defind in this interface. The format of the names can be derived based on the unique Oid of its name type.

Included below are code examples utilizing the GSSName interface. The code below creates a GSSName, converts it to an MN, performs a comparison, obtains a printable representation of the name, exports it to a byte array and then re-imports to obtain a new GSSName.

      GSSManager manager = GSSManager.getInstance();

      // create a host based service name
      GSSName name = manager.createName("service@host",
                   GSSName.NT_HOSTBASED_SERVICE);

      Oid krb5 = new Oid("1.2.840.113554.1.2.2");

      GSSName mechName = name.canonicalize(krb5);

      // the above two steps are equivalent to the following
      GSSName mechName = manager.createName("service@host",
                      GSSName.NT_HOSTBASED_SERVICE, krb5);

      // perform name comparison
      if (name.equals(mechName))
              print("Names are equals.");

      // obtain textual representation of name and its printable
      // name type
      print(mechName.toString() +
                      mechName.getStringNameType().toString());

      // export and re-import the name
      byte [] exportName = mechName.export();

      // create a new name object from the exported buffer
      GSSName newName = manager.createName(exportName,
                      GSSName.NT_EXPORT_NAME);

Since:
1.4
See Also:
export(),
equals(GSSName),
GSSManager.createName(String, Oid),
GSSManager.createName(String, Oid, Oid),
GSSManager.createName(byte[], Oid)

Field Summary
static Oid | NT_ANONYMOUS Name type for representing an anonymous entity.
static Oid | NT_EXPORT_NAME Name type used to indicate an exported name produced by the export method.
static Oid | NT_HOSTBASED_SERVICE Oid indicating a host-based service name form.
static Oid | NT_MACHINE_UID_NAME Name type to indicate a numeric user identifier corresponding to a user on a local system.
static Oid | NT_STRING_UID_NAME Name type to indicate a string of digits representing the numeric user identifier of a user on a local system.
static Oid | NT_USER_NAME Name type to indicate a named user on a local system.
Method Summary
GSSName | canonicalize(Oid mech) Creates a name that is canonicalized for some mechanism.
boolean | equals(GSSName another) Compares two GSSName objects to determine if they refer to the same entity.
boolean | equals(Object another) Compares this GSSName object to another Object that might be a GSSName.
byte[] | export() Returns a canonical contiguous byte representation of a mechanism name (MN), suitable for direct, byte by byte comparison by authorization functions.
Oid | getStringNameType() Returns the name type of the printable representation of this name that can be obtained from the toString method.
int | hashCode() Returns a hashcode value for this GSSName.
boolean | isAnonymous() Tests if this name object represents an anonymous entity.
boolean | isMN() Tests if this name object represents a Mechanism Name (MN).
String | toString() Returns a textual representation of the GSSName object.

Field Detail

NT_HOSTBASED_SERVICE

public static final Oid NT_HOSTBASED_SERVICE
Oid indicating a host-based service name form. It is used to represent services associated with host computers. This name form is constructed using two elements, "service" and "hostname", as follows: service@hostname.

It represents the following Oid value:
{ 1(iso), 3(org), 6(dod), 1(internet), 5(security), 6(nametypes), 2(gss-host-based-services) }

NT_USER_NAME

public static final Oid NT_USER_NAME
Name type to indicate a named user on a local system.

 It represents the following Oid value:
{ iso(1) member-body(2) United
 States(840) mit(113554) infosys(1) gssapi(2) generic(1) user_name(1)
 }

NT_MACHINE_UID_NAME

public static final Oid NT_MACHINE_UID_NAME
Name type to indicate a numeric user identifier corresponding to a user on a local system. (e.g. Uid).

It represents the following Oid value:
{ iso(1) member-body(2) United States(840) mit(113554) infosys(1) gssapi(2) generic(1) machine_uid_name(2) }

NT_STRING_UID_NAME

public static final Oid NT_STRING_UID_NAME
Name type to indicate a string of digits representing the numeric user identifier of a user on a local system.

 It represents the following Oid value:
{ iso(1) member-body(2) United
 States(840) mit(113554) infosys(1) gssapi(2) generic(1)
 string_uid_name(3) }

NT_ANONYMOUS

public static final Oid NT_ANONYMOUS
Name type for representing an anonymous entity.

It represents the following Oid value:
{ 1(iso), 3(org), 6(dod), 1(internet), 5(security), 6(nametypes), 3(gss-anonymous-name) }

NT_EXPORT_NAME

public static final Oid NT_EXPORT_NAME
Name type used to indicate an exported name produced by the export method.

It represents the following Oid value:
{ 1(iso), 3(org), 6(dod), 1(internet), 5(security), 6(nametypes), 4(gss-api-exported-name) }

Method Detail

equals

public boolean equals(GSSName another)
               throws GSSException
Compares two GSSName objects to determine if they refer to the same entity.

Parameters:
another - the GSSName to compare this name with
Returns:
true if the two names contain at least one primitive element in common. If either of the names represents an anonymous entity, the method will return false.
Throws:
GSSException - when the names cannot be compared, containing the following major error codes: GSSException.BAD_NAMETYPE, GSSException.FAILURE

equals

public boolean equals(Object another)
Compares this GSSName object to another Object that might be a GSSName. The behaviour is exactly the same as in equals except that no GSSException is thrown; instead, false will be returned in the situation where an error occurs.

Overrides:
equals in class Object
Parameters:
another - the object to compare this name to
Returns:
true if the object to compare to is also a GSSName and the two names refer to the same entity.
See Also:
equals(GSSName)

hashCode

public int hashCode()
Returns a hashcode value for this GSSName.

Overrides:
hashCode in class Object
Returns:
a hashCode value
See Also:
Object.equals(java.lang.Object), Hashtable

canonicalize

public GSSName canonicalize(Oid mech)
                     throws GSSException
Creates a name that is canonicalized for some mechanism.

Parameters:
mech - the oid for the mechanism for which the canonical form of the name is requested.
Returns:
a GSSName that contains just one primitive element representing this name in a canonicalized form for the desired mechanism.
Throws:
GSSException - containing the following major error codes: GSSException.BAD_MECH, GSSException.BAD_NAMETYPE, GSSException.BAD_NAME, GSSException.FAILURE

export

public byte[] export()
              throws GSSException
Returns a canonical contiguous byte representation of a mechanism name (MN), suitable for direct, byte by byte comparison by authorization functions. If the name is not an MN, implementations may throw a GSSException with the NAME_NOT_MN status code. If an implementation chooses not to throw an exception, it should use some system specific default mechanism to canonicalize the name and then export it. Structurally, an exported name object consists of a header containing an OID identifying the mechanism that authenticated the name, and a trailer containing the name itself, where the syntax of the trailer is defined by the individual mechanism specification. The format of the header of the output buffer is specified in RFC 2743.

The exported name is useful when used in large access control lists where the overhead of creating a GSSName object on each name and invoking the equals method on each name from the ACL may be prohibitive.

Exported names may be re-imported by using the byte array factory method GSSManager.createName and specifying the NT_EXPORT_NAME as the name type object identifier. The resulting GSSName name will also be a MN.

Returns:
a byte[] containing the exported name. RFC 2743 defines the "Mechanism-Independent Exported Name Object Format" for these bytes.
Throws:
GSSException - containing the following major error codes: GSSException.BAD_NAME, GSSException.BAD_NAMETYPE, GSSException.FAILURE

toString

public String toString()
Returns a textual representation of the GSSName object. To retrieve the printed name format, which determines the syntax of the returned string, use the getStringNameType method.

Overrides:
toString in class Object
Returns:
a String representing this name in printable form.

getStringNameType

public Oid getStringNameType()
                      throws GSSException
Returns the name type of the printable representation of this name that can be obtained from the toString method.

Returns:
an Oid representing the namespace of the name returned from the toString method.
Throws:
GSSException - containing the following major error codes: GSSException.FAILURE

isAnonymous

public boolean isAnonymous()
Tests if this name object represents an anonymous entity.

Returns:
true if this is an anonymous name, false otherwise.

isMN

public boolean isMN()
Tests if this name object represents a Mechanism Name (MN). An MN is a GSSName the contains exactly one mechanism's primitive name element.

Returns:
true if this is an MN, false otherwise.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


MessageProp (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.ietf.jgss
Class MessageProp

java.lang.Object
    extended by org.ietf.jgss.MessageProp
public class MessageProp
extends Object

This is a utility class used within the per-message GSSContext methods to convey per-message properties.

When used with the GSSContext interface's wrap and getMIC methods, an instance of this class is used to indicate the desired Quality-of-Protection (QOP) and to request if confidentiality services are to be applied to caller supplied data (wrap only). To request default QOP, the value of 0 should be used for QOP.

When used with the unwrap and verifyMIC methods of the GSSContext interface, an instance of this class will be used to indicate the applied QOP and confidentiality services over the supplied message. In the case of verifyMIC, the confidentiality state will always be false. Upon return from these methods, this object will also contain any supplementary status values applicable to the processed token. The supplementary status values can indicate old tokens, out of sequence tokens, gap tokens or duplicate tokens.

Since:
1.4
See Also:
GSSContext.wrap(byte[], int, int, org.ietf.jgss.MessageProp),
GSSContext.unwrap(byte[], int, int, org.ietf.jgss.MessageProp),
GSSContext.getMIC(byte[], int, int, org.ietf.jgss.MessageProp),
GSSContext.verifyMIC(byte[], int, int, byte[], int, int, org.ietf.jgss.MessageProp)

Constructor Summary
MessageProp(boolean privState)
Constructor which sets the desired privacy state.
MessageProp(int qop, boolean privState)
Constructor which sets the values for the qop and privacy state.
Method Summary
int | getMinorStatus() Retrieves the minor status code that the underlying mechanism might have set for this per-message operation.
String | getMinorString() Retrieves a string explaining the minor status code.
boolean | getPrivacy() Retrieves the privacy state.
int | getQOP() Retrieves the QOP value.
boolean | isDuplicateToken() Tests if this is a duplicate of an earlier token.
boolean | isGapToken() Tests if an expected token was not received, i.e., one or more predecessor tokens have not yet been successfully processed.
boolean | isOldToken() Tests if this token's validity period has expired, i.e., the token is too old to be checked for duplication.
boolean | isUnseqToken() Tests if a later token had already been processed.
void | setPrivacy(boolean privState) Sets the privacy state.
void | setQOP(int qop) Sets the QOP value.
void | setSupplementaryStates(boolean duplicate, boolean old, boolean unseq, boolean gap, int minorStatus, String minorString) This method sets the state for the supplementary information flags and the minor status in MessageProp.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

MessageProp

public MessageProp(boolean privState)
Constructor which sets the desired privacy state. The QOP value used is 0.

Parameters:
privState - the privacy (i.e. confidentiality) state

MessageProp

public MessageProp(int qop,
                   boolean privState)
Constructor which sets the values for the qop and privacy state.

Parameters:
qop - the QOP value
privState - the privacy (i.e. confidentiality) state
Method Detail

getQOP

public int getQOP()
Retrieves the QOP value.

Returns:
an int representing the QOP value
See Also:
setQOP(int)

getPrivacy

public boolean getPrivacy()
Retrieves the privacy state.

Returns:
true if the privacy (i.e., confidentiality) state is true, false otherwise.
See Also:
setPrivacy(boolean)

setQOP

public void setQOP(int qop)
Sets the QOP value.

Parameters:
qop - the int value to set the QOP to
See Also:
getQOP()

setPrivacy

public void setPrivacy(boolean privState)
Sets the privacy state.

Parameters:
privState - true is the privacy (i.e., confidentiality) state is true, false otherwise.
See Also:
getPrivacy()

isDuplicateToken

public boolean isDuplicateToken()
Tests if this is a duplicate of an earlier token.

Returns:
true if this is a duplicate, false otherwise.

isOldToken

public boolean isOldToken()
Tests if this token's validity period has expired, i.e., the token is too old to be checked for duplication.

Returns:
true if the token's validity period has expired, false otherwise.

isUnseqToken

public boolean isUnseqToken()
Tests if a later token had already been processed.

Returns:
true if a later token had already been processed, false otherwise.

isGapToken

public boolean isGapToken()
Tests if an expected token was not received, i.e., one or more predecessor tokens have not yet been successfully processed.

Returns:
true if an expected per-message token was not received, false otherwise.

getMinorStatus

public int getMinorStatus()
Retrieves the minor status code that the underlying mechanism might have set for this per-message operation.

Returns:
the int minor status

getMinorString

public String getMinorString()
Retrieves a string explaining the minor status code.

Returns:
a String corresponding to the minor status code. null will be returned when no minor status code has been set.

setSupplementaryStates

public void setSupplementaryStates(boolean duplicate,
                                   boolean old,
                                   boolean unseq,
                                   boolean gap,
                                   int minorStatus,
                                   String minorString)
This method sets the state for the supplementary information flags and the minor status in MessageProp. It is not used by the application but by the GSS implementation to return this information to the caller of a per-message context method.

Parameters:
duplicate - true if the token was a duplicate of an earlier token, false otherwise
old - true if the token's validity period has expired, false otherwise
unseq - true if a later token has already been processed, false otherwise
gap - true if one or more predecessor tokens have not yet been successfully processed, false otherwise
minorStatus - the int minor status code for the per-message operation
minorString - the textual representation of the minorStatus value
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Oid (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.ietf.jgss
Class Oid

java.lang.Object
    extended by org.ietf.jgss.Oid
public class Oid
extends Object

This class represents Universal Object Identifiers (Oids) and their associated operations.

Oids are hierarchically globally-interpretable identifiers used within the GSS-API framework to identify mechanisms and name formats.

The structure and encoding of Oids is defined in ISOIEC-8824 and ISOIEC-8825. For example the Oid representation of Kerberos V5 mechanism is "1.2.840.113554.1.2.2"

The GSSName name class contains public static Oid objects representing the standard name types defined in GSS-API.

Since:
1.4

Constructor Summary
Oid(byte[] data)
Creates an Oid object from its ASN.1 DER encoding.
Oid(InputStream derOid)
Creates an Oid object from its ASN.1 DER encoding.
Oid(String strOid)
Constructs an Oid object from a string representation of its integer components.
Method Summary
boolean | containedIn(Oid[] oids) A utility method to test if this Oid value is contained within the supplied Oid array.
boolean | equals(Object other) Tests if two Oid objects represent the same Object identifier value.
byte[] | getDER() Returns the full ASN.1 DER encoding for this oid object, which includes the tag and length.
int | hashCode() Returns a hashcode value for this Oid.
String | toString() Returns a string representation of the oid's integer components in dot separated notation.
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait

Constructor Detail

Oid

public Oid(String strOid)
    throws GSSException
Constructs an Oid object from a string representation of its integer components.

Parameters:
strOid - the dot separated string representation of the oid. For instance, "1.2.840.113554.1.2.2".
Throws:
GSSException - may be thrown when the string is incorrectly formatted

Oid

public Oid(InputStream derOid)
    throws GSSException
Creates an Oid object from its ASN.1 DER encoding. This refers to the full encoding including tag and length. The structure and encoding of Oids is defined in ISOIEC-8824 and ISOIEC-8825. This method is identical in functionality to its byte array counterpart.

Parameters:
derOid - stream containing the DER encoded oid
Throws:
GSSException - may be thrown when the DER encoding does not follow the prescribed format.

Oid

public Oid(byte[] data)
    throws GSSException
Creates an Oid object from its ASN.1 DER encoding. This refers to the full encoding including tag and length. The structure and encoding of Oids is defined in ISOIEC-8824 and ISOIEC-8825. This method is identical in functionality to its InputStream conterpart.

Parameters:
data - byte array containing the DER encoded oid
Throws:
GSSException - may be thrown when the DER encoding does not follow the prescribed format.
Method Detail

toString

public String toString()
Returns a string representation of the oid's integer components in dot separated notation.

Overrides:
toString in class Object
Returns:
string representation in the following format: "1.2.3.4.5"

equals

public boolean equals(Object other)
Tests if two Oid objects represent the same Object identifier value.

Overrides:
equals in class Object
Parameters:
other - the Oid object that has to be compared to this one
Returns:
true if the two Oid objects represent the same value, false otherwise.
See Also:
Object.hashCode(), Hashtable

getDER

public byte[] getDER()
              throws GSSException
Returns the full ASN.1 DER encoding for this oid object, which includes the tag and length.

Returns:
byte array containing the DER encoding of this oid object.
Throws:
GSSException - may be thrown when the oid can't be encoded

containedIn

public boolean containedIn(Oid[] oids)
A utility method to test if this Oid value is contained within the supplied Oid array.

Parameters:
oids - the array of Oid's to search
Returns:
true if the array contains this Oid value, false otherwise

hashCode

public int hashCode()
Returns a hashcode value for this Oid.

Overrides:
hashCode in class Object
Returns:
a hashCode value
See Also:
Object.equals(java.lang.Object), Hashtable
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


org.ietf.jgss (Java 2 Platform SE v1.4.2)

 org.ietf.jgss
Interfaces
GSSContext
GSSCredential
GSSName
Classes
ChannelBinding
GSSManager
MessageProp
Oid
Exceptions
GSSException


org.ietf.jgss (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

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.

See:
Description

Interface Summary
GSSContext | This interface encapsulates the GSS-API security context and provides the security services that are available over the context.
GSSCredential | This interface encapsulates the GSS-API credentials for an entity.
GSSName | This interface encapsulates a single GSS-API principal entity.

Class Summary
ChannelBinding | This class encapsulates the concept of caller-provided channel binding information.
GSSManager | This class serves as a factory for other important GSS-API classes and also provides information about the mechanisms that are supported.
MessageProp | This is a utility class used within the per-message GSSContext methods to convey per-message properties.
Oid | This class represents Universal Object Identifiers (Oids) and their associated operations.

Exception Summary
GSSException This exception is thrown whenever a GSS-API error occurs, including any mechanism specific error.

Package org.ietf.jgss Description

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. The security mechanisms that an application can chose to use are identified with unique object identifiers. One example of such a mechanism is the Kerberos v5 GSS-API mechanism (object identifier 1.2.840.113554.1.2.2). This mechanism is available through the default instance of the GSSManager class.

The GSS-API is defined in a language independent way in RFC 2743. The Java language bindings are defined in RFC 2853

An application starts out by instantiating a GSSManager which then serves as a factory for a security context. An application can use specific principal names and credentials that are also created using the GSSManager; or it can instantiate a context with system defaults. It then goes through a context establishment loop. Once a context is established with the peer, authentication is complete. Data protection such as integrity and confidentiality can then be obtained from this context.

The GSS-API does not perform any communication with the peer. It merely produces tokens that the application must somehow transport to the other end.

Credential Acquisition

The GSS-API itself does not dictate how an underlying mechanism obtains the credentials that are needed for authentication. It is assumed that prior to calling the GSS-API, these credentials are obtained and stored in a location that the mechanism provider is aware of. However, the default model in the Java 2 platform will be that mechanism providers must obtain credentials only from the private or public credential sets associated with the Subject in the current access control context. The Kerberos v5 mechanism will search for the required INITIATE and ACCEPT credentials (KerberosTicket and KerberosKey) in the private credential set where as some other mechanism might look in the public set or in both. If the desired credential is not present in the appropriate sets of the current Subject, the GSS-API call must fail.

This model has the advantage that credential management is simple and predictable from the applications 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 JGSS mechanism would fail, or if it renewed a time based credential it would be sure that a JGSS mechanism would succeed.

This model does require that a JAAS login be performed in order to authenticate and populate a Subject that the JGSS mechnanism can later utilize. However, applications have the ability to relax this restiction by means of a system property: javax.security.auth.useSubjectCredsOnly. By default this system property will be assumed to be true (even when it is unset) indicating that providers must only use the credentials that are present in the current Subject. However, if this property is explicitly set to false by the application, then it indicates that the provider is free to use any credentials cache of its choice. Such a credential cache might be a disk cache, an in-memory cache, or even just the current Subject itself.

Related Documentation

For an online tutorial on using Java GSS-API, please see Introduction to JAAS and Java GSS-API.

Since:
1.4
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


org.ietf.jgss Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package org.ietf.jgss

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class org.ietf.jgss.ChannelBinding
    • class org.ietf.jgss.GSSManager
    • class org.ietf.jgss.MessageProp
    • class org.ietf.jgss.Oid
    • class java.lang.Throwable (implements java.io.Serializable)
      • class java.lang.Exception
        • class org.ietf.jgss.GSSException

Interface Hierarchy

  • interface java.lang.Cloneable
    • interface org.ietf.jgss.GSSCredential
  • interface org.ietf.jgss.GSSContext
  • interface org.ietf.jgss.GSSName
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package org.ietf.jgss (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
org.ietf.jgss

Packages that use org.ietf.jgss
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.

Classes in org.ietf.jgss used by org.ietf.jgss
ChannelBinding
This class encapsulates the concept of caller-provided channel binding information.
GSSContext
This interface encapsulates the GSS-API security context and provides the security services that are available over the context.
GSSCredential
This interface encapsulates the GSS-API credentials for an entity.
GSSException
This exception is thrown whenever a GSS-API error occurs, including any mechanism specific error.
GSSManager
This class serves as a factory for other important GSS-API classes and also provides information about the mechanisms that are supported.
GSSName
This interface encapsulates a single GSS-API principal entity.
MessageProp
This is a utility class used within the per-message GSSContext methods to convey per-message properties.
Oid
This class represents Universal Object Identifiers (Oids) and their associated operations.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.ietf.jgss.ChannelBinding (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.ietf.jgss.ChannelBinding

Packages that use ChannelBinding
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.

Uses of ChannelBinding in org.ietf.jgss

Methods in org.ietf.jgss with parameters of type ChannelBinding
 void GSSContext.setChannelBinding(ChannelBinding cb)
Sets the channel bindings to be used during context establishment.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.ietf.jgss.GSSContext (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.ietf.jgss.GSSContext

Packages that use GSSContext
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.

Uses of GSSContext in org.ietf.jgss

Methods in org.ietf.jgss that return GSSContext
abstract GSSContext | GSSManager.createContext(GSSName peer, Oid mech, GSSCredential myCred, int lifetime) Factory method for creating a context on the initiator's side.
abstract GSSContext | GSSManager.createContext(GSSCredential myCred) Factory method for creating a context on the acceptor' side.
abstract GSSContext | GSSManager.createContext(byte[] interProcessToken) Factory method for creating a previously exported context.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.ietf.jgss.GSSCredential (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.ietf.jgss.GSSCredential

Packages that use GSSCredential
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.

Uses of GSSCredential in org.ietf.jgss

Methods in org.ietf.jgss that return GSSCredential
GSSCredential | GSSContext.getDelegCred() Obtains the credentials delegated by the context initiator to the context acceptor.
abstract GSSCredential | GSSManager.createCredential(int usage) Factory method for acquiring default credentials.
abstract GSSCredential | GSSManager.createCredential(GSSName name, int lifetime, Oid mech, int usage) Factory method for acquiring a single mechanism credential.
abstract GSSCredential | GSSManager.createCredential(GSSName name, int lifetime, Oid[] mechs, int usage) Factory method for acquiring credentials over a set of mechanisms.

Methods in org.ietf.jgss with parameters of type GSSCredential
abstract GSSContext | GSSManager.createContext(GSSName peer, Oid mech, GSSCredential myCred, int lifetime) Factory method for creating a context on the initiator's side.
abstract GSSContext | GSSManager.createContext(GSSCredential myCred) Factory method for creating a context on the acceptor' side.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.ietf.jgss.GSSException (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.ietf.jgss.GSSException

Packages that use GSSException
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.

Uses of GSSException in org.ietf.jgss

Methods in org.ietf.jgss that throw GSSException
byte[] | GSSContext.initSecContext(byte[] inputBuf, int offset, int len) Called by the context initiator to start the context creation phase and process any tokens generated by the peer's acceptSecContext method.
int | GSSContext.initSecContext(InputStream inStream, OutputStream outStream) Called by the context initiator to start the context creation phase and process any tokens generated by the peer's acceptSecContext method using streams.
byte[] | GSSContext.acceptSecContext(byte[] inToken, int offset, int len) Called by the context acceptor upon receiving a token from the peer.
void | GSSContext.acceptSecContext(InputStream inStream, OutputStream outStream) Called by the context acceptor to process a token from the peer using streams.
void | GSSContext.dispose() Releases any system resources and cryptographic information stored in the context object and invalidates the context.
int | GSSContext.getWrapSizeLimit(int qop, boolean confReq, int maxTokenSize) Used to determine limits on the size of the message that can be passed to wrap.
byte[] | GSSContext.wrap(byte[] inBuf, int offset, int len, MessageProp msgProp) Applies per-message security services over the established security context.
void | GSSContext.wrap(InputStream inStream, OutputStream outStream, MessageProp msgProp) Applies per-message security services over the established security context using streams.
byte[] | GSSContext.unwrap(byte[] inBuf, int offset, int len, MessageProp msgProp) Used to process tokens generated by the wrap method on the other side of the context.
void | GSSContext.unwrap(InputStream inStream, OutputStream outStream, MessageProp msgProp) Uses streams to process tokens generated by the wrap method on the other side of the context.
byte[] | GSSContext.getMIC(byte[] inMsg, int offset, int len, MessageProp msgProp) Returns a token containing a cryptographic Message Integrity Code (MIC) for the supplied message, for transfer to the peer application.
void | GSSContext.getMIC(InputStream inStream, OutputStream outStream, MessageProp msgProp) Uses streams to produce a token containing a cryptographic MIC for the supplied message, for transfer to the peer application.
void | GSSContext.verifyMIC(byte[] inToken, int tokOffset, int tokLen, byte[] inMsg, int msgOffset, int msgLen, MessageProp msgProp) Verifies the cryptographic MIC, contained in the token parameter, over the supplied message.
void | GSSContext.verifyMIC(InputStream tokStream, InputStream msgStream, MessageProp msgProp) Uses streams to verify the cryptographic MIC, contained in the token parameter, over the supplied message.
byte[] | GSSContext.export() Exports this context so that another process may import it..
void | GSSContext.requestMutualAuth(boolean state) Requests that mutual authentication be done during context establishment.
void | GSSContext.requestReplayDet(boolean state) Requests that replay detection be enabled for the per-message security services after context establishemnt.
void | GSSContext.requestSequenceDet(boolean state) Requests that sequence checking be enabled for the per-message security services after context establishemnt.
void | GSSContext.requestCredDeleg(boolean state) Requests that the initiator's credentials be delegated to the acceptor during context establishment.
void | GSSContext.requestAnonymity(boolean state) Requests that the initiator's identity not be disclosed to the acceptor.
void | GSSContext.requestConf(boolean state) Requests that data confidentiality be enabled for the wrap method.
void | GSSContext.requestInteg(boolean state) Requests that data integrity be enabled for the wrap and getMICmethods.
void | GSSContext.requestLifetime(int lifetime) Requests a lifetime in seconds for the context.
void | GSSContext.setChannelBinding(ChannelBinding cb) Sets the channel bindings to be used during context establishment.
boolean | GSSContext.isTransferable() Determines if the context is transferable to other processes through the use of the export method.
GSSName | GSSContext.getSrcName() Returns the name of the context initiator.
GSSName | GSSContext.getTargName() Returns the name of the context acceptor.
Oid | GSSContext.getMech() Determines what mechanism is being used for this context.
GSSCredential | GSSContext.getDelegCred() Obtains the credentials delegated by the context initiator to the context acceptor.
boolean | GSSContext.isInitiator() Determines if this is the context initiator.
void | GSSCredential.dispose() Releases any sensitive information that the GSSCredential object may be containing.
GSSName | GSSCredential.getName() Retrieves the name of the entity that the credential asserts.
GSSName | GSSCredential.getName(Oid mech) Retrieves a Mechanism Name of the entity that the credential asserts.
int | GSSCredential.getRemainingLifetime() Returns the remaining lifetime in seconds for a credential.
int | GSSCredential.getRemainingInitLifetime(Oid mech) Returns the lifetime in seconds for the credential to remain capable of initiating security contexts using the specified mechanism.
int | GSSCredential.getRemainingAcceptLifetime(Oid mech) Returns the lifetime in seconds for the credential to remain capable of accepting security contexts using the specified mechanism.
int | GSSCredential.getUsage() Returns the credential usage mode.
int | GSSCredential.getUsage(Oid mech) Returns the credential usage mode for a specific mechanism.
Oid[] | GSSCredential.getMechs() Returns a list of mechanisms supported by this credential.
void | GSSCredential.add(GSSName name, int initLifetime, int acceptLifetime, Oid mech, int usage) Adds a mechanism specific credential-element to an existing credential.
abstract Oid[] | GSSManager.getNamesForMech(Oid mech) Returns then name types supported by the indicated mechanism.
abstract GSSName | GSSManager.createName(String nameStr, Oid nameType) Factory method to convert a string name from the specified namespace to a GSSName object.
abstract GSSName | GSSManager.createName(byte[] name, Oid nameType) Factory method to convert a byte array containing a name from the specified namespace to a GSSName object.
abstract GSSName | GSSManager.createName(String nameStr, Oid nameType, Oid mech) Factory method to convert a string name from the specified namespace to a GSSName object and canonicalize it at the same time for a mechanism.
abstract GSSName | GSSManager.createName(byte[] name, Oid nameType, Oid mech) Factory method to convert a byte array containing a name from the specified namespace to a GSSName object and canonicalize it at the same time for a mechanism.
abstract GSSCredential | GSSManager.createCredential(int usage) Factory method for acquiring default credentials.
abstract GSSCredential | GSSManager.createCredential(GSSName name, int lifetime, Oid mech, int usage) Factory method for acquiring a single mechanism credential.
abstract GSSCredential | GSSManager.createCredential(GSSName name, int lifetime, Oid[] mechs, int usage) Factory method for acquiring credentials over a set of mechanisms.
abstract GSSContext | GSSManager.createContext(GSSName peer, Oid mech, GSSCredential myCred, int lifetime) Factory method for creating a context on the initiator's side.
abstract GSSContext | GSSManager.createContext(GSSCredential myCred) Factory method for creating a context on the acceptor' side.
abstract GSSContext | GSSManager.createContext(byte[] interProcessToken) Factory method for creating a previously exported context.
abstract void | GSSManager.addProviderAtFront(Provider p, Oid mech) This method is used to indicate to the GSSManager that the application would like a particular provider to be used ahead of all others when support is desired for the given mechanism.
abstract void | GSSManager.addProviderAtEnd(Provider p, Oid mech) This method is used to indicate to the GSSManager that the application would like a particular provider to be used if no other provider can be found that supports the given mechanism.
boolean | GSSName.equals(GSSName another) Compares two GSSName objects to determine if they refer to the same entity.
GSSName | GSSName.canonicalize(Oid mech) Creates a name that is canonicalized for some mechanism.
byte[] | GSSName.export() Returns a canonical contiguous byte representation of a mechanism name (MN), suitable for direct, byte by byte comparison by authorization functions.
Oid | GSSName.getStringNameType() Returns the name type of the printable representation of this name that can be obtained from the toString method.
byte[] | Oid.getDER() Returns the full ASN.1 DER encoding for this oid object, which includes the tag and length.

Constructors in org.ietf.jgss that throw GSSException
Oid(String strOid)
Constructs an Oid object from a string representation of its integer components.
Oid(InputStream derOid)
Creates an Oid object from its ASN.1 DER encoding.
Oid(byte[] data)
Creates an Oid object from its ASN.1 DER encoding.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.ietf.jgss.GSSManager (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.ietf.jgss.GSSManager

Packages that use GSSManager
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.

Uses of GSSManager in org.ietf.jgss

Methods in org.ietf.jgss that return GSSManager
static GSSManager GSSManager.getInstance()
Returns the default GSSManager implementation.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.ietf.jgss.GSSName (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.ietf.jgss.GSSName

Packages that use GSSName
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.

Uses of GSSName in org.ietf.jgss

Methods in org.ietf.jgss that return GSSName
GSSName | GSSContext.getSrcName() Returns the name of the context initiator.
GSSName | GSSContext.getTargName() Returns the name of the context acceptor.
GSSName | GSSCredential.getName() Retrieves the name of the entity that the credential asserts.
GSSName | GSSCredential.getName(Oid mech) Retrieves a Mechanism Name of the entity that the credential asserts.
abstract GSSName | GSSManager.createName(String nameStr, Oid nameType) Factory method to convert a string name from the specified namespace to a GSSName object.
abstract GSSName | GSSManager.createName(byte[] name, Oid nameType) Factory method to convert a byte array containing a name from the specified namespace to a GSSName object.
abstract GSSName | GSSManager.createName(String nameStr, Oid nameType, Oid mech) Factory method to convert a string name from the specified namespace to a GSSName object and canonicalize it at the same time for a mechanism.
abstract GSSName | GSSManager.createName(byte[] name, Oid nameType, Oid mech) Factory method to convert a byte array containing a name from the specified namespace to a GSSName object and canonicalize it at the same time for a mechanism.
GSSName | GSSName.canonicalize(Oid mech) Creates a name that is canonicalized for some mechanism.

Methods in org.ietf.jgss with parameters of type GSSName
void | GSSCredential.add(GSSName name, int initLifetime, int acceptLifetime, Oid mech, int usage) Adds a mechanism specific credential-element to an existing credential.
abstract GSSCredential | GSSManager.createCredential(GSSName name, int lifetime, Oid mech, int usage) Factory method for acquiring a single mechanism credential.
abstract GSSCredential | GSSManager.createCredential(GSSName name, int lifetime, Oid[] mechs, int usage) Factory method for acquiring credentials over a set of mechanisms.
abstract GSSContext | GSSManager.createContext(GSSName peer, Oid mech, GSSCredential myCred, int lifetime) Factory method for creating a context on the initiator's side.
boolean | GSSName.equals(GSSName another) Compares two GSSName objects to determine if they refer to the same entity.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.ietf.jgss.MessageProp (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.ietf.jgss.MessageProp

Packages that use MessageProp
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.

Uses of MessageProp in org.ietf.jgss

Methods in org.ietf.jgss with parameters of type MessageProp
byte[] | GSSContext.wrap(byte[] inBuf, int offset, int len, MessageProp msgProp) Applies per-message security services over the established security context.
void | GSSContext.wrap(InputStream inStream, OutputStream outStream, MessageProp msgProp) Applies per-message security services over the established security context using streams.
byte[] | GSSContext.unwrap(byte[] inBuf, int offset, int len, MessageProp msgProp) Used to process tokens generated by the wrap method on the other side of the context.
void | GSSContext.unwrap(InputStream inStream, OutputStream outStream, MessageProp msgProp) Uses streams to process tokens generated by the wrap method on the other side of the context.
byte[] | GSSContext.getMIC(byte[] inMsg, int offset, int len, MessageProp msgProp) Returns a token containing a cryptographic Message Integrity Code (MIC) for the supplied message, for transfer to the peer application.
void | GSSContext.getMIC(InputStream inStream, OutputStream outStream, MessageProp msgProp) Uses streams to produce a token containing a cryptographic MIC for the supplied message, for transfer to the peer application.
void | GSSContext.verifyMIC(byte[] inToken, int tokOffset, int tokLen, byte[] inMsg, int msgOffset, int msgLen, MessageProp msgProp) Verifies the cryptographic MIC, contained in the token parameter, over the supplied message.
void | GSSContext.verifyMIC(InputStream tokStream, InputStream msgStream, MessageProp msgProp) Uses streams to verify the cryptographic MIC, contained in the token parameter, over the supplied message.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.ietf.jgss.Oid (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.ietf.jgss.Oid

Packages that use Oid
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.

Uses of Oid in org.ietf.jgss

Fields in org.ietf.jgss declared as Oid
static Oid | GSSName.NT_HOSTBASED_SERVICE Oid indicating a host-based service name form.
static Oid | GSSName.NT_USER_NAME Name type to indicate a named user on a local system.
static Oid | GSSName.NT_MACHINE_UID_NAME Name type to indicate a numeric user identifier corresponding to a user on a local system.
static Oid | GSSName.NT_STRING_UID_NAME Name type to indicate a string of digits representing the numeric user identifier of a user on a local system.
static Oid | GSSName.NT_ANONYMOUS Name type for representing an anonymous entity.
static Oid | GSSName.NT_EXPORT_NAME Name type used to indicate an exported name produced by the export method.

Methods in org.ietf.jgss that return Oid
Oid | GSSContext.getMech() Determines what mechanism is being used for this context.
Oid[] | GSSCredential.getMechs() Returns a list of mechanisms supported by this credential.
abstract Oid[] | GSSManager.getMechs() Returns a list of mechanisms that are available to GSS-API callers through this GSSManager.
abstract Oid[] | GSSManager.getNamesForMech(Oid mech) Returns then name types supported by the indicated mechanism.
abstract Oid[] | GSSManager.getMechsForName(Oid nameType) Returns a list of mechanisms that support the indicated name type.
Oid | GSSName.getStringNameType() Returns the name type of the printable representation of this name that can be obtained from the toString method.

Methods in org.ietf.jgss with parameters of type Oid
GSSName | GSSCredential.getName(Oid mech) Retrieves a Mechanism Name of the entity that the credential asserts.
int | GSSCredential.getRemainingInitLifetime(Oid mech) Returns the lifetime in seconds for the credential to remain capable of initiating security contexts using the specified mechanism.
int | GSSCredential.getRemainingAcceptLifetime(Oid mech) Returns the lifetime in seconds for the credential to remain capable of accepting security contexts using the specified mechanism.
int | GSSCredential.getUsage(Oid mech) Returns the credential usage mode for a specific mechanism.
void | GSSCredential.add(GSSName name, int initLifetime, int acceptLifetime, Oid mech, int usage) Adds a mechanism specific credential-element to an existing credential.
abstract Oid[] | GSSManager.getNamesForMech(Oid mech) Returns then name types supported by the indicated mechanism.
abstract Oid[] | GSSManager.getMechsForName(Oid nameType) Returns a list of mechanisms that support the indicated name type.
abstract GSSName | GSSManager.createName(String nameStr, Oid nameType) Factory method to convert a string name from the specified namespace to a GSSName object.
abstract GSSName | GSSManager.createName(byte[] name, Oid nameType) Factory method to convert a byte array containing a name from the specified namespace to a GSSName object.
abstract GSSName | GSSManager.createName(String nameStr, Oid nameType, Oid mech) Factory method to convert a string name from the specified namespace to a GSSName object and canonicalize it at the same time for a mechanism.
abstract GSSName | GSSManager.createName(byte[] name, Oid nameType, Oid mech) Factory method to convert a byte array containing a name from the specified namespace to a GSSName object and canonicalize it at the same time for a mechanism.
abstract GSSCredential | GSSManager.createCredential(GSSName name, int lifetime, Oid mech, int usage) Factory method for acquiring a single mechanism credential.
abstract GSSCredential | GSSManager.createCredential(GSSName name, int lifetime, Oid[] mechs, int usage) Factory method for acquiring credentials over a set of mechanisms.
abstract GSSContext | GSSManager.createContext(GSSName peer, Oid mech, GSSCredential myCred, int lifetime) Factory method for creating a context on the initiator's side.
abstract void | GSSManager.addProviderAtFront(Provider p, Oid mech) This method is used to indicate to the GSSManager that the application would like a particular provider to be used ahead of all others when support is desired for the given mechanism.
abstract void | GSSManager.addProviderAtEnd(Provider p, Oid mech) This method is used to indicate to the GSSManager that the application would like a particular provider to be used if no other provider can be found that supports the given mechanism.
GSSName | GSSName.canonicalize(Oid mech) Creates a name that is canonicalized for some mechanism.
boolean | Oid.containedIn(Oid[] oids) A utility method to test if this Oid value is contained within the supplied Oid array.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


_IDLTypeStub (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class _IDLTypeStub

java.lang.Object
    extended by org.omg.CORBA.portable.ObjectImpl
        extended by org.omg.CORBA._IDLTypeStub
All Implemented Interfaces:
IDLEntity, IDLType, IDLTypeOperations, IRObject, IRObjectOperations, Object, Serializable
public class _IDLTypeStub
extends ObjectImpl
implements IDLType

The Stub for IDLType. For more information on Stub files, see "Generated Files: Stubs".

org/omg/CORBA/_IDLTypeStub.java Generated by the IDL-to-Java compiler (portable), version "3.0" from ir.idl. 03 June 1999 11:33:44 o'clock GMT+00:00

Constructor Summary
_IDLTypeStub()
Constructs a default _IDLTypeStub object.
_IDLTypeStub(Delegate delegate)
Constructs an _IDLTypeStub object initialized with the given Delegate object.
Method Summary
String[] | _ids() Retrieves a string array containing the repository identifiers supported by this ObjectImpl object.
DefinitionKind | def_kind() Returns the DefinitionKind corresponding to this Interface Repository object.
void | destroy() Destroys this object.
TypeCode | type() The type attribute describes the type defined by an object derived from IDLType.
Methods inherited from class org.omg.CORBA.portable.ObjectImpl
_create_request, _create_request, _duplicate, _get_delegate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _invoke, _is_a, _is_equivalent, _is_local, _non_existent, _orb, _release, _releaseReply, _request, _request, _servant_postinvoke, _servant_preinvoke, _set_delegate, _set_policy_override, equals, hashCode, toString
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Constructor Detail

_IDLTypeStub

public _IDLTypeStub()
Constructs a default _IDLTypeStub object. NOTE: If the default constructor is used, the object is useless until the method _set_delegate has been called.

_IDLTypeStub

public _IDLTypeStub(Delegate delegate)
Constructs an _IDLTypeStub object initialized with the given Delegate object.

Parameters:
delegate - a Delegate object
Method Detail

type

public TypeCode type()
Description copied from interface: IDLTypeOperations
The type attribute describes the type defined by an object derived from IDLType.

Specified by:
type in interface IDLTypeOperations
Returns:
the TypeCode defined by this object.

def_kind

public DefinitionKind def_kind()
Description copied from interface: IRObjectOperations
Returns the DefinitionKind corresponding to this Interface Repository object.

Specified by:
def_kind in interface IRObjectOperations
Returns:
the DefinitionKind corresponding to this Interface Repository object.

destroy

public void destroy()
Description copied from interface: IRObjectOperations
Destroys this object. If the object is a Container, this method is applied to all its contents. If the object contains an IDLType attribute for an anonymous type, that IDLType is destroyed. If the object is currently contained in some other object, it is removed. If the method is invoked on a Repository or on a PrimitiveDef then the BAD_INV_ORDER exception is raised with minor value 2. An attempt to destroy an object that would leave the repository in an incoherent state causes BAD_INV_ORDER exception to be raised with the minor code 1.

Specified by:
destroy in interface IRObjectOperations

_ids

public String[] _ids()
Description copied from class: ObjectImpl
Retrieves a string array containing the repository identifiers supported by this ObjectImpl object. For example, for a stub, this method returns information about all the interfaces supported by the stub.

Specified by:
_ids in class ObjectImpl
Returns:
the array of all repository identifiers supported by this ObjectImpl instance
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


_PolicyStub (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class _PolicyStub

java.lang.Object
    extended by org.omg.CORBA.portable.ObjectImpl
        extended by org.omg.CORBA._PolicyStub
All Implemented Interfaces:
IDLEntity, Object, Policy, PolicyOperations, Serializable
public class _PolicyStub
extends ObjectImpl
implements Policy

The Stub for Policy. For more information on Stub files, see "Generated Files: Stubs".

org/omg/CORBA/_PolicyStub.java Generated by the IDL-to-Java compiler (portable), version "3.0" from ../../../../../src/share/classes/org/omg/PortableServer/corba.idl. Saturday, July 17, 1999 12:26:20 AM PDT

Constructor Summary
_PolicyStub()
Constructors NOTE: If the default constructor is used, the object is useless until _set_delegate (...) is called.
_PolicyStub(Delegate delegate)
Constructs a _PolicyStub object initialized with the given Delegate object.
Method Summary
String[] | _ids() Retrieves a string array containing the repository identifiers supported by this ObjectImpl object.
Policy | copy() Copies the policy object.
void | destroy() Destroys the policy object.
int | policy_type() Returns the constant value that corresponds to the type of the policy object.
Methods inherited from class org.omg.CORBA.portable.ObjectImpl
_create_request, _create_request, _duplicate, _get_delegate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _invoke, _is_a, _is_equivalent, _is_local, _non_existent, _orb, _release, _releaseReply, _request, _request, _servant_postinvoke, _servant_preinvoke, _set_delegate, _set_policy_override, equals, hashCode, toString
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Constructor Detail

_PolicyStub

public _PolicyStub()
Constructors NOTE: If the default constructor is used, the object is useless until _set_delegate (...) is called.

_PolicyStub

public _PolicyStub(Delegate delegate)
Constructs a _PolicyStub object initialized with the given Delegate object.

Parameters:
delegate - a Delegate Object
Method Detail

policy_type

public int policy_type()
Returns the constant value that corresponds to the type of the policy object. The values of the polivy objectys are allocated by the OMG. New values for PolicyType should be obtained from the OMG by sending mail to request@omg.org. In general the constant values that are allocated are defined in conjunction with the definition of the corresponding policy object.

Specified by:
policy_type in interface PolicyOperations
Returns:
the constant value that corresponds to the type of the policy object.

copy

public Policy copy()
Copies the policy object. The copy does not retain any relationships that the policy had with any domain or object.

Specified by:
copy in interface PolicyOperations
Returns:
the copy of the policy object.

destroy

public void destroy()
Destroys the policy object. It is the responsibility of the policy object to determine whether it can be destroyed.

Specified by:
destroy in interface PolicyOperations

_ids

public String[] _ids()
Description copied from class: ObjectImpl
Retrieves a string array containing the repository identifiers supported by this ObjectImpl object. For example, for a stub, this method returns information about all the interfaces supported by the stub.

Specified by:
_ids in class ObjectImpl
Returns:
the array of all repository identifiers supported by this ObjectImpl instance
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Any (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class Any

java.lang.Object
    extended by org.omg.CORBA.Any
All Implemented Interfaces:
IDLEntity, Serializable
public abstract class Any
extends Object
implements IDLEntity

Serves as a container for any data that can be described in IDL or for any IDL primitive type. An Any object is used as a component of a NamedValue object, which provides information about arguments or return values in requests, and which is used to define name/value pairs in Context objects.

An Any object consists of two parts:

  1. a data value
  2. a TypeCode object describing the type of the data value contained in the Any object. For example, a TypeCode object for an array contains a field for the length of the array and a field for the type of elements in the array. (Note that in this case, the second field of the TypeCode object is itself a TypeCode object.)

A large part of the Any class consists of pairs of methods for inserting values into and extracting values from an Any object.

For a given primitive type X, these methods are:

void insert_X(X x)
This method allows the insertion of an instance x of primitive type X into the value field of the Any object. Note that the method insert_X also resets the Any object's type field if necessary.
X extract_X()
This method allows the extraction of an instance of type X from the Any object.

This method throws the exception BAD_OPERATION under two conditions:

  1. the type of the element contained in the Any object is not X
  2. the method extract_X is called before the value field of the Any object has been set

There are distinct method pairs for each primitive IDL data type (insert_long and extract_long, insert_string and extract_string, and so on).

The class Any also has methods for getting and setting the type code, for testing two Any objects for equality, and for reading an Any object from a stream or writing it to a stream.

Since:
JDK1.2

Constructor Summary
Any()
Method Summary
abstract InputStream | create_input_stream() Creates an input stream from which this Any object's value can be unmarshalled.
abstract OutputStream | create_output_stream() Creates an output stream into which this Any object's value can be marshalled.
abstract boolean | equal(Any a) Checks for equality between this Any object and the given Any object.
abstract Any | extract_any() Extracts the Any object in this Any object's value field.
abstract boolean | extract_boolean() Extracts the boolean in this Any object's value field.
abstract char | extract_char() Extracts the char in this Any object's value field.
abstract double | extract_double() Extracts the double in this Any object's value field.
BigDecimal | extract_fixed() Extracts the java.math.BigDecimal object in this Any object's value field.
abstract float | extract_float() Extracts the float in this Any object's value field.
abstract int | extract_long() Extracts the int in this Any object's value field.
abstract long | extract_longlong() Extracts the long in this Any object's value field.
abstract Object | extract_Object() Extracts the org.omg.CORBA.Object in this Any object's value field.
abstract byte | extract_octet() Extracts the byte in this Any object's value field.
Principal | extract_Principal() Deprecated. Deprecated by CORBA 2.2.
abstract short | extract_short() Extracts the short in this Any object's value field.
Streamable | extract_Streamable() Extracts a Streamable from this Any object's value field.
abstract String | extract_string() Extracts the String object in this Any object's value field.
abstract TypeCode | extract_TypeCode() Extracts the TypeCode object in this Any object's value field.
abstract int | extract_ulong() Extracts the int in this Any object's value field.
abstract long | extract_ulonglong() Extracts the long in this Any object's value field.
abstract short | extract_ushort() Extracts the short in this Any object's value field.
abstract Serializable | extract_Value() Extracts the java.io.Serializable object in this Any object's value field.
abstract char | extract_wchar() Extracts the char in this Any object's value field.
abstract String | extract_wstring() Extracts the String object in this Any object's value field.
abstract void | insert_any(Any a) Inserts the given Any object into this Any object's value field.
abstract void | insert_boolean(boolean b) Inserts the given boolean into this Any object's value field.
abstract void | insert_char(char c) Inserts the given char into this Any object's value field.
abstract void | insert_double(double d) Inserts the given double into this Any object's value field.
void | insert_fixed(BigDecimal value) Throws an org.omg.CORBA.NO_IMPLEMENT exception.
void | insert_fixed(BigDecimal value, TypeCode type) Throws an org.omg.CORBA.NO_IMPLEMENT exception.
abstract void | insert_float(float f) Inserts the given float into this Any object's value field.
abstract void | insert_long(int l) Inserts the given int into this Any object's value field.
abstract void | insert_longlong(long l) Inserts the given long into this Any object's value field.
abstract void | insert_Object(Object o) Inserts the given org.omg.CORBA.Object object into this Any object's value field.
abstract void | insert_Object(Object o, TypeCode t) Inserts the given org.omg.CORBA.Object object into this Any object's value field.
abstract void | insert_octet(byte b) Inserts the given byte into this Any object's value field.
void | insert_Principal(Principal p) Deprecated. Deprecated by CORBA 2.2.
abstract void | insert_short(short s) Inserts the given short into this Any object's value field.
void | insert_Streamable(Streamable s) Inserts the given Streamable object into this Any object's value field.
abstract void | insert_string(String s) Inserts the given String object into this Any object's value field.
abstract void | insert_TypeCode(TypeCode t) Inserts the given TypeCode object into this Any object's value field.
abstract void | insert_ulong(int l) Inserts the given int into this Any object's value field.
abstract void | insert_ulonglong(long l) Inserts the given long into this Any object's value field.
abstract void | insert_ushort(short s) Inserts the given short into this Any object's value field.
abstract void | insert_Value(Serializable v) Inserts the given java.io.Serializable object into this Any object's value field.
abstract void | insert_Value(Serializable v, TypeCode t) Inserts the given java.io.Serializable object into this Any object's value field.
abstract void | insert_wchar(char c) Inserts the given char into this Any object's value field.
abstract void | insert_wstring(String s) Inserts the given String object into this Any object's value field.
abstract void | read_value(InputStream is, TypeCode t) Reads off (unmarshals) the value of an Any object from the given input stream using the given typecode.
abstract TypeCode | type() Returns type information for the element contained in this Any object.
abstract void | type(TypeCode t) Sets this Any object's type field to the given TypeCode object and clears its value.
abstract void | write_value(OutputStream os) Writes out the value of this Any object to the given output stream.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

Any

public Any()
Method Detail

equal

public abstract boolean equal(Any a)
Checks for equality between this Any object and the given Any object. Two Any objects are equal if both their values and type codes are equal.

Parameters:
a - the Any object to test for equality
Returns:
true if the Any objects are equal; false otherwise
See Also:
CORBA package comments for unimplemented features

type

public abstract TypeCode type()
Returns type information for the element contained in this Any object.

Returns:
the TypeCode object containing type information about the value contained in this Any object

type

public abstract void type(TypeCode t)
Sets this Any object's type field to the given TypeCode object and clears its value.

Note that using this method to set the type code wipes out the value if there is one. The method is provided primarily so that the type may be set properly for IDL out parameters. Generally, setting the type is done by the insert_X methods, which will set the type to X if it is not already set to X.

Parameters:
t - the TypeCode object giving information for the value in this Any object

read_value

public abstract void read_value(InputStream is,
                                TypeCode t)
                         throws MARSHAL
Reads off (unmarshals) the value of an Any object from the given input stream using the given typecode.

Parameters:
is - the org.omg.CORBA.portable.InputStream object from which to read the value contained in this Any object
t - a TypeCode object containing type information about the value to be read
Throws:
MARSHAL - when the given TypeCode object is not consistent with the value that was contained in the input stream

write_value

public abstract void write_value(OutputStream os)
Writes out the value of this Any object to the given output stream. If both typecode and value need to be written, use create_output_stream() to create an OutputStream, then use write_any on the OutputStream.

If this method is called on an Any object that has not had a value inserted into its value field, it will throw the exception java.lang.NullPointerException.

Parameters:
os - the org.omg.CORBA.portable.OutputStream object into which to marshal the value of this Any object

create_output_stream

public abstract OutputStream create_output_stream()
Creates an output stream into which this Any object's value can be marshalled.

Returns:
the newly-created OutputStream

create_input_stream

public abstract InputStream create_input_stream()
Creates an input stream from which this Any object's value can be unmarshalled.

Returns:
the newly-created InputStream

extract_short

public abstract short extract_short()
                             throws BAD_OPERATION
Extracts the short in this Any object's value field.

Returns:
the short stored in this Any object
Throws:
BAD_OPERATION - if this Any object contains something other than a short or the value field has not yet been set

insert_short

public abstract void insert_short(short s)
Inserts the given short into this Any object's value field.

Parameters:
s - the short to insert into this Any object

extract_long

public abstract int extract_long()
                          throws BAD_OPERATION
Extracts the int in this Any object's value field.

Returns:
the int stored in this Any object
Throws:
BAD_OPERATION - if this Any object contains something other than an int or the value field has not yet been set

insert_long

public abstract void insert_long(int l)
Inserts the given int into this Any object's value field.

Parameters:
l - the int to insert into this Any object

extract_longlong

public abstract long extract_longlong()
                               throws BAD_OPERATION
Extracts the long in this Any object's value field.

Returns:
the long stored in this Any object
Throws:
BAD_OPERATION - if this Any object contains something other than a long or the value field has not yet been set

insert_longlong

public abstract void insert_longlong(long l)
Inserts the given long into this Any object's value field.

Parameters:
l - the long to insert into this Any object

extract_ushort

public abstract short extract_ushort()
                              throws BAD_OPERATION
Extracts the short in this Any object's value field.

Returns:
the short stored in this Any object
Throws:
BAD_OPERATION - if this Any object contains something other than a short or the value field has not yet been set

insert_ushort

public abstract void insert_ushort(short s)
Inserts the given short into this Any object's value field.

Parameters:
s - the short to insert into this Any object

extract_ulong

public abstract int extract_ulong()
                           throws BAD_OPERATION
Extracts the int in this Any object's value field.

Returns:
the int stored in this Any object
Throws:
BAD_OPERATION - if this Any object contains something other than an int or the value field has not yet been set

insert_ulong

public abstract void insert_ulong(int l)
Inserts the given int into this Any object's value field.

Parameters:
l - the int to insert into this Any object

extract_ulonglong

public abstract long extract_ulonglong()
                                throws BAD_OPERATION
Extracts the long in this Any object's value field.

Returns:
the long stored in this Any object
Throws:
BAD_OPERATION - if this Any object contains something other than a long or the value field has not yet been set

insert_ulonglong

public abstract void insert_ulonglong(long l)
Inserts the given long into this Any object's value field.

Parameters:
l - the long to insert into this Any object

extract_float

public abstract float extract_float()
                             throws BAD_OPERATION
Extracts the float in this Any object's value field.

Returns:
the float stored in this Any object
Throws:
BAD_OPERATION - if this Any object contains something other than a float or the value field has not yet been set

insert_float

public abstract void insert_float(float f)
Inserts the given float into this Any object's value field.

Parameters:
f - the float to insert into this Any object

extract_double

public abstract double extract_double()
                               throws BAD_OPERATION
Extracts the double in this Any object's value field.

Returns:
the double stored in this Any object
Throws:
BAD_OPERATION - if this Any object contains something other than a double or the value field has not yet been set

insert_double

public abstract void insert_double(double d)
Inserts the given double into this Any object's value field.

Parameters:
d - the double to insert into this Any object

extract_boolean

public abstract boolean extract_boolean()
                                 throws BAD_OPERATION
Extracts the boolean in this Any object's value field.

Returns:
the boolean stored in this Any object
Throws:
BAD_OPERATION - if this Any object contains something other than a boolean or the value field has not yet been set

insert_boolean

public abstract void insert_boolean(boolean b)
Inserts the given boolean into this Any object's value field.

Parameters:
b - the boolean to insert into this Any object

extract_char

public abstract char extract_char()
                           throws BAD_OPERATION
Extracts the char in this Any object's value field.

Returns:
the char stored in this Any object
Throws:
BAD_OPERATION - if this Any object contains something other than a char or the value field has not yet been set

insert_char

public abstract void insert_char(char c)
                          throws DATA_CONVERSION
Inserts the given char into this Any object's value field.

Parameters:
c - the char to insert into this Any object
Throws:
DATA_CONVERSION - if there is a data conversion error

extract_wchar

public abstract char extract_wchar()
                            throws BAD_OPERATION
Extracts the char in this Any object's value field.

Returns:
the char stored in this Any object
Throws:
BAD_OPERATION - if this Any object contains something other than a char or the value field has not yet been set

insert_wchar

public abstract void insert_wchar(char c)
Inserts the given char into this Any object's value field.

Parameters:
c - the char to insert into this Any object

extract_octet

public abstract byte extract_octet()
                            throws BAD_OPERATION
Extracts the byte in this Any object's value field.

Returns:
the byte stored in this Any object
Throws:
BAD_OPERATION - if this Any object contains something other than a byte or the value field has not yet been set

insert_octet

public abstract void insert_octet(byte b)
Inserts the given byte into this Any object's value field.

Parameters:
b - the byte to insert into this Any object

extract_any

public abstract Any extract_any()
                         throws BAD_OPERATION
Extracts the Any object in this Any object's value field.

Returns:
the Any object stored in this Any object
Throws:
BAD_OPERATION - if this Any object contains something other than an Any object or the value field has not yet been set

insert_any

public abstract void insert_any(Any a)
Inserts the given Any object into this Any object's value field.

Parameters:
a - the Any object to insert into this Any object

extract_Object

public abstract Object extract_Object()
                               throws BAD_OPERATION
Extracts the org.omg.CORBA.Object in this Any object's value field.

Returns:
the org.omg.CORBA.Object stored in this Any object
Throws:
BAD_OPERATION - if this Any object contains something other than an org.omg.CORBA.Object or the value field has not yet been set

insert_Object

public abstract void insert_Object(Object o)
Inserts the given org.omg.CORBA.Object object into this Any object's value field.

Parameters:
o - the org.omg.CORBA.Object object to insert into this Any object

extract_Value

public abstract Serializable extract_Value()
                                    throws BAD_OPERATION
Extracts the java.io.Serializable object in this Any object's value field.

Returns:
the java.io.Serializable object stored in this Any object
Throws:
BAD_OPERATION - if this Any object contains something other than a java.io.Serializable object or the value field has not yet been set

insert_Value

public abstract void insert_Value(Serializable v)
Inserts the given java.io.Serializable object into this Any object's value field.

Parameters:
v - the java.io.Serializable object to insert into this Any object

insert_Value

public abstract void insert_Value(Serializable v,
                                  TypeCode t)
                           throws MARSHAL
Inserts the given java.io.Serializable object into this Any object's value field.

Parameters:
v - the java.io.Serializable object to insert into this Any object
t - the TypeCode object that is to be inserted into this Any object's type field and that describes the java.io.Serializable object being inserted
Throws:
MARSHAL - if the ORB has a problem marshalling or unmarshalling parameters

insert_Object

public abstract void insert_Object(Object o,
                                   TypeCode t)
                            throws BAD_PARAM
Inserts the given org.omg.CORBA.Object object into this Any object's value field.

Parameters:
o - the org.omg.CORBA.Object instance to insert into this Any object
t - the TypeCode object that is to be inserted into this Any object and that describes the Object being inserted
Throws:
BAD_OPERATION - if this method is invalid for this Any object
BAD_PARAM

extract_string

public abstract String extract_string()
                               throws BAD_OPERATION
Extracts the String object in this Any object's value field.

Returns:
the String object stored in this Any object
Throws:
BAD_OPERATION - if this Any object contains something other than a String object or the value field has not yet been set

insert_string

public abstract void insert_string(String s)
                            throws DATA_CONVERSION,
                                   MARSHAL
Inserts the given String object into this Any object's value field.

Parameters:
s - the String object to insert into this Any object
Throws:
DATA_CONVERSION - if there is a data conversion error
MARSHAL - if the ORB has a problem marshalling or unmarshalling parameters

extract_wstring

public abstract String extract_wstring()
                                throws BAD_OPERATION
Extracts the String object in this Any object's value field.

Returns:
the String object stored in this Any object
Throws:
BAD_OPERATION - if this Any object contains something other than a String object or the value field has not yet been set

insert_wstring

public abstract void insert_wstring(String s)
                             throws MARSHAL
Inserts the given String object into this Any object's value field.

Parameters:
s - the String object to insert into this Any object
Throws:
MARSHAL - if the ORB has a problem marshalling or unmarshalling parameters

extract_TypeCode

public abstract TypeCode extract_TypeCode()
                                   throws BAD_OPERATION
Extracts the TypeCode object in this Any object's value field.

Returns:
the TypeCode object stored in this Any object
Throws:
BAD_OPERATION - if this Any object contains something other than a TypeCode object or the value field has not yet been set

insert_TypeCode

public abstract void insert_TypeCode(TypeCode t)
Inserts the given TypeCode object into this Any object's value field.

Parameters:
t - the TypeCode object to insert into this Any object

extract_Principal

public Principal extract_Principal()
                            throws BAD_OPERATION
Deprecated. Deprecated by CORBA 2.2.

Extracts the Principal object in this Any object's value field. Note that the class Principal has been deprecated.

Returns:
the Principal object stored in this Any object
Throws:
BAD_OPERATION - if this Any object contains something other than a Principal object or the value field has not yet been set
See Also:
CORBA package comments for unimplemented features

insert_Principal

public void insert_Principal(Principal p)
Deprecated. Deprecated by CORBA 2.2.

Inserts the given Principal object into this Any object's value field. Note that the class Principal has been deprecated.

Parameters:
p - the Principal object to insert into this Any object
See Also:
CORBA package comments for unimplemented features

extract_Streamable

public Streamable extract_Streamable()
                              throws BAD_INV_ORDER
Extracts a Streamable from this Any object's value field. This method allows the extraction of non-primitive IDL types.

Returns:
the Streamable stored in the Any object.
Throws:
BAD_INV_ORDER - if the caller has invoked operations in the wrong order
See Also:
CORBA package comments for unimplemented features

insert_Streamable

public void insert_Streamable(Streamable s)
Inserts the given Streamable object into this Any object's value field. This method allows the insertion of non-primitive IDL types.

Parameters:
s - the Streamable object to insert into this Any object; may be a non-primitive IDL type
See Also:
CORBA package comments for unimplemented features

extract_fixed

public BigDecimal extract_fixed()
Extracts the java.math.BigDecimal object in this Any object's value field.

Returns:
the java.math.BigDecimal object stored in this Any object
Throws:
BAD_OPERATION - if this Any object contains something other than a java.math.BigDecimal object or the value field has not yet been set
See Also:
CORBA package comments for unimplemented features

insert_fixed

public void insert_fixed(BigDecimal value)
Throws an org.omg.CORBA.NO_IMPLEMENT exception.

Inserts the given java.math.BigDecimal object into this Any object's value field.

Parameters:
value - the java.math.BigDecimal object to insert into this Any object
See Also:
CORBA package comments for unimplemented features

insert_fixed

public void insert_fixed(BigDecimal value,
                         TypeCode type)
                  throws BAD_INV_ORDER
Throws an org.omg.CORBA.NO_IMPLEMENT exception.

Inserts the given java.math.BigDecimal object into this Any object's value field.

Parameters:
value - the java.math.BigDecimal object to insert into this Any object
type - the TypeCode object that is to be inserted into this Any object's type field and that describes the java.math.BigDecimal object being inserted
Throws:
BAD_INV_ORDER - if this method is invoked improperly
See Also:
CORBA package comments for unimplemented features
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


AnyHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class AnyHolder

java.lang.Object
    extended by org.omg.CORBA.AnyHolder
All Implemented Interfaces:
Streamable
public final class AnyHolder
extends Object
implements Streamable

The Holder for Any. For more information on Holder files, see "Generated Files: Holder Files".

A Holder class for Any objects that is used to store "out" and "inout" parameters in IDL methods. If an IDL method signature has an IDL any as an "out" or "inout" parameter, the programmer must pass an instance of AnyHolder as the corresponding parameter in the method invocation; for "inout" parameters, the programmer must also fill the "in" value to be sent to the server. Before the method invocation returns, the ORB will fill in the value corresponding to the "out" value returned from the server.

If myAnyHolder is an instance of AnyHolder, the value stored in its value field can be accessed with myAnyHolder.value.

Since:
JDK1.2

Field Summary
 Any value
The Any value held by this AnyHolder object.
Constructor Summary
AnyHolder()
Constructs a new AnyHolder object with its value field initialized to null.
AnyHolder(Any initial)
Constructs a new AnyHolder object for the given Any object.
Method Summary
void | _read(InputStream input) Reads from input and initalizes the value in the Holder with the unmarshalled data.
TypeCode | _type() Returns the TypeCode object corresponding to the value held in this AnyHolder object.
void | _write(OutputStream output) Marshals to output the value in this AnyHolder object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public Any value
The Any value held by this AnyHolder object.

Constructor Detail

AnyHolder

public AnyHolder()
Constructs a new AnyHolder object with its value field initialized to null.

AnyHolder

public AnyHolder(Any initial)
Constructs a new AnyHolder object for the given Any object.

Parameters:
initial - the Any object with which to initialize the value field of the new AnyHolder object
Method Detail

_read

public void _read(InputStream input)
Reads from input and initalizes the value in the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
input - the InputStream containing CDR formatted data from the wire.

_write

public void _write(OutputStream output)
Marshals to output the value in this AnyHolder object.

Specified by:
_write in interface Streamable
Parameters:
output - the OutputStream which will contain the CDR formatted data.

_type

public TypeCode _type()
Returns the TypeCode object corresponding to the value held in this AnyHolder object.

Specified by:
_type in interface Streamable
Returns:
the TypeCode of the value held in this AnyHolder object
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


AnySeqHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class AnySeqHelper

java.lang.Object
    extended by org.omg.CORBA.AnySeqHelper
public abstract class AnySeqHelper
extends Object

The Helper for AnySeq. For more information on Helper files, see "Generated Files: Helper Files".

org/omg/CORBA/AnySeqHelper.java Generated by the IDL-to-Java compiler (portable), version "3.0" from streams.idl 13 May 1999 22:41:36 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

Constructor Summary
AnySeqHelper()
Method Summary
static Any[] | extract(Any a)
static String | id()
static void | insert(Any a, Any[] that)
static Any[] | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, Any[] value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

AnySeqHelper

public AnySeqHelper()
Method Detail

insert

public static void insert(Any a,
                          Any[] that)

extract

public static Any[] extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static Any[] read(InputStream istream)

write

public static void write(OutputStream ostream,
                         Any[] value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


AnySeqHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class AnySeqHolder

java.lang.Object
    extended by org.omg.CORBA.AnySeqHolder
All Implemented Interfaces:
Streamable
public final class AnySeqHolder
extends Object
implements Streamable

The Holder for AnySeq. For more information on Holder files, see "Generated Files: Holder Files".

org/omg/CORBA/AnySeqHolder.java Generated by the IDL-to-Java compiler (portable), version "3.0" from streams.idl 13 May 1999 22:41:36 o'clock GMT+00:00

Field Summary
 Any[] value
Constructor Summary
AnySeqHolder()
AnySeqHolder(Any[] initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public Any[] value
Constructor Detail

AnySeqHolder

public AnySeqHolder()

AnySeqHolder

public AnySeqHolder(Any[] initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ARG_IN (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Interface ARG_IN

public interface ARG_IN

Signifies an "input" argument to an invocation, meaning that the argument is being passed from the client to the server. ARG_IN.value is one of the possible values used to indicate the direction in which a parameter is being passed during an invocation performed using the Dynamic Invocation Interface (DII).

The code fragment below shows a typical usage:

    ORB orb = ORB.init(args, null);
    org.omg.CORBA.NamedValue nv = orb.create_named_value(
         "IDLArgumentIdentifier", myAny, org.omg.CORBA.ARG_IN.value);

Since:
JDK1.2
See Also:
NamedValue

Field Summary
static int value
The value indicating an input argument.

Field Detail

value

public static final int value
The value indicating an input argument.

See Also:
Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


ARG_INOUT (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Interface ARG_INOUT

public interface ARG_INOUT

Signifies an argument used for both input and output in an invocation, meaning that the argument is being passed from the client to the server and then back from the server to the client. ARG_INOUT.value is one of the possible values used to indicate the direction in which a parameter is being passed during a dynamic invocation using the Dynamic Invocation Interface (DII).

The code fragment below shows a typical usage:

  ORB orb = ORB.init(args, null);
  org.omg.CORBA.NamedValue nv = orb.create_named_value(
        "argumentIdentifier", myAny, org.omg.CORBA.ARG_INOUT.value);

Since:
JDK1.2
See Also:
NamedValue

Field Summary
static int value
The constant value indicating an argument used for both input and output.

Field Detail

value

public static final int value
The constant value indicating an argument used for both input and output.

See Also:
Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ARG_OUT (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Interface ARG_OUT

public interface ARG_OUT

A constant that signifies an "output" argument to an invocation, meaning that the argument is being passed from the server to the client. ARG_OUT.value is one of the possible values used to indicate the direction in which a parameter is being passed during a dynamic invocation using the Dynamic Invocation Interface (DII).

The code fragment below shows a typical usage:

  ORB orb = ORB.init(args, null);
  org.omg.CORBA.NamedValue nv = orb.create_named_value(
        "argumentIdentifier", myAny, org.omg.CORBA.ARG_OUT.value);

Since:
JDK1.2
See Also:
NamedValue

Field Summary
static int value
The constant value indicating an output argument.

Field Detail

value

public static final int value
The constant value indicating an output argument.

See Also:
Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


BAD_CONTEXT (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class BAD_CONTEXT

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by org.omg.CORBA.SystemException
                    extended by org.omg.CORBA.BAD_CONTEXT
All Implemented Interfaces:
Serializable
public final class BAD_CONTEXT
extends SystemException

Exception thrown when an operation is invoked by a client but the passed context does not contain the context values required by the operation.

It contains a minor code, which gives more detailed information about what caused the exception, and a completion status. It may also contain a string describing the exception.

Since:
JDK1.2
See Also:
documentation on Java IDL exceptions

Field Summary
Fields inherited from class org.omg.CORBA.SystemException
completed, minor
Constructor Summary
BAD_CONTEXT()
Constructs a BAD_CONTEXT exception with a default minor code of 0 and a completion state of COMPLETED_NO.
BAD_CONTEXT(int minor, CompletionStatus completed)
Constructs a BAD_CONTEXT exception with the specified minor code and completion status.
BAD_CONTEXT(String s)
Constructs a BAD_CONTEXT exception with the specified detail message, a minor code of 0 and a completion state of COMPLETED_NO.
BAD_CONTEXT(String s, int minor, CompletionStatus completed)
Constructs a BAD_CONTEXT exception with the specified detail message, minor code, and completion status.
Methods inherited from class org.omg.CORBA.SystemException
toString
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

BAD_CONTEXT

public BAD_CONTEXT()
Constructs a BAD_CONTEXT exception with a default minor code of 0 and a completion state of COMPLETED_NO.

BAD_CONTEXT

public BAD_CONTEXT(String s)
Constructs a BAD_CONTEXT exception with the specified detail message, a minor code of 0 and a completion state of COMPLETED_NO.

Parameters:
s - a String object containing a detail message

BAD_CONTEXT

public BAD_CONTEXT(int minor,
                   CompletionStatus completed)
Constructs a BAD_CONTEXT exception with the specified minor code and completion status.

Parameters:
minor - the minor code
completed - an instance of CompletionStatus indicating the completion status

BAD_CONTEXT

public BAD_CONTEXT(String s,
                   int minor,
                   CompletionStatus completed)
Constructs a BAD_CONTEXT exception with the specified detail message, minor code, and completion status. A detail message is a String that describes this particular exception.

Parameters:
s - the String containing a detail message
minor - the minor code
completed - an instance of CompletionStatus indicating the completion status
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


BAD_INV_ORDER (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class BAD_INV_ORDER

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by org.omg.CORBA.SystemException
                    extended by org.omg.CORBA.BAD_INV_ORDER
All Implemented Interfaces:
Serializable
public final class BAD_INV_ORDER
extends SystemException

This exception indicates that the caller has invoked operations in the wrong order. For example, it can be raised by an ORB if an application makes an ORB-related call without having correctly initialized the ORB first.

It contains a minor code, which gives more detailed information about what caused the exception, and a completion status. It may also contain a string describing the exception.

Since:
JDK1.2
See Also:
documentation on Java IDL exceptions

Field Summary
Fields inherited from class org.omg.CORBA.SystemException
completed, minor
Constructor Summary
BAD_INV_ORDER()
Constructs a BAD_INV_ORDER exception with a default minor code of 0 and a completion state of COMPLETED_NO.
BAD_INV_ORDER(int minor, CompletionStatus completed)
Constructs a BAD_INV_ORDER exceptionBAD_INV_ORDER with the specified minor code and completion status.
BAD_INV_ORDER(String s)
Constructs a BAD_INV_ORDER exception with the specified detail message, a minor code of 0, and a completion state of COMPLETED_NO.
BAD_INV_ORDER(String s, int minor, CompletionStatus completed)
Constructs a BAD_INV_ORDER exception with the specified detail message, minor code, and completion status.
Methods inherited from class org.omg.CORBA.SystemException
toString
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

BAD_INV_ORDER

public BAD_INV_ORDER()
Constructs a BAD_INV_ORDER exception with a default minor code of 0 and a completion state of COMPLETED_NO.

BAD_INV_ORDER

public BAD_INV_ORDER(String s)
Constructs a BAD_INV_ORDER exception with the specified detail message, a minor code of 0, and a completion state of COMPLETED_NO.

Parameters:
s - the String containing a detail message

BAD_INV_ORDER

public BAD_INV_ORDER(int minor,
                     CompletionStatus completed)
Constructs a BAD_INV_ORDER exceptionBAD_INV_ORDER with the specified minor code and completion status.

Parameters:
minor - the minor code
completed - an instance of CompletionStatus indicating the completion status

BAD_INV_ORDER

public BAD_INV_ORDER(String s,
                     int minor,
                     CompletionStatus completed)
Constructs a BAD_INV_ORDER exception with the specified detail message, minor code, and completion status. A detail message is a String that describes this particular exception.

Parameters:
s - the String containing a detail message
minor - the minor code
completed - the completion status
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


BAD_OPERATION (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class BAD_OPERATION

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by org.omg.CORBA.SystemException
                    extended by org.omg.CORBA.BAD_OPERATION
All Implemented Interfaces:
Serializable
public final class BAD_OPERATION
extends SystemException

Exception thrown when an object reference denotes an existing object, but that the object does not support the operation that was invoked.

It contains a minor code, which gives more detailed information about what caused the exception, and a completion status. It may also contain a string describing the exception.

Since:
JDK1.2
See Also:
documentation on Java IDL exceptions

Field Summary
Fields inherited from class org.omg.CORBA.SystemException
completed, minor
Constructor Summary
BAD_OPERATION()
Constructs a BAD_OPERATION exception with a default minor code of 0 and a completion state of COMPLETED_NO.
BAD_OPERATION(int minor, CompletionStatus completed)
Constructs a BAD_OPERATION exception with the specified minor code and completion status.
BAD_OPERATION(String s)
Constructs a BAD_OPERATION exception with the specified detail message, a minor code of 0, and a completion state of COMPLETED_NO.
BAD_OPERATION(String s, int minor, CompletionStatus completed)
Constructs a BAD_OPERATION exception with the specified detail message, minor code, and completion status.
Methods inherited from class org.omg.CORBA.SystemException
toString
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

BAD_OPERATION

public BAD_OPERATION()
Constructs a BAD_OPERATION exception with a default minor code of 0 and a completion state of COMPLETED_NO.

BAD_OPERATION

public BAD_OPERATION(String s)
Constructs a BAD_OPERATION exception with the specified detail message, a minor code of 0, and a completion state of COMPLETED_NO.

Parameters:
s - the String containing a detail message

BAD_OPERATION

public BAD_OPERATION(int minor,
                     CompletionStatus completed)
Constructs a BAD_OPERATION exception with the specified minor code and completion status.

Parameters:
minor - the minor code
completed - an instance of CompletionStatus indicating the completion status

BAD_OPERATION

public BAD_OPERATION(String s,
                     int minor,
                     CompletionStatus completed)
Constructs a BAD_OPERATION exception with the specified detail message, minor code, and completion status. A detail message is a String that describes this particular exception.

Parameters:
s - the String containing a detail message
minor - the minor code
completed - an instance of CompletionStatus indicating the completion status
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


BAD_PARAM (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class BAD_PARAM

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by org.omg.CORBA.SystemException
                    extended by org.omg.CORBA.BAD_PARAM
All Implemented Interfaces:
Serializable
public final class BAD_PARAM
extends SystemException

Exception thrown when a parameter passed to a call is out of range or otherwise considered illegal. An ORB may raise this exception if null values or null pointers are passed to an operation (for language mappings where the concept of a null pointers or null values applies). BAD_PARAM can also be raised as a result of a client generating requests with incorrect parameters using the DII.

It contains a minor code, which gives more detailed information about what caused the exception, and a completion status. It may also contain a string describing the exception.

Since:
JDK1.2
See Also:
documentation on Java IDL exceptions, meaning of minor codes

Field Summary
Fields inherited from class org.omg.CORBA.SystemException
completed, minor
Constructor Summary
BAD_PARAM()
Constructs a BAD_PARAM exception with a default minor code of 0 and a completion state of COMPLETED_NO.
BAD_PARAM(int minor, CompletionStatus completed)
Constructs a BAD_PARAM exception with the specified minor code and completion status.
BAD_PARAM(String s)
Constructs a BAD_PARAM exception with the specified detail message, a minor code of 0, and a completion state of COMPLETED_NO.
BAD_PARAM(String s, int minor, CompletionStatus completed)
Constructs a BAD_PARAM exception with the specified detail message, minor code, and completion status.
Methods inherited from class org.omg.CORBA.SystemException
toString
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

BAD_PARAM

public BAD_PARAM()
Constructs a BAD_PARAM exception with a default minor code of 0 and a completion state of COMPLETED_NO.

BAD_PARAM

public BAD_PARAM(String s)
Constructs a BAD_PARAM exception with the specified detail message, a minor code of 0, and a completion state of COMPLETED_NO.

Parameters:
s - the String containing a detail message describing this exception

BAD_PARAM

public BAD_PARAM(int minor,
                 CompletionStatus completed)
Constructs a BAD_PARAM exception with the specified minor code and completion status.

Parameters:
minor - the minor code
completed - the completion status

BAD_PARAM

public BAD_PARAM(String s,
                 int minor,
                 CompletionStatus completed)
Constructs a BAD_PARAM exception with the specified detail message, minor code, and completion status. A detail message is a String that describes this particular exception.

Parameters:
s - the String containing a detail message
minor - the minor code
completed - the completion status
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


BAD_POLICY (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Interface BAD_POLICY

public interface BAD_POLICY

A PolicyErrorCode which would be filled in the PolicyError exception.

Field Summary
static short value
The Error code in PolicyError exception.

Field Detail

value

public static final short value
The Error code in PolicyError exception.

See Also:
Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


BAD_POLICY_TYPE (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Interface BAD_POLICY_TYPE

public interface BAD_POLICY_TYPE

A PolicyErrorCode which would be filled in the PolicyError exception.

Field Summary
static short value
The Error code in PolicyError exception.

Field Detail

value

public static final short value
The Error code in PolicyError exception.

See Also:
Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


BAD_POLICY_VALUE (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Interface BAD_POLICY_VALUE

public interface BAD_POLICY_VALUE

Contains the value used to indicate a policy value that is incorrect for a valid policy type in a call to the create_policy method defined in the ORB class.

Field Summary
static short value
The value used to represent a bad policy value error in a PolicyError exception.

Field Detail

value

public static final short value
The value used to represent a bad policy value error in a PolicyError exception.

See Also:
PolicyError, Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


BAD_TYPECODE (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class BAD_TYPECODE

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by org.omg.CORBA.SystemException
                    extended by org.omg.CORBA.BAD_TYPECODE
All Implemented Interfaces:
Serializable
public final class BAD_TYPECODE
extends SystemException

Exception thrown when the ORB has encountered a malformed type code (for example, a type code with an invalid TCKind value).

It contains a minor code, which gives more detailed information about what caused the exception, and a completion status. It may also contain a string describing the exception.

Since:
JDK1.2
See Also:
documentation on Java IDL exceptions

Field Summary
Fields inherited from class org.omg.CORBA.SystemException
completed, minor
Constructor Summary
BAD_TYPECODE()
Constructs a BAD_TYPECODE exception with a default minor code of 0 and a completion state of COMPLETED_NO.
BAD_TYPECODE(int minor, CompletionStatus completed)
Constructs a BAD_TYPECODE exception with the specified minor code and completion status.
BAD_TYPECODE(String s)
Constructs a BAD_TYPECODE exception with the specified detail, a minor code of 0, and a completion state of COMPLETED_NO.
BAD_TYPECODE(String s, int minor, CompletionStatus completed)
Constructs a BAD_TYPECODE exception with the specified detail message, minor code, and completion status.
Methods inherited from class org.omg.CORBA.SystemException
toString
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

BAD_TYPECODE

public BAD_TYPECODE()
Constructs a BAD_TYPECODE exception with a default minor code of 0 and a completion state of COMPLETED_NO.

BAD_TYPECODE

public BAD_TYPECODE(String s)
Constructs a BAD_TYPECODE exception with the specified detail, a minor code of 0, and a completion state of COMPLETED_NO.

Parameters:
s - the String containing a detail message

BAD_TYPECODE

public BAD_TYPECODE(int minor,
                    CompletionStatus completed)
Constructs a BAD_TYPECODE exception with the specified minor code and completion status.

Parameters:
minor - the minor code
completed - an instance of CompletionStatus indicating the completion status

BAD_TYPECODE

public BAD_TYPECODE(String s,
                    int minor,
                    CompletionStatus completed)
Constructs a BAD_TYPECODE exception with the specified detail message, minor code, and completion status. A detail message is a String that describes this particular exception.

Parameters:
s - the String containing a detail message
minor - the minor code
completed - an instance of CompletionStatus indicating the completion status
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


BooleanHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class BooleanHolder

java.lang.Object
    extended by org.omg.CORBA.BooleanHolder
All Implemented Interfaces:
Streamable
public final class BooleanHolder
extends Object
implements Streamable

The Holder for Boolean. For more information on Holder files, see "Generated Files: Holder Files".

A Holder class for a boolean that is used to store "out" and "inout" parameters in IDL methods. If an IDL method signature has an IDL boolean as an "out" or "inout" parameter, the programmer must pass an instance of BooleanHolder as the corresponding parameter in the method invocation; for "inout" parameters, the programmer must also fill the "in" value to be sent to the server. Before the method invocation returns, the ORB will fill in the value corresponding to the "out" value returned from the server.

If myBooleanHolder is an instance of BooleanHolder, the value stored in its value field can be accessed with myBooleanHolder.value.

Since:
JDK1.2

Field Summary
 boolean value
The boolean value held by this BooleanHolder object.
Constructor Summary
BooleanHolder()
Constructs a new BooleanHolder object with its value field initialized to false.
BooleanHolder(boolean initial)
Constructs a new BooleanHolder object with its value field initialized with the given boolean.
Method Summary
void | _read(InputStream input) Reads unmarshalled data from input and assigns it to this BooleanHolder object's value field.
TypeCode | _type() Retrieves the TypeCode object that corresponds to the value held in this BooleanHolder object.
void | _write(OutputStream output) Marshals the value in this BooleanHolder object's value field to the output stream output.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public boolean value
The boolean value held by this BooleanHolder object.

Constructor Detail

BooleanHolder

public BooleanHolder()
Constructs a new BooleanHolder object with its value field initialized to false.

BooleanHolder

public BooleanHolder(boolean initial)
Constructs a new BooleanHolder object with its value field initialized with the given boolean.

Parameters:
initial - the boolean with which to initialize the value field of the newly-created BooleanHolder object
Method Detail

_read

public void _read(InputStream input)
Reads unmarshalled data from input and assigns it to this BooleanHolder object's value field.

Specified by:
_read in interface Streamable
Parameters:
input - the InputStream object containing CDR formatted data from the wire

_write

public void _write(OutputStream output)
Marshals the value in this BooleanHolder object's value field to the output stream output.

Specified by:
_write in interface Streamable
Parameters:
output - the OutputStream which will contain the CDR formatted data

_type

public TypeCode _type()
Retrieves the TypeCode object that corresponds to the value held in this BooleanHolder object.

Specified by:
_type in interface Streamable
Returns:
the TypeCode for the value held in this BooleanHolder object
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


BooleanSeqHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class BooleanSeqHelper

java.lang.Object
    extended by org.omg.CORBA.BooleanSeqHelper
public abstract class BooleanSeqHelper
extends Object

The Helper for BooleanSeq. For more information on Helper files, see "Generated Files: Helper Files".

org/omg/CORBA/BooleanSeqHelper.java Generated by the IDL-to-Java compiler (portable), version "3.0" from streams.idl 13 May 1999 22:41:36 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

Constructor Summary
BooleanSeqHelper()
Method Summary
static boolean[] | extract(Any a)
static String | id()
static void | insert(Any a, boolean[] that)
static boolean[] | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, boolean[] value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

BooleanSeqHelper

public BooleanSeqHelper()
Method Detail

insert

public static void insert(Any a,
                          boolean[] that)

extract

public static boolean[] extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static boolean[] read(InputStream istream)

write

public static void write(OutputStream ostream,
                         boolean[] value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


BooleanSeqHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class BooleanSeqHolder

java.lang.Object
    extended by org.omg.CORBA.BooleanSeqHolder
All Implemented Interfaces:
Streamable
public final class BooleanSeqHolder
extends Object
implements Streamable

The Holder for BooleanSeq. For more information on Holder files, see "Generated Files: Holder Files".

org/omg/CORBA/BooleanSeqHolder.java Generated by the IDL-to-Java compiler (portable), version "3.0" from streams.idl 13 May 1999 22:41:36 o'clock GMT+00:00

Field Summary
 boolean[] value
Constructor Summary
BooleanSeqHolder()
BooleanSeqHolder(boolean[] initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public boolean[] value
Constructor Detail

BooleanSeqHolder

public BooleanSeqHolder()

BooleanSeqHolder

public BooleanSeqHolder(boolean[] initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Bounds (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class Bounds

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.CORBA.Bounds
All Implemented Interfaces:
IDLEntity, Serializable
public final class Bounds
extends UserException

A user exception thrown when a parameter is not within the legal bounds for the object that a method is trying to access.

See Also:
documentation on Java IDL exceptions

Constructor Summary
Bounds()
Constructs an Bounds with no specified detail message.
Bounds(String reason)
Constructs an Bounds with the specified detail message.
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

Bounds

public Bounds()
Constructs an Bounds with no specified detail message.

Bounds

public Bounds(String reason)
Constructs an Bounds with the specified detail message.

Parameters:
reason - the detail message.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ByteHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class ByteHolder

java.lang.Object
    extended by org.omg.CORBA.ByteHolder
All Implemented Interfaces:
Streamable
public final class ByteHolder
extends Object
implements Streamable

The Holder for Byte. For more information on Holder files, see "Generated Files: Holder Files".

A Holder class for a byte that is used to store "out" and "inout" parameters in IDL methods. If an IDL method signature has an IDL octet as an "out" or "inout" parameter, the programmer must pass an instance of ByteHolder as the corresponding parameter in the method invocation; for "inout" parameters, the programmer must also fill the "in" value to be sent to the server. Before the method invocation returns, the ORB will fill in the value corresponding to the "out" value returned from the server.

If myByteHolder is an instance of ByteHolder, the value stored in its value field can be accessed with myByteHolder.value.

Since:
JDK1.2

Field Summary
 byte value
The byte value held by this ByteHolder object.
Constructor Summary
ByteHolder()
Constructs a new ByteHolder object with its value field initialized to 0.
ByteHolder(byte initial)
Constructs a new ByteHolder object for the given byte.
Method Summary
void | _read(InputStream input) Reads from input and initalizes the value in this ByteHolder object with the unmarshalled data.
TypeCode | _type() Returns the TypeCode corresponding to the value held in this ByteHolder object.
void | _write(OutputStream output) Marshals to output the value in this ByteHolder object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public byte value
The byte value held by this ByteHolder object.

Constructor Detail

ByteHolder

public ByteHolder()
Constructs a new ByteHolder object with its value field initialized to 0.

ByteHolder

public ByteHolder(byte initial)
Constructs a new ByteHolder object for the given byte.

Parameters:
initial - the byte with which to initialize the value field of the new ByteHolder object
Method Detail

_read

public void _read(InputStream input)
Reads from input and initalizes the value in this ByteHolder object with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
input - the InputStream containing CDR formatted data from the wire.

_write

public void _write(OutputStream output)
Marshals to output the value in this ByteHolder object.

Specified by:
_write in interface Streamable
Parameters:
output - the OutputStream which will contain the CDR formatted data.

_type

public TypeCode _type()
Returns the TypeCode corresponding to the value held in this ByteHolder object.

Specified by:
_type in interface Streamable
Returns:
the TypeCode of the value held in this ByteHolder object
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


CharHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class CharHolder

java.lang.Object
    extended by org.omg.CORBA.CharHolder
All Implemented Interfaces:
Streamable
public final class CharHolder
extends Object
implements Streamable

The Holder for Char. For more information on Holder files, see "Generated Files: Holder Files".

A Holder class for a char that is used to store "out" and "inout" parameters in IDL methods. If an IDL method signature has an IDL char as an "out" or "inout" parameter, the programmer must pass an instance of CharHolder as the corresponding parameter in the method invocation; for "inout" parameters, the programmer must also fill the "in" value to be sent to the server. Before the method invocation returns, the ORB will fill in the value corresponding to the "out" value returned from the server.

If myCharHolder is an instance of CharHolder, the value stored in its value field can be accessed with myCharHolder.value.

Since:
JDK1.2

Field Summary
 char value
The char value held by this CharHolder object.
Constructor Summary
CharHolder()
Constructs a new CharHolder object with its value field initialized to 0.
CharHolder(char initial)
Constructs a new CharHolder object for the given char.
Method Summary
void | _read(InputStream input) Reads from input and initalizes the value in this CharHolder object with the unmarshalled data.
TypeCode | _type() Returns the TypeCode object corresponding to the value held in this CharHolder object.
void | _write(OutputStream output) Marshals to output the value in this CharHolder object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public char value
The char value held by this CharHolder object.

Constructor Detail

CharHolder

public CharHolder()
Constructs a new CharHolder object with its value field initialized to 0.

CharHolder

public CharHolder(char initial)
Constructs a new CharHolder object for the given char.

Parameters:
initial - the char with which to initialize the value field of the new CharHolder object
Method Detail

_read

public void _read(InputStream input)
Reads from input and initalizes the value in this CharHolder object with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
input - the InputStream containing CDR formatted data from the wire

_write

public void _write(OutputStream output)
Marshals to output the value in this CharHolder object.

Specified by:
_write in interface Streamable
Parameters:
output - the OutputStream which will contain the CDR formatted data

_type

public TypeCode _type()
Returns the TypeCode object corresponding to the value held in this CharHolder object.

Specified by:
_type in interface Streamable
Returns:
the TypeCode of the value held in this CharHolder object
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


CharSeqHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class CharSeqHelper

java.lang.Object
    extended by org.omg.CORBA.CharSeqHelper
public abstract class CharSeqHelper
extends Object

The Helper for CharSeq. For more information on Helper files, see "Generated Files: Helper Files".

org/omg/CORBA/CharSeqHelper.java Generated by the IDL-to-Java compiler (portable), version "3.0" from streams.idl 13 May 1999 22:41:36 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

Constructor Summary
CharSeqHelper()
Method Summary
static char[] | extract(Any a)
static String | id()
static void | insert(Any a, char[] that)
static char[] | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, char[] value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

CharSeqHelper

public CharSeqHelper()
Method Detail

insert

public static void insert(Any a,
                          char[] that)

extract

public static char[] extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static char[] read(InputStream istream)

write

public static void write(OutputStream ostream,
                         char[] value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


CharSeqHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class CharSeqHolder

java.lang.Object
    extended by org.omg.CORBA.CharSeqHolder
All Implemented Interfaces:
Streamable
public final class CharSeqHolder
extends Object
implements Streamable

The Holder for CharSeq. For more information on Holder files, see "Generated Files: Holder Files".

org/omg/CORBA/CharSeqHolder.java Generated by the IDL-to-Java compiler (portable), version "3.0" from streams.idl 13 May 1999 22:41:36 o'clock GMT+00:00

Field Summary
 char[] value
Constructor Summary
CharSeqHolder()
CharSeqHolder(char[] initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public char[] value
Constructor Detail

CharSeqHolder

public CharSeqHolder()

CharSeqHolder

public CharSeqHolder(char[] initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


COMM_FAILURE (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class COMM_FAILURE

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by org.omg.CORBA.SystemException
                    extended by org.omg.CORBA.COMM_FAILURE
All Implemented Interfaces:
Serializable
public final class COMM_FAILURE
extends SystemException

This exception is raised if communication is lost while an operation is in progress, after the request was sent by the client, but before the reply from the server has been returned to the client.

It contains a minor code, which gives more detailed information about what caused the exception, and a completion status. It may also contain a string describing the exception.

See the section meaning of minor codes to see the minor codes for this exception.

Since:
JDK1.2
See Also:
meaning of minor codes

Field Summary
Fields inherited from class org.omg.CORBA.SystemException
completed, minor
Constructor Summary
COMM_FAILURE()
Constructs a COMM_FAILURE exception with a default minor code of 0 and a completion state of COMPLETED_NO.
COMM_FAILURE(int minor, CompletionStatus completed)
Constructs a COMM_FAILURE exception with the specified minor code and completion status.
COMM_FAILURE(String s)
Constructs a COMM_FAILURE exception with the specified detail message, a minor code of 0, and a completion state of COMPLETED_NO.
COMM_FAILURE(String s, int minor, CompletionStatus completed)
Constructs a COMM_FAILURE exception with the specified detail message, minor code, and completion status.
Methods inherited from class org.omg.CORBA.SystemException
toString
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

COMM_FAILURE

public COMM_FAILURE()
Constructs a COMM_FAILURE exception with a default minor code of 0 and a completion state of COMPLETED_NO.

COMM_FAILURE

public COMM_FAILURE(String s)
Constructs a COMM_FAILURE exception with the specified detail message, a minor code of 0, and a completion state of COMPLETED_NO.

Parameters:
s - the String containing a detail message describing this exception

COMM_FAILURE

public COMM_FAILURE(int minor,
                    CompletionStatus completed)
Constructs a COMM_FAILURE exception with the specified minor code and completion status.

Parameters:
minor - the minor code
completed - the completion status, which must be one of COMPLETED_YES, COMPLETED_NO, or COMPLETED_MAYBE.

COMM_FAILURE

public COMM_FAILURE(String s,
                    int minor,
                    CompletionStatus completed)
Constructs a COMM_FAILURE exception with the specified detail message, minor code, and completion status. A detail message is a String that describes this particular exception.

Parameters:
s - the String containing a detail message
minor - the minor code
completed - the completion status, which must be one of COMPLETED_YES, COMPLETED_NO, or COMPLETED_MAYBE.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


CompletionStatus (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class CompletionStatus

java.lang.Object
    extended by org.omg.CORBA.CompletionStatus
All Implemented Interfaces:
IDLEntity, Serializable
public final class CompletionStatus
extends Object
implements IDLEntity

An object that indicates whether a method had completed running when a SystemException was thrown.

The class CompletionStatus contains three CompletionStatus instances, which are constants representing each possible completion status: COMPLETED_MAYBE, COMPLETED_NO, and COMPLETED_YES. It also contains three int members, each a constant corresponding to one of the CompletionStatus instances. These int members make it possible to use a switch statement.

The class also contains two methods:

  • public int value() -- which accesses the value field of a CompletionStatus object
  • public static CompletionStatus from_int(int i) -- for creating an instance from one of the int members

Since:
JDK1.2
See Also:
SystemException

Field Summary
static int | _COMPLETED_MAYBE The constant indicating that a method completed running before a SystemException was thrown.
static int | _COMPLETED_NO The constant indicating that a method completed running before a SystemException was thrown.
static int | _COMPLETED_YES The constant indicating that a method completed running before a SystemException was thrown.
static CompletionStatus | COMPLETED_MAYBE An instance of CompletionStatus initialized with the constant _COMPLETED_MAYBE.
static CompletionStatus | COMPLETED_NO An instance of CompletionStatus initialized with the constant _COMPLETED_NO.
static CompletionStatus | COMPLETED_YES An instance of CompletionStatus initialized with the constant _COMPLETED_YES.
Method Summary
static CompletionStatus | from_int(int i) Creates a CompletionStatus object from the given int.
int | value() Retrieves the value of this CompletionStatus object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

_COMPLETED_YES

public static final int _COMPLETED_YES
The constant indicating that a method completed running before a SystemException was thrown.

See Also:
Constant Field Values

_COMPLETED_NO

public static final int _COMPLETED_NO
The constant indicating that a method completed running before a SystemException was thrown.

See Also:
Constant Field Values

_COMPLETED_MAYBE

public static final int _COMPLETED_MAYBE
The constant indicating that a method completed running before a SystemException was thrown.

See Also:
Constant Field Values

COMPLETED_YES

public static final CompletionStatus COMPLETED_YES
An instance of CompletionStatus initialized with the constant _COMPLETED_YES.

COMPLETED_NO

public static final CompletionStatus COMPLETED_NO
An instance of CompletionStatus initialized with the constant _COMPLETED_NO.

COMPLETED_MAYBE

public static final CompletionStatus COMPLETED_MAYBE
An instance of CompletionStatus initialized with the constant _COMPLETED_MAYBE.

Method Detail

value

public int value()
Retrieves the value of this CompletionStatus object.

Returns:
one of the possible CompletionStatus values: _COMPLETED_YES, _COMPLETED_NO, or _COMPLETED_MAYBE

from_int

public static CompletionStatus from_int(int i)
Creates a CompletionStatus object from the given int.

Parameters:
i - one of _COMPLETED_YES, _COMPLETED_NO, or _COMPLETED_MAYBE
Returns:
one of the possible CompletionStatus objects with values: _COMPLETED_YES, _COMPLETED_NO, or _COMPLETED_MAYBE
Throws:
BAD_PARAM - if the argument given is not one of the int constants defined in CompletionStatus
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


CompletionStatusHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class CompletionStatusHelper

java.lang.Object
    extended by org.omg.CORBA.CompletionStatusHelper
public abstract class CompletionStatusHelper
extends Object

The Helper for CompletionStatus. For more information on Helper files, see "Generated Files: Helper Files".

org/omg/CORBA/CompletionStatusHelper.java Generated by the IDL-to-Java compiler (portable), version "3.0" 03 June 1999 11:52:03 o'clock GMT+00:00

Constructor Summary
CompletionStatusHelper()
Method Summary
static CompletionStatus | extract(Any a)
static String | id()
static void | insert(Any a, CompletionStatus that)
static CompletionStatus | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, CompletionStatus value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

CompletionStatusHelper

public CompletionStatusHelper()
Method Detail

insert

public static void insert(Any a,
                          CompletionStatus that)

extract

public static CompletionStatus extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static CompletionStatus read(InputStream istream)

write

public static void write(OutputStream ostream,
                         CompletionStatus value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Context (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class Context

java.lang.Object
    extended by org.omg.CORBA.Context
public abstract class Context
extends Object

An object used in Request operations to specify the context object in which context strings must be resolved before being sent along with the request invocation. A Context object contains a list of properties in the form of NamedValue objects. These properties represent information about the client, the environment, or the circumstances of a request and generally are properties that might be inconvenient to pass as parameters.

A Context object is created by first calling the ORB method get_default_context and then calling the method create_child on the default context.

Each property in a Context object is represented by a NamedValue object. The property name is contained in the NamedValue object's name field, and the value associated with the name is contained in the Any object that was assigned to the NamedValue object's value field.

Context properties can represent a portion of a client's or application's environment that is meant to be propagated to (and made implicitly part of) a server's environment. (Examples might be a window identifier or user preference information). Once a server has been invoked (that is, after the properties are propagated), the server may query its Context object for these properties using the method get_values.

When an operation declaration includes a context clause, the stubs and skeletons will have an additional argument added for the context. When an operation invocation occurs, the ORB causes the properties that were named in the operation definition in IDL and that are present in the client's Context object to be provided in the Context object parameter to the invoked method.

Context property names (which are strings) typically have the form of an OMG IDL identifier or a series of OMG IDL identifiers separated by periods. A context property name pattern is either a property name or a property name followed by a single "*". A property name pattern without a trailing "*" is said to match only itself. A property name pattern of the form "<name>*" matches any property name that starts with <name> and continues with zero or more additional characters.

Property name patterns are used in the context clause of an operation definition and as a parameter for the method Context.get_values.

Context objects may be "chained" together to achieve a particular defaulting behavior. A Context object created with the method create_child will be chained to its parent (the Context object that created it), and that means that the parent will be searched after the child in a search for property names.

Properties defined in a particular Context object effectively override those properties in the next higher level. The scope used in a search for properties may be restricted by specifying a starting scope and by using the flag CTX_RESTRICT_SCOPE when invoking the method get_values.

A Context object may be named for purposes of specifying a starting search scope.

Since:
JDK1.2

Constructor Summary
Context()
Method Summary
abstract String | context_name() Retrieves the name of this Context object.
abstract Context | create_child(String child_ctx_name) Creates a Context object with the given string as its name and with this Context object set as its parent.
abstract void | delete_values(String propname) Deletes from this Context object the NamedValue object(s) whose name field matches the given property name.
abstract NVList | get_values(String start_scope, int op_flags, String pattern) Retrieves the NamedValue objects whose name field matches the given name or name pattern.
abstract Context | parent() Retrieves the parent of this Context object.
abstract void | set_one_value(String propname, Any propvalue) Creates a NamedValue object and adds it to this Context object.
abstract void | set_values(NVList values) I Sets one or more property values in this Context object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

Context

public Context()
Method Detail

context_name

public abstract String context_name()
Retrieves the name of this Context object.

Returns:
the name of this Context object

parent

public abstract Context parent()
Retrieves the parent of this Context object.

Returns:
the Context object that is the parent of this Context object

create_child

public abstract Context create_child(String child_ctx_name)
Creates a Context object with the given string as its name and with this Context object set as its parent.

The new Context object is chained into its parent Context object. This means that in a search for matching property names, if a match is not found in this context, the search will continue in the parent. If that is not successful, the search will continue in the grandparent, if there is one, and so on.

Parameters:
child_ctx_name - the String object to be set as the name of the new Context object
Returns:
the newly-created child Context object initialized with the specified name

set_one_value

public abstract void set_one_value(String propname,
                                   Any propvalue)
Creates a NamedValue object and adds it to this Context object. The name field of the new NamedValue object is set to the given string, the value field is set to the given Any object, and the flags field is set to zero.

Parameters:
propname - the name of the property to be set
propvalue - the Any object to which the value of the property will be set. The Any object's value field contains the value to be associated with the given propname; the kind field must be set to TCKind.tk_string.

set_values

public abstract void set_values(NVList values)
I Sets one or more property values in this Context object. The NVList supplied to this method contains one or more NamedValue objects. In each NamedValue object, the name field holds the name of the property, and the flags field must be set to zero. The NamedValue object's value field contains an Any object, which, in turn, contains the value for the property. Since the value is always a string, the Any object must have the kind field of its TypeCode set to TCKind.tk_string.

Parameters:
values - an NVList containing the property names and associated values to be set
See Also:
get_values(java.lang.String, int, java.lang.String), NamedValue, Any

delete_values

public abstract void delete_values(String propname)
Deletes from this Context object the NamedValue object(s) whose name field matches the given property name. If the String object supplied for propname has a trailing wildcard character ("*"), then all NamedValue objects whose name fields match will be deleted. The search scope is always limited to this Context object.

If no matching property is found, an exception is returned.

Parameters:
propname - name of the property to be deleted

get_values

public abstract NVList get_values(String start_scope,
                                  int op_flags,
                                  String pattern)
Retrieves the NamedValue objects whose name field matches the given name or name pattern. This method allows for wildcard searches, which means that there can be multiple matches and therefore multiple values returned. If the property is not found at the indicated level, the search continues up the context object tree until a match is found or all Context objects in the chain have been exhausted.

If no match is found, an error is returned and no property list is returned.

Parameters:
start_scope - a String object indicating the context object level at which to initiate the search for the specified properties (for example, "_USER", "_GROUP", "_SYSTEM"). Valid scope names are implementation-specific. If a scope name is omitted, the search begins with the specified context object. If the specified scope name is not found, an exception is returned.
op_flags - an operation flag. The one flag that may be specified is CTX_RESTRICT_SCOPE. If this flag is specified, searching is limited to the specified start_scope or this Context object.
pattern - the property name whose values are to be retrieved. pattern may be a name or a name with a trailing wildcard character ("*").
Returns:
an NVList containing all the property values (in the form of NamedValue objects) whose associated property name matches the given name or name pattern
See Also:
set_values(org.omg.CORBA.NVList), NamedValue
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ContextList (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class ContextList

java.lang.Object
    extended by org.omg.CORBA.ContextList
public abstract class ContextList
extends Object

An object containing a modifiable list of String objects that represent property names. This class is used in Request operations to describe the contexts that need to be resolved and sent with the invocation. (A context is resolved by giving a property name and getting back the value associated with it.) This is done by calling the Context method get_values and supplying a string from a ContextList object as the third parameter. The method get_values returns an NVList object containing the NamedValue objects that hold the value(s) identified by the given string.

A ContextList object is created by the ORB, as illustrated here:

   ORB orb = ORB.init(args, null);
   org.omg.CORBA.ContextList ctxList = orb.create_context_list();
The variable ctxList represents an empty ContextList object. Strings are added to the list with the method add, accessed with the method item, and removed with the method remove.

Since:
JDK1.2
See Also:
Context

Constructor Summary
ContextList()
Method Summary
abstract void | add(String ctx) Adds a String object to this ContextList object.
abstract int | count() Returns the number of String objects in this ContextList object.
abstract String | item(int index) Returns the String object at the given index.
abstract void | remove(int index) Removes the String object at the given index.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ContextList

public ContextList()
Method Detail

count

public abstract int count()
Returns the number of String objects in this ContextList object.

Returns:
an int representing the number of Strings in this ContextList object

add

public abstract void add(String ctx)
Adds a String object to this ContextList object.

Parameters:
ctx - the String object to be added

item

public abstract String item(int index)
                     throws Bounds
Returns the String object at the given index.

Parameters:
index - the index of the string desired, with 0 being the index of the first string
Returns:
the string at the given index
Throws:
Bounds - if the index is greater than or equal to the number of strings in this ContextList object

remove

public abstract void remove(int index)
                     throws Bounds
Removes the String object at the given index. Note that the indices of all strings following the one removed are shifted down by one.

Parameters:
index - the index of the String object to be removed, with 0 designating the first string
Throws:
Bounds - if the index is greater than or equal to the number of String objects in this ContextList object
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


CTX_RESTRICT_SCOPE (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Interface CTX_RESTRICT_SCOPE

public interface CTX_RESTRICT_SCOPE

A flag that can be used as the second parameter to the method Context.get_values to restrict the search scope. When this flag is used, it restricts the search for context values to this particular Context object or to the scope specified in the first parameter to Context.get_values.

Usage:

     NVList props = myContext.get_values("_USER",
                     CTX_RESTRICT_SCOPE.value, "id*");

Since:
JDK1.2
See Also:
Context.get_values(String, int, String)

Field Summary
static int value
The field containing the int value of a CTX_RESTRICT_SCOPE flag.

Field Detail

value

public static final int value
The field containing the int value of a CTX_RESTRICT_SCOPE flag.

See Also:
Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Current (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Interface Current

All Superinterfaces:
CurrentOperations, IDLEntity, Object, Serializable
All Known Subinterfaces:
Current, Current
public interface Current
extends CurrentOperations, Object, IDLEntity

Interfaces derived from the Current interface enable ORB and CORBA services to provide access to information (context) associated with the thread of execution in which they are running. This information is accessed in a structured manner using interfaces derived from the Current interface defined in the CORBA module.

Each ORB or CORBA service that needs its own context derives an interface from the CORBA module's Current. Users of the service can obtain an instance of the appropriate Current interface by invoking ORB::resolve_initial_references.

org/omg/CORBA/Current.java Generated by the IDL-to-Java compiler (portable), version "3.0" from ../../../../../src/share/classes/org/omg/PortableServer/corba.idl Saturday, July 17, 1999 12:26:21 AM PDT.

Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


CurrentHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class CurrentHelper

java.lang.Object
    extended by org.omg.CORBA.CurrentHelper
public abstract class CurrentHelper
extends Object

The Helper for Current. For more information on Helper files, see "Generated Files: Helper Files".

org/omg/CORBA/CurrentHelper.java Generated by the IDL-to-Java compiler (portable), version "3.0" from ../../../../../src/share/classes/org/omg/PortableServer/corba.idl Saturday, July 17, 1999 12:26:21 AM PDT

Constructor Summary
CurrentHelper()
Method Summary
static Current | extract(Any a)
static String | id()
static void | insert(Any a, Current that)
static Current | narrow(Object obj)
static Current | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, Current value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

CurrentHelper

public CurrentHelper()
Method Detail

insert

public static void insert(Any a,
                          Current that)

extract

public static Current extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static Current read(InputStream istream)

write

public static void write(OutputStream ostream,
                         Current value)

narrow

public static Current narrow(Object obj)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


CurrentHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class CurrentHolder

java.lang.Object
    extended by org.omg.CORBA.CurrentHolder
All Implemented Interfaces:
Streamable
public final class CurrentHolder
extends Object
implements Streamable

The Holder for Current. For more information on Holder files, see "Generated Files: Holder Files".

org/omg/CORBA/CurrentHolder.java Generated by the IDL-to-Java compiler (portable), version "3.0" from ../../../../../src/share/classes/org/omg/PortableServer/corba.idl Saturday, July 17, 1999 12:26:21 AM PDT

Field Summary
 Current value
Constructor Summary
CurrentHolder()
CurrentHolder(Current initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public Current value
Constructor Detail

CurrentHolder

public CurrentHolder()

CurrentHolder

public CurrentHolder(Current initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


CurrentOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Interface CurrentOperations

All Known Subinterfaces:
Current, Current, Current, CurrentOperations, CurrentOperations
public interface CurrentOperations

The interface for Current. For more information on Operations interfaces, see "Generated Files". org/omg/CORBA/CurrentOperations.java Generated by the IDL-to-Java compiler (portable), version "3.0" from ../../../../../src/share/classes/org/omg/PortableServer/corba.idl Saturday, July 17, 1999 12:26:21 AM PDT.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


CustomMarshal (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Interface CustomMarshal

All Known Subinterfaces:
CustomValue
public interface CustomMarshal

An abstract value type that is meant to be used by the ORB, not the user. Semantically it is treated as a custom valuetype's implicit base class, although the custom valutype does not actually inherit it in IDL. The implementer of a custom value type shall provide an implementation of the CustomMarshal operations. The manner in which this is done is specified in the IDL to Java langague mapping. Each custom marshaled value type shall have its own implementation.

See Also:
DataOutputStream, DataInputStream

Method Summary
void | marshal(DataOutputStream os) Marshal method has to be implemented by the Customized Marshal class This is the method invoked for Marshalling.
void | unmarshal(DataInputStream is) Unmarshal method has to be implemented by the Customized Marshal class This is the method invoked for Unmarshalling.

Method Detail

marshal

public void marshal(DataOutputStream os)
Marshal method has to be implemented by the Customized Marshal class This is the method invoked for Marshalling.

Parameters:
os - a DataOutputStream

unmarshal

public void unmarshal(DataInputStream is)
Unmarshal method has to be implemented by the Customized Marshal class This is the method invoked for Unmarshalling.

Parameters:
is - a DataInputStream
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DATA_CONVERSION (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class DATA_CONVERSION

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by org.omg.CORBA.SystemException
                    extended by org.omg.CORBA.DATA_CONVERSION
All Implemented Interfaces:
Serializable
public final class DATA_CONVERSION
extends SystemException

This exception is raised if an ORB cannot convert the representation of data as marshaled into its native representation or vice-versa. For example, DATA_CONVERSION can be raised if wide character codeset conversion fails, or if an ORB cannot convert floating point values between different representations.

It contains a minor code, which gives more detailed information about what caused the exception, and a completion status. It may also contain a string describing the exception.

See the section meaning of minor codes to see the minor codes for this exception.

Since:
JDK1.2
See Also:
documentation on Java IDL exceptions

Field Summary
Fields inherited from class org.omg.CORBA.SystemException
completed, minor
Constructor Summary
DATA_CONVERSION()
Constructs a DATA_CONVERSION exception with a default minor code of 0 and a completion state of COMPLETED_NO.
DATA_CONVERSION(int minor, CompletionStatus completed)
Constructs a DATA_CONVERSION exception with the specified minor code and completion status.
DATA_CONVERSION(String s)
Constructs a DATA_CONVERSION exception with the specified detail.
DATA_CONVERSION(String s, int minor, CompletionStatus completed)
Constructs a DATA_CONVERSION exception with the specified detail message, minor code, and completion status.
Methods inherited from class org.omg.CORBA.SystemException
toString
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

DATA_CONVERSION

public DATA_CONVERSION()
Constructs a DATA_CONVERSION exception with a default minor code of 0 and a completion state of COMPLETED_NO.

DATA_CONVERSION

public DATA_CONVERSION(String s)
Constructs a DATA_CONVERSION exception with the specified detail.

Parameters:
s - the String containing a detail message

DATA_CONVERSION

public DATA_CONVERSION(int minor,
                       CompletionStatus completed)
Constructs a DATA_CONVERSION exception with the specified minor code and completion status.

Parameters:
minor - the minor code
completed - the completion status

DATA_CONVERSION

public DATA_CONVERSION(String s,
                       int minor,
                       CompletionStatus completed)
Constructs a DATA_CONVERSION exception with the specified detail message, minor code, and completion status. A detail message is a String that describes this particular exception.

Parameters:
s - the String containing a detail message
minor - the minor code
completed - the completion status
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DataInputStream (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Interface DataInputStream

All Superinterfaces:
IDLEntity, Serializable, ValueBase
public interface DataInputStream
extends ValueBase

Defines the methods used to read primitive data types from input streams for unmarshaling custom value types. This interface is used by user written custom unmarshaling code for custom value types.

See Also:
DataOutputStream, CustomMarshal

Method Summary
 Object read_Abstract()
Reads an IDL Abstract interface from the input stream.
 void read_any_array(AnySeqHolder seq, int offset, int length)
Reads array of IDL Anys from offset for length elements from the input stream.
 Any read_any()
Reads an IDL Any value from the input stream.
 void read_boolean_array(BooleanSeqHolder seq, int offset, int length)
Reads array of IDL booleans from offset for length elements from the input stream.
 boolean read_boolean()
Reads an IDL boolean value from the input stream.
 void read_char_array(CharSeqHolder seq, int offset, int length)
Reads array of IDL characters from offset for length elements from the input stream.
 char read_char()
Reads an IDL character value from the input stream.
 void read_double_array(DoubleSeqHolder seq, int offset, int length)
Reads array of IDL doubles from offset for length elements from the input stream.
 double read_double()
Reads an IDL double from the input stream.
 void read_float_array(FloatSeqHolder seq, int offset, int length)
Reads array of IDL floats from offset for length elements from the input stream.
 float read_float()
Reads an IDL float from the input stream.
 void read_long_array(LongSeqHolder seq, int offset, int length)
Reads array of IDL longs from offset for length elements from the input stream.
 int read_long()
Reads an IDL long from the input stream.
 void read_longlong_array(LongLongSeqHolder seq, int offset, int length)
Reads array of IDL long longs from offset for length elements from the input stream.
 long read_longlong()
Reads an IDL long long from the input stream.
 Object read_Object()
Reads an IDL CORBA::Object from the input stream.
 void read_octet_array(OctetSeqHolder seq, int offset, int length)
Reads array of IDL octets from offset for length elements from the input stream.
 byte read_octet()
Reads an IDL octet value from the input stream.
 void read_short_array(ShortSeqHolder seq, int offset, int length)
Reads array of IDL shorts from offset for length elements from the input stream.
 short read_short()
Reads an IDL short from the input stream.
 String read_string()
Reads an IDL string from the input stream.
 TypeCode read_TypeCode()
Reads an IDL typecode from the input stream.
 void read_ulong_array(ULongSeqHolder seq, int offset, int length)
Reads array of IDL unsigned longs from offset for length elements from the input stream.
 int read_ulong()
Reads an IDL unsigned long from the input stream.
 void read_ulonglong_array(ULongLongSeqHolder seq, int offset, int length)
Reads array of IDL unsigned long longs from offset for length elements from the input stream.
 long read_ulonglong()
Reads an unsigned IDL long long from the input stream.
 void read_ushort_array(UShortSeqHolder seq, int offset, int length)
Reads array of IDL unsigned shorts from offset for length elements from the input stream.
 short read_ushort()
Reads an IDL unsigned short from the input stream.
 Serializable read_Value()
Reads an IDL value type from the input stream.
 void read_wchar_array(WCharSeqHolder seq, int offset, int length)
Reads array of IDL wide characters from offset for length elements from the input stream.
 char read_wchar()
Reads an IDL wide character value from the input stream.
 String read_wstring()
Reads an IDL wide string from the input stream.
Methods inherited from interface org.omg.CORBA.portable.ValueBase
_truncatable_ids

Method Detail

read_any

public Any read_any()
Reads an IDL Any value from the input stream.

Returns:
the Any read.
Throws:
org.omg.CORBA.MARSHAL - If an inconsistency is detected, including not having registered a streaming policy, then the standard system exception MARSHAL is raised.

read_boolean

public boolean read_boolean()
Reads an IDL boolean value from the input stream.

Returns:
the boolean read.
Throws:
org.omg.CORBA.MARSHAL - If an inconsistency is detected, including not having registered a streaming policy, then the standard system exception MARSHAL is raised.

read_char

public char read_char()
Reads an IDL character value from the input stream.

Returns:
the character read.
Throws:
org.omg.CORBA.MARSHAL - If an inconsistency is detected, including not having registered a streaming policy, then the standard system exception MARSHAL is raised.

read_wchar

public char read_wchar()
Reads an IDL wide character value from the input stream.

Returns:
the wide character read.
Throws:
org.omg.CORBA.MARSHAL - If an inconsistency is detected, including not having registered a streaming policy, then the standard system exception MARSHAL is raised.

read_octet

public byte read_octet()
Reads an IDL octet value from the input stream.

Returns:
the octet value read.
Throws:
org.omg.CORBA.MARSHAL - If an inconsistency is detected, including not having registered a streaming policy, then the standard system exception MARSHAL is raised.

read_short

public short read_short()
Reads an IDL short from the input stream.

Returns:
the short read.
Throws:
org.omg.CORBA.MARSHAL - If an inconsistency is detected, including not having registered a streaming policy, then the standard system exception MARSHAL is raised.

read_ushort

public short read_ushort()
Reads an IDL unsigned short from the input stream.

Returns:
the unsigned short read.
Throws:
org.omg.CORBA.MARSHAL - If an inconsistency is detected, including not having registered a streaming policy, then the standard system exception MARSHAL is raised.

read_long

public int read_long()
Reads an IDL long from the input stream.

Returns:
the long read.
Throws:
org.omg.CORBA.MARSHAL - If an inconsistency is detected, including not having registered a streaming policy, then the standard system exception MARSHAL is raised.

read_ulong

public int read_ulong()
Reads an IDL unsigned long from the input stream.

Returns:
the unsigned long read.
Throws:
org.omg.CORBA.MARSHAL - If an inconsistency is detected, including not having registered a streaming policy, then the standard system exception MARSHAL is raised.

read_longlong

public long read_longlong()
Reads an IDL long long from the input stream.

Returns:
the long long read.
Throws:
org.omg.CORBA.MARSHAL - If an inconsistency is detected, including not having registered a streaming policy, then the standard system exception MARSHAL is raised.

read_ulonglong

public long read_ulonglong()
Reads an unsigned IDL long long from the input stream.

Returns:
the unsigned long long read.
Throws:
org.omg.CORBA.MARSHAL - If an inconsistency is detected, including not having registered a streaming policy, then the standard system exception MARSHAL is raised.

read_float

public float read_float()
Reads an IDL float from the input stream.

Returns:
the float read.
Throws:
org.omg.CORBA.MARSHAL - If an inconsistency is detected, including not having registered a streaming policy, then the standard system exception MARSHAL is raised.

read_double

public double read_double()
Reads an IDL double from the input stream.

Returns:
the double read.
Throws:
org.omg.CORBA.MARSHAL - If an inconsistency is detected, including not having registered a streaming policy, then the standard system exception MARSHAL is raised.

read_string

public String read_string()
Reads an IDL string from the input stream.

Returns:
the string read.
Throws:
org.omg.CORBA.MARSHAL - If an inconsistency is detected, including not having registered a streaming policy, then the standard system exception MARSHAL is raised.

read_wstring

public String read_wstring()
Reads an IDL wide string from the input stream.

Returns:
the wide string read.
Throws:
org.omg.CORBA.MARSHAL - If an inconsistency is detected, including not having registered a streaming policy, then the standard system exception MARSHAL is raised.

read_Object

public Object read_Object()
Reads an IDL CORBA::Object from the input stream.

Returns:
the CORBA::Object read.
Throws:
org.omg.CORBA.MARSHAL - If an inconsistency is detected, including not having registered a streaming policy, then the standard system exception MARSHAL is raised.

read_Abstract

public Object read_Abstract()
Reads an IDL Abstract interface from the input stream.

Returns:
the Abstract interface read.
Throws:
org.omg.CORBA.MARSHAL - If an inconsistency is detected, including not having registered a streaming policy, then the standard system exception MARSHAL is raised.

read_Value

public Serializable read_Value()
Reads an IDL value type from the input stream.

Returns:
the value type read.
Throws:
org.omg.CORBA.MARSHAL - If an inconsistency is detected, including not having registered a streaming policy, then the standard system exception MARSHAL is raised.

read_TypeCode

public TypeCode read_TypeCode()
Reads an IDL typecode from the input stream.

Returns:
the typecode read.
Throws:
org.omg.CORBA.MARSHAL - If an inconsistency is detected, including not having registered a streaming policy, then the standard system exception MARSHAL is raised.

read_any_array

public void read_any_array(AnySeqHolder seq,
                           int offset,
                           int length)
Reads array of IDL Anys from offset for length elements from the input stream.

Parameters:
seq - The out parameter holder for the array to be read.
offset - The index into seq of the first element to read from the input stream.
length - The number of elements to read from the input stream.
Throws:
org.omg.CORBA.MARSHAL - If an inconsistency is detected, including not having registered a streaming policy, then the standard system exception MARSHAL is raised.

read_boolean_array

public void read_boolean_array(BooleanSeqHolder seq,
                               int offset,
                               int length)
Reads array of IDL booleans from offset for length elements from the input stream.

Parameters:
seq - The out parameter holder for the array to be read.
offset - The index into seq of the first element to read from the input stream.
length - The number of elements to read from the input stream.
Throws:
org.omg.CORBA.MARSHAL - If an inconsistency is detected, including not having registered a streaming policy, then the standard system exception MARSHAL is raised.

read_char_array

public void read_char_array(CharSeqHolder seq,
                            int offset,
                            int length)
Reads array of IDL characters from offset for length elements from the input stream.

Parameters:
seq - The out parameter holder for the array to be read.
offset - The index into seq of the first element to read from the input stream.
length - The number of elements to read from the input stream.
Throws:
org.omg.CORBA.MARSHAL - If an inconsistency is detected, including not having registered a streaming policy, then the standard system exception MARSHAL is raised.

read_wchar_array

public void read_wchar_array(WCharSeqHolder seq,
                             int offset,
                             int length)
Reads array of IDL wide characters from offset for length elements from the input stream.

Parameters:
seq - The out parameter holder for the array to be read.
offset - The index into seq of the first element to read from the input stream.
length - The number of elements to read from the input stream.
Throws:
org.omg.CORBA.MARSHAL - If an inconsistency is detected, including not having registered a streaming policy, then the standard system exception MARSHAL is raised.

read_octet_array

public void read_octet_array(OctetSeqHolder seq,
                             int offset,
                             int length)
Reads array of IDL octets from offset for length elements from the input stream.

Parameters:
seq - The out parameter holder for the array to be read.
offset - The index into seq of the first element to read from the input stream.
length - The number of elements to read from the input stream.
Throws:
org.omg.CORBA.MARSHAL - If an inconsistency is detected, including not having registered a streaming policy, then the standard system exception MARSHAL is raised.

read_short_array

public void read_short_array(ShortSeqHolder seq,
                             int offset,
                             int length)
Reads array of IDL shorts from offset for length elements from the input stream.

Parameters:
seq - The out parameter holder for the array to be read.
offset - The index into seq of the first element to read from the input stream.
length - The number of elements to read from the input stream.
Throws:
org.omg.CORBA.MARSHAL - If an inconsistency is detected, including not having registered a streaming policy, then the standard system exception MARSHAL is raised.

read_ushort_array

public void read_ushort_array(UShortSeqHolder seq,
                              int offset,
                              int length)
Reads array of IDL unsigned shorts from offset for length elements from the input stream.

Parameters:
seq - The out parameter holder for the array to be read.
offset - The index into seq of the first element to read from the input stream.
length - The number of elements to read from the input stream.
Throws:
org.omg.CORBA.MARSHAL - If an inconsistency is detected, including not having registered a streaming policy, then the standard system exception MARSHAL is raised.

read_long_array

public void read_long_array(LongSeqHolder seq,
                            int offset,
                            int length)
Reads array of IDL longs from offset for length elements from the input stream.

Parameters:
seq - The out parameter holder for the array to be read.
offset - The index into seq of the first element to read from the input stream.
length - The number of elements to read from the input stream.
Throws:
org.omg.CORBA.MARSHAL - If an inconsistency is detected, including not having registered a streaming policy, then the standard system exception MARSHAL is raised.

read_ulong_array

public void read_ulong_array(ULongSeqHolder seq,
                             int offset,
                             int length)
Reads array of IDL unsigned longs from offset for length elements from the input stream.

Parameters:
seq - The out parameter holder for the array to be read.
offset - The index into seq of the first element to read from the input stream.
length - The number of elements to read from the input stream.
Throws:
org.omg.CORBA.MARSHAL - If an inconsistency is detected, including not having registered a streaming policy, then the standard system exception MARSHAL is raised.

read_ulonglong_array

public void read_ulonglong_array(ULongLongSeqHolder seq,
                                 int offset,
                                 int length)
Reads array of IDL unsigned long longs from offset for length elements from the input stream.

Parameters:
seq - The out parameter holder for the array to be read.
offset - The index into seq of the first element to read from the input stream.
length - The number of elements to read from the input stream.
Throws:
org.omg.CORBA.MARSHAL - If an inconsistency is detected, including not having registered a streaming policy, then the standard system exception MARSHAL is raised.

read_longlong_array

public void read_longlong_array(LongLongSeqHolder seq,
                                int offset,
                                int length)
Reads array of IDL long longs from offset for length elements from the input stream.

Parameters:
seq - The out parameter holder for the array to be read.
offset - The index into seq of the first element to read from the input stream.
length - The number of elements to read from the input stream.
Throws:
org.omg.CORBA.MARSHAL - If an inconsistency is detected, including not having registered a streaming policy, then the standard system exception MARSHAL is raised.

read_float_array

public void read_float_array(FloatSeqHolder seq,
                             int offset,
                             int length)
Reads array of IDL floats from offset for length elements from the input stream.

Parameters:
seq - The out parameter holder for the array to be read.
offset - The index into seq of the first element to read from the input stream.
length - The number of elements to read from the input stream.
Throws:
org.omg.CORBA.MARSHAL - If an inconsistency is detected, including not having registered a streaming policy, then the standard system exception MARSHAL is raised.

read_double_array

public void read_double_array(DoubleSeqHolder seq,
                              int offset,
                              int length)
Reads array of IDL doubles from offset for length elements from the input stream.

Parameters:
seq - The out parameter holder for the array to be read.
offset - The index into seq of the first element to read from the input stream.
length - The number of elements to read from the input stream.
Throws:
org.omg.CORBA.MARSHAL - If an inconsistency is detected, including not having registered a streaming policy, then the standard system exception MARSHAL is raised.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DataOutputStream (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Interface DataOutputStream

All Superinterfaces:
IDLEntity, Serializable, ValueBase
public interface DataOutputStream
extends ValueBase

Defines the methods used to write primitive data types to output streams for marshalling custom value types. This interface is used by user written custom marshalling code for custom value types.

See Also:
DataInputStream, CustomMarshal

Method Summary
void | write_Abstract(Object value) Writes the IDL Abstract interface type to the output stream.
void | write_any_array(Any[] seq, int offset, int length) Writes the array of IDL Anys from offset for length elements to the output stream.
void | write_any(Any value) Writes the Any value to the output stream.
void | write_boolean_array(boolean[] seq, int offset, int length) Writes the array of IDL booleans from offset for length elements to the output stream.
void | write_boolean(boolean value) Writes the boolean value to the output stream.
void | write_char_array(char[] seq, int offset, int length) Writes the array of IDL characters from offset for length elements to the output stream.
void | write_char(char value) Writes the IDL character value to the output stream.
void | write_double_array(double[] seq, int offset, int length) Writes the array of IDL doubles from offset for length elements to the output stream.
void | write_double(double value) Writes the IDL double value to the output stream.
void | write_float_array(float[] seq, int offset, int length) Writes the array of IDL floats from offset for length elements to the output stream.
void | write_float(float value) Writes the IDL float value to the output stream.
void | write_long_array(int[] seq, int offset, int length) Writes the array of IDL longs from offset for length elements to the output stream.
void | write_long(int value) Writes the IDL long value (represented as a Java int) to the output stream.
void | write_longlong_array(long[] seq, int offset, int length) Writes the array of IDL long longs from offset for length elements to the output stream.
void | write_longlong(long value) Writes the IDL long long value (represented as a Java long) to the output stream.
void | write_Object(Object value) Writes the IDL CORBA::Object value to the output stream.
void | write_octet_array(byte[] seq, int offset, int length) Writes the array of IDL octets from offset for length elements to the output stream.
void | write_octet(byte value) Writes the IDL octet value (represented as a Java byte) to the output stream.
void | write_short_array(short[] seq, int offset, int length) Writes the array of IDL shorts from offset for length elements to the output stream.
void | write_short(short value) Writes the IDL short value to the output stream.
void | write_string(String value) Writes the IDL string value to the output stream.
void | write_TypeCode(TypeCode value) Writes the typecode to the output stream.
void | write_ulong_array(int[] seq, int offset, int length) Writes the array of IDL unsigned longs (represented as Java ints) from offset for length elements to the output stream.
void | write_ulong(int value) Writes the IDL unsigned long value (represented as a Java int) to the output stream.
void | write_ulonglong_array(long[] seq, int offset, int length) Writes the array of IDL unsigned long longs (represented as Java longs) from offset for length elements to the output stream.
void | write_ulonglong(long value) Writes the IDL unsigned long long value (represented as a Java long) to the output stream.
void | write_ushort_array(short[] seq, int offset, int length) Writes the array of IDL unsigned shorts (represented as Java shorts) from offset for length elements to the output stream.
void | write_ushort(short value) Writes the IDL unsigned short value (represented as a Java short value) to the output stream.
void | write_Value(Serializable value) Writes the IDL value type value to the output stream.
void | write_wchar_array(char[] seq, int offset, int length) Writes the array of IDL wide characters from offset for length elements to the output stream.
void | write_wchar(char value) Writes the IDL wide character value to the output stream.
void | write_wstring(String value) Writes the IDL wide string value (represented as a Java String) to the output stream.
Methods inherited from interface org.omg.CORBA.portable.ValueBase
_truncatable_ids

Method Detail

write_any

public void write_any(Any value)
Writes the Any value to the output stream.

Parameters:
value - The value to be written.

write_boolean

public void write_boolean(boolean value)
Writes the boolean value to the output stream.

Parameters:
value - The value to be written.

write_char

public void write_char(char value)
Writes the IDL character value to the output stream.

Parameters:
value - The value to be written.

write_wchar

public void write_wchar(char value)
Writes the IDL wide character value to the output stream.

Parameters:
value - The value to be written.

write_octet

public void write_octet(byte value)
Writes the IDL octet value (represented as a Java byte) to the output stream.

Parameters:
value - The value to be written.

write_short

public void write_short(short value)
Writes the IDL short value to the output stream.

Parameters:
value - The value to be written.

write_ushort

public void write_ushort(short value)
Writes the IDL unsigned short value (represented as a Java short value) to the output stream.

Parameters:
value - The value to be written.

write_long

public void write_long(int value)
Writes the IDL long value (represented as a Java int) to the output stream.

Parameters:
value - The value to be written.

write_ulong

public void write_ulong(int value)
Writes the IDL unsigned long value (represented as a Java int) to the output stream.

Parameters:
value - The value to be written.

write_longlong

public void write_longlong(long value)
Writes the IDL long long value (represented as a Java long) to the output stream.

Parameters:
value - The value to be written.

write_ulonglong

public void write_ulonglong(long value)
Writes the IDL unsigned long long value (represented as a Java long) to the output stream.

Parameters:
value - The value to be written.

write_float

public void write_float(float value)
Writes the IDL float value to the output stream.

Parameters:
value - The value to be written.

write_double

public void write_double(double value)
Writes the IDL double value to the output stream.

Parameters:
value - The value to be written.

write_string

public void write_string(String value)
Writes the IDL string value to the output stream.

Parameters:
value - The value to be written.

write_wstring

public void write_wstring(String value)
Writes the IDL wide string value (represented as a Java String) to the output stream.

Parameters:
value - The value to be written.

write_Object

public void write_Object(Object value)
Writes the IDL CORBA::Object value to the output stream.

Parameters:
value - The value to be written.

write_Abstract

public void write_Abstract(Object value)
Writes the IDL Abstract interface type to the output stream.

Parameters:
value - The value to be written.

write_Value

public void write_Value(Serializable value)
Writes the IDL value type value to the output stream.

Parameters:
value - The value to be written.

write_TypeCode

public void write_TypeCode(TypeCode value)
Writes the typecode to the output stream.

Parameters:
value - The value to be written.

write_any_array

public void write_any_array(Any[] seq,
                            int offset,
                            int length)
Writes the array of IDL Anys from offset for length elements to the output stream.

Parameters:
seq - The array to be written.
offset - The index into seq of the first element to write to the output stream.
length - The number of elements to write to the output stream.

write_boolean_array

public void write_boolean_array(boolean[] seq,
                                int offset,
                                int length)
Writes the array of IDL booleans from offset for length elements to the output stream.

Parameters:
seq - The array to be written.
offset - The index into seq of the first element to write to the output stream.
length - The number of elements to write to the output stream.

write_char_array

public void write_char_array(char[] seq,
                             int offset,
                             int length)
Writes the array of IDL characters from offset for length elements to the output stream.

Parameters:
seq - The array to be written.
offset - The index into seq of the first element to write to the output stream.
length - The number of elements to write to the output stream.

write_wchar_array

public void write_wchar_array(char[] seq,
                              int offset,
                              int length)
Writes the array of IDL wide characters from offset for length elements to the output stream.

Parameters:
seq - The array to be written.
offset - The index into seq of the first element to write to the output stream.
length - The number of elements to write to the output stream.

write_octet_array

public void write_octet_array(byte[] seq,
                              int offset,
                              int length)
Writes the array of IDL octets from offset for length elements to the output stream.

Parameters:
seq - The array to be written.
offset - The index into seq of the first element to write to the output stream.
length - The number of elements to write to the output stream.

write_short_array

public void write_short_array(short[] seq,
                              int offset,
                              int length)
Writes the array of IDL shorts from offset for length elements to the output stream.

Parameters:
seq - The array to be written.
offset - The index into seq of the first element to write to the output stream.
length - The number of elements to write to the output stream.

write_ushort_array

public void write_ushort_array(short[] seq,
                               int offset,
                               int length)
Writes the array of IDL unsigned shorts (represented as Java shorts) from offset for length elements to the output stream.

Parameters:
seq - The array to be written.
offset - The index into seq of the first element to write to the output stream.
length - The number of elements to write to the output stream.

write_long_array

public void write_long_array(int[] seq,
                             int offset,
                             int length)
Writes the array of IDL longs from offset for length elements to the output stream.

Parameters:
seq - The array to be written.
offset - The index into seq of the first element to write to the output stream.
length - The number of elements to write to the output stream.

write_ulong_array

public void write_ulong_array(int[] seq,
                              int offset,
                              int length)
Writes the array of IDL unsigned longs (represented as Java ints) from offset for length elements to the output stream.

Parameters:
seq - The array to be written.
offset - The index into seq of the first element to write to the output stream.
length - The number of elements to write to the output stream.

write_ulonglong_array

public void write_ulonglong_array(long[] seq,
                                  int offset,
                                  int length)
Writes the array of IDL unsigned long longs (represented as Java longs) from offset for length elements to the output stream.

Parameters:
seq - The array to be written.
offset - The index into seq of the first element to write to the output stream.
length - The number of elements to write to the output stream.

write_longlong_array

public void write_longlong_array(long[] seq,
                                 int offset,
                                 int length)
Writes the array of IDL long longs from offset for length elements to the output stream.

Parameters:
seq - The array to be written.
offset - The index into seq of the first element to write to the output stream.
length - The number of elements to write to the output stream.

write_float_array

public void write_float_array(float[] seq,
                              int offset,
                              int length)
Writes the array of IDL floats from offset for length elements to the output stream.

Parameters:
seq - The array to be written.
offset - The index into seq of the first element to write to the output stream.
length - The number of elements to write to the output stream.

write_double_array

public void write_double_array(double[] seq,
                               int offset,
                               int length)
Writes the array of IDL doubles from offset for length elements to the output stream.

Parameters:
seq - The array to be written.
offset - The index into seq of the first element to write to the output stream.
length - The number of elements to write to the output stream.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DefinitionKind (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class DefinitionKind

java.lang.Object
    extended by org.omg.CORBA.DefinitionKind
All Implemented Interfaces:
IDLEntity, Serializable
public class DefinitionKind
extends Object
implements IDLEntity

The class that provides the constants used to identify the type of an Interface Repository object. This class contains two kinds of constants, those that are an int and those that are an instance of the class DefinitionKind. This class provides the method from_int, which given one of the int constants, creates the corresponding DefinitionKind instance. It also provides the method value, which returns the int constant that is the value for a DefinitionKind instance.

See Also:
IRObject

Field Summary
static int | _dk_AbstractInterface The constant that indicates that an Interface Repository object does not have a definition kind.
static int | _dk_Alias The constant that indicates that an Interface Repository object does not have a definition kind.
static int | _dk_all The constant that indicates that an Interface Repository object does not have a definition kind.
static int | _dk_Array The constant that indicates that an Interface Repository object does not have a definition kind.
static int | _dk_Attribute The constant that indicates that an Interface Repository object does not have a definition kind.
static int | _dk_Constant The constant that indicates that an Interface Repository object does not have a definition kind.
static int | _dk_Enum The constant that indicates that an Interface Repository object does not have a definition kind.
static int | _dk_Exception The constant that indicates that an Interface Repository object does not have a definition kind.
static int | _dk_Fixed The constant that indicates that an Interface Repository object does not have a definition kind.
static int | _dk_Interface The constant that indicates that an Interface Repository object does not have a definition kind.
static int | _dk_Module The constant that indicates that an Interface Repository object does not have a definition kind.
static int | _dk_Native The constant that indicates that an Interface Repository object does not have a definition kind.
static int | _dk_none The constant that indicates that an Interface Repository object does not have a definition kind.
static int | _dk_Operation The constant that indicates that an Interface Repository object does not have a definition kind.
static int | _dk_Primitive The constant that indicates that an Interface Repository object does not have a definition kind.
static int | _dk_Repository The constant that indicates that an Interface Repository object does not have a definition kind.
static int | _dk_Sequence The constant that indicates that an Interface Repository object does not have a definition kind.
static int | _dk_String The constant that indicates that an Interface Repository object does not have a definition kind.
static int | _dk_Struct The constant that indicates that an Interface Repository object does not have a definition kind.
static int | _dk_Typedef The constant that indicates that an Interface Repository object does not have a definition kind.
static int | _dk_Union The constant that indicates that an Interface Repository object does not have a definition kind.
static int | _dk_Value The constant that indicates that an Interface Repository object does not have a definition kind.
static int | _dk_ValueBox The constant that indicates that an Interface Repository object does not have a definition kind.
static int | _dk_ValueMember The constant that indicates that an Interface Repository object does not have a definition kind.
static int | _dk_Wstring The constant that indicates that an Interface Repository object does not have a definition kind.
static DefinitionKind | dk_AbstractInterface The static instance of DefinitionKind indicating that an Interface Repository object represents an abstract interface.
static DefinitionKind | dk_Alias The static instance of DefinitionKind indicating that an Interface Repository object is an Alias.
static DefinitionKind | dk_all The wildcard DefinitionKind constant, useful in all occasions where any DefinitionKind is appropriate.
static DefinitionKind | dk_Array The static instance of DefinitionKind indicating that an Interface Repository object is an Array.
static DefinitionKind | dk_Attribute The static instance of DefinitionKind indicating that an Interface Repository object is an Attribute.
static DefinitionKind | dk_Constant The static instance of DefinitionKind indicating that an Interface Repository object is a constant.
static DefinitionKind | dk_Enum The static instance of DefinitionKind indicating that an Interface Repository object is an Enum.
static DefinitionKind | dk_Exception The static instance of DefinitionKind indicating that an Interface Repository object is an Exception.
static DefinitionKind | dk_Fixed The static instance of DefinitionKind indicating that an Interface Repository object is a Fixed value.
static DefinitionKind | dk_Interface The static instance of DefinitionKind indicating that an Interface Repository object is an Interface.
static DefinitionKind | dk_Module The static instance of DefinitionKind indicating that an Interface Repository object is a Module.
static DefinitionKind | dk_Native The static instance of DefinitionKind indicating that an Interface Repository object is a Native value.
static DefinitionKind | dk_none The static instance of DefinitionKind indicating that an Interface Repository object has no definition kind.
static DefinitionKind | dk_Operation The static instance of DefinitionKind indicating that an Interface Repository object is an Operation.
static DefinitionKind | dk_Primitive The static instance of DefinitionKind indicating that an Interface Repository object is a Primitive.
static DefinitionKind | dk_Repository The static instance of DefinitionKind indicating that an Interface Repository object is a Repository.
static DefinitionKind | dk_Sequence The static instance of DefinitionKind indicating that an Interface Repository object is a Sequence.
static DefinitionKind | dk_String The static instance of DefinitionKind indicating that an Interface Repository object is a String.
static DefinitionKind | dk_Struct The static instance of DefinitionKind indicating that an Interface Repository object is a Struct.
static DefinitionKind | dk_Typedef The static instance of DefinitionKind indicating that an Interface Repository object is a Typedef.
static DefinitionKind | dk_Union The static instance of DefinitionKind indicating that an Interface Repository object is a Union.
static DefinitionKind | dk_Value The static instance of DefinitionKind indicating that an Interface Repository object is a Value.
static DefinitionKind | dk_ValueBox The static instance of DefinitionKind indicating that an Interface Repository object is a ValueBox.
static DefinitionKind | dk_ValueMember The static instance of DefinitionKind indicating that an Interface Repository object is a ValueMember.
static DefinitionKind | dk_Wstring The static instance of DefinitionKind indicating that an Interface Repository object is a Wstring.
Constructor Summary
protected DefinitionKind(int _value)
Constructs a DefinitionKind object with its _value field initialized with the given value.
Method Summary
static DefinitionKind | from_int(int i) Creates a DefinitionKind instance corresponding to the given code .
int | value() Returns the int constant identifying the type of an IR object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

_dk_none

public static final int _dk_none
The constant that indicates that an Interface Repository object does not have a definition kind.

See Also:
Constant Field Values

_dk_all

public static final int _dk_all
The constant that indicates that an Interface Repository object does not have a definition kind.

See Also:
Constant Field Values

_dk_Attribute

public static final int _dk_Attribute
The constant that indicates that an Interface Repository object does not have a definition kind.

See Also:
Constant Field Values

_dk_Constant

public static final int _dk_Constant
The constant that indicates that an Interface Repository object does not have a definition kind.

See Also:
Constant Field Values

_dk_Exception

public static final int _dk_Exception
The constant that indicates that an Interface Repository object does not have a definition kind.

See Also:
Constant Field Values

_dk_Interface

public static final int _dk_Interface
The constant that indicates that an Interface Repository object does not have a definition kind.

See Also:
Constant Field Values

_dk_Module

public static final int _dk_Module
The constant that indicates that an Interface Repository object does not have a definition kind.

See Also:
Constant Field Values

_dk_Operation

public static final int _dk_Operation
The constant that indicates that an Interface Repository object does not have a definition kind.

See Also:
Constant Field Values

_dk_Typedef

public static final int _dk_Typedef
The constant that indicates that an Interface Repository object does not have a definition kind.

See Also:
Constant Field Values

_dk_Alias

public static final int _dk_Alias
The constant that indicates that an Interface Repository object does not have a definition kind.

See Also:
Constant Field Values

_dk_Struct

public static final int _dk_Struct
The constant that indicates that an Interface Repository object does not have a definition kind.

See Also:
Constant Field Values

_dk_Union

public static final int _dk_Union
The constant that indicates that an Interface Repository object does not have a definition kind.

See Also:
Constant Field Values

_dk_Enum

public static final int _dk_Enum
The constant that indicates that an Interface Repository object does not have a definition kind.

See Also:
Constant Field Values

_dk_Primitive

public static final int _dk_Primitive
The constant that indicates that an Interface Repository object does not have a definition kind.

See Also:
Constant Field Values

_dk_String

public static final int _dk_String
The constant that indicates that an Interface Repository object does not have a definition kind.

See Also:
Constant Field Values

_dk_Sequence

public static final int _dk_Sequence
The constant that indicates that an Interface Repository object does not have a definition kind.

See Also:
Constant Field Values

_dk_Array

public static final int _dk_Array
The constant that indicates that an Interface Repository object does not have a definition kind.

See Also:
Constant Field Values

_dk_Repository

public static final int _dk_Repository
The constant that indicates that an Interface Repository object does not have a definition kind.

See Also:
Constant Field Values

_dk_Wstring

public static final int _dk_Wstring
The constant that indicates that an Interface Repository object does not have a definition kind.

See Also:
Constant Field Values

_dk_Fixed

public static final int _dk_Fixed
The constant that indicates that an Interface Repository object does not have a definition kind.

See Also:
Constant Field Values

_dk_Value

public static final int _dk_Value
The constant that indicates that an Interface Repository object does not have a definition kind.

See Also:
Constant Field Values

_dk_ValueBox

public static final int _dk_ValueBox
The constant that indicates that an Interface Repository object does not have a definition kind.

See Also:
Constant Field Values

_dk_ValueMember

public static final int _dk_ValueMember
The constant that indicates that an Interface Repository object does not have a definition kind.

See Also:
Constant Field Values

_dk_Native

public static final int _dk_Native
The constant that indicates that an Interface Repository object does not have a definition kind.

See Also:
Constant Field Values

_dk_AbstractInterface

public static final int _dk_AbstractInterface
The constant that indicates that an Interface Repository object does not have a definition kind.

See Also:
Constant Field Values

dk_none

public static final DefinitionKind dk_none
The static instance of DefinitionKind indicating that an Interface Repository object has no definition kind.

dk_all

public static final DefinitionKind dk_all
The wildcard DefinitionKind constant, useful in all occasions where any DefinitionKind is appropriate. The Container's contents method makes use of this constant to return all contained definitions of any kind.

dk_Attribute

public static final DefinitionKind dk_Attribute
The static instance of DefinitionKind indicating that an Interface Repository object is an Attribute.

dk_Constant

public static final DefinitionKind dk_Constant
The static instance of DefinitionKind indicating that an Interface Repository object is a constant.

dk_Exception

public static final DefinitionKind dk_Exception
The static instance of DefinitionKind indicating that an Interface Repository object is an Exception.

dk_Interface

public static final DefinitionKind dk_Interface
The static instance of DefinitionKind indicating that an Interface Repository object is an Interface.

dk_Module

public static final DefinitionKind dk_Module
The static instance of DefinitionKind indicating that an Interface Repository object is a Module.

dk_Operation

public static final DefinitionKind dk_Operation
The static instance of DefinitionKind indicating that an Interface Repository object is an Operation.

dk_Typedef

public static final DefinitionKind dk_Typedef
The static instance of DefinitionKind indicating that an Interface Repository object is a Typedef.

dk_Alias

public static final DefinitionKind dk_Alias
The static instance of DefinitionKind indicating that an Interface Repository object is an Alias.

dk_Struct

public static final DefinitionKind dk_Struct
The static instance of DefinitionKind indicating that an Interface Repository object is a Struct.

dk_Union

public static final DefinitionKind dk_Union
The static instance of DefinitionKind indicating that an Interface Repository object is a Union.

dk_Enum

public static final DefinitionKind dk_Enum
The static instance of DefinitionKind indicating that an Interface Repository object is an Enum.

dk_Primitive

public static final DefinitionKind dk_Primitive
The static instance of DefinitionKind indicating that an Interface Repository object is a Primitive.

dk_String

public static final DefinitionKind dk_String
The static instance of DefinitionKind indicating that an Interface Repository object is a String.

dk_Sequence

public static final DefinitionKind dk_Sequence
The static instance of DefinitionKind indicating that an Interface Repository object is a Sequence.

dk_Array

public static final DefinitionKind dk_Array
The static instance of DefinitionKind indicating that an Interface Repository object is an Array.

dk_Repository

public static final DefinitionKind dk_Repository
The static instance of DefinitionKind indicating that an Interface Repository object is a Repository.

dk_Wstring

public static final DefinitionKind dk_Wstring
The static instance of DefinitionKind indicating that an Interface Repository object is a Wstring.

dk_Fixed

public static final DefinitionKind dk_Fixed
The static instance of DefinitionKind indicating that an Interface Repository object is a Fixed value.

dk_Value

public static final DefinitionKind dk_Value
The static instance of DefinitionKind indicating that an Interface Repository object is a Value.

dk_ValueBox

public static final DefinitionKind dk_ValueBox
The static instance of DefinitionKind indicating that an Interface Repository object is a ValueBox.

dk_ValueMember

public static final DefinitionKind dk_ValueMember
The static instance of DefinitionKind indicating that an Interface Repository object is a ValueMember.

dk_Native

public static final DefinitionKind dk_Native
The static instance of DefinitionKind indicating that an Interface Repository object is a Native value.

dk_AbstractInterface

public static final DefinitionKind dk_AbstractInterface
The static instance of DefinitionKind indicating that an Interface Repository object represents an abstract interface.

Constructor Detail

DefinitionKind

protected DefinitionKind(int _value)
Constructs a DefinitionKind object with its _value field initialized with the given value.

Parameters:
_value - one of the int constants defined in the class DefinitionKind
Method Detail

value

public int value()
Returns the int constant identifying the type of an IR object.

Returns:
the int constant from the class DefinitionKind that is the value of this DefinitionKind instance

from_int

public static DefinitionKind from_int(int i)
Creates a DefinitionKind instance corresponding to the given code .

Parameters:
i - one of the int constants from the class DefinitionKind
Returns:
the DefinitionKind instance corresponding to the given code
Throws:
BAD_PARAM - if the given parameter is not one of the int constants from the class DefinitionKind
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DefinitionKindHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class DefinitionKindHelper

java.lang.Object
    extended by org.omg.CORBA.DefinitionKindHelper
public abstract class DefinitionKindHelper
extends Object

The Helper for DefinitionKind. For more information on Helper files, see "Generated Files: Helper Files".

org/omg/CORBA/DefinitionKindHelper.java Generated by the IDL-to-Java compiler (portable), version "3.0" from ir.idl 03 June 1999 11:33:43 o'clock GMT+00:00

Constructor Summary
DefinitionKindHelper()
Method Summary
static DefinitionKind | extract(Any a)
static String | id()
static void | insert(Any a, DefinitionKind that)
static DefinitionKind | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, DefinitionKind value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DefinitionKindHelper

public DefinitionKindHelper()
Method Detail

insert

public static void insert(Any a,
                          DefinitionKind that)

extract

public static DefinitionKind extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static DefinitionKind read(InputStream istream)

write

public static void write(OutputStream ostream,
                         DefinitionKind value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DomainManager (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Interface DomainManager

All Superinterfaces:
DomainManagerOperations, IDLEntity, Object, Serializable
public interface DomainManager
extends DomainManagerOperations, Object, IDLEntity

Provides mechanisms for establishing and navigating relationships to superior and subordinate domains, as well as for creating and accessing policies. The DomainManager has associated with it the policy objects for a particular domain. The domain manager also records the membership of the domain and provides the means to add and remove members. The domain manager is itself a member of a domain, possibly the domain it manages. The domain manager provides mechanisms for establishing and navigating relationships to superior and subordinate domains and creating and accessing policies.

Methods inherited from interface org.omg.CORBA.DomainManagerOperations
get_domain_policy
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DomainManagerOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Interface DomainManagerOperations

All Known Subinterfaces:
DomainManager
public interface DomainManagerOperations

Provides the DomainManager with the means to access policies.

The DomainManager has associated with it the policy objects for a particular domain. The domain manager also records the membership of the domain and provides the means to add and remove members. The domain manager is itself a member of a domain, possibly the domain it manages. The domain manager provides mechanisms for establishing and navigating relationships to superior and subordinate domains and creating and accessing policies.

Method Summary
 Policy get_domain_policy(int policy_type)
This returns the policy of the specified type for objects in this domain.

Method Detail

get_domain_policy

public Policy get_domain_policy(int policy_type)
This returns the policy of the specified type for objects in this domain. The types of policies available are domain specific. See the CORBA specification for a list of standard ORB policies.

Parameters:
policy_type - Type of policy to request
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DoubleHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class DoubleHolder

java.lang.Object
    extended by org.omg.CORBA.DoubleHolder
All Implemented Interfaces:
Streamable
public final class DoubleHolder
extends Object
implements Streamable

The Holder for Double. For more information on Holder files, see "Generated Files: Holder Files".

A Holder class for a double that is used to store "out" and "inout" parameters in IDL methods. If an IDL method signature has an IDL double as an "out" or "inout" parameter, the programmer must pass an instance of DoubleHolder as the corresponding parameter in the method invocation; for "inout" parameters, the programmer must also fill the "in" value to be sent to the server. Before the method invocation returns, the ORB will fill in the value corresponding to the "out" value returned from the server.

If myDoubleHolder is an instance of DoubleHolder, the value stored in its value field can be accessed with myDoubleHolder.value.

Since:
JDK1.2

Field Summary
 double value
The double value held by this DoubleHolder object.
Constructor Summary
DoubleHolder()
Constructs a new DoubleHolder object with its value field initialized to 0.0.
DoubleHolder(double initial)
Constructs a new DoubleHolder object for the given double.
Method Summary
void | _read(InputStream input) Read a double value from the input stream and store it in the value member.
TypeCode | _type() Return the TypeCode of this holder object.
void | _write(OutputStream output) Write the double value stored in this holder to an OutputStream.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public double value
The double value held by this DoubleHolder object.

Constructor Detail

DoubleHolder

public DoubleHolder()
Constructs a new DoubleHolder object with its value field initialized to 0.0.

DoubleHolder

public DoubleHolder(double initial)
Constructs a new DoubleHolder object for the given double.

Parameters:
initial - the double with which to initialize the value field of the new DoubleHolder object
Method Detail

_read

public void _read(InputStream input)
Read a double value from the input stream and store it in the value member.

Specified by:
_read in interface Streamable
Parameters:
input - the InputStream to read from.

_write

public void _write(OutputStream output)
Write the double value stored in this holder to an OutputStream.

Specified by:
_write in interface Streamable
Parameters:
output - the OutputStream to write into.

_type

public TypeCode _type()
Return the TypeCode of this holder object.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DoubleSeqHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class DoubleSeqHelper

java.lang.Object
    extended by org.omg.CORBA.DoubleSeqHelper
public abstract class DoubleSeqHelper
extends Object

The Helper for DoubleSeq. For more information on Helper files, see "Generated Files: Helper Files".

org/omg/CORBA/DoubleSeqHelper.java Generated by the IDL-to-Java compiler (portable), version "3.0" from streams.idl 13 May 1999 22:41:37 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

Constructor Summary
DoubleSeqHelper()
Method Summary
static double[] | extract(Any a)
static String | id()
static void | insert(Any a, double[] that)
static double[] | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, double[] value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DoubleSeqHelper

public DoubleSeqHelper()
Method Detail

insert

public static void insert(Any a,
                          double[] that)

extract

public static double[] extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static double[] read(InputStream istream)

write

public static void write(OutputStream ostream,
                         double[] value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DoubleSeqHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class DoubleSeqHolder

java.lang.Object
    extended by org.omg.CORBA.DoubleSeqHolder
All Implemented Interfaces:
Streamable
public final class DoubleSeqHolder
extends Object
implements Streamable

The Holder for DoubleSeq. For more information on Holder files, see "Generated Files: Holder Files".

org/omg/CORBA/DoubleSeqHolder.java Generated by the IDL-to-Java compiler (portable), version "3.0" from streams.idl 13 May 1999 22:41:37 o'clock GMT+00:00

Field Summary
 double[] value
Constructor Summary
DoubleSeqHolder()
DoubleSeqHolder(double[] initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public double[] value
Constructor Detail

DoubleSeqHolder

public DoubleSeqHolder()

DoubleSeqHolder

public DoubleSeqHolder(double[] initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynamicImplementation (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class DynamicImplementation

java.lang.Object
    extended by org.omg.CORBA.portable.ObjectImpl
        extended by org.omg.CORBA.DynamicImplementation
All Implemented Interfaces:
Object
Direct Known Subclasses:
_BindingIteratorImplBase, _NamingContextImplBase
Deprecated. org.omg.CORBA.DynamicImplementation

public class DynamicImplementation
extends ObjectImpl

Constructor Summary
DynamicImplementation()
Deprecated.
Method Summary
String[] | _ids() Deprecated. Retrieves a string array containing the repository identifiers supported by this ObjectImpl object.
void | invoke(ServerRequest request) Deprecated. Deprecated by Portable Object Adapter
Methods inherited from class org.omg.CORBA.portable.ObjectImpl
_create_request, _create_request, _duplicate, _get_delegate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _invoke, _is_a, _is_equivalent, _is_local, _non_existent, _orb, _release, _releaseReply, _request, _request, _servant_postinvoke, _servant_preinvoke, _set_delegate, _set_policy_override, equals, hashCode, toString
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait

Constructor Detail

DynamicImplementation

public DynamicImplementation()
Deprecated.
Method Detail

invoke

public void invoke(ServerRequest request)
Deprecated. Deprecated by Portable Object Adapter

_ids

public String[] _ids()
Deprecated.
Description copied from class: ObjectImpl
Retrieves a string array containing the repository identifiers supported by this ObjectImpl object. For example, for a stub, this method returns information about all the interfaces supported by the stub.

Specified by:
_ids in class ObjectImpl
Returns:
the array of all repository identifiers supported by this ObjectImpl instance
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynAny (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Interface DynAny

All Superinterfaces:
Object
All Known Subinterfaces:
DynArray, DynEnum, DynFixed, DynSequence, DynStruct, DynUnion, DynValue
public interface DynAny
extends Object

Enables org.omg.CORBA.Any values to be dynamically interpreted (traversed) and constructed. A DynAny object is associated with a data value which may correspond to a copy of the value inserted into an Any. The DynAny APIs enable traversal of the data value associated with an Any at runtime and extraction of the primitive constituents of the data value.

Method Summary
void | assign(DynAny dyn_any) Copy the contents from one Dynamic Any into another.
DynAny | copy() Clones this DynAny object.
DynAny | current_component() Returns a DynAny object reference that can be used to get/set the value of the component currently accessed.
void | destroy() Destroys this DynAny object and frees any resources used to represent the data value associated with it.
void | from_any(Any value) Make a DynAny object from an Any object.
Any | get_any() Retrieves the org.omg.CORBA.Any contained in this DynAny object.
boolean | get_boolean() Retrieves the boolean contained in this DynAny object.
char | get_char() Retrieves the char contained in this DynAny object.
double | get_double() Retrieves the double contained in this DynAny object.
float | get_float() Retrieves the float contained in this DynAny object.
int | get_long() Retrieves the int contained in this DynAny object.
long | get_longlong() Retrieves the long contained in this DynAny object.
byte | get_octet() Retrieves the byte contained in this DynAny object.
Object | get_reference() Retrieves the org.omg.CORBA.Other contained in this DynAny object.
short | get_short() Retrieves the short contained in this DynAny object.
String | get_string() Retrieves the String contained in this DynAny object.
TypeCode | get_typecode() Retrieves the org.omg.CORBA.TypeCode contained in this DynAny object.
int | get_ulong() Retrieves the int contained in this DynAny object.
long | get_ulonglong() Retrieves the long contained in this DynAny object.
short | get_ushort() Retrieves the short contained in this DynAny object.
Serializable | get_val() Retrieves the java.io.Serializable object contained in this DynAny object.
char | get_wchar() Retrieves the char contained in this DynAny object.
String | get_wstring() Retrieves the String contained in this DynAny object.
void | insert_any(Any value) Inserts the given org.omg.CORBA.Any object as the value for this DynAny object.
void | insert_boolean(boolean value) Inserts the given boolean as the value for this DynAny object.
void | insert_char(char value) Inserts the given char as the value for this DynAny object.
void | insert_double(double value) Inserts the given double as the value for this DynAny object.
void | insert_float(float value) Inserts the given float as the value for this DynAny object.
void | insert_long(int value) Inserts the given int as the value for this DynAny object.
void | insert_longlong(long value) Inserts the given long as the value for this DynAny object.
void | insert_octet(byte value) Inserts the given byte as the value for this DynAny object.
void | insert_reference(Object value) Inserts the given org.omg.CORBA.Object as the value for this DynAny object.
void | insert_short(short value) Inserts the given short as the value for this DynAny object.
void | insert_string(String value) Inserts the given String object as the value for this DynAny object.
void | insert_typecode(TypeCode value) Inserts the given org.omg.CORBA.TypeCode as the value for this DynAny object.
void | insert_ulong(int value) Inserts the given int as the value for this DynAny object.
void | insert_ulonglong(long value) Inserts the given long as the value for this DynAny object.
void | insert_ushort(short value) Inserts the given short as the value for this DynAny object.
void | insert_val(Serializable value) Inserts the given java.io.Serializable object as the value for this DynAny object.
void | insert_wchar(char value) Inserts the given char as the value for this DynAny object.
void | insert_wstring(String value) Inserts the given String as the value for this DynAny object.
boolean | next() Moves to the next component of this DynAny object.
void | rewind() Moves the internal pointer to the first component.
boolean | seek(int index) Moves the internal pointer to the given index.
Any | to_any() Convert a DynAny object to an Any object.
TypeCode | type() Returns the TypeCode of the object inserted into this DynAny.
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Method Detail

type

public TypeCode type()
Returns the TypeCode of the object inserted into this DynAny.

Returns:
the TypeCode object.

assign

public void assign(DynAny dyn_any)
            throws Invalid
Copy the contents from one Dynamic Any into another.

Parameters:
dyn_any - the DynAny object whose contents are assigned to this DynAny.
Throws:
Invalid - if the source DynAny is invalid

from_any

public void from_any(Any value)
              throws Invalid
Make a DynAny object from an Any object.

Parameters:
value - the Any object.
Throws:
Invalid - if the source Any object is empty or bad

to_any

public Any to_any()
           throws Invalid
Convert a DynAny object to an Any object.

Returns:
the Any object.
Throws:
Invalid - if this DynAny is empty or bad. created or does not contain a meaningful value

destroy

public void destroy()
Destroys this DynAny object and frees any resources used to represent the data value associated with it. This method also destroys all DynAny objects obtained from it.

Destruction of DynAny objects should be handled with care, taking into account issues dealing with the representation of data values associated with DynAny objects. A programmer who wants to destroy a DynAny object but still be able to manipulate some component of the data value associated with it, should first create a DynAny object for the component and then make a copy of the created DynAny object.

copy

public DynAny copy()
Clones this DynAny object.

Returns:
a copy of this DynAny object

insert_boolean

public void insert_boolean(boolean value)
                    throws InvalidValue
Inserts the given boolean as the value for this DynAny object.

If this method is called on a constructed DynAny object, it initializes the next component of the constructed data value associated with this DynAny object.

Parameters:
value - the boolean to insert into this DynAny object
Throws:
InvalidValue - if the value inserted is not consistent with the type of the accessed component in this DynAny object

insert_octet

public void insert_octet(byte value)
                  throws InvalidValue
Inserts the given byte as the value for this DynAny object.

If this method is called on a constructed DynAny object, it initializes the next component of the constructed data value associated with this DynAny object.

Parameters:
value - the byte to insert into this DynAny object
Throws:
InvalidValue - if the value inserted is not consistent with the type of the accessed component in this DynAny object

insert_char

public void insert_char(char value)
                 throws InvalidValue
Inserts the given char as the value for this DynAny object.

If this method is called on a constructed DynAny object, it initializes the next component of the constructed data value associated with this DynAny object.

Parameters:
value - the char to insert into this DynAny object
Throws:
InvalidValue - if the value inserted is not consistent with the type of the accessed component in this DynAny object

insert_short

public void insert_short(short value)
                  throws InvalidValue
Inserts the given short as the value for this DynAny object.

If this method is called on a constructed DynAny object, it initializes the next component of the constructed data value associated with this DynAny object.

Parameters:
value - the short to insert into this DynAny object
Throws:
InvalidValue - if the value inserted is not consistent with the type of the accessed component in this DynAny object

insert_ushort

public void insert_ushort(short value)
                   throws InvalidValue
Inserts the given short as the value for this DynAny object.

If this method is called on a constructed DynAny object, it initializes the next component of the constructed data value associated with this DynAny object.

Parameters:
value - the short to insert into this DynAny object
Throws:
InvalidValue - if the value inserted is not consistent with the type of the accessed component in this DynAny object

insert_long

public void insert_long(int value)
                 throws InvalidValue
Inserts the given int as the value for this DynAny object.

If this method is called on a constructed DynAny object, it initializes the next component of the constructed data value associated with this DynAny object.

Parameters:
value - the int to insert into this DynAny object
Throws:
InvalidValue - if the value inserted is not consistent with the type of the accessed component in this DynAny object

insert_ulong

public void insert_ulong(int value)
                  throws InvalidValue
Inserts the given int as the value for this DynAny object.

If this method is called on a constructed DynAny object, it initializes the next component of the constructed data value associated with this DynAny object.

Parameters:
value - the int to insert into this DynAny object
Throws:
InvalidValue - if the value inserted is not consistent with the type of the accessed component in this DynAny object

insert_float

public void insert_float(float value)
                  throws InvalidValue
Inserts the given float as the value for this DynAny object.

If this method is called on a constructed DynAny object, it initializes the next component of the constructed data value associated with this DynAny object.

Parameters:
value - the float to insert into this DynAny object
Throws:
InvalidValue - if the value inserted is not consistent with the type of the accessed component in this DynAny object

insert_double

public void insert_double(double value)
                   throws InvalidValue
Inserts the given double as the value for this DynAny object.

If this method is called on a constructed DynAny object, it initializes the next component of the constructed data value associated with this DynAny object.

Parameters:
value - the double to insert into this DynAny object
Throws:
InvalidValue - if the value inserted is not consistent with the type of the accessed component in this DynAny object

insert_string

public void insert_string(String value)
                   throws InvalidValue
Inserts the given String object as the value for this DynAny object.

If this method is called on a constructed DynAny object, it initializes the next component of the constructed data value associated with this DynAny object.

Parameters:
value - the String to insert into this DynAny object
Throws:
InvalidValue - if the value inserted is not consistent with the type of the accessed component in this DynAny object

insert_reference

public void insert_reference(Object value)
                      throws InvalidValue
Inserts the given org.omg.CORBA.Object as the value for this DynAny object.

If this method is called on a constructed DynAny object, it initializes the next component of the constructed data value associated with this DynAny object.

Parameters:
value - the org.omg.CORBA.Object to insert into this DynAny object
Throws:
InvalidValue - if the value inserted is not consistent with the type of the accessed component in this DynAny object

insert_typecode

public void insert_typecode(TypeCode value)
                     throws InvalidValue
Inserts the given org.omg.CORBA.TypeCode as the value for this DynAny object.

If this method is called on a constructed DynAny object, it initializes the next component of the constructed data value associated with this DynAny object.

Parameters:
value - the org.omg.CORBA.TypeCode to insert into this DynAny object
Throws:
InvalidValue - if the value inserted is not consistent with the type of the accessed component in this DynAny object

insert_longlong

public void insert_longlong(long value)
                     throws InvalidValue
Inserts the given long as the value for this DynAny object.

If this method is called on a constructed DynAny object, it initializes the next component of the constructed data value associated with this DynAny object.

Parameters:
value - the long to insert into this DynAny object
Throws:
InvalidValue - if the value inserted is not consistent with the type of the accessed component in this DynAny object

insert_ulonglong

public void insert_ulonglong(long value)
                      throws InvalidValue
Inserts the given long as the value for this DynAny object.

If this method is called on a constructed DynAny object, it initializes the next component of the constructed data value associated with this DynAny object.

Parameters:
value - the long to insert into this DynAny object
Throws:
InvalidValue - if the value inserted is not consistent with the type of the accessed component in this DynAny object

insert_wchar

public void insert_wchar(char value)
                  throws InvalidValue
Inserts the given char as the value for this DynAny object.

If this method is called on a constructed DynAny object, it initializes the next component of the constructed data value associated with this DynAny object.

Parameters:
value - the char to insert into this DynAny object
Throws:
InvalidValue - if the value inserted is not consistent with the type of the accessed component in this DynAny object

insert_wstring

public void insert_wstring(String value)
                    throws InvalidValue
Inserts the given String as the value for this DynAny object.

If this method is called on a constructed DynAny object, it initializes the next component of the constructed data value associated with this DynAny object.

Parameters:
value - the String to insert into this DynAny object
Throws:
InvalidValue - if the value inserted is not consistent with the type of the accessed component in this DynAny object

insert_any

public void insert_any(Any value)
                throws InvalidValue
Inserts the given org.omg.CORBA.Any object as the value for this DynAny object.

If this method is called on a constructed DynAny object, it initializes the next component of the constructed data value associated with this DynAny object.

Parameters:
value - the org.omg.CORBA.Any object to insert into this DynAny object
Throws:
InvalidValue - if the value inserted is not consistent with the type of the accessed component in this DynAny object

insert_val

public void insert_val(Serializable value)
                throws InvalidValue
Inserts the given java.io.Serializable object as the value for this DynAny object.

If this method is called on a constructed DynAny object, it initializes the next component of the constructed data value associated with this DynAny object.

Parameters:
value - the java.io.Serializable object to insert into this DynAny object
Throws:
InvalidValue - if the value inserted is not consistent with the type of the accessed component in this DynAny object

get_val

public Serializable get_val()
                     throws TypeMismatch
Retrieves the java.io.Serializable object contained in this DynAny object.

Returns:
the java.io.Serializable object that is the value for this DynAny object
Throws:
TypeMismatch - if the type code of the accessed component in this DynAny object is not equivalent to the type code for a java.io.Serializable object

get_boolean

public boolean get_boolean()
                    throws TypeMismatch
Retrieves the boolean contained in this DynAny object.

Returns:
the boolean that is the value for this DynAny object
Throws:
TypeMismatch - if the type code of the accessed component in this DynAny object is not equivalent to the type code for a boolean

get_octet

public byte get_octet()
               throws TypeMismatch
Retrieves the byte contained in this DynAny object.

Returns:
the byte that is the value for this DynAny object
Throws:
TypeMismatch - if the type code of the accessed component in this DynAny object is not equivalent to the type code for a byte

get_char

public char get_char()
              throws TypeMismatch
Retrieves the char contained in this DynAny object.

Returns:
the char that is the value for this DynAny object
Throws:
TypeMismatch - if the type code of the accessed component in this DynAny object is not equivalent to the type code for a char

get_short

public short get_short()
                throws TypeMismatch
Retrieves the short contained in this DynAny object.

Returns:
the short that is the value for this DynAny object
Throws:
TypeMismatch - if the type code of the accessed component in this DynAny object is not equivalent to the type code for a short

get_ushort

public short get_ushort()
                 throws TypeMismatch
Retrieves the short contained in this DynAny object.

Returns:
the short that is the value for this DynAny object
Throws:
TypeMismatch - if the type code of the accessed component in this DynAny object is not equivalent to the type code for a short

get_long

public int get_long()
             throws TypeMismatch
Retrieves the int contained in this DynAny object.

Returns:
the int that is the value for this DynAny object
Throws:
TypeMismatch - if the type code of the accessed component in this DynAny object is not equivalent to the type code for a int

get_ulong

public int get_ulong()
              throws TypeMismatch
Retrieves the int contained in this DynAny object.

Returns:
the int that is the value for this DynAny object
Throws:
TypeMismatch - if the type code of the accessed component in this DynAny object is not equivalent to the type code for a int

get_float

public float get_float()
                throws TypeMismatch
Retrieves the float contained in this DynAny object.

Returns:
the float that is the value for this DynAny object
Throws:
TypeMismatch - if the type code of the accessed component in this DynAny object is not equivalent to the type code for a float

get_double

public double get_double()
                  throws TypeMismatch
Retrieves the double contained in this DynAny object.

Returns:
the double that is the value for this DynAny object
Throws:
TypeMismatch - if the type code of the accessed component in this DynAny object is not equivalent to the type code for a double

get_string

public String get_string()
                  throws TypeMismatch
Retrieves the String contained in this DynAny object.

Returns:
the String that is the value for this DynAny object
Throws:
TypeMismatch - if the type code of the accessed component in this DynAny object is not equivalent to the type code for a String

get_reference

public Object get_reference()
                     throws TypeMismatch
Retrieves the org.omg.CORBA.Other contained in this DynAny object.

Returns:
the org.omg.CORBA.Other that is the value for this DynAny object
Throws:
TypeMismatch - if the type code of the accessed component in this DynAny object is not equivalent to the type code for an org.omg.CORBA.Other

get_typecode

public TypeCode get_typecode()
                      throws TypeMismatch
Retrieves the org.omg.CORBA.TypeCode contained in this DynAny object.

Returns:
the org.omg.CORBA.TypeCode that is the value for this DynAny object
Throws:
TypeMismatch - if the type code of the accessed component in this DynAny object is not equivalent to the type code for a org.omg.CORBA.TypeCode

get_longlong

public long get_longlong()
                  throws TypeMismatch
Retrieves the long contained in this DynAny object.

Returns:
the long that is the value for this DynAny object
Throws:
TypeMismatch - if the type code of the accessed component in this DynAny object is not equivalent to the type code for a long

get_ulonglong

public long get_ulonglong()
                   throws TypeMismatch
Retrieves the long contained in this DynAny object.

Returns:
the long that is the value for this DynAny object
Throws:
TypeMismatch - if the type code of the accessed component in this DynAny object is not equivalent to the type code for a long

get_wchar

public char get_wchar()
               throws TypeMismatch
Retrieves the char contained in this DynAny object.

Returns:
the char that is the value for this DynAny object
Throws:
TypeMismatch - if the type code of the accessed component in this DynAny object is not equivalent to the type code for a char

get_wstring

public String get_wstring()
                   throws TypeMismatch
Retrieves the String contained in this DynAny object.

Returns:
the String that is the value for this DynAny object
Throws:
TypeMismatch - if the type code of the accessed component in this DynAny object is not equivalent to the type code for a String

get_any

public Any get_any()
            throws TypeMismatch
Retrieves the org.omg.CORBA.Any contained in this DynAny object.

Returns:
the org.omg.CORBA.Any that is the value for this DynAny object
Throws:
TypeMismatch - if the type code of the accessed component in this DynAny object is not equivalent to the type code for an org.omg.CORBA.Any

current_component

public DynAny current_component()
Returns a DynAny object reference that can be used to get/set the value of the component currently accessed. The appropriate insert method can be called on the resulting DynAny object to initialize the component. The appropriate get method can be called on the resulting DynAny object to extract the value of the component.

Returns:
a DynAny object reference that can be used to retrieve or set the value of the component currently accessed

next

public boolean next()
Moves to the next component of this DynAny object. This method is used for iterating through the components of a constructed type, effectively moving a pointer from one component to the next. The pointer starts out on the first component when a DynAny object is created.

Returns:
true if the pointer points to a component; false if there are no more components or this DynAny is associated with a basic type rather than a constructed type

seek

public boolean seek(int index)
Moves the internal pointer to the given index. Logically, this method sets a new offset for this pointer.

Parameters:
index - an int indicating the position to which the pointer should move. The first position is 0.
Returns:
true if the pointer points to a component; false if there is no component at the designated index. If this DynAny object is associated with a basic type, this method returns false for any index other than 0.

rewind

public void rewind()
Moves the internal pointer to the first component.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynArray (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Interface DynArray

All Superinterfaces:
DynAny, Object
public interface DynArray
extends Object, DynAny

Represents a DynAny object associated with an array.

Method Summary
Any[] | get_elements() Returns the value of all the elements of this array.
void | set_elements(Any[] value) Sets the value of this DynArray object to the given array.
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override
Methods inherited from interface org.omg.CORBA.DynAny
assign, copy, current_component, destroy, from_any, get_any, get_boolean, get_char, get_double, get_float, get_long, get_longlong, get_octet, get_reference, get_short, get_string, get_typecode, get_ulong, get_ulonglong, get_ushort, get_val, get_wchar, get_wstring, insert_any, insert_boolean, insert_char, insert_double, insert_float, insert_long, insert_longlong, insert_octet, insert_reference, insert_short, insert_string, insert_typecode, insert_ulong, insert_ulonglong, insert_ushort, insert_val, insert_wchar, insert_wstring, next, rewind, seek, to_any, type

Method Detail

get_elements

public Any[] get_elements()
Returns the value of all the elements of this array.

Returns:
the array of Any objects that is the value for this DynArray object
See Also:
set_elements(org.omg.CORBA.Any[])

set_elements

public void set_elements(Any[] value)
                  throws InvalidSeq
Sets the value of this DynArray object to the given array.

Parameters:
value - the array of Any objects
Throws:
InvalidSeq - if the sequence is bad
See Also:
get_elements()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynEnum (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Interface DynEnum

All Superinterfaces:
DynAny, Object
public interface DynEnum
extends Object, DynAny

Represents a DynAny object associated with an IDL enum.

Method Summary
String | value_as_string() Return the value of the IDL enum stored in this DynEnum as a string.
void | value_as_string(String arg) Set a particular enum in this DynEnum.
int | value_as_ulong() Return the value of the IDL enum as a Java int.
void | value_as_ulong(int arg) Set the value of the IDL enum.
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override
Methods inherited from interface org.omg.CORBA.DynAny
assign, copy, current_component, destroy, from_any, get_any, get_boolean, get_char, get_double, get_float, get_long, get_longlong, get_octet, get_reference, get_short, get_string, get_typecode, get_ulong, get_ulonglong, get_ushort, get_val, get_wchar, get_wstring, insert_any, insert_boolean, insert_char, insert_double, insert_float, insert_long, insert_longlong, insert_octet, insert_reference, insert_short, insert_string, insert_typecode, insert_ulong, insert_ulonglong, insert_ushort, insert_val, insert_wchar, insert_wstring, next, rewind, seek, to_any, type

Method Detail

value_as_string

public String value_as_string()
Return the value of the IDL enum stored in this DynEnum as a string.

Returns:
the stringified value.

value_as_string

public void value_as_string(String arg)
Set a particular enum in this DynEnum.

Parameters:
arg - the string corresponding to the value.

value_as_ulong

public int value_as_ulong()
Return the value of the IDL enum as a Java int.

Returns:
the integer value.

value_as_ulong

public void value_as_ulong(int arg)
Set the value of the IDL enum.

Parameters:
arg - the int value of the enum.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynFixed (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Interface DynFixed

All Superinterfaces:
DynAny, Object
public interface DynFixed
extends Object, DynAny

Represents a DynAny object that is associated with an IDL fixed type.

Method Summary
byte[] | get_value() Returns the value of the fixed type represented in this DynFixed object.
void | set_value(byte[] val) Sets the given fixed type instance as the value for this DynFixed object.
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override
Methods inherited from interface org.omg.CORBA.DynAny
assign, copy, current_component, destroy, from_any, get_any, get_boolean, get_char, get_double, get_float, get_long, get_longlong, get_octet, get_reference, get_short, get_string, get_typecode, get_ulong, get_ulonglong, get_ushort, get_val, get_wchar, get_wstring, insert_any, insert_boolean, insert_char, insert_double, insert_float, insert_long, insert_longlong, insert_octet, insert_reference, insert_short, insert_string, insert_typecode, insert_ulong, insert_ulonglong, insert_ushort, insert_val, insert_wchar, insert_wstring, next, rewind, seek, to_any, type

Method Detail

get_value

public byte[] get_value()
Returns the value of the fixed type represented in this DynFixed object.

Returns:
the value as a byte array
See Also:
set_value(byte[])

set_value

public void set_value(byte[] val)
               throws InvalidValue
Sets the given fixed type instance as the value for this DynFixed object.

Parameters:
val - the value of the fixed type as a byte array
Throws:
InvalidValue - if the given argument is bad
See Also:
get_value()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynSequence (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Interface DynSequence

All Superinterfaces:
DynAny, Object
public interface DynSequence
extends Object, DynAny

The representation of a DynAny object that is associated with an IDL sequence.

Method Summary
Any[] | get_elements() Returns the value of every element in this sequence.
int | length() Returns the length of the sequence represented by this DynFixed object.
void | length(int arg) Sets the length of the sequence represented by this DynFixed object to the given argument.
void | set_elements(Any[] value) Sets the values of all elements in this sequence with the given array.
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override
Methods inherited from interface org.omg.CORBA.DynAny
assign, copy, current_component, destroy, from_any, get_any, get_boolean, get_char, get_double, get_float, get_long, get_longlong, get_octet, get_reference, get_short, get_string, get_typecode, get_ulong, get_ulonglong, get_ushort, get_val, get_wchar, get_wstring, insert_any, insert_boolean, insert_char, insert_double, insert_float, insert_long, insert_longlong, insert_octet, insert_reference, insert_short, insert_string, insert_typecode, insert_ulong, insert_ulonglong, insert_ushort, insert_val, insert_wchar, insert_wstring, next, rewind, seek, to_any, type

Method Detail

length

public int length()
Returns the length of the sequence represented by this DynFixed object.

Returns:
the length of the sequence

length

public void length(int arg)
Sets the length of the sequence represented by this DynFixed object to the given argument.

Parameters:
arg - the length of the sequence

get_elements

public Any[] get_elements()
Returns the value of every element in this sequence.

Returns:
an array of Any objects containing the values in the sequence
See Also:
set_elements(org.omg.CORBA.Any[])

set_elements

public void set_elements(Any[] value)
                  throws InvalidSeq
Sets the values of all elements in this sequence with the given array.

Parameters:
value - the array of Any objects to be set
Throws:
InvalidSeq - if the array of values is bad
See Also:
get_elements()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynStruct (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Interface DynStruct

All Superinterfaces:
DynAny, Object
public interface DynStruct
extends Object, DynAny

The representation of a DynAny object that is associated with an IDL struct.

Method Summary
TCKind | current_member_kind() Returns the TCKind object that describes the kind of the current member.
String | current_member_name() During a traversal, returns the name of the current member.
NameValuePair[] | get_members() Returns an array containing all the members of the stored struct.
void | set_members(NameValuePair[] value) Set the members of the struct.
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override
Methods inherited from interface org.omg.CORBA.DynAny
assign, copy, current_component, destroy, from_any, get_any, get_boolean, get_char, get_double, get_float, get_long, get_longlong, get_octet, get_reference, get_short, get_string, get_typecode, get_ulong, get_ulonglong, get_ushort, get_val, get_wchar, get_wstring, insert_any, insert_boolean, insert_char, insert_double, insert_float, insert_long, insert_longlong, insert_octet, insert_reference, insert_short, insert_string, insert_typecode, insert_ulong, insert_ulonglong, insert_ushort, insert_val, insert_wchar, insert_wstring, next, rewind, seek, to_any, type

Method Detail

current_member_name

public String current_member_name()
During a traversal, returns the name of the current member.

Returns:
the string name of the current member

current_member_kind

public TCKind current_member_kind()
Returns the TCKind object that describes the kind of the current member.

Returns:
the TCKind object that describes the current member

get_members

public NameValuePair[] get_members()
Returns an array containing all the members of the stored struct.

Returns:
the array of name-value pairs
See Also:
set_members(org.omg.CORBA.NameValuePair[])

set_members

public void set_members(NameValuePair[] value)
                 throws InvalidSeq
Set the members of the struct.

Parameters:
value - the array of name-value pairs.
Throws:
InvalidSeq - if the given argument is invalid
See Also:
get_members()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynUnion (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Interface DynUnion

All Superinterfaces:
DynAny, Object
public interface DynUnion
extends Object, DynAny

The DynUnion interface represents a DynAny object that is associated with an IDL union. Union values can be traversed using the operations defined in DynAny. The first component in the union corresponds to the discriminator; the second corresponds to the actual value of the union. Calling the method next() twice allows you to access both components.

Method Summary
TCKind | discriminator_kind() Returns the TCKind object associated with the discriminator of this union.
DynAny | discriminator() Returns a DynAny object reference that must be narrowed to the type of the discriminator in order to insert/get the discriminator value.
TCKind | member_kind() Returns the TCKind associated with the member of this union.
String | member_name() Allows for the inspection of the name of this union member without checking the value of the discriminator.
void | member_name(String arg) Allows for the assignment of the name of this union member.
DynAny | member() Returns a DynAny object reference that is used in order to insert/get a member of this union.
boolean | set_as_default() Determines whether the discriminator associated with this union has been assigned a valid default value.
void | set_as_default(boolean arg) Determines whether the discriminator associated with this union gets assigned a valid default value.
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override
Methods inherited from interface org.omg.CORBA.DynAny
assign, copy, current_component, destroy, from_any, get_any, get_boolean, get_char, get_double, get_float, get_long, get_longlong, get_octet, get_reference, get_short, get_string, get_typecode, get_ulong, get_ulonglong, get_ushort, get_val, get_wchar, get_wstring, insert_any, insert_boolean, insert_char, insert_double, insert_float, insert_long, insert_longlong, insert_octet, insert_reference, insert_short, insert_string, insert_typecode, insert_ulong, insert_ulonglong, insert_ushort, insert_val, insert_wchar, insert_wstring, next, rewind, seek, to_any, type

Method Detail

set_as_default

public boolean set_as_default()
Determines whether the discriminator associated with this union has been assigned a valid default value.

Returns:
true if the discriminator has a default value; false otherwise

set_as_default

public void set_as_default(boolean arg)
Determines whether the discriminator associated with this union gets assigned a valid default value.

Parameters:
arg - true if the discriminator gets assigned a default value

discriminator

public DynAny discriminator()
Returns a DynAny object reference that must be narrowed to the type of the discriminator in order to insert/get the discriminator value.

Returns:
a DynAny object reference representing the discriminator value

discriminator_kind

public TCKind discriminator_kind()
Returns the TCKind object associated with the discriminator of this union.

Returns:
the TCKind object associated with the discriminator of this union

member

public DynAny member()
Returns a DynAny object reference that is used in order to insert/get a member of this union.

Returns:
the DynAny object representing a member of this union

member_name

public String member_name()
Allows for the inspection of the name of this union member without checking the value of the discriminator.

Returns:
the name of this union member

member_name

public void member_name(String arg)
Allows for the assignment of the name of this union member.

Parameters:
arg - the new name of this union member

member_kind

public TCKind member_kind()
Returns the TCKind associated with the member of this union.

Returns:
the TCKind object associated with the member of this union
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynValue (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Interface DynValue

All Superinterfaces:
DynAny, Object
public interface DynValue
extends Object, DynAny

The representation of a DynAny object that is associated with an IDL value type.

Method Summary
TCKind | current_member_kind() Returns the TCKind object that describes the current member.
String | current_member_name() Returns the name of the current member while traversing a DynAny object that represents a Value object.
NameValuePair[] | get_members() Returns an array containing all the members of the value object stored in this DynValue.
void | set_members(NameValuePair[] value) Sets the members of the value object this DynValue object represents to the given array of NameValuePair objects.
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override
Methods inherited from interface org.omg.CORBA.DynAny
assign, copy, current_component, destroy, from_any, get_any, get_boolean, get_char, get_double, get_float, get_long, get_longlong, get_octet, get_reference, get_short, get_string, get_typecode, get_ulong, get_ulonglong, get_ushort, get_val, get_wchar, get_wstring, insert_any, insert_boolean, insert_char, insert_double, insert_float, insert_long, insert_longlong, insert_octet, insert_reference, insert_short, insert_string, insert_typecode, insert_ulong, insert_ulonglong, insert_ushort, insert_val, insert_wchar, insert_wstring, next, rewind, seek, to_any, type

Method Detail

current_member_name

public String current_member_name()
Returns the name of the current member while traversing a DynAny object that represents a Value object.

Returns:
the name of the current member

current_member_kind

public TCKind current_member_kind()
Returns the TCKind object that describes the current member.

Returns:
the TCKind object corresponding to the current member

get_members

public NameValuePair[] get_members()
Returns an array containing all the members of the value object stored in this DynValue.

Returns:
an array of name-value pairs.
See Also:
set_members(org.omg.CORBA.NameValuePair[])

set_members

public void set_members(NameValuePair[] value)
                 throws InvalidSeq
Sets the members of the value object this DynValue object represents to the given array of NameValuePair objects.

Parameters:
value - the array of name-value pairs to be set
Throws:
InvalidSeq - if an inconsistent value is part of the given array
See Also:
get_members()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Environment (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class Environment

java.lang.Object
    extended by org.omg.CORBA.Environment
public abstract class Environment
extends Object

A container (holder) for an exception that is used in Request operations to make exceptions available to the client. An Environment object is created with the ORB method create_environment.

Since:
JDK1.2

Constructor Summary
Environment()
Method Summary
abstract void | clear() Clears this Environment object of its exception.
abstract Exception | exception() Retrieves the exception in this Environment object.
abstract void | exception(Exception except) Inserts the given exception into this Environment object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

Environment

public Environment()
Method Detail

exception

public abstract Exception exception()
Retrieves the exception in this Environment object.

Returns:
the exception in this Environment object

exception

public abstract void exception(Exception except)
Inserts the given exception into this Environment object.

Parameters:
except - the exception to be set

clear

public abstract void clear()
Clears this Environment object of its exception.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ExceptionList (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class ExceptionList

java.lang.Object
    extended by org.omg.CORBA.ExceptionList
public abstract class ExceptionList
extends Object

An object used in Request operations to describe the exceptions that can be thrown by a method. It maintains a modifiable list of TypeCodes of the exceptions.

The following code fragment demonstrates creating an ExceptionList object:

    ORB orb = ORB.init(args, null);
    org.omg.CORBA.ExceptionList excList = orb.create_exception_list();
The variable excList represents an ExceptionList object with no TypeCode objects in it.

To add items to the list, you first create a TypeCode object for the exception you want to include, using the ORB method create_exception_tc. Then you use the ExceptionList method add to add it to the list. The class ExceptionList has a method for getting the number of TypeCode objects in the list, and after items have been added, it is possible to call methods for accessing or deleting an item at a designated index.

Since:
JDK1.2

Constructor Summary
ExceptionList()
Method Summary
abstract void | add(TypeCode exc) Adds a TypeCode object describing an exception to this ExceptionList object.
abstract int | count() Retrieves the number of TypeCode objects in this ExceptionList object.
abstract TypeCode | item(int index) Returns the TypeCode object at the given index.
abstract void | remove(int index) Removes the TypeCode object at the given index.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ExceptionList

public ExceptionList()
Method Detail

count

public abstract int count()
Retrieves the number of TypeCode objects in this ExceptionList object.

Returns:
the number of TypeCode objects in this ExceptionList object

add

public abstract void add(TypeCode exc)
Adds a TypeCode object describing an exception to this ExceptionList object.

Parameters:
exc - the TypeCode object to be added

item

public abstract TypeCode item(int index)
                       throws Bounds
Returns the TypeCode object at the given index. The first item is at index 0.

Parameters:
index - the index of the TypeCode object desired. This must be an int between 0 and the number of TypeCode objects minus one, inclusive.
Returns:
the TypeCode object at the given index
Throws:
Bounds - if the index given is greater than or equal to the number of TypeCode objects in this ExceptionList object

remove

public abstract void remove(int index)
                     throws Bounds
Removes the TypeCode object at the given index. Note that the indices of all the TypeCoded objects following the one deleted are shifted down by one.

Parameters:
index - the index of the TypeCode object to be removed. This must be an int between 0 and the number of TypeCode objects minus one, inclusive.
Throws:
Bounds - if the index is greater than or equal to the number of TypeCode objects in this ExceptionList object
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


FieldNameHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class FieldNameHelper

java.lang.Object
    extended by org.omg.CORBA.FieldNameHelper
public abstract class FieldNameHelper
extends Object

The Helper for FieldName. For more information on Helper files, see "Generated Files: Helper Files".

org/omg/CORBA/FieldNameHelper.java Generated by the IDL-to-Java compiler (portable), version "3.0" 03 June 1999 11:52:03 o'clock GMT+00:00

Constructor Summary
FieldNameHelper()
Method Summary
static String | extract(Any a)
static String | id()
static void | insert(Any a, String that)
static String | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, String value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

FieldNameHelper

public FieldNameHelper()
Method Detail

insert

public static void insert(Any a,
                          String that)

extract

public static String extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static String read(InputStream istream)

write

public static void write(OutputStream ostream,
                         String value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


FixedHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class FixedHolder

java.lang.Object
    extended by org.omg.CORBA.FixedHolder
All Implemented Interfaces:
Streamable
public final class FixedHolder
extends Object
implements Streamable

The Holder for Fixed. For more information on Holder files, see "Generated Files: Holder Files".

FixedHolder is a container class for values of IDL type "fixed", which is mapped to the Java class java.math.BigDecimal. It is usually used to store "out" and "inout" IDL method parameters. If an IDL method signature has a fixed as an "out" or "inout" parameter, the programmer must pass an instance of FixedHolder as the corresponding parameter in the method invocation; for "inout" parameters, the programmer must also fill the "in" value to be sent to the server. Before the method invocation returns, the ORB will fill in the contained value corresponding to the "out" value returned from the server.

Field Summary
 BigDecimal value
The value held by the FixedHolder
Constructor Summary
FixedHolder()
Construct the FixedHolder without initializing the contained value.
FixedHolder(BigDecimal initial)
Construct the FixedHolder and initialize it with the given value.
Method Summary
void | _read(InputStream input) Read a fixed point value from the input stream and store it in the value member.
TypeCode | _type() Return the TypeCode of this holder object.
void | _write(OutputStream output) Write the fixed point value stored in this holder to an OutputStream.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public BigDecimal value
The value held by the FixedHolder

Constructor Detail

FixedHolder

public FixedHolder()
Construct the FixedHolder without initializing the contained value.

FixedHolder

public FixedHolder(BigDecimal initial)
Construct the FixedHolder and initialize it with the given value.

Parameters:
initial - the value used to initialize the FixedHolder
Method Detail

_read

public void _read(InputStream input)
Read a fixed point value from the input stream and store it in the value member.

Specified by:
_read in interface Streamable
Parameters:
input - the InputStream to read from.

_write

public void _write(OutputStream output)
Write the fixed point value stored in this holder to an OutputStream.

Specified by:
_write in interface Streamable
Parameters:
output - the OutputStream to write into.

_type

public TypeCode _type()
Return the TypeCode of this holder object.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


FloatHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class FloatHolder

java.lang.Object
    extended by org.omg.CORBA.FloatHolder
All Implemented Interfaces:
Streamable
public final class FloatHolder
extends Object
implements Streamable

The Holder for Float. For more information on Holder files, see "Generated Files: Holder Files".

A Holder class for a float that is used to store "out" and "inout" parameters in IDL methods. If an IDL method signature has an IDL float as an "out" or "inout" parameter, the programmer must pass an instance of FloatHolder as the corresponding parameter in the method invocation; for "inout" parameters, the programmer must also fill the "in" value to be sent to the server. Before the method invocation returns, the ORB will fill in the value corresponding to the "out" value returned from the server.

If myFloatHolder is an instance of FloatHolder, the value stored in its value field can be accessed with myFloatHolder.value.

Since:
JDK1.2

Field Summary
 float value
The float value held by this FloatHolder object.
Constructor Summary
FloatHolder()
Constructs a new FloatHolder object with its value field initialized to 0.0.
FloatHolder(float initial)
Constructs a new FloatHolder object for the given float.
Method Summary
void | _read(InputStream input) Read a float from an input stream and initialize the value member with the float value.
TypeCode | _type() Return the TypeCode of this Streamable.
void | _write(OutputStream output) Write the float value into an output stream.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public float value
The float value held by this FloatHolder object.

Constructor Detail

FloatHolder

public FloatHolder()
Constructs a new FloatHolder object with its value field initialized to 0.0.

FloatHolder

public FloatHolder(float initial)
Constructs a new FloatHolder object for the given float.

Parameters:
initial - the float with which to initialize the value field of the new FloatHolder object
Method Detail

_read

public void _read(InputStream input)
Read a float from an input stream and initialize the value member with the float value.

Specified by:
_read in interface Streamable
Parameters:
input - the InputStream to read from.

_write

public void _write(OutputStream output)
Write the float value into an output stream.

Specified by:
_write in interface Streamable
Parameters:
output - the OutputStream to write into.

_type

public TypeCode _type()
Return the TypeCode of this Streamable.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


FloatSeqHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class FloatSeqHelper

java.lang.Object
    extended by org.omg.CORBA.FloatSeqHelper
public abstract class FloatSeqHelper
extends Object

The Helper for FloatSeq. For more information on Helper files, see "Generated Files: Helper Files".

org/omg/CORBA/FloatSeqHelper.java Generated by the IDL-to-Java compiler (portable), version "3.0" from streams.idl 13 May 1999 22:41:37 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

Constructor Summary
FloatSeqHelper()
Method Summary
static float[] | extract(Any a)
static String | id()
static void | insert(Any a, float[] that)
static float[] | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, float[] value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

FloatSeqHelper

public FloatSeqHelper()
Method Detail

insert

public static void insert(Any a,
                          float[] that)

extract

public static float[] extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static float[] read(InputStream istream)

write

public static void write(OutputStream ostream,
                         float[] value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


FloatSeqHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class FloatSeqHolder

java.lang.Object
    extended by org.omg.CORBA.FloatSeqHolder
All Implemented Interfaces:
Streamable
public final class FloatSeqHolder
extends Object
implements Streamable

The Holder for FloatSeq. For more information on Holder files, see "Generated Files: Holder Files".

org/omg/CORBA/FloatSeqHolder.java Generated by the IDL-to-Java compiler (portable), version "3.0" from streams.idl 13 May 1999 22:41:37 o'clock GMT+00:00

Field Summary
 float[] value
Constructor Summary
FloatSeqHolder()
FloatSeqHolder(float[] initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public float[] value
Constructor Detail

FloatSeqHolder

public FloatSeqHolder()

FloatSeqHolder

public FloatSeqHolder(float[] initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


FREE_MEM (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class FREE_MEM

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by org.omg.CORBA.SystemException
                    extended by org.omg.CORBA.FREE_MEM
All Implemented Interfaces:
Serializable
public final class FREE_MEM
extends SystemException

Exception thrown when the ORB failed in an attempt to free dynamic memory, for example because of heap corruption or memory segments being locked.

It contains a minor code, which gives more detailed information about what caused the exception, and a completion status. It may also contain a string describing the exception.

Since:
JDK1.2
See Also:
documentation on Java IDL exceptions

Field Summary
Fields inherited from class org.omg.CORBA.SystemException
completed, minor
Constructor Summary
FREE_MEM()
Constructs a FREE_MEM exception with a default minor code of 0 and a completion state of COMPLETED_NO.
FREE_MEM(int minor, CompletionStatus completed)
Constructs a FREE_MEM exception with the specified minor code and completion status.
FREE_MEM(String s)
Constructs a FREE_MEM exception with the specified detail message, a minor code of 0, and a completion state of COMPLETED_NO.
FREE_MEM(String s, int minor, CompletionStatus completed)
Constructs a FREE_MEM exception with the specified detail message, minor code, and completion status.
Methods inherited from class org.omg.CORBA.SystemException
toString
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

FREE_MEM

public FREE_MEM()
Constructs a FREE_MEM exception with a default minor code of 0 and a completion state of COMPLETED_NO.

FREE_MEM

public FREE_MEM(String s)
Constructs a FREE_MEM exception with the specified detail message, a minor code of 0, and a completion state of COMPLETED_NO.

Parameters:
s - the String containing a detail message

FREE_MEM

public FREE_MEM(int minor,
                CompletionStatus completed)
Constructs a FREE_MEM exception with the specified minor code and completion status.

Parameters:
minor - the minor code
completed - the completion status

FREE_MEM

public FREE_MEM(String s,
                int minor,
                CompletionStatus completed)
Constructs a FREE_MEM exception with the specified detail message, minor code, and completion status. A detail message is a String that describes this particular exception.

Parameters:
s - the String containing a detail message
minor - the minor code
completed - the completion status
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


IdentifierHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class IdentifierHelper

java.lang.Object
    extended by org.omg.CORBA.IdentifierHelper
public abstract class IdentifierHelper
extends Object

The Helper for Identifier. For more information on Helper files, see "Generated Files: Helper Files".

org/omg/CORBA/IdentifierHelper.java Generated by the IDL-to-Java compiler (portable), version "3.0" from ir.idl 03 June 1999 11:33:42 o'clock GMT+00:00

Constructor Summary
IdentifierHelper()
Method Summary
static String | extract(Any a)
static String | id()
static void | insert(Any a, String that)
static String | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, String value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

IdentifierHelper

public IdentifierHelper()
Method Detail

insert

public static void insert(Any a,
                          String that)

extract

public static String extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static String read(InputStream istream)

write

public static void write(OutputStream ostream,
                         String value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


IDLType (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Interface IDLType

All Superinterfaces:
IDLEntity, IDLTypeOperations, IRObject, IRObjectOperations, Object, Serializable
All Known Implementing Classes:
_IDLTypeStub
public interface IDLType
extends IDLTypeOperations, IRObject, IDLEntity

An abstract interface inherited by all Interface Repository (IR) objects that represent OMG IDL types. It provides access to the TypeCode object describing the type and is used in defining the other interfaces wherever definitions of IDLType must be referenced.

Methods inherited from interface org.omg.CORBA.IDLTypeOperations
type
Methods inherited from interface org.omg.CORBA.IRObjectOperations
def_kind, destroy
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


IDLTypeHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class IDLTypeHelper

java.lang.Object
    extended by org.omg.CORBA.IDLTypeHelper
public abstract class IDLTypeHelper
extends Object

The Helper for IDLType. For more information on Helper files, see "Generated Files: Helper Files".

org/omg/CORBA/IDLTypeHelper.java Generated by the IDL-to-Java compiler (portable), version "3.0" from ir.idl 03 June 1999 11:33:44 o'clock GMT+00:00

Constructor Summary
IDLTypeHelper()
Method Summary
static IDLType | extract(Any a)
static String | id()
static void | insert(Any a, IDLType that)
static IDLType | narrow(Object obj)
static IDLType | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, IDLType value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

IDLTypeHelper

public IDLTypeHelper()
Method Detail

insert

public static void insert(Any a,
                          IDLType that)

extract

public static IDLType extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static IDLType read(InputStream istream)

write

public static void write(OutputStream ostream,
                         IDLType value)

narrow

public static IDLType narrow(Object obj)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


IDLTypeOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Interface IDLTypeOperations

All Superinterfaces:
IRObjectOperations
All Known Subinterfaces:
IDLType
All Known Implementing Classes:
_IDLTypeStub
public interface IDLTypeOperations
extends IRObjectOperations

This interface must be implemented by all IDLType objects. The IDLType is inherited by all IR objects that represent IDL types, including interfaces, typedefs, and anonymous types.

See Also:
IDLType, IRObject, IRObjectOperations

Method Summary
 TypeCode type()
The type attribute describes the type defined by an object derived from IDLType.
Methods inherited from interface org.omg.CORBA.IRObjectOperations
def_kind, destroy

Method Detail

type

public TypeCode type()
The type attribute describes the type defined by an object derived from IDLType.

Returns:
the TypeCode defined by this object.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


IMP_LIMIT (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class IMP_LIMIT

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by org.omg.CORBA.SystemException
                    extended by org.omg.CORBA.IMP_LIMIT
All Implemented Interfaces:
Serializable
public final class IMP_LIMIT
extends SystemException

This exception indicates that an implementation limit was exceeded in the ORB run time. For example, an ORB may reach the maximum number of references it can hold simultaneously in an address space, the size of a parameter may have exceeded the allowed maximum, or an ORB may impose a maximum on the number of clients or servers that can run simultaneously.

It contains a minor code, which gives more detailed information about what caused the exception, and a completion status. It may also contain a string describing the exception.

Since:
JDK1.2
See Also:
documentation on Java IDL exceptions

Field Summary
Fields inherited from class org.omg.CORBA.SystemException
completed, minor
Constructor Summary
IMP_LIMIT()
Constructs an IMP_LIMIT exception with a default minor code of 0 and a completion state of COMPLETED_NO.
IMP_LIMIT(int minor, CompletionStatus completed)
Constructs an IMP_LIMIT exception with the specified minor code and completion status.
IMP_LIMIT(String s)
Constructs an IMP_LIMIT exception with the specified detail message, a minor code of 0, and a completion state of COMPLETED_NO.
IMP_LIMIT(String s, int minor, CompletionStatus completed)
Constructs an IMP_LIMIT exception with the specified detail message, minor code, and completion status.
Methods inherited from class org.omg.CORBA.SystemException
toString
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

IMP_LIMIT

public IMP_LIMIT()
Constructs an IMP_LIMIT exception with a default minor code of 0 and a completion state of COMPLETED_NO.

IMP_LIMIT

public IMP_LIMIT(String s)
Constructs an IMP_LIMIT exception with the specified detail message, a minor code of 0, and a completion state of COMPLETED_NO.

Parameters:
s - the String containing a detail message

IMP_LIMIT

public IMP_LIMIT(int minor,
                 CompletionStatus completed)
Constructs an IMP_LIMIT exception with the specified minor code and completion status.

Parameters:
minor - the minor code
completed - the completion status

IMP_LIMIT

public IMP_LIMIT(String s,
                 int minor,
                 CompletionStatus completed)
Constructs an IMP_LIMIT exception with the specified detail message, minor code, and completion status. A detail message is a String that describes this particular exception.

Parameters:
s - the String containing a detail message
minor - the minor code
completed - the completion status
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


INITIALIZE (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class INITIALIZE

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by org.omg.CORBA.SystemException
                    extended by org.omg.CORBA.INITIALIZE
All Implemented Interfaces:
Serializable
public final class INITIALIZE
extends SystemException

Exception thrown when an ORB has encountered a failure during its initialization, such as failure to acquire networking resources or detecting a configuration error.

It contains a minor code, which gives more detailed information about what caused the exception, and a completion status. It may also contain a string describing the exception.

Since:
JDK1.2
See Also:
documentation on Java IDL exceptions

Field Summary
Fields inherited from class org.omg.CORBA.SystemException
completed, minor
Constructor Summary
INITIALIZE()
Constructs an INITIALIZE exception with a default minor code of 0 and a completion state of CompletionStatus.COMPLETED_NO.
INITIALIZE(int minor, CompletionStatus completed)
Constructs an INITIALIZE exception with the specified minor code and completion status.
INITIALIZE(String s)
Constructs an INITIALIZE exception with the specified detail message, a minor code of 0, and a completion state of CompletionStatus.COMPLETED_NO.
INITIALIZE(String s, int minor, CompletionStatus completed)
Constructs an INITIALIZE exception with the specified detail message, minor code, and completion status.
Methods inherited from class org.omg.CORBA.SystemException
toString
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

INITIALIZE

public INITIALIZE()
Constructs an INITIALIZE exception with a default minor code of 0 and a completion state of CompletionStatus.COMPLETED_NO.

INITIALIZE

public INITIALIZE(String s)
Constructs an INITIALIZE exception with the specified detail message, a minor code of 0, and a completion state of CompletionStatus.COMPLETED_NO.

Parameters:
s - the String containing a detail message

INITIALIZE

public INITIALIZE(int minor,
                  CompletionStatus completed)
Constructs an INITIALIZE exception with the specified minor code and completion status.

Parameters:
minor - the minor code
completed - an instance of CompletionStatus indicating the completion status of the method that threw this exception

INITIALIZE

public INITIALIZE(String s,
                  int minor,
                  CompletionStatus completed)
Constructs an INITIALIZE exception with the specified detail message, minor code, and completion status. A detail message is a String that describes this particular exception.

Parameters:
s - the String containing a detail message
minor - the minor code
completed - an instance of CompletionStatus indicating the completion status of the method that threw this exception
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


INTERNAL (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class INTERNAL

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by org.omg.CORBA.SystemException
                    extended by org.omg.CORBA.INTERNAL
All Implemented Interfaces:
Serializable
public final class INTERNAL
extends SystemException

This exception indicates an internal failure in an ORB, for example, if an ORB has detected corruption of its internal data structures.

It contains a minor code, which gives more detailed information about what caused the exception, and a completion status. It may also contain a string describing the exception.

See the section meaning of minor codes to see the minor codes for this exception.

Since:
JDK1.2
See Also:
documentation on Java IDL exceptions

Field Summary
Fields inherited from class org.omg.CORBA.SystemException
completed, minor
Constructor Summary
INTERNAL()
Constructs an INTERNAL exception with a default minor code of 0 and a completion state of COMPLETED_NO.
INTERNAL(int minor, CompletionStatus completed)
Constructs an INTERNAL exception with the specified minor code and completion status.
INTERNAL(String s)
Constructs an INTERNAL exception with the specified detail message, a minor code of 0, and a completion state of COMPLETED_NO.
INTERNAL(String s, int minor, CompletionStatus completed)
Constructs an INTERNAL exception with the specified detail message, minor code, and completion status.
Methods inherited from class org.omg.CORBA.SystemException
toString
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

INTERNAL

public INTERNAL()
Constructs an INTERNAL exception with a default minor code of 0 and a completion state of COMPLETED_NO.

INTERNAL

public INTERNAL(String s)
Constructs an INTERNAL exception with the specified detail message, a minor code of 0, and a completion state of COMPLETED_NO.

Parameters:
s - the String containing a detail message

INTERNAL

public INTERNAL(int minor,
                CompletionStatus completed)
Constructs an INTERNAL exception with the specified minor code and completion status.

Parameters:
minor - the minor code
completed - an instance of CompletionStatus that indicates the completion status of the method that threw this exception

INTERNAL

public INTERNAL(String s,
                int minor,
                CompletionStatus completed)
Constructs an INTERNAL exception with the specified detail message, minor code, and completion status. A detail message is a String that describes this particular exception.

Parameters:
s - the String containing a detail message
minor - the minor code
completed - an instance of CompletionStatus that indicates the completion status of the method that threw this exception
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


INTF_REPOS (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class INTF_REPOS

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by org.omg.CORBA.SystemException
                    extended by org.omg.CORBA.INTF_REPOS
All Implemented Interfaces:
Serializable
public final class INTF_REPOS
extends SystemException

Exception raised when an ORB cannot reach the interface repository, or some other failure relating to the interface repository is detected.

It contains a minor code, which gives more detailed information about what caused the exception, and a completion status. It may also contain a string describing the exception.

Since:
JDK1.2
See Also:
documentation on Java IDL exceptions

Field Summary
Fields inherited from class org.omg.CORBA.SystemException
completed, minor
Constructor Summary
INTF_REPOS()
Constructs an INTF_REPOS exception with a default minor code of 0 and a completion state of COMPLETED_NO.
INTF_REPOS(int minor, CompletionStatus completed)
Constructs an INTF_REPOS exception with the specified minor code and completion status.
INTF_REPOS(String s)
Constructs an INTF_REPOS exception with the specified detail.
INTF_REPOS(String s, int minor, CompletionStatus completed)
Constructs an INTF_REPOS exception with the specified detail message, minor code, and completion status.
Methods inherited from class org.omg.CORBA.SystemException
toString
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

INTF_REPOS

public INTF_REPOS()
Constructs an INTF_REPOS exception with a default minor code of 0 and a completion state of COMPLETED_NO.

INTF_REPOS

public INTF_REPOS(String s)
Constructs an INTF_REPOS exception with the specified detail.

Parameters:
s - the String containing a detail message

INTF_REPOS

public INTF_REPOS(int minor,
                  CompletionStatus completed)
Constructs an INTF_REPOS exception with the specified minor code and completion status.

Parameters:
minor - the minor code
completed - the completion status

INTF_REPOS

public INTF_REPOS(String s,
                  int minor,
                  CompletionStatus completed)
Constructs an INTF_REPOS exception with the specified detail message, minor code, and completion status. A detail message is a String that describes this particular exception.

Parameters:
s - the String containing a detail message
minor - the minor code
completed - the completion status
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


IntHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class IntHolder

java.lang.Object
    extended by org.omg.CORBA.IntHolder
All Implemented Interfaces:
Streamable
public final class IntHolder
extends Object
implements Streamable

The Holder for Int. For more information on Holder files, see "Generated Files: Holder Files".

A Holder class for an int that is used to store "out" and "inout" parameters in IDL methods. If an IDL method signature has an IDL long as an "out" or "inout" parameter, the programmer must pass an instance of IntHolder as the corresponding parameter in the method invocation; for "inout" parameters, the programmer must also fill the "in" value to be sent to the server. Before the method invocation returns, the ORB will fill in the value corresponding to the "out" value returned from the server.

If myIntHolder is an instance of IntHolder, the value stored in its value field can be accessed with myIntHolder.value.

Since:
JDK1.2

Field Summary
 int value
The int value held by this IntHolder object in its value field.
Constructor Summary
IntHolder()
Constructs a new IntHolder object with its value field initialized to 0.
IntHolder(int initial)
Constructs a new IntHolder object with its value field initialized to the given int.
Method Summary
void | _read(InputStream input) Reads unmarshalled data from input and assigns it to the value field in this IntHolder object.
TypeCode | _type() Retrieves the TypeCode object that corresponds to the value held in this IntHolder object's value field.
void | _write(OutputStream output) Marshals the value in this IntHolder object's value field to the output stream output.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public int value
The int value held by this IntHolder object in its value field.

Constructor Detail

IntHolder

public IntHolder()
Constructs a new IntHolder object with its value field initialized to 0.

IntHolder

public IntHolder(int initial)
Constructs a new IntHolder object with its value field initialized to the given int.

Parameters:
initial - the int with which to initialize the value field of the newly-created IntHolder object
Method Detail

_read

public void _read(InputStream input)
Reads unmarshalled data from input and assigns it to the value field in this IntHolder object.

Specified by:
_read in interface Streamable
Parameters:
input - the InputStream object containing CDR formatted data from the wire

_write

public void _write(OutputStream output)
Marshals the value in this IntHolder object's value field to the output stream output.

Specified by:
_write in interface Streamable
Parameters:
output - the OutputStream object that will contain the CDR formatted data

_type

public TypeCode _type()
Retrieves the TypeCode object that corresponds to the value held in this IntHolder object's value field.

Specified by:
_type in interface Streamable
Returns:
the type code for the value held in this IntHolder object
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


INV_FLAG (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class INV_FLAG

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by org.omg.CORBA.SystemException
                    extended by org.omg.CORBA.INV_FLAG
All Implemented Interfaces:
Serializable
public final class INV_FLAG
extends SystemException

Exception thrown when an invalid flag was passed to an operation (for example, when creating a DII request).

It contains a minor code, which gives more detailed information about what caused the exception, and a completion status. It may also contain a string describing the exception.

Since:
JDK1.2
See Also:
documentation on Java IDL exceptions

Field Summary
Fields inherited from class org.omg.CORBA.SystemException
completed, minor
Constructor Summary
INV_FLAG()
Constructs an INV_FLAG exception with a default minor code of 0 and a completion state of COMPLETED_NO.
INV_FLAG(int minor, CompletionStatus completed)
Constructs an INV_FLAG exception with the specified minor code and completion status.
INV_FLAG(String s)
Constructs an INV_FLAG exception with the specified detail message, a minor code of 0, and a completion state of COMPLETED_NO.
INV_FLAG(String s, int minor, CompletionStatus completed)
Constructs an INV_FLAG exception with the specified detail message, minor code, and completion status.
Methods inherited from class org.omg.CORBA.SystemException
toString
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

INV_FLAG

public INV_FLAG()
Constructs an INV_FLAG exception with a default minor code of 0 and a completion state of COMPLETED_NO.

INV_FLAG

public INV_FLAG(String s)
Constructs an INV_FLAG exception with the specified detail message, a minor code of 0, and a completion state of COMPLETED_NO.

Parameters:
s - the String containing a detail message

INV_FLAG

public INV_FLAG(int minor,
                CompletionStatus completed)
Constructs an INV_FLAG exception with the specified minor code and completion status.

Parameters:
minor - the minor code
completed - an instance of CompletionStatus indicating the completion status

INV_FLAG

public INV_FLAG(String s,
                int minor,
                CompletionStatus completed)
Constructs an INV_FLAG exception with the specified detail message, minor code, and completion status. A detail message is a String that describes this particular exception.

Parameters:
s - the String containing a detail message
minor - the minor code
completed - an instance of CompletionStatus indicating the completion status
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


INV_IDENT (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class INV_IDENT

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by org.omg.CORBA.SystemException
                    extended by org.omg.CORBA.INV_IDENT
All Implemented Interfaces:
Serializable
public final class INV_IDENT
extends SystemException

This exception indicates that an IDL identifier is syntactically invalid. It may be raised if, for example, an identifier passed to the interface repository does not conform to IDL identifier syntax, or if an illegal operation name is used with the DII.

It contains a minor code, which gives more detailed information about what caused the exception, and a completion status. It may also contain a string describing the exception.

Since:
JDK1.2
See Also:
documentation on Java IDL exceptions

Field Summary
Fields inherited from class org.omg.CORBA.SystemException
completed, minor
Constructor Summary
INV_IDENT()
Constructs an INV_IDENT exception with a default minor code of 0 and a completion state of COMPLETED_NO.
INV_IDENT(int minor, CompletionStatus completed)
Constructs an INV_IDENT exception with the specified minor code and completion status.
INV_IDENT(String s)
Constructs an INV_IDENT exception with the specified detail message, a minor code of 0, and a completion state of COMPLETED_NO.
INV_IDENT(String s, int minor, CompletionStatus completed)
Constructs an INV_IDENT exception with the specified detail message, minor code, and completion status.
Methods inherited from class org.omg.CORBA.SystemException
toString
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

INV_IDENT

public INV_IDENT()
Constructs an INV_IDENT exception with a default minor code of 0 and a completion state of COMPLETED_NO.

INV_IDENT

public INV_IDENT(String s)
Constructs an INV_IDENT exception with the specified detail message, a minor code of 0, and a completion state of COMPLETED_NO.

Parameters:
s - the String containing a detail message

INV_IDENT

public INV_IDENT(int minor,
                 CompletionStatus completed)
Constructs an INV_IDENT exception with the specified minor code and completion status.

Parameters:
minor - the minor code
completed - a CompletionStatus object indicating the completion status

INV_IDENT

public INV_IDENT(String s,
                 int minor,
                 CompletionStatus completed)
Constructs an INV_IDENT exception with the specified detail message, minor code, and completion status. A detail message is a String that describes this particular exception.

Parameters:
s - the String containing a detail message
minor - the minor code
completed - a CompletionStatus object indicating the completion status
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


INV_OBJREF (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class INV_OBJREF

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by org.omg.CORBA.SystemException
                    extended by org.omg.CORBA.INV_OBJREF
All Implemented Interfaces:
Serializable
public final class INV_OBJREF
extends SystemException

This exception indicates that an object reference is internally malformed. For example, the repository ID may have incorrect syntax or the addressing information may be invalid. This exception is raised by ORB::string_to_object if the passed string does not decode correctly. An ORB may choose to detect calls via nil references (but is not obliged to do detect them). INV_OBJREF is used to indicate this.

It contains a minor code, which gives more detailed information about what caused the exception, and a completion status. It may also contain a string describing the exception.

See the section Minor Code Meanings to see the minor codes for this exception.

Since:
JDK1.2
See Also:
documentation on Java IDL exceptions

Field Summary
Fields inherited from class org.omg.CORBA.SystemException
completed, minor
Constructor Summary
INV_OBJREF()
Constructs an INV_OBJREF exception with a default minor code of 0 and a completion state of COMPLETED_NO.
INV_OBJREF(int minor, CompletionStatus completed)
Constructs an INV_OBJREF exception with the specified minor code and completion status.
INV_OBJREF(String s)
Constructs an INV_OBJREF exception with the specified detail message, a minor code of 0, and a completion state of COMPLETED_NO.
INV_OBJREF(String s, int minor, CompletionStatus completed)
Constructs an INV_OBJREF exception with the specified detail message, minor code, and completion status.
Methods inherited from class org.omg.CORBA.SystemException
toString
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

INV_OBJREF

public INV_OBJREF()
Constructs an INV_OBJREF exception with a default minor code of 0 and a completion state of COMPLETED_NO.

INV_OBJREF

public INV_OBJREF(String s)
Constructs an INV_OBJREF exception with the specified detail message, a minor code of 0, and a completion state of COMPLETED_NO.

Parameters:
s - the String containing a detail message

INV_OBJREF

public INV_OBJREF(int minor,
                  CompletionStatus completed)
Constructs an INV_OBJREF exception with the specified minor code and completion status.

Parameters:
minor - the minor code
completed - a CompletionStatus instance indicating the completion status

INV_OBJREF

public INV_OBJREF(String s,
                  int minor,
                  CompletionStatus completed)
Constructs an INV_OBJREF exception with the specified detail message, minor code, and completion status. A detail message is a String that describes this particular exception.

Parameters:
s - the String containing a detail message
minor - the minor code
completed - a CompletionStatus instance indicating the completion status
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


INV_POLICY (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class INV_POLICY

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by org.omg.CORBA.SystemException
                    extended by org.omg.CORBA.INV_POLICY
All Implemented Interfaces:
Serializable
public final class INV_POLICY
extends SystemException

Standard exception thrown when an invocation cannot be made because of an incompatibility between Policy overrides that apply to the particular invocation. It contains a minor code, which gives more detailed information about what caused the exception, and a completion status. It may also contain a string describing the exception.

See Also:
documentation on Java IDL exceptions

Field Summary
Fields inherited from class org.omg.CORBA.SystemException
completed, minor
Constructor Summary
INV_POLICY()
Constructs a INV_POLICY exception with a default minor code of 0, a completion state of CompletionStatus.COMPLETED_NO, and a null description.
INV_POLICY(int minor, CompletionStatus completed)
Constructs a INV_POLICY exception with the specified minor code and completion status.
INV_POLICY(String s)
Constructs a INV_POLICY exception with the specified description message, a minor code of 0, and a completion state of COMPLETED_NO.
INV_POLICY(String s, int minor, CompletionStatus completed)
Constructs a INV_POLICY exception with the specified description message, minor code, and completion status.
Methods inherited from class org.omg.CORBA.SystemException
toString
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

INV_POLICY

public INV_POLICY()
Constructs a INV_POLICY exception with a default minor code of 0, a completion state of CompletionStatus.COMPLETED_NO, and a null description.

INV_POLICY

public INV_POLICY(String s)
Constructs a INV_POLICY exception with the specified description message, a minor code of 0, and a completion state of COMPLETED_NO.

Parameters:
s - the String containing a detail message

INV_POLICY

public INV_POLICY(int minor,
                  CompletionStatus completed)
Constructs a INV_POLICY exception with the specified minor code and completion status.

Parameters:
minor - the minor code
completed - the completion status

INV_POLICY

public INV_POLICY(String s,
                  int minor,
                  CompletionStatus completed)
Constructs a INV_POLICY exception with the specified description message, minor code, and completion status.

Parameters:
s - the String containing a description message
minor - the minor code
completed - the completion status
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


INVALID_TRANSACTION (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class INVALID_TRANSACTION

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by org.omg.CORBA.SystemException
                    extended by org.omg.CORBA.INVALID_TRANSACTION
All Implemented Interfaces:
Serializable
public final class INVALID_TRANSACTION
extends SystemException

Exception thrown when the request carried an invalid transaction context. For example, this exception could be raised if an error occurred when trying to register a resource.

It contains a minor code, which gives more detailed information about what caused the exception, and a completion status. It may also contain a string describing the exception.

Since:
JDK1.2
See Also:
documentation on Java IDL exceptions

Field Summary
Fields inherited from class org.omg.CORBA.SystemException
completed, minor
Constructor Summary
INVALID_TRANSACTION()
Constructs an INVALID_TRANSACTION exception with a default minor code of 0 and a completion state of COMPLETED_NO.
INVALID_TRANSACTION(int minor, CompletionStatus completed)
Constructs an INVALID_TRANSACTION exception with the specified minor code and completion status.
INVALID_TRANSACTION(String s)
Constructs an INVALID_TRANSACTION exception with the specified detail message.
INVALID_TRANSACTION(String s, int minor, CompletionStatus completed)
Constructs an INVALID_TRANSACTION exception with the specified detail message, minor code, and completion status.
Methods inherited from class org.omg.CORBA.SystemException
toString
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

INVALID_TRANSACTION

public INVALID_TRANSACTION()
Constructs an INVALID_TRANSACTION exception with a default minor code of 0 and a completion state of COMPLETED_NO.

INVALID_TRANSACTION

public INVALID_TRANSACTION(String s)
Constructs an INVALID_TRANSACTION exception with the specified detail message.

Parameters:
s - the String containing a detail message

INVALID_TRANSACTION

public INVALID_TRANSACTION(int minor,
                           CompletionStatus completed)
Constructs an INVALID_TRANSACTION exception with the specified minor code and completion status.

Parameters:
minor - the minor code
completed - the completion status

INVALID_TRANSACTION

public INVALID_TRANSACTION(String s,
                           int minor,
                           CompletionStatus completed)
Constructs an INVALID_TRANSACTION exception with the specified detail message, minor code, and completion status. A detail message is a String that describes this particular exception.

Parameters:
s - the String containing a detail message
minor - the minor code
completed - the completion status
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


IRObject (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Interface IRObject

All Superinterfaces:
IDLEntity, IRObjectOperations, Object, Serializable
All Known Subinterfaces:
IDLType
All Known Implementing Classes:
_IDLTypeStub
public interface IRObject
extends IRObjectOperations, Object, IDLEntity

An IRObject IDL interface represents the most generic interface from which all other Interface Repository interfaces are derived, even the Repository itself.

Methods inherited from interface org.omg.CORBA.IRObjectOperations
def_kind, destroy
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


IRObjectOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Interface IRObjectOperations

All Known Subinterfaces:
IDLType, IDLTypeOperations, IRObject
All Known Implementing Classes:
_IDLTypeStub
public interface IRObjectOperations

This is the Operations interface for the mapping from IRObject. Several interfaces are used as base interfaces for objects in the Interface Repository (IR). These base interfaces are not instantiable. A common set of operations is used to locate objects within the Interface Repository. Some of these operations are defined in the IRObject. All IR objects inherit from the IRObject interface, which provides an operation for identifying the actual type of the object. (The IDL base interface IRObject represents the most generic interface from which all other Interface Repository interfaces are derived, even the Repository itself.) All java implementations of IR objects must implement the IRObjectOperations interface.

See Also:
IDLTypeOperations, IDLType, IRObject

Method Summary
DefinitionKind | def_kind() Returns the DefinitionKind corresponding to this Interface Repository object.
void | destroy() Destroys this object.

Method Detail

def_kind

public DefinitionKind def_kind()
Returns the DefinitionKind corresponding to this Interface Repository object.

Returns:
the DefinitionKind corresponding to this Interface Repository object.

destroy

public void destroy()
Destroys this object. If the object is a Container, this method is applied to all its contents. If the object contains an IDLType attribute for an anonymous type, that IDLType is destroyed. If the object is currently contained in some other object, it is removed. If the method is invoked on a Repository or on a PrimitiveDef then the BAD_INV_ORDER exception is raised with minor value 2. An attempt to destroy an object that would leave the repository in an incoherent state causes BAD_INV_ORDER exception to be raised with the minor code 1.

Throws:
BAD_INV_ORDER - if this method is invoked on a repository or PrimitiveDef, or if an attempt to destroy an object would leave the repository in an incoherent state
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


LocalObject (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class LocalObject

java.lang.Object
    extended by org.omg.CORBA.LocalObject
All Implemented Interfaces:
Object
public class LocalObject
extends Object
implements Object

Used as a base class for implementation of a local IDL interface in the Java language mapping. It is a class which implements all the operations in the org.omg.CORBA.Object interface.

Local interfaces are implemented by using CORBA::LocalObject to provide implementations of Object pseudo operations and any other ORB-specific support mechanisms that are appropriate for such objects. Object implementation techniques are inherently language-mapping specific. Therefore, the LocalObject type is not defined in IDL, but is specified in each language mapping.

Methods that do not apply to local objects throw an org.omg.CORBA.NO_IMPLEMENT exception with the message, "This is a locally contrained object." Attempting to use a LocalObject to create a DII request results in NO_IMPLEMENT system exception. Attempting to marshal or stringify a LocalObject results in a MARSHAL system exception. Narrowing and widening references to LocalObjects must work as for regular object references.

LocalObject is to be used as the base class of locally constrained objects, such as those in the PortableServer module. The specification here is based on the CORBA Components Volume I - orbos/99-07-01

See Also:
CORBA package comments for unimplemented features

Constructor Summary
LocalObject()
Constructs a default LocalObject instance.
Method Summary
Request | _create_request(Context ctx, String operation, NVList arg_list, NamedValue result) Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.
Request | _create_request(Context ctx, String operation, NVList arg_list, NamedValue result, ExceptionList exceptions, ContextList contexts) Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.
Object | _duplicate() Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.
DomainManager[] | _get_domain_managers() 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.
Object | _get_interface_def() Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.
Object | _get_interface() 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.
Policy | _get_policy(int policy_type) 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.
int | _hash(int maximum) Returns a hash value that is consistent for the lifetime of the object, using the given number as the maximum.
InputStream | _invoke(OutputStream output) Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.
boolean | _is_a(String repository_id) 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.
boolean | _is_equivalent(Object that) Determines whether the two object references are equivalent, so far as the ORB can easily determine.
boolean | _is_local() Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.
boolean | _non_existent() Always returns false.
ORB | _orb() Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.
void | _release() Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.
void | _releaseReply(InputStream input) Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.
Request | _request(String operation) Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.
OutputStream | _request(String operation, boolean responseExpected) Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.
void | _servant_postinvoke(ServantObject servant) Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.
ServantObject | _servant_preinvoke(String operation, Class expectedType) Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.
Object | _set_policy_override(Policy[] policies, SetOverrideType set_add) 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.
boolean | validate_connection() 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.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

LocalObject

public LocalObject()
Constructs a default LocalObject instance.

Method Detail

_is_equivalent

public boolean _is_equivalent(Object that)

Determines whether the two object references are equivalent, so far as the ORB can easily determine. Two object references are equivalent if they are identical. Two distinct object references which in fact refer to the same object are also equivalent. However, ORBs are not required to attempt determination of whether two distinct object references refer to the same object, since such determination could be impractically expensive.

Default implementation of the org.omg.CORBA.Object method.

Specified by:
_is_equivalent in interface Object
Parameters:
that - the object reference with which to check for equivalence
Returns:
true if this object reference is known to be equivalent to the given object reference. Note that false indicates only that the two object references are distinct, not necessarily that they reference distinct objects.

_non_existent

public boolean _non_existent()
Always returns false. This method is the default implementation of the org.omg.CORBA.Object method.

Specified by:
_non_existent in interface Object
Returns:
false

_hash

public int _hash(int maximum)
Returns a hash value that is consistent for the lifetime of the object, using the given number as the maximum. This method is the default implementation of the org.omg.CORBA.Object method.

Specified by:
_hash in interface Object
Parameters:
maximum - an int identifying maximum value of the hashcode
Returns:
this instance's hashcode

_is_a

public boolean _is_a(String repository_id)
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. This method is the default implementation of the org.omg.CORBA.Object method.

Specified by:
_is_a in interface Object
Parameters:
repository_id - a String
Returns:
NO_IMPLEMENT because this is a locally constrained object and this method does not apply to local objects
Throws:
NO_IMPLEMENT - because this is a locally constrained object and this method does not apply to local objects
See Also:
CORBA package comments for unimplemented features

_duplicate

public Object _duplicate()
Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.

Specified by:
_duplicate in interface Object
Returns:
a duplicate of this LocalObject instance.
Throws:
NO_IMPLEMENT
See Also:
CORBA package comments for unimplemented features

_release

public void _release()
Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.

Specified by:
_release in interface Object
Throws:
NO_IMPLEMENT
See Also:
CORBA package comments for unimplemented features

_request

public Request _request(String operation)
Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.

Specified by:
_request in interface Object
Parameters:
operation - a String giving the name of an operation to be performed by the request that is returned
Returns:
a Request object with the given operation
Throws:
NO_IMPLEMENT
See Also:
CORBA package comments for unimplemented features

_create_request

public Request _create_request(Context ctx,
                               String operation,
                               NVList arg_list,
                               NamedValue result)
Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.

Specified by:
_create_request in interface Object
Parameters:
ctx - a Context object containing a list of properties
operation - the String representing the name of the method to be invoked
arg_list - an NVList containing the actual arguments to the method being invoked
result - a NamedValue object to serve as a container for the method's return value
Returns:
a new Request object initialized with the given arguments
Throws:
NO_IMPLEMENT
See Also:
CORBA package comments for unimplemented features

_create_request

public Request _create_request(Context ctx,
                               String operation,
                               NVList arg_list,
                               NamedValue result,
                               ExceptionList exceptions,
                               ContextList contexts)
Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.

Specified by:
_create_request in interface Object
Parameters:
ctx - a Context object containing a list of properties
operation - the name of the method to be invoked
arg_list - an NVList containing the actual arguments to the method being invoked
result - a NamedValue object to serve as a container for the method's return value
exceptions - an ExceptionList object containing a list of possible exceptions the method can throw
contexts - a ContextList object containing a list of context strings that need to be resolved and sent with the Request instance
Returns:
the new Request object initialized with the given arguments
Throws:
NO_IMPLEMENT
See Also:
CORBA package comments for unimplemented features

_get_interface

public Object _get_interface()
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. This method is the default implementation of the org.omg.CORBA.Object method.

Returns:
NO_IMPLEMENT because this is a locally constrained object and this method does not apply to local objects
Throws:
NO_IMPLEMENT - because this is a locally constrained object and this method does not apply to local objects
See Also:
CORBA package comments for unimplemented features

_get_interface_def

public Object _get_interface_def()
Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.

Specified by:
_get_interface_def in interface Object
Returns:
the InterfaceDef object in the Interface Repository which provides type information about the object referred to by this object reference
Throws:
NO_IMPLEMENT
See Also:
CORBA package comments for unimplemented features

_orb

public ORB _orb()
Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.

Returns:
the ORB instance that created the Delegate contained in this ObjectImpl
Throws:
NO_IMPLEMENT
See Also:
CORBA package comments for unimplemented features

_get_policy

public Policy _get_policy(int policy_type)
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. This method is the default implementation of the org.omg.CORBA.Object method.

Specified by:
_get_policy in interface Object
Parameters:
policy_type - an int
Returns:
NO_IMPLEMENT because this is a locally constrained object and this method does not apply to local objects
Throws:
NO_IMPLEMENT - because this is a locally constrained object and this method does not apply to local objects
See Also:
CORBA package comments for unimplemented features

_get_domain_managers

public DomainManager[] _get_domain_managers()
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. This method is the default implementation of the org.omg.CORBA.Object method.

Specified by:
_get_domain_managers in interface Object
Returns:
the list of immediately enclosing domain managers of this object. At least one domain manager is always returned in the list since by default each object is associated with at least one domain manager at creation.
Throws:
NO_IMPLEMENT
See Also:
CORBA package comments for unimplemented features

_set_policy_override

public Object _set_policy_override(Policy[] policies,
                                   SetOverrideType set_add)
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. This method is the default implementation of the org.omg.CORBA.Object method.

Specified by:
_set_policy_override in interface Object
Parameters:
policies - an array
set_add - a flag
Returns:
NO_IMPLEMENT because this is a locally constrained object and this method does not apply to local objects
Throws:
NO_IMPLEMENT - because this is a locally constrained object and this method does not apply to local objects
See Also:
CORBA package comments for unimplemented features

_is_local

public boolean _is_local()
Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.

Returns true for this LocalObject instance.

Returns:
true always
Throws:
NO_IMPLEMENT
See Also:
CORBA package comments for unimplemented features

_servant_preinvoke

public ServantObject _servant_preinvoke(String operation,
                                        Class expectedType)
Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.

Parameters:
operation - a String indicating which operation to preinvoke
expectedType - the class of the type of operation mentioned above
Returns:
NO_IMPLEMENT because this is a locally constrained object and this method does not apply to local objects
Throws:
NO_IMPLEMENT - because this is a locally constrained object and this method does not apply to local object
See Also:
CORBA package comments for unimplemented features

_servant_postinvoke

public void _servant_postinvoke(ServantObject servant)
Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.

Parameters:
servant - the servant object on which to post-invoke
Throws:
NO_IMPLEMENT
See Also:
CORBA package comments for unimplemented features

_request

public OutputStream _request(String operation,
                             boolean responseExpected)
Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.

Called by a stub to obtain an OutputStream for marshaling arguments. The stub must supply the operation name, and indicate if a response is expected (i.e is this a oneway call).

Parameters:
operation - the name of the operation being requested
responseExpected - true if a response is expected, false if it is a one-way call
Returns:
NO_IMPLEMENT because this is a locally constrained object and this method does not apply to local objects
Throws:
NO_IMPLEMENT - because this is a locally constrained object and this method does not apply to local objects
See Also:
CORBA package comments for unimplemented features

_invoke

public InputStream _invoke(OutputStream output)
                    throws ApplicationException,
                           RemarshalException
Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.

Called to invoke an operation. The stub provides an OutputStream that was previously returned by a _request() call. _invoke returns an InputStream which contains the marshaled reply. If an exception occurs, _invoke may throw an ApplicationException object which contains an InputStream from which the user exception state may be unmarshaled.

Parameters:
output - the OutputStream to invoke
Returns:
NO_IMPLEMENT because this is a locally constrained object and this method does not apply to local objects
Throws:
ApplicationException - If an exception occurs, _invoke may throw an ApplicationException object which contains an InputStream from which the user exception state may be unmarshaled.
RemarshalException - If an exception occurs, _invoke may throw an ApplicationException object which contains an InputStream from which the user exception state may be unmarshaled.
NO_IMPLEMENT - because this is a locally constrained object and this method does not apply to local objects
See Also:
CORBA package comments for unimplemented features

_releaseReply

public void _releaseReply(InputStream input)
Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.

May optionally be called by a stub to release a reply stream back to the ORB when the unmarshaling has completed. The stub passes the InputStream returned by _invoke() or ApplicationException.getInputStream(). A null value may also be passed to _releaseReply, in which case the method is a no-op.

Parameters:
input - the reply stream back to the ORB or null
Throws:
NO_IMPLEMENT
See Also:
CORBA package comments for unimplemented features

validate_connection

public boolean validate_connection()
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. This method is the default implementation of the org.omg.CORBA.Object method.

Returns:
NO_IMPLEMENT because this is a locally constrained object and this method does not apply to local objects
Throws:
NO_IMPLEMENT - because this is a locally constrained object and this method does not apply to local objects
See Also:
CORBA package comments for unimplemented features
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


LongHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class LongHolder

java.lang.Object
    extended by org.omg.CORBA.LongHolder
All Implemented Interfaces:
Streamable
public final class LongHolder
extends Object
implements Streamable

The Holder for Long. For more information on Holder files, see "Generated Files: Holder Files".

A Holder class for a long that is used to store "out" and "inout" parameters in IDL methods. If an IDL method signature has an IDL long long as an "out" or "inout" parameter, the programmer must pass an instance of LongHolder as the corresponding parameter in the method invocation; for "inout" parameters, the programmer must also fill the "in" value to be sent to the server. Before the method invocation returns, the ORB will fill in the value corresponding to the "out" value returned from the server.

If myLongHolder is an instance of LongHolder, the value stored in its value field can be accessed with myLongHolder.value.

Since:
JDK1.2

Field Summary
 long value
The long value held by this LongHolder object.
Constructor Summary
LongHolder()
Constructs a new LongHolder object with its value field initialized to 0.
LongHolder(long initial)
Constructs a new LongHolder object with its value field initialized to the given long.
Method Summary
void | _read(InputStream input) Reads from input and initalizes the value in the Holder with the unmarshalled data.
TypeCode | _type() Returns the TypeCode object corresponding to the value held in the Holder.
void | _write(OutputStream output) Marshals to output the value in the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public long value
The long value held by this LongHolder object.

Constructor Detail

LongHolder

public LongHolder()
Constructs a new LongHolder object with its value field initialized to 0.

LongHolder

public LongHolder(long initial)
Constructs a new LongHolder object with its value field initialized to the given long.

Parameters:
initial - the long with which to initialize the value field of the newly-created LongHolder object
Method Detail

_read

public void _read(InputStream input)
Reads from input and initalizes the value in the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
input - the InputStream containing CDR formatted data from the wire

_write

public void _write(OutputStream output)
Marshals to output the value in the Holder.

Specified by:
_write in interface Streamable
Parameters:
output - the OutputStream which will contain the CDR formatted data

_type

public TypeCode _type()
Returns the TypeCode object corresponding to the value held in the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode of the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


LongLongSeqHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class LongLongSeqHelper

java.lang.Object
    extended by org.omg.CORBA.LongLongSeqHelper
public abstract class LongLongSeqHelper
extends Object

The Helper for LongLongSeq. For more information on Helper files, see "Generated Files: Helper Files".

org/omg/CORBA/LongLongSeqHelper.java Generated by the IDL-to-Java compiler (portable), version "3.0" from streams.idl 13 May 1999 22:41:37 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

Constructor Summary
LongLongSeqHelper()
Method Summary
static long[] | extract(Any a)
static String | id()
static void | insert(Any a, long[] that)
static long[] | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, long[] value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

LongLongSeqHelper

public LongLongSeqHelper()
Method Detail

insert

public static void insert(Any a,
                          long[] that)

extract

public static long[] extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static long[] read(InputStream istream)

write

public static void write(OutputStream ostream,
                         long[] value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


LongLongSeqHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class LongLongSeqHolder

java.lang.Object
    extended by org.omg.CORBA.LongLongSeqHolder
All Implemented Interfaces:
Streamable
public final class LongLongSeqHolder
extends Object
implements Streamable

The Holder for LongLongSeq. For more information on Holder files, see "Generated Files: Holder Files".

org/omg/CORBA/LongLongSeqHolder.java Generated by the IDL-to-Java compiler (portable), version "3.0" from streams.idl 13 May 1999 22:41:36 o'clock GMT+00:00

Field Summary
 long[] value
Constructor Summary
LongLongSeqHolder()
LongLongSeqHolder(long[] initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public long[] value
Constructor Detail

LongLongSeqHolder

public LongLongSeqHolder()

LongLongSeqHolder

public LongLongSeqHolder(long[] initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


LongSeqHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class LongSeqHelper

java.lang.Object
    extended by org.omg.CORBA.LongSeqHelper
public abstract class LongSeqHelper
extends Object

The Helper for LongSeqHelper. For more information on Helper files, see "Generated Files: Helper Files".

org/omg/CORBA/LongSeqHelper.java Generated by the IDL-to-Java compiler (portable), version "3.0" from streams.idl 13 May 1999 22:41:36 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

Constructor Summary
LongSeqHelper()
Method Summary
static int[] | extract(Any a)
static String | id()
static void | insert(Any a, int[] that)
static int[] | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, int[] value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

LongSeqHelper

public LongSeqHelper()
Method Detail

insert

public static void insert(Any a,
                          int[] that)

extract

public static int[] extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static int[] read(InputStream istream)

write

public static void write(OutputStream ostream,
                         int[] value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


LongSeqHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class LongSeqHolder

java.lang.Object
    extended by org.omg.CORBA.LongSeqHolder
All Implemented Interfaces:
Streamable
public final class LongSeqHolder
extends Object
implements Streamable

The Holder for LongSeq. For more information on Holder files, see "Generated Files: Holder Files".

org/omg/CORBA/LongSeqHolder.java Generated by the IDL-to-Java compiler (portable), version "3.0" from streams.idl 13 May 1999 22:41:36 o'clock GMT+00:00

Field Summary
 int[] value
Constructor Summary
LongSeqHolder()
LongSeqHolder(int[] initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public int[] value
Constructor Detail

LongSeqHolder

public LongSeqHolder()

LongSeqHolder

public LongSeqHolder(int[] initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MARSHAL (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class MARSHAL

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by org.omg.CORBA.SystemException
                    extended by org.omg.CORBA.MARSHAL
All Implemented Interfaces:
Serializable
public final class MARSHAL
extends SystemException

A request or reply from the network is structurally invalid. This error typically indicates a bug in either the client-side or server-side run time. For example, if a reply from the server indicates that the message contains 1000 bytes, but the actual message is shorter or longer than 1000 bytes, the ORB raises this exception. MARSHAL can also be caused by using the DII or DSI incorrectly, for example, if the type of the actual parameters sent does not agree with IDL signature of an operation.

It contains a minor code, which gives more detailed information about what caused the exception, and a completion status. It may also contain a string describing the exception.

See the section Minor Code Meanings to see the minor codes for this exception.

Since:
JDK1.2

Field Summary
Fields inherited from class org.omg.CORBA.SystemException
completed, minor
Constructor Summary
MARSHAL()
Constructs a MARSHAL exception with a default minor code of 0, a completion state of CompletionStatus.COMPLETED_NO, and a null description.
MARSHAL(int minor, CompletionStatus completed)
Constructs a MARSHAL exception with the specified minor code and completion status.
MARSHAL(String s)
Constructs a MARSHAL exception with the specified description message, a minor code of 0, and a completion state of COMPLETED_NO.
MARSHAL(String s, int minor, CompletionStatus completed)
Constructs a MARSHAL exception with the specified description message, minor code, and completion status.
Methods inherited from class org.omg.CORBA.SystemException
toString
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

MARSHAL

public MARSHAL()
Constructs a MARSHAL exception with a default minor code of 0, a completion state of CompletionStatus.COMPLETED_NO, and a null description.

MARSHAL

public MARSHAL(String s)
Constructs a MARSHAL exception with the specified description message, a minor code of 0, and a completion state of COMPLETED_NO.

Parameters:
s - the String containing a description of the exception

MARSHAL

public MARSHAL(int minor,
               CompletionStatus completed)
Constructs a MARSHAL exception with the specified minor code and completion status.

Parameters:
minor - the minor code
completed - the completion status

MARSHAL

public MARSHAL(String s,
               int minor,
               CompletionStatus completed)
Constructs a MARSHAL exception with the specified description message, minor code, and completion status.

Parameters:
s - the String containing a description message
minor - the minor code
completed - the completion status
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NamedValue (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class NamedValue

java.lang.Object
    extended by org.omg.CORBA.NamedValue
public abstract class NamedValue
extends Object

An object used in the DII and DSI to describe arguments and return values. NamedValue objects are also used in the Context object routines to pass lists of property names and values.

A NamedValue object contains:

  • a name -- If the NamedValue object is used to describe arguments to a request, the name will be an argument identifier specified in the OMG IDL interface definition for the operation being described.
  • a value -- an Any object
  • an argument mode flag -- one of the following:
    • ARG_IN.value
    • ARG_OUT.value
    • ARG_INOUT.value
    • zero -- if this NamedValue object represents a property in a Context object rather than a parameter or return value

The class NamedValue has three methods, which access its fields. The following code fragment demonstrates creating a NamedValue object and then accessing its fields:

    ORB orb = ORB.init(args, null);
    String s = "argument_1";
    org.omg.CORBA.Any myAny = orb.create_any();
    myAny.insert_long(12345);
    int in = org.omg.CORBA.ARG_IN.value;

    org.omg.CORBA.NamedValue nv = orb.create_named_value(
        s, myAny, in);
    System.out.println("This nv name is " + nv.name());
    try {
        System.out.println("This nv value is " + nv.value().extract_long());
        System.out.println("This nv flag is " + nv.flags());
    } catch (org.omg.CORBA.BAD_OPERATION b) {
      System.out.println("extract failed");
    }

If this code fragment were put into a main method, the output would be something like the following:

    This nv name is argument_1
    This nv value is 12345
    This nv flag is 1

Note that the method value returns an Any object. In order to access the long contained in the Any object, we used the method extract_long.

Since:
JDK1.2
See Also:
Any, ARG_IN, ARG_INOUT, ARG_OUT

Constructor Summary
NamedValue()
Method Summary
abstract int | flags() Retrieves the argument mode flag for this NamedValue object.
abstract String | name() Retrieves the name for this NamedValue object.
abstract Any | value() Retrieves the value for this NamedValue object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

NamedValue

public NamedValue()
Method Detail

name

public abstract String name()
Retrieves the name for this NamedValue object.

Returns:
a String object representing the name of this NamedValue object

value

public abstract Any value()
Retrieves the value for this NamedValue object.

Returns:
an Any object containing the value of this NamedValue object

flags

public abstract int flags()
Retrieves the argument mode flag for this NamedValue object.

Returns:
an int representing the argument mode for this NamedValue object
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NameValuePair (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class NameValuePair

java.lang.Object
    extended by org.omg.CORBA.NameValuePair
All Implemented Interfaces:
IDLEntity, Serializable
public final class NameValuePair
extends Object
implements IDLEntity

Associates a name with a value that is an attribute of an IDL struct, and is used in the DynStruct APIs.

Field Summary
String | id The name to be associated with a value by this NameValuePair object.
Any | value The value to be associated with a name by this NameValuePair object.
Constructor Summary
NameValuePair()
Constructs an empty NameValuePair object.
NameValuePair(String __id, Any __value)
Constructs a NameValuePair object that associates the given name with the given org.omg.CORBA.Any object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

id

public String id
The name to be associated with a value by this NameValuePair object.

value

public Any value
The value to be associated with a name by this NameValuePair object.

Constructor Detail

NameValuePair

public NameValuePair()
Constructs an empty NameValuePair object. To associate a name with a value after using this constructor, the fields of this object have to be accessed individually.

NameValuePair

public NameValuePair(String __id,
                     Any __value)
Constructs a NameValuePair object that associates the given name with the given org.omg.CORBA.Any object.

Parameters:
__id - the name to be associated with the given Any object
__value - the Any object to be associated with the given name
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NameValuePairHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class NameValuePairHelper

java.lang.Object
    extended by org.omg.CORBA.NameValuePairHelper
public abstract class NameValuePairHelper
extends Object

The Helper for NameValuePair. For more information on Helper files, see "Generated Files: Helper Files".

org/omg/CORBA/NameValuePairHelper.java Generated by the IDL-to-Java compiler (portable), version "3.0" 03 June 1999 11:52:03 o'clock GMT+00:00

Constructor Summary
NameValuePairHelper()
Method Summary
static NameValuePair | extract(Any a)
static String | id()
static void | insert(Any a, NameValuePair that)
static NameValuePair | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, NameValuePair value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

NameValuePairHelper

public NameValuePairHelper()
Method Detail

insert

public static void insert(Any a,
                          NameValuePair that)

extract

public static NameValuePair extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static NameValuePair read(InputStream istream)

write

public static void write(OutputStream ostream,
                         NameValuePair value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NO_IMPLEMENT (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class NO_IMPLEMENT

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by org.omg.CORBA.SystemException
                    extended by org.omg.CORBA.NO_IMPLEMENT
All Implemented Interfaces:
Serializable
public final class NO_IMPLEMENT
extends SystemException

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 can, for example, be raised by an ORB if a client asks for an object's type definition from the interface repository, but no interface repository is provided by the ORB.

It contains a minor code, which gives more detailed information about what caused the exception, and a completion status. It may also contain a string describing the exception.

See the section Minor Code Meanings to see the minor codes for this exception.

Since:
JDK1.2

Field Summary
Fields inherited from class org.omg.CORBA.SystemException
completed, minor
Constructor Summary
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(int minor, CompletionStatus completed)
Constructs a NO_IMPLEMENT exception with the specified minor code and completion status.
NO_IMPLEMENT(String s)
Constructs a NO_IMPLEMENT exception with the specified description message, a minor code of 0, and a completion state of COMPLETED_NO.
NO_IMPLEMENT(String s, int minor, CompletionStatus completed)
Constructs a NO_IMPLEMENT exception with the specified description message, minor code, and completion status.
Methods inherited from class org.omg.CORBA.SystemException
toString
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

NO_IMPLEMENT

public 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

public NO_IMPLEMENT(String s)
Constructs a NO_IMPLEMENT exception with the specified description message, a minor code of 0, and a completion state of COMPLETED_NO.

Parameters:
s - the String containing a description of the exception

NO_IMPLEMENT

public NO_IMPLEMENT(int minor,
                    CompletionStatus completed)
Constructs a NO_IMPLEMENT exception with the specified minor code and completion status.

Parameters:
minor - an int specifying the minor code
completed - a CompletionStatus instance indicating the completion status

NO_IMPLEMENT

public NO_IMPLEMENT(String s,
                    int minor,
                    CompletionStatus completed)
Constructs a NO_IMPLEMENT exception with the specified description message, minor code, and completion status.

Parameters:
s - the String containing a description message
minor - an int specifying the minor code
completed - a CompletionStatus instance indicating the completion status
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NO_MEMORY (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class NO_MEMORY

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by org.omg.CORBA.SystemException
                    extended by org.omg.CORBA.NO_MEMORY
All Implemented Interfaces:
Serializable
public final class NO_MEMORY
extends SystemException

Exception thrown when the ORB run time has run out of memory.

It contains a minor code, which gives more detailed information about what caused the exception, and a completion status. It may also contain a string describing the exception.

Since:
JDK1.2
See Also:
documentation on Java IDL exceptions

Field Summary
Fields inherited from class org.omg.CORBA.SystemException
completed, minor
Constructor Summary
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(int minor, CompletionStatus completed)
Constructs a NO_MEMORY exception with the specified minor code and completion status.
NO_MEMORY(String s)
Constructs a NO_MEMORY exception with the specified description message, a minor code of 0, and a completion state of COMPLETED_NO.
NO_MEMORY(String s, int minor, CompletionStatus completed)
Constructs a NO_MEMORY exception with the specified description message, minor code, and completion status.
Methods inherited from class org.omg.CORBA.SystemException
toString
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

NO_MEMORY

public 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

public NO_MEMORY(String s)
Constructs a NO_MEMORY exception with the specified description message, a minor code of 0, and a completion state of COMPLETED_NO.

Parameters:
s - the String containing a description message

NO_MEMORY

public NO_MEMORY(int minor,
                 CompletionStatus completed)
Constructs a NO_MEMORY exception with the specified minor code and completion status.

Parameters:
minor - the minor code
completed - the completion status

NO_MEMORY

public NO_MEMORY(String s,
                 int minor,
                 CompletionStatus completed)
Constructs a NO_MEMORY exception with the specified description message, minor code, and completion status.

Parameters:
s - the String containing a description message
minor - the minor code
completed - the completion status
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NO_PERMISSION (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class NO_PERMISSION

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by org.omg.CORBA.SystemException
                    extended by org.omg.CORBA.NO_PERMISSION
All Implemented Interfaces:
Serializable
public final class NO_PERMISSION
extends SystemException

Exception thrown when an invocation failed because the caller has insufficient privileges.

It contains a minor code, which gives more detailed information about what caused the exception, and a completion status. It may also contain a string describing the exception.

Since:
JDK1.2
See Also:
documentation on Java IDL exceptions

Field Summary
Fields inherited from class org.omg.CORBA.SystemException
completed, minor
Constructor Summary
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(int minor, CompletionStatus completed)
Constructs a NO_PERMISSION exception with the specified minor code and completion status.
NO_PERMISSION(String s)
Constructs a NO_PERMISSION exception with the specified description, a minor code of 0, and a completion state of COMPLETED_NO.
NO_PERMISSION(String s, int minor, CompletionStatus completed)
Constructs a NO_PERMISSION exception with the specified description message, minor code, and completion status.
Methods inherited from class org.omg.CORBA.SystemException
toString
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

NO_PERMISSION

public 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

public NO_PERMISSION(String s)
Constructs a NO_PERMISSION exception with the specified description, a minor code of 0, and a completion state of COMPLETED_NO.

Parameters:
s - the String containing a description message

NO_PERMISSION

public NO_PERMISSION(int minor,
                     CompletionStatus completed)
Constructs a NO_PERMISSION exception with the specified minor code and completion status.

Parameters:
minor - the minor code
completed - the completion status

NO_PERMISSION

public NO_PERMISSION(String s,
                     int minor,
                     CompletionStatus completed)
Constructs a NO_PERMISSION exception with the specified description message, minor code, and completion status.

Parameters:
s - the String containing a description message
minor - the minor code
completed - the completion status
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NO_RESOURCES (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class NO_RESOURCES

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by org.omg.CORBA.SystemException
                    extended by org.omg.CORBA.NO_RESOURCES
All Implemented Interfaces:
Serializable
public final class NO_RESOURCES
extends SystemException

Exception thrown when the ORB has encountered some general resource limitation. For example, the run time may have reached the maximum permissible number of open connections.

It contains a minor code, which gives more detailed information about what caused the exception, and a completion status. It may also contain a string describing the exception.

Since:
JDK1.2
See Also:
documentation on Java IDL exceptions

Field Summary
Fields inherited from class org.omg.CORBA.SystemException
completed, minor
Constructor Summary
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(int minor, CompletionStatus completed)
Constructs a NO_RESOURCES exception with the specified minor code and completion status.
NO_RESOURCES(String s)
Constructs a NO_RESOURCES exception with the specified description, a minor code of 0, and a completion state of COMPLETED_NO.
NO_RESOURCES(String s, int minor, CompletionStatus completed)
Constructs a NO_RESOURCES exception with the specified description message, minor code, and completion status.
Methods inherited from class org.omg.CORBA.SystemException
toString
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

NO_RESOURCES

public 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

public NO_RESOURCES(String s)
Constructs a NO_RESOURCES exception with the specified description, a minor code of 0, and a completion state of COMPLETED_NO.

Parameters:
s - the String containing a description message

NO_RESOURCES

public NO_RESOURCES(int minor,
                    CompletionStatus completed)
Constructs a NO_RESOURCES exception with the specified minor code and completion status.

Parameters:
minor - the minor code
completed - the completion status

NO_RESOURCES

public NO_RESOURCES(String s,
                    int minor,
                    CompletionStatus completed)
Constructs a NO_RESOURCES exception with the specified description message, minor code, and completion status.

Parameters:
s - the String containing a description message
minor - the minor code
completed - the completion status
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NO_RESPONSE (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class NO_RESPONSE

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by org.omg.CORBA.SystemException
                    extended by org.omg.CORBA.NO_RESPONSE
All Implemented Interfaces:
Serializable
public final class NO_RESPONSE
extends SystemException

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.

It contains a minor code, which gives more detailed information about what caused the exception, and a completion status. It may also contain a string describing the exception.

Since:
JDK1.2
See Also:
documentation on Java IDL exceptions

Field Summary
Fields inherited from class org.omg.CORBA.SystemException
completed, minor
Constructor Summary
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(int minor, CompletionStatus completed)
Constructs a NO_RESPONSE exception with the specified minor code and completion status.
NO_RESPONSE(String s)
Constructs a NO_RESPONSE exception with the specified description message, a minor code of 0, and a completion state of COMPLETED_NO.
NO_RESPONSE(String s, int minor, CompletionStatus completed)
Constructs a NO_RESPONSE exception with the specified description message, minor code, and completion status.
Methods inherited from class org.omg.CORBA.SystemException
toString
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

NO_RESPONSE

public 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

public NO_RESPONSE(String s)
Constructs a NO_RESPONSE exception with the specified description message, a minor code of 0, and a completion state of COMPLETED_NO.

Parameters:
s - the String containing a description message

NO_RESPONSE

public NO_RESPONSE(int minor,
                   CompletionStatus completed)
Constructs a NO_RESPONSE exception with the specified minor code and completion status.

Parameters:
minor - the minor code
completed - the completion status

NO_RESPONSE

public NO_RESPONSE(String s,
                   int minor,
                   CompletionStatus completed)
Constructs a NO_RESPONSE exception with the specified description message, minor code, and completion status.

Parameters:
s - the String containing a description message
minor - the minor code
completed - the completion status
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NVList (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class NVList

java.lang.Object
    extended by org.omg.CORBA.NVList
public abstract class NVList
extends Object

A modifiable list containing NamedValue objects.

The class NVList is used as follows:

  • to describe arguments for a Request object in the Dynamic Invocation Interface and the Dynamic Skeleton Interface
  • to describe context values in a Context object

Each NamedValue object consists of the following:

  • a name, which is a String object
  • a value, as an Any object
  • an argument mode flag

An NVList object may be created using one of the following ORB methods:

  1. org.omg.CORBA.ORB.create_list
        org.omg.CORBA.NVList nv = orb.create_list(3);
    The variable nv represents a newly-created NVList object. The argument is a memory-management hint to the orb and does not imply the actual length of the list. If, for example, you want to use an NVList object in a request, and the method being invoked takes three parameters, you might optimize by supplying 3 to the method create_list. Note that the new NVList will not necessarily have a length of 3; it could have a length of 2 or 4, for instance. Note also that you can add any number of NamedValue objects to this list regardless of its original length.

  2. org.omg.CORBA.ORB.create_operation_list
        org.omg.CORBA.NVList nv = orb.create_operation_list(myOperationDef);
    The variable nv represents a newly-created NVList object that contains descriptions of the arguments to the method described in the given OperationDef object.

The methods in the class NVList all deal with the NamedValue objects in the list. There are three methods for adding a NamedValue object, a method for getting the count of NamedValue objects in the list, a method for retrieving a NamedValue object at a given index, and a method for removing a NamedValue object at a given index.

Since:
JDK1.2
See Also:
Request, ServerRequest, NamedValue, Context

Constructor Summary
NVList()
Method Summary
abstract NamedValue | add_item(String item_name, int flags) Creates a new NamedValue object initialized with the given name and flag, and adds it to the end of this NVList object.
abstract NamedValue | add_value(String item_name, Any val, int flags) Creates a new NamedValue object initialized with the given name, value, and flag, and adds it to the end of this NVList object.
abstract NamedValue | add(int flags) Creates a new NamedValue object initialized with the given flag and adds it to the end of this NVList object.
abstract int | count() Returns the number of NamedValue objects that have been added to this NVList object.
abstract NamedValue | item(int index) Retrieves the NamedValue object at the given index.
abstract void | remove(int index) Removes the NamedValue object at the given index.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

NVList

public NVList()
Method Detail

count

public abstract int count()
Returns the number of NamedValue objects that have been added to this NVList object.

Returns:
an int indicating the number of NamedValue objects in this NVList.

add

public abstract NamedValue add(int flags)
Creates a new NamedValue object initialized with the given flag and adds it to the end of this NVList object. The flag can be any one of the argument passing modes: ARG_IN.value, ARG_OUT.value, or ARG_INOUT.value.

Parameters:
flags - one of the argument mode flags
Returns:
the newly-created NamedValue object

add_item

public abstract NamedValue add_item(String item_name,
                                    int flags)
Creates a new NamedValue object initialized with the given name and flag, and adds it to the end of this NVList object. The flag can be any one of the argument passing modes: ARG_IN.value, ARG_OUT.value, or ARG_INOUT.value.

Parameters:
item_name - the name for the new NamedValue object
flags - one of the argument mode flags
Returns:
the newly-created NamedValue object

add_value

public abstract NamedValue add_value(String item_name,
                                     Any val,
                                     int flags)
Creates a new NamedValue object initialized with the given name, value, and flag, and adds it to the end of this NVList object.

Parameters:
item_name - the name for the new NamedValue object
val - an Any object containing the value for the new NamedValue object
flags - one of the following argument passing modes: ARG_IN.value, ARG_OUT.value, or ARG_INOUT.value
Returns:
the newly created NamedValue object

item

public abstract NamedValue item(int index)
                         throws Bounds
Retrieves the NamedValue object at the given index.

Parameters:
index - the index of the desired NamedValue object, which must be between zero and the length of the list minus one, inclusive. The first item is at index zero.
Returns:
the NamedValue object at the given index
Throws:
Bounds - if the index is greater than or equal to number of NamedValue objects

remove

public abstract void remove(int index)
                     throws Bounds
Removes the NamedValue object at the given index. Note that the indices of all NamedValue objects following the one removed are shifted down by one.

Parameters:
index - the index of the NamedValue object to be removed, which must be between zero and the length of the list minus one, inclusive. The first item is at index zero.
Throws:
Bounds - if the index is greater than or equal to number of NamedValue objects in the list
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


OBJ_ADAPTER (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class OBJ_ADAPTER

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by org.omg.CORBA.SystemException
                    extended by org.omg.CORBA.OBJ_ADAPTER
All Implemented Interfaces:
Serializable
public final class OBJ_ADAPTER
extends SystemException

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.

It contains a minor code, which gives more detailed information about what caused the exception, and a completion status. It may also contain a string describing the exception.

See the section Minor Code Meanings to see the minor codes for this exception.

Since:
JDK1.2
See Also:
documentation on Java IDL exceptions

Field Summary
Fields inherited from class org.omg.CORBA.SystemException
completed, minor
Constructor Summary
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(int minor, CompletionStatus completed)
Constructs an OBJ_ADAPTER exception with the specified minor code and completion status.
OBJ_ADAPTER(String s)
Constructs an OBJ_ADAPTER exception with the specified description, a minor code of 0, and a completion state of COMPLETED_NO.
OBJ_ADAPTER(String s, int minor, CompletionStatus completed)
Constructs an OBJ_ADAPTER exception with the specified description message, minor code, and completion status.
Methods inherited from class org.omg.CORBA.SystemException
toString
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

OBJ_ADAPTER

public 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

public OBJ_ADAPTER(String s)
Constructs an OBJ_ADAPTER exception with the specified description, a minor code of 0, and a completion state of COMPLETED_NO.

Parameters:
s - the String containing a description message

OBJ_ADAPTER

public OBJ_ADAPTER(int minor,
                   CompletionStatus completed)
Constructs an OBJ_ADAPTER exception with the specified minor code and completion status.

Parameters:
minor - the minor code
completed - the completion status

OBJ_ADAPTER

public OBJ_ADAPTER(String s,
                   int minor,
                   CompletionStatus completed)
Constructs an OBJ_ADAPTER exception with the specified description message, minor code, and completion status.

Parameters:
s - the String containing a description message
minor - the minor code
completed - the completion status
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Object (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Interface Object

All Known Implementing Classes:
_BindingIteratorImplBase, _BindingIteratorStub, _DynAnyFactoryStub, _DynAnyStub, _DynArrayStub, _DynEnumStub, _DynFixedStub, _DynSequenceStub, _DynStructStub, _DynUnionStub, _DynValueStub, _IDLTypeStub, _NamingContextExtStub, _NamingContextImplBase, _NamingContextStub, _PolicyStub, _ServantActivatorStub, _ServantLocatorStub, LocalObject, ObjectImpl
public interface Object

The definition for a CORBA object reference.

A CORBA object reference is a handle for a particular CORBA object implemented by a server. A CORBA object reference identifies the same CORBA object each time the reference is used to invoke a method on the object. A CORBA object may have multiple, distinct object references.

The org.omg.CORBA.Object interface is the root of the inheritance hierarchy for all CORBA object references in the Java programming language, analogous to java.rmi.Remote for RMI remote objects.

A CORBA object may be either local or remote. If it is a local object (that is, running in the same VM as the client), invocations may be directly serviced by the object instance, and the object reference could point to the actual instance of the object implementation class. If a CORBA object is a remote object (that is, running in a different VM from the client), the object reference points to a stub (proxy) which uses the ORB machinery to make a remote invocation on the server where the object implementation resides.

Default implementations of the methods in the interface org.omg.CORBA.Object are provided in the class org.omg.CORBA.portable.ObjectImpl, which is the base class for stubs and object implementations.

See Also:
ObjectImpl

Method Summary
Request | _create_request(Context ctx, String operation, NVList arg_list, NamedValue result) Creates a Request instance initialized with the given context, method name, list of arguments, and container for the method's return value.
Request | _create_request(Context ctx, String operation, NVList arg_list, NamedValue result, ExceptionList exclist, ContextList ctxlist) Creates a Request instance initialized with the given context, method name, list of arguments, container for the method's return value, list of possible exceptions, and list of context strings needing to be resolved.
Object | _duplicate() Returns a duplicate of this CORBA object reference.
DomainManager[] | _get_domain_managers() Retrieves the DomainManagers of this object.
Object | _get_interface_def() Obtains an InterfaceDef for the object implementation referenced by this object reference.
Policy | _get_policy(int policy_type) Returns the Policy object of the specified type which applies to this object.
int | _hash(int maximum) Returns an ORB-internal identifier for this object reference.
boolean | _is_a(String repositoryIdentifier) Checks whether this object is an instance of a class that implements the given interface.
boolean | _is_equivalent(Object other) Determines whether the two object references are equivalent, so far as the ORB can easily determine.
boolean | _non_existent() Determines whether the server object for this object reference has been destroyed.
void | _release() Signals that the caller is done using this object reference, so internal ORB resources associated with this object reference can be released.
Request | _request(String operation) Creates a Request instance for use in the Dynamic Invocation Interface.
Object | _set_policy_override(Policy[] policies, SetOverrideType set_add) Returns a new Object with the given policies either replacing any existing policies in this Object or with the given policies added to the existing ones, depending on the value of the given SetOverrideType object.

Method Detail

_is_a

public boolean _is_a(String repositoryIdentifier)
Checks whether this object is an instance of a class that implements the given interface.

Parameters:
repositoryIdentifier - the interface to check against
Returns:
true if this object reference is an instance of a class that implements the interface; false otherwise

_is_equivalent

public boolean _is_equivalent(Object other)
Determines whether the two object references are equivalent, so far as the ORB can easily determine. Two object references are equivalent if they are identical. Two distinct object references which in fact refer to the same object are also equivalent. However, ORBs are not required to attempt determination of whether two distinct object references refer to the same object, since such determination could be impractically expensive.

Parameters:
other - the other object reference with which to check for equivalence
Returns:
true if this object reference is known to be equivalent to the given object reference. Note that false indicates only that the two object references are distinct, not necessarily that they reference distinct objects.

_non_existent

public boolean _non_existent()
Determines whether the server object for this object reference has been destroyed.

Returns:
true if the ORB knows authoritatively that the server object does not exist; false otherwise

_hash

public int _hash(int maximum)
Returns an ORB-internal identifier for this object reference. This is a hash identifier, which does not change during the lifetime of the object reference, and so neither will any hash function of that identifier change. The value returned is not guaranteed to be unique; in other words, another object reference may have the same hash value. If two object references hash differently, then they are distinct object references; however, both may still refer to the same CORBA object.

Parameters:
maximum - the upper bound on the hash value returned by the ORB
Returns:
the ORB-internal hash identifier for this object reference

_duplicate

public Object _duplicate()
Returns a duplicate of this CORBA object reference. The server object implementation is not involved in creating the duplicate, and the implementation cannot distinguish whether the original object reference or a duplicate was used to make a request.

Note that this method is not very useful in the Java platform, since memory management is handled by the VM. It is included for compliance with the CORBA APIs.

The method _duplicate may return this object reference itself.

Returns:
a duplicate of this object reference or this object reference itself

_release

public void _release()
Signals that the caller is done using this object reference, so internal ORB resources associated with this object reference can be released. Note that the object implementation is not involved in this operation, and other references to the same object are not affected.

_get_interface_def

public Object _get_interface_def()
Obtains an InterfaceDef for the object implementation referenced by this object reference. The InterfaceDef object may be used to introspect on the methods, attributes, and other type information for the object referred to by this object reference.

Returns:
the InterfaceDef object in the Interface Repository which provides type information about the object referred to by this object reference

_request

public Request _request(String operation)
Creates a Request instance for use in the Dynamic Invocation Interface.

Parameters:
operation - the name of the method to be invoked using the Request instance
Returns:
the newly-created Request instance

_create_request

public Request _create_request(Context ctx,
                               String operation,
                               NVList arg_list,
                               NamedValue result)
Creates a Request instance initialized with the given context, method name, list of arguments, and container for the method's return value.

Parameters:
ctx - a Context object containing a list of properties
operation - the name of the method to be invoked
arg_list - an NVList containing the actual arguments to the method being invoked
result - a NamedValue object to serve as a container for the method's return value
Returns:
the newly-created Request object
See Also:
Request, NVList, NamedValue

_create_request

public Request _create_request(Context ctx,
                               String operation,
                               NVList arg_list,
                               NamedValue result,
                               ExceptionList exclist,
                               ContextList ctxlist)
Creates a Request instance initialized with the given context, method name, list of arguments, container for the method's return value, list of possible exceptions, and list of context strings needing to be resolved.

Parameters:
ctx - a Context object containing a list of properties
operation - the name of the method to be invoked
arg_list - an NVList containing the actual arguments to the method being invoked
result - a NamedValue object to serve as a container for the method's return value
exclist - an ExceptionList object containing a list of possible exceptions the method can throw
ctxlist - a ContextList object containing a list of context strings that need to be resolved and sent with the Request instance
Returns:
the newly-created Request object
See Also:
Request, NVList, NamedValue, ExceptionList, ContextList

_get_policy

public Policy _get_policy(int policy_type)
Returns the Policy object of the specified type which applies to this object.

Parameters:
policy_type - the type of policy to be obtained
Returns:
A Policy object of the type specified by the policy_type parameter
Throws:
BAD_PARAM - when the value of policy type is not valid either because the specified type is not supported by this ORB or because a policy object of that type is not associated with this Object

_get_domain_managers

public DomainManager[] _get_domain_managers()
Retrieves the DomainManagers of this object. This allows administration services (and applications) to retrieve the domain managers, and hence the security and other policies applicable to individual objects that are members of the domain.

Returns:
the list of immediately enclosing domain managers of this object. At least one domain manager is always returned in the list since by default each object is associated with at least one domain manager at creation.

_set_policy_override

public Object _set_policy_override(Policy[] policies,
                                   SetOverrideType set_add)
Returns a new Object with the given policies either replacing any existing policies in this Object or with the given policies added to the existing ones, depending on the value of the given SetOverrideType object.

Parameters:
policies - an array of Policy objects containing the policies to be added or to be used as replacements
set_add - either SetOverrideType.SET_OVERRIDE, indicating that the given policies will replace any existing ones, or SetOverrideType.ADD_OVERRIDE, indicating that the given policies should be added to any existing ones
Returns:
a new Object with the given policies replacing or added to those in this Object
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


OBJECT_NOT_EXIST (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class OBJECT_NOT_EXIST

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by org.omg.CORBA.SystemException
                    extended by org.omg.CORBA.OBJECT_NOT_EXIST
All Implemented Interfaces:
Serializable
public final class OBJECT_NOT_EXIST
extends SystemException

Exception raised whenever an invocation on a deleted object was performed. It is an authoritative "hard" fault report. Anyone receiving it is allowed (even expected) to delete all copies of this object reference and to perform other appropriate "final recovery" style procedures. Bridges forward this exception to clients, also destroying any records they may hold (for example, proxy objects used in reference translation). The clients could in turn purge any of their own data structures.

It contains a minor code, which gives more detailed information about what caused the exception, and a completion status. It may also contain a string describing the exception.

See the section Minor Code Meanings to see the minor codes for this exception.

Since:
JDK1.2
See Also:
documentation on Java IDL exceptions

Field Summary
Fields inherited from class org.omg.CORBA.SystemException
completed, minor
Constructor Summary
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(int minor, CompletionStatus completed)
Constructs an OBJECT_NOT_EXIST exception with the specified minor code and completion status.
OBJECT_NOT_EXIST(String s)
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(String s, int minor, CompletionStatus completed)
Constructs an OBJECT_NOT_EXIST exception with the specified description message, minor code, and completion status.
Methods inherited from class org.omg.CORBA.SystemException
toString
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

OBJECT_NOT_EXIST

public 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

public OBJECT_NOT_EXIST(String s)
Constructs an OBJECT_NOT_EXIST exception with the specified description, a minor code of 0, and a completion state of COMPLETED_NO.

Parameters:
s - the String containing a description message

OBJECT_NOT_EXIST

public OBJECT_NOT_EXIST(int minor,
                        CompletionStatus completed)
Constructs an OBJECT_NOT_EXIST exception with the specified minor code and completion status.

Parameters:
minor - the minor code
completed - the completion status

OBJECT_NOT_EXIST

public OBJECT_NOT_EXIST(String s,
                        int minor,
                        CompletionStatus completed)
Constructs an OBJECT_NOT_EXIST exception with the specified description message, minor code, and completion status.

Parameters:
s - the String containing a description message
minor - the minor code
completed - the completion status
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ObjectHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class ObjectHelper

java.lang.Object
    extended by org.omg.CORBA.ObjectHelper
public abstract class ObjectHelper
extends Object

Constructor Summary
ObjectHelper()
Method Summary
static Object | extract(Any a)
static String | id()
static void | insert(Any a, Object that)
static Object | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, Object value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ObjectHelper

public ObjectHelper()
Method Detail

insert

public static void insert(Any a,
                          Object that)

extract

public static Object extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static Object read(InputStream istream)

write

public static void write(OutputStream ostream,
                         Object value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ObjectHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class ObjectHolder

java.lang.Object
    extended by org.omg.CORBA.ObjectHolder
All Implemented Interfaces:
Streamable
public final class ObjectHolder
extends Object
implements Streamable

The Holder for Object. For more information on Holder files, see "Generated Files: Holder Files".

A Holder class for a CORBA object reference (a value of type org.omg.CORBA.Object). It is usually used to store "out" and "inout" parameters in IDL methods. If an IDL method signature has a CORBA Object reference as an "out" or "inout" parameter, the programmer must pass an instance of ObjectHolder as the corresponding parameter in the method invocation; for "inout" parameters, the programmer must also fill the "in" value to be sent to the server. Before the method invocation returns, the ORB will fill in the value corresponding to the "out" value returned from the server.

If myObjectHolder is an instance of ObjectHolder, the value stored in its value field can be accessed with myObjectHolder.value.

Since:
JDK1.2

Field Summary
 Object value
The Object value held by this ObjectHolder object.
Constructor Summary
ObjectHolder()
Constructs a new ObjectHolder object with its value field initialized to null.
ObjectHolder(Object initial)
Constructs a new ObjectHolder object with its value field initialized to the given Object.
Method Summary
void | _read(InputStream input) Reads from input and initalizes the value in this ObjectHolder object with the unmarshalled data.
TypeCode | _type() Returns the TypeCode corresponding to the value held in this ObjectHolder object
void | _write(OutputStream output) Marshals to output the value in this ObjectHolder object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public Object value
The Object value held by this ObjectHolder object.

Constructor Detail

ObjectHolder

public ObjectHolder()
Constructs a new ObjectHolder object with its value field initialized to null.

ObjectHolder

public ObjectHolder(Object initial)
Constructs a new ObjectHolder object with its value field initialized to the given Object.

Parameters:
initial - the Object with which to initialize the value field of the newly-created ObjectHolder object
Method Detail

_read

public void _read(InputStream input)
Reads from input and initalizes the value in this ObjectHolder object with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
input - the InputStream containing CDR formatted data from the wire.

_write

public void _write(OutputStream output)
Marshals to output the value in this ObjectHolder object.

Specified by:
_write in interface Streamable
Parameters:
output - the OutputStream which will contain the CDR formatted data.

_type

public TypeCode _type()
Returns the TypeCode corresponding to the value held in this ObjectHolder object

Specified by:
_type in interface Streamable
Returns:
the TypeCode of the value held in this ObjectHolder object
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


OctetSeqHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class OctetSeqHelper

java.lang.Object
    extended by org.omg.CORBA.OctetSeqHelper
public abstract class OctetSeqHelper
extends Object

The Helper for OctetSeq. For more information on Helper files, see "Generated Files: Helper Files".

org/omg/CORBA/OctetSeqHelper.java Generated by the IDL-to-Java compiler (portable), version "3.0" from streams.idl 13 May 1999 22:41:36 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

Constructor Summary
OctetSeqHelper()
Method Summary
static byte[] | extract(Any a)
static String | id()
static void | insert(Any a, byte[] that)
static byte[] | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, byte[] value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

OctetSeqHelper

public OctetSeqHelper()
Method Detail

insert

public static void insert(Any a,
                          byte[] that)

extract

public static byte[] extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static byte[] read(InputStream istream)

write

public static void write(OutputStream ostream,
                         byte[] value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


OctetSeqHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class OctetSeqHolder

java.lang.Object
    extended by org.omg.CORBA.OctetSeqHolder
All Implemented Interfaces:
Streamable
public final class OctetSeqHolder
extends Object
implements Streamable

The Holder for OctetSeq. For more information on Holder files, see "Generated Files: Holder Files".

org/omg/CORBA/OctetSeqHolder.java Generated by the IDL-to-Java compiler (portable), version "3.0" from streams.idl 13 May 1999 22:41:36 o'clock GMT+00:00

Field Summary
 byte[] value
Constructor Summary
OctetSeqHolder()
OctetSeqHolder(byte[] initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public byte[] value
Constructor Detail

OctetSeqHolder

public OctetSeqHolder()

OctetSeqHolder

public OctetSeqHolder(byte[] initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


OMGVMCID (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Interface OMGVMCID

public interface OMGVMCID

The vendor minor code ID reserved for OMG. Minor codes for the standard exceptions are prefaced by the VMCID assigned to OMG, defined as the constant OMGVMCID, which, like all VMCIDs, occupies the high order 20 bits.

Field Summary
static int value
The vendor minor code ID reserved for OMG.

Field Detail

value

public static final int value
The vendor minor code ID reserved for OMG. This value is or'd with the high order 20 bits of the minor code to produce the minor value in a system exception.

See Also:
Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ORB (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class ORB

java.lang.Object
    extended by org.omg.CORBA.ORB
Direct Known Subclasses:
ORB
public abstract class ORB
extends Object

A class providing APIs for the CORBA Object Request Broker features. The ORB class also provides "pluggable ORB implementation" APIs that allow another vendor's ORB implementation to be used.

An ORB makes it possible for CORBA objects to communicate with each other by connecting objects making requests (clients) with objects servicing requests (servers).

The ORB class, which encapsulates generic CORBA functionality, does the following: (Note that items 5 and 6, which include most of the methods in the class ORB, are typically used with the Dynamic Invocation Interface (DII) and the Dynamic Skeleton Interface (DSI). These interfaces may be used by a developer directly, but most commonly they are used by the ORB internally and are not seen by the general programmer.)

  1. initializes the ORB implementation by supplying values for predefined properties and environmental parameters
  2. obtains initial object references to services such as the NameService using the method resolve_initial_references
  3. converts object references to strings and back
  4. connects the ORB to a servant (an instance of a CORBA object implementation) and disconnects the ORB from a servant
  5. creates objects such as
    • TypeCode
    • Any
    • NamedValue
    • Context
    • Environment
    • lists (such as NVList) containing these objects
  6. sends multiple messages in the DII

The ORB class can be used to obtain references to objects implemented anywhere on the network.

An application or applet gains access to the CORBA environment by initializing itself into an ORB using one of three init methods. Two of the three methods use the properties (associations of a name with a value) shown in the table below.

Standard Java CORBA Properties:
Property Name | Property Value
org.omg.CORBA.ORBClass | class name of an ORB implementation
org.omg.CORBA.ORBSingletonClass | class name of the ORB returned by init()

These properties allow a different vendor's ORB implementation to be "plugged in."

When an ORB instance is being created, the class name of the ORB implementation is located using the following standard search order:

  1. check in Applet parameter or application string array, if any
  2. check in properties parameter, if any
  3. check in the System properties
  4. check in the orb.properties file located in the user.home directory (if any)
  5. check in the orb.properties file located in the java.home/lib directory (if any)
  6. fall back on a hardcoded default behavior (use the Java IDL implementation)

Note that Java IDL provides a default implementation for the fully-functional ORB and for the Singleton ORB. When the method init is given no parameters, the default Singleton ORB is returned. When the method init is given parameters but no ORB class is specified, the Java IDL ORB implementation is returned.

The following code fragment creates an ORB object initialized with the default ORB Singleton. This ORB has a restricted implementation to prevent malicious applets from doing anything beyond creating typecodes. It is called a singleton because there is only one instance for an entire virtual machine.

    ORB orb = ORB.init();

The following code fragment creates an ORB object for an application. The parameter args represents the arguments supplied to the application's main method. Since the property specifies the ORB class to be "SomeORBImplementation", the new ORB will be initialized with that ORB implementation. If p had been null, and the arguments had not specified an ORB class, the new ORB would have been initialized with the default Java IDL implementation.

    Properties p = new Properties();
    p.put("org.omg.CORBA.ORBClass", "SomeORBImplementation");
    ORB orb = ORB.init(args, p);

The following code fragment creates an ORB object for the applet supplied as the first parameter. If the given applet does not specify an ORB class, the new ORB will be initialized with the default Java IDL implementation.

    ORB orb = ORB.init(myApplet, null);

An application or applet can be initialized in one or more ORBs. ORB initialization is a bootstrap call into the CORBA world.

Since:
JDK1.2

Constructor Summary
ORB()
Method Summary
void | connect(Object obj) Connects the given servant object (a Java object that is an instance of the server implementation class) to the ORB.
TypeCode | create_abstract_interface_tc(String id, String name) Create a TypeCode object for an IDL abstract interface.
abstract TypeCode | create_alias_tc(String id, String name, TypeCode original_type) Creates a TypeCode object representing an IDL alias (typedef).
abstract Any | create_any() Creates an IDL Any object initialized to contain a Typecode object whose kind field is set to TCKind.tc_null.
abstract TypeCode | create_array_tc(int length, TypeCode element_type) Creates a TypeCode object representing an IDL array.
DynAny | create_basic_dyn_any(TypeCode type) Creates a basic DynAny object from the given TypeCode object.
abstract ContextList | create_context_list() Creates an empty ContextList object.
DynAny | create_dyn_any(Any value) Creates a new DynAny object from the given Any object.
DynArray | create_dyn_array(TypeCode type) Creates a new DynArray object from the given TypeCode object.
DynEnum | create_dyn_enum(TypeCode type) Creates a new DynEnum object from the given TypeCode object.
DynSequence | create_dyn_sequence(TypeCode type) Creates a new DynSequence object from the given TypeCode object.
DynStruct | create_dyn_struct(TypeCode type) Creates a new DynStruct object from the given TypeCode object.
DynUnion | create_dyn_union(TypeCode type) Creates a new DynUnion object from the given TypeCode object.
abstract TypeCode | create_enum_tc(String id, String name, String[] members) Creates a TypeCode object representing an IDL enum.
abstract Environment | create_environment() Creates an Environment object.
abstract ExceptionList | create_exception_list() Creates an empty ExceptionList object.
abstract TypeCode | create_exception_tc(String id, String name, StructMember[] members) Creates a TypeCode object representing an IDL exception.
TypeCode | create_fixed_tc(short digits, short scale) Create a TypeCode object for an IDL fixed type.
abstract TypeCode | create_interface_tc(String id, String name) Creates a TypeCode object representing an IDL interface.
abstract NVList | create_list(int count) Allocates an NVList with (probably) enough space for the specified number of NamedValue objects.
abstract NamedValue | create_named_value(String s, Any any, int flags) Creates a NamedValue object using the given name, value, and argument mode flags.
TypeCode | create_native_tc(String id, String name) Create a TypeCode object for an IDL native type.
NVList | create_operation_list(Object oper) Creates an NVList initialized with argument descriptions for the operation described in the given OperationDef object.
abstract OutputStream | create_output_stream() Creates a new org.omg.CORBA.portable.OutputStream into which IDL method parameters can be marshalled during method invocation.
Policy | create_policy(int type, Any val) Can be invoked to create new instances of policy objects of a specific type with specified initial state.
abstract TypeCode | create_recursive_sequence_tc(int bound, int offset) Deprecated. Use a combination of create_recursive_tc and create_sequence_tc instead
TypeCode | create_recursive_tc(String id) Create a recursive TypeCode object which serves as a placeholder for a concrete TypeCode during the process of creating TypeCodes which contain recursion.
abstract TypeCode | create_sequence_tc(int bound, TypeCode element_type) Creates a TypeCode object representing an IDL sequence.
abstract TypeCode | create_string_tc(int bound) Creates a TypeCode object representing a bounded IDL string.
abstract TypeCode | create_struct_tc(String id, String name, StructMember[] members) Creates a TypeCode object representing an IDL struct.
abstract TypeCode | create_union_tc(String id, String name, TypeCode discriminator_type, UnionMember[] members) Creates a TypeCode object representing an IDL union.
TypeCode | create_value_box_tc(String id, String name, TypeCode boxed_type) Creates a TypeCode object for an IDL value box.
TypeCode | create_value_tc(String id, String name, short type_modifier, TypeCode concrete_base, ValueMember[] members) Create a TypeCode object for an IDL value type.
abstract TypeCode | create_wstring_tc(int bound) Creates a TypeCode object representing a bounded IDL wstring (wide string).
void | destroy() Destroys the ORB so that its resources can be reclaimed.
void | disconnect(Object obj) Disconnects the given servant object from the ORB.
Current | get_current() Deprecated. use resolve_initial_references.
abstract Context | get_default_context() Gets the default Context object.
abstract Request | get_next_response() Gets the next Request instance for which a response has been received.
abstract TypeCode | get_primitive_tc(TCKind tcKind) Retrieves the TypeCode object that represents the given primitive IDL type.
boolean | get_service_information(short service_type, ServiceInformationHolder service_info) Used to obtain information about CORBA facilities and services that are supported by this ORB.
static ORB | init() Returns the ORB singleton object.
static ORB | init(Applet app, Properties props) Creates a new ORB instance for an applet.
static ORB | init(String[] args, Properties props) Creates a new ORB instance for a standalone application.
abstract String[] | list_initial_services() Returns a list of the initially available CORBA object references, such as "NameService" and "InterfaceRepository".
abstract String | object_to_string(Object obj) Converts the given CORBA object reference to a string.
void | perform_work() Performs an implementation-dependent unit of work if called by the main thread.
abstract boolean | poll_next_response() Finds out if any of the deferred (asynchronous) invocations have a response yet.
abstract Object | resolve_initial_references(String object_name) Resolves a specific object reference from the set of available initial service names.
void | run() This operation blocks the current thread until the ORB has completed the shutdown process, initiated when some thread calls shutdown.
abstract void | send_multiple_requests_deferred(Request[] req) Sends multiple dynamic (DII) requests asynchronously.
abstract void | send_multiple_requests_oneway(Request[] req) Sends multiple dynamic (DII) requests asynchronously without expecting any responses.
protected abstract void | set_parameters(Applet app, Properties props) Allows the ORB implementation to be initialized with the given applet and parameters.
protected abstract void | set_parameters(String[] args, Properties props) Allows the ORB implementation to be initialized with the given parameters and properties.
void | shutdown(boolean wait_for_completion) 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.
abstract Object | string_to_object(String str) Converts a string produced by the method object_to_string back to a CORBA object reference.
boolean | work_pending() Returns true if the ORB needs the main thread to perform some work, and false if the ORB does not need the main thread.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ORB

public ORB()
Method Detail

init

public static ORB init()
Returns the ORB singleton object. This method always returns the same ORB instance, which is an instance of the class described by the org.omg.CORBA.ORBSingletonClass system property.

This no-argument version of the method init is used primarily as a factory for TypeCode objects, which are used by Helper classes to implement the method type. It is also used to create Any objects that are used to describe union labels (as part of creating a TypeCode object for a union).

This method is not intended to be used by applets, and in the event that it is called in an applet environment, the ORB it returns is restricted so that it can be used only as a factory for TypeCode objects. Any TypeCode objects it produces can be safely shared among untrusted applets.

If an ORB is created using this method from an applet, a system exception will be thrown if methods other than those for creating TypeCode objects are invoked.

Returns:
the singleton ORB

init

public static ORB init(String[] args,
                       Properties props)
Creates a new ORB instance for a standalone application. This method may be called from applications only and returns a new fully functional ORB object each time it is called.

Parameters:
args - command-line arguments for the application's main method; may be null
props - application-specific properties; may be null
Returns:
the newly-created ORB instance

init

public static ORB init(Applet app,
                       Properties props)
Creates a new ORB instance for an applet. This method may be called from applets only and returns a new fully-functional ORB object each time it is called.

Parameters:
app - the applet; may be null
props - applet-specific properties; may be null
Returns:
the newly-created ORB instance

set_parameters

protected abstract void set_parameters(String[] args,
                                       Properties props)
Allows the ORB implementation to be initialized with the given parameters and properties. This method, used in applications only, is implemented by subclass ORB implementations and called by the appropriate init method to pass in its parameters.

Parameters:
args - command-line arguments for the application's main method; may be null
props - application-specific properties; may be null

set_parameters

protected abstract void set_parameters(Applet app,
                                       Properties props)
Allows the ORB implementation to be initialized with the given applet and parameters. This method, used in applets only, is implemented by subclass ORB implementations and called by the appropriate init method to pass in its parameters.

Parameters:
app - the applet; may be null
props - applet-specific properties; may be null

connect

public void connect(Object obj)
Connects the given servant object (a Java object that is an instance of the server implementation class) to the ORB. The servant class must extend the ImplBase class corresponding to the interface that is supported by the server. The servant must thus be a CORBA object reference, and inherit from org.omg.CORBA.Object. Servants created by the user can start receiving remote invocations after the method connect has been called. A servant may also be automatically and implicitly connected to the ORB if it is passed as an IDL parameter in an IDL method invocation on a non-local object, that is, if the servant object has to be marshalled and sent outside of the process address space.

Calling the method connect has no effect when the servant object is already connected to the ORB.

Deprecated by the OMG in favor of the Portable Object Adapter APIs.

Parameters:
obj - The servant object reference

destroy

public void destroy()
Destroys the ORB so that its resources can be reclaimed. Any operation invoked on a destroyed ORB reference will throw the OBJECT_NOT_EXIST exception. Once an ORB has been destroyed, another call to init with the same ORBid will return a reference to a newly constructed ORB.

If destroy is called on an ORB that has not been shut down, it will start the shut down process and block until the ORB has shut down before it destroys the ORB.
If an application calls destroy in a thread that is currently servicing an invocation, the BAD_INV_ORDER system exception will be thrown with the OMG minor code 3, since blocking would result in a deadlock.

For maximum portability and to avoid resource leaks, an application should always call shutdown and destroy on all ORB instances before exiting.

Throws:
BAD_INV_ORDER - if the current thread is servicing an invocation

disconnect

public void disconnect(Object obj)
Disconnects the given servant object from the ORB. After this method returns, the ORB will reject incoming remote requests for the disconnected servant and will send the exception org.omg.CORBA.OBJECT_NOT_EXIST back to the remote client. Thus the object appears to be destroyed from the point of view of remote clients. Note, however, that local requests issued using the servant directly do not pass through the ORB; hence, they will continue to be processed by the servant.

Calling the method disconnect has no effect if the servant is not connected to the ORB.

Deprecated by the OMG in favor of the Portable Object Adapter APIs.

Parameters:
obj - The servant object to be disconnected from the ORB

list_initial_services

public abstract String[] list_initial_services()
Returns a list of the initially available CORBA object references, such as "NameService" and "InterfaceRepository".

Returns:
an array of String objects that represent the object references for CORBA services that are initially available with this ORB

resolve_initial_references

public abstract Object resolve_initial_references(String object_name)
                                           throws InvalidName
Resolves a specific object reference from the set of available initial service names.

Parameters:
object_name - the name of the initial service as a string
Returns:
the object reference associated with the given name
Throws:
InvalidName - if the given name is not associated with a known service

object_to_string

public abstract String object_to_string(Object obj)
Converts the given CORBA object reference to a string. Note that the format of this string is predefined by IIOP, allowing strings generated by a different ORB to be converted back into an object reference.

The resulting String object may be stored or communicated in any way that a String object can be manipulated.

Parameters:
obj - the object reference to stringify
Returns:
the string representing the object reference

string_to_object

public abstract Object string_to_object(String str)
Converts a string produced by the method object_to_string back to a CORBA object reference.

Parameters:
str - the string to be converted back to an object reference. It must be the result of converting an object reference to a string using the method object_to_string.
Returns:
the object reference

create_list

public abstract NVList create_list(int count)
Allocates an NVList with (probably) enough space for the specified number of NamedValue objects. Note that the specified size is only a hint to help with storage allocation and does not imply the maximum size of the list.

Parameters:
count - suggested number of NamedValue objects for which to allocate space
Returns:
the newly-created NVList
See Also:
NVList

create_operation_list

public NVList create_operation_list(Object oper)
Creates an NVList initialized with argument descriptions for the operation described in the given OperationDef object. This OperationDef object is obtained from an Interface Repository. The arguments in the returned NVList object are in the same order as in the original IDL operation definition, which makes it possible for the list to be used in dynamic invocation requests.

Parameters:
oper - the OperationDef object to use to create the list
Returns:
a newly-created NVList object containing descriptions of the arguments to the method described in the given OperationDef object
See Also:
NVList

create_named_value

public abstract NamedValue create_named_value(String s,
                                              Any any,
                                              int flags)
Creates a NamedValue object using the given name, value, and argument mode flags.

A NamedValue object serves as (1) a parameter or return value or (2) a context property. It may be used by itself or as an element in an NVList object.

Parameters:
s - the name of the NamedValue object
any - the Any value to be inserted into the NamedValue object
flags - the argument mode flags for the NamedValue: one of ARG_IN.value, ARG_OUT.value, or ARG_INOUT.value.
Returns:
the newly-created NamedValue object
See Also:
NamedValue

create_exception_list

public abstract ExceptionList create_exception_list()
Creates an empty ExceptionList object.

Returns:
the newly-created ExceptionList object

create_context_list

public abstract ContextList create_context_list()
Creates an empty ContextList object.

Returns:
the newly-created ContextList object
See Also:
ContextList, Context

get_default_context

public abstract Context get_default_context()
Gets the default Context object.

Returns:
the default Context object
See Also:
Context

create_environment

public abstract Environment create_environment()
Creates an Environment object.

Returns:
the newly-created Environment object
See Also:
Environment

create_output_stream

public abstract OutputStream create_output_stream()
Creates a new org.omg.CORBA.portable.OutputStream into which IDL method parameters can be marshalled during method invocation.

Returns:
the newly-created org.omg.CORBA.portable.OutputStream object

send_multiple_requests_oneway

public abstract void send_multiple_requests_oneway(Request[] req)
Sends multiple dynamic (DII) requests asynchronously without expecting any responses. Note that oneway invocations are not guaranteed to reach the server.

Parameters:
req - an array of request objects

send_multiple_requests_deferred

public abstract void send_multiple_requests_deferred(Request[] req)
Sends multiple dynamic (DII) requests asynchronously.

Parameters:
req - an array of Request objects

poll_next_response

public abstract boolean poll_next_response()
Finds out if any of the deferred (asynchronous) invocations have a response yet.

Returns:
true if there is a response available; false otherwise

get_next_response

public abstract Request get_next_response()
                                   throws WrongTransaction
Gets the next Request instance for which a response has been received.

Returns:
the next Request object ready with a response
Throws:
WrongTransaction - if the method get_next_response is called from a transaction scope different from the one from which the original request was sent. See the OMG Transaction Service specification for details.

get_primitive_tc

public abstract TypeCode get_primitive_tc(TCKind tcKind)
Retrieves the TypeCode object that represents the given primitive IDL type.

Parameters:
tcKind - the TCKind instance corresponding to the desired primitive type
Returns:
the requested TypeCode object

create_struct_tc

public abstract TypeCode create_struct_tc(String id,
                                          String name,
                                          StructMember[] members)
Creates a TypeCode object representing an IDL struct. The TypeCode object is initialized with the given id, name, and members.

Parameters:
id - the repository id for the struct
name - the name of the struct
members - an array describing the members of the struct
Returns:
a newly-created TypeCode object describing an IDL struct

create_union_tc

public abstract TypeCode create_union_tc(String id,
                                         String name,
                                         TypeCode discriminator_type,
                                         UnionMember[] members)
Creates a TypeCode object representing an IDL union. The TypeCode object is initialized with the given id, name, discriminator type, and members.

Parameters:
id - the repository id of the union
name - the name of the union
discriminator_type - the type of the union discriminator
members - an array describing the members of the union
Returns:
a newly-created TypeCode object describing an IDL union

create_enum_tc

public abstract TypeCode create_enum_tc(String id,
                                        String name,
                                        String[] members)
Creates a TypeCode object representing an IDL enum. The TypeCode object is initialized with the given id, name, and members.

Parameters:
id - the repository id for the enum
name - the name for the enum
members - an array describing the members of the enum
Returns:
a newly-created TypeCode object describing an IDL enum

create_alias_tc

public abstract TypeCode create_alias_tc(String id,
                                         String name,
                                         TypeCode original_type)
Creates a TypeCode object representing an IDL alias (typedef). The TypeCode object is initialized with the given id, name, and original type.

Parameters:
id - the repository id for the alias
name - the name for the alias
original_type - the TypeCode object describing the original type for which this is an alias
Returns:
a newly-created TypeCode object describing an IDL alias

create_exception_tc

public abstract TypeCode create_exception_tc(String id,
                                             String name,
                                             StructMember[] members)
Creates a TypeCode object representing an IDL exception. The TypeCode object is initialized with the given id, name, and members.

Parameters:
id - the repository id for the exception
name - the name for the exception
members - an array describing the members of the exception
Returns:
a newly-created TypeCode object describing an IDL exception

create_interface_tc

public abstract TypeCode create_interface_tc(String id,
                                             String name)
Creates a TypeCode object representing an IDL interface. The TypeCode object is initialized with the given id and name.

Parameters:
id - the repository id for the interface
name - the name for the interface
Returns:
a newly-created TypeCode object describing an IDL interface

create_string_tc

public abstract TypeCode create_string_tc(int bound)
Creates a TypeCode object representing a bounded IDL string. The TypeCode object is initialized with the given bound, which represents the maximum length of the string. Zero indicates that the string described by this type code is unbounded.

Parameters:
bound - the bound for the string; cannot be negative
Returns:
a newly-created TypeCode object describing a bounded IDL string
Throws:
BAD_PARAM - if bound is a negative value

create_wstring_tc

public abstract TypeCode create_wstring_tc(int bound)
Creates a TypeCode object representing a bounded IDL wstring (wide string). The TypeCode object is initialized with the given bound, which represents the maximum length of the wide string. Zero indicates that the string described by this type code is unbounded.

Parameters:
bound - the bound for the wstring; cannot be negative
Returns:
a newly-created TypeCode object describing a bounded IDL wstring
Throws:
BAD_PARAM - if bound is a negative value

create_sequence_tc

public abstract TypeCode create_sequence_tc(int bound,
                                            TypeCode element_type)
Creates a TypeCode object representing an IDL sequence. The TypeCode object is initialized with the given bound and element type.

Parameters:
bound - the bound for the sequence, 0 if unbounded
element_type - the TypeCode object describing the elements contained in the sequence
Returns:
a newly-created TypeCode object describing an IDL sequence

create_recursive_sequence_tc

public abstract TypeCode create_recursive_sequence_tc(int bound,
                                                      int offset)
Deprecated. Use a combination of create_recursive_tc and create_sequence_tc instead

Creates a TypeCode object representing a a recursive IDL sequence.

For the IDL struct Node in following code fragment, the offset parameter for creating its sequence would be 1:

    Struct Node {
        long value;
        Sequence <Node> subnodes;
    };

Parameters:
bound - the bound for the sequence, 0 if unbounded
offset - the index to the enclosing TypeCode object that describes the elements of this sequence
Returns:
a newly-created TypeCode object describing a recursive sequence
See Also:
create_recursive_tc, create_sequence_tc

create_array_tc

public abstract TypeCode create_array_tc(int length,
                                         TypeCode element_type)
Creates a TypeCode object representing an IDL array. The TypeCode object is initialized with the given length and element type.

Parameters:
length - the length of the array
element_type - a TypeCode object describing the type of element contained in the array
Returns:
a newly-created TypeCode object describing an IDL array

create_native_tc

public TypeCode create_native_tc(String id,
                                 String name)
Create a TypeCode object for an IDL native type.

Parameters:
id - the logical id for the native type.
name - the name of the native type.
Returns:
the requested TypeCode.

create_abstract_interface_tc

public TypeCode create_abstract_interface_tc(String id,
                                             String name)
Create a TypeCode object for an IDL abstract interface.

Parameters:
id - the logical id for the abstract interface type.
name - the name of the abstract interface type.
Returns:
the requested TypeCode.

create_fixed_tc

public TypeCode create_fixed_tc(short digits,
                                short scale)
Create a TypeCode object for an IDL fixed type.

Parameters:
digits - specifies the total number of decimal digits in the number and must be from 1 to 31 inclusive.
scale - specifies the position of the decimal point.
Returns:
the requested TypeCode.

create_value_tc

public TypeCode create_value_tc(String id,
                                String name,
                                short type_modifier,
                                TypeCode concrete_base,
                                ValueMember[] members)
Create a TypeCode object for an IDL value type. The concrete_base parameter is the TypeCode for the immediate concrete valuetype base of the valuetype for which the TypeCode is being created. It may be null if the valuetype does not have a concrete base.

Parameters:
id - the logical id for the value type.
name - the name of the value type.
type_modifier - one of the value type modifier constants: VM_NONE, VM_CUSTOM, VM_ABSTRACT or VM_TRUNCATABLE
concrete_base - a TypeCode object describing the concrete valuetype base
members - an array containing the members of the value type
Returns:
the requested TypeCode

create_recursive_tc

public TypeCode create_recursive_tc(String id)
Create a recursive TypeCode object which serves as a placeholder for a concrete TypeCode during the process of creating TypeCodes which contain recursion. The id parameter specifies the repository id of the type for which the recursive TypeCode is serving as a placeholder. Once the recursive TypeCode has been properly embedded in the enclosing TypeCode which corresponds to the specified repository id, it will function as a normal TypeCode. Invoking operations on the recursive TypeCode before it has been embedded in the enclosing TypeCode will result in a BAD_TYPECODE exception.

For example, the following IDL type declaration contains recursion:

    Struct Node {
        Sequence<Node> subnodes;
    };

To create a TypeCode for struct Node, you would invoke the TypeCode creation operations as shown below:

 String nodeID = "IDL:Node:1.0";
 TypeCode recursiveSeqTC = orb.create_sequence_tc(0, orb.create_recursive_tc(nodeID));
 StructMember[] members = { new StructMember("subnodes", recursiveSeqTC, null) };
 TypeCode structNodeTC = orb.create_struct_tc(nodeID, "Node", members);

Also note that the following is an illegal IDL type declaration:

    Struct Node {
        Node next;
    };

Recursive types can only appear within sequences which can be empty. That way marshaling problems, when transmitting the struct in an Any, are avoided.

Parameters:
id - the logical id of the referenced type
Returns:
the requested TypeCode

create_value_box_tc

public TypeCode create_value_box_tc(String id,
                                    String name,
                                    TypeCode boxed_type)
Creates a TypeCode object for an IDL value box.

Parameters:
id - the logical id for the value type
name - the name of the value type
boxed_type - the TypeCode for the type
Returns:
the requested TypeCode

create_any

public abstract Any create_any()
Creates an IDL Any object initialized to contain a Typecode object whose kind field is set to TCKind.tc_null.

Returns:
a newly-created Any object

get_current

public Current get_current()
Deprecated. use resolve_initial_references.

Retrieves a Current object. The Current interface is used to manage thread-specific information for use by services such as transactions and security.

Returns:
a newly-created Current object
See Also:
CORBA package comments for unimplemented features

run

public void run()
This operation blocks the current thread until the ORB has completed the shutdown process, initiated when some thread calls shutdown. It may be used by multiple threads which get all notified when the ORB shuts down.

shutdown

public void shutdown(boolean wait_for_completion)
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. If an application does this in a thread that is currently servicing an invocation, the BAD_INV_ORDER system exception will be thrown with the OMG minor code 3, since blocking would result in a deadlock.
If the wait_for_completion parameter is FALSE, then shutdown may not have completed upon return.

While the ORB is in the process of shutting down, the ORB operates as normal, servicing incoming and outgoing requests until all requests have been completed. Once an ORB has shutdown, only object reference management operations may be invoked on the ORB or any object reference obtained from it. An application may also invoke the destroy operation on the ORB itself. Invoking any other operation will throw the BAD_INV_ORDER system exception with the OMG minor code 4.

The ORB.run method will return after shutdown has been called.

Parameters:
wait_for_completion - true if the call should block until the shutdown is complete; false if it should return immediately
Throws:
BAD_INV_ORDER - if the current thread is servicing an invocation

work_pending

public boolean work_pending()
Returns true if the ORB needs the main thread to perform some work, and false if the ORB does not need the main thread.

Returns:
true if there is work pending, meaning that the ORB needs the main thread to perform some work; false if there is no work pending and thus the ORB does not need the main thread

perform_work

public void perform_work()
Performs an implementation-dependent unit of work if called by the main thread. Otherwise it does nothing. The methods work_pending and perform_work can be used in conjunction to implement a simple polling loop that multiplexes the main thread among the ORB and other activities.

get_service_information

public boolean get_service_information(short service_type,
                                       ServiceInformationHolder service_info)
Used to obtain information about CORBA facilities and services that are supported by this ORB. The service type for which information is being requested is passed in as the in parameter service_type, the values defined by constants in the CORBA module. If service information is available for that type, that is returned in the out parameter service_info, and the operation returns the value true. If no information for the requested services type is available, the operation returns false (i.e., the service is not supported by this ORB).

Parameters:
service_type - a short indicating the service type for which information is being requested
service_info - a ServiceInformationHolder object that will hold the ServiceInformation object produced by this method
Returns:
true if service information is available for the service_type; false if no information for the requested services type is available
See Also:
CORBA package comments for unimplemented features

create_dyn_any

public DynAny create_dyn_any(Any value)
Creates a new DynAny object from the given Any object.

Parameters:
value - the Any object from which to create a new DynAny object
Returns:
the new DynAny object created from the given Any object
See Also:
CORBA package comments for unimplemented features, DynamicAny package replaces these API

create_basic_dyn_any

public DynAny create_basic_dyn_any(TypeCode type)
                            throws InconsistentTypeCode
Creates a basic DynAny object from the given TypeCode object.

Parameters:
type - the TypeCode object from which to create a new DynAny object
Returns:
the new DynAny object created from the given TypeCode object
Throws:
InconsistentTypeCode - if the given TypeCode object is not consistent with the operation.
See Also:
CORBA package comments for unimplemented features, DynamicAny package replaces these API

create_dyn_struct

public DynStruct create_dyn_struct(TypeCode type)
                            throws InconsistentTypeCode
Creates a new DynStruct object from the given TypeCode object.

Parameters:
type - the TypeCode object from which to create a new DynStruct object
Returns:
the new DynStruct object created from the given TypeCode object
Throws:
InconsistentTypeCode - if the given TypeCode object is not consistent with the operation.
See Also:
CORBA package comments for unimplemented features, DynamicAny package replaces these API

create_dyn_sequence

public DynSequence create_dyn_sequence(TypeCode type)
                                throws InconsistentTypeCode
Creates a new DynSequence object from the given TypeCode object.

Parameters:
type - the TypeCode object from which to create a new DynSequence object
Returns:
the new DynSequence object created from the given TypeCode object
Throws:
InconsistentTypeCode - if the given TypeCode object is not consistent with the operation.
See Also:
CORBA package comments for unimplemented features, DynamicAny package replaces these API

create_dyn_array

public DynArray create_dyn_array(TypeCode type)
                          throws InconsistentTypeCode
Creates a new DynArray object from the given TypeCode object.

Parameters:
type - the TypeCode object from which to create a new DynArray object
Returns:
the new DynArray object created from the given TypeCode object
Throws:
InconsistentTypeCode - if the given TypeCode object is not consistent with the operation.
See Also:
CORBA package comments for unimplemented features, DynamicAny package replaces these API

create_dyn_union

public DynUnion create_dyn_union(TypeCode type)
                          throws InconsistentTypeCode
Creates a new DynUnion object from the given TypeCode object.

Parameters:
type - the TypeCode object from which to create a new DynUnion object
Returns:
the new DynUnion object created from the given TypeCode object
Throws:
InconsistentTypeCode - if the given TypeCode object is not consistent with the operation.
See Also:
CORBA package comments for unimplemented features, DynamicAny package replaces these API

create_dyn_enum

public DynEnum create_dyn_enum(TypeCode type)
                        throws InconsistentTypeCode
Creates a new DynEnum object from the given TypeCode object.

Parameters:
type - the TypeCode object from which to create a new DynEnum object
Returns:
the new DynEnum object created from the given TypeCode object
Throws:
InconsistentTypeCode - if the given TypeCode object is not consistent with the operation.
See Also:
CORBA package comments for unimplemented features, DynamicAny package replaces these API

create_policy

public Policy create_policy(int type,
                            Any val)
                     throws PolicyError
Can be invoked to create new instances of policy objects of a specific type with specified initial state. If create_policy fails to instantiate a new Policy object due to its inability to interpret the requested type and content of the policy, it raises the PolicyError exception with the appropriate reason.

Parameters:
type - the PolicyType of the policy object to be created
val - the value that will be used to set the initial state of the Policy object that is created
Returns:
Reference to a newly created Policy object of type specified by the type parameter and initialized to a state specified by the val parameter
Throws:
org.omg.CORBA.PolicyError - when the requested policy is not supported or a requested initial state for the policy is not supported.
PolicyError
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


org.omg.CORBA (Java 2 Platform SE v1.4.2)

 org.omg.CORBA
Interfaces
ARG_IN
ARG_INOUT
ARG_OUT
BAD_POLICY
BAD_POLICY_TYPE
BAD_POLICY_VALUE
CTX_RESTRICT_SCOPE
Current
CurrentOperations
CustomMarshal
DataInputStream
DataOutputStream
DomainManager
DomainManagerOperations
DynAny
DynArray
DynEnum
DynFixed
DynSequence
DynStruct
DynUnion
DynValue
IDLType
IDLTypeOperations
IRObject
IRObjectOperations
Object
OMGVMCID
Policy
PolicyOperations
PRIVATE_MEMBER
PUBLIC_MEMBER
UNSUPPORTED_POLICY
UNSUPPORTED_POLICY_VALUE
VM_ABSTRACT
VM_CUSTOM
VM_NONE
VM_TRUNCATABLE
Classes
_IDLTypeStub
_PolicyStub
Any
AnyHolder
AnySeqHelper
AnySeqHolder
BooleanHolder
BooleanSeqHelper
BooleanSeqHolder
ByteHolder
CharHolder
CharSeqHelper
CharSeqHolder
CompletionStatus
CompletionStatusHelper
Context
ContextList
CurrentHelper
CurrentHolder
DefinitionKind
DefinitionKindHelper
DoubleHolder
DoubleSeqHelper
DoubleSeqHolder
DynamicImplementation
Environment
ExceptionList
FieldNameHelper
FixedHolder
FloatHolder
FloatSeqHelper
FloatSeqHolder
IdentifierHelper
IDLTypeHelper
IntHolder
LocalObject
LongHolder
LongLongSeqHelper
LongLongSeqHolder
LongSeqHelper
LongSeqHolder
NamedValue
NameValuePair
NameValuePairHelper
NVList
ObjectHelper
ObjectHolder
OctetSeqHelper
OctetSeqHolder
ORB
ParameterMode
ParameterModeHelper
ParameterModeHolder
PolicyErrorCodeHelper
PolicyErrorHelper
PolicyErrorHolder
PolicyHelper
PolicyHolder
PolicyListHelper
PolicyListHolder
PolicyTypeHelper
Principal
PrincipalHolder
RepositoryIdHelper
Request
ServerRequest
ServiceDetail
ServiceDetailHelper
ServiceInformation
ServiceInformationHelper
ServiceInformationHolder
SetOverrideType
SetOverrideTypeHelper
ShortHolder
ShortSeqHelper
ShortSeqHolder
StringHolder
StringSeqHelper
StringSeqHolder
StringValueHelper
StructMember
StructMemberHelper
TCKind
TypeCode
TypeCodeHolder
ULongLongSeqHelper
ULongLongSeqHolder
ULongSeqHelper
ULongSeqHolder
UnionMember
UnionMemberHelper
UnknownUserExceptionHelper
UnknownUserExceptionHolder
UShortSeqHelper
UShortSeqHolder
ValueBaseHelper
ValueBaseHolder
ValueMember
ValueMemberHelper
VersionSpecHelper
VisibilityHelper
WCharSeqHelper
WCharSeqHolder
WrongTransactionHelper
WrongTransactionHolder
WStringSeqHelper
WStringSeqHolder
WStringValueHelper
Exceptions
BAD_CONTEXT
BAD_INV_ORDER
BAD_OPERATION
BAD_PARAM
BAD_TYPECODE
Bounds
COMM_FAILURE
DATA_CONVERSION
FREE_MEM
IMP_LIMIT
INITIALIZE
INTERNAL
INTF_REPOS
INV_FLAG
INV_IDENT
INV_OBJREF
INV_POLICY
INVALID_TRANSACTION
MARSHAL
NO_IMPLEMENT
NO_MEMORY
NO_PERMISSION
NO_RESOURCES
NO_RESPONSE
OBJ_ADAPTER
OBJECT_NOT_EXIST
PERSIST_STORE
PolicyError
SystemException
TRANSACTION_REQUIRED
TRANSACTION_ROLLEDBACK
TRANSIENT
UNKNOWN
UnknownUserException
UserException
WrongTransaction


org.omg.CORBA (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

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).

See:
Description

Interface Summary
ARG_IN | Signifies an "input" argument to an invocation, meaning that the argument is being passed from the client to the server.
ARG_INOUT | Signifies an argument used for both input and output in an invocation, meaning that the argument is being passed from the client to the server and then back from the server to the client.
ARG_OUT | A constant that signifies an "output" argument to an invocation, meaning that the argument is being passed from the server to the client.
BAD_POLICY | A PolicyErrorCode which would be filled in the PolicyError exception.
BAD_POLICY_TYPE | A PolicyErrorCode which would be filled in the PolicyError exception.
BAD_POLICY_VALUE | Contains the value used to indicate a policy value that is incorrect for a valid policy type in a call to the create_policy method defined in the ORB class.
CTX_RESTRICT_SCOPE | A flag that can be used as the second parameter to the method Context.get_values to restrict the search scope.
Current | Interfaces derived from the Current interface enable ORB and CORBA services to provide access to information (context) associated with the thread of execution in which they are running.
CurrentOperations | The interface for Current.
CustomMarshal | An abstract value type that is meant to be used by the ORB, not the user.
DataInputStream | Defines the methods used to read primitive data types from input streams for unmarshaling custom value types.
DataOutputStream | Defines the methods used to write primitive data types to output streams for marshalling custom value types.
DomainManager | Provides mechanisms for establishing and navigating relationships to superior and subordinate domains, as well as for creating and accessing policies.
DomainManagerOperations | Provides the DomainManager with the means to access policies.
DynAny | Enables org.omg.CORBA.Any values to be dynamically interpreted (traversed) and constructed.
DynArray | Represents a DynAny object associated with an array.
DynEnum | Represents a DynAny object associated with an IDL enum.
DynFixed | Represents a DynAny object that is associated with an IDL fixed type.
DynSequence | The representation of a DynAny object that is associated with an IDL sequence.
DynStruct | The representation of a DynAny object that is associated with an IDL struct.
DynUnion | The DynUnion interface represents a DynAny object that is associated with an IDL union.
DynValue | The representation of a DynAny object that is associated with an IDL value type.
IDLType | An abstract interface inherited by all Interface Repository (IR) objects that represent OMG IDL types.
IDLTypeOperations | This interface must be implemented by all IDLType objects.
IRObject | An IRObject IDL interface represents the most generic interface from which all other Interface Repository interfaces are derived, even the Repository itself.
IRObjectOperations | This is the Operations interface for the mapping from IRObject.
Object | The definition for a CORBA object reference.
OMGVMCID | The vendor minor code ID reserved for OMG.
Policy | Interfaces derived from the Policy interface allow an ORB or CORBA service access to certain choices that affect its operation.
PolicyOperations | Provides the operations for a Policy object.
PRIVATE_MEMBER | Constant to define a private member in the ValueMember class.
PUBLIC_MEMBER | Constant to define a public member in the ValueMember class.
UNSUPPORTED_POLICY | 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 | 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.
VM_ABSTRACT | Defines the code used to represent an Abstract interface in a typecode.
VM_CUSTOM | Defines the code used to represent a custom marshalled value type in a typecode.
VM_NONE | Defines the code used to represent the one of the values of a value type in a typecode.
VM_TRUNCATABLE | Defines the code used to represent a truncatable value type in a typecode.

Class Summary
_IDLTypeStub | The Stub for IDLType.
_PolicyStub | The Stub for Policy.
Any | Serves as a container for any data that can be described in IDL or for any IDL primitive type.
AnyHolder | The Holder for Any.
AnySeqHelper | The Helper for AnySeq.
AnySeqHolder | The Holder for AnySeq.
BooleanHolder | The Holder for Boolean.
BooleanSeqHelper | The Helper for BooleanSeq.
BooleanSeqHolder | The Holder for BooleanSeq.
ByteHolder | The Holder for Byte.
CharHolder | The Holder for Char.
CharSeqHelper | The Helper for CharSeq.
CharSeqHolder | The Holder for CharSeq.
CompletionStatus | An object that indicates whether a method had completed running when a SystemException was thrown.
CompletionStatusHelper | The Helper for CompletionStatus.
Context | An object used in Request operations to specify the context object in which context strings must be resolved before being sent along with the request invocation.
ContextList | An object containing a modifiable list of String objects that represent property names.
CurrentHelper | The Helper for Current.
CurrentHolder | The Holder for Current.
DefinitionKind | The class that provides the constants used to identify the type of an Interface Repository object.
DefinitionKindHelper | The Helper for DefinitionKind.
DoubleHolder | The Holder for Double.
DoubleSeqHelper | The Helper for DoubleSeq.
DoubleSeqHolder | The Holder for DoubleSeq.
DynamicImplementation | Deprecated. org.omg.CORBA.DynamicImplementation
Environment | A container (holder) for an exception that is used in Request operations to make exceptions available to the client.
ExceptionList | An object used in Request operations to describe the exceptions that can be thrown by a method.
FieldNameHelper | The Helper for FieldName.
FixedHolder | The Holder for Fixed.
FloatHolder | The Holder for Float.
FloatSeqHelper | The Helper for FloatSeq.
FloatSeqHolder | The Holder for FloatSeq.
IdentifierHelper | The Helper for Identifier.
IDLTypeHelper | The Helper for IDLType.
IntHolder | The Holder for Int.
LocalObject | Used as a base class for implementation of a local IDL interface in the Java language mapping.
LongHolder | The Holder for Long.
LongLongSeqHelper | The Helper for LongLongSeq.
LongLongSeqHolder | The Holder for LongLongSeq.
LongSeqHelper | The Helper for LongSeqHelper.
LongSeqHolder | The Holder for LongSeq.
NamedValue | An object used in the DII and DSI to describe arguments and return values.
NameValuePair | Associates a name with a value that is an attribute of an IDL struct, and is used in the DynStruct APIs.
NameValuePairHelper | The Helper for NameValuePair.
NVList | A modifiable list containing NamedValue objects.
ObjectHelper |
ObjectHolder | The Holder for Object.
OctetSeqHelper | The Helper for OctetSeq.
OctetSeqHolder | The Holder for OctetSeq.
ORB | A class providing APIs for the CORBA Object Request Broker features.
ParameterMode | Enumeration of parameter modes for Parameter.
ParameterModeHelper | Enumeration of parameter modes for Parameter.
ParameterModeHolder | Enumeration of parameter modes for Parameter.
PolicyErrorCodeHelper | Encapsulates a reason a Policy may be invalid.
PolicyErrorHelper | Thrown to indicate problems with parameter values passed to the ORB.create_policy operation.
PolicyErrorHolder | Thrown to indicate problems with parameter values passed to the ORB.create_policy operation.
PolicyHelper | The Helper for Policy.
PolicyHolder | The Holder for Policy.
PolicyListHelper | The Helper for PolicyList.
PolicyListHolder | The Holder for PolicyList.
PolicyTypeHelper | The Helper for PolicyType.
Principal | Deprecated. Deprecated by CORBA 2.2.
PrincipalHolder | Deprecated. Deprecated by CORBA 2.2.
RepositoryIdHelper | The Helper for RepositoryId.
Request | An object containing the information necessary for invoking a method.
ServerRequest | An object that captures the explicit state of a request for the Dynamic Skeleton Interface (DSI).
ServiceDetail | 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.
ServiceDetailHelper |
ServiceInformation | 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.
ServiceInformationHelper |
ServiceInformationHolder | The Holder for ServiceInformation.
SetOverrideType | 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.
SetOverrideTypeHelper | The Helper for SetOverrideType.
ShortHolder | The Holder for Short.
ShortSeqHelper | The Helper for ShortSeqHelper.
ShortSeqHolder | The Holder for ShortSeq.
StringHolder | The Holder for String.
StringSeqHelper | An array of Strings
StringSeqHolder | An array of Strings
StringValueHelper | The Helper for StringValue.
StructMember | 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.
StructMemberHelper | The Helper for StructMember.
TCKind | The Java mapping of the IDL enum TCKind, which specifies the kind of a TypeCode object.
TypeCode | A container for information about a specific CORBA data type.
TypeCodeHolder | The Holder for TypeCode.
ULongLongSeqHelper | The Helper for ULongLongSeq.
ULongLongSeqHolder | The Holder for ULongLongSeq.
ULongSeqHelper | The Helper for ULongSeq.
ULongSeqHolder | The Holder for ULongSeq.
UnionMember | A description in the Interface Repository of a member of an IDL union.
UnionMemberHelper | The Helper for UnionMember.
UnknownUserExceptionHelper | The Helper for UnknownUserException.
UnknownUserExceptionHolder | The Holder for UnknownUserException.
UShortSeqHelper | The Helper for UShortSeq.
UShortSeqHolder | The Holder for UShortSeq.
ValueBaseHelper |
ValueBaseHolder | The Holder for ValueBase.
ValueMember | A description in the Interface Repository of a member of a value object.
ValueMemberHelper | The Helper for ValueMember.
VersionSpecHelper | The Helper for VersionSpec.
VisibilityHelper | The Helper for Visibility.
WCharSeqHelper | The Helper for WCharSeq.
WCharSeqHolder | The Holder for WCharSeq.
WrongTransactionHelper | The Helper for WrongTransaction.
WrongTransactionHolder | The Holder for WrongTransaction.
WStringSeqHelper | An array of WStrings
WStringSeqHolder | An array of WStrings
WStringValueHelper | 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

Exception Summary
BAD_CONTEXT | Exception thrown when an operation is invoked by a client but the passed context does not contain the context values required by the operation.
BAD_INV_ORDER | This exception indicates that the caller has invoked operations in the wrong order.
BAD_OPERATION | Exception thrown when an object reference denotes an existing object, but that the object does not support the operation that was invoked.
BAD_PARAM | Exception thrown when a parameter passed to a call is out of range or otherwise considered illegal.
BAD_TYPECODE | Exception thrown when the ORB has encountered a malformed type code (for example, a type code with an invalid TCKind value).
Bounds | A user exception thrown when a parameter is not within the legal bounds for the object that a method is trying to access.
COMM_FAILURE | This exception is raised if communication is lost while an operation is in progress, after the request was sent by the client, but before the reply from the server has been returned to the client.
DATA_CONVERSION | This exception is raised if an ORB cannot convert the representation of data as marshaled into its native representation or vice-versa.
FREE_MEM | Exception thrown when the ORB failed in an attempt to free dynamic memory, for example because of heap corruption or memory segments being locked.
IMP_LIMIT | This exception indicates that an implementation limit was exceeded in the ORB run time.
INITIALIZE | Exception thrown when an ORB has encountered a failure during its initialization, such as failure to acquire networking resources or detecting a configuration error.
INTERNAL | This exception indicates an internal failure in an ORB, for example, if an ORB has detected corruption of its internal data structures.
INTF_REPOS | Exception raised when an ORB cannot reach the interface repository, or some other failure relating to the interface repository is detected.
INV_FLAG | Exception thrown when an invalid flag was passed to an operation (for example, when creating a DII request).
INV_IDENT | This exception indicates that an IDL identifier is syntactically invalid.
INV_OBJREF | This exception indicates that an object reference is internally malformed.
INV_POLICY | Standard exception thrown when an invocation cannot be made because of an incompatibility between Policy overrides that apply to the particular invocation.
INVALID_TRANSACTION | Exception thrown when the request carried an invalid transaction context.
MARSHAL | A request or reply from the network is structurally invalid.
NO_IMPLEMENT | This exception indicates that even though the operation that was invoked exists (it has an IDL definition), no implementation for that operation exists.
NO_MEMORY | Exception thrown when the ORB run time has run out of memory.
NO_PERMISSION | Exception thrown when an invocation failed because the caller has insufficient privileges.
NO_RESOURCES | Exception thrown when the ORB has encountered some general resource limitation.
NO_RESPONSE | 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.
OBJ_ADAPTER | 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.
OBJECT_NOT_EXIST | Exception raised whenever an invocation on a deleted object was performed.
PERSIST_STORE | This exception indicates a persistent storage failure, for example, failure to establish a database connection or corruption of a database.
PolicyError | A user exception thrown when a policy error occurs.
SystemException | The root class for all CORBA standard exceptions.
TRANSACTION_REQUIRED | Exception indicates that the request carried a null transaction context, but an active transaction is required.
TRANSACTION_ROLLEDBACK | Exception thrown when the transaction associated with the request has already been rolled back or marked to roll back.
TRANSIENT | Exception thrown when the ORB attempted to reach an object and failed.
UNKNOWN | 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.
UnknownUserException | A class that contains user exceptions returned by the server.
UserException | The root class for CORBA IDL-defined user exceptions.
WrongTransaction | The CORBA WrongTransaction user-defined exception.

Package org.omg.CORBA Description

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).

For a precise list of supported sections of official CORBA specifications with which the Java 2 Platform, Standard Edition, v.1.4 complies, see Official Specifications for CORBA support in J2SE 1.4.

General Information

The information in this section is information relevant to someone who compiles Interface Definition Language (IDL) files and uses the ORB to write clients and servers.

The classes and interfaces described in this section can be put into four groups: ORB classes, Exceptions, Helper classes, and Holder classes.

The ORB Class

An ORB handles (or brokers) method invocations between a client and the method's implementation on a server. Because the client and server may be anywhere on a network, and because the invocation and implementation may be written in different programming languages, an ORB does a great deal of work behind the scenes to accomplish this communication.

Most of what an ORB does is completely transparent to the user, and a major portion of the CORBA package consists of classes used by the ORB behind the scenes. The result is that most programmers will use only a small part of this package directly. In fact, most programmers will use only a few methods from the ORB class, some exceptions, and occasionally, a holder class.

ORB Methods

Before an application can enter the CORBA environment, it must first:

  • Be initialized into the ORB and possibly the object adapter (POA) environments.
  • Get references to ORB object (for use in future ORB operations) and perhaps other objects (including the root POA or some Object Adapter objects).

The following operations are provided to initialize applications and obtain the appropriate object references:

  • Operations providing access to the ORB, which are discussed in this section.
  • Operations providing access to Object Adapters, Interface Repository, Naming Service, and other Object Services. These operations are described in Other Classes.

When an application requires a CORBA environment it needs a mechanism to get an ORB object reference and possibly an OA object reference (such as the root POA). This serves two purposes. First, it initializes an application into the ORB and OA environments. Second, it returns the ORB object reference and the OA object reference to the application for use in future ORB and OA operations.

In order to obtain an ORB object reference, applications call the ORB.init operation. The parameters to the call can comprise an identifier for the ORB for which the object reference is required, and an arg_list, which is used to allow environment-specific data to be passed into the call.

These are the ORB methods that provide access to the ORB:

  • init()
  • init(String [] args, Properties props)
  • init(Applet app, Properties props)

Using the init() method without parameters initiates a singleton ORB, which can only give typecode creation anys needed in code generated in Helper classes by idlj.

Applications require a portable means by which to obtain their initial object references. References are required for the root POA, POA Current, Interface Repository, and various Object Services instances. The functionality required by the application is similar to that provided by the Naming Service. However, the OMG does not want to mandate that the Naming Service be made available to all applications in order that they may be portably initialized. Consequently, the operations shown in this section provide a simplified, local version of the Naming Service that applications can use to obtain a small, defined set of object references which are essential to its operation. Because only a small well-defined set of objects are expected with this mechanism, the naming context can be flattened to be a single-level name space. This simplification results in only two operations being defined to achieve the functionality required.

Initial references are obtained via two operations provided in the ORB object interface, providing facilities to list and resolve initial object references. These are:

  • resolve_initial_references(String name)
  • list_initial_services()
  • register_initial_reference(String id, org.omg.CORBA.Object obj)

An example that uses some of these methods is Getting Started with Java IDL.

Exceptions

Exceptions in Java IDL are similar to those in any code written in the Java programming language. If a method is defined to throw an exception, then any code using that method must have a try/catch block and handle that exception when it is thrown.

The documentation on Java IDL exceptions has more information and explains the difference between system exceptions and user-defined exceptions.

The following is a list of the system exceptions (which are unchecked exceptions inheriting through org.omg.CORBA.SystemException from java.lang.RuntimeException) that are defined in the package org.omg.CORBA:

        BAD_CONTEXT
        BAD_INV_ORDER
        BAD_OPERATION
        BAD_PARAM
        BAD_TYPECODE
        COMM_FAILURE
        DATA_CONVERSION
        FREE_MEM
        IMP_LIMIT
        INITIALIZE
        INTERNAL
        INTF_REPOS
        INVALID_TRANSACTION
        INV_FLAG
        INV_IDENT
        INV_OBJREF
        INV_POLICY
        MARSHAL
        NO_IMPLEMENT
        NO_MEMORY
        NO_PERMISSION
        NO_RESOURCES
        NO_RESPONSE
        OBJECT_NOT_EXIST
        OBJ_ADAPTER
        PERSIST_STORE
        TRANSACTION_REQUIRED
        TRANSACTION_ROLLEDBACK
        TRANSIENT
        UNKNOWN

The following is a list of user-defined exceptions defined in the package org.omg.CORBA.

        Bounds
        UnknownUserException
        WrongTransaction
        PolicyError

Subpackages

There are some packages inside the CORBA package with "Package" as part of their names. These packages are generally quite small because all they do is provide exceptions or classes for use by interfaces and classes in the CORBA package.

For example, the package org.omg.CORBA.TypeCodePackage contains two exceptions thrown by methods in the class TypeCode. These exceptions are:

  • BadKind
  • Bounds
The package org.omg.CORBA.ORBPackage contains two exceptions:
  • InvalidName
  • InconsistentTypeCode

Another package that is a subpackage of CORBA is the portable package. It provides a set of ORB APIs that makes it possible for code generated by one vendor's IDL compiler to run on another vendor's ORB.

Holder classes

Support for out and inout parameter passing modes requires the use of additional holder classes. Because the Java programming language does not support out or inout parameters, holder classes are needed as a means of passing a parameter that can be modified. To support portable stubs and skeletons, holder classes also implement the org.omg.CORBA.portable.Streamable interface.

Holder classes are named by appending "Holder" to the name of the type. The name of the type refers to its name in the Java programming language. For example, a holder class for the interface named Account in the Java programming language would be named AccountHolder.

Holder classes are available for all of the basic IDL datatypes in the org.omg.CORBA package. So, for example, there are already-defined classes for LongHolder, ShortHolder, FloatHolder, and so on. Classes are also generated for all named user-defined IDL types except those defined by typedefs. (Note that in this context user defined includes types that are defined in OMG specifications such as those for the Interface Repository, and other OMG services.)

Each holder class has:

  • a constructor from an instance
  • a default constructor
  • a public instance member, value which is the typed value.
  • a method for reading an input stream and assigning the contents to the type's value field
  • a method for writing the value of the value field to an output stream
  • a method for getting the typecode of the type

The default constructor sets the value field to the default value for the type as defined by the Java language:

  • false for boolean
  • 0 for numeric and char types
  • null for strings and object references

As an example, if the interface Account, defined in OMG IDL, were mapped to the Java programming language, the following holder class would be generated:

public final class AccountHolder implements
    org.omg.CORBA.portable.Streamable
{
  // field that holds an Account object
  public Account value = null;

  // default constructor
  public AccountHolder ()
  {
  }

  // creates a new AccountHolder from initialValue
  public AccountHolder (Account initialValue)
  {
    value = initialValue;
  }

  // reads the contents of i and assigns the contents to value
  public void _read (org.omg.CORBA.portable.InputStream i)
  {
    value = AccountHelper.read (i);
  }

  // writes value to o
  public void _write (org.omg.CORBA.portable.OutputStream o)
  {
    AccountHelper.write (o, value);
  }

  // returns the typecode for Account
  public org.omg.CORBA.TypeCode _type ()
  {
    return AccountHelper.type ();
  }

}

For more information on Holder classes, see Chapter 1.4, Mapping for Basic Types in the OMG IDL to Java Language Mapping. The Holder classes defined in the package org.omg.CORBA are:

     AnyHolder
     AnySeqHolder
     BooleanHolder
     BooleanSeqHolder
     ByteHolder
     CharHolder
     CharSeqHolder
     CurrentHolder
     DoubleHolder
     DoubleSeqHolder
     FixedHolder
     FloatHolder
     FloatSeqHolder
     IntHolder
     LongHolder
     LongLongSeqHolder
     LongSeqHolder
     ObjectHolder
     OctetSeqHolder
     ParameterModeHolder
     PolicyErrorHolder
     PolicyListHolder
     PrincipalHolder
     ServiceInformationHolder
     ShortHolder
     ShortSeqHolder
     StringHolder
     StringSeqHolder
     TypeCodeHolder
     ULongLongSeqHolder
     ULongSeqHolder
     UnknownUserExceptionHolder
     UShortSeqHolder
     ValueBaseHolder
     WCharSeqHolder
     WrongTransactionHolder
     WStringSeqHolder

Helper Classes

Helper files supply several static methods needed to manipulate the type. These include:

  • Any insert and extract operations for the type
  • getting the repository id
  • getting the typecode
  • reading and writing the type from and to a stream
  • implement the ValueHelper interface (if it is a user-defined value type)

The helper class for a mapped IDL interface or abstract interface also include narrow operation(s). The static narrow method allows an org.omg.CORBA.Object to be narrowed to the object reference of a more specific type. The IDL exception CORBA.BAD_PARAM is thrown if the narrow fails because the object reference does not support the requested type. A different system exception is raised to indicate other kinds of errors. Trying to narrow a null will always succeed with a return value of null. Generally, the only helper method an application programmer uses is the narrow method. The other methods are normally used behind the scenes and are transparent to the programmer.

Helper classes fall into two broad categories, helpers for value types and helpers for non value types. Because all of the helper classes in one category provide the same methods, one generic explanation of each category of helper classes is presented here.

When OMG IDL is mapped to the Java programming language, a "helper" class is generated for each user-defined type. This generated class will have the name of the user-defined type with the suffix Helper appended. For example, if the interface Account is defined in OMG IDL, the idlj compiler will automatically generate a class named AccountHelper. The AccountHelper class will contain the static methods needed for manipulating instances of the type, in this case, Account objects.

The narrow Method

When an object is the return value for a method, it is returned in the form of a generic object, either an org.omg.CORBA.Object object or a java.lang.Object object. This object must be cast to its more specific type before it can be operated on. For example, an Account object will be returned as a generic object and must be narrowed to an Account object so that Account methods may be called on it.

The narrow method has two forms, one that takes an org.omg.CORBA.Object object and one that takes a java.lang.Object object. Whether the interface is abstract or not determines which narrow method its helper class will provide. The helper class for an interface that is not abstract will have a narrow method that takes a CORBA object, whereas the narrow method for an interface that is abstract will take an object in the Java programming language. The helper class for a non-abstract interface that has at least one abstract base interface will provide both versions of the narrow method.

The Hello World tutorial uses a narrow method that looks like this:

        // 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 latest Inter-Operable naming Service.
        NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);

        // resolve the Object Reference in Naming
        String name = "Hello";
        helloImpl = HelloHelper.narrow(ncRef.resolve_str(name));

Example of a Basic Helper Class

A basic helper class, for purposes of this explanation, is one with the methods that are provided by every helper class, plus a narrow method if the type defined in OMG IDL maps to an interface in the Java programming language. Types that are not value types will have a basic helper class generated for them.

For example, assuming that the interface Account is not a value type IDL type and is also not an abstract interface and has no abstract base interfaces, its AccountHelper class will look like this:

abstract public class AccountHelper
{
  private static String  _id = "IDL:Account:1.0";

  // inserts an Account object into an Any object
  public static void insert (org.omg.CORBA.Any a, Account 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 ());
  }

  // extracts an Account object from an Any object
  public static Account extract (org.omg.CORBA.Any a)
  {
    return read (a.create_input_stream ());
  }

  private static org.omg.CORBA.TypeCode __typeCode = null;
  // gets the typecode for this type
  synchronized public static org.omg.CORBA.TypeCode type ()
  {
    if (__typeCode == null)
    {
      __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (AccountHelper.id (), "Account");
    }
    return __typeCode;
  }

  // gets the repository id for this type
  public static String id ()
  {
    return _id;
  }

  // reads an Account object from an input stream
  public static Account read (org.omg.CORBA.portable.InputStream istream)
  {
    return narrow (istream.read_Object (_AccountStub.class));
  }

  // writes an Account object to an outputstream
  public static void write (org.omg.CORBA.portable.OutputStream ostream, Account value)
  {
    ostream.write_Object ((org.omg.CORBA.Object) value);
  }

  // converts (narrows) an Object to an Account object
  public static Account narrow (org.omg.CORBA.Object obj)
  {
    if (obj == null)
      return null;
    else if (obj instanceof Account)
      return (Account)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 ();
      _AccountStub stub = new _AccountStub ();
      stub._set_delegate(delegate);
      return stub;
    }
  }

}

Value Type Helper Classes

A helper class for a value type includes different renderings of the same methods generated for non-value type methods. The main difference is that value types are types that can be passed by value as parameters or return values of a method, which means that they must be serializable.

Assuming that Address is a value type, the AddressHelper class will look like this:

abstract public class AddressHelper
{
  private static String  _id = "IDL:Address:1.0";

  // same as for non-value type
  public static void insert (org.omg.CORBA.Any a, Address 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 ());
  }

  // same as for non-value type
  public static Address extract (org.omg.CORBA.Any a)
  {
    return read (a.create_input_stream ());
  }

  private static org.omg.CORBA.TypeCode __typeCode = null;
  private static boolean __active = false;

  // getting the typecode for the type
  synchronized public static org.omg.CORBA.TypeCode type ()
  {
    if (__typeCode == null)
    {
      synchronized (org.omg.CORBA.TypeCode.class)
      {
        if (__typeCode == null)
        {
          if (__active)
          {
            return org.omg.CORBA.ORB.init().create_recursive_tc ( _id );
          }
          __active = true;
          org.omg.CORBA.ValueMember[] _members0 = new org.omg.CORBA.ValueMember[0];
          org.omg.CORBA.TypeCode _tcOf_members0 = null;
          __typeCode = org.omg.CORBA.ORB.init ().create_value_tc (_id, "Address", org.omg.CORBA.VM_NONE.value, null, _members0);
          __active = false;
        }
      }
    }
    return __typeCode;
  }

  // same as for non-value type
  public static String id ()
  {
    return _id;
  }

  // reads a serializable instance of Address from the given input stream
  public static Address read (org.omg.CORBA.portable.InputStream istream)
  {
    return (Address)((org.omg.CORBA_2_3.portable.InputStream) istream).read_value (id ());
  }

  // writes a serializable instance of Address to the given output stream
  public static void write (org.omg.CORBA.portable.OutputStream ostream, Address value)
  {
    ((org.omg.CORBA_2_3.portable.OutputStream) ostream).write_value (value, id ());
  }

}

The Helper classes defined in the package org.omg.CORBA are:

     AnySeqHelper
     BooleanSeqHelper
     CharSeqHelper
     CompletionStatusHelper
     CurrentHelper
     DefinitionKindHelper
     DoubleSeqHelper
     FieldNameHelper
     FloatSeqHelper
     IdentifierHelper
     IDLTypeHelper
     LongLongSeqHelper
     LongSeqHelper
     NameValuePairHelper
     ObjectHelper
     OctetSeqHelper
     ParameterModeHelper
     PolicyErrorCodeHelper
     PolicyErrorHelper
     PolicyHelper
     PolicyListHelper
     PolicyTypeHelper
     RepositoryIdHelper
     ServiceDetailHelper
     ServiceInformationHelper
     SetOverrideTypeHelper
     ShortSeqHelper
     StringSeqHelper
     StringValueHelper
     StructMemberHelper
     ULongLongSeqHelper
     ULongSeqHelper
     UnionMemberHelper
     UnknownUserExceptionHelper
     UShortSeqHelper
     ValueBaseHelper
     ValueMemberHelper
     VersionSpecHelper
     VisibilityHelper
     WCharSeqHelper
     WrongTransactionHelper
     WStringSeqHelper
     WStringValueHelper

Other Classes

The other classes and interfaces in the CORBA package, which are used behind the scenes, can be put into four groups. Three of the groups are used with requests in some capacity, and the fourth group, concerning the Interface Repository, is a category by itself.

Classes Created by an ORB

The first group contains classes that are created by an ORB and contain information used in request operations.
  • TCKind -- indicates the kind (datatype) for a TypeCode object
  • TypeCode -- indicates a datatype and possibly other information
  • Any -- contains a value and its typecode
  • NamedValue -- contains a name, an Any object, and an argument mode flag. NamedValue objects contain information about method arguments, method return values, or a context.
  • ContextList -- a list of strings that describe the contexts that need to be resolved and sent with an invocation
  • ExceptionList -- a list of TypeCodes for exceptions that may be thrown by a method
  • Environment -- a container for the exception thrown during a method invocation
  • Context -- a list of NamedValue objects used to pass auxiliary information from client to server
  • NVList -- a list of NamedValue objects, used to pass arguments or get results

Classes That Deal with Requests

The second group of classes deals with requests:
  • Object -- the base class for all CORBA object references
  • Request -- the main class in the DII, which contains methods for adding arguments to the request, for accessing information about the method being invoked (the method name, its arguments, exceptions it throws, and so on), and for making invocations on the request
  • DynamicImplementation -- the base class for server implementations using the DSI. It has the method invoke, which is used by an implementation of this class to determine the state of a ServerRequest object and to set its result or exception
  • ServerRequest -- captures the explicit state of a request for the Dynamic Skeleton Interface

Interfaces That Serve as Constants

The third group contains interfaces that serve as constants. The IDL-to-Java mapping mandates that IDL enums are mapped to a Java class with the enumerated values represented as public static final fields in that class (e.g. DefinitionKind). On the other hand IDL constants defined outside of an IDL interface are mapped to a Java interface for each constant.

This is why several interfaces in the org.omg.CORBA package consist of a single field, value, which is a short. This field is a constant used for such things as an error code or value modifier. For example, the value field of the interface BAD_POLICY is one of the possible reasons for the exception PolicyError to be thrown. To specify this error code, you would use BAD_POLICY.value.

The exception PolicyError uses the value field of the following interfaces as its possible error codes.

  • BAD_POLICY
  • BAD_POLICY_TYPE
  • BAD_POLICY_VALUE
  • UNSUPPORTED_POLICY
  • UNSUPPORTED_POLICY_VALUE
The method TypeCode.type_modifier returns the value field of one of the following interfaces. The VM in the names of these interfaces stands for "value modifier."
  • VM_NONE
  • VM_ABSTRACT
  • VM_CUSTOM
  • VM_TRUNCATABLE
The following constants are returned by a ValueMember object's access method to denote the visibility of the ValueMember object.
  • PRIVATE_MEMBER
  • PUBLIC_MEMBER
These flags, used in NamedValue objects or as parameters to methods, are defined in the following interfaces:
  • ARG_IN
  • ARG_INOUT
  • ARG_OUT
  • CTX_RESTRICT_SCOPE

Interface Repository Interfaces and Classes

A fourth group contains the Interface Repository interfaces and classes, which are generated by the idlj compiler from the OMG IDL interface ir.idl. The purpose of the Interface Repository is to identify the interfaces stored in it so that they can be accessed by an ORB. Each module, type, interface, attribute, operation, parameter, exception, constant, and so on is described completely by the Interface Repository API.

An ORB does not require that there be an interface repository, and Java IDL does not include one. Even though this release does not include an implementation of an interface repository, the following IR classes and interfaces have been included for the purpose of creating typecodes (see create_value_tc, create_struct_tc, create_union_tc and create_exception_tc methods in interface org.omg.CORBA.ORB):
&nbs

  • IRObject
  • IDLType
  • DefinitionKind
  • StructMember
  • UnionMember
  • ValueMember

Related Documentation

For overviews, guides, and a tutorial, please see:
  • Java IDL home page

CORBA Features Not Implemented in Java IDL

Some of the API included in org.omg subpackages is provided for conformance with the current OMG CORBA specification but is not implemented in Sun's release of the JDKTM. This enables other JDK licensees to provide implementations of this API in standard extensions and products.

Features That Throw NO_IMPLEMENT

Some of the API included in org.omg subpackages throw NO_IMPLEMENT exceptions for various reasons. Among these reasons are:

  • In some cases, for example LocalObject, the complete implementation according to the specification indicates that these API should throw NO_IMPLEMENT.

  • In most cases, for example methods in ORB.java, methods that throw NO_IMPLEMENT are actually implemented in subclasses elsewhere in the ORB code.

  • In some cases, for example _get_interface_def() and _get_interface, API are really not yet implemented.

General Summary of Features or API Not Implemented in This Release:

  • Interface Repository. An Interface Repository is not required for normal operation of Java IDL.
  • Java IDL does not support long double.
  • Policies (org.omg.CORBA.Policy) and methods for getting them are not implemented.
  • Domain managers (org.omg.CORBA.DomainManager) and methods for getting them are not implemented.
  • Service Information org.omg.CORBA.ServiceInformation and ORB method public boolean get_service_information(short service_type, ServiceInformationHolder service_info) are not implemented.
  • ORB methods for supporting single-threading (perform_work, work_pending) are not implemented.
  • IDL contexts.

Specific List of Unimplemented Features in Package org.omg.CORBA

Unimplemented Methods in package org.omg.CORBA:

  • ORB
    • public org.omg.CORBA.Policy create_policy(int type, org.omg.CORBA.Any val)
    • public void perform_work()
    • public boolean work_pending()
    • public org.omg.CORBA.Current get_current()
    • create_operation_list
    • get_default_context
    • get_service_information
    • obsolete DynAnys (deprecated in favor of DynamicAny package)

Since:
JDK1.2
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


org.omg.CORBA Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package org.omg.CORBA

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class org.omg.CORBA.Any (implements org.omg.CORBA.portable.IDLEntity)
    • class org.omg.CORBA.AnyHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CORBA.AnySeqHelper
    • class org.omg.CORBA.AnySeqHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CORBA.BooleanHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CORBA.BooleanSeqHelper
    • class org.omg.CORBA.BooleanSeqHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CORBA.ByteHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CORBA.CharHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CORBA.CharSeqHelper
    • class org.omg.CORBA.CharSeqHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CORBA.CompletionStatus (implements org.omg.CORBA.portable.IDLEntity)
    • class org.omg.CORBA.CompletionStatusHelper
    • class org.omg.CORBA.Context
    • class org.omg.CORBA.ContextList
    • class org.omg.CORBA.CurrentHelper
    • class org.omg.CORBA.CurrentHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CORBA.DefinitionKind (implements org.omg.CORBA.portable.IDLEntity)
    • class org.omg.CORBA.DefinitionKindHelper
    • class org.omg.CORBA.DoubleHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CORBA.DoubleSeqHelper
    • class org.omg.CORBA.DoubleSeqHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CORBA.Environment
    • class org.omg.CORBA.ExceptionList
    • class org.omg.CORBA.FieldNameHelper
    • class org.omg.CORBA.FixedHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CORBA.FloatHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CORBA.FloatSeqHelper
    • class org.omg.CORBA.FloatSeqHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CORBA.IdentifierHelper
    • class org.omg.CORBA.IDLTypeHelper
    • class org.omg.CORBA.IntHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CORBA.LocalObject (implements org.omg.CORBA.Object)
    • class org.omg.CORBA.LongHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CORBA.LongLongSeqHelper
    • class org.omg.CORBA.LongLongSeqHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CORBA.LongSeqHelper
    • class org.omg.CORBA.LongSeqHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CORBA.NamedValue
    • class org.omg.CORBA.NameValuePair (implements org.omg.CORBA.portable.IDLEntity)
    • class org.omg.CORBA.NameValuePairHelper
    • class org.omg.CORBA.NVList
    • class org.omg.CORBA.ObjectHelper
    • class org.omg.CORBA.ObjectHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CORBA.portable.ObjectImpl (implements org.omg.CORBA.Object)
      • class org.omg.CORBA._IDLTypeStub (implements org.omg.CORBA.IDLType)
      • class org.omg.CORBA._PolicyStub (implements org.omg.CORBA.Policy)
      • class org.omg.CORBA.DynamicImplementation
    • class org.omg.CORBA.OctetSeqHelper
    • class org.omg.CORBA.OctetSeqHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CORBA.ORB
    • class org.omg.CORBA.ParameterMode (implements org.omg.CORBA.portable.IDLEntity)
    • class org.omg.CORBA.ParameterModeHelper
    • class org.omg.CORBA.ParameterModeHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CORBA.PolicyErrorCodeHelper
    • class org.omg.CORBA.PolicyErrorHelper
    • class org.omg.CORBA.PolicyErrorHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CORBA.PolicyHelper
    • class org.omg.CORBA.PolicyHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CORBA.PolicyListHelper
    • class org.omg.CORBA.PolicyListHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CORBA.PolicyTypeHelper
    • class org.omg.CORBA.Principal
    • class org.omg.CORBA.PrincipalHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CORBA.RepositoryIdHelper
    • class org.omg.CORBA.Request
    • class org.omg.CORBA.ServerRequest
    • class org.omg.CORBA.ServiceDetail (implements org.omg.CORBA.portable.IDLEntity)
    • class org.omg.CORBA.ServiceDetailHelper
    • class org.omg.CORBA.ServiceInformation (implements org.omg.CORBA.portable.IDLEntity)
    • class org.omg.CORBA.ServiceInformationHelper
    • class org.omg.CORBA.ServiceInformationHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CORBA.SetOverrideType (implements org.omg.CORBA.portable.IDLEntity)
    • class org.omg.CORBA.SetOverrideTypeHelper
    • class org.omg.CORBA.ShortHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CORBA.ShortSeqHelper
    • class org.omg.CORBA.ShortSeqHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CORBA.StringHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CORBA.StringSeqHelper
    • class org.omg.CORBA.StringSeqHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CORBA.StringValueHelper (implements org.omg.CORBA.portable.BoxedValueHelper)
    • class org.omg.CORBA.StructMember (implements org.omg.CORBA.portable.IDLEntity)
    • class org.omg.CORBA.StructMemberHelper
    • class org.omg.CORBA.TCKind
    • class java.lang.Throwable (implements java.io.Serializable)
      • class java.lang.Exception
        • class java.lang.RuntimeException
          • class org.omg.CORBA.SystemException
            • class org.omg.CORBA.BAD_CONTEXT
            • class org.omg.CORBA.BAD_INV_ORDER
            • class org.omg.CORBA.BAD_OPERATION
            • class org.omg.CORBA.BAD_PARAM
            • class org.omg.CORBA.BAD_TYPECODE
            • class org.omg.CORBA.COMM_FAILURE
            • class org.omg.CORBA.DATA_CONVERSION
            • class org.omg.CORBA.FREE_MEM
            • class org.omg.CORBA.IMP_LIMIT
            • class org.omg.CORBA.INITIALIZE
            • class org.omg.CORBA.INTERNAL
            • class org.omg.CORBA.INTF_REPOS
            • class org.omg.CORBA.INV_FLAG
            • class org.omg.CORBA.INV_IDENT
            • class org.omg.CORBA.INV_OBJREF
            • class org.omg.CORBA.INV_POLICY
            • class org.omg.CORBA.INVALID_TRANSACTION
            • class org.omg.CORBA.MARSHAL
            • class org.omg.CORBA.NO_IMPLEMENT
            • class org.omg.CORBA.NO_MEMORY
            • class org.omg.CORBA.NO_PERMISSION
            • class org.omg.CORBA.NO_RESOURCES
            • class org.omg.CORBA.NO_RESPONSE
            • class org.omg.CORBA.OBJ_ADAPTER
            • class org.omg.CORBA.OBJECT_NOT_EXIST
            • class org.omg.CORBA.PERSIST_STORE
            • class org.omg.CORBA.TRANSACTION_REQUIRED
            • class org.omg.CORBA.TRANSACTION_ROLLEDBACK
            • class org.omg.CORBA.TRANSIENT
            • class org.omg.CORBA.UNKNOWN
        • class org.omg.CORBA.UserException (implements org.omg.CORBA.portable.IDLEntity)
          • class org.omg.CORBA.Bounds
          • class org.omg.CORBA.PolicyError
          • class org.omg.CORBA.UnknownUserException
          • class org.omg.CORBA.WrongTransaction
    • class org.omg.CORBA.TypeCode (implements org.omg.CORBA.portable.IDLEntity)
    • class org.omg.CORBA.TypeCodeHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CORBA.ULongLongSeqHelper
    • class org.omg.CORBA.ULongLongSeqHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CORBA.ULongSeqHelper
    • class org.omg.CORBA.ULongSeqHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CORBA.UnionMember (implements org.omg.CORBA.portable.IDLEntity)
    • class org.omg.CORBA.UnionMemberHelper
    • class org.omg.CORBA.UnknownUserExceptionHelper
    • class org.omg.CORBA.UnknownUserExceptionHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CORBA.UShortSeqHelper
    • class org.omg.CORBA.UShortSeqHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CORBA.ValueBaseHelper
    • class org.omg.CORBA.ValueBaseHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CORBA.ValueMember (implements org.omg.CORBA.portable.IDLEntity)
    • class org.omg.CORBA.ValueMemberHelper
    • class org.omg.CORBA.VersionSpecHelper
    • class org.omg.CORBA.VisibilityHelper
    • class org.omg.CORBA.WCharSeqHelper
    • class org.omg.CORBA.WCharSeqHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CORBA.WrongTransactionHelper
    • class org.omg.CORBA.WrongTransactionHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CORBA.WStringSeqHelper
    • class org.omg.CORBA.WStringSeqHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CORBA.WStringValueHelper (implements org.omg.CORBA.portable.BoxedValueHelper)

Interface Hierarchy

  • interface org.omg.CORBA.ARG_IN
  • interface org.omg.CORBA.ARG_INOUT
  • interface org.omg.CORBA.ARG_OUT
  • interface org.omg.CORBA.BAD_POLICY
  • interface org.omg.CORBA.BAD_POLICY_TYPE
  • interface org.omg.CORBA.BAD_POLICY_VALUE
  • interface org.omg.CORBA.CTX_RESTRICT_SCOPE
  • interface org.omg.CORBA.CurrentOperations
    • interface org.omg.CORBA.Current (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CORBA.Object)
  • interface org.omg.CORBA.CustomMarshal
  • interface org.omg.CORBA.DomainManagerOperations
    • interface org.omg.CORBA.DomainManager (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CORBA.Object)
  • interface org.omg.CORBA.IRObjectOperations
    • interface org.omg.CORBA.IDLTypeOperations
      • interface org.omg.CORBA.IDLType (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CORBA.IRObject)
    • interface org.omg.CORBA.IRObject (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CORBA.Object)
      • interface org.omg.CORBA.IDLType (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CORBA.IDLTypeOperations)
  • interface org.omg.CORBA.Object
    • interface org.omg.CORBA.Current (also extends org.omg.CORBA.CurrentOperations, org.omg.CORBA.portable.IDLEntity)
    • interface org.omg.CORBA.DomainManager (also extends org.omg.CORBA.DomainManagerOperations, org.omg.CORBA.portable.IDLEntity)
    • interface org.omg.CORBA.DynAny
      • interface org.omg.CORBA.DynArray (also extends org.omg.CORBA.Object)
      • interface org.omg.CORBA.DynEnum (also extends org.omg.CORBA.Object)
      • interface org.omg.CORBA.DynFixed (also extends org.omg.CORBA.Object)
      • interface org.omg.CORBA.DynSequence (also extends org.omg.CORBA.Object)
      • interface org.omg.CORBA.DynStruct (also extends org.omg.CORBA.Object)
      • interface org.omg.CORBA.DynUnion (also extends org.omg.CORBA.Object)
      • interface org.omg.CORBA.DynValue (also extends org.omg.CORBA.Object)
    • interface org.omg.CORBA.DynArray (also extends org.omg.CORBA.DynAny)
    • interface org.omg.CORBA.DynEnum (also extends org.omg.CORBA.DynAny)
    • interface org.omg.CORBA.DynFixed (also extends org.omg.CORBA.DynAny)
    • interface org.omg.CORBA.DynSequence (also extends org.omg.CORBA.DynAny)
    • interface org.omg.CORBA.DynStruct (also extends org.omg.CORBA.DynAny)
    • interface org.omg.CORBA.DynUnion (also extends org.omg.CORBA.DynAny)
    • interface org.omg.CORBA.DynValue (also extends org.omg.CORBA.DynAny)
    • interface org.omg.CORBA.IRObject (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CORBA.IRObjectOperations)
      • interface org.omg.CORBA.IDLType (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CORBA.IDLTypeOperations)
    • interface org.omg.CORBA.Policy (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CORBA.PolicyOperations)
  • interface org.omg.CORBA.OMGVMCID
  • interface org.omg.CORBA.PolicyOperations
    • interface org.omg.CORBA.Policy (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CORBA.Object)
  • interface org.omg.CORBA.PRIVATE_MEMBER
  • interface org.omg.CORBA.PUBLIC_MEMBER
  • interface java.io.Serializable
    • interface org.omg.CORBA.portable.IDLEntity
      • interface org.omg.CORBA.Current (also extends org.omg.CORBA.CurrentOperations, org.omg.CORBA.Object)
      • interface org.omg.CORBA.DomainManager (also extends org.omg.CORBA.DomainManagerOperations, org.omg.CORBA.Object)
      • interface org.omg.CORBA.IDLType (also extends org.omg.CORBA.IDLTypeOperations, org.omg.CORBA.IRObject)
      • interface org.omg.CORBA.IRObject (also extends org.omg.CORBA.IRObjectOperations, org.omg.CORBA.Object)
        • interface org.omg.CORBA.IDLType (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CORBA.IDLTypeOperations)
      • interface org.omg.CORBA.Policy (also extends org.omg.CORBA.Object, org.omg.CORBA.PolicyOperations)
      • interface org.omg.CORBA.portable.ValueBase
        • interface org.omg.CORBA.DataInputStream
        • interface org.omg.CORBA.DataOutputStream
  • interface org.omg.CORBA.UNSUPPORTED_POLICY
  • interface org.omg.CORBA.UNSUPPORTED_POLICY_VALUE
  • interface org.omg.CORBA.VM_ABSTRACT
  • interface org.omg.CORBA.VM_CUSTOM
  • interface org.omg.CORBA.VM_NONE
  • interface org.omg.CORBA.VM_TRUNCATABLE
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package org.omg.CORBA (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
org.omg.CORBA

Packages that use org.omg.CORBA
javax.rmi.CORBA | Contains portability APIs for RMI-IIOP.
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 | Provides the exceptions used with the DynAny interface (InvalidValue, Invalid, InvalidSeq, and TypeMismatch).
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.TypeCodePackage | Provides the user-defined exceptions BadKind and Bounds, which are thrown by methods in in the class TypeCode.
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_2_3 | The CORBA_2_3 package defines additions to existing CORBA interfaces in the Java 2 Standard Edition. 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.CosNaming | Provides a naming service for Java IDL.
org.omg.CosNaming.NamingContextExtPackage | This package contains the following classes, which are used in org.omg.CosNaming.NamingContextExt:
org.omg.CosNaming.NamingContextPackage | This package contains Exception classes for the org.omg.CosNaming 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 | 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 | 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 | 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 | 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 | This package contains the exceptions specified in the IOP::CodeFactory interface (as part of the Portable Interceptors spec).
org.omg.IOP.CodecPackage | This package is generated from the IOP::Codec IDL interface definition.
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 | 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 | 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 | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.
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 | Encapsulates the processing state of the POAs it is associated with.
org.omg.PortableServer.POAPackage | Allows programmers to construct object implementations that are portable between different ORB products.
org.omg.PortableServer.ServantLocatorPackage | Provides classes and interfaces for locating the servant.
org.omg.SendingContext | Provides support for the marshalling of value types.
org.omg.stub.java.rmi | Contains RMI-IIOP Stubs for the Remote types that occur in the java.rmi package.

Classes in org.omg.CORBA used by javax.rmi.CORBA
Object
The definition for a CORBA object reference.
ORB
A class providing APIs for the CORBA Object Request Broker features.
SystemException
The root class for all CORBA standard exceptions.

Classes in org.omg.CORBA used by org.omg.CORBA
Any
Serves as a container for any data that can be described in IDL or for any IDL primitive type.
AnySeqHolder
The Holder for AnySeq.
BAD_INV_ORDER
This exception indicates that the caller has invoked operations in the wrong order.
BAD_OPERATION
Exception thrown when an object reference denotes an existing object, but that the object does not support the operation that was invoked.
BAD_PARAM
Exception thrown when a parameter passed to a call is out of range or otherwise considered illegal.
BooleanSeqHolder
The Holder for BooleanSeq.
Bounds
A user exception thrown when a parameter is not within the legal bounds for the object that a method is trying to access.
CharSeqHolder
The Holder for CharSeq.
CompletionStatus
An object that indicates whether a method had completed running when a SystemException was thrown.
Context
An object used in Request operations to specify the context object in which context strings must be resolved before being sent along with the request invocation.
ContextList
An object containing a modifiable list of String objects that represent property names.
Current
Interfaces derived from the Current interface enable ORB and CORBA services to provide access to information (context) associated with the thread of execution in which they are running.
CurrentOperations
The interface for Current.
DATA_CONVERSION
This exception is raised if an ORB cannot convert the representation of data as marshaled into its native representation or vice-versa.
DataInputStream
Defines the methods used to read primitive data types from input streams for unmarshaling custom value types.
DataOutputStream
Defines the methods used to write primitive data types to output streams for marshalling custom value types.
DefinitionKind
The class that provides the constants used to identify the type of an Interface Repository object.
DomainManager
Provides mechanisms for establishing and navigating relationships to superior and subordinate domains, as well as for creating and accessing policies.
DomainManagerOperations
Provides the DomainManager with the means to access policies.
DoubleSeqHolder
The Holder for DoubleSeq.
DynAny
Enables org.omg.CORBA.Any values to be dynamically interpreted (traversed) and constructed.
DynArray
Represents a DynAny object associated with an array.
DynEnum
Represents a DynAny object associated with an IDL enum.
DynSequence
The representation of a DynAny object that is associated with an IDL sequence.
DynStruct
The representation of a DynAny object that is associated with an IDL struct.
DynUnion
The DynUnion interface represents a DynAny object that is associated with an IDL union.
Environment
A container (holder) for an exception that is used in Request operations to make exceptions available to the client.
ExceptionList
An object used in Request operations to describe the exceptions that can be thrown by a method.
FloatSeqHolder
The Holder for FloatSeq.
IDLType
An abstract interface inherited by all Interface Repository (IR) objects that represent OMG IDL types.
IDLTypeOperations
This interface must be implemented by all IDLType objects.
IRObject
An IRObject IDL interface represents the most generic interface from which all other Interface Repository interfaces are derived, even the Repository itself.
IRObjectOperations
This is the Operations interface for the mapping from IRObject.
LongLongSeqHolder
The Holder for LongLongSeq.
LongSeqHolder
The Holder for LongSeq.
MARSHAL
A request or reply from the network is structurally invalid.
NamedValue
An object used in the DII and DSI to describe arguments and return values.
NameValuePair
Associates a name with a value that is an attribute of an IDL struct, and is used in the DynStruct APIs.
NVList
A modifiable list containing NamedValue objects.
Object
The definition for a CORBA object reference.
OctetSeqHolder
The Holder for OctetSeq.
ORB
A class providing APIs for the CORBA Object Request Broker features.
ParameterMode
Enumeration of parameter modes for Parameter.
Policy
Interfaces derived from the Policy interface allow an ORB or CORBA service access to certain choices that affect its operation.
PolicyError
A user exception thrown when a policy error occurs.
PolicyOperations
Provides the operations for a Policy object.
Principal
Deprecated. Deprecated by CORBA 2.2.
Request
An object containing the information necessary for invoking a method.
ServerRequest
An object that captures the explicit state of a request for the Dynamic Skeleton Interface (DSI).
ServiceDetail
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.
ServiceInformation
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.
ServiceInformationHolder
The Holder for ServiceInformation.
SetOverrideType
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.
ShortSeqHolder
The Holder for ShortSeq.
StructMember
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.
SystemException
The root class for all CORBA standard exceptions.
TCKind
The Java mapping of the IDL enum TCKind, which specifies the kind of a TypeCode object.
TypeCode
A container for information about a specific CORBA data type.
ULongLongSeqHolder
The Holder for ULongLongSeq.
ULongSeqHolder
The Holder for ULongSeq.
UnionMember
A description in the Interface Repository of a member of an IDL union.
UnknownUserException
A class that contains user exceptions returned by the server.
UserException
The root class for CORBA IDL-defined user exceptions.
UShortSeqHolder
The Holder for UShortSeq.
ValueMember
A description in the Interface Repository of a member of a value object.
WCharSeqHolder
The Holder for WCharSeq.
WrongTransaction
The CORBA WrongTransaction user-defined exception.

Classes in org.omg.CORBA used by org.omg.CORBA.DynAnyPackage
UserException
The root class for CORBA IDL-defined user exceptions.

Classes in org.omg.CORBA used by org.omg.CORBA.ORBPackage
UserException
The root class for CORBA IDL-defined user exceptions.

Classes in org.omg.CORBA used by org.omg.CORBA.TypeCodePackage
UserException
The root class for CORBA IDL-defined user exceptions.

Classes in org.omg.CORBA used by org.omg.CORBA.portable
Any
Serves as a container for any data that can be described in IDL or for any IDL primitive type.
Context
An object used in Request operations to specify the context object in which context strings must be resolved before being sent along with the request invocation.
ContextList
An object containing a modifiable list of String objects that represent property names.
CustomMarshal
An abstract value type that is meant to be used by the ORB, not the user.
DomainManager
Provides mechanisms for establishing and navigating relationships to superior and subordinate domains, as well as for creating and accessing policies.
ExceptionList
An object used in Request operations to describe the exceptions that can be thrown by a method.
NamedValue
An object used in the DII and DSI to describe arguments and return values.
NVList
A modifiable list containing NamedValue objects.
Object
The definition for a CORBA object reference.
ORB
A class providing APIs for the CORBA Object Request Broker features.
Policy
Interfaces derived from the Policy interface allow an ORB or CORBA service access to certain choices that affect its operation.
Principal
Deprecated. Deprecated by CORBA 2.2.
Request
An object containing the information necessary for invoking a method.
SetOverrideType
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.
SystemException
The root class for all CORBA standard exceptions.
TypeCode
A container for information about a specific CORBA data type.

Classes in org.omg.CORBA used by org.omg.CORBA_2_3
BAD_PARAM
Exception thrown when a parameter passed to a call is out of range or otherwise considered illegal.
ORB
A class providing APIs for the CORBA Object Request Broker features.

Classes in org.omg.CORBA used by org.omg.CosNaming
Any
Serves as a container for any data that can be described in IDL or for any IDL primitive type.
DynamicImplementation
Deprecated. org.omg.CORBA.DynamicImplementation
Object
The definition for a CORBA object reference.
ORB
A class providing APIs for the CORBA Object Request Broker features.
ServerRequest
An object that captures the explicit state of a request for the Dynamic Skeleton Interface (DSI).
TypeCode
A container for information about a specific CORBA data type.

Classes in org.omg.CORBA used by org.omg.CosNaming.NamingContextExtPackage
Any
Serves as a container for any data that can be described in IDL or for any IDL primitive type.
TypeCode
A container for information about a specific CORBA data type.
UserException
The root class for CORBA IDL-defined user exceptions.

Classes in org.omg.CORBA used by org.omg.CosNaming.NamingContextPackage
Any
Serves as a container for any data that can be described in IDL or for any IDL primitive type.
TypeCode
A container for information about a specific CORBA data type.
UserException
The root class for CORBA IDL-defined user exceptions.

Classes in org.omg.CORBA used by org.omg.Dynamic
Any
Serves as a container for any data that can be described in IDL or for any IDL primitive type.
ParameterMode
Enumeration of parameter modes for Parameter.

Classes in org.omg.CORBA used by org.omg.DynamicAny
Any
Serves as a container for any data that can be described in IDL or for any IDL primitive type.
Object
The definition for a CORBA object reference.
TCKind
The Java mapping of the IDL enum TCKind, which specifies the kind of a TypeCode object.
TypeCode
A container for information about a specific CORBA data type.

Classes in org.omg.CORBA used by org.omg.DynamicAny.DynAnyFactoryPackage
Any
Serves as a container for any data that can be described in IDL or for any IDL primitive type.
TypeCode
A container for information about a specific CORBA data type.

Classes in org.omg.CORBA used by org.omg.DynamicAny.DynAnyPackage
Any
Serves as a container for any data that can be described in IDL or for any IDL primitive type.
TypeCode
A container for information about a specific CORBA data type.

Classes in org.omg.CORBA used by org.omg.IOP
Any
Serves as a container for any data that can be described in IDL or for any IDL primitive type.
Object
The definition for a CORBA object reference.
TypeCode
A container for information about a specific CORBA data type.

Classes in org.omg.CORBA used by org.omg.IOP.CodecFactoryPackage
Any
Serves as a container for any data that can be described in IDL or for any IDL primitive type.
TypeCode
A container for information about a specific CORBA data type.
UserException
The root class for CORBA IDL-defined user exceptions.

Classes in org.omg.CORBA used by org.omg.IOP.CodecPackage
Any
Serves as a container for any data that can be described in IDL or for any IDL primitive type.
TypeCode
A container for information about a specific CORBA data type.
UserException
The root class for CORBA IDL-defined user exceptions.

Classes in org.omg.CORBA used by org.omg.Messaging
Any
Serves as a container for any data that can be described in IDL or for any IDL primitive type.
TypeCode
A container for information about a specific CORBA data type.

Classes in org.omg.CORBA used by org.omg.PortableInterceptor
Any
Serves as a container for any data that can be described in IDL or for any IDL primitive type.
Object
The definition for a CORBA object reference.
Policy
Interfaces derived from the Policy interface allow an ORB or CORBA service access to certain choices that affect its operation.
PolicyError
A user exception thrown when a policy error occurs.
TypeCode
A container for information about a specific CORBA data type.
UserException
The root class for CORBA IDL-defined user exceptions.

Classes in org.omg.CORBA used by org.omg.PortableInterceptor.ORBInitInfoPackage
Any
Serves as a container for any data that can be described in IDL or for any IDL primitive type.
TypeCode
A container for information about a specific CORBA data type.
UserException
The root class for CORBA IDL-defined user exceptions.

Classes in org.omg.CORBA used by org.omg.PortableServer
Any
Serves as a container for any data that can be described in IDL or for any IDL primitive type.
Current
Interfaces derived from the Current interface enable ORB and CORBA services to provide access to information (context) associated with the thread of execution in which they are running.
CurrentOperations
The interface for Current.
Object
The definition for a CORBA object reference.
ORB
A class providing APIs for the CORBA Object Request Broker features.
Policy
Interfaces derived from the Policy interface allow an ORB or CORBA service access to certain choices that affect its operation.
PolicyOperations
Provides the operations for a Policy object.
TypeCode
A container for information about a specific CORBA data type.
UserException
The root class for CORBA IDL-defined user exceptions.

Classes in org.omg.CORBA used by org.omg.PortableServer.CurrentPackage
Any
Serves as a container for any data that can be described in IDL or for any IDL primitive type.
TypeCode
A container for information about a specific CORBA data type.
UserException
The root class for CORBA IDL-defined user exceptions.

Classes in org.omg.CORBA used by org.omg.PortableServer.POAManagerPackage
Any
Serves as a container for any data that can be described in IDL or for any IDL primitive type.
TypeCode
A container for information about a specific CORBA data type.
UserException
The root class for CORBA IDL-defined user exceptions.

Classes in org.omg.CORBA used by org.omg.PortableServer.POAPackage
Any
Serves as a container for any data that can be described in IDL or for any IDL primitive type.
TypeCode
A container for information about a specific CORBA data type.
UserException
The root class for CORBA IDL-defined user exceptions.

Classes in org.omg.CORBA used by org.omg.PortableServer.ServantLocatorPackage
TypeCode
A container for information about a specific CORBA data type.

Classes in org.omg.CORBA used by org.omg.SendingContext
Object
The definition for a CORBA object reference.

Classes in org.omg.CORBA used by org.omg.stub.java.rmi
Object
The definition for a CORBA object reference.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


ParameterMode (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class ParameterMode

java.lang.Object
    extended by org.omg.CORBA.ParameterMode
All Implemented Interfaces:
IDLEntity, Serializable
public class ParameterMode
extends Object
implements IDLEntity

Enumeration of parameter modes for Parameter. Possible vaues:

  • PARAM_IN - Represents an "in" parameter.
  • PARAM_OUT - Represents an "out" parameter.
  • PARAM_INOUT - Represents an "inout" parameter.

Field Summary
static int | _PARAM_IN
static int | _PARAM_INOUT
static int | _PARAM_OUT
static ParameterMode | PARAM_IN
static ParameterMode | PARAM_INOUT
static ParameterMode | PARAM_OUT
Constructor Summary
protected ParameterMode(int value)
Method Summary
static ParameterMode | from_int(int value)
int | value()
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

_PARAM_IN

public static final int _PARAM_IN
See Also:
Constant Field Values

PARAM_IN

public static final ParameterMode PARAM_IN

_PARAM_OUT

public static final int _PARAM_OUT
See Also:
Constant Field Values

PARAM_OUT

public static final ParameterMode PARAM_OUT

_PARAM_INOUT

public static final int _PARAM_INOUT
See Also:
Constant Field Values

PARAM_INOUT

public static final ParameterMode PARAM_INOUT
Constructor Detail

ParameterMode

protected ParameterMode(int value)
Method Detail

value

public int value()

from_int

public static ParameterMode from_int(int value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ParameterModeHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class ParameterModeHelper

java.lang.Object
    extended by org.omg.CORBA.ParameterModeHelper
public abstract class ParameterModeHelper
extends Object

Enumeration of parameter modes for Parameter. Possible vaues:

  • PARAM_IN - Represents an "in" parameter.
  • PARAM_OUT - Represents an "out" parameter.
  • PARAM_INOUT - Represents an "inout" parameter.

Constructor Summary
ParameterModeHelper()
Method Summary
static ParameterMode | extract(Any a)
static String | id()
static void | insert(Any a, ParameterMode that)
static ParameterMode | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, ParameterMode value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ParameterModeHelper

public ParameterModeHelper()
Method Detail

insert

public static void insert(Any a,
                          ParameterMode that)

extract

public static ParameterMode extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static ParameterMode read(InputStream istream)

write

public static void write(OutputStream ostream,
                         ParameterMode value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ParameterModeHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class ParameterModeHolder

java.lang.Object
    extended by org.omg.CORBA.ParameterModeHolder
All Implemented Interfaces:
Streamable
public final class ParameterModeHolder
extends Object
implements Streamable

Enumeration of parameter modes for Parameter. Possible vaues:

  • PARAM_IN - Represents an "in" parameter.
  • PARAM_OUT - Represents an "out" parameter.
  • PARAM_INOUT - Represents an "inout" parameter.

Field Summary
 ParameterMode value
Constructor Summary
ParameterModeHolder()
ParameterModeHolder(ParameterMode initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public ParameterMode value
Constructor Detail

ParameterModeHolder

public ParameterModeHolder()

ParameterModeHolder

public ParameterModeHolder(ParameterMode initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


PERSIST_STORE (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class PERSIST_STORE

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by org.omg.CORBA.SystemException
                    extended by org.omg.CORBA.PERSIST_STORE
All Implemented Interfaces:
Serializable
public final class PERSIST_STORE
extends SystemException

This exception indicates a persistent storage failure, for example, failure to establish a database connection or corruption of a database.

It contains a minor code, which gives more detailed information about what caused the exception, and a completion status. It may also contain a string describing the exception.

See Also:
documentation on Java IDL exceptions

Field Summary
Fields inherited from class org.omg.CORBA.SystemException
completed, minor
Constructor Summary
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(int minor, CompletionStatus completed)
Constructs a PERSIST_STORE exception with the specified minor code and completion status.
PERSIST_STORE(String s)
Constructs a PERSIST_STORE exception with the specified description message, a minor code of 0, and a completion state of COMPLETED_NO.
PERSIST_STORE(String s, int minor, CompletionStatus completed)
Constructs a PERSIST_STORE exception with the specified description message, minor code, and completion status.
Methods inherited from class org.omg.CORBA.SystemException
toString
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

PERSIST_STORE

public 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

public PERSIST_STORE(String s)
Constructs a PERSIST_STORE exception with the specified description message, a minor code of 0, and a completion state of COMPLETED_NO.

Parameters:
s - the String containing a detail message

PERSIST_STORE

public PERSIST_STORE(int minor,
                     CompletionStatus completed)
Constructs a PERSIST_STORE exception with the specified minor code and completion status.

Parameters:
minor - the minor code
completed - the completion status

PERSIST_STORE

public PERSIST_STORE(String s,
                     int minor,
                     CompletionStatus completed)
Constructs a PERSIST_STORE exception with the specified description message, minor code, and completion status.

Parameters:
s - the String containing a description message
minor - the minor code
completed - the completion status
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Policy (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Interface Policy

All Superinterfaces:
IDLEntity, Object, PolicyOperations, Serializable
All Known Subinterfaces:
IdAssignmentPolicy, IdUniquenessPolicy, ImplicitActivationPolicy, LifespanPolicy, RequestProcessingPolicy, ServantRetentionPolicy, ThreadPolicy
All Known Implementing Classes:
_PolicyStub
public interface Policy
extends PolicyOperations, Object, IDLEntity

Interfaces derived from the Policy interface allow an ORB or CORBA service access to certain choices that affect its operation. This information is accessed in a structured manner using interfaces derived from the Policy interface defined in the CORBA module. A CORBA service does not have to use this method of accessing operating options, but may choose to do so. The Security Service in particular uses this technique for associating Security Policy with objects in the system. An interface generated by the IDL-to-Java compiler. org/omg/CORBA/Policy.java Generated by the IDL-to-Java compiler (portable), version "3.0" from ../../../../../src/share/classes/org/omg/PortableServer/corba.idl Saturday, July 17, 1999 12:26:20 AM PDT

Methods inherited from interface org.omg.CORBA.PolicyOperations
copy, destroy, policy_type
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


PolicyError (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class PolicyError

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.CORBA.PolicyError
All Implemented Interfaces:
IDLEntity, Serializable
public final class PolicyError
extends UserException

A user exception thrown when a policy error occurs. A PolicyError exception may include one of the following policy error reason codes defined in the org.omg.CORBA package: BAD_POLICY, BAD_POLICY_TYPE, BAD_POLICY_VALUE, UNSUPPORTED_POLICY, UNSUPPORTED_POLICY_VALUE.

Field Summary
 short reason
The reason for the PolicyError exception being thrown.
Constructor Summary
PolicyError()
Constructs a default PolicyError user exception with no reason code and an empty reason detail message.
PolicyError(short __reason)
Constructs a PolicyError user exception initialized with the given reason code and an empty reason detail message.
PolicyError(String reason_string, short __reason)
Constructs a PolicyError user exception initialized with the given reason detail message and reason code.
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

reason

public short reason
The reason for the PolicyError exception being thrown.

Constructor Detail

PolicyError

public PolicyError()
Constructs a default PolicyError user exception with no reason code and an empty reason detail message.

PolicyError

public PolicyError(short __reason)
Constructs a PolicyError user exception initialized with the given reason code and an empty reason detail message.

Parameters:
__reason - the reason code.

PolicyError

public PolicyError(String reason_string,
                   short __reason)
Constructs a PolicyError user exception initialized with the given reason detail message and reason code.

Parameters:
reason_string - the reason detail message.
__reason - the reason code.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


PolicyErrorCodeHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class PolicyErrorCodeHelper

java.lang.Object
    extended by org.omg.CORBA.PolicyErrorCodeHelper
public abstract class PolicyErrorCodeHelper
extends Object

Encapsulates a reason a Policy may be invalid.

See Also:
PolicyError

Constructor Summary
PolicyErrorCodeHelper()
Method Summary
static short | extract(Any a)
static String | id()
static void | insert(Any a, short that)
static short | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, short value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

PolicyErrorCodeHelper

public PolicyErrorCodeHelper()
Method Detail

insert

public static void insert(Any a,
                          short that)

extract

public static short extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static short read(InputStream istream)

write

public static void write(OutputStream ostream,
                         short value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


PolicyErrorHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class PolicyErrorHelper

java.lang.Object
    extended by org.omg.CORBA.PolicyErrorHelper
public abstract class PolicyErrorHelper
extends Object

Thrown to indicate problems with parameter values passed to the ORB.create_policy operation.

Constructor Summary
PolicyErrorHelper()
Method Summary
static PolicyError | extract(Any a)
static String | id()
static void | insert(Any a, PolicyError that)
static PolicyError | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, PolicyError value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

PolicyErrorHelper

public PolicyErrorHelper()
Method Detail

insert

public static void insert(Any a,
                          PolicyError that)

extract

public static PolicyError extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static PolicyError read(InputStream istream)

write

public static void write(OutputStream ostream,
                         PolicyError value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


PolicyErrorHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class PolicyErrorHolder

java.lang.Object
    extended by org.omg.CORBA.PolicyErrorHolder
All Implemented Interfaces:
Streamable
public final class PolicyErrorHolder
extends Object
implements Streamable

Thrown to indicate problems with parameter values passed to the ORB.create_policy operation.

Field Summary
 PolicyError value
Constructor Summary
PolicyErrorHolder()
PolicyErrorHolder(PolicyError initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public PolicyError value
Constructor Detail

PolicyErrorHolder

public PolicyErrorHolder()

PolicyErrorHolder

public PolicyErrorHolder(PolicyError initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


PolicyHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class PolicyHelper

java.lang.Object
    extended by org.omg.CORBA.PolicyHelper
public abstract class PolicyHelper
extends Object

The Helper for Policy. For more information on Helper files, see "Generated Files: Helper Files".

org/omg/CORBA/PolicyHelper.java Generated by the IDL-to-Java compiler (portable), version "3.0" from ../../../../../src/share/classes/org/omg/PortableServer/corba.idl Saturday, July 17, 1999 12:26:20 AM PDT

Constructor Summary
PolicyHelper()
Method Summary
static Policy | extract(Any a)
static String | id()
static void | insert(Any a, Policy that)
static Policy | narrow(Object obj)
static Policy | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, Policy value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

PolicyHelper

public PolicyHelper()
Method Detail

insert

public static void insert(Any a,
                          Policy that)

extract

public static Policy extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static Policy read(InputStream istream)

write

public static void write(OutputStream ostream,
                         Policy value)

narrow

public static Policy narrow(Object obj)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


PolicyHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class PolicyHolder

java.lang.Object
    extended by org.omg.CORBA.PolicyHolder
All Implemented Interfaces:
Streamable
public final class PolicyHolder
extends Object
implements Streamable

The Holder for Policy. For more information on Holder files, see "Generated Files: Holder Files".

org/omg/CORBA/PolicyHolder.java Generated by the IDL-to-Java compiler (portable), version "3.0" from ../../../../../src/share/classes/org/omg/PortableServer/corba.idl Saturday, July 17, 1999 12:26:20 AM PDT

Field Summary
 Policy value
Constructor Summary
PolicyHolder()
PolicyHolder(Policy initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public Policy value
Constructor Detail

PolicyHolder

public PolicyHolder()

PolicyHolder

public PolicyHolder(Policy initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


PolicyListHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class PolicyListHelper

java.lang.Object
    extended by org.omg.CORBA.PolicyListHelper
public abstract class PolicyListHelper
extends Object

The Helper for PolicyList. For more information on Helper files, see "Generated Files: Helper Files".

org/omg/CORBA/PolicyListHelper.java Generated by the IDL-to-Java compiler (portable), version "3.0" from ../../../../../src/share/classes/org/omg/PortableServer/corba.idl Saturday, July 17, 1999 12:26:21 AM PDT

Constructor Summary
PolicyListHelper()
Method Summary
static Policy[] | extract(Any a)
static String | id()
static void | insert(Any a, Policy[] that)
static Policy[] | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, Policy[] value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

PolicyListHelper

public PolicyListHelper()
Method Detail

insert

public static void insert(Any a,
                          Policy[] that)

extract

public static Policy[] extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static Policy[] read(InputStream istream)

write

public static void write(OutputStream ostream,
                         Policy[] value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


PolicyListHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class PolicyListHolder

java.lang.Object
    extended by org.omg.CORBA.PolicyListHolder
All Implemented Interfaces:
Streamable
public final class PolicyListHolder
extends Object
implements Streamable

The Holder for PolicyList. For more information on Holder files, see "Generated Files: Holder Files".

org/omg/CORBA/PolicyListHolder.java Generated by the IDL-to-Java compiler (portable), version "3.0" from ../../../../../src/share/classes/org/omg/PortableServer/corba.idl Saturday, July 17, 1999 12:26:21 AM PDT

Field Summary
 Policy[] value
Constructor Summary
PolicyListHolder()
PolicyListHolder(Policy[] initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public Policy[] value
Constructor Detail

PolicyListHolder

public PolicyListHolder()

PolicyListHolder

public PolicyListHolder(Policy[] initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


PolicyOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Interface PolicyOperations

All Known Subinterfaces:
IdAssignmentPolicy, IdAssignmentPolicyOperations, IdUniquenessPolicy, IdUniquenessPolicyOperations, ImplicitActivationPolicy, ImplicitActivationPolicyOperations, LifespanPolicy, LifespanPolicyOperations, Policy, RequestProcessingPolicy, RequestProcessingPolicyOperations, ServantRetentionPolicy, ServantRetentionPolicyOperations, ThreadPolicy, ThreadPolicyOperations
All Known Implementing Classes:
_PolicyStub
public interface PolicyOperations

Provides the operations for a Policy object.

Method Summary
Policy | copy() Returns a copy of the Policy object.
void | destroy() Destroys the Policy object.
int | policy_type() Returns the constant value that corresponds to the type of the policy object.

Method Detail

policy_type

public int policy_type()
Returns the constant value that corresponds to the type of the policy object. The values of the policy objects are allocated by the OMG. New values for PolicyType should be obtained from the OMG by sending mail to request@omg.org. In general the constant values that are allocated are defined in conjunction with the definition of the corresponding policy object.

Returns:
the constant value that corresponds to the type of the policy object

copy

public Policy copy()
Returns a copy of the Policy object. The copy does not retain any relationships that the policy had with any domain or object.

Returns:
a copy of the Policy object

destroy

public void destroy()
Destroys the Policy object. It is the responsibility of the Policy object to determine whether it can be destroyed.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


PolicyTypeHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class PolicyTypeHelper

java.lang.Object
    extended by org.omg.CORBA.PolicyTypeHelper
public abstract class PolicyTypeHelper
extends Object

The Helper for PolicyType. For more information on Helper files, see "Generated Files: Helper Files".

org/omg/CORBA/PolicyTypeHelper.java Generated by the IDL-to-Java compiler (portable), version "3.0" from ../../../../../src/share/classes/org/omg/PortableServer/corba.idl Saturday, July 17, 1999 12:26:20 AM PDT

Constructor Summary
PolicyTypeHelper()
Method Summary
static int | extract(Any a)
static String | id()
static void | insert(Any a, int that)
static int | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, int value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

PolicyTypeHelper

public PolicyTypeHelper()
Method Detail

insert

public static void insert(Any a,
                          int that)

extract

public static int extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static int read(InputStream istream)

write

public static void write(OutputStream ostream,
                         int value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Principal (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class Principal

java.lang.Object
    extended by org.omg.CORBA.Principal
Deprecated. Deprecated by CORBA 2.2.

public class Principal
extends Object

A class that contains information about the identity of the client, for access control and other purposes. It contains a single attribute, the name of the Principal, encoded as a sequence of bytes.

Constructor Summary
Principal()
Deprecated.
Method Summary
byte[] | name() Deprecated. Deprecated by CORBA 2.2.
void | name(byte[] value) Deprecated. Deprecated by CORBA 2.2.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

Principal

public Principal()
Deprecated.
Method Detail

name

public void name(byte[] value)
Deprecated. Deprecated by CORBA 2.2.

Sets the name of this Principal object to the given value.

Parameters:
value - the value to be set in the Principal

name

public byte[] name()
Deprecated. Deprecated by CORBA 2.2.

Gets the name of this Principal object.

Returns:
the name of this Principal object
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


PrincipalHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class PrincipalHolder

java.lang.Object
    extended by org.omg.CORBA.PrincipalHolder
All Implemented Interfaces:
Streamable
Deprecated. Deprecated by CORBA 2.2.

public final class PrincipalHolder
extends Object
implements Streamable

The Holder for Principal. For more information on Holder files, see "Generated Files: Holder Files".

A container class for values of type Principal that is used to store "out" and "inout" parameters in IDL methods. If an IDL method signature has an IDL Principal as an "out" or "inout" parameter, the programmer must pass an instance of PrincipalHolder as the corresponding parameter in the method invocation; for "inout" parameters, the programmer must also fill the "in" value to be sent to the server. Before the method invocation returns, the ORB will fill in the value corresponding to the "out" value returned from the server.

If myPrincipalHolder is an instance of PrincipalHolder, the value stored in its value field can be accessed with myPrincipalHolder.value.

Since:
JDK1.2

Field Summary
 Principal value
Deprecated. The Principal value held by this PrincipalHolder object.
Constructor Summary
PrincipalHolder()
Deprecated. Constructs a new PrincipalHolder object with its value field initialized to null.
PrincipalHolder(Principal initial)
Deprecated. Constructs a new PrincipalHolder object with its value field initialized to the given Principal object.
Method Summary
void | _read(InputStream input) Deprecated. Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Deprecated. Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream output) Deprecated. Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public Principal value
Deprecated.
The Principal value held by this PrincipalHolder object.

Constructor Detail

PrincipalHolder

public PrincipalHolder()
Deprecated.
Constructs a new PrincipalHolder object with its value field initialized to null.

PrincipalHolder

public PrincipalHolder(Principal initial)
Deprecated.
Constructs a new PrincipalHolder object with its value field initialized to the given Principal object.

Parameters:
initial - the Principal with which to initialize the value field of the newly-created PrincipalHolder object
Method Detail

_read

public void _read(InputStream input)
Deprecated.
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
input - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream output)
Deprecated.
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
output - the CDR OutputStream

_type

public TypeCode _type()
Deprecated.
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


PRIVATE_MEMBER (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Interface PRIVATE_MEMBER

public interface PRIVATE_MEMBER

Constant to define a private member in the ValueMember class.

PRIVATE_MEMBER is one of the two constants of typedef Visibility used in the interface repository to identify visibility of a ValueMember type. The other constant is PUBLIC_MEMBER.

Field Summary
static short value

Field Detail

value

public static final short value
See Also:
Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


PUBLIC_MEMBER (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Interface PUBLIC_MEMBER

public interface PUBLIC_MEMBER

Constant to define a public member in the ValueMember class.

PUBLIC_MEMBER is one of the two constants of typedef Visibility used in the interface repository to identify visibility of a ValueMember type. The other constant is PRIVATE_MEMBER.

Field Summary
static short value

Field Detail

value

public static final short value
See Also:
Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


RepositoryIdHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class RepositoryIdHelper

java.lang.Object
    extended by org.omg.CORBA.RepositoryIdHelper
public abstract class RepositoryIdHelper
extends Object

The Helper for RepositoryId. For more information on Helper files, see "Generated Files: Helper Files".

org/omg/CORBA/RepositoryIdHelper.java Generated by the IDL-to-Java compiler (portable), version "3.0" from ir.idl 03 June 1999 11:33:43 o'clock GMT+00:00

Constructor Summary
RepositoryIdHelper()
Method Summary
static String | extract(Any a)
static String | id()
static void | insert(Any a, String that)
static String | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, String value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

RepositoryIdHelper

public RepositoryIdHelper()
Method Detail

insert

public static void insert(Any a,
                          String that)

extract

public static String extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static String read(InputStream istream)

write

public static void write(OutputStream ostream,
                         String value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Request (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class Request

java.lang.Object
    extended by org.omg.CORBA.Request
public abstract class Request
extends Object

An object containing the information necessary for invoking a method. This class is the cornerstone of the ORB Dynamic Invocation Interface (DII), which allows dynamic creation and invocation of requests. A server cannot tell the difference between a client invocation using a client stub and a request using the DII.

A Request object consists of:

  • the name of the operation to be invoked
  • an NVList containing arguments for the operation.
    Each item in the list is a NamedValue object, which has three parts:
    1. the name of the argument
    2. the value of the argument (as an Any object)
    3. the argument mode flag indicating whether the argument is for input, output, or both

Request objects may also contain additional information, depending on how an operation was defined in the original IDL interface definition. For example, where appropriate, they may contain a NamedValue object to hold the return value or exception, a context, a list of possible exceptions, and a list of context strings that need to be resolved.

New Request objects are created using one of the create_request methods in the Object class. In other words, a create_request method is performed on the object which is to be invoked.

See Also:
NamedValue

Constructor Summary
Request()
Method Summary
abstract Any | add_in_arg() Creates an input argument and adds it to this Request object.
abstract Any | add_inout_arg() Adds an input/output argument to this Request object.
abstract Any | add_named_in_arg(String name) Creates an input argument with the given name and adds it to this Request object.
abstract Any | add_named_inout_arg(String name) Adds an input/output argument with the given name to this Request object.
abstract Any | add_named_out_arg(String name) Adds an output argument with the given name to this Request object.
abstract Any | add_out_arg() Adds an output argument to this Request object.
abstract NVList | arguments() Retrieves the NVList object containing the arguments to the method being invoked.
abstract ContextList | contexts() Retrieves the ContextList object for this request.
abstract Context | ctx() Retrieves the Context object for this request.
abstract void | ctx(Context c) Sets this request's Context object to the one given.
abstract Environment | env() Retrieves the Environment object for this request.
abstract ExceptionList | exceptions() Retrieves the ExceptionList object for this request.
abstract void | get_response() Allows the user to access the response for the invocation triggered earlier with the send_deferred method.
abstract void | invoke() Makes a synchronous invocation using the information in the Request object.
abstract String | operation() Retrieves the name of the method to be invoked.
abstract boolean | poll_response() Allows the user to determine whether a response has been received for the invocation triggered earlier with the send_deferred method.
abstract NamedValue | result() Retrieves the NamedValue object containing the return value for the method.
abstract Any | return_value() Returns the Any object that contains the value for the result of the method.
abstract void | send_deferred() Makes an asynchronous invocation on the request.
abstract void | send_oneway() Makes a oneway invocation on the request.
abstract void | set_return_type(TypeCode tc) Sets the typecode for the return value of the method.
abstract Object | target() Retrieves the the target object reference.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

Request

public Request()
Method Detail

target

public abstract Object target()
Retrieves the the target object reference.

Returns:
the object reference that points to the object implementation for the method to be invoked

operation

public abstract String operation()
Retrieves the name of the method to be invoked.

Returns:
the name of the method to be invoked

arguments

public abstract NVList arguments()
Retrieves the NVList object containing the arguments to the method being invoked. The elements in the list are NamedValue objects, with each one describing an argument to the method.

Returns:
the NVList object containing the arguments for the method

result

public abstract NamedValue result()
Retrieves the NamedValue object containing the return value for the method.

Returns:
the NamedValue object containing the result of the method

env

public abstract Environment env()
Retrieves the Environment object for this request. It contains the exception that the method being invoked has thrown (after the invocation returns).

Returns:
the Environment object for this request

exceptions

public abstract ExceptionList exceptions()
Retrieves the ExceptionList object for this request. This list contains TypeCode objects describing the exceptions that may be thrown by the method being invoked.

Returns:
the ExceptionList object describing the exceptions that may be thrown by the method being invoked

contexts

public abstract ContextList contexts()
Retrieves the ContextList object for this request. This list contains context Strings that need to be resolved and sent with the invocation.

Returns:
the list of context strings whose values need to be resolved and sent with the invocation.

ctx

public abstract Context ctx()
Retrieves the Context object for this request. This is a list of properties giving information about the client, the environment, or the circumstances of this request.

Returns:
the Context object that is to be used to resolve any context strings whose values need to be sent with the invocation

ctx

public abstract void ctx(Context c)
Sets this request's Context object to the one given.

Parameters:
c - the new Context object to be used for resolving context strings

add_in_arg

public abstract Any add_in_arg()
Creates an input argument and adds it to this Request object.

Returns:
an Any object that contains the value and typecode for the input argument added

add_named_in_arg

public abstract Any add_named_in_arg(String name)
Creates an input argument with the given name and adds it to this Request object.

Parameters:
name - the name of the argument being added
Returns:
an Any object that contains the value and typecode for the input argument added

add_inout_arg

public abstract Any add_inout_arg()
Adds an input/output argument to this Request object.

Returns:
an Any object that contains the value and typecode for the input/output argument added

add_named_inout_arg

public abstract Any add_named_inout_arg(String name)
Adds an input/output argument with the given name to this Request object.

Parameters:
name - the name of the argument being added
Returns:
an Any object that contains the value and typecode for the input/output argument added

add_out_arg

public abstract Any add_out_arg()
Adds an output argument to this Request object.

Returns:
an Any object that contains the value and typecode for the output argument added

add_named_out_arg

public abstract Any add_named_out_arg(String name)
Adds an output argument with the given name to this Request object.

Parameters:
name - the name of the argument being added
Returns:
an Any object that contains the value and typecode for the output argument added

set_return_type

public abstract void set_return_type(TypeCode tc)
Sets the typecode for the return value of the method.

Parameters:
tc - the TypeCode object containing type information for the return value

return_value

public abstract Any return_value()
Returns the Any object that contains the value for the result of the method.

Returns:
an Any object containing the value and typecode for the return value

invoke

public abstract void invoke()
Makes a synchronous invocation using the information in the Request object. Exception information is placed into the Request object's environment object.

send_oneway

public abstract void send_oneway()
Makes a oneway invocation on the request. In other words, it does not expect or wait for a response. Note that this can be used even if the operation was not declared as oneway in the IDL declaration. No response or exception information is returned.

send_deferred

public abstract void send_deferred()
Makes an asynchronous invocation on the request. In other words, it does not wait for a response before it returns to the user. The user can then later use the methods poll_response and get_response to get the result or exception information for the invocation.

poll_response

public abstract boolean poll_response()
Allows the user to determine whether a response has been received for the invocation triggered earlier with the send_deferred method.

Returns:
true if the method response has been received; false otherwise

get_response

public abstract void get_response()
                           throws WrongTransaction
Allows the user to access the response for the invocation triggered earlier with the send_deferred method.

Throws:
WrongTransaction - if the method get_response was invoked from a different transaction's scope than the one from which the request was originally sent. See the OMG Transaction Service specification for details.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ServerRequest (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class ServerRequest

java.lang.Object
    extended by org.omg.CORBA.ServerRequest
public abstract class ServerRequest
extends Object

An object that captures the explicit state of a request for the Dynamic Skeleton Interface (DSI). This class, the cornerstone of the DSI, is analogous to the Request object in the DII.

The ORB is responsible for creating this embodiment of a request, and delivering it to a Dynamic Implementation Routine (DIR). A dynamic servant (a DIR) is created by implementing the DynamicImplementation class, which has a single invoke method. This method accepts a ServerRequest object. The abstract class ServerRequest defines methods for accessing the method name, the arguments and the context of the request, as well as methods for setting the result of the request either as a return value or an exception.

A subtlety with accessing the arguments of the request is that the DIR needs to provide type information about the expected arguments, since there is no compiled information about these. This information is provided through an NVList, which is a list of NamedValue objects. Each NamedValue object contains an Any object, which in turn has a TypeCode object representing the type of the argument.

Similarly, type information needs to be provided for the response, for either the expected result or for an exception, so the methods result and except take an Any object as a parameter.

See Also:
DynamicImplementation, NVList, NamedValue

Constructor Summary
ServerRequest()
Method Summary
 void arguments(NVList args)
Specifies method parameter types and retrieves "in" and "inout" argument values.
abstract  Context ctx()
Returns the context information specified in IDL for the operation when the operation is not an attribute access and the operation's IDL definition contains a context expression; otherwise it returns a nil Context reference.
 void except(Any any)
Deprecated. use set_exception()
 String op_name()
Deprecated. use operation()
 String operation()
Throws an org.omg.CORBA.NO_IMPLEMENT exception.
 void params(NVList params)
Deprecated. use the method arguments
 void result(Any any)
Deprecated. use the method set_result
 void set_exception(Any any)
Throws an org.omg.CORBA.NO_IMPLEMENT exception.
 void set_result(Any any)
Throws an org.omg.CORBA.NO_IMPLEMENT exception.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ServerRequest

public ServerRequest()
Method Detail

op_name

public String op_name()
Deprecated. use operation()

Retrieves the name of the operation being invoked. According to OMG IDL's rules, these names must be unique among all operations supported by this object's "most-derived" interface. Note that the operation names for getting and setting attributes are _get_<attribute_name> and _set_<attribute_name>, respectively.

Returns:
the name of the operation to be invoked

operation

public String operation()
Throws an org.omg.CORBA.NO_IMPLEMENT exception.

Retrieves the name of the operation being invoked. According to OMG IDL's rules, these names must be unique among all operations supported by this object's "most-derived" interface. Note that the operation names for getting and setting attributes are _get_<attribute_name> and _set_<attribute_name>, respectively.

Returns:
the name of the operation to be invoked
See Also:
CORBA package comments for unimplemented features

params

public void params(NVList params)
Deprecated. use the method arguments

Specifies method parameter types and retrieves "in" and "inout" argument values.

Note that this method is deprecated; use the method arguments in its place.

Unless it calls the method set_exception, the DIR must call this method exactly once, even if the method signature contains no parameters. Once the method arguments or set_exception has been called, calling arguments on the same ServerRequest object will result in a BAD_INV_ORDER system exception. The DIR must pass in to the method arguments an NVList initialized with TypeCodes and Flags describing the parameter types for the operation, in the order in which they appear in the IDL specification (left to right). A potentially-different NVList will be returned from arguments, with the "in" and "inout" argument values supplied. If it does not call the method set_exception, the DIR must supply the returned NVList with return values for any "out" arguments before returning, and may also change the return values for any "inout" arguments.

Parameters:
params - the arguments of the method, in the form of an NVList object

arguments

public void arguments(NVList args)
Specifies method parameter types and retrieves "in" and "inout" argument values. Unless it calls the method set_exception, the DIR must call this method exactly once, even if the method signature contains no parameters. Once the method arguments or set_exception has been called, calling arguments on the same ServerRequest object will result in a BAD_INV_ORDER system exception. The DIR must pass in to the method arguments an NVList initialized with TypeCodes and Flags describing the parameter types for the operation, in the order in which they appear in the IDL specification (left to right). A potentially-different NVList will be returned from arguments, with the "in" and "inout" argument values supplied. If it does not call the method set_exception, the DIR must supply the returned NVList with return values for any "out" arguments before returning, and it may also change the return values for any "inout" arguments.

Parameters:
args - the arguments of the method, in the form of an NVList
See Also:
CORBA package comments for unimplemented features

result

public void result(Any any)
Deprecated. use the method set_result

Specifies any return value for the call.

Note that this method is deprecated; use the method set_result in its place.

Unless the method set_exception is called, if the invoked method has a non-void result type, the method set_result must be called exactly once before the DIR returns. If the operation has a void result type, the method set_result may optionally be called once with an Any object whose type is tk_void. Calling the method set_result before the method arguments has been called or after the method set_result or set_exception has been called will result in a BAD_INV_ORDER exception. Calling the method set_result without having previously called the method ctx when the IDL operation contains a context expression, or when the NVList passed to arguments did not describe all parameters passed by the client, may result in a MARSHAL system exception.

Parameters:
any - an Any object containing the return value to be set

set_result

public void set_result(Any any)
Throws an org.omg.CORBA.NO_IMPLEMENT exception.

Specifies any return value for the call. Unless the method set_exception is called, if the invoked method has a non-void result type, the method set_result must be called exactly once before the DIR returns. If the operation has a void result type, the method set_result may optionally be called once with an Any object whose type is tk_void. Calling the method set_result before the method arguments has been called or after the method set_result or set_exception has been called will result in a BAD_INV_ORDER exception. Calling the method set_result without having previously called the method ctx when the IDL operation contains a context expression, or when the NVList passed to arguments did not describe all parameters passed by the client, may result in a MARSHAL system exception.

Parameters:
any - an Any object containing the return value to be set
See Also:
CORBA package comments for unimplemented features

except

public void except(Any any)
Deprecated. use set_exception()

The DIR may call set_exception at any time to return an exception to the client. The Any passed to set_exception must contain either a system exception or a user exception specified in the raises expression of the invoked operation's IDL definition. Passing in an Any that does not contain an exception will result in a BAD_PARAM system exception. Passing in an unlisted user exception will result in either the DIR receiving a BAD_PARAM system exception or in the client receiving an UNKNOWN_EXCEPTION system exception.

Parameters:
any - the Any object containing the exception

set_exception

public void set_exception(Any any)
Throws an org.omg.CORBA.NO_IMPLEMENT exception.

Returns the given exception to the client. This method is invoked by the DIR, which may call it at any time. The Any object passed to this method must contain either a system exception or one of the user exceptions specified in the invoked operation's IDL definition. Passing in an Any object that does not contain an exception will cause a BAD_PARAM system exception to be thrown. Passing in an unlisted user exception will result in either the DIR receiving a BAD_PARAM system exception or in the client receiving an UNKNOWN_EXCEPTION system exception.

Parameters:
any - the Any object containing the exception
Throws:
BAD_PARAM - if the given Any object does not contain an exception or the exception is an unlisted user exception
UNKNOWN_EXCEPTION - if the given exception is an unlisted user exception and the DIR did not receive a BAD_PARAM exception
See Also:
CORBA package comments for unimplemented features

ctx

public abstract Context ctx()
Returns the context information specified in IDL for the operation when the operation is not an attribute access and the operation's IDL definition contains a context expression; otherwise it returns a nil Context reference. Calling the method ctx before the method arguments has been called or after the method ctx, set_result, or set_exception has been called will result in a BAD_INV_ORDER system exception.

Returns:
the context object that is to be used to resolve any context strings whose values need to be sent with the invocation.
Throws:
BAD_INV_ORDER - if (1) the method ctx is called before the method arguments or (2) the method ctx is called after calling set_result or set_exception
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ServiceDetail (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class ServiceDetail

java.lang.Object
    extended by org.omg.CORBA.ServiceDetail
All Implemented Interfaces:
IDLEntity, Serializable
public final class ServiceDetail
extends Object
implements IDLEntity

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.

Field Summary
byte[] | service_detail The data describing the ORB service that this ServiceDetail object represents.
int | service_detail_type The type of the ORB service that this ServiceDetail object represents.
Constructor Summary
ServiceDetail()
Constructs a ServiceDetail object with 0 for the type of ORB service and an empty description.
ServiceDetail(int service_detail_type, byte[] service_detail)
Constructs a ServiceDetail object with the given ORB service type and the given description.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

service_detail_type

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

service_detail

public byte[] service_detail
The data describing the ORB service that this ServiceDetail object represents.

Constructor Detail

ServiceDetail

public ServiceDetail()
Constructs a ServiceDetail object with 0 for the type of ORB service and an empty description.

ServiceDetail

public ServiceDetail(int service_detail_type,
                     byte[] service_detail)
Constructs a ServiceDetail object with the given ORB service type and the given description.

Parameters:
service_detail_type - an int specifying the type of ORB service
service_detail - a byte array describing the ORB service
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ServiceDetailHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class ServiceDetailHelper

java.lang.Object
    extended by org.omg.CORBA.ServiceDetailHelper
public abstract class ServiceDetailHelper
extends Object

Constructor Summary
ServiceDetailHelper()
Method Summary
static ServiceDetail | extract(Any a)
static String | id()
static void | insert(Any a, ServiceDetail that)
static ServiceDetail | read(InputStream in)
static TypeCode | type()
static void | write(OutputStream out, ServiceDetail that)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ServiceDetailHelper

public ServiceDetailHelper()
Method Detail

write

public static void write(OutputStream out,
                         ServiceDetail that)

read

public static ServiceDetail read(InputStream in)

extract

public static ServiceDetail extract(Any a)

insert

public static void insert(Any a,
                          ServiceDetail that)

type

public static TypeCode type()

id

public static String id()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ServiceInformation (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class ServiceInformation

java.lang.Object
    extended by org.omg.CORBA.ServiceInformation
All Implemented Interfaces:
IDLEntity, Serializable
public final class ServiceInformation
extends Object
implements IDLEntity

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.

Field Summary
ServiceDetail[] | service_details Array of ServiceDetails giving more details about the service.
int[] | service_options Array of ints representing service options.
Constructor Summary
ServiceInformation()
Constructs a ServiceInformation object with empty service_options and service_details.
ServiceInformation(int[] __service_options, ServiceDetail[] __service_details)
Constructs a ServiceInformation object with the given service_options and service_details.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

service_options

public int[] service_options
Array of ints representing service options.

service_details

public ServiceDetail[] service_details
Array of ServiceDetails giving more details about the service.

Constructor Detail

ServiceInformation

public ServiceInformation()
Constructs a ServiceInformation object with empty service_options and service_details.

ServiceInformation

public ServiceInformation(int[] __service_options,
                          ServiceDetail[] __service_details)
Constructs a ServiceInformation object with the given service_options and service_details.

Parameters:
__service_options - An array of ints describing the service options.
__service_details - An array of ServiceDetails describing the service details.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ServiceInformationHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class ServiceInformationHelper

java.lang.Object
    extended by org.omg.CORBA.ServiceInformationHelper
public abstract class ServiceInformationHelper
extends Object

Constructor Summary
ServiceInformationHelper()
Method Summary
static ServiceInformation | extract(Any a)
static String | id()
static void | insert(Any a, ServiceInformation that)
static ServiceInformation | read(InputStream in)
static TypeCode | type()
static void | write(OutputStream out, ServiceInformation that)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ServiceInformationHelper

public ServiceInformationHelper()
Method Detail

write

public static void write(OutputStream out,
                         ServiceInformation that)

read

public static ServiceInformation read(InputStream in)

extract

public static ServiceInformation extract(Any a)

insert

public static void insert(Any a,
                          ServiceInformation that)

type

public static TypeCode type()

id

public static String id()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ServiceInformationHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class ServiceInformationHolder

java.lang.Object
    extended by org.omg.CORBA.ServiceInformationHolder
All Implemented Interfaces:
Streamable
public final class ServiceInformationHolder
extends Object
implements Streamable

The Holder for ServiceInformation. For more information on Holder files, see "Generated Files: Holder Files".

A Holder class for a ServiceInformation object that is used to store "out" and "inout" parameters in IDL methods. If an IDL method signature has an IDL xxx as an "out" or "inout" parameter, the programmer must pass an instance of ServiceInformationHolder as the corresponding parameter in the method invocation; for "inout" parameters, the programmer must also fill the "in" value to be sent to the server. Before the method invocation returns, the ORB will fill in the value corresponding to the "out" value returned from the server.

If myServiceInformationHolder is an instance of ServiceInformationHolder, the value stored in its value field can be accessed with myServiceInformationHolder.value.

Field Summary
 ServiceInformation value
The ServiceInformation value held by this ServiceInformationHolder object in its value field.
Constructor Summary
ServiceInformationHolder()
Constructs a new ServiceInformationHolder object with its value field initialized to null.
ServiceInformationHolder(ServiceInformation arg)
Constructs a new ServiceInformationHolder object with its value field initialized to the given ServiceInformation object.
Method Summary
void | _read(InputStream in) Reads unmarshalled data from the input stream in and assigns it to the value field in this ServiceInformationHolder object.
TypeCode | _type() Retrieves the TypeCode object that corresponds to the value held in this ServiceInformationHolder object's value field.
void | _write(OutputStream out) Marshals the value in this ServiceInformationHolder object's value field to the output stream out.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public ServiceInformation value
The ServiceInformation value held by this ServiceInformationHolder object in its value field.

Constructor Detail

ServiceInformationHolder

public ServiceInformationHolder()
Constructs a new ServiceInformationHolder object with its value field initialized to null.

ServiceInformationHolder

public ServiceInformationHolder(ServiceInformation arg)
Constructs a new ServiceInformationHolder object with its value field initialized to the given ServiceInformation object.

Parameters:
arg - the ServiceInformation object with which to initialize the value field of the newly-created ServiceInformationHolder object
Method Detail

_write

public void _write(OutputStream out)
Marshals the value in this ServiceInformationHolder object's value field to the output stream out.

Specified by:
_write in interface Streamable
Parameters:
out - the OutputStream object that will contain the CDR formatted data

_read

public void _read(InputStream in)
Reads unmarshalled data from the input stream in and assigns it to the value field in this ServiceInformationHolder object.

Specified by:
_read in interface Streamable
Parameters:
in - the InputStream object containing CDR formatted data from the wire

_type

public TypeCode _type()
Retrieves the TypeCode object that corresponds to the value held in this ServiceInformationHolder object's value field.

Specified by:
_type in interface Streamable
Returns:
the type code for the value held in this ServiceInformationHolder object
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


SetOverrideType (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class SetOverrideType

java.lang.Object
    extended by org.omg.CORBA.SetOverrideType
All Implemented Interfaces:
IDLEntity, Serializable
public class SetOverrideType
extends Object
implements IDLEntity

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.

The method omg.org.CORBA.Object._set_policy_override takes either SetOverrideType.SET_OVERRIDE or SetOverrideType.ADD_OVERRIDE as its second argument. The method _set_policy_override creates a new Object initialized with the Policy objects supplied as the first argument. If the second argument is ADD_OVERRIDE, the new policies are added to those of the Object instance that is calling the _set_policy_override method. If SET_OVERRIDE is given instead, the existing policies are replaced with the given ones.

Since:
JDK1.2

Field Summary
static int | _ADD_OVERRIDE The int constant for the enum value ADD_OVERRIDE.
static int | _SET_OVERRIDE The int constant for the enum value SET_OVERRIDE.
static SetOverrideType | ADD_OVERRIDE The SetOverrideType constant for the enum value ADD_OVERRIDE.
static SetOverrideType | SET_OVERRIDE The SetOverrideType constant for the enum value SET_OVERRIDE.
Constructor Summary
protected SetOverrideType(int _value)
Constructs a SetOverrideType instance from an int.
Method Summary
static SetOverrideType | from_int(int i) Converts the given int to the corresponding SetOverrideType instance.
int | value() Retrieves the value of this SetOverrideType instance.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

_SET_OVERRIDE

public static final int _SET_OVERRIDE
The int constant for the enum value SET_OVERRIDE.

See Also:
Constant Field Values

_ADD_OVERRIDE

public static final int _ADD_OVERRIDE
The int constant for the enum value ADD_OVERRIDE.

See Also:
Constant Field Values

SET_OVERRIDE

public static final SetOverrideType SET_OVERRIDE
The SetOverrideType constant for the enum value SET_OVERRIDE.

ADD_OVERRIDE

public static final SetOverrideType ADD_OVERRIDE
The SetOverrideType constant for the enum value ADD_OVERRIDE.

Constructor Detail

SetOverrideType

protected SetOverrideType(int _value)
Constructs a SetOverrideType instance from an int.

Parameters:
_value - must be either SET_OVERRIDE or ADD_OVERRIDE
Method Detail

value

public int value()
Retrieves the value of this SetOverrideType instance.

Returns:
the int for this SetOverrideType instance.

from_int

public static SetOverrideType from_int(int i)
Converts the given int to the corresponding SetOverrideType instance.

Parameters:
i - the int to convert; must be either SetOverrideType._SET_OVERRIDE or SetOverrideType._ADD_OVERRIDE
Returns:
the SetOverrideType instance whose value matches the given int
Throws:
BAD_PARAM - if the given int does not match the value of any SetOverrideType instance
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


SetOverrideTypeHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class SetOverrideTypeHelper

java.lang.Object
    extended by org.omg.CORBA.SetOverrideTypeHelper
public abstract class SetOverrideTypeHelper
extends Object

The Helper for SetOverrideType. For more information on Helper files, see "Generated Files: Helper Files".

org/omg/CORBA/SetOverrideTypeHelper.java Generated by the IDL-to-Java compiler (portable), version "3.0" 03 June 1999 11:52:03 o'clock GMT+00:00

Constructor Summary
SetOverrideTypeHelper()
Method Summary
static SetOverrideType | extract(Any a)
static String | id()
static void | insert(Any a, SetOverrideType that)
static SetOverrideType | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, SetOverrideType value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

SetOverrideTypeHelper

public SetOverrideTypeHelper()
Method Detail

insert

public static void insert(Any a,
                          SetOverrideType that)

extract

public static SetOverrideType extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static SetOverrideType read(InputStream istream)

write

public static void write(OutputStream ostream,
                         SetOverrideType value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ShortHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class ShortHolder

java.lang.Object
    extended by org.omg.CORBA.ShortHolder
All Implemented Interfaces:
Streamable
public final class ShortHolder
extends Object
implements Streamable

The Holder for Short. For more information on Holder files, see "Generated Files: Holder Files".

short that is used to store "out" and "inout" parameters in IDL operations. If an IDL operation signature has an IDL short as an "out" or "inout" parameter, the programmer must pass an instance of ShortHolder as the corresponding parameter in the method invocation; for "inout" parameters, the programmer must also fill the "in" value to be sent to the server. Before the method invocation returns, the ORB will fill in the value corresponding to the "out" value returned from the server.

If myShortHolder is an instance of ShortHolder, the value stored in its value field can be accessed with myShortHolder.value.

Since:
JDK1.2

Field Summary
 short value
The short value held by this ShortHolder object.
Constructor Summary
ShortHolder()
Constructs a new ShortHolder object with its value field initialized to 0.
ShortHolder(short initial)
Constructs a new ShortHolder object with its value field initialized to the given short.
Method Summary
void | _read(InputStream input) Reads from input and initalizes the value in this ShortHolder object with the unmarshalled data.
TypeCode | _type() Returns the TypeCode corresponding to the value held in this ShortHolder object.
void | _write(OutputStream output) Marshals to output the value in this ShortHolder object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public short value
The short value held by this ShortHolder object.

Constructor Detail

ShortHolder

public ShortHolder()
Constructs a new ShortHolder object with its value field initialized to 0.

ShortHolder

public ShortHolder(short initial)
Constructs a new ShortHolder object with its value field initialized to the given short.

Parameters:
initial - the short with which to initialize the value field of the newly-created ShortHolder object
Method Detail

_read

public void _read(InputStream input)
Reads from input and initalizes the value in this ShortHolder object with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
input - the InputStream containing CDR formatted data from the wire.

_write

public void _write(OutputStream output)
Marshals to output the value in this ShortHolder object.

Specified by:
_write in interface Streamable
Parameters:
output - the OutputStream which will contain the CDR formatted data.

_type

public TypeCode _type()
Returns the TypeCode corresponding to the value held in this ShortHolder object.

Specified by:
_type in interface Streamable
Returns:
the TypeCode of the value held in this ShortHolder object
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ShortSeqHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class ShortSeqHelper

java.lang.Object
    extended by org.omg.CORBA.ShortSeqHelper
public abstract class ShortSeqHelper
extends Object

The Helper for ShortSeqHelper. For more information on Helper files, see "Generated Files: Helper Files".

org/omg/CORBA/ShortSeqHelper.java Generated by the IDL-to-Java compiler (portable), version "3.0" from streams.idl 13 May 1999 22:41:36 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

Constructor Summary
ShortSeqHelper()
Method Summary
static short[] | extract(Any a)
static String | id()
static void | insert(Any a, short[] that)
static short[] | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, short[] value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ShortSeqHelper

public ShortSeqHelper()
Method Detail

insert

public static void insert(Any a,
                          short[] that)

extract

public static short[] extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static short[] read(InputStream istream)

write

public static void write(OutputStream ostream,
                         short[] value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ShortSeqHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class ShortSeqHolder

java.lang.Object
    extended by org.omg.CORBA.ShortSeqHolder
All Implemented Interfaces:
Streamable
public final class ShortSeqHolder
extends Object
implements Streamable

The Holder for ShortSeq. For more information on Holder files, see "Generated Files: Holder Files".

org/omg/CORBA/ShortSeqHolder.java Generated by the IDL-to-Java compiler (portable), version "3.0" from streams.idl 13 May 1999 22:41:36 o'clock GMT+00:00

Field Summary
 short[] value
Constructor Summary
ShortSeqHolder()
ShortSeqHolder(short[] initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public short[] value
Constructor Detail

ShortSeqHolder

public ShortSeqHolder()

ShortSeqHolder

public ShortSeqHolder(short[] initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


StringHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class StringHolder

java.lang.Object
    extended by org.omg.CORBA.StringHolder
All Implemented Interfaces:
Streamable
public final class StringHolder
extends Object
implements Streamable

The Holder for String. For more information on Holder files, see "Generated Files: Holder Files".

A Holder class for a String that is used to store "out" and "inout" parameters in IDL operations. If an IDL operation signature has an IDL string as an "out" or "inout" parameter, the programmer must pass an instance of StringHolder as the corresponding parameter in the method invocation; for "inout" parameters, the programmer must also fill the "in" value to be sent to the server. Before the method invocation returns, the ORB will fill in the value corresponding to the "out" value returned from the server.

If myStringHolder is an instance of StringHolder, the value stored in its value field can be accessed with myStringHolder.value.

Since:
JDK1.2

Field Summary
 String value
The String value held by this StringHolder object.
Constructor Summary
StringHolder()
Constructs a new StringHolder object with its value field initialized to null.
StringHolder(String initial)
Constructs a new StringHolder object with its value field initialized to the given String.
Method Summary
void | _read(InputStream input) Reads the unmarshalled data from input and assigns it to the value field of this StringHolder object.
TypeCode | _type() Retrieves the TypeCode object that corresponds to the value held in this StringHolder object.
void | _write(OutputStream output) Marshals the value held by this StringHolder object to the output stream output.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public String value
The String value held by this StringHolder object.

Constructor Detail

StringHolder

public StringHolder()
Constructs a new StringHolder object with its value field initialized to null.

StringHolder

public StringHolder(String initial)
Constructs a new StringHolder object with its value field initialized to the given String.

Parameters:
initial - the String with which to initialize the value field of the newly-created StringHolder object
Method Detail

_read

public void _read(InputStream input)
Reads the unmarshalled data from input and assigns it to the value field of this StringHolder object.

Specified by:
_read in interface Streamable
Parameters:
input - the InputStream containing CDR formatted data from the wire.

_write

public void _write(OutputStream output)
Marshals the value held by this StringHolder object to the output stream output.

Specified by:
_write in interface Streamable
Parameters:
output - the OutputStream which will contain the CDR formatted data.

_type

public TypeCode _type()
Retrieves the TypeCode object that corresponds to the value held in this StringHolder object.

Specified by:
_type in interface Streamable
Returns:
the type code of the value held in this StringHolder object
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


StringSeqHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class StringSeqHelper

java.lang.Object
    extended by org.omg.CORBA.StringSeqHelper
public abstract class StringSeqHelper
extends Object

An array of Strings

Constructor Summary
StringSeqHelper()
Method Summary
static String[] | extract(Any a)
static String | id()
static void | insert(Any a, String[] that)
static String[] | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, String[] value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

StringSeqHelper

public StringSeqHelper()
Method Detail

insert

public static void insert(Any a,
                          String[] that)

extract

public static String[] extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static String[] read(InputStream istream)

write

public static void write(OutputStream ostream,
                         String[] value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


StringSeqHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class StringSeqHolder

java.lang.Object
    extended by org.omg.CORBA.StringSeqHolder
All Implemented Interfaces:
Streamable
public final class StringSeqHolder
extends Object
implements Streamable

An array of Strings

Field Summary
 String[] value
Constructor Summary
StringSeqHolder()
StringSeqHolder(String[] initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public String[] value
Constructor Detail

StringSeqHolder

public StringSeqHolder()

StringSeqHolder

public StringSeqHolder(String[] initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


StringValueHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class StringValueHelper

java.lang.Object
    extended by org.omg.CORBA.StringValueHelper
All Implemented Interfaces:
BoxedValueHelper
public class StringValueHelper
extends Object
implements BoxedValueHelper

The Helper for StringValue. For more information on Helper files, see "Generated Files: Helper Files".

org/omg/CORBA/StringValueHelper.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

Constructor Summary
StringValueHelper()
Method Summary
static String | extract(Any a)
String | get_id()
static String | id()
static void | insert(Any a, String that)
Serializable | read_value(InputStream istream)
static String | read(InputStream istream)
static TypeCode | type()
void | write_value(OutputStream ostream, Serializable value)
static void | write(OutputStream ostream, String value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

StringValueHelper

public StringValueHelper()
Method Detail

insert

public static void insert(Any a,
                          String that)

extract

public static String extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static String read(InputStream istream)

read_value

public Serializable read_value(InputStream istream)
Specified by:
read_value in interface BoxedValueHelper

write

public static void write(OutputStream ostream,
                         String value)

write_value

public void write_value(OutputStream ostream,
                        Serializable value)
Specified by:
write_value in interface BoxedValueHelper

get_id

public String get_id()
Specified by:
get_id in interface BoxedValueHelper
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


StructMember (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class StructMember

java.lang.Object
    extended by org.omg.CORBA.StructMember
All Implemented Interfaces:
IDLEntity, Serializable
public final class StructMember
extends Object
implements IDLEntity

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.

Field Summary
String | name The name of the struct member described by this StructMember object.
TypeCode | type The type of the struct member described by this StructMember object.
IDLType | type_def The typedef that represents the IDL type of the struct member described by this StructMember object.
Constructor Summary
StructMember()
Constructs a default StructMember object.
StructMember(String __name, TypeCode __type, IDLType __type_def)
Constructs a StructMember object initialized with the given values.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

name

public String name
The name of the struct member described by this StructMember object.

type

public TypeCode type
The type of the struct member described by this StructMember object.

type_def

public IDLType type_def
The typedef that represents the IDL type of the struct member described by this StructMember object.

Constructor Detail

StructMember

public StructMember()
Constructs a default StructMember object.

StructMember

public StructMember(String __name,
                    TypeCode __type,
                    IDLType __type_def)
Constructs a StructMember object initialized with the given values.

Parameters:
__name - a String object with the name of the struct member
__type - a TypeCode object describing the type of the struct member
__type_def - an IDLType object representing the IDL type of the struct member
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


StructMemberHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class StructMemberHelper

java.lang.Object
    extended by org.omg.CORBA.StructMemberHelper
public abstract class StructMemberHelper
extends Object

The Helper for StructMember. For more information on Helper files, see "Generated Files: Helper Files".

org/omg/CORBA/StructMemberHelper.java Generated by the IDL-to-Java compiler (portable), version "3.0" from ir.idl 03 June 1999 11:33:43 o'clock GMT+00:00

Constructor Summary
StructMemberHelper()
Method Summary
static StructMember | extract(Any a)
static String | id()
static void | insert(Any a, StructMember that)
static StructMember | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, StructMember value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

StructMemberHelper

public StructMemberHelper()
Method Detail

insert

public static void insert(Any a,
                          StructMember that)

extract

public static StructMember extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static StructMember read(InputStream istream)

write

public static void write(OutputStream ostream,
                         StructMember value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


SystemException (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class SystemException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by org.omg.CORBA.SystemException
All Implemented Interfaces:
Serializable
Direct Known Subclasses:
BAD_CONTEXT, BAD_INV_ORDER, BAD_OPERATION, BAD_PARAM, BAD_TYPECODE, COMM_FAILURE, DATA_CONVERSION, FREE_MEM, IMP_LIMIT, IndirectionException, INITIALIZE, INTERNAL, INTF_REPOS, INV_FLAG, INV_IDENT, INV_OBJREF, INV_POLICY, INVALID_TRANSACTION, MARSHAL, NO_IMPLEMENT, NO_MEMORY, NO_PERMISSION, NO_RESOURCES, NO_RESPONSE, OBJ_ADAPTER, OBJECT_NOT_EXIST, PERSIST_STORE, TRANSACTION_REQUIRED, TRANSACTION_ROLLEDBACK, TRANSIENT, UNKNOWN, UnknownException
public abstract class SystemException
extends RuntimeException

The root class for all CORBA standard exceptions. These exceptions may be thrown as a result of any CORBA operation invocation and may also be returned by many standard CORBA API methods. The standard exceptions contain a minor code, allowing more detailed specification, and a completion status. This class is subclassed to generate each one of the set of standard ORB exceptions. SystemException extends java.lang.RuntimeException; thus none of the SystemException exceptions need to be declared in signatures of the Java methods mapped from operations in IDL interfaces.

See Also:
documentation on Java IDL exceptions

Field Summary
CompletionStatus | completed The status of the operation that threw this exception.
int | minor The CORBA Exception minor code.
Constructor Summary
protected SystemException(String reason, int minor, CompletionStatus completed)
Constructs a SystemException exception with the specified detail message, minor code, and completion status.
Method Summary
 String toString()
Converts this exception to a representative string.
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

minor

public int minor
The CORBA Exception minor code.

completed

public CompletionStatus completed
The status of the operation that threw this exception.

Constructor Detail

SystemException

protected SystemException(String reason,
                          int minor,
                          CompletionStatus completed)
Constructs a SystemException exception with the specified detail message, minor code, and completion status. A detail message is a String that describes this particular exception.

Parameters:
reason - the String containing a detail message
minor - the minor code
completed - the completion status
Method Detail

toString

public String toString()
Converts this exception to a representative string.

Overrides:
toString in class Throwable
Returns:
a string representation of this throwable.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TCKind (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class TCKind

java.lang.Object
    extended by org.omg.CORBA.TCKind
public class TCKind
extends Object

The Java mapping of the IDL enum TCKind, which specifies the kind of a TypeCode object. There is one kind for each primitive and essential IDL data type.

The class TCKind consists of:

  • a set of int constants, one for each kind of IDL data type. These int constants make it possible to use a switch statement.
  • a set of TCKind constants, one for each kind of IDL data type. The value field for each TCKind instance is initialized with the int constant that corresponds with the IDL data type that the instance represents.
  • the method from_intfor converting an int to its corresponding TCKind instance

    Example:

          org.omg.CORBA.TCKind k = org.omg.CORBA.TCKind.from_int(
                         org.omg.CORBA.TCKind._tk_string);
    The variable k represents the TCKind instance for the IDL type string, which is tk_string.

  • the method value for accessing the _value field of a TCKind constant

    Example:

       int i = org.omg.CORBA.TCKind.tk_char.value();
    The variable i represents 9, the value for the IDL data type char.

The value field of a TCKind instance is the CDR encoding used for a TypeCode object in an IIOP message.

Field Summary
static int | _tk_abstract_interface The int constant for the IDL data type abstract interface.
static int | _tk_alias The int constant for the IDL data type alias.
static int | _tk_any The int constant for the IDL data type any.
static int | _tk_array The int constant for the IDL data type array.
static int | _tk_boolean The int constant for the IDL data type boolean.
static int | _tk_char The int constant for the IDL data type char.
static int | _tk_double The int constant for the IDL data type double.
static int | _tk_enum The int constant for the IDL data type enum.
static int | _tk_except The int constant for the IDL data type except.
static int | _tk_fixed The int constant for the IDL data type fixed.
static int | _tk_float The int constant for the IDL data type float.
static int | _tk_long The int constant for the IDL data type long.
static int | _tk_longdouble The int constant for the IDL data type longdouble.
static int | _tk_longlong The int constant for the IDL data type longlong.
static int | _tk_native The int constant for the IDL data type native.
static int | _tk_null The int constant for a null IDL data type.
static int | _tk_objref The int constant for the IDL data type objref.
static int | _tk_octet The int constant for the IDL data type octet.
static int | _tk_Principal The int constant for the IDL data type Principal.
static int | _tk_sequence The int constant for the IDL data type sequence.
static int | _tk_short The int constant for the IDL data type short.
static int | _tk_string The int constant for the IDL data type string.
static int | _tk_struct The int constant for the IDL data type struct.
static int | _tk_TypeCode The int constant for the IDL data type TypeCode.
static int | _tk_ulong The int constant for the IDL data type ulong.
static int | _tk_ulonglong The int constant for the IDL data type ulonglong.
static int | _tk_union The int constant for the IDL data type union.
static int | _tk_ushort The int constant for the IDL data type ushort.
static int | _tk_value The int constant for the IDL data type value.
static int | _tk_value_box The int constant for the IDL data type value_box.
static int | _tk_void The int constant for the IDL data type void.
static int | _tk_wchar The int constant for the IDL data type wchar.
static int | _tk_wstring The int constant for the IDL data type wstring.
static TCKind | tk_abstract_interface The TCKind constant whose value field is initialized with TCKind._tk_abstract_interface.
static TCKind | tk_alias The TCKind constant whose value field is initialized with TCKind._tk_alias.
static TCKind | tk_any The TCKind constant whose value field is initialized with TCKind._tk_any.
static TCKind | tk_array The TCKind constant whose value field is initialized with TCKind._tk_array.
static TCKind | tk_boolean The TCKind constant whose value field is initialized with TCKind._tk_boolean.
static TCKind | tk_char The TCKind constant whose value field is initialized with TCKind._tk_char.
static TCKind | tk_double The TCKind constant whose value field is initialized with TCKind._tk_double.
static TCKind | tk_enum The TCKind constant whose value field is initialized with TCKind._tk_enum.
static TCKind | tk_except The TCKind constant whose value field is initialized with TCKind._tk_except.
static TCKind | tk_fixed The TCKind constant whose value field is initialized with TCKind._tk_fixed.
static TCKind | tk_float The TCKind constant whose value field is initialized with TCKind._tk_float.
static TCKind | tk_long The TCKind constant whose value field is initialized with TCKind._tk_long.
static TCKind | tk_longdouble The TCKind constant whose value field is initialized with TCKind._tk_longdouble.
static TCKind | tk_longlong The TCKind constant whose value field is initialized with TCKind._tk_longlong.
static TCKind | tk_native The TCKind constant whose value field is initialized with TCKind._tk_native.
static TCKind | tk_null The TCKind constant whose value field is initialized with TCKind._tk_null.
static TCKind | tk_objref The TCKind constant whose value field is initialized with TCKind._tk_objref.
static TCKind | tk_octet The TCKind constant whose value field is initialized with TCKind._tk_octet.
static TCKind | tk_Principal The TCKind constant whose value field is initialized with TCKind._tk_Principal.
static TCKind | tk_sequence The TCKind constant whose value field is initialized with TCKind._tk_sequence.
static TCKind | tk_short The TCKind constant whose value field is initialized with TCKind._tk_short.
static TCKind | tk_string The TCKind constant whose value field is initialized with TCKind._tk_string.
static TCKind | tk_struct The TCKind constant whose value field is initialized with TCKind._tk_struct.
static TCKind | tk_TypeCode The TCKind constant whose value field is initialized with TCKind._tk_TypeCode.
static TCKind | tk_ulong The TCKind constant whose value field is initialized with TCKind._tk_ulong.
static TCKind | tk_ulonglong The TCKind constant whose value field is initialized with TCKind._tk_ulonglong.
static TCKind | tk_union The TCKind constant whose value field is initialized with TCKind._tk_union.
static TCKind | tk_ushort The TCKind constant whose value field is initialized with TCKind._tk_ushort.
static TCKind | tk_value The TCKind constant whose value field is initialized with TCKind._tk_value.
static TCKind | tk_value_box The TCKind constant whose value field is initialized with TCKind._tk_value_box.
static TCKind | tk_void The TCKind constant whose value field is initialized with TCKind._tk_void.
static TCKind | tk_wchar The TCKind constant whose value field is initialized with TCKind._tk_wchar.
static TCKind | tk_wstring The TCKind constant whose value field is initialized with TCKind._tk_wstring.
Constructor Summary
protected TCKind(int _value)
Deprecated. Do not use this constructor as this method should be private according to the OMG specification. Use from_int(int) instead.
Method Summary
static TCKind | from_int(int i) Converts the given int to the corresponding TCKind instance.
int | value() Retrieves the value of this TCKind instance.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

_tk_null

public static final int _tk_null
The int constant for a null IDL data type.

See Also:
Constant Field Values

_tk_void

public static final int _tk_void
The int constant for the IDL data type void.

See Also:
Constant Field Values

_tk_short

public static final int _tk_short
The int constant for the IDL data type short.

See Also:
Constant Field Values

_tk_long

public static final int _tk_long
The int constant for the IDL data type long.

See Also:
Constant Field Values

_tk_ushort

public static final int _tk_ushort
The int constant for the IDL data type ushort.

See Also:
Constant Field Values

_tk_ulong

public static final int _tk_ulong
The int constant for the IDL data type ulong.

See Also:
Constant Field Values

_tk_float

public static final int _tk_float
The int constant for the IDL data type float.

See Also:
Constant Field Values

_tk_double

public static final int _tk_double
The int constant for the IDL data type double.

See Also:
Constant Field Values

_tk_boolean

public static final int _tk_boolean
The int constant for the IDL data type boolean.

See Also:
Constant Field Values

_tk_char

public static final int _tk_char
The int constant for the IDL data type char.

See Also:
Constant Field Values

_tk_octet

public static final int _tk_octet
The int constant for the IDL data type octet.

See Also:
Constant Field Values

_tk_any

public static final int _tk_any
The int constant for the IDL data type any.

See Also:
Constant Field Values

_tk_TypeCode

public static final int _tk_TypeCode
The int constant for the IDL data type TypeCode.

See Also:
Constant Field Values

_tk_Principal

public static final int _tk_Principal
The int constant for the IDL data type Principal.

See Also:
Constant Field Values

_tk_objref

public static final int _tk_objref
The int constant for the IDL data type objref.

See Also:
Constant Field Values

_tk_struct

public static final int _tk_struct
The int constant for the IDL data type struct.

See Also:
Constant Field Values

_tk_union

public static final int _tk_union
The int constant for the IDL data type union.

See Also:
Constant Field Values

_tk_enum

public static final int _tk_enum
The int constant for the IDL data type enum.

See Also:
Constant Field Values

_tk_string

public static final int _tk_string
The int constant for the IDL data type string.

See Also:
Constant Field Values

_tk_sequence

public static final int _tk_sequence
The int constant for the IDL data type sequence.

See Also:
Constant Field Values

_tk_array

public static final int _tk_array
The int constant for the IDL data type array.

See Also:
Constant Field Values

_tk_alias

public static final int _tk_alias
The int constant for the IDL data type alias.

See Also:
Constant Field Values

_tk_except

public static final int _tk_except
The int constant for the IDL data type except.

See Also:
Constant Field Values

_tk_longlong

public static final int _tk_longlong
The int constant for the IDL data type longlong.

See Also:
Constant Field Values

_tk_ulonglong

public static final int _tk_ulonglong
The int constant for the IDL data type ulonglong.

See Also:
Constant Field Values

_tk_longdouble

public static final int _tk_longdouble
The int constant for the IDL data type longdouble.

See Also:
Constant Field Values

_tk_wchar

public static final int _tk_wchar
The int constant for the IDL data type wchar.

See Also:
Constant Field Values

_tk_wstring

public static final int _tk_wstring
The int constant for the IDL data type wstring.

See Also:
Constant Field Values

_tk_fixed

public static final int _tk_fixed
The int constant for the IDL data type fixed.

See Also:
Constant Field Values

_tk_value

public static final int _tk_value
The int constant for the IDL data type value.

See Also:
Constant Field Values

_tk_value_box

public static final int _tk_value_box
The int constant for the IDL data type value_box.

See Also:
Constant Field Values

_tk_native

public static final int _tk_native
The int constant for the IDL data type native.

See Also:
Constant Field Values

_tk_abstract_interface

public static final int _tk_abstract_interface
The int constant for the IDL data type abstract interface.

See Also:
Constant Field Values

tk_null

public static final TCKind tk_null
The TCKind constant whose value field is initialized with TCKind._tk_null.

tk_void

public static final TCKind tk_void
The TCKind constant whose value field is initialized with TCKind._tk_void.

tk_short

public static final TCKind tk_short
The TCKind constant whose value field is initialized with TCKind._tk_short.

tk_long

public static final TCKind tk_long
The TCKind constant whose value field is initialized with TCKind._tk_long.

tk_ushort

public static final TCKind tk_ushort
The TCKind constant whose value field is initialized with TCKind._tk_ushort.

tk_ulong

public static final TCKind tk_ulong
The TCKind constant whose value field is initialized with TCKind._tk_ulong.

tk_float

public static final TCKind tk_float
The TCKind constant whose value field is initialized with TCKind._tk_float.

tk_double

public static final TCKind tk_double
The TCKind constant whose value field is initialized with TCKind._tk_double.

tk_boolean

public static final TCKind tk_boolean
The TCKind constant whose value field is initialized with TCKind._tk_boolean.

tk_char

public static final TCKind tk_char
The TCKind constant whose value field is initialized with TCKind._tk_char.

tk_octet

public static final TCKind tk_octet
The TCKind constant whose value field is initialized with TCKind._tk_octet.

tk_any

public static final TCKind tk_any
The TCKind constant whose value field is initialized with TCKind._tk_any.

tk_TypeCode

public static final TCKind tk_TypeCode
The TCKind constant whose value field is initialized with TCKind._tk_TypeCode.

tk_Principal

public static final TCKind tk_Principal
The TCKind constant whose value field is initialized with TCKind._tk_Principal.

tk_objref

public static final TCKind tk_objref
The TCKind constant whose value field is initialized with TCKind._tk_objref.

tk_struct

public static final TCKind tk_struct
The TCKind constant whose value field is initialized with TCKind._tk_struct.

tk_union

public static final TCKind tk_union
The TCKind constant whose value field is initialized with TCKind._tk_union.

tk_enum

public static final TCKind tk_enum
The TCKind constant whose value field is initialized with TCKind._tk_enum.

tk_string

public static final TCKind tk_string
The TCKind constant whose value field is initialized with TCKind._tk_string.

tk_sequence

public static final TCKind tk_sequence
The TCKind constant whose value field is initialized with TCKind._tk_sequence.

tk_array

public static final TCKind tk_array
The TCKind constant whose value field is initialized with TCKind._tk_array.

tk_alias

public static final TCKind tk_alias
The TCKind constant whose value field is initialized with TCKind._tk_alias.

tk_except

public static final TCKind tk_except
The TCKind constant whose value field is initialized with TCKind._tk_except.

tk_longlong

public static final TCKind tk_longlong
The TCKind constant whose value field is initialized with TCKind._tk_longlong.

tk_ulonglong

public static final TCKind tk_ulonglong
The TCKind constant whose value field is initialized with TCKind._tk_ulonglong.

tk_longdouble

public static final TCKind tk_longdouble
The TCKind constant whose value field is initialized with TCKind._tk_longdouble.

tk_wchar

public static final TCKind tk_wchar
The TCKind constant whose value field is initialized with TCKind._tk_wchar.

tk_wstring

public static final TCKind tk_wstring
The TCKind constant whose value field is initialized with TCKind._tk_wstring.

tk_fixed

public static final TCKind tk_fixed
The TCKind constant whose value field is initialized with TCKind._tk_fixed.

tk_value

public static final TCKind tk_value
The TCKind constant whose value field is initialized with TCKind._tk_value.

tk_value_box

public static final TCKind tk_value_box
The TCKind constant whose value field is initialized with TCKind._tk_value_box.

tk_native

public static final TCKind tk_native
The TCKind constant whose value field is initialized with TCKind._tk_native.

tk_abstract_interface

public static final TCKind tk_abstract_interface
The TCKind constant whose value field is initialized with TCKind._tk_abstract_interface.

Constructor Detail

TCKind

protected TCKind(int _value)
Deprecated. Do not use this constructor as this method should be private according to the OMG specification. Use from_int(int) instead.

Creates a new TCKind instance initialized with the given int.

Parameters:
_value - the int to convert. It must be one of the int constants in the class TCKind.
Method Detail

value

public int value()
Retrieves the value of this TCKind instance.

Returns:
the int that represents the kind of IDL data type for this TCKind instance

from_int

public static TCKind from_int(int i)
Converts the given int to the corresponding TCKind instance.

Parameters:
i - the int to convert. It must be one of the int constants in the class TCKind.
Returns:
the TCKind instance whose value field matches the given int
Throws:
BAD_PARAM - if the given int does not match the _value field of any TCKind instance
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TRANSACTION_REQUIRED (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class TRANSACTION_REQUIRED

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by org.omg.CORBA.SystemException
                    extended by org.omg.CORBA.TRANSACTION_REQUIRED
All Implemented Interfaces:
Serializable
public final class TRANSACTION_REQUIRED
extends SystemException

Exception indicates that the request carried a null transaction context, but an active transaction is required.

It contains a minor code, which gives information about what caused the exception, and a completion status. It may also contain a string describing the exception. The OMG Transaction Service specfication has details.

See Also:
documentation on Java IDL exceptions

Field Summary
Fields inherited from class org.omg.CORBA.SystemException
completed, minor
Constructor Summary
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(int minor, CompletionStatus completed)
Constructs a TRANSACTION_REQUIRED exception with the specified minor code and completion status.
TRANSACTION_REQUIRED(String s)
Constructs a TRANSACTION_REQUIRED exception with the specified description message, a minor code of 0, and a completion state of COMPLETED_NO.
TRANSACTION_REQUIRED(String s, int minor, CompletionStatus completed)
Constructs a TRANSACTION_REQUIRED exception with the specified description message, minor code, and completion status.
Methods inherited from class org.omg.CORBA.SystemException
toString
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

TRANSACTION_REQUIRED

public 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

public TRANSACTION_REQUIRED(String s)
Constructs a TRANSACTION_REQUIRED exception with the specified description message, a minor code of 0, and a completion state of COMPLETED_NO.

Parameters:
s - the String containing a detail message

TRANSACTION_REQUIRED

public TRANSACTION_REQUIRED(int minor,
                            CompletionStatus completed)
Constructs a TRANSACTION_REQUIRED exception with the specified minor code and completion status.

Parameters:
minor - the minor code
completed - the completion status

TRANSACTION_REQUIRED

public TRANSACTION_REQUIRED(String s,
                            int minor,
                            CompletionStatus completed)
Constructs a TRANSACTION_REQUIRED exception with the specified description message, minor code, and completion status.

Parameters:
s - the String containing a description message
minor - the minor code
completed - the completion status
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TRANSACTION_ROLLEDBACK (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class TRANSACTION_ROLLEDBACK

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by org.omg.CORBA.SystemException
                    extended by org.omg.CORBA.TRANSACTION_ROLLEDBACK
All Implemented Interfaces:
Serializable
public final class TRANSACTION_ROLLEDBACK
extends SystemException

Exception thrown when the transaction associated with the request has already been rolled back or marked to roll back. Thus, the requested operation either could not be performed or was not performed because further computation on behalf of the transaction would be fruitless.

See the OMG Transaction Service specification for details. It contains a minor code, which gives more detailed information about what caused the exception, and a completion status. It may also contain a string describing the exception.

See Also:
documentation on Java IDL exceptions

Field Summary
Fields inherited from class org.omg.CORBA.SystemException
completed, minor
Constructor Summary
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(int minor, CompletionStatus completed)
Constructs a TRANSACTION_ROLLEDBACK exception with the specified minor code and completion status.
TRANSACTION_ROLLEDBACK(String s)
Constructs a TRANSACTION_ROLLEDBACK exception with the specified description message, a minor code of 0, and a completion state of COMPLETED_NO.
TRANSACTION_ROLLEDBACK(String s, int minor, CompletionStatus completed)
Constructs a TRANSACTION_ROLLEDBACK exception with the specified description message, minor code, and completion status.
Methods inherited from class org.omg.CORBA.SystemException
toString
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

TRANSACTION_ROLLEDBACK

public 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

public TRANSACTION_ROLLEDBACK(String s)
Constructs a TRANSACTION_ROLLEDBACK exception with the specified description message, a minor code of 0, and a completion state of COMPLETED_NO.

Parameters:
s - the String containing a detail message

TRANSACTION_ROLLEDBACK

public TRANSACTION_ROLLEDBACK(int minor,
                              CompletionStatus completed)
Constructs a TRANSACTION_ROLLEDBACK exception with the specified minor code and completion status.

Parameters:
minor - the minor code
completed - the completion status

TRANSACTION_ROLLEDBACK

public TRANSACTION_ROLLEDBACK(String s,
                              int minor,
                              CompletionStatus completed)
Constructs a TRANSACTION_ROLLEDBACK exception with the specified description message, minor code, and completion status.

Parameters:
s - the String containing a description message
minor - the minor code
completed - the completion status
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TRANSIENT (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class TRANSIENT

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by org.omg.CORBA.SystemException
                    extended by org.omg.CORBA.TRANSIENT
All Implemented Interfaces:
Serializable
public final class TRANSIENT
extends SystemException

Exception thrown when the ORB attempted to reach an object and failed. It is not an indication that an object does not exist. Instead, it simply means that no further determination of an object's status was possible because it could not be reached. This exception is raised if an attempt to establish a connection fails, for example, because the server or the implementation repository is down.

It contains a minor code, which gives more detailed information about what caused the exception, and a completion status. It may also contain a string describing the exception.

See Also:
documentation on Java IDL exceptions

Field Summary
Fields inherited from class org.omg.CORBA.SystemException
completed, minor
Constructor Summary
TRANSIENT()
Constructs a TRANSIENT exception with a default minor code of 0, a completion state of CompletionStatus.COMPLETED_NO, and a null description.
TRANSIENT(int minor, CompletionStatus completed)
Constructs a TRANSIENT exception with the specified minor code and completion status.
TRANSIENT(String s)
Constructs a TRANSIENT exception with the specified description message, a minor code of 0, and a completion state of COMPLETED_NO.
TRANSIENT(String s, int minor, CompletionStatus completed)
Constructs a TRANSIENT exception with the specified description message, minor code, and completion status.
Methods inherited from class org.omg.CORBA.SystemException
toString
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

TRANSIENT

public TRANSIENT()
Constructs a TRANSIENT exception with a default minor code of 0, a completion state of CompletionStatus.COMPLETED_NO, and a null description.

TRANSIENT

public TRANSIENT(String s)
Constructs a TRANSIENT exception with the specified description message, a minor code of 0, and a completion state of COMPLETED_NO.

Parameters:
s - the String containing a detail message

TRANSIENT

public TRANSIENT(int minor,
                 CompletionStatus completed)
Constructs a TRANSIENT exception with the specified minor code and completion status.

Parameters:
minor - the minor code
completed - the completion status

TRANSIENT

public TRANSIENT(String s,
                 int minor,
                 CompletionStatus completed)
Constructs a TRANSIENT exception with the specified description message, minor code, and completion status.

Parameters:
s - the String containing a description message
minor - the minor code
completed - the completion status
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TypeCode (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class TypeCode

java.lang.Object
    extended by org.omg.CORBA.TypeCode
All Implemented Interfaces:
IDLEntity, Serializable
public abstract class TypeCode
extends Object
implements IDLEntity

A container for information about a specific CORBA data type.

TypeCode objects are used:

  • in the Dynamic Invocation Interface -- to indicate the types of the actual arguments or the type of the return value.
    NamedValue objects are used to represent arguments and return values. One of their components is an Any object, which in turn has as one of its components a TypeCode object.
  • by an Interface Repository to represent the type specifications that are part of many OMG IDL declarations

The representation of a TypeCode object is opaque, but abstractly, a TypeCode object consists of:

  • a kind field, which is set to an instance of the class TCKind
  • zero or more additional fields appropriate for the particular kind. For example, the TypeCode object describing the OMG IDL type 1ong has kind TCKind.tk_long and no additional fields. The TypeCode describing OMG IDL type sequence<boolean, 10> has a kind field with the value TCKind.tk_sequence and also fields with the values boolean and 10 for the type of sequence elements and the length of the sequence.

TypeCode objects can be obtained in various ways:
  1. from a call to the method Any.insert_X, where X is a basic IDL type. This method creates a TypeCode object for type X and assigns it to the Any object's type field.
  2. from invocations of methods in the ORB class

    For example, the following creates a TypeCode object for a string with a maximum of 30 characters:

       org.omg.CORBA.TypeCode tcString = orb.create_string_tc(30);

    The following creates a TypeCode object for an array of five strings:

       org.omg.CORBA.TypeCode tcArray = orb.create_array_tc(
                                       5, TCKind.tk_string);

    The following creates a TypeCode object for an interface named "Account":

       org.omg.CORBA.TypeCode tcInterface = orb.create_interface_tc(
                                                 "thisId", "Account");
  3. as the return value from the _type method in Holder classes for user-defined IDL types. These Holder classes are generated by the idltojava compiler.
  4. from a CORBA Interface Repository

Most of the methods in the class TypeCode are accessors, and the information contained in a TypeCode object is specific to a particular type. Therefore, methods must be invoked only on the kind of type codes to which they apply. If an accessor method tries to access information from an inappropriate kind of type code, it will throw the exception TypeCodePackage.BadKind. For example, if the method discriminator_type is called on anything other than a union, it will throw BadKind because only unions have a discriminator. The following list shows which methods apply to which kinds of type codes:

These methods may be invoked on all TypeCode kinds:

  • equal
  • kind

These methods may be invoked on objref, struct, union, enum, alias, exception, value, value_box, native, and abstract_interface:

  • id
  • name

These methods may be invoked on struct, union, enum, and exception:

  • member_count
  • member_name

These methods may be invoked on struct, union, and exception:

  • member_type(int index)

These methods may be invoked on union:

  • member_label
  • discriminator_type
  • default_index

These methods may be invoked on string, sequence, and array:

  • length

These methods may be invoked on alias, sequence, array, and value_box:

  • content_type

Unlike other CORBA pseudo-objects, TypeCode objects can be passed as general IDL parameters.

The methods parameter and param_count, which are deprecated, are not mapped.

Java IDL extends the CORBA specification to allow all operations permitted on a struct TypeCode to be permitted on an exception TypeCode as well.

Constructor Summary
TypeCode()
Method Summary
abstract TypeCode | concrete_base_type() Returns the TypeCode object that describes the concrete base type of the value type that this TypeCode object describes.
abstract TypeCode | content_type() Returns the TypeCode object representing the IDL type for the members of the object described by this TypeCode object.
abstract int | default_index() Returns the index of the default member, or -1 if there is no default member.
abstract TypeCode | discriminator_type() Returns a TypeCode object describing all non-default member labels.
abstract boolean | equal(TypeCode tc) Compares this TypeCode object with the given one, testing for equality.
abstract boolean | equivalent(TypeCode tc) Tests to see if the given TypeCode object is equivalent to this TypeCode object.
abstract short | fixed_digits() Returns the number of digits in the fixed type described by this TypeCode object.
abstract short | fixed_scale() Returns the scale of the fixed type described by this TypeCode object.
abstract TypeCode | get_compact_typecode() Strips out all optional name and member name fields, but leaves all alias typecodes intact.
abstract String | id() Retrieves the RepositoryId globally identifying the type of this TypeCode object.
abstract TCKind | kind() Retrieves the kind of this TypeCode object.
abstract int | length() Returns the number of elements in the type described by this TypeCode object.
abstract int | member_count() Retrieves the number of members in the type described by this TypeCode object.
abstract Any | member_label(int index) Retrieves the label of the union member identified by the given index.
abstract String | member_name(int index) Retrieves the simple name of the member identified by the given index.
abstract TypeCode | member_type(int index) Retrieves the TypeCode object describing the type of the member identified by the given index.
abstract short | member_visibility(int index) Returns the constant that indicates the visibility of the member at the given index.
abstract String | name() Retrieves the simple name identifying this TypeCode object within its enclosing scope.
abstract short | type_modifier() Returns a constant indicating the modifier of the value type that this TypeCode object describes.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

TypeCode

public TypeCode()
Method Detail

equal

public abstract boolean equal(TypeCode tc)
Compares this TypeCode object with the given one, testing for equality. TypeCode objects are equal if they are interchangeable and give identical results when TypeCode operations are applied to them.

Parameters:
tc - the TypeCode object to compare against
Returns:
true if the type codes are equal; false otherwise

equivalent

public abstract boolean equivalent(TypeCode tc)
Tests to see if the given TypeCode object is equivalent to this TypeCode object.

Not implemented; see package comments.

Parameters:
tc - the typecode to compare with this typecode
Returns:
true if the given typecode is equivalent to this typecode; false otherwise
See Also:
CORBA package comments for unimplemented features

get_compact_typecode

public abstract TypeCode get_compact_typecode()
Strips out all optional name and member name fields, but leaves all alias typecodes intact.

Returns:
a TypeCode object with optional name and member name fields stripped out, except for alias typecodes, which are left intact
See Also:
CORBA package comments for unimplemented features

kind

public abstract TCKind kind()
Retrieves the kind of this TypeCode object. The kind of a type code determines which TypeCode methods may legally be invoked on it.

The method kind may be invoked on any TypeCode object.

Returns:
the TCKind instance indicating the value of the kind field of this TypeCode object

id

public abstract String id()
                   throws BadKind
Retrieves the RepositoryId globally identifying the type of this TypeCode object.

The method id can be invoked on object reference, structure, union, enumeration, alias, exception, valuetype, boxed valuetype, native, and abstract interface type codes. Object reference, exception, valuetype, boxed valuetype, native, and abstract interface TypeCode objects always have a RepositoryId. Structure, union, enumeration, and alias TypeCode objects obtained from the Interface Repository or the method ORB.create_operation_list also always have a RepositoryId. If there is no RepositoryId, the method can return an empty string.

Returns:
the RepositoryId for this TypeCode object or an empty string if there is no RepositoryID
Throws:
BadKind - if the method is invoked on an inappropriate kind ofTypeCode object

name

public abstract String name()
                     throws BadKind
Retrieves the simple name identifying this TypeCode object within its enclosing scope. Since names are local to a Repository, the name returned from a TypeCode object may not match the name of the type in any particular Repository, and may even be an empty string.

The method name can be invoked on object reference, structure, union, enumeration, alias, exception, valuetype, boxed valuetype, native, and abstract interface TypeCode objects.

Returns:
the name identifying this TypeCode object or an empty string
Throws:
BadKind - if the method is invoked on an inappropriate kind ofTypeCode object

member_count

public abstract int member_count()
                          throws BadKind
Retrieves the number of members in the type described by this TypeCode object.

The method member_count can be invoked on structure, union, and enumeration TypeCode objects. Java IDL extends the CORBA specification to allow this method to operate on exceptions as well.

Returns:
the number of members constituting the type described by this TypeCode object
Throws:
BadKind - if the method is invoked on an inappropriate kind of TypeCode object

member_name

public abstract String member_name(int index)
                            throws BadKind,
                                   Bounds
Retrieves the simple name of the member identified by the given index. Since names are local to a Repository, the name returned from a TypeCode object may not match the name of the member in any particular Repository, and may even be an empty string.

The method member_name can be invoked on structure, union, and enumeration TypeCode objects. Java IDL extends the CORBA specification to allow this method to operate on exceptions as well.

Parameters:
index - index of the member for which a name is being reqested
Returns:
simple name of the member identified by the index or an empty string
Throws:
Bounds - if the index is equal to or greater than the number of members constituting the type
BadKind - if the method is invoked on an inappropriate kind of TypeCode object

member_type

public abstract TypeCode member_type(int index)
                              throws BadKind,
                                     Bounds
Retrieves the TypeCode object describing the type of the member identified by the given index.

The method member_type can be invoked on structure and union TypeCode objects. Java IDL extends the CORBA specification to allow this method to operate on exceptions as well.

Parameters:
index - index of the member for which type information is begin requested
Returns:
the TypeCode object describing the member at the given index
Throws:
Bounds - if the index is equal to or greater than the number of members constituting the type
BadKind - if the method is invoked on an inappropriate kind of TypeCode object

member_label

public abstract Any member_label(int index)
                          throws BadKind,
                                 Bounds
Retrieves the label of the union member identified by the given index. For the default member, the label is the zero octet.

The method member_label can only be invoked on union TypeCode objects.

Parameters:
index - index of the union member for which the label is being requested
Returns:
an Any object describing the label of the requested union member or the zero octet for the default member
Throws:
Bounds - if the index is equal to or greater than the number of members constituting the union
BadKind - if the method is invoked on a non-union TypeCode object

discriminator_type

public abstract TypeCode discriminator_type()
                                     throws BadKind
Returns a TypeCode object describing all non-default member labels. The method discriminator_type can be invoked only on union TypeCode objects.

Returns:
the TypeCode object describing the non-default member labels
Throws:
BadKind - if the method is invoked on a non-union TypeCode object

default_index

public abstract int default_index()
                           throws BadKind
Returns the index of the default member, or -1 if there is no default member.

The method default_index can be invoked only on union TypeCode objects.

Returns:
the index of the default member, or -1 if there is no default member
Throws:
BadKind - if the method is invoked on a non-union TypeCode object

length

public abstract int length()
                    throws BadKind
Returns the number of elements in the type described by this TypeCode object. For strings and sequences, it returns the bound, with zero indicating an unbounded string or sequence. For arrays, it returns the number of elements in the array.

The method length can be invoked on string, sequence, and array TypeCode objects.

Returns:
the bound for strings and sequences, or the number of elements for arrays
Throws:
BadKind - if the method is invoked on an inappropriate kind of TypeCode object

content_type

public abstract TypeCode content_type()
                               throws BadKind
Returns the TypeCode object representing the IDL type for the members of the object described by this TypeCode object. For sequences and arrays, it returns the element type. For aliases, it returns the original type. Note that multidimensional arrays are represented by nesting TypeCode objects, one per dimension. For boxed valuetypes, it returns the boxed type.

The method content_type can be invoked on sequence, array, alias, and boxed valuetype TypeCode objects.

Returns:
a TypeCode object representing the element type for sequences and arrays, the original type for aliases, or the boxed type for boxed valuetypes.
Throws:
BadKind - if the method is invoked on an inappropriate kind of TypeCode object

fixed_digits

public abstract short fixed_digits()
                            throws BadKind
Returns the number of digits in the fixed type described by this TypeCode object. For example, the typecode for the number 3000.275d could be fixed<7,3>, where 7 is the precision and 3 is the scale.

Returns:
the total number of digits
Throws:
BadKind - if this method is invoked on an inappropriate kind of TypeCode object

fixed_scale

public abstract short fixed_scale()
                           throws BadKind
Returns the scale of the fixed type described by this TypeCode object. A positive number indicates the number of digits to the right of the decimal point. For example, the number 3000d could have the typecode fixed<4,0>, where the first number is the precision and the second number is the scale. A negative number is also possible and adds zeroes to the left of the decimal point. In this case, fixed<1,-3>, could be the typecode for the number 3000d.

Returns:
the scale of the fixed type that this TypeCode object describes
Throws:
BadKind - if this method is invoked on an inappropriate kind of TypeCode object

member_visibility

public abstract short member_visibility(int index)
                                 throws BadKind,
                                        Bounds
Returns the constant that indicates the visibility of the member at the given index. This operation can only be invoked on non-boxed value TypeCode objects.

Parameters:
index - an int indicating the index into the value
Returns:
either PRIVATE_MEMBER.value or PUBLIC_MEMBER.value
Throws:
BadKind - if this method is invoked on a non-value type TypeCode object
Bounds - if the given index is out of bounds
See Also:
CORBA package comments for unimplemented features

type_modifier

public abstract short type_modifier()
                             throws BadKind
Returns a constant indicating the modifier of the value type that this TypeCode object describes. The constant returned must be one of the following: VM_NONE.value, VM_ABSTRACT.value, VM_CUSTOM.value, or VM_TRUNCATABLE.value,

Returns:
a constant describing the value type that this TypeCode object describes
Throws:
BadKind - if this method is invoked on a non-value type TypeCode object
See Also:
CORBA package comments for unimplemented features

concrete_base_type

public abstract TypeCode concrete_base_type()
                                     throws BadKind
Returns the TypeCode object that describes the concrete base type of the value type that this TypeCode object describes. Returns null if it doesn't have a concrete base type.

Returns:
the TypeCode object that describes the concrete base type of the value type that this TypeCode object describes
Throws:
BadKind - if this method is invoked on a non-boxed value type TypeCode object
See Also:
CORBA package comments for unimplemented features
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TypeCodeHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class TypeCodeHolder

java.lang.Object
    extended by org.omg.CORBA.TypeCodeHolder
All Implemented Interfaces:
Streamable
public final class TypeCodeHolder
extends Object
implements Streamable

The Holder for TypeCode. For more information on Holder files, see "Generated Files: Holder Files".

A Holder class for a TypeCode object that is used to store "out" and "inout" parameters in IDL operations. If an IDL operation signature has an IDL TypeCode as an "out" or "inout" parameter, the programmer must pass an instance of TypeCodeHolder as the corresponding parameter in the method invocation; for "inout" parameters, the programmer must also fill the "in" value to be sent to the server. Before the method invocation returns, the ORB will fill in the value corresponding to the "out" value returned from the server.

If myTypeCodeHolder is an instance of TypeCodeHolder, the value stored in its value field can be accessed with myTypeCodeHolder.value.

Since:
JDK1.2

Field Summary
 TypeCode value
The TypeCode value held by this TypeCodeHolder object.
Constructor Summary
TypeCodeHolder()
Constructs a new TypeCodeHolder object with its value field initialized to null.
TypeCodeHolder(TypeCode initial)
Constructs a new TypeCodeHolder object with its value field initialized to the given TypeCode object.
Method Summary
void | _read(InputStream input) Reads from input and initalizes the value in this TypeCodeHolder object with the unmarshalled data.
TypeCode | _type() Returns the TypeCode corresponding to the value held in this TypeCodeHolder object.
void | _write(OutputStream output) Marshals to output the value in this TypeCodeHolder object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public TypeCode value
The TypeCode value held by this TypeCodeHolder object.

Constructor Detail

TypeCodeHolder

public TypeCodeHolder()
Constructs a new TypeCodeHolder object with its value field initialized to null.

TypeCodeHolder

public TypeCodeHolder(TypeCode initial)
Constructs a new TypeCodeHolder object with its value field initialized to the given TypeCode object.

Parameters:
initial - the TypeCode object with which to initialize the value field of the newly-created TypeCodeHolder object
Method Detail

_read

public void _read(InputStream input)
Reads from input and initalizes the value in this TypeCodeHolder object with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
input - the InputStream containing CDR formatted data from the wire

_write

public void _write(OutputStream output)
Marshals to output the value in this TypeCodeHolder object.

Specified by:
_write in interface Streamable
Parameters:
output - the OutputStream which will contain the CDR formatted data

_type

public TypeCode _type()
Returns the TypeCode corresponding to the value held in this TypeCodeHolder object.

Specified by:
_type in interface Streamable
Returns:
the TypeCode of the value held in this TypeCodeHolder object
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ULongLongSeqHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class ULongLongSeqHelper

java.lang.Object
    extended by org.omg.CORBA.ULongLongSeqHelper
public abstract class ULongLongSeqHelper
extends Object

The Helper for ULongLongSeq. For more information on Helper files, see "Generated Files: Helper Files".

org/omg/CORBA/ULongLongSeqHelper.java Generated by the IDL-to-Java compiler (portable), version "3.0" from streams.idl 13 May 1999 22:41:37 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

Constructor Summary
ULongLongSeqHelper()
Method Summary
static long[] | extract(Any a)
static String | id()
static void | insert(Any a, long[] that)
static long[] | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, long[] value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ULongLongSeqHelper

public ULongLongSeqHelper()
Method Detail

insert

public static void insert(Any a,
                          long[] that)

extract

public static long[] extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static long[] read(InputStream istream)

write

public static void write(OutputStream ostream,
                         long[] value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ULongLongSeqHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class ULongLongSeqHolder

java.lang.Object
    extended by org.omg.CORBA.ULongLongSeqHolder
All Implemented Interfaces:
Streamable
public final class ULongLongSeqHolder
extends Object
implements Streamable

The Holder for ULongLongSeq. For more information on Holder files, see "Generated Files: Holder Files".

org/omg/CORBA/ULongLongSeqHolder.java Generated by the IDL-to-Java compiler (portable), version "3.0" from streams.idl 13 May 1999 22:41:37 o'clock GMT+00:00

Field Summary
 long[] value
Constructor Summary
ULongLongSeqHolder()
ULongLongSeqHolder(long[] initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public long[] value
Constructor Detail

ULongLongSeqHolder

public ULongLongSeqHolder()

ULongLongSeqHolder

public ULongLongSeqHolder(long[] initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ULongSeqHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class ULongSeqHelper

java.lang.Object
    extended by org.omg.CORBA.ULongSeqHelper
public abstract class ULongSeqHelper
extends Object

The Helper for ULongSeq. For more information on Helper files, see "Generated Files: Helper Files".

org/omg/CORBA/ULongSeqHelper.java Generated by the IDL-to-Java compiler (portable), version "3.0" from streams.idl 13 May 1999 22:41:36 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

Constructor Summary
ULongSeqHelper()
Method Summary
static int[] | extract(Any a)
static String | id()
static void | insert(Any a, int[] that)
static int[] | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, int[] value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ULongSeqHelper

public ULongSeqHelper()
Method Detail

insert

public static void insert(Any a,
                          int[] that)

extract

public static int[] extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static int[] read(InputStream istream)

write

public static void write(OutputStream ostream,
                         int[] value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ULongSeqHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class ULongSeqHolder

java.lang.Object
    extended by org.omg.CORBA.ULongSeqHolder
All Implemented Interfaces:
Streamable
public final class ULongSeqHolder
extends Object
implements Streamable

The Holder for ULongSeq. For more information on Holder files, see "Generated Files: Holder Files".

org/omg/CORBA/ULongSeqHolder.java Generated by the IDL-to-Java compiler (portable), version "3.0" from streams.idl 13 May 1999 22:41:36 o'clock GMT+00:00

Field Summary
 int[] value
Constructor Summary
ULongSeqHolder()
ULongSeqHolder(int[] initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public int[] value
Constructor Detail

ULongSeqHolder

public ULongSeqHolder()

ULongSeqHolder

public ULongSeqHolder(int[] initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


UnionMember (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class UnionMember

java.lang.Object
    extended by org.omg.CORBA.UnionMember
All Implemented Interfaces:
IDLEntity, Serializable
public final class UnionMember
extends Object
implements IDLEntity

A description in the Interface Repository of a member of an IDL union.

Field Summary
Any | label The label of the union member described by this UnionMember object.
String | name The name of the union member described by this UnionMember object.
TypeCode | type The type of the union member described by this UnionMember object.
IDLType | type_def The typedef that represents the IDL type of the union member described by this UnionMember object.
Constructor Summary
UnionMember()
Constructs a new UnionMember object with its fields initialized to null.
UnionMember(String __name, Any __label, TypeCode __type, IDLType __type_def)
Constructs a new UnionMember object with its fields initialized to the given values.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

name

public String name
The name of the union member described by this UnionMember object.

label

public Any label
The label of the union member described by this UnionMember object.

type

public TypeCode type
The type of the union member described by this UnionMember object.

type_def

public IDLType type_def
The typedef that represents the IDL type of the union member described by this UnionMember object.

Constructor Detail

UnionMember

public UnionMember()
Constructs a new UnionMember object with its fields initialized to null.

UnionMember

public UnionMember(String __name,
                   Any __label,
                   TypeCode __type,
                   IDLType __type_def)
Constructs a new UnionMember object with its fields initialized to the given values.

Parameters:
__name - a String object with the name of this UnionMember object
__label - an Any object with the label of this UnionMember object
__type - a TypeCode object describing the type of this UnionMember object
__type_def - an IDLType object that represents the IDL type of this UnionMember object
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


UnionMemberHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class UnionMemberHelper

java.lang.Object
    extended by org.omg.CORBA.UnionMemberHelper
public abstract class UnionMemberHelper
extends Object

The Helper for UnionMember. For more information on Helper files, see "Generated Files: Helper Files".

org/omg/CORBA/UnionMemberHelper.java Generated by the IDL-to-Java compiler (portable), version "3.0" from ir.idl 03 June 1999 11:33:43 o'clock GMT+00:00

Constructor Summary
UnionMemberHelper()
Method Summary
static UnionMember | extract(Any a)
static String | id()
static void | insert(Any a, UnionMember that)
static UnionMember | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, UnionMember value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

UnionMemberHelper

public UnionMemberHelper()
Method Detail

insert

public static void insert(Any a,
                          UnionMember that)

extract

public static UnionMember extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static UnionMember read(InputStream istream)

write

public static void write(OutputStream ostream,
                         UnionMember value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


UNKNOWN (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class UNKNOWN

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by org.omg.CORBA.SystemException
                    extended by org.omg.CORBA.UNKNOWN
All Implemented Interfaces:
Serializable
public final class UNKNOWN
extends SystemException

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 is also raised if the server returns a system exception that is unknown to the client. (This can happen if the server uses a later version of CORBA than the client and new system exceptions have been added to the later version.)

It contains a minor code, which gives more detailed information about what caused the exception, and a completion status. It may also contain a string describing the exception.

See the section Minor Code Meanings to see the minor codes for this exception.

See Also:
documentation on Java IDL exceptions

Field Summary
Fields inherited from class org.omg.CORBA.SystemException
completed, minor
Constructor Summary
UNKNOWN()
Constructs an UNKNOWN exception with a default minor code of 0, a completion state of CompletionStatus.COMPLETED_NO, and a null description.
UNKNOWN(int minor, CompletionStatus completed)
Constructs an UNKNOWN exception with the specified minor code and completion status.
UNKNOWN(String s)
Constructs an UNKNOWN exception with the specified description message, a minor code of 0, and a completion state of COMPLETED_NO.
UNKNOWN(String s, int minor, CompletionStatus completed)
Constructs an UNKNOWN exception with the specified description message, minor code, and completion status.
Methods inherited from class org.omg.CORBA.SystemException
toString
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

UNKNOWN

public UNKNOWN()
Constructs an UNKNOWN exception with a default minor code of 0, a completion state of CompletionStatus.COMPLETED_NO, and a null description.

UNKNOWN

public UNKNOWN(String s)
Constructs an UNKNOWN exception with the specified description message, a minor code of 0, and a completion state of COMPLETED_NO.

Parameters:
s - the String containing a detail message

UNKNOWN

public UNKNOWN(int minor,
               CompletionStatus completed)
Constructs an UNKNOWN exception with the specified minor code and completion status.

Parameters:
minor - the minor code
completed - the completion status

UNKNOWN

public UNKNOWN(String s,
               int minor,
               CompletionStatus completed)
Constructs an UNKNOWN exception with the specified description message, minor code, and completion status.

Parameters:
s - the String containing a description message
minor - the minor code
completed - the completion status
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


UnknownUserException (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class UnknownUserException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.CORBA.UnknownUserException
All Implemented Interfaces:
IDLEntity, Serializable
public final class UnknownUserException
extends UserException

A class that contains user exceptions returned by the server. When the client uses the DII to make an invocation, any user exception returned from the server is enclosed in an Any object contained in the UnknownUserException object. This is available from the Environment object returned by the method Request.env.

See Also:
documentation on Java IDL exceptions, Request

Field Summary
 Any except
The Any instance that contains the actual user exception thrown by the server.
Constructor Summary
UnknownUserException()
Constructs an UnknownUserException object.
UnknownUserException(Any a)
Constructs an UnknownUserException object that contains the given Any object.
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

except

public Any except
The Any instance that contains the actual user exception thrown by the server.

Constructor Detail

UnknownUserException

public UnknownUserException()
Constructs an UnknownUserException object.

UnknownUserException

public UnknownUserException(Any a)
Constructs an UnknownUserException object that contains the given Any object.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


UnknownUserExceptionHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class UnknownUserExceptionHelper

java.lang.Object
    extended by org.omg.CORBA.UnknownUserExceptionHelper
public abstract class UnknownUserExceptionHelper
extends Object

The Helper for UnknownUserException. For more information on Helper files, see "Generated Files: Helper Files".

org/omg/CORBA/UnknownUserExceptionHelper.java Generated by the IDL-to-Java compiler (portable), version "3.0" from CORBA.idl Thursday, August 24, 2000 5:52:22 PM PDT

Constructor Summary
UnknownUserExceptionHelper()
Method Summary
static UnknownUserException | extract(Any a)
static String | id()
static void | insert(Any a, UnknownUserException that)
static UnknownUserException | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, UnknownUserException value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

UnknownUserExceptionHelper

public UnknownUserExceptionHelper()
Method Detail

insert

public static void insert(Any a,
                          UnknownUserException that)

extract

public static UnknownUserException extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static UnknownUserException read(InputStream istream)

write

public static void write(OutputStream ostream,
                         UnknownUserException value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


UnknownUserExceptionHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class UnknownUserExceptionHolder

java.lang.Object
    extended by org.omg.CORBA.UnknownUserExceptionHolder
All Implemented Interfaces:
Streamable
public final class UnknownUserExceptionHolder
extends Object
implements Streamable

The Holder for UnknownUserException. For more information on Holder files, see "Generated Files: Holder Files".

org/omg/CORBA/UnknownUserExceptionHolder.java Generated by the IDL-to-Java compiler (portable), version "3.0" from CORBA.idl Thursday, August 24, 2000 5:52:22 PM PDT

Field Summary
 UnknownUserException value
Constructor Summary
UnknownUserExceptionHolder()
UnknownUserExceptionHolder(UnknownUserException initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public UnknownUserException value
Constructor Detail

UnknownUserExceptionHolder

public UnknownUserExceptionHolder()

UnknownUserExceptionHolder

public UnknownUserExceptionHolder(UnknownUserException initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


UNSUPPORTED_POLICY (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Interface UNSUPPORTED_POLICY

public interface UNSUPPORTED_POLICY

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.

Field Summary
static short value
The Error code for PolicyError exception.

Field Detail

value

public static final short value
The Error code for PolicyError exception.

See Also:
Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


UNSUPPORTED_POLICY_VALUE (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Interface UNSUPPORTED_POLICY_VALUE

public interface UNSUPPORTED_POLICY_VALUE

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.

Field Summary
static short value
The Error code for PolicyError exception.

Field Detail

value

public static final short value
The Error code for PolicyError exception.

See Also:
Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


UserException (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class UserException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
All Implemented Interfaces:
IDLEntity, Serializable
Direct Known Subclasses:
AdapterAlreadyExists, AdapterInactive, AdapterNonExistent, AlreadyBound, BadKind, Bounds, Bounds, CannotProceed, DuplicateName, FormatMismatch, ForwardRequest, ForwardRequest, InconsistentTypeCode, InconsistentTypeCode, Invalid, InvalidAddress, InvalidName, InvalidName, InvalidName, InvalidPolicy, InvalidSeq, InvalidSlot, InvalidTypeForEncoding, InvalidValue, InvalidValue, NoContext, NoServant, NotEmpty, NotFound, ObjectAlreadyActive, ObjectNotActive, PolicyError, ServantAlreadyActive, ServantNotActive, TypeMismatch, TypeMismatch, TypeMismatch, UnknownEncoding, UnknownUserException, WrongAdapter, WrongPolicy, WrongTransaction
public abstract class UserException
extends Exception
implements IDLEntity

The root class for CORBA IDL-defined user exceptions. All CORBA user exceptions are checked exceptions, which means that they need to be declared in method signatures.

See Also:
documentation on Java IDL exceptions

Constructor Summary
protected | UserException() Constructs a UserException object.
protected | UserException(String reason) Constructs a UserException object with a detail message.
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

UserException

protected UserException()
Constructs a UserException object. This method is called only by subclasses.

UserException

protected UserException(String reason)
Constructs a UserException object with a detail message. This method is called only by subclasses.

Parameters:
reason - a String object giving the reason for this exception
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


UShortSeqHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class UShortSeqHelper

java.lang.Object
    extended by org.omg.CORBA.UShortSeqHelper
public abstract class UShortSeqHelper
extends Object

The Helper for UShortSeq. For more information on Helper files, see "Generated Files: Helper Files".

org/omg/CORBA/UShortSeqHelper.java Generated by the IDL-to-Java compiler (portable), version "3.0" from streams.idl 13 May 1999 22:41:36 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

Constructor Summary
UShortSeqHelper()
Method Summary
static short[] | extract(Any a)
static String | id()
static void | insert(Any a, short[] that)
static short[] | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, short[] value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

UShortSeqHelper

public UShortSeqHelper()
Method Detail

insert

public static void insert(Any a,
                          short[] that)

extract

public static short[] extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static short[] read(InputStream istream)

write

public static void write(OutputStream ostream,
                         short[] value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


UShortSeqHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class UShortSeqHolder

java.lang.Object
    extended by org.omg.CORBA.UShortSeqHolder
All Implemented Interfaces:
Streamable
public final class UShortSeqHolder
extends Object
implements Streamable

The Holder for UShortSeq. For more information on Holder files, see "Generated Files: Holder Files".

org/omg/CORBA/UShortSeqHolder.java Generated by the IDL-to-Java compiler (portable), version "3.0" from streams.idl 13 May 1999 22:41:36 o'clock GMT+00:00

Field Summary
 short[] value
Constructor Summary
UShortSeqHolder()
UShortSeqHolder(short[] initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public short[] value
Constructor Detail

UShortSeqHolder

public UShortSeqHolder()

UShortSeqHolder

public UShortSeqHolder(short[] initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ValueBaseHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class ValueBaseHelper

java.lang.Object
    extended by org.omg.CORBA.ValueBaseHelper
public abstract class ValueBaseHelper
extends Object

Constructor Summary
ValueBaseHelper()
Method Summary
static Serializable | extract(Any a)
static String | id()
static void | insert(Any a, Serializable that)
static Serializable | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, Serializable value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ValueBaseHelper

public ValueBaseHelper()
Method Detail

insert

public static void insert(Any a,
                          Serializable that)

extract

public static Serializable extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static Serializable read(InputStream istream)

write

public static void write(OutputStream ostream,
                         Serializable value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ValueBaseHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class ValueBaseHolder

java.lang.Object
    extended by org.omg.CORBA.ValueBaseHolder
All Implemented Interfaces:
Streamable
public final class ValueBaseHolder
extends Object
implements Streamable

The Holder for ValueBase. For more information on Holder files, see "Generated Files: Holder Files".

A Holder class for a java.io.Serializable that is used to store "out" and "inout" parameters in IDL methods. If an IDL method signature has an IDL ValueBase as an "out" or "inout" parameter, the programmer must pass an instance of ValueBaseHolder as the corresponding parameter in the method invocation; for "inout" parameters, the programmer must also fill the "in" value to be sent to the server. Before the method invocation returns, the ORB will fill in the value corresponding to the "out" value returned from the server.

If myValueBaseHolder is an instance of ValueBaseHolder, the value stored in its value field can be accessed with myValueBaseHolder.value.

Field Summary
 Serializable value
The java.io.Serializable value held by this ValueBaseHolder object.
Constructor Summary
ValueBaseHolder()
Constructs a new ValueBaseHolder object with its value field initialized to 0.
ValueBaseHolder(Serializable initial)
Constructs a new ValueBaseHolder object with its value field initialized to the given java.io.Serializable.
Method Summary
void | _read(InputStream input) Reads from input and initalizes the value in the Holder with the unmarshalled data.
TypeCode | _type() Returns the TypeCode object corresponding to the value held in the Holder.
void | _write(OutputStream output) Marshals to output the value in the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public Serializable value
The java.io.Serializable value held by this ValueBaseHolder object.

Constructor Detail

ValueBaseHolder

public ValueBaseHolder()
Constructs a new ValueBaseHolder object with its value field initialized to 0.

ValueBaseHolder

public ValueBaseHolder(Serializable initial)
Constructs a new ValueBaseHolder object with its value field initialized to the given java.io.Serializable.

Parameters:
initial - the java.io.Serializable with which to initialize the value field of the newly-created ValueBaseHolder object
Method Detail

_read

public void _read(InputStream input)
Reads from input and initalizes the value in the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
input - the InputStream containing CDR formatted data from the wire

_write

public void _write(OutputStream output)
Marshals to output the value in the Holder.

Specified by:
_write in interface Streamable
Parameters:
output - the OutputStream which will contain the CDR formatted data

_type

public TypeCode _type()
Returns the TypeCode object corresponding to the value held in the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode of the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ValueMember (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class ValueMember

java.lang.Object
    extended by org.omg.CORBA.ValueMember
All Implemented Interfaces:
IDLEntity, Serializable
public final class ValueMember
extends Object
implements IDLEntity

A description in the Interface Repository of a member of a value object.

Field Summary
short | access The type of access (public, private) for the value member described by this ValueMember object.
String | defined_in The repository ID of the value in which this member is defined.
String | id The repository ID of the value member described by this ValueMember object;
String | name The name of the value member described by this ValueMember object.
TypeCode | type The type of of this value member.
IDLType | type_def The typedef that represents the IDL type of the value member described by this ValueMember object.
String | version The version of the value in which this member is defined.
Constructor Summary
ValueMember()
Constructs a default ValueMember object.
ValueMember(String __name, String __id, String __defined_in, String __version, TypeCode __type, IDLType __type_def, short __access)
Constructs a ValueMember object initialized with the given values.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

name

public String name
The name of the value member described by this ValueMember object.

id

public String id
The repository ID of the value member described by this ValueMember object;

defined_in

public String defined_in
The repository ID of the value in which this member is defined.

version

public String version
The version of the value in which this member is defined.

type

public TypeCode type
The type of of this value member.

type_def

public IDLType type_def
The typedef that represents the IDL type of the value member described by this ValueMember object.

access

public short access
The type of access (public, private) for the value member described by this ValueMember object.

Constructor Detail

ValueMember

public ValueMember()
Constructs a default ValueMember object.

ValueMember

public ValueMember(String __name,
                   String __id,
                   String __defined_in,
                   String __version,
                   TypeCode __type,
                   IDLType __type_def,
                   short __access)
Constructs a ValueMember object initialized with the given values.

Parameters:
__name - The name of the value member described by this ValueMember object.
__id - The repository ID of the value member described by this ValueMember object;
__defined_in - The repository ID of the value in which this member is defined.
__version - The version of the value in which this member is defined.
__type - The type of of this value member.
__type_def - The typedef that represents the IDL type of the value member described by this ValueMember object.
__access - The type of access (public, private) for the value member described by this ValueMember object.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ValueMemberHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class ValueMemberHelper

java.lang.Object
    extended by org.omg.CORBA.ValueMemberHelper
public abstract class ValueMemberHelper
extends Object

The Helper for ValueMember. For more information on Helper files, see "Generated Files: Helper Files".

org/omg/CORBA/ValueMemberHelper.java Generated by the IDL-to-Java compiler (portable), version "3.0" from ir.idl 03 June 1999 11:33:44 o'clock GMT+00:00

Constructor Summary
ValueMemberHelper()
Method Summary
static ValueMember | extract(Any a)
static String | id()
static void | insert(Any a, ValueMember that)
static ValueMember | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, ValueMember value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ValueMemberHelper

public ValueMemberHelper()
Method Detail

insert

public static void insert(Any a,
                          ValueMember that)

extract

public static ValueMember extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static ValueMember read(InputStream istream)

write

public static void write(OutputStream ostream,
                         ValueMember value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


VersionSpecHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class VersionSpecHelper

java.lang.Object
    extended by org.omg.CORBA.VersionSpecHelper
public abstract class VersionSpecHelper
extends Object

The Helper for VersionSpec. For more information on Helper files, see "Generated Files: Helper Files".

org/omg/CORBA/VersionSpecHelper.java Generated by the IDL-to-Java compiler (portable), version "3.0" from ir.idl 03 June 1999 11:33:43 o'clock GMT+00:00

Constructor Summary
VersionSpecHelper()
Method Summary
static String | extract(Any a)
static String | id()
static void | insert(Any a, String that)
static String | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, String value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

VersionSpecHelper

public VersionSpecHelper()
Method Detail

insert

public static void insert(Any a,
                          String that)

extract

public static String extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static String read(InputStream istream)

write

public static void write(OutputStream ostream,
                         String value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


VisibilityHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class VisibilityHelper

java.lang.Object
    extended by org.omg.CORBA.VisibilityHelper
public abstract class VisibilityHelper
extends Object

The Helper for Visibility. For more information on Helper files, see "Generated Files: Helper Files".

org/omg/CORBA/VisibilityHelper.java Generated by the IDL-to-Java compiler (portable), version "3.0" from ir.idl 03 June 1999 11:33:44 o'clock GMT+00:00

Constructor Summary
VisibilityHelper()
Method Summary
static short | extract(Any a)
static String | id()
static void | insert(Any a, short that)
static short | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, short value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

VisibilityHelper

public VisibilityHelper()
Method Detail

insert

public static void insert(Any a,
                          short that)

extract

public static short extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static short read(InputStream istream)

write

public static void write(OutputStream ostream,
                         short value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


VM_ABSTRACT (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Interface VM_ABSTRACT

public interface VM_ABSTRACT

Defines the code used to represent an Abstract interface in a typecode. This is one of the possible results of the type_modified method on the TypeCode interface.

See Also:
TypeCode

Field Summary
static short value
The value representing an abstract interface value type in a typecode.

Field Detail

value

public static final short value
The value representing an abstract interface value type in a typecode.

See Also:
Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


VM_CUSTOM (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Interface VM_CUSTOM

public interface VM_CUSTOM

Defines the code used to represent a custom marshalled value type in a typecode. This is one of the possible results of the type_modifier method on the TypeCode interface.

See Also:
TypeCode

Field Summary
static short value
The value representing a custom marshalled value type in a typecode.

Field Detail

value

public static final short value
The value representing a custom marshalled value type in a typecode.

See Also:
Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


VM_NONE (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Interface VM_NONE

public interface VM_NONE

Defines the code used to represent the one of the values of a value type in a typecode.

Since:
JDK1.2
See Also:
TypeCode

Field Summary
static short value
The value representing the value type in a typecode as per CORBA 2.3 spec.

Field Detail

value

public static final short value
The value representing the value type in a typecode as per CORBA 2.3 spec.

See Also:
Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


VM_TRUNCATABLE (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Interface VM_TRUNCATABLE

public interface VM_TRUNCATABLE

Defines the code used to represent a truncatable value type in a typecode. A value type is truncatable if it inherits "safely" from another value type, which means it can be cast to a more general inherited type. This is one of the possible results of the type_modifier method on the TypeCode interface.

See Also:
TypeCode

Field Summary
static short value
The value representing a truncatable value type in a typecode.

Field Detail

value

public static final short value
The value representing a truncatable value type in a typecode.

See Also:
Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


WCharSeqHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class WCharSeqHelper

java.lang.Object
    extended by org.omg.CORBA.WCharSeqHelper
public abstract class WCharSeqHelper
extends Object

The Helper for WCharSeq. For more information on Helper files, see "Generated Files: Helper Files".

org/omg/CORBA/WCharSeqHelper.java Generated by the IDL-to-Java compiler (portable), version "3.0" from streams.idl 13 May 1999 22:41:36 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

Constructor Summary
WCharSeqHelper()
Method Summary
static char[] | extract(Any a)
static String | id()
static void | insert(Any a, char[] that)
static char[] | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, char[] value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

WCharSeqHelper

public WCharSeqHelper()
Method Detail

insert

public static void insert(Any a,
                          char[] that)

extract

public static char[] extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static char[] read(InputStream istream)

write

public static void write(OutputStream ostream,
                         char[] value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


WCharSeqHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class WCharSeqHolder

java.lang.Object
    extended by org.omg.CORBA.WCharSeqHolder
All Implemented Interfaces:
Streamable
public final class WCharSeqHolder
extends Object
implements Streamable

The Holder for WCharSeq. For more information on Holder files, see "Generated Files: Holder Files".

org/omg/CORBA/WCharSeqHolder.java Generated by the IDL-to-Java compiler (portable), version "3.0" from streams.idl 13 May 1999 22:41:36 o'clock GMT+00:00

Field Summary
 char[] value
Constructor Summary
WCharSeqHolder()
WCharSeqHolder(char[] initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public char[] value
Constructor Detail

WCharSeqHolder

public WCharSeqHolder()

WCharSeqHolder

public WCharSeqHolder(char[] initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


WrongTransaction (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class WrongTransaction

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.CORBA.WrongTransaction
All Implemented Interfaces:
IDLEntity, Serializable
public final class WrongTransaction
extends UserException

The CORBA WrongTransaction user-defined exception. This exception is thrown only by the methods Request.get_response and ORB.get_next_response when they are invoked from a transaction scope that is different from the one in which the client originally sent the request. See the OMG Transaction Service Specification for details.

See Also:
documentation on Java IDL exceptions

Constructor Summary
WrongTransaction()
Constructs a WrongTransaction object with an empty detail message.
WrongTransaction(String reason)
Constructs a WrongTransaction object with the given detail message.
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

WrongTransaction

public WrongTransaction()
Constructs a WrongTransaction object with an empty detail message.

WrongTransaction

public WrongTransaction(String reason)
Constructs a WrongTransaction object with the given detail message.

Parameters:
reason - The detail message explaining what caused this exception to be thrown.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


WrongTransactionHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class WrongTransactionHelper

java.lang.Object
    extended by org.omg.CORBA.WrongTransactionHelper
public abstract class WrongTransactionHelper
extends Object

The Helper for WrongTransaction. For more information on Helper files, see "Generated Files: Helper Files".

org/omg/CORBA/WrongTransactionHelper.java Generated by the IDL-to-Java compiler (portable), version "3.0" from CORBA.idl Thursday, August 24, 2000 5:32:50 PM PDT

Constructor Summary
WrongTransactionHelper()
Method Summary
static WrongTransaction | extract(Any a)
static String | id()
static void | insert(Any a, WrongTransaction that)
static WrongTransaction | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, WrongTransaction value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

WrongTransactionHelper

public WrongTransactionHelper()
Method Detail

insert

public static void insert(Any a,
                          WrongTransaction that)

extract

public static WrongTransaction extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static WrongTransaction read(InputStream istream)

write

public static void write(OutputStream ostream,
                         WrongTransaction value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


WrongTransactionHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class WrongTransactionHolder

java.lang.Object
    extended by org.omg.CORBA.WrongTransactionHolder
All Implemented Interfaces:
Streamable
public final class WrongTransactionHolder
extends Object
implements Streamable

The Holder for WrongTransaction. For more information on Holder files, see "Generated Files: Holder Files".

org/omg/CORBA/WrongTransactionHolder.java Generated by the IDL-to-Java compiler (portable), version "3.0" from CORBA.idl Thursday, August 24, 2000 5:32:50 PM PDT

Field Summary
 WrongTransaction value
Constructor Summary
WrongTransactionHolder()
WrongTransactionHolder(WrongTransaction initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public WrongTransaction value
Constructor Detail

WrongTransactionHolder

public WrongTransactionHolder()

WrongTransactionHolder

public WrongTransactionHolder(WrongTransaction initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


WStringSeqHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class WStringSeqHelper

java.lang.Object
    extended by org.omg.CORBA.WStringSeqHelper
public abstract class WStringSeqHelper
extends Object

An array of WStrings

Constructor Summary
WStringSeqHelper()
Method Summary
static String[] | extract(Any a)
static String | id()
static void | insert(Any a, String[] that)
static String[] | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, String[] value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

WStringSeqHelper

public WStringSeqHelper()
Method Detail

insert

public static void insert(Any a,
                          String[] that)

extract

public static String[] extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static String[] read(InputStream istream)

write

public static void write(OutputStream ostream,
                         String[] value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


WStringSeqHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class WStringSeqHolder

java.lang.Object
    extended by org.omg.CORBA.WStringSeqHolder
All Implemented Interfaces:
Streamable
public final class WStringSeqHolder
extends Object
implements Streamable

An array of WStrings

Field Summary
 String[] value
Constructor Summary
WStringSeqHolder()
WStringSeqHolder(String[] initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public String[] value
Constructor Detail

WStringSeqHolder

public WStringSeqHolder()

WStringSeqHolder

public WStringSeqHolder(String[] initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


WStringValueHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA
Class WStringValueHelper

java.lang.Object
    extended by org.omg.CORBA.WStringValueHelper
All Implemented Interfaces:
BoxedValueHelper
public class WStringValueHelper
extends Object
implements BoxedValueHelper

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

Constructor Summary
WStringValueHelper()
Method Summary
static String | extract(Any a)
String | get_id()
static String | id()
static void | insert(Any a, String that)
Serializable | read_value(InputStream istream)
static String | read(InputStream istream)
static TypeCode | type()
void | write_value(OutputStream ostream, Serializable value)
static void | write(OutputStream ostream, String value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

WStringValueHelper

public WStringValueHelper()
Method Detail

insert

public static void insert(Any a,
                          String that)

extract

public static String extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static String read(InputStream istream)

read_value

public Serializable read_value(InputStream istream)
Specified by:
read_value in interface BoxedValueHelper

write

public static void write(OutputStream ostream,
                         String value)

write_value

public void write_value(OutputStream ostream,
                        Serializable value)
Specified by:
write_value in interface BoxedValueHelper

get_id

public String get_id()
Specified by:
get_id in interface BoxedValueHelper
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Uses of Class org.omg.CORBA._IDLTypeStub (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA._IDLTypeStub

No usage of org.omg.CORBA._IDLTypeStub

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA._PolicyStub (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA._PolicyStub

No usage of org.omg.CORBA._PolicyStub

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.Any (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.Any

Packages that use Any
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.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.CosNaming | Provides a naming service for Java IDL.
org.omg.CosNaming.NamingContextExtPackage | This package contains the following classes, which are used in org.omg.CosNaming.NamingContextExt:
org.omg.CosNaming.NamingContextPackage | This package contains Exception classes for the org.omg.CosNaming 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 | 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 | 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 | 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 | 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 | This package contains the exceptions specified in the IOP::CodeFactory interface (as part of the Portable Interceptors spec).
org.omg.IOP.CodecPackage | This package is generated from the IOP::Codec IDL interface definition.
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 | 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 | 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 | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.
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 | Encapsulates the processing state of the POAs it is associated with.
org.omg.PortableServer.POAPackage | Allows programmers to construct object implementations that are portable between different ORB products.

Uses of Any in org.omg.CORBA

Fields in org.omg.CORBA declared as Any
Any[] | AnySeqHolder.value
Any | UnknownUserException.except The Any instance that contains the actual user exception thrown by the server.
Any | AnyHolder.value The Any value held by this AnyHolder object.
Any | NameValuePair.value The value to be associated with a name by this NameValuePair object.
Any | UnionMember.label The label of the union member described by this UnionMember object.

Methods in org.omg.CORBA that return Any
Any | DataInputStream.read_any() Reads an IDL Any value from the input stream.
static Any[] | AnySeqHelper.extract(Any a)
static Any[] | AnySeqHelper.read(InputStream istream)
Any[] | DynArray.get_elements() Returns the value of all the elements of this array.
Any[] | DynSequence.get_elements() Returns the value of every element in this sequence.
Any | DynAny.to_any() Convert a DynAny object to an Any object.
Any | DynAny.get_any() Retrieves the org.omg.CORBA.Any contained in this DynAny object.
abstract Any | TypeCode.member_label(int index) Retrieves the label of the union member identified by the given index.
abstract Any | Any.extract_any() Extracts the Any object in this Any object's value field.
abstract Any | NamedValue.value() Retrieves the value for this NamedValue object.
abstract Any | Request.add_in_arg() Creates an input argument and adds it to this Request object.
abstract Any | Request.add_named_in_arg(String name) Creates an input argument with the given name and adds it to this Request object.
abstract Any | Request.add_inout_arg() Adds an input/output argument to this Request object.
abstract Any | Request.add_named_inout_arg(String name) Adds an input/output argument with the given name to this Request object.
abstract Any | Request.add_out_arg() Adds an output argument to this Request object.
abstract Any | Request.add_named_out_arg(String name) Adds an output argument with the given name to this Request object.
abstract Any | Request.return_value() Returns the Any object that contains the value for the result of the method.
abstract Any | ORB.create_any() Creates an IDL Any object initialized to contain a Typecode object whose kind field is set to TCKind.tc_null.

Methods in org.omg.CORBA with parameters of type Any
static void WStringSeqHelper.insert(Any a, String[] that)
static String[] WStringSeqHelper.extract(Any a)
static void UnknownUserExceptionHelper.insert(Any a, UnknownUserException that)
static UnknownUserException UnknownUserExceptionHelper.extract(Any a)
static void StringSeqHelper.insert(Any a, String[] that)
static String[] StringSeqHelper.extract(Any a)
static void PolicyErrorHelper.insert(Any a, PolicyError that)
static PolicyError PolicyErrorHelper.extract(Any a)
static void PolicyErrorCodeHelper.insert(Any a, short that)
static short PolicyErrorCodeHelper.extract(Any a)
static void ParameterModeHelper.insert(Any a, ParameterMode that)
static ParameterMode ParameterModeHelper.extract(Any a)
static void WStringValueHelper.insert(Any a, String that)
static String WStringValueHelper.extract(Any a)
static void WCharSeqHelper.insert(Any a, char[] that)
static char[] WCharSeqHelper.extract(Any a)
static void VisibilityHelper.insert(Any a, short that)
static short VisibilityHelper.extract(Any a)
static void VersionSpecHelper.insert(Any a, String that)
static String VersionSpecHelper.extract(Any a)
static void ValueMemberHelper.insert(Any a, ValueMember that)
static ValueMember ValueMemberHelper.extract(Any a)
static void ValueBaseHelper.insert(Any a, Serializable that)
static Serializable ValueBaseHelper.extract(Any a)
static void UnionMemberHelper.insert(Any a, UnionMember that)
static UnionMember UnionMemberHelper.extract(Any a)
static void UShortSeqHelper.insert(Any a, short[] that)
static short[] UShortSeqHelper.extract(Any a)
static void ULongSeqHelper.insert(Any a, int[] that)
static int[] ULongSeqHelper.extract(Any a)
static void ULongLongSeqHelper.insert(Any a, long[] that)
static long[] ULongLongSeqHelper.extract(Any a)
static void StructMemberHelper.insert(Any a, StructMember that)
static StructMember StructMemberHelper.extract(Any a)
static void StringValueHelper.insert(Any a, String that)
static String StringValueHelper.extract(Any a)
static void ShortSeqHelper.insert(Any a, short[] that)
static short[] ShortSeqHelper.extract(Any a)
static void SetOverrideTypeHelper.insert(Any a, SetOverrideType that)
static SetOverrideType SetOverrideTypeHelper.extract(Any a)
static void RepositoryIdHelper.insert(Any a, String that)
static String RepositoryIdHelper.extract(Any a)
static void PolicyListHelper.insert(Any a, Policy[] that)
static Policy[] PolicyListHelper.extract(Any a)
static void PolicyTypeHelper.insert(Any a, int that)
static int PolicyTypeHelper.extract(Any a)
static void PolicyHelper.insert(Any a, Policy that)
static Policy PolicyHelper.extract(Any a)
static void OctetSeqHelper.insert(Any a, byte[] that)
static byte[] OctetSeqHelper.extract(Any a)
static void NameValuePairHelper.insert(Any a, NameValuePair that)
static NameValuePair NameValuePairHelper.extract(Any a)
static void LongSeqHelper.insert(Any a, int[] that)
static int[] LongSeqHelper.extract(Any a)
static void LongLongSeqHelper.insert(Any a, long[] that)
static long[] LongLongSeqHelper.extract(Any a)
static void IdentifierHelper.insert(Any a, String that)
static String IdentifierHelper.extract(Any a)
static void IDLTypeHelper.insert(Any a, IDLType that)
static IDLType IDLTypeHelper.extract(Any a)
static void FloatSeqHelper.insert(Any a, float[] that)
static float[] FloatSeqHelper.extract(Any a)
static void FieldNameHelper.insert(Any a, String that)
static String FieldNameHelper.extract(Any a)
static void DoubleSeqHelper.insert(Any a, double[] that)
static double[] DoubleSeqHelper.extract(Any a)
static void DefinitionKindHelper.insert(Any a, DefinitionKind that)
static DefinitionKind DefinitionKindHelper.extract(Any a)
 void DataOutputStream.write_any(Any value)
Writes the Any value to the output stream.
 void DataOutputStream.write_any_array(Any[] seq, int offset, int length)
Writes the array of IDL Anys from offset for length elements to the output stream.
static void CurrentHelper.insert(Any a, Current that)
static Current CurrentHelper.extract(Any a)
static void CompletionStatusHelper.insert(Any a, CompletionStatus that)
static CompletionStatus CompletionStatusHelper.extract(Any a)
static void CharSeqHelper.insert(Any a, char[] that)
static char[] CharSeqHelper.extract(Any a)
static void BooleanSeqHelper.insert(Any a, boolean[] that)
static boolean[] BooleanSeqHelper.extract(Any a)
static void AnySeqHelper.insert(Any a, Any[] that)
static Any[] AnySeqHelper.extract(Any a)
static void AnySeqHelper.write(OutputStream ostream, Any[] value)
static ServiceDetail ServiceDetailHelper.extract(Any a)
static void ServiceDetailHelper.insert(Any a, ServiceDetail that)
static void ObjectHelper.insert(Any a, Object that)
static Object ObjectHelper.extract(Any a)
static ServiceInformation ServiceInformationHelper.extract(Any a)
static void ServiceInformationHelper.insert(Any a, ServiceInformation that)
static void WrongTransactionHelper.insert(Any a, WrongTransaction that)
static WrongTransaction WrongTransactionHelper.extract(Any a)
 void ServerRequest.result(Any any)
Deprecated. use the method set_result
 void ServerRequest.set_result(Any any)
Throws an org.omg.CORBA.NO_IMPLEMENT exception.
 void ServerRequest.except(Any any)
Deprecated. use set_exception()
 void ServerRequest.set_exception(Any any)
Throws an org.omg.CORBA.NO_IMPLEMENT exception.
 void DynArray.set_elements(Any[] value)
Sets the value of this DynArray object to the given array.
 void DynSequence.set_elements(Any[] value)
Sets the values of all elements in this sequence with the given array.
 void DynAny.from_any(Any value)
Make a DynAny object from an Any object.
 void DynAny.insert_any(Any value)
Inserts the given org.omg.CORBA.Any object as the value for this DynAny object.
abstract  void Context.set_one_value(String propname, Any propvalue)
Creates a NamedValue object and adds it to this Context object.
abstract  boolean Any.equal(Any a)
Checks for equality between this Any object and the given Any object.
abstract  void Any.insert_any(Any a)
Inserts the given Any object into this Any object's value field.
abstract  NamedValue NVList.add_value(String item_name, Any val, int flags)
Creates a new NamedValue object initialized with the given name, value, and flag, and adds it to the end of this NVList object.
abstract  NamedValue ORB.create_named_value(String s, Any any, int flags)
Creates a NamedValue object using the given name, value, and argument mode flags.
 DynAny ORB.create_dyn_any(Any value)
Creates a new DynAny object from the given Any object.
 Policy ORB.create_policy(int type, Any val)
Can be invoked to create new instances of policy objects of a specific type with specified initial state.

Constructors in org.omg.CORBA with parameters of type Any
AnySeqHolder(Any[] initialValue)
UnknownUserException(Any a)
Constructs an UnknownUserException object that contains the given Any object.
AnyHolder(Any initial)
Constructs a new AnyHolder object for the given Any object.
NameValuePair(String __id, Any __value)
Constructs a NameValuePair object that associates the given name with the given org.omg.CORBA.Any object.
UnionMember(String __name, Any __label, TypeCode __type, IDLType __type_def)
Constructs a new UnionMember object with its fields initialized to the given values.

Uses of Any in org.omg.CORBA.portable

Methods in org.omg.CORBA.portable that return Any
abstract  Any InputStream.read_any()
Reads an Any from this input stream.

Methods in org.omg.CORBA.portable with parameters of type Any
abstract  void OutputStream.write_any(Any value)
Writes an Any on this output stream.

Uses of Any in org.omg.CosNaming

Methods in org.omg.CosNaming with parameters of type Any
static void | NamingContextExtHelper.insert(Any a, NamingContextExt that)
static NamingContextExt | NamingContextExtHelper.extract(Any a)
static void | NamingContextHelper.insert(Any a, NamingContext that)
static NamingContext | NamingContextHelper.extract(Any a)
static void | NameHelper.insert(Any a, NameComponent[] that)
static NameComponent[] | NameHelper.extract(Any a)
static void | NameComponentHelper.insert(Any a, NameComponent that)
static NameComponent | NameComponentHelper.extract(Any a)
static void | BindingTypeHelper.insert(Any a, BindingType that)
static BindingType | BindingTypeHelper.extract(Any a)
static void | BindingListHelper.insert(Any a, Binding[] that)
static Binding[] | BindingListHelper.extract(Any a)
static void | BindingIteratorHelper.insert(Any a, BindingIterator that)
static BindingIterator | BindingIteratorHelper.extract(Any a)
static void | BindingHelper.insert(Any a, Binding that)
static Binding | BindingHelper.extract(Any a)
static void | IstringHelper.insert(Any a, String that)
static String | IstringHelper.extract(Any a)

Uses of Any in org.omg.CosNaming.NamingContextExtPackage

Methods in org.omg.CosNaming.NamingContextExtPackage with parameters of type Any
static void | URLStringHelper.insert(Any a, String that)
static String | URLStringHelper.extract(Any a)
static void | StringNameHelper.insert(Any a, String that)
static String | StringNameHelper.extract(Any a)
static void | InvalidAddressHelper.insert(Any a, InvalidAddress that)
static InvalidAddress | InvalidAddressHelper.extract(Any a)
static void | AddressHelper.insert(Any a, String that)
static String | AddressHelper.extract(Any a)

Uses of Any in org.omg.CosNaming.NamingContextPackage

Methods in org.omg.CosNaming.NamingContextPackage with parameters of type Any
static void | NotFoundReasonHelper.insert(Any a, NotFoundReason that)
static NotFoundReason | NotFoundReasonHelper.extract(Any a)
static void | NotFoundHelper.insert(Any a, NotFound that)
static NotFound | NotFoundHelper.extract(Any a)
static void | NotEmptyHelper.insert(Any a, NotEmpty that)
static NotEmpty | NotEmptyHelper.extract(Any a)
static void | InvalidNameHelper.insert(Any a, InvalidName that)
static InvalidName | InvalidNameHelper.extract(Any a)
static void | CannotProceedHelper.insert(Any a, CannotProceed that)
static CannotProceed | CannotProceedHelper.extract(Any a)
static void | AlreadyBoundHelper.insert(Any a, AlreadyBound that)
static AlreadyBound | AlreadyBoundHelper.extract(Any a)

Uses of Any in org.omg.Dynamic

Fields in org.omg.Dynamic declared as Any
 Any Parameter.argument

Constructors in org.omg.Dynamic with parameters of type Any
Parameter(Any _argument, ParameterMode _mode)

Uses of Any in org.omg.DynamicAny

Fields in org.omg.DynamicAny declared as Any
 Any NameValuePair.value
The Any value associated with the name.

Methods in org.omg.DynamicAny that return Any
Any | DynValueBoxOperations.get_boxed_value() Returns the boxed value as an Any.
Any[] | _DynSequenceStub.get_elements() Returns the elements of the sequence.
Any | _DynSequenceStub.to_any() Creates an any value from a DynAny object.
Any | _DynSequenceStub.get_any() Extracts an Any value contained in the Any represented by this DynAny.
Any | _DynFixedStub.to_any() Creates an any value from a DynAny object.
Any | _DynFixedStub.get_any() Extracts an Any value contained in the Any represented by this DynAny.
Any | _DynEnumStub.to_any() Creates an any value from a DynAny object.
Any | _DynEnumStub.get_any() Extracts an Any value contained in the Any represented by this DynAny.
Any[] | _DynArrayStub.get_elements() Returns the elements of the DynArray.
Any | _DynArrayStub.to_any() Creates an any value from a DynAny object.
Any | _DynArrayStub.get_any() Extracts an Any value contained in the Any represented by this DynAny.
Any | _DynValueStub.to_any() Creates an any value from a DynAny object.
Any | _DynValueStub.get_any() Extracts an Any value contained in the Any represented by this DynAny.
Any | _DynAnyStub.to_any() Creates an any value from a DynAny object.
Any | _DynAnyStub.get_any() Extracts an Any value contained in the Any represented by this DynAny.
Any | _DynUnionStub.to_any() Creates an any value from a DynAny object.
Any | _DynUnionStub.get_any() Extracts an Any value contained in the Any represented by this DynAny.
Any | _DynStructStub.to_any() Creates an any value from a DynAny object.
Any | _DynStructStub.get_any() Extracts an Any value contained in the Any represented by this DynAny.
static Any[] | AnySeqHelper.extract(Any a)
static Any[] | AnySeqHelper.read(InputStream istream)
Any[] | DynSequenceOperations.get_elements() Returns the elements of the sequence.
Any[] | DynArrayOperations.get_elements() Returns the elements of the DynArray.
Any | DynAnyOperations.to_any() Creates an any value from a DynAny object.
Any | DynAnyOperations.get_any() Extracts an Any value contained in the Any represented by this DynAny.

Methods in org.omg.DynamicAny with parameters of type Any
void | DynValueBoxOperations.set_boxed_value(Any boxed) Replaces the boxed value with the specified value.
void | _DynSequenceStub.set_elements(Any[] value) Sets the elements of a sequence.
void | _DynSequenceStub.from_any(Any value) Initializes the value associated with a DynAny object with the value contained in an any.
void | _DynSequenceStub.insert_any(Any value) Inserts an Any value into the Any represented by this DynAny.
void | _DynFixedStub.from_any(Any value) Initializes the value associated with a DynAny object with the value contained in an any.
void | _DynFixedStub.insert_any(Any value) Inserts an Any value into the Any represented by this DynAny.
void | _DynEnumStub.from_any(Any value) Initializes the value associated with a DynAny object with the value contained in an any.
void | _DynEnumStub.insert_any(Any value) Inserts an Any value into the Any represented by this DynAny.
void | _DynArrayStub.set_elements(Any[] value) Sets the DynArray to contain the passed elements.
void | _DynArrayStub.from_any(Any value) Initializes the value associated with a DynAny object with the value contained in an any.
void | _DynArrayStub.insert_any(Any value) Inserts an Any value into the Any represented by this DynAny.
void | _DynValueStub.from_any(Any value) Initializes the value associated with a DynAny object with the value contained in an any.
void | _DynValueStub.insert_any(Any value) Inserts an Any value into the Any represented by this DynAny.
void | _DynAnyStub.from_any(Any value) Initializes the value associated with a DynAny object with the value contained in an any.
void | _DynAnyStub.insert_any(Any value) Inserts an Any value into the Any represented by this DynAny.
void | _DynUnionStub.from_any(Any value) Initializes the value associated with a DynAny object with the value contained in an any.
void | _DynUnionStub.insert_any(Any value) Inserts an Any value into the Any represented by this DynAny.
DynAny | _DynAnyFactoryStub.create_dyn_any(Any value) Creates a new DynAny object from an any value.
void | _DynStructStub.from_any(Any value) Initializes the value associated with a DynAny object with the value contained in an any.
void | _DynStructStub.insert_any(Any value) Inserts an Any value into the Any represented by this DynAny.
static void | NameValuePairSeqHelper.insert(Any a, NameValuePair[] that)
static NameValuePair[] | NameValuePairSeqHelper.extract(Any a)
static void | NameValuePairHelper.insert(Any a, NameValuePair that)
static NameValuePair | NameValuePairHelper.extract(Any a)
static void | NameDynAnyPairSeqHelper.insert(Any a, NameDynAnyPair[] that)
static NameDynAnyPair[] | NameDynAnyPairSeqHelper.extract(Any a)
static void | DynSequenceHelper.insert(Any a, DynSequence that)
static DynSequence | DynSequenceHelper.extract(Any a)
static void | NameDynAnyPairHelper.insert(Any a, NameDynAnyPair that)
static NameDynAnyPair | NameDynAnyPairHelper.extract(Any a)
static void | FieldNameHelper.insert(Any a, String that)
static String | FieldNameHelper.extract(Any a)
static void | DynFixedHelper.insert(Any a, DynFixed that)
static DynFixed | DynFixedHelper.extract(Any a)
static void | DynEnumHelper.insert(Any a, DynEnum that)
static DynEnum | DynEnumHelper.extract(Any a)
static void | DynAnySeqHelper.insert(Any a, DynAny[] that)
static DynAny[] | DynAnySeqHelper.extract(Any a)
static void | DynArrayHelper.insert(Any a, DynArray that)
static DynArray | DynArrayHelper.extract(Any a)
static void | DynValueHelper.insert(Any a, DynValue that)
static DynValue | DynValueHelper.extract(Any a)
static void | DynAnyHelper.insert(Any a, DynAny that)
static DynAny | DynAnyHelper.extract(Any a)
static void | DynUnionHelper.insert(Any a, DynUnion that)
static DynUnion | DynUnionHelper.extract(Any a)
static void | DynAnyFactoryHelper.insert(Any a, DynAnyFactory that)
static DynAnyFactory | DynAnyFactoryHelper.extract(Any a)
static void | DynStructHelper.insert(Any a, DynStruct that)
static DynStruct | DynStructHelper.extract(Any a)
static void | AnySeqHelper.insert(Any a, Any[] that)
static Any[] | AnySeqHelper.extract(Any a)
static void | AnySeqHelper.write(OutputStream ostream, Any[] value)
void | DynSequenceOperations.set_elements(Any[] value) Sets the elements of a sequence.
void | DynArrayOperations.set_elements(Any[] value) Sets the DynArray to contain the passed elements.
DynAny | DynAnyFactoryOperations.create_dyn_any(Any value) Creates a new DynAny object from an any value.
void | DynAnyOperations.from_any(Any value) Initializes the value associated with a DynAny object with the value contained in an any.
void | DynAnyOperations.insert_any(Any value) Inserts an Any value into the Any represented by this DynAny.

Constructors in org.omg.DynamicAny with parameters of type Any
NameValuePair(String _id, Any _value)

Uses of Any in org.omg.DynamicAny.DynAnyFactoryPackage

Methods in org.omg.DynamicAny.DynAnyFactoryPackage with parameters of type Any
static void | InconsistentTypeCodeHelper.insert(Any a, InconsistentTypeCode that)
static InconsistentTypeCode | InconsistentTypeCodeHelper.extract(Any a)

Uses of Any in org.omg.DynamicAny.DynAnyPackage

Methods in org.omg.DynamicAny.DynAnyPackage with parameters of type Any
static void | TypeMismatchHelper.insert(Any a, TypeMismatch that)
static TypeMismatch | TypeMismatchHelper.extract(Any a)
static void | InvalidValueHelper.insert(Any a, InvalidValue that)
static InvalidValue | InvalidValueHelper.extract(Any a)

Uses of Any in org.omg.IOP

Methods in org.omg.IOP that return Any
Any | CodecOperations.decode(byte[] data) Decodes the given byte array into an Any based on the encoding format effective for this Codec.
Any | CodecOperations.decode_value(byte[] data, TypeCode tc) Decodes the given byte array into an Any based on the given TypeCode and the encoding format effective for this Codec.

Methods in org.omg.IOP with parameters of type Any
static void | TaggedProfileHelper.insert(Any a, TaggedProfile that)
static TaggedProfile | TaggedProfileHelper.extract(Any a)
static void | TaggedComponentHelper.insert(Any a, TaggedComponent that)
static TaggedComponent | TaggedComponentHelper.extract(Any a)
static void | ServiceIdHelper.insert(Any a, int that)
static int | ServiceIdHelper.extract(Any a)
static void | ServiceContextListHelper.insert(Any a, ServiceContext[] that)
static ServiceContext[] | ServiceContextListHelper.extract(Any a)
static void | ServiceContextHelper.insert(Any a, ServiceContext that)
static ServiceContext | ServiceContextHelper.extract(Any a)
static void | ProfileIdHelper.insert(Any a, int that)
static int | ProfileIdHelper.extract(Any a)
static void | MultipleComponentProfileHelper.insert(Any a, TaggedComponent[] that)
static TaggedComponent[] | MultipleComponentProfileHelper.extract(Any a)
static void | IORHelper.insert(Any a, IOR that)
static IOR | IORHelper.extract(Any a)
static void | ComponentIdHelper.insert(Any a, int that)
static int | ComponentIdHelper.extract(Any a)
static void | CodecFactoryHelper.insert(Any a, CodecFactory that)
static CodecFactory | CodecFactoryHelper.extract(Any a)
byte[] | CodecOperations.encode(Any data) Converts the given any into a byte array based on the encoding format effective for this Codec.
byte[] | CodecOperations.encode_value(Any data) Converts the given any into a byte array based on the encoding format effective for this Codec.

Uses of Any in org.omg.IOP.CodecFactoryPackage

Methods in org.omg.IOP.CodecFactoryPackage with parameters of type Any
static void | UnknownEncodingHelper.insert(Any a, UnknownEncoding that)
static UnknownEncoding | UnknownEncodingHelper.extract(Any a)

Uses of Any in org.omg.IOP.CodecPackage

Methods in org.omg.IOP.CodecPackage with parameters of type Any
static void | TypeMismatchHelper.insert(Any a, TypeMismatch that)
static TypeMismatch | TypeMismatchHelper.extract(Any a)
static void | InvalidTypeForEncodingHelper.insert(Any a, InvalidTypeForEncoding that)
static InvalidTypeForEncoding | InvalidTypeForEncodingHelper.extract(Any a)
static void | FormatMismatchHelper.insert(Any a, FormatMismatch that)
static FormatMismatch | FormatMismatchHelper.extract(Any a)

Uses of Any in org.omg.Messaging

Methods in org.omg.Messaging with parameters of type Any
static void | SyncScopeHelper.insert(Any a, short that)
static short | SyncScopeHelper.extract(Any a)

Uses of Any in org.omg.PortableInterceptor

Methods in org.omg.PortableInterceptor that return Any
Any | ServerRequestInfoOperations.sending_exception() Returns an any which contains the exception to be returned to the client.
Any | CurrentOperations.get_slot(int id) Retrieves the slot data the application set in PICurrent via get_slot.
Any | RequestInfoOperations.result() Returns an any containing the result of the operation invocation.
Any | RequestInfoOperations.get_slot(int id) Returns the data from the given slot of the PortableInterceptor.Current that is in the scope of the request.
Any | ClientRequestInfoOperations.received_exception() Returns an any which contains the exception to be returned to the client.

Methods in org.omg.PortableInterceptor with parameters of type Any
Policy | PolicyFactoryOperations.create_policy(int type, Any value) Returns an instance of the appropriate interface derived from CORBA.Policy whose value corresponds to the specified any.
void | ServerRequestInfoOperations.set_slot(int id, Any data) Allows an Interceptor to set a slot in the PortableInterceptor.Current that is in the scope of the request.
static void | InvalidSlotHelper.insert(Any a, InvalidSlot that)
static InvalidSlot | InvalidSlotHelper.extract(Any a)
static void | ForwardRequestHelper.insert(Any a, ForwardRequest that)
static ForwardRequest | ForwardRequestHelper.extract(Any a)
static void | CurrentHelper.insert(Any a, Current that)
static Current | CurrentHelper.extract(Any a)
void | CurrentOperations.set_slot(int id, Any data) Sets data in a slot.

Uses of Any in org.omg.PortableInterceptor.ORBInitInfoPackage

Methods in org.omg.PortableInterceptor.ORBInitInfoPackage with parameters of type Any
static void | ObjectIdHelper.insert(Any a, String that)
static String | ObjectIdHelper.extract(Any a)
static void | InvalidNameHelper.insert(Any a, InvalidName that)
static InvalidName | InvalidNameHelper.extract(Any a)
static void | DuplicateNameHelper.insert(Any a, DuplicateName that)
static DuplicateName | DuplicateNameHelper.extract(Any a)

Uses of Any in org.omg.PortableServer

Methods in org.omg.PortableServer with parameters of type Any
static void | ServantLocatorHelper.insert(Any a, ServantLocator that)
static ServantLocator | ServantLocatorHelper.extract(Any a)
static void | ServantActivatorHelper.insert(Any a, ServantActivator that)
static ServantActivator | ServantActivatorHelper.extract(Any a)
static void | POAHelper.insert(Any a, POA that)
static POA | POAHelper.extract(Any a)
static void | ForwardRequestHelper.insert(Any a, ForwardRequest that)
static ForwardRequest | ForwardRequestHelper.extract(Any a)
static void | CurrentHelper.insert(Any a, Current that)
static Current | CurrentHelper.extract(Any a)

Uses of Any in org.omg.PortableServer.CurrentPackage

Methods in org.omg.PortableServer.CurrentPackage with parameters of type Any
static void | NoContextHelper.insert(Any a, NoContext that)
static NoContext | NoContextHelper.extract(Any a)

Uses of Any in org.omg.PortableServer.POAManagerPackage

Methods in org.omg.PortableServer.POAManagerPackage with parameters of type Any
static void | AdapterInactiveHelper.insert(Any a, AdapterInactive that)
static AdapterInactive | AdapterInactiveHelper.extract(Any a)

Uses of Any in org.omg.PortableServer.POAPackage

Methods in org.omg.PortableServer.POAPackage with parameters of type Any
static void | WrongPolicyHelper.insert(Any a, WrongPolicy that)
static WrongPolicy | WrongPolicyHelper.extract(Any a)
static void | WrongAdapterHelper.insert(Any a, WrongAdapter that)
static WrongAdapter | WrongAdapterHelper.extract(Any a)
static void | ServantNotActiveHelper.insert(Any a, ServantNotActive that)
static ServantNotActive | ServantNotActiveHelper.extract(Any a)
static void | ServantAlreadyActiveHelper.insert(Any a, ServantAlreadyActive that)
static ServantAlreadyActive | ServantAlreadyActiveHelper.extract(Any a)
static void | ObjectNotActiveHelper.insert(Any a, ObjectNotActive that)
static ObjectNotActive | ObjectNotActiveHelper.extract(Any a)
static void | ObjectAlreadyActiveHelper.insert(Any a, ObjectAlreadyActive that)
static ObjectAlreadyActive | ObjectAlreadyActiveHelper.extract(Any a)
static void | NoServantHelper.insert(Any a, NoServant that)
static NoServant | NoServantHelper.extract(Any a)
static void | InvalidPolicyHelper.insert(Any a, InvalidPolicy that)
static InvalidPolicy | InvalidPolicyHelper.extract(Any a)
static void | AdapterNonExistentHelper.insert(Any a, AdapterNonExistent that)
static AdapterNonExistent | AdapterNonExistentHelper.extract(Any a)
static void | AdapterAlreadyExistsHelper.insert(Any a, AdapterAlreadyExists that)
static AdapterAlreadyExists | AdapterAlreadyExistsHelper.extract(Any a)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.AnyHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.AnyHolder

No usage of org.omg.CORBA.AnyHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.AnySeqHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.AnySeqHelper

No usage of org.omg.CORBA.AnySeqHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.AnySeqHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.AnySeqHolder

Packages that use AnySeqHolder
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).

Uses of AnySeqHolder in org.omg.CORBA

Methods in org.omg.CORBA with parameters of type AnySeqHolder
 void DataInputStream.read_any_array(AnySeqHolder seq, int offset, int length)
Reads array of IDL Anys from offset for length elements from the input stream.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.ARG_IN (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.ARG_IN

No usage of org.omg.CORBA.ARG_IN

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.ARG_INOUT (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.ARG_INOUT

No usage of org.omg.CORBA.ARG_INOUT

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.ARG_OUT (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.ARG_OUT

No usage of org.omg.CORBA.ARG_OUT

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.BAD_CONTEXT (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.BAD_CONTEXT

No usage of org.omg.CORBA.BAD_CONTEXT

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.BAD_INV_ORDER (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.BAD_INV_ORDER

Packages that use BAD_INV_ORDER
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).

Uses of BAD_INV_ORDER in org.omg.CORBA

Methods in org.omg.CORBA that throw BAD_INV_ORDER
Streamable | Any.extract_Streamable() Extracts a Streamable from this Any object's value field.
void | Any.insert_fixed(BigDecimal value, TypeCode type) Throws an org.omg.CORBA.NO_IMPLEMENT exception.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.BAD_OPERATION (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.BAD_OPERATION

Packages that use BAD_OPERATION
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).

Uses of BAD_OPERATION in org.omg.CORBA

Methods in org.omg.CORBA that throw BAD_OPERATION
abstract short | Any.extract_short() Extracts the short in this Any object's value field.
abstract int | Any.extract_long() Extracts the int in this Any object's value field.
abstract long | Any.extract_longlong() Extracts the long in this Any object's value field.
abstract short | Any.extract_ushort() Extracts the short in this Any object's value field.
abstract int | Any.extract_ulong() Extracts the int in this Any object's value field.
abstract long | Any.extract_ulonglong() Extracts the long in this Any object's value field.
abstract float | Any.extract_float() Extracts the float in this Any object's value field.
abstract double | Any.extract_double() Extracts the double in this Any object's value field.
abstract boolean | Any.extract_boolean() Extracts the boolean in this Any object's value field.
abstract char | Any.extract_char() Extracts the char in this Any object's value field.
abstract char | Any.extract_wchar() Extracts the char in this Any object's value field.
abstract byte | Any.extract_octet() Extracts the byte in this Any object's value field.
abstract Any | Any.extract_any() Extracts the Any object in this Any object's value field.
abstract Object | Any.extract_Object() Extracts the org.omg.CORBA.Object in this Any object's value field.
abstract Serializable | Any.extract_Value() Extracts the java.io.Serializable object in this Any object's value field.
abstract String | Any.extract_string() Extracts the String object in this Any object's value field.
abstract String | Any.extract_wstring() Extracts the String object in this Any object's value field.
abstract TypeCode | Any.extract_TypeCode() Extracts the TypeCode object in this Any object's value field.
Principal | Any.extract_Principal() Deprecated. Deprecated by CORBA 2.2.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.BAD_PARAM (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.BAD_PARAM

Packages that use BAD_PARAM
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_2_3 | The CORBA_2_3 package defines additions to existing CORBA interfaces in the Java 2 Standard Edition. 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.

Uses of BAD_PARAM in org.omg.CORBA

Methods in org.omg.CORBA that throw BAD_PARAM
abstract  void Any.insert_Object(Object o, TypeCode t)
Inserts the given org.omg.CORBA.Object object into this Any object's value field.

Uses of BAD_PARAM in org.omg.CORBA_2_3

Methods in org.omg.CORBA_2_3 that throw BAD_PARAM
 Object ORB.get_value_def(String repid)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.BAD_POLICY (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.BAD_POLICY

No usage of org.omg.CORBA.BAD_POLICY

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.BAD_POLICY_TYPE (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.BAD_POLICY_TYPE

No usage of org.omg.CORBA.BAD_POLICY_TYPE

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.BAD_POLICY_VALUE (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.BAD_POLICY_VALUE

No usage of org.omg.CORBA.BAD_POLICY_VALUE

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.BAD_TYPECODE (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.BAD_TYPECODE

No usage of org.omg.CORBA.BAD_TYPECODE

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.BooleanHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.BooleanHolder

No usage of org.omg.CORBA.BooleanHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.BooleanSeqHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.BooleanSeqHelper

No usage of org.omg.CORBA.BooleanSeqHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.BooleanSeqHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.BooleanSeqHolder

Packages that use BooleanSeqHolder
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).

Uses of BooleanSeqHolder in org.omg.CORBA

Methods in org.omg.CORBA with parameters of type BooleanSeqHolder
 void DataInputStream.read_boolean_array(BooleanSeqHolder seq, int offset, int length)
Reads array of IDL booleans from offset for length elements from the input stream.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.Bounds (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.Bounds

Packages that use Bounds
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).

Uses of Bounds in org.omg.CORBA

Methods in org.omg.CORBA that throw Bounds
abstract TypeCode | ExceptionList.item(int index) Returns the TypeCode object at the given index.
abstract void | ExceptionList.remove(int index) Removes the TypeCode object at the given index.
abstract String | ContextList.item(int index) Returns the String object at the given index.
abstract void | ContextList.remove(int index) Removes the String object at the given index.
abstract NamedValue | NVList.item(int index) Retrieves the NamedValue object at the given index.
abstract void | NVList.remove(int index) Removes the NamedValue object at the given index.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.ByteHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.ByteHolder

No usage of org.omg.CORBA.ByteHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.CharHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.CharHolder

No usage of org.omg.CORBA.CharHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.CharSeqHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.CharSeqHelper

No usage of org.omg.CORBA.CharSeqHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.CharSeqHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.CharSeqHolder

Packages that use CharSeqHolder
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).

Uses of CharSeqHolder in org.omg.CORBA

Methods in org.omg.CORBA with parameters of type CharSeqHolder
 void DataInputStream.read_char_array(CharSeqHolder seq, int offset, int length)
Reads array of IDL characters from offset for length elements from the input stream.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.COMM_FAILURE (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.COMM_FAILURE

No usage of org.omg.CORBA.COMM_FAILURE

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.CompletionStatus (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.CompletionStatus

Packages that use CompletionStatus
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).

Uses of CompletionStatus in org.omg.CORBA

Fields in org.omg.CORBA declared as CompletionStatus
static CompletionStatus | CompletionStatus.COMPLETED_YES An instance of CompletionStatus initialized with the constant _COMPLETED_YES.
static CompletionStatus | CompletionStatus.COMPLETED_NO An instance of CompletionStatus initialized with the constant _COMPLETED_NO.
static CompletionStatus | CompletionStatus.COMPLETED_MAYBE An instance of CompletionStatus initialized with the constant _COMPLETED_MAYBE.
CompletionStatus | SystemException.completed The status of the operation that threw this exception.

Methods in org.omg.CORBA that return CompletionStatus
static CompletionStatus | CompletionStatusHelper.extract(Any a)
static CompletionStatus | CompletionStatusHelper.read(InputStream istream)
static CompletionStatus | CompletionStatus.from_int(int i) Creates a CompletionStatus object from the given int.

Methods in org.omg.CORBA with parameters of type CompletionStatus
static void | CompletionStatusHelper.insert(Any a, CompletionStatus that)
static void | CompletionStatusHelper.write(OutputStream ostream, CompletionStatus value)

Constructors in org.omg.CORBA with parameters of type CompletionStatus
UNKNOWN(int minor, CompletionStatus completed)
Constructs an UNKNOWN exception with the specified minor code and completion status.
UNKNOWN(String s, int minor, CompletionStatus completed)
Constructs an UNKNOWN exception with the specified description message, minor code, and completion status.
TRANSACTION_ROLLEDBACK(int minor, CompletionStatus completed)
Constructs a TRANSACTION_ROLLEDBACK exception with the specified minor code and completion status.
TRANSACTION_ROLLEDBACK(String s, int minor, CompletionStatus completed)
Constructs a TRANSACTION_ROLLEDBACK exception with the specified description message, minor code, and completion status.
TRANSACTION_REQUIRED(int minor, CompletionStatus completed)
Constructs a TRANSACTION_REQUIRED exception with the specified minor code and completion status.
TRANSACTION_REQUIRED(String s, int minor, CompletionStatus completed)
Constructs a TRANSACTION_REQUIRED exception with the specified description message, minor code, and completion status.
TRANSIENT(int minor, CompletionStatus completed)
Constructs a TRANSIENT exception with the specified minor code and completion status.
TRANSIENT(String s, int minor, CompletionStatus completed)
Constructs a TRANSIENT exception with the specified description message, minor code, and completion status.
PERSIST_STORE(int minor, CompletionStatus completed)
Constructs a PERSIST_STORE exception with the specified minor code and completion status.
PERSIST_STORE(String s, int minor, CompletionStatus completed)
Constructs a PERSIST_STORE exception with the specified description message, minor code, and completion status.
OBJ_ADAPTER(int minor, CompletionStatus completed)
Constructs an OBJ_ADAPTER exception with the specified minor code and completion status.
OBJ_ADAPTER(String s, int minor, CompletionStatus completed)
Constructs an OBJ_ADAPTER exception with the specified description message, minor code, and completion status.
OBJECT_NOT_EXIST(int minor, CompletionStatus completed)
Constructs an OBJECT_NOT_EXIST exception with the specified minor code and completion status.
OBJECT_NOT_EXIST(String s, int minor, CompletionStatus completed)
Constructs an OBJECT_NOT_EXIST exception with the specified description message, minor code, and completion status.
NO_RESPONSE(int minor, CompletionStatus completed)
Constructs a NO_RESPONSE exception with the specified minor code and completion status.
NO_RESPONSE(String s, int minor, CompletionStatus completed)
Constructs a NO_RESPONSE exception with the specified description message, minor code, and completion status.
NO_RESOURCES(int minor, CompletionStatus completed)
Constructs a NO_RESOURCES exception with the specified minor code and completion status.
NO_RESOURCES(String s, int minor, CompletionStatus completed)
Constructs a NO_RESOURCES exception with the specified description message, minor code, and completion status.
NO_PERMISSION(int minor, CompletionStatus completed)
Constructs a NO_PERMISSION exception with the specified minor code and completion status.
NO_PERMISSION(String s, int minor, CompletionStatus completed)
Constructs a NO_PERMISSION exception with the specified description message, minor code, and completion status.
NO_MEMORY(int minor, CompletionStatus completed)
Constructs a NO_MEMORY exception with the specified minor code and completion status.
NO_MEMORY(String s, int minor, CompletionStatus completed)
Constructs a NO_MEMORY exception with the specified description message, minor code, and completion status.
INV_POLICY(int minor, CompletionStatus completed)
Constructs a INV_POLICY exception with the specified minor code and completion status.
INV_POLICY(String s, int minor, CompletionStatus completed)
Constructs a INV_POLICY exception with the specified description message, minor code, and completion status.
INV_OBJREF(int minor, CompletionStatus completed)
Constructs an INV_OBJREF exception with the specified minor code and completion status.
INV_OBJREF(String s, int minor, CompletionStatus completed)
Constructs an INV_OBJREF exception with the specified detail message, minor code, and completion status.
INV_IDENT(int minor, CompletionStatus completed)
Constructs an INV_IDENT exception with the specified minor code and completion status.
INV_IDENT(String s, int minor, CompletionStatus completed)
Constructs an INV_IDENT exception with the specified detail message, minor code, and completion status.
INV_FLAG(int minor, CompletionStatus completed)
Constructs an INV_FLAG exception with the specified minor code and completion status.
INV_FLAG(String s, int minor, CompletionStatus completed)
Constructs an INV_FLAG exception with the specified detail message, minor code, and completion status.
INVALID_TRANSACTION(int minor, CompletionStatus completed)
Constructs an INVALID_TRANSACTION exception with the specified minor code and completion status.
INVALID_TRANSACTION(String s, int minor, CompletionStatus completed)
Constructs an INVALID_TRANSACTION exception with the specified detail message, minor code, and completion status.
INTF_REPOS(int minor, CompletionStatus completed)
Constructs an INTF_REPOS exception with the specified minor code and completion status.
INTF_REPOS(String s, int minor, CompletionStatus completed)
Constructs an INTF_REPOS exception with the specified detail message, minor code, and completion status.
INTERNAL(int minor, CompletionStatus completed)
Constructs an INTERNAL exception with the specified minor code and completion status.
INTERNAL(String s, int minor, CompletionStatus completed)
Constructs an INTERNAL exception with the specified detail message, minor code, and completion status.
IMP_LIMIT(int minor, CompletionStatus completed)
Constructs an IMP_LIMIT exception with the specified minor code and completion status.
IMP_LIMIT(String s, int minor, CompletionStatus completed)
Constructs an IMP_LIMIT exception with the specified detail message, minor code, and completion status.
FREE_MEM(int minor, CompletionStatus completed)
Constructs a FREE_MEM exception with the specified minor code and completion status.
FREE_MEM(String s, int minor, CompletionStatus completed)
Constructs a FREE_MEM exception with the specified detail message, minor code, and completion status.
COMM_FAILURE(int minor, CompletionStatus completed)
Constructs a COMM_FAILURE exception with the specified minor code and completion status.
COMM_FAILURE(String s, int minor, CompletionStatus completed)
Constructs a COMM_FAILURE exception with the specified detail message, minor code, and completion status.
BAD_TYPECODE(int minor, CompletionStatus completed)
Constructs a BAD_TYPECODE exception with the specified minor code and completion status.
BAD_TYPECODE(String s, int minor, CompletionStatus completed)
Constructs a BAD_TYPECODE exception with the specified detail message, minor code, and completion status.
BAD_CONTEXT(int minor, CompletionStatus completed)
Constructs a BAD_CONTEXT exception with the specified minor code and completion status.
BAD_CONTEXT(String s, int minor, CompletionStatus completed)
Constructs a BAD_CONTEXT exception with the specified detail message, minor code, and completion status.
INITIALIZE(int minor, CompletionStatus completed)
Constructs an INITIALIZE exception with the specified minor code and completion status.
INITIALIZE(String s, int minor, CompletionStatus completed)
Constructs an INITIALIZE exception with the specified detail message, minor code, and completion status.
NO_IMPLEMENT(int minor, CompletionStatus completed)
Constructs a NO_IMPLEMENT exception with the specified minor code and completion status.
NO_IMPLEMENT(String s, int minor, CompletionStatus completed)
Constructs a NO_IMPLEMENT exception with the specified description message, minor code, and completion status.
BAD_INV_ORDER(int minor, CompletionStatus completed)
Constructs a BAD_INV_ORDER exceptionBAD_INV_ORDER with the specified minor code and completion status.
BAD_INV_ORDER(String s, int minor, CompletionStatus completed)
Constructs a BAD_INV_ORDER exception with the specified detail message, minor code, and completion status.
BAD_PARAM(int minor, CompletionStatus completed)
Constructs a BAD_PARAM exception with the specified minor code and completion status.
BAD_PARAM(String s, int minor, CompletionStatus completed)
Constructs a BAD_PARAM exception with the specified detail message, minor code, and completion status.
DATA_CONVERSION(int minor, CompletionStatus completed)
Constructs a DATA_CONVERSION exception with the specified minor code and completion status.
DATA_CONVERSION(String s, int minor, CompletionStatus completed)
Constructs a DATA_CONVERSION exception with the specified detail message, minor code, and completion status.
BAD_OPERATION(int minor, CompletionStatus completed)
Constructs a BAD_OPERATION exception with the specified minor code and completion status.
BAD_OPERATION(String s, int minor, CompletionStatus completed)
Constructs a BAD_OPERATION exception with the specified detail message, minor code, and completion status.
SystemException(String reason, int minor, CompletionStatus completed)
Constructs a SystemException exception with the specified detail message, minor code, and completion status.
MARSHAL(int minor, CompletionStatus completed)
Constructs a MARSHAL exception with the specified minor code and completion status.
MARSHAL(String s, int minor, CompletionStatus completed)
Constructs a MARSHAL exception with the specified description message, minor code, and completion status.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.CompletionStatusHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.CompletionStatusHelper

No usage of org.omg.CORBA.CompletionStatusHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.Context (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.Context

Packages that use Context
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.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.

Uses of Context in org.omg.CORBA

Methods in org.omg.CORBA that return Context
abstract Context | ServerRequest.ctx() Returns the context information specified in IDL for the operation when the operation is not an attribute access and the operation's IDL definition contains a context expression; otherwise it returns a nil Context reference.
abstract Context | Context.parent() Retrieves the parent of this Context object.
abstract Context | Context.create_child(String child_ctx_name) Creates a Context object with the given string as its name and with this Context object set as its parent.
abstract Context | Request.ctx() Retrieves the Context object for this request.
abstract Context | ORB.get_default_context() Gets the default Context object.

Methods in org.omg.CORBA with parameters of type Context
Request | LocalObject._create_request(Context ctx, String operation, NVList arg_list, NamedValue result) Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.
Request | LocalObject._create_request(Context ctx, String operation, NVList arg_list, NamedValue result, ExceptionList exceptions, ContextList contexts) Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.
abstract void | Request.ctx(Context c) Sets this request's Context object to the one given.
Request | Object._create_request(Context ctx, String operation, NVList arg_list, NamedValue result) Creates a Request instance initialized with the given context, method name, list of arguments, and container for the method's return value.
Request | Object._create_request(Context ctx, String operation, NVList arg_list, NamedValue result, ExceptionList exclist, ContextList ctxlist) Creates a Request instance initialized with the given context, method name, list of arguments, container for the method's return value, list of possible exceptions, and list of context strings needing to be resolved.

Uses of Context in org.omg.CORBA.portable

Methods in org.omg.CORBA.portable that return Context
 Context InputStream.read_Context()
Reads a CORBA context from the stream.

Methods in org.omg.CORBA.portable with parameters of type Context
abstract Request | Delegate.create_request(Object obj, Context ctx, String operation, NVList arg_list, NamedValue result) Creates a Request instance for use in the Dynamic Invocation Interface.
abstract Request | Delegate.create_request(Object obj, Context ctx, String operation, NVList arg_list, NamedValue result, ExceptionList exclist, ContextList ctxlist) Creates a Request instance for use in the Dynamic Invocation Interface.
Request | ObjectImpl._create_request(Context ctx, String operation, NVList arg_list, NamedValue result) Creates a Request object that contains the given context, method, argument list, and container for the result.
Request | ObjectImpl._create_request(Context ctx, String operation, NVList arg_list, NamedValue result, ExceptionList exceptions, ContextList contexts) Creates a Request object that contains the given context, method, argument list, container for the result, exceptions, and list of property names to be used in resolving the context strings.
void | OutputStream.write_Context(Context ctx, ContextList contexts) Writes a CORBA context on this stream.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.ContextList (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.ContextList

Packages that use ContextList
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.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.

Uses of ContextList in org.omg.CORBA

Methods in org.omg.CORBA that return ContextList
abstract ContextList | Request.contexts() Retrieves the ContextList object for this request.
abstract ContextList | ORB.create_context_list() Creates an empty ContextList object.

Methods in org.omg.CORBA with parameters of type ContextList
Request | LocalObject._create_request(Context ctx, String operation, NVList arg_list, NamedValue result, ExceptionList exceptions, ContextList contexts) Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.
Request | Object._create_request(Context ctx, String operation, NVList arg_list, NamedValue result, ExceptionList exclist, ContextList ctxlist) Creates a Request instance initialized with the given context, method name, list of arguments, container for the method's return value, list of possible exceptions, and list of context strings needing to be resolved.

Uses of ContextList in org.omg.CORBA.portable

Methods in org.omg.CORBA.portable with parameters of type ContextList
abstract Request | Delegate.create_request(Object obj, Context ctx, String operation, NVList arg_list, NamedValue result, ExceptionList exclist, ContextList ctxlist) Creates a Request instance for use in the Dynamic Invocation Interface.
Request | ObjectImpl._create_request(Context ctx, String operation, NVList arg_list, NamedValue result, ExceptionList exceptions, ContextList contexts) Creates a Request object that contains the given context, method, argument list, container for the result, exceptions, and list of property names to be used in resolving the context strings.
void | OutputStream.write_Context(Context ctx, ContextList contexts) Writes a CORBA context on this stream.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.CTX_RESTRICT_SCOPE (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.CTX_RESTRICT_SCOPE

No usage of org.omg.CORBA.CTX_RESTRICT_SCOPE

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.Current (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.Current

Packages that use Current
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.PortableServer | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of Current in org.omg.CORBA

Fields in org.omg.CORBA declared as Current
 Current CurrentHolder.value

Methods in org.omg.CORBA that return Current
static Current | CurrentHelper.extract(Any a)
static Current | CurrentHelper.read(InputStream istream)
static Current | CurrentHelper.narrow(Object obj)
Current | ORB.get_current() Deprecated. use resolve_initial_references.

Methods in org.omg.CORBA with parameters of type Current
static void | CurrentHelper.insert(Any a, Current that)
static void | CurrentHelper.write(OutputStream ostream, Current value)

Constructors in org.omg.CORBA with parameters of type Current
CurrentHolder(Current initialValue)

Uses of Current in org.omg.PortableServer

Subinterfaces of Current in org.omg.PortableServer
 interface Current
The PortableServer::Current interface, derived from CORBA::Current, provides method implementations with access to the identity of the object on which the method was invoked.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.CurrentHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.CurrentHelper

No usage of org.omg.CORBA.CurrentHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.CurrentHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.CurrentHolder

No usage of org.omg.CORBA.CurrentHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.CurrentOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.CurrentOperations

Packages that use CurrentOperations
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.PortableServer | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of CurrentOperations in org.omg.CORBA

Subinterfaces of CurrentOperations in org.omg.CORBA
 interface Current
Interfaces derived from the Current interface enable ORB and CORBA services to provide access to information (context) associated with the thread of execution in which they are running.

Uses of CurrentOperations in org.omg.PortableServer

Subinterfaces of CurrentOperations in org.omg.PortableServer
 interface CurrentOperations
The PortableServer::Current interface, derived from CORBA::Current, provides method implementations with access to the identity of the object on which the method was invoked.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.CustomMarshal (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.CustomMarshal

Packages that use CustomMarshal
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.

Uses of CustomMarshal in org.omg.CORBA.portable

Subinterfaces of CustomMarshal in org.omg.CORBA.portable
 interface CustomValue
An extension of ValueBase that is implemented by custom value types.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.DATA_CONVERSION (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.DATA_CONVERSION

Packages that use DATA_CONVERSION
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).

Uses of DATA_CONVERSION in org.omg.CORBA

Methods in org.omg.CORBA that throw DATA_CONVERSION
abstract void | Any.insert_char(char c) Inserts the given char into this Any object's value field.
abstract void | Any.insert_string(String s) Inserts the given String object into this Any object's value field.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.DataInputStream (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.DataInputStream

Packages that use DataInputStream
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).

Uses of DataInputStream in org.omg.CORBA

Methods in org.omg.CORBA with parameters of type DataInputStream
 void CustomMarshal.unmarshal(DataInputStream is)
Unmarshal method has to be implemented by the Customized Marshal class This is the method invoked for Unmarshalling.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.DataOutputStream (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.DataOutputStream

Packages that use DataOutputStream
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).

Uses of DataOutputStream in org.omg.CORBA

Methods in org.omg.CORBA with parameters of type DataOutputStream
 void CustomMarshal.marshal(DataOutputStream os)
Marshal method has to be implemented by the Customized Marshal class This is the method invoked for Marshalling.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.DefinitionKind (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.DefinitionKind

Packages that use DefinitionKind
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).

Uses of DefinitionKind in org.omg.CORBA

Fields in org.omg.CORBA declared as DefinitionKind
static DefinitionKind | DefinitionKind.dk_none The static instance of DefinitionKind indicating that an Interface Repository object has no definition kind.
static DefinitionKind | DefinitionKind.dk_all The wildcard DefinitionKind constant, useful in all occasions where any DefinitionKind is appropriate.
static DefinitionKind | DefinitionKind.dk_Attribute The static instance of DefinitionKind indicating that an Interface Repository object is an Attribute.
static DefinitionKind | DefinitionKind.dk_Constant The static instance of DefinitionKind indicating that an Interface Repository object is a constant.
static DefinitionKind | DefinitionKind.dk_Exception The static instance of DefinitionKind indicating that an Interface Repository object is an Exception.
static DefinitionKind | DefinitionKind.dk_Interface The static instance of DefinitionKind indicating that an Interface Repository object is an Interface.
static DefinitionKind | DefinitionKind.dk_Module The static instance of DefinitionKind indicating that an Interface Repository object is a Module.
static DefinitionKind | DefinitionKind.dk_Operation The static instance of DefinitionKind indicating that an Interface Repository object is an Operation.
static DefinitionKind | DefinitionKind.dk_Typedef The static instance of DefinitionKind indicating that an Interface Repository object is a Typedef.
static DefinitionKind | DefinitionKind.dk_Alias The static instance of DefinitionKind indicating that an Interface Repository object is an Alias.
static DefinitionKind | DefinitionKind.dk_Struct The static instance of DefinitionKind indicating that an Interface Repository object is a Struct.
static DefinitionKind | DefinitionKind.dk_Union The static instance of DefinitionKind indicating that an Interface Repository object is a Union.
static DefinitionKind | DefinitionKind.dk_Enum The static instance of DefinitionKind indicating that an Interface Repository object is an Enum.
static DefinitionKind | DefinitionKind.dk_Primitive The static instance of DefinitionKind indicating that an Interface Repository object is a Primitive.
static DefinitionKind | DefinitionKind.dk_String The static instance of DefinitionKind indicating that an Interface Repository object is a String.
static DefinitionKind | DefinitionKind.dk_Sequence The static instance of DefinitionKind indicating that an Interface Repository object is a Sequence.
static DefinitionKind | DefinitionKind.dk_Array The static instance of DefinitionKind indicating that an Interface Repository object is an Array.
static DefinitionKind | DefinitionKind.dk_Repository The static instance of DefinitionKind indicating that an Interface Repository object is a Repository.
static DefinitionKind | DefinitionKind.dk_Wstring The static instance of DefinitionKind indicating that an Interface Repository object is a Wstring.
static DefinitionKind | DefinitionKind.dk_Fixed The static instance of DefinitionKind indicating that an Interface Repository object is a Fixed value.
static DefinitionKind | DefinitionKind.dk_Value The static instance of DefinitionKind indicating that an Interface Repository object is a Value.
static DefinitionKind | DefinitionKind.dk_ValueBox The static instance of DefinitionKind indicating that an Interface Repository object is a ValueBox.
static DefinitionKind | DefinitionKind.dk_ValueMember The static instance of DefinitionKind indicating that an Interface Repository object is a ValueMember.
static DefinitionKind | DefinitionKind.dk_Native The static instance of DefinitionKind indicating that an Interface Repository object is a Native value.
static DefinitionKind | DefinitionKind.dk_AbstractInterface The static instance of DefinitionKind indicating that an Interface Repository object represents an abstract interface.

Methods in org.omg.CORBA that return DefinitionKind
DefinitionKind | _IDLTypeStub.def_kind()
static DefinitionKind | DefinitionKindHelper.extract(Any a)
static DefinitionKind | DefinitionKindHelper.read(InputStream istream)
static DefinitionKind | DefinitionKind.from_int(int i) Creates a DefinitionKind instance corresponding to the given code .
DefinitionKind | IRObjectOperations.def_kind() Returns the DefinitionKind corresponding to this Interface Repository object.

Methods in org.omg.CORBA with parameters of type DefinitionKind
static void | DefinitionKindHelper.insert(Any a, DefinitionKind that)
static void | DefinitionKindHelper.write(OutputStream ostream, DefinitionKind value)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.DefinitionKindHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.DefinitionKindHelper

No usage of org.omg.CORBA.DefinitionKindHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.DomainManager (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.DomainManager

Packages that use DomainManager
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.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.

Uses of DomainManager in org.omg.CORBA

Methods in org.omg.CORBA that return DomainManager
DomainManager[] | LocalObject._get_domain_managers() 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.
DomainManager[] | Object._get_domain_managers() Retrieves the DomainManagers of this object.

Uses of DomainManager in org.omg.CORBA.portable

Methods in org.omg.CORBA.portable that return DomainManager
DomainManager[] | Delegate.get_domain_managers(Object self) Retrieves the DomainManagers of this object.
DomainManager[] | ObjectImpl._get_domain_managers() Retrieves a list of the domain managers for this ObjectImpl object.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.DomainManagerOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.DomainManagerOperations

Packages that use DomainManagerOperations
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).

Uses of DomainManagerOperations in org.omg.CORBA

Subinterfaces of DomainManagerOperations in org.omg.CORBA
 interface DomainManager
Provides mechanisms for establishing and navigating relationships to superior and subordinate domains, as well as for creating and accessing policies.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.DoubleHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.DoubleHolder

No usage of org.omg.CORBA.DoubleHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.DoubleSeqHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.DoubleSeqHelper

No usage of org.omg.CORBA.DoubleSeqHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.DoubleSeqHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.DoubleSeqHolder

Packages that use DoubleSeqHolder
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).

Uses of DoubleSeqHolder in org.omg.CORBA

Methods in org.omg.CORBA with parameters of type DoubleSeqHolder
 void DataInputStream.read_double_array(DoubleSeqHolder seq, int offset, int length)
Reads array of IDL doubles from offset for length elements from the input stream.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.DynamicImplementation (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.DynamicImplementation

Packages that use DynamicImplementation
org.omg.CosNaming Provides a naming service for Java IDL.

Uses of DynamicImplementation in org.omg.CosNaming

Subclasses of DynamicImplementation in org.omg.CosNaming
class | _BindingIteratorImplBase
class | _NamingContextImplBase

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.DynAny (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.DynAny

Packages that use DynAny
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).

Uses of DynAny in org.omg.CORBA

Subinterfaces of DynAny in org.omg.CORBA
interface | DynArray Represents a DynAny object associated with an array.
interface | DynEnum Represents a DynAny object associated with an IDL enum.
interface | DynFixed Represents a DynAny object that is associated with an IDL fixed type.
interface | DynSequence The representation of a DynAny object that is associated with an IDL sequence.
interface | DynStruct The representation of a DynAny object that is associated with an IDL struct.
interface | DynUnion The DynUnion interface represents a DynAny object that is associated with an IDL union.
interface | DynValue The representation of a DynAny object that is associated with an IDL value type.

Methods in org.omg.CORBA that return DynAny
DynAny | DynUnion.discriminator() Returns a DynAny object reference that must be narrowed to the type of the discriminator in order to insert/get the discriminator value.
DynAny | DynUnion.member() Returns a DynAny object reference that is used in order to insert/get a member of this union.
DynAny | DynAny.copy() Clones this DynAny object.
DynAny | DynAny.current_component() Returns a DynAny object reference that can be used to get/set the value of the component currently accessed.
DynAny | ORB.create_dyn_any(Any value) Creates a new DynAny object from the given Any object.
DynAny | ORB.create_basic_dyn_any(TypeCode type) Creates a basic DynAny object from the given TypeCode object.

Methods in org.omg.CORBA with parameters of type DynAny
 void DynAny.assign(DynAny dyn_any)
Copy the contents from one Dynamic Any into another.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.DynArray (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.DynArray

Packages that use DynArray
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).

Uses of DynArray in org.omg.CORBA

Methods in org.omg.CORBA that return DynArray
 DynArray ORB.create_dyn_array(TypeCode type)
Creates a new DynArray object from the given TypeCode object.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.DynEnum (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.DynEnum

Packages that use DynEnum
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).

Uses of DynEnum in org.omg.CORBA

Methods in org.omg.CORBA that return DynEnum
 DynEnum ORB.create_dyn_enum(TypeCode type)
Creates a new DynEnum object from the given TypeCode object.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.DynFixed (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.DynFixed

No usage of org.omg.CORBA.DynFixed

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.DynSequence (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.DynSequence

Packages that use DynSequence
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).

Uses of DynSequence in org.omg.CORBA

Methods in org.omg.CORBA that return DynSequence
 DynSequence ORB.create_dyn_sequence(TypeCode type)
Creates a new DynSequence object from the given TypeCode object.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.DynStruct (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.DynStruct

Packages that use DynStruct
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).

Uses of DynStruct in org.omg.CORBA

Methods in org.omg.CORBA that return DynStruct
 DynStruct ORB.create_dyn_struct(TypeCode type)
Creates a new DynStruct object from the given TypeCode object.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.DynUnion (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.DynUnion

Packages that use DynUnion
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).

Uses of DynUnion in org.omg.CORBA

Methods in org.omg.CORBA that return DynUnion
 DynUnion ORB.create_dyn_union(TypeCode type)
Creates a new DynUnion object from the given TypeCode object.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.DynValue (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.DynValue

No usage of org.omg.CORBA.DynValue

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.Environment (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.Environment

Packages that use Environment
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).

Uses of Environment in org.omg.CORBA

Methods in org.omg.CORBA that return Environment
abstract Environment | Request.env() Retrieves the Environment object for this request.
abstract Environment | ORB.create_environment() Creates an Environment object.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.ExceptionList (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.ExceptionList

Packages that use ExceptionList
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.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.

Uses of ExceptionList in org.omg.CORBA

Methods in org.omg.CORBA that return ExceptionList
abstract ExceptionList | Request.exceptions() Retrieves the ExceptionList object for this request.
abstract ExceptionList | ORB.create_exception_list() Creates an empty ExceptionList object.

Methods in org.omg.CORBA with parameters of type ExceptionList
Request | LocalObject._create_request(Context ctx, String operation, NVList arg_list, NamedValue result, ExceptionList exceptions, ContextList contexts) Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.
Request | Object._create_request(Context ctx, String operation, NVList arg_list, NamedValue result, ExceptionList exclist, ContextList ctxlist) Creates a Request instance initialized with the given context, method name, list of arguments, container for the method's return value, list of possible exceptions, and list of context strings needing to be resolved.

Uses of ExceptionList in org.omg.CORBA.portable

Methods in org.omg.CORBA.portable with parameters of type ExceptionList
abstract Request | Delegate.create_request(Object obj, Context ctx, String operation, NVList arg_list, NamedValue result, ExceptionList exclist, ContextList ctxlist) Creates a Request instance for use in the Dynamic Invocation Interface.
Request | ObjectImpl._create_request(Context ctx, String operation, NVList arg_list, NamedValue result, ExceptionList exceptions, ContextList contexts) Creates a Request object that contains the given context, method, argument list, container for the result, exceptions, and list of property names to be used in resolving the context strings.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.FieldNameHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.FieldNameHelper

No usage of org.omg.CORBA.FieldNameHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.FixedHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.FixedHolder

No usage of org.omg.CORBA.FixedHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.FloatHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.FloatHolder

No usage of org.omg.CORBA.FloatHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.FloatSeqHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.FloatSeqHelper

No usage of org.omg.CORBA.FloatSeqHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.FloatSeqHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.FloatSeqHolder

Packages that use FloatSeqHolder
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).

Uses of FloatSeqHolder in org.omg.CORBA

Methods in org.omg.CORBA with parameters of type FloatSeqHolder
 void DataInputStream.read_float_array(FloatSeqHolder seq, int offset, int length)
Reads array of IDL floats from offset for length elements from the input stream.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.FREE_MEM (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.FREE_MEM

No usage of org.omg.CORBA.FREE_MEM

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.IdentifierHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.IdentifierHelper

No usage of org.omg.CORBA.IdentifierHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.IDLType (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.IDLType

Packages that use IDLType
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).

Uses of IDLType in org.omg.CORBA

Classes in org.omg.CORBA that implement IDLType
 class _IDLTypeStub
The Stub for IDLType.

Fields in org.omg.CORBA declared as IDLType
IDLType | ValueMember.type_def The typedef that represents the IDL type of the value member described by this ValueMember object.
IDLType | UnionMember.type_def The typedef that represents the IDL type of the union member described by this UnionMember object.
IDLType | StructMember.type_def The typedef that represents the IDL type of the struct member described by this StructMember object.

Methods in org.omg.CORBA that return IDLType
static IDLType | IDLTypeHelper.extract(Any a)
static IDLType | IDLTypeHelper.read(InputStream istream)
static IDLType | IDLTypeHelper.narrow(Object obj)

Methods in org.omg.CORBA with parameters of type IDLType
static void | IDLTypeHelper.insert(Any a, IDLType that)
static void | IDLTypeHelper.write(OutputStream ostream, IDLType value)

Constructors in org.omg.CORBA with parameters of type IDLType
ValueMember(String __name, String __id, String __defined_in, String __version, TypeCode __type, IDLType __type_def, short __access)
Constructs a ValueMember object initialized with the given values.
UnionMember(String __name, Any __label, TypeCode __type, IDLType __type_def)
Constructs a new UnionMember object with its fields initialized to the given values.
StructMember(String __name, TypeCode __type, IDLType __type_def)
Constructs a StructMember object initialized with the given values.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.IDLTypeHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.IDLTypeHelper

No usage of org.omg.CORBA.IDLTypeHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.IDLTypeOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.IDLTypeOperations

Packages that use IDLTypeOperations
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).

Uses of IDLTypeOperations in org.omg.CORBA

Subinterfaces of IDLTypeOperations in org.omg.CORBA
 interface IDLType
An abstract interface inherited by all Interface Repository (IR) objects that represent OMG IDL types.

Classes in org.omg.CORBA that implement IDLTypeOperations
 class _IDLTypeStub
The Stub for IDLType.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.IMP_LIMIT (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.IMP_LIMIT

No usage of org.omg.CORBA.IMP_LIMIT

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.INITIALIZE (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.INITIALIZE

No usage of org.omg.CORBA.INITIALIZE

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.INTERNAL (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.INTERNAL

No usage of org.omg.CORBA.INTERNAL

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.INTF_REPOS (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.INTF_REPOS

No usage of org.omg.CORBA.INTF_REPOS

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.IntHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.IntHolder

No usage of org.omg.CORBA.IntHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.INV_FLAG (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.INV_FLAG

No usage of org.omg.CORBA.INV_FLAG

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.INV_IDENT (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.INV_IDENT

No usage of org.omg.CORBA.INV_IDENT

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.INV_OBJREF (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.INV_OBJREF

No usage of org.omg.CORBA.INV_OBJREF

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.INV_POLICY (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.INV_POLICY

No usage of org.omg.CORBA.INV_POLICY

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.INVALID_TRANSACTION (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.INVALID_TRANSACTION

No usage of org.omg.CORBA.INVALID_TRANSACTION

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.IRObject (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.IRObject

Packages that use IRObject
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).

Uses of IRObject in org.omg.CORBA

Subinterfaces of IRObject in org.omg.CORBA
 interface IDLType
An abstract interface inherited by all Interface Repository (IR) objects that represent OMG IDL types.

Classes in org.omg.CORBA that implement IRObject
 class _IDLTypeStub
The Stub for IDLType.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.IRObjectOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.IRObjectOperations

Packages that use IRObjectOperations
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).

Uses of IRObjectOperations in org.omg.CORBA

Subinterfaces of IRObjectOperations in org.omg.CORBA
interface | IDLType An abstract interface inherited by all Interface Repository (IR) objects that represent OMG IDL types.
interface | IDLTypeOperations This interface must be implemented by all IDLType objects.
interface | IRObject An IRObject IDL interface represents the most generic interface from which all other Interface Repository interfaces are derived, even the Repository itself.

Classes in org.omg.CORBA that implement IRObjectOperations
 class _IDLTypeStub
The Stub for IDLType.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.LocalObject (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.LocalObject

No usage of org.omg.CORBA.LocalObject

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.LongHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.LongHolder

No usage of org.omg.CORBA.LongHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.LongLongSeqHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.LongLongSeqHelper

No usage of org.omg.CORBA.LongLongSeqHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.LongLongSeqHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.LongLongSeqHolder

Packages that use LongLongSeqHolder
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).

Uses of LongLongSeqHolder in org.omg.CORBA

Methods in org.omg.CORBA with parameters of type LongLongSeqHolder
 void DataInputStream.read_longlong_array(LongLongSeqHolder seq, int offset, int length)
Reads array of IDL long longs from offset for length elements from the input stream.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.LongSeqHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.LongSeqHelper

No usage of org.omg.CORBA.LongSeqHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.LongSeqHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.LongSeqHolder

Packages that use LongSeqHolder
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).

Uses of LongSeqHolder in org.omg.CORBA

Methods in org.omg.CORBA with parameters of type LongSeqHolder
 void DataInputStream.read_long_array(LongSeqHolder seq, int offset, int length)
Reads array of IDL longs from offset for length elements from the input stream.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.MARSHAL (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.MARSHAL

Packages that use MARSHAL
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).

Uses of MARSHAL in org.omg.CORBA

Methods in org.omg.CORBA that throw MARSHAL
abstract void | Any.read_value(InputStream is, TypeCode t) Reads off (unmarshals) the value of an Any object from the given input stream using the given typecode.
abstract void | Any.insert_Value(Serializable v, TypeCode t) Inserts the given java.io.Serializable object into this Any object's value field.
abstract void | Any.insert_string(String s) Inserts the given String object into this Any object's value field.
abstract void | Any.insert_wstring(String s) Inserts the given String object into this Any object's value field.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.NamedValue (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.NamedValue

Packages that use NamedValue
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.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.

Uses of NamedValue in org.omg.CORBA

Methods in org.omg.CORBA that return NamedValue
abstract NamedValue | NVList.add(int flags) Creates a new NamedValue object initialized with the given flag and adds it to the end of this NVList object.
abstract NamedValue | NVList.add_item(String item_name, int flags) Creates a new NamedValue object initialized with the given name and flag, and adds it to the end of this NVList object.
abstract NamedValue | NVList.add_value(String item_name, Any val, int flags) Creates a new NamedValue object initialized with the given name, value, and flag, and adds it to the end of this NVList object.
abstract NamedValue | NVList.item(int index) Retrieves the NamedValue object at the given index.
abstract NamedValue | Request.result() Retrieves the NamedValue object containing the return value for the method.
abstract NamedValue | ORB.create_named_value(String s, Any any, int flags) Creates a NamedValue object using the given name, value, and argument mode flags.

Methods in org.omg.CORBA with parameters of type NamedValue
Request | LocalObject._create_request(Context ctx, String operation, NVList arg_list, NamedValue result) Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.
Request | LocalObject._create_request(Context ctx, String operation, NVList arg_list, NamedValue result, ExceptionList exceptions, ContextList contexts) Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.
Request | Object._create_request(Context ctx, String operation, NVList arg_list, NamedValue result) Creates a Request instance initialized with the given context, method name, list of arguments, and container for the method's return value.
Request | Object._create_request(Context ctx, String operation, NVList arg_list, NamedValue result, ExceptionList exclist, ContextList ctxlist) Creates a Request instance initialized with the given context, method name, list of arguments, container for the method's return value, list of possible exceptions, and list of context strings needing to be resolved.

Uses of NamedValue in org.omg.CORBA.portable

Methods in org.omg.CORBA.portable with parameters of type NamedValue
abstract Request | Delegate.create_request(Object obj, Context ctx, String operation, NVList arg_list, NamedValue result) Creates a Request instance for use in the Dynamic Invocation Interface.
abstract Request | Delegate.create_request(Object obj, Context ctx, String operation, NVList arg_list, NamedValue result, ExceptionList exclist, ContextList ctxlist) Creates a Request instance for use in the Dynamic Invocation Interface.
Request | ObjectImpl._create_request(Context ctx, String operation, NVList arg_list, NamedValue result) Creates a Request object that contains the given context, method, argument list, and container for the result.
Request | ObjectImpl._create_request(Context ctx, String operation, NVList arg_list, NamedValue result, ExceptionList exceptions, ContextList contexts) Creates a Request object that contains the given context, method, argument list, container for the result, exceptions, and list of property names to be used in resolving the context strings.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.NameValuePair (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.NameValuePair

Packages that use NameValuePair
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).

Uses of NameValuePair in org.omg.CORBA

Methods in org.omg.CORBA that return NameValuePair
static NameValuePair | NameValuePairHelper.extract(Any a)
static NameValuePair | NameValuePairHelper.read(InputStream istream)
NameValuePair[] | DynValue.get_members() Returns an array containing all the members of the value object stored in this DynValue.
NameValuePair[] | DynStruct.get_members() Returns an array containing all the members of the stored struct.

Methods in org.omg.CORBA with parameters of type NameValuePair
static void | NameValuePairHelper.insert(Any a, NameValuePair that)
static void | NameValuePairHelper.write(OutputStream ostream, NameValuePair value)
void | DynValue.set_members(NameValuePair[] value) Sets the members of the value object this DynValue object represents to the given array of NameValuePair objects.
void | DynStruct.set_members(NameValuePair[] value) Set the members of the struct.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.NameValuePairHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.NameValuePairHelper

No usage of org.omg.CORBA.NameValuePairHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.NO_IMPLEMENT (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.NO_IMPLEMENT

No usage of org.omg.CORBA.NO_IMPLEMENT

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.NO_MEMORY (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.NO_MEMORY

No usage of org.omg.CORBA.NO_MEMORY

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.NO_PERMISSION (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.NO_PERMISSION

No usage of org.omg.CORBA.NO_PERMISSION

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.NO_RESOURCES (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.NO_RESOURCES

No usage of org.omg.CORBA.NO_RESOURCES

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.NO_RESPONSE (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.NO_RESPONSE

No usage of org.omg.CORBA.NO_RESPONSE

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.NVList (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.NVList

Packages that use NVList
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.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.

Uses of NVList in org.omg.CORBA

Methods in org.omg.CORBA that return NVList
abstract NVList | Context.get_values(String start_scope, int op_flags, String pattern) Retrieves the NamedValue objects whose name field matches the given name or name pattern.
abstract NVList | Request.arguments() Retrieves the NVList object containing the arguments to the method being invoked.
abstract NVList | ORB.create_list(int count) Allocates an NVList with (probably) enough space for the specified number of NamedValue objects.
NVList | ORB.create_operation_list(Object oper) Creates an NVList initialized with argument descriptions for the operation described in the given OperationDef object.

Methods in org.omg.CORBA with parameters of type NVList
Request | LocalObject._create_request(Context ctx, String operation, NVList arg_list, NamedValue result) Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.
Request | LocalObject._create_request(Context ctx, String operation, NVList arg_list, NamedValue result, ExceptionList exceptions, ContextList contexts) Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.
void | ServerRequest.params(NVList params) Deprecated. use the method arguments
void | ServerRequest.arguments(NVList args) Specifies method parameter types and retrieves "in" and "inout" argument values.
abstract void | Context.set_values(NVList values) I Sets one or more property values in this Context object.
Request | Object._create_request(Context ctx, String operation, NVList arg_list, NamedValue result) Creates a Request instance initialized with the given context, method name, list of arguments, and container for the method's return value.
Request | Object._create_request(Context ctx, String operation, NVList arg_list, NamedValue result, ExceptionList exclist, ContextList ctxlist) Creates a Request instance initialized with the given context, method name, list of arguments, container for the method's return value, list of possible exceptions, and list of context strings needing to be resolved.

Uses of NVList in org.omg.CORBA.portable

Methods in org.omg.CORBA.portable with parameters of type NVList
abstract Request | Delegate.create_request(Object obj, Context ctx, String operation, NVList arg_list, NamedValue result) Creates a Request instance for use in the Dynamic Invocation Interface.
abstract Request | Delegate.create_request(Object obj, Context ctx, String operation, NVList arg_list, NamedValue result, ExceptionList exclist, ContextList ctxlist) Creates a Request instance for use in the Dynamic Invocation Interface.
Request | ObjectImpl._create_request(Context ctx, String operation, NVList arg_list, NamedValue result) Creates a Request object that contains the given context, method, argument list, and container for the result.
Request | ObjectImpl._create_request(Context ctx, String operation, NVList arg_list, NamedValue result, ExceptionList exceptions, ContextList contexts) Creates a Request object that contains the given context, method, argument list, container for the result, exceptions, and list of property names to be used in resolving the context strings.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.OBJ_ADAPTER (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.OBJ_ADAPTER

No usage of org.omg.CORBA.OBJ_ADAPTER

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.Object (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.Object

Packages that use Object
javax.rmi.CORBA | Contains portability APIs for RMI-IIOP.
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_2_3 | The CORBA_2_3 package defines additions to existing CORBA interfaces in the Java 2 Standard Edition. 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 | Provides methods for the input and output of value types, and contains other updates to the 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.CosNaming | Provides a naming service for Java IDL.
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.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.PortableInterceptor | Provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.
org.omg.PortableServer | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.
org.omg.PortableServer.portable | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.
org.omg.SendingContext | Provides support for the marshalling of value types.
org.omg.stub.java.rmi | Contains RMI-IIOP Stubs for the Remote types that occur in the java.rmi package.

Uses of Object in javax.rmi.CORBA

Classes in javax.rmi.CORBA that implement Object
 class Stub
Base class from which all RMI-IIOP stubs must inherit.

Methods in javax.rmi.CORBA that return Object
 Object Tie.thisObject()
Returns an object reference for the target object represented by this tie.

Uses of Object in org.omg.CORBA

Subinterfaces of Object in org.omg.CORBA
interface | Current Interfaces derived from the Current interface enable ORB and CORBA services to provide access to information (context) associated with the thread of execution in which they are running.
interface | DomainManager Provides mechanisms for establishing and navigating relationships to superior and subordinate domains, as well as for creating and accessing policies.
interface | DynAny Enables org.omg.CORBA.Any values to be dynamically interpreted (traversed) and constructed.
interface | DynArray Represents a DynAny object associated with an array.
interface | DynEnum Represents a DynAny object associated with an IDL enum.
interface | DynFixed Represents a DynAny object that is associated with an IDL fixed type.
interface | DynSequence The representation of a DynAny object that is associated with an IDL sequence.
interface | DynStruct The representation of a DynAny object that is associated with an IDL struct.
interface | DynUnion The DynUnion interface represents a DynAny object that is associated with an IDL union.
interface | DynValue The representation of a DynAny object that is associated with an IDL value type.
interface | IDLType An abstract interface inherited by all Interface Repository (IR) objects that represent OMG IDL types.
interface | IRObject An IRObject IDL interface represents the most generic interface from which all other Interface Repository interfaces are derived, even the Repository itself.
interface | Policy Interfaces derived from the Policy interface allow an ORB or CORBA service access to certain choices that affect its operation.

Classes in org.omg.CORBA that implement Object
class | _IDLTypeStub The Stub for IDLType.
class | _PolicyStub The Stub for Policy.
class | DynamicImplementation Deprecated. org.omg.CORBA.DynamicImplementation
class | LocalObject Used as a base class for implementation of a local IDL interface in the Java language mapping.

Fields in org.omg.CORBA declared as Object
 Object ObjectHolder.value
The Object value held by this ObjectHolder object.

Methods in org.omg.CORBA that return Object
 Object LocalObject._duplicate()
Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.
 Object LocalObject._get_interface()
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.
 Object LocalObject._get_interface_def()
Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.
 Object LocalObject._set_policy_override(Policy[] policies, SetOverrideType set_add)
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.
 Object DataInputStream.read_Object()
Reads an IDL CORBA::Object from the input stream.
static Object ObjectHelper.extract(Any a)
static Object ObjectHelper.read(InputStream istream)
 Object DynAny.get_reference()
Retrieves the org.omg.CORBA.Other contained in this DynAny object.
abstract  Object Any.extract_Object()
Extracts the org.omg.CORBA.Object in this Any object's value field.
abstract  Object Request.target()
Retrieves the the target object reference.
 Object Object._duplicate()
Returns a duplicate of this CORBA object reference.
 Object Object._get_interface_def()
Obtains an InterfaceDef for the object implementation referenced by this object reference.
 Object Object._set_policy_override(Policy[] policies, SetOverrideType set_add)
Returns a new Object with the given policies either replacing any existing policies in this Object or with the given policies added to the existing ones, depending on the value of the given SetOverrideType object.
abstract  Object ORB.resolve_initial_references(String object_name)
Resolves a specific object reference from the set of available initial service names.
abstract  Object ORB.string_to_object(String str)
Converts a string produced by the method object_to_string back to a CORBA object reference.

Methods in org.omg.CORBA with parameters of type Object
 boolean LocalObject._is_equivalent(Object that)
Determines whether the two object references are equivalent, so far as the ORB can easily determine.
static Policy PolicyHelper.narrow(Object obj)
static IDLType IDLTypeHelper.narrow(Object obj)
 void DataOutputStream.write_Object(Object value)
Writes the IDL CORBA::Object value to the output stream.
static Current CurrentHelper.narrow(Object obj)
static void ObjectHelper.insert(Any a, Object that)
static void ObjectHelper.write(OutputStream ostream, Object value)
 void DynAny.insert_reference(Object value)
Inserts the given org.omg.CORBA.Object as the value for this DynAny object.
abstract  void Any.insert_Object(Object o)
Inserts the given org.omg.CORBA.Object object into this Any object's value field.
abstract  void Any.insert_Object(Object o, TypeCode t)
Inserts the given org.omg.CORBA.Object object into this Any object's value field.
 boolean Object._is_equivalent(Object other)
Determines whether the two object references are equivalent, so far as the ORB can easily determine.
 void ORB.connect(Object obj)
Connects the given servant object (a Java object that is an instance of the server implementation class) to the ORB.
 void ORB.disconnect(Object obj)
Disconnects the given servant object from the ORB.
abstract  String ORB.object_to_string(Object obj)
Converts the given CORBA object reference to a string.
 NVList ORB.create_operation_list(Object oper)
Creates an NVList initialized with argument descriptions for the operation described in the given OperationDef object.

Constructors in org.omg.CORBA with parameters of type Object
ObjectHolder(Object initial)
Constructs a new ObjectHolder object with its value field initialized to the given Object.

Uses of Object in org.omg.CORBA_2_3

Methods in org.omg.CORBA_2_3 that return Object
 Object ORB.get_value_def(String repid)

Uses of Object in org.omg.CORBA_2_3.portable

Methods in org.omg.CORBA_2_3.portable with parameters of type Object
 String Delegate.get_codebase(Object self)
Returns the codebase for object reference provided.

Uses of Object in org.omg.CORBA.portable

Classes in org.omg.CORBA.portable that implement Object
 class ObjectImpl
The common base class for all stub classes; provides default implementations of the org.omg.CORBA.Object methods.

Methods in org.omg.CORBA.portable that return Object
abstract Object | Delegate.get_interface_def(Object self) Return an InterfaceDef for the object reference provided.
abstract Object | Delegate.duplicate(Object obj) Returns a duplicate of the object reference provided.
Object | Delegate.set_policy_override(Object self, Policy[] policies, SetOverrideType set_add) Associates the policies passed in with a newly created object reference that it returns.
Object | ObjectImpl._duplicate() Returns a duplicate of this ObjectImpl object.
Object | ObjectImpl._get_interface_def() Retrieves the interface definition for this ObjectImpl object.
Object | ObjectImpl._set_policy_override(Policy[] policies, SetOverrideType set_add) Sets this ObjectImpl object's override type for the given policies to the given instance of SetOverrideType.
abstract Object | InputStream.read_Object() Reads a CORBA object from this input stream.
Object | InputStream.read_Object(Class clz) Unmarshals an object and returns a CORBA Object, which is an instance of the class passed as its argument.

Methods in org.omg.CORBA.portable with parameters of type Object
abstract  Object Delegate.get_interface_def(Object self)
Return an InterfaceDef for the object reference provided.
abstract  Object Delegate.duplicate(Object obj)
Returns a duplicate of the object reference provided.
abstract  void Delegate.release(Object obj)
Releases resources associated with the object reference provided.
abstract  boolean Delegate.is_a(Object obj, String repository_id)
Checks if the object reference is an instance of the given interface.
abstract  boolean Delegate.non_existent(Object obj)
Determines whether the server object for the object reference has been destroyed.
abstract  boolean Delegate.is_equivalent(Object obj, Object other)
Determines if the two object references are equivalent.
abstract  int Delegate.hash(Object obj, int max)
Returns an ORB-internal identifier (hashcode) for this object reference.
abstract  Request Delegate.request(Object obj, String operation)
Creates a Request instance for use in the Dynamic Invocation Interface.
abstract  Request Delegate.create_request(Object obj, Context ctx, String operation, NVList arg_list, NamedValue result)
Creates a Request instance for use in the Dynamic Invocation Interface.
abstract  Request Delegate.create_request(Object obj, Context ctx, String operation, NVList arg_list, NamedValue result, ExceptionList exclist, ContextList ctxlist)
Creates a Request instance for use in the Dynamic Invocation Interface.
 ORB Delegate.orb(Object obj)
Provides a reference to the orb associated with its parameter.
 Policy Delegate.get_policy(Object self, int policy_type)
Returns the Policy object of the specified type which applies to this object.
 DomainManager[] Delegate.get_domain_managers(Object self)
Retrieves the DomainManagers of this object.
 Object Delegate.set_policy_override(Object self, Policy[] policies, SetOverrideType set_add)
Associates the policies passed in with a newly created object reference that it returns.
 boolean Delegate.is_local(Object self)
Returns true if this object is implemented by a local servant.
 ServantObject Delegate.servant_preinvoke(Object self, String operation, Class expectedType)
Returns a Java reference to the servant which should be used for this request.
 void Delegate.servant_postinvoke(Object self, ServantObject servant)
servant_postinvoke() is invoked by the local stub after the operation has been invoked on the local servant.
 OutputStream Delegate.request(Object self, String operation, boolean responseExpected)
request is called by a stub to obtain an OutputStream for marshaling arguments.
 InputStream Delegate.invoke(Object self, OutputStream output)
invoke is called by a stub to invoke an operation.
 void Delegate.releaseReply(Object self, InputStream input)
releaseReply may optionally be called by a stub to release a reply stream back to the ORB when the unmarshaling has completed.
 String Delegate.toString(Object self)
Provides the implementation to override the toString() method of the delegating CORBA object.
 int Delegate.hashCode(Object self)
Provides the implementation to override the hashCode() method of the delegating CORBA object.
 boolean Delegate.equals(Object self, Object obj)
Provides the implementation to override the equals(java.lang.Object obj) method of the delegating CORBA object.
 boolean ObjectImpl._is_equivalent(Object that)
Checks whether the the given ObjectImpl object is equivalent to this ObjectImpl object.
abstract  void OutputStream.write_Object(Object value)
Writes a CORBA Object on this output stream.

Uses of Object in org.omg.CosNaming

Subinterfaces of Object in org.omg.CosNaming
interface | BindingIterator The BindingIterator interface allows a client to iterate through the bindings using the next_one or next_n operations.
interface | NamingContext A naming context is an object that contains a set of name bindings in which each name is unique.
interface | NamingContextExt 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.

Classes in org.omg.CosNaming that implement Object
class | _BindingIteratorImplBase
class | _BindingIteratorStub The BindingIterator interface allows a client to iterate through the bindings using the next_one or next_n operations.
class | _NamingContextExtStub 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.
class | _NamingContextImplBase
class | _NamingContextStub A naming context is an object that contains a set of name bindings in which each name is unique.

Methods in org.omg.CosNaming that return Object
Object | _NamingContextExtStub.resolve_str(String sn) This operation resolves the Stringified name into the object reference.
Object | _NamingContextExtStub.resolve(NameComponent[] n) The resolve operation is the process of retrieving an object bound to a name in a given context.
Object | NamingContextExtOperations.resolve_str(String sn) This operation resolves the Stringified name into the object reference.
Object | _NamingContextStub.resolve(NameComponent[] n) The resolve operation is the process of retrieving an object bound to a name in a given context.
Object | NamingContextOperations.resolve(NameComponent[] n) The resolve operation is the process of retrieving an object bound to a name in a given context.

Methods in org.omg.CosNaming with parameters of type Object
void | _NamingContextExtStub.bind(NameComponent[] n, Object obj) Creates a binding of a name and an object in the naming context.
void | _NamingContextExtStub.rebind(NameComponent[] n, Object obj) Creates a binding of a name and an object in the naming context even if the name is already bound in the context.
static NamingContextExt | NamingContextExtHelper.narrow(Object obj)
void | _NamingContextStub.bind(NameComponent[] n, Object obj) Creates a binding of a name and an object in the naming context.
void | _NamingContextStub.rebind(NameComponent[] n, Object obj) Creates a binding of a name and an object in the naming context even if the name is already bound in the context.
static NamingContext | NamingContextHelper.narrow(Object obj)
void | NamingContextOperations.bind(NameComponent[] n, Object obj) Creates a binding of a name and an object in the naming context.
void | NamingContextOperations.rebind(NameComponent[] n, Object obj) Creates a binding of a name and an object in the naming context even if the name is already bound in the context.
static BindingIterator | BindingIteratorHelper.narrow(Object obj)

Uses of Object in org.omg.DynamicAny

Subinterfaces of Object in org.omg.DynamicAny
interface | DynAnyFactory DynAny objects can be created by invoking operations on the DynAnyFactory object.
interface | DynValueBox DynValueBox objects support the manipulation of IDL boxed value types.
interface | DynValueCommon DynValueCommon provides operations supported by both the DynValue and DynValueBox interfaces.

Classes in org.omg.DynamicAny that implement Object
class | _DynAnyFactoryStub DynAny objects can be created by invoking operations on the DynAnyFactory object.
class | _DynAnyStub Any values can be dynamically interpreted (traversed) and constructed through DynAny objects.
class | _DynArrayStub DynArray objects support the manipulation of IDL arrays.
class | _DynEnumStub DynEnum objects support the manipulation of IDL enumerated values.
class | _DynFixedStub DynFixed objects support the manipulation of IDL fixed values.
class | _DynSequenceStub DynSequence objects support the manipulation of IDL sequences.
class | _DynStructStub DynStruct objects support the manipulation of IDL struct and exception values.
class | _DynUnionStub DynUnion objects support the manipulation of IDL unions.
class | _DynValueStub DynValue objects support the manipulation of IDL non-boxed value types.

Methods in org.omg.DynamicAny that return Object
Object | _DynSequenceStub.get_reference() Extracts the reference to a CORBA Object from this DynAny.
Object | _DynFixedStub.get_reference() Extracts the reference to a CORBA Object from this DynAny.
Object | _DynEnumStub.get_reference() Extracts the reference to a CORBA Object from this DynAny.
Object | _DynArrayStub.get_reference() Extracts the reference to a CORBA Object from this DynAny.
Object | _DynValueStub.get_reference() Extracts the reference to a CORBA Object from this DynAny.
Object | _DynAnyStub.get_reference() Extracts the reference to a CORBA Object from this DynAny.
Object | _DynUnionStub.get_reference() Extracts the reference to a CORBA Object from this DynAny.
Object | _DynStructStub.get_reference() Extracts the reference to a CORBA Object from this DynAny.
Object | DynAnyOperations.get_reference() Extracts the reference to a CORBA Object from this DynAny.

Methods in org.omg.DynamicAny with parameters of type Object
void | _DynSequenceStub.insert_reference(Object value) Inserts a reference to a CORBA object into the DynAny.
void | _DynFixedStub.insert_reference(Object value) Inserts a reference to a CORBA object into the DynAny.
void | _DynEnumStub.insert_reference(Object value) Inserts a reference to a CORBA object into the DynAny.
void | _DynArrayStub.insert_reference(Object value) Inserts a reference to a CORBA object into the DynAny.
void | _DynValueStub.insert_reference(Object value) Inserts a reference to a CORBA object into the DynAny.
void | _DynAnyStub.insert_reference(Object value) Inserts a reference to a CORBA object into the DynAny.
void | _DynUnionStub.insert_reference(Object value) Inserts a reference to a CORBA object into the DynAny.
void | _DynStructStub.insert_reference(Object value) Inserts a reference to a CORBA object into the DynAny.
static DynSequence | DynSequenceHelper.narrow(Object obj)
static DynFixed | DynFixedHelper.narrow(Object obj)
static DynEnum | DynEnumHelper.narrow(Object obj)
static DynArray | DynArrayHelper.narrow(Object obj)
static DynValue | DynValueHelper.narrow(Object obj)
static DynAny | DynAnyHelper.narrow(Object obj)
static DynUnion | DynUnionHelper.narrow(Object obj)
static DynAnyFactory | DynAnyFactoryHelper.narrow(Object obj)
static DynStruct | DynStructHelper.narrow(Object obj)
void | DynAnyOperations.insert_reference(Object value) Inserts a reference to a CORBA object into the DynAny.

Uses of Object in org.omg.IOP

Subinterfaces of Object in org.omg.IOP
interface | Codec The formats of IOR components and service context data used by ORB services are often defined as CDR encapsulations encoding instances of IDL defined data types.
interface | CodecFactory Codecs are obtained from the CodecFactory.

Methods in org.omg.IOP with parameters of type Object
static CodecFactory CodecFactoryHelper.narrow(Object obj)

Uses of Object in org.omg.PortableInterceptor

Subinterfaces of Object in org.omg.PortableInterceptor
interface | ClientRequestInfo Request Information, accessible to client-side request interceptors.
interface | ClientRequestInterceptor Client-side request interceptor.
interface | Interceptor All Portable Interceptors implement Interceptor.
interface | IORInfo Provides the server-side ORB service with access to the applicable policies during IOR construction and the ability to add components.
interface | IORInterceptor Interceptor used to establish tagged components in the profiles within an IOR.
interface | ORBInitializer Facilitates interceptor registration and ORB initialization.
interface | ORBInitInfo Passed to each ORBInitializer, allowing it to to register interceptors and perform other duties while the ORB is initializing.
interface | PolicyFactory Enables policy types to be constructed using CORBA.ORB.create_policy.
interface | RequestInfo Request Information, accessible to Interceptors.
interface | ServerRequestInfo Request Information, accessible to server-side request interceptors.
interface | ServerRequestInterceptor Server-side request interceptor.

Fields in org.omg.PortableInterceptor declared as Object
 Object ForwardRequest.forward
The new object to forward the request to.

Methods in org.omg.PortableInterceptor that return Object
Object | ORBInitInfoOperations.resolve_initial_references(String id) Identical to ORB.resolve_initial_references.
Object | RequestInfoOperations.forward_reference() Contains the object to which the request will be forwarded, if the reply_status attribute is LOCATION_FORWARD.
Object | ClientRequestInfoOperations.target() Returns the object which the client called to perform the operation.
Object | ClientRequestInfoOperations.effective_target() Returns the actual object on which the operation will be invoked.

Methods in org.omg.PortableInterceptor with parameters of type Object
void | ORBInitInfoOperations.register_initial_reference(String id, Object obj) Identical to ORB.register_initial_reference.
static Current | CurrentHelper.narrow(Object obj)

Constructors in org.omg.PortableInterceptor with parameters of type Object
ForwardRequest(Object _forward)
ForwardRequest(String $reason, Object _forward)

Uses of Object in org.omg.PortableServer

Subinterfaces of Object in org.omg.PortableServer
interface | AdapterActivator 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 find_POA is called with an activate parameter value of TRUE.
interface | IdAssignmentPolicy IdAssignmentPolicy specifies whether Object Ids in the created POA are generated by the application or by the ORB.
interface | IdUniquenessPolicy The IdUniquenessPolicy specifies whether the servants activated in the created POA must have unique object i identities.
interface | ImplicitActivationPolicy This policy specifies whether implicit activation of servants is supported in the created POA.
interface | LifespanPolicy The LifespanPolicy specifies the lifespan of the objects implemented in the created POA.
interface | POA A POA object manages the implementation of a collection of objects.
interface | POAManager Each POA object has an associated POAManager object.
interface | RequestProcessingPolicy This policy specifies how requests are processed by the created POA.
interface | ServantActivator When the POA has the RETAIN policy it uses servant managers that are ServantActivators.
interface | ServantLocator When the POA has the NON_RETAIN policy it uses servant managers that are ServantLocators.
interface | ServantManager 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.
interface | ServantRetentionPolicy This policy specifies whether the created POA retains active servants in an Active Object Map.
interface | ThreadPolicy The ThreadPolicy specifies the threading model used with the created POA.

Classes in org.omg.PortableServer that implement Object
class | _ServantActivatorStub When the POA has the RETAIN policy it uses servant managers that are ServantActivators.
class | _ServantLocatorStub When the POA has the NON_RETAIN policy it uses servant managers that are ServantLocators.

Fields in org.omg.PortableServer declared as Object
 Object ForwardRequest.forward_reference

Methods in org.omg.PortableServer that return Object
 Object POAOperations.create_reference(String intf)
This operation creates an object reference that encapsulates a POA-generated Object Id value and the specified interface repository id.
 Object POAOperations.create_reference_with_id(byte[] oid, String intf)
This operation creates an object reference that encapsulates the specified Object Id and interface repository Id values.
 Object POAOperations.servant_to_reference(Servant p_servant)
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.
 Object POAOperations.id_to_reference(byte[] oid)
If an object with the specified Object Id value is currently active, a reference encapsulating the information used to activate the object is returned.
 Object Servant._this_object()
Allows the servant to obtain the object reference for the target CORBA object it is incarnating for that request.
 Object Servant._this_object(ORB orb)
Allows the servant to obtain the object reference for the target CORBA Object it is incarnating for that request.
 Object Servant._get_interface_def()
Returns an InterfaceDef object as a CORBA::Object that defines the runtime type of the CORBA::Object implemented by the Servant.

Methods in org.omg.PortableServer with parameters of type Object
static ServantLocator | ServantLocatorHelper.narrow(Object obj)
static ServantActivator | ServantActivatorHelper.narrow(Object obj)
static POA | POAHelper.narrow(Object obj)
static Current | CurrentHelper.narrow(Object obj)
Servant | POAOperations.reference_to_servant(Object reference) 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.
byte[] | POAOperations.reference_to_id(Object reference) This operation returns the Object Id value encapsulated by the specified reference.

Constructors in org.omg.PortableServer with parameters of type Object
ForwardRequest(Object _forward_reference)
ForwardRequest(String $reason, Object _forward_reference)

Uses of Object in org.omg.PortableServer.portable

Methods in org.omg.PortableServer.portable that return Object
Object | Delegate.this_object(Servant Self) This allows the servant to obtain the object reference for the target CORBA Object it is incarnating for that request.
Object | Delegate.get_interface_def(Servant self) This operation returns an object in the Interface Repository which provides type information that may be useful to a program.

Uses of Object in org.omg.SendingContext

Subinterfaces of Object in org.omg.SendingContext
 interface RunTime
Defines the base class that represents the Sending Context of a request.

Uses of Object in org.omg.stub.java.rmi

Classes in org.omg.stub.java.rmi that implement Object
 class _Remote_Stub
This class provides the Stub for the Remote Type.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.OBJECT_NOT_EXIST (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.OBJECT_NOT_EXIST

No usage of org.omg.CORBA.OBJECT_NOT_EXIST

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.ObjectHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.ObjectHelper

No usage of org.omg.CORBA.ObjectHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.ObjectHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.ObjectHolder

No usage of org.omg.CORBA.ObjectHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.OctetSeqHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.OctetSeqHelper

No usage of org.omg.CORBA.OctetSeqHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.OctetSeqHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.OctetSeqHolder

Packages that use OctetSeqHolder
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).

Uses of OctetSeqHolder in org.omg.CORBA

Methods in org.omg.CORBA with parameters of type OctetSeqHolder
 void DataInputStream.read_octet_array(OctetSeqHolder seq, int offset, int length)
Reads array of IDL octets from offset for length elements from the input stream.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.OMGVMCID (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.OMGVMCID

No usage of org.omg.CORBA.OMGVMCID

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.ORB (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.ORB

Packages that use ORB
javax.rmi.CORBA | Contains portability APIs for RMI-IIOP.
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_2_3 | The CORBA_2_3 package defines additions to existing CORBA interfaces in the Java 2 Standard Edition. 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.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.CosNaming | Provides a naming service for Java IDL.
org.omg.PortableServer | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.
org.omg.PortableServer.portable | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of ORB in javax.rmi.CORBA

Methods in javax.rmi.CORBA that return ORB
 ORB Tie.orb()
Returns the ORB for this tie.

Methods in javax.rmi.CORBA with parameters of type ORB
 Object UtilDelegate.copyObject(Object obj, ORB orb)
Delegation call for Util.copyObject(java.lang.Object, org.omg.CORBA.ORB).
 Object[] UtilDelegate.copyObjects(Object[] obj, ORB orb)
Delegation call for Util.copyObjects(java.lang.Object[], org.omg.CORBA.ORB).
static Object[] Util.copyObjects(Object[] obj, ORB orb)
Copies or connects an array of objects.
static Object Util.copyObject(Object obj, ORB orb)
Copies or connects an object.
 void Tie.orb(ORB orb)
Sets the ORB for this tie.
 void StubDelegate.connect(Stub self, ORB orb)
Delegation call for Stub.connect(org.omg.CORBA.ORB).
 void Stub.connect(ORB orb)
Connects this stub to an ORB.

Uses of ORB in org.omg.CORBA

Methods in org.omg.CORBA that return ORB
ORB | LocalObject._orb() Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.
static ORB | ORB.init() Returns the ORB singleton object.
static ORB | ORB.init(String[] args, Properties props) Creates a new ORB instance for a standalone application.
static ORB | ORB.init(Applet app, Properties props) Creates a new ORB instance for an applet.

Uses of ORB in org.omg.CORBA_2_3

Subclasses of ORB in org.omg.CORBA_2_3
 class ORB
A class extending org.omg.CORBA.ORB to make the ORB portable under the OMG CORBA version 2.3 specification.

Uses of ORB in org.omg.CORBA.portable

Methods in org.omg.CORBA.portable that return ORB
ORB | Delegate.orb(Object obj) Provides a reference to the orb associated with its parameter.
ORB | ObjectImpl._orb() Returns a reference to the ORB associated with this object and its delegate.
ORB | OutputStream.orb() Returns the ORB that created this OutputStream.
ORB | InputStream.orb() Returns the ORB that created this InputStream.

Uses of ORB in org.omg.CosNaming

Methods in org.omg.CosNaming with parameters of type ORB
NamingContextExt | NamingContextExtPOA._this(ORB orb)
NamingContext | NamingContextPOA._this(ORB orb)
BindingIterator | BindingIteratorPOA._this(ORB orb)

Uses of ORB in org.omg.PortableServer

Methods in org.omg.PortableServer that return ORB
 ORB Servant._orb()
Returns the instance of the ORB currently associated with the Servant (convenience method).

Methods in org.omg.PortableServer with parameters of type ORB
ServantLocator | ServantLocatorPOA._this(ORB orb)
ServantActivator | ServantActivatorPOA._this(ORB orb)
Object | Servant._this_object(ORB orb) Allows the servant to obtain the object reference for the target CORBA Object it is incarnating for that request.

Uses of ORB in org.omg.PortableServer.portable

Methods in org.omg.PortableServer.portable that return ORB
 ORB Delegate.orb(Servant Self)
Convenience method that returns the instance of the ORB currently associated with the Servant.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.ParameterMode (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.ParameterMode

Packages that use ParameterMode
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.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.

Uses of ParameterMode in org.omg.CORBA

Fields in org.omg.CORBA declared as ParameterMode
ParameterMode | ParameterModeHolder.value
static ParameterMode | ParameterMode.PARAM_IN
static ParameterMode | ParameterMode.PARAM_OUT
static ParameterMode | ParameterMode.PARAM_INOUT

Methods in org.omg.CORBA that return ParameterMode
static ParameterMode | ParameterModeHelper.extract(Any a)
static ParameterMode | ParameterModeHelper.read(InputStream istream)
static ParameterMode | ParameterMode.from_int(int value)

Methods in org.omg.CORBA with parameters of type ParameterMode
static void | ParameterModeHelper.insert(Any a, ParameterMode that)
static void | ParameterModeHelper.write(OutputStream ostream, ParameterMode value)

Constructors in org.omg.CORBA with parameters of type ParameterMode
ParameterModeHolder(ParameterMode initialValue)

Uses of ParameterMode in org.omg.Dynamic

Fields in org.omg.Dynamic declared as ParameterMode
 ParameterMode Parameter.mode

Constructors in org.omg.Dynamic with parameters of type ParameterMode
Parameter(Any _argument, ParameterMode _mode)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.ParameterModeHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.ParameterModeHelper

No usage of org.omg.CORBA.ParameterModeHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.ParameterModeHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.ParameterModeHolder

No usage of org.omg.CORBA.ParameterModeHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.PERSIST_STORE (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.PERSIST_STORE

No usage of org.omg.CORBA.PERSIST_STORE

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.Policy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.Policy

Packages that use Policy
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.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.PortableInterceptor | Provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.
org.omg.PortableServer | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of Policy in org.omg.CORBA

Classes in org.omg.CORBA that implement Policy
 class _PolicyStub
The Stub for Policy.

Fields in org.omg.CORBA declared as Policy
Policy[] | PolicyListHolder.value
Policy | PolicyHolder.value

Methods in org.omg.CORBA that return Policy
Policy | LocalObject._get_policy(int policy_type) 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.
Policy | _PolicyStub.copy() Copies the policy object.
static Policy[] | PolicyListHelper.extract(Any a)
static Policy[] | PolicyListHelper.read(InputStream istream)
static Policy | PolicyHelper.extract(Any a)
static Policy | PolicyHelper.read(InputStream istream)
static Policy | PolicyHelper.narrow(Object obj)
Policy | DomainManagerOperations.get_domain_policy(int policy_type) This returns the policy of the specified type for objects in this domain.
Policy | PolicyOperations.copy() Returns a copy of the Policy object.
Policy | Object._get_policy(int policy_type) Returns the Policy object of the specified type which applies to this object.
Policy | ORB.create_policy(int type, Any val) Can be invoked to create new instances of policy objects of a specific type with specified initial state.

Methods in org.omg.CORBA with parameters of type Policy
Object | LocalObject._set_policy_override(Policy[] policies, SetOverrideType set_add) 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.
static void | PolicyListHelper.insert(Any a, Policy[] that)
static void | PolicyListHelper.write(OutputStream ostream, Policy[] value)
static void | PolicyHelper.insert(Any a, Policy that)
static void | PolicyHelper.write(OutputStream ostream, Policy value)
Object | Object._set_policy_override(Policy[] policies, SetOverrideType set_add) Returns a new Object with the given policies either replacing any existing policies in this Object or with the given policies added to the existing ones, depending on the value of the given SetOverrideType object.

Constructors in org.omg.CORBA with parameters of type Policy
PolicyListHolder(Policy[] initialValue)
PolicyHolder(Policy initialValue)

Uses of Policy in org.omg.CORBA.portable

Methods in org.omg.CORBA.portable that return Policy
Policy | Delegate.get_policy(Object self, int policy_type) Returns the Policy object of the specified type which applies to this object.
Policy | ObjectImpl._get_policy(int policy_type) Retrieves the Policy object for this ObjectImpl object that has the given policy type.

Methods in org.omg.CORBA.portable with parameters of type Policy
Object | Delegate.set_policy_override(Object self, Policy[] policies, SetOverrideType set_add) Associates the policies passed in with a newly created object reference that it returns.
Object | ObjectImpl._set_policy_override(Policy[] policies, SetOverrideType set_add) Sets this ObjectImpl object's override type for the given policies to the given instance of SetOverrideType.

Uses of Policy in org.omg.PortableInterceptor

Methods in org.omg.PortableInterceptor that return Policy
Policy | PolicyFactoryOperations.create_policy(int type, Any value) Returns an instance of the appropriate interface derived from CORBA.Policy whose value corresponds to the specified any.
Policy | ServerRequestInfoOperations.get_server_policy(int type) Returns the policy in effect for this operation for the given policy type.
Policy | IORInfoOperations.get_effective_policy(int type) Allows an ORB service implementation to determine what server side policy of a particular type is in effect for an IOR being constructed.
Policy | ClientRequestInfoOperations.get_request_policy(int type) Returns the given policy in effect for this operation.

Uses of Policy in org.omg.PortableServer

Subinterfaces of Policy in org.omg.PortableServer
interface | IdAssignmentPolicy IdAssignmentPolicy specifies whether Object Ids in the created POA are generated by the application or by the ORB.
interface | IdUniquenessPolicy The IdUniquenessPolicy specifies whether the servants activated in the created POA must have unique object i identities.
interface | ImplicitActivationPolicy This policy specifies whether implicit activation of servants is supported in the created POA.
interface | LifespanPolicy The LifespanPolicy specifies the lifespan of the objects implemented in the created POA.
interface | RequestProcessingPolicy This policy specifies how requests are processed by the created POA.
interface | ServantRetentionPolicy This policy specifies whether the created POA retains active servants in an Active Object Map.
interface | ThreadPolicy The ThreadPolicy specifies the threading model used with the created POA.

Methods in org.omg.PortableServer with parameters of type Policy
 POA POAOperations.create_POA(String adapter_name, POAManager a_POAManager, Policy[] policies)
This operation creates a new POA as a child of the target POA.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.PolicyError (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.PolicyError

Packages that use PolicyError
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.PortableInterceptor | Provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.

Uses of PolicyError in org.omg.CORBA

Fields in org.omg.CORBA declared as PolicyError
 PolicyError PolicyErrorHolder.value

Methods in org.omg.CORBA that return PolicyError
static PolicyError | PolicyErrorHelper.extract(Any a)
static PolicyError | PolicyErrorHelper.read(InputStream istream)

Methods in org.omg.CORBA with parameters of type PolicyError
static void | PolicyErrorHelper.insert(Any a, PolicyError that)
static void | PolicyErrorHelper.write(OutputStream ostream, PolicyError value)

Methods in org.omg.CORBA that throw PolicyError
 Policy ORB.create_policy(int type, Any val)
Can be invoked to create new instances of policy objects of a specific type with specified initial state.

Constructors in org.omg.CORBA with parameters of type PolicyError
PolicyErrorHolder(PolicyError initialValue)

Uses of PolicyError in org.omg.PortableInterceptor

Methods in org.omg.PortableInterceptor that throw PolicyError
 Policy PolicyFactoryOperations.create_policy(int type, Any value)
Returns an instance of the appropriate interface derived from CORBA.Policy whose value corresponds to the specified any.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.PolicyErrorCodeHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.PolicyErrorCodeHelper

No usage of org.omg.CORBA.PolicyErrorCodeHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.PolicyErrorHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.PolicyErrorHelper

No usage of org.omg.CORBA.PolicyErrorHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.PolicyErrorHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.PolicyErrorHolder

No usage of org.omg.CORBA.PolicyErrorHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.PolicyHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.PolicyHelper

No usage of org.omg.CORBA.PolicyHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.PolicyHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.PolicyHolder

No usage of org.omg.CORBA.PolicyHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.PolicyListHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.PolicyListHelper

No usage of org.omg.CORBA.PolicyListHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.PolicyListHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.PolicyListHolder

No usage of org.omg.CORBA.PolicyListHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.PolicyOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.PolicyOperations

Packages that use PolicyOperations
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.PortableServer | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of PolicyOperations in org.omg.CORBA

Subinterfaces of PolicyOperations in org.omg.CORBA
 interface Policy
Interfaces derived from the Policy interface allow an ORB or CORBA service access to certain choices that affect its operation.

Classes in org.omg.CORBA that implement PolicyOperations
 class _PolicyStub
The Stub for Policy.

Uses of PolicyOperations in org.omg.PortableServer

Subinterfaces of PolicyOperations in org.omg.PortableServer
interface | IdAssignmentPolicy IdAssignmentPolicy specifies whether Object Ids in the created POA are generated by the application or by the ORB.
interface | IdAssignmentPolicyOperations IdAssignmentPolicy specifies whether Object Ids in the created POA are generated by the application or by the ORB.
interface | IdUniquenessPolicy The IdUniquenessPolicy specifies whether the servants activated in the created POA must have unique object i identities.
interface | IdUniquenessPolicyOperations The IdUniquenessPolicy specifies whether the servants activated in the created POA must have unique object i identities.
interface | ImplicitActivationPolicy This policy specifies whether implicit activation of servants is supported in the created POA.
interface | ImplicitActivationPolicyOperations This policy specifies whether implicit activation of servants is supported in the created POA.
interface | LifespanPolicy The LifespanPolicy specifies the lifespan of the objects implemented in the created POA.
interface | LifespanPolicyOperations The LifespanPolicy specifies the lifespan of the objects implemented in the created POA.
interface | RequestProcessingPolicy This policy specifies how requests are processed by the created POA.
interface | RequestProcessingPolicyOperations This policy specifies how requests are processed by the created POA.
interface | ServantRetentionPolicy This policy specifies whether the created POA retains active servants in an Active Object Map.
interface | ServantRetentionPolicyOperations This policy specifies whether the created POA retains active servants in an Active Object Map.
interface | ThreadPolicy The ThreadPolicy specifies the threading model used with the created POA.
interface | ThreadPolicyOperations The ThreadPolicy specifies the threading model used with the created POA.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.PolicyTypeHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.PolicyTypeHelper

No usage of org.omg.CORBA.PolicyTypeHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.Principal (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.Principal

Packages that use Principal
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.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.

Uses of Principal in org.omg.CORBA

Fields in org.omg.CORBA declared as Principal
 Principal PrincipalHolder.value
Deprecated. The Principal value held by this PrincipalHolder object.

Methods in org.omg.CORBA that return Principal
 Principal Any.extract_Principal()
Deprecated. Deprecated by CORBA 2.2.

Methods in org.omg.CORBA with parameters of type Principal
 void Any.insert_Principal(Principal p)
Deprecated. Deprecated by CORBA 2.2.

Constructors in org.omg.CORBA with parameters of type Principal
PrincipalHolder(Principal initial)
Deprecated. Constructs a new PrincipalHolder object with its value field initialized to the given Principal object.

Uses of Principal in org.omg.CORBA.portable

Methods in org.omg.CORBA.portable that return Principal
 Principal InputStream.read_Principal()
Deprecated. Deprecated by CORBA 2.2.

Methods in org.omg.CORBA.portable with parameters of type Principal
 void OutputStream.write_Principal(Principal value)
Deprecated. Deprecated by CORBA 2.2.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.PrincipalHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.PrincipalHolder

No usage of org.omg.CORBA.PrincipalHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.PRIVATE_MEMBER (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.PRIVATE_MEMBER

No usage of org.omg.CORBA.PRIVATE_MEMBER

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.PUBLIC_MEMBER (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.PUBLIC_MEMBER

No usage of org.omg.CORBA.PUBLIC_MEMBER

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.RepositoryIdHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.RepositoryIdHelper

No usage of org.omg.CORBA.RepositoryIdHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.Request (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.Request

Packages that use Request
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.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.

Uses of Request in org.omg.CORBA

Methods in org.omg.CORBA that return Request
Request | LocalObject._request(String operation) Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.
Request | LocalObject._create_request(Context ctx, String operation, NVList arg_list, NamedValue result) Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.
Request | LocalObject._create_request(Context ctx, String operation, NVList arg_list, NamedValue result, ExceptionList exceptions, ContextList contexts) Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.
Request | Object._request(String operation) Creates a Request instance for use in the Dynamic Invocation Interface.
Request | Object._create_request(Context ctx, String operation, NVList arg_list, NamedValue result) Creates a Request instance initialized with the given context, method name, list of arguments, and container for the method's return value.
Request | Object._create_request(Context ctx, String operation, NVList arg_list, NamedValue result, ExceptionList exclist, ContextList ctxlist) Creates a Request instance initialized with the given context, method name, list of arguments, container for the method's return value, list of possible exceptions, and list of context strings needing to be resolved.
abstract Request | ORB.get_next_response() Gets the next Request instance for which a response has been received.

Methods in org.omg.CORBA with parameters of type Request
abstract void | ORB.send_multiple_requests_oneway(Request[] req) Sends multiple dynamic (DII) requests asynchronously without expecting any responses.
abstract void | ORB.send_multiple_requests_deferred(Request[] req) Sends multiple dynamic (DII) requests asynchronously.

Uses of Request in org.omg.CORBA.portable

Methods in org.omg.CORBA.portable that return Request
abstract Request | Delegate.request(Object obj, String operation) Creates a Request instance for use in the Dynamic Invocation Interface.
abstract Request | Delegate.create_request(Object obj, Context ctx, String operation, NVList arg_list, NamedValue result) Creates a Request instance for use in the Dynamic Invocation Interface.
abstract Request | Delegate.create_request(Object obj, Context ctx, String operation, NVList arg_list, NamedValue result, ExceptionList exclist, ContextList ctxlist) Creates a Request instance for use in the Dynamic Invocation Interface.
Request | ObjectImpl._request(String operation) Creates a Request object containing the given method that can be used with the Dynamic Invocation Interface.
Request | ObjectImpl._create_request(Context ctx, String operation, NVList arg_list, NamedValue result) Creates a Request object that contains the given context, method, argument list, and container for the result.
Request | ObjectImpl._create_request(Context ctx, String operation, NVList arg_list, NamedValue result, ExceptionList exceptions, ContextList contexts) Creates a Request object that contains the given context, method, argument list, container for the result, exceptions, and list of property names to be used in resolving the context strings.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.ServerRequest (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.ServerRequest

Packages that use ServerRequest
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.CosNaming | Provides a naming service for Java IDL.
org.omg.PortableServer | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of ServerRequest in org.omg.CORBA

Methods in org.omg.CORBA with parameters of type ServerRequest
 void DynamicImplementation.invoke(ServerRequest request)
Deprecated. Deprecated by Portable Object Adapter

Uses of ServerRequest in org.omg.CosNaming

Methods in org.omg.CosNaming with parameters of type ServerRequest
void | _BindingIteratorImplBase.invoke(ServerRequest r)
void | _NamingContextImplBase.invoke(ServerRequest r)

Uses of ServerRequest in org.omg.PortableServer

Methods in org.omg.PortableServer with parameters of type ServerRequest
abstract  void DynamicImplementation.invoke(ServerRequest request)
Receives requests issued to any CORBA object incarnated by the DSI servant and performs the processing necessary to execute the request.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.ServiceDetail (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.ServiceDetail

Packages that use ServiceDetail
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).

Uses of ServiceDetail in org.omg.CORBA

Fields in org.omg.CORBA declared as ServiceDetail
 ServiceDetail[] ServiceInformation.service_details
Array of ServiceDetails giving more details about the service.

Methods in org.omg.CORBA that return ServiceDetail
static ServiceDetail | ServiceDetailHelper.read(InputStream in)
static ServiceDetail | ServiceDetailHelper.extract(Any a)

Methods in org.omg.CORBA with parameters of type ServiceDetail
static void | ServiceDetailHelper.write(OutputStream out, ServiceDetail that)
static void | ServiceDetailHelper.insert(Any a, ServiceDetail that)

Constructors in org.omg.CORBA with parameters of type ServiceDetail
ServiceInformation(int[] __service_options, ServiceDetail[] __service_details)
Constructs a ServiceInformation object with the given service_options and service_details.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.ServiceDetailHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.ServiceDetailHelper

No usage of org.omg.CORBA.ServiceDetailHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.ServiceInformation (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.ServiceInformation

Packages that use ServiceInformation
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).

Uses of ServiceInformation in org.omg.CORBA

Fields in org.omg.CORBA declared as ServiceInformation
 ServiceInformation ServiceInformationHolder.value
The ServiceInformation value held by this ServiceInformationHolder object in its value field.

Methods in org.omg.CORBA that return ServiceInformation
static ServiceInformation | ServiceInformationHelper.read(InputStream in)
static ServiceInformation | ServiceInformationHelper.extract(Any a)

Methods in org.omg.CORBA with parameters of type ServiceInformation
static void | ServiceInformationHelper.write(OutputStream out, ServiceInformation that)
static void | ServiceInformationHelper.insert(Any a, ServiceInformation that)

Constructors in org.omg.CORBA with parameters of type ServiceInformation
ServiceInformationHolder(ServiceInformation arg)
Constructs a new ServiceInformationHolder object with its value field initialized to the given ServiceInformation object.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.ServiceInformationHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.ServiceInformationHelper

No usage of org.omg.CORBA.ServiceInformationHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.ServiceInformationHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.ServiceInformationHolder

Packages that use ServiceInformationHolder
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).

Uses of ServiceInformationHolder in org.omg.CORBA

Methods in org.omg.CORBA with parameters of type ServiceInformationHolder
 boolean ORB.get_service_information(short service_type, ServiceInformationHolder service_info)
Used to obtain information about CORBA facilities and services that are supported by this ORB.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.SetOverrideType (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.SetOverrideType

Packages that use SetOverrideType
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.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.

Uses of SetOverrideType in org.omg.CORBA

Fields in org.omg.CORBA declared as SetOverrideType
static SetOverrideType | SetOverrideType.SET_OVERRIDE The SetOverrideType constant for the enum value SET_OVERRIDE.
static SetOverrideType | SetOverrideType.ADD_OVERRIDE The SetOverrideType constant for the enum value ADD_OVERRIDE.

Methods in org.omg.CORBA that return SetOverrideType
static SetOverrideType | SetOverrideTypeHelper.extract(Any a)
static SetOverrideType | SetOverrideTypeHelper.read(InputStream istream)
static SetOverrideType | SetOverrideType.from_int(int i) Converts the given int to the corresponding SetOverrideType instance.

Methods in org.omg.CORBA with parameters of type SetOverrideType
Object | LocalObject._set_policy_override(Policy[] policies, SetOverrideType set_add) 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.
static void | SetOverrideTypeHelper.insert(Any a, SetOverrideType that)
static void | SetOverrideTypeHelper.write(OutputStream ostream, SetOverrideType value)
Object | Object._set_policy_override(Policy[] policies, SetOverrideType set_add) Returns a new Object with the given policies either replacing any existing policies in this Object or with the given policies added to the existing ones, depending on the value of the given SetOverrideType object.

Uses of SetOverrideType in org.omg.CORBA.portable

Methods in org.omg.CORBA.portable with parameters of type SetOverrideType
Object | Delegate.set_policy_override(Object self, Policy[] policies, SetOverrideType set_add) Associates the policies passed in with a newly created object reference that it returns.
Object | ObjectImpl._set_policy_override(Policy[] policies, SetOverrideType set_add) Sets this ObjectImpl object's override type for the given policies to the given instance of SetOverrideType.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.SetOverrideTypeHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.SetOverrideTypeHelper

No usage of org.omg.CORBA.SetOverrideTypeHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.ShortHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.ShortHolder

No usage of org.omg.CORBA.ShortHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.ShortSeqHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.ShortSeqHelper

No usage of org.omg.CORBA.ShortSeqHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.ShortSeqHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.ShortSeqHolder

Packages that use ShortSeqHolder
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).

Uses of ShortSeqHolder in org.omg.CORBA

Methods in org.omg.CORBA with parameters of type ShortSeqHolder
 void DataInputStream.read_short_array(ShortSeqHolder seq, int offset, int length)
Reads array of IDL shorts from offset for length elements from the input stream.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.StringHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.StringHolder

No usage of org.omg.CORBA.StringHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.StringSeqHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.StringSeqHelper

No usage of org.omg.CORBA.StringSeqHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.StringSeqHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.StringSeqHolder

No usage of org.omg.CORBA.StringSeqHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.StringValueHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.StringValueHelper

No usage of org.omg.CORBA.StringValueHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.StructMember (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.StructMember

Packages that use StructMember
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).

Uses of StructMember in org.omg.CORBA

Methods in org.omg.CORBA that return StructMember
static StructMember | StructMemberHelper.extract(Any a)
static StructMember | StructMemberHelper.read(InputStream istream)

Methods in org.omg.CORBA with parameters of type StructMember
static void | StructMemberHelper.insert(Any a, StructMember that)
static void | StructMemberHelper.write(OutputStream ostream, StructMember value)
abstract TypeCode | ORB.create_struct_tc(String id, String name, StructMember[] members) Creates a TypeCode object representing an IDL struct.
abstract TypeCode | ORB.create_exception_tc(String id, String name, StructMember[] members) Creates a TypeCode object representing an IDL exception.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.StructMemberHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.StructMemberHelper

No usage of org.omg.CORBA.StructMemberHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.SystemException (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.SystemException

Packages that use SystemException
javax.rmi.CORBA | Contains portability APIs for RMI-IIOP.
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.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.

Uses of SystemException in javax.rmi.CORBA

Methods in javax.rmi.CORBA with parameters of type SystemException
 RemoteException UtilDelegate.mapSystemException(SystemException ex)
Delegation call for Util.mapSystemException(org.omg.CORBA.SystemException).
static RemoteException Util.mapSystemException(SystemException ex)
Maps a SystemException to a RemoteException.

Uses of SystemException in org.omg.CORBA

Subclasses of SystemException in org.omg.CORBA
class | BAD_CONTEXT Exception thrown when an operation is invoked by a client but the passed context does not contain the context values required by the operation.
class | BAD_INV_ORDER This exception indicates that the caller has invoked operations in the wrong order.
class | BAD_OPERATION Exception thrown when an object reference denotes an existing object, but that the object does not support the operation that was invoked.
class | BAD_PARAM Exception thrown when a parameter passed to a call is out of range or otherwise considered illegal.
class | BAD_TYPECODE Exception thrown when the ORB has encountered a malformed type code (for example, a type code with an invalid TCKind value).
class | COMM_FAILURE This exception is raised if communication is lost while an operation is in progress, after the request was sent by the client, but before the reply from the server has been returned to the client.
class | DATA_CONVERSION This exception is raised if an ORB cannot convert the representation of data as marshaled into its native representation or vice-versa.
class | FREE_MEM Exception thrown when the ORB failed in an attempt to free dynamic memory, for example because of heap corruption or memory segments being locked.
class | IMP_LIMIT This exception indicates that an implementation limit was exceeded in the ORB run time.
class | INITIALIZE Exception thrown when an ORB has encountered a failure during its initialization, such as failure to acquire networking resources or detecting a configuration error.
class | INTERNAL This exception indicates an internal failure in an ORB, for example, if an ORB has detected corruption of its internal data structures.
class | INTF_REPOS Exception raised when an ORB cannot reach the interface repository, or some other failure relating to the interface repository is detected.
class | INV_FLAG Exception thrown when an invalid flag was passed to an operation (for example, when creating a DII request).
class | INV_IDENT This exception indicates that an IDL identifier is syntactically invalid.
class | INV_OBJREF This exception indicates that an object reference is internally malformed.
class | INV_POLICY Standard exception thrown when an invocation cannot be made because of an incompatibility between Policy overrides that apply to the particular invocation.
class | INVALID_TRANSACTION Exception thrown when the request carried an invalid transaction context.
class | MARSHAL A request or reply from the network is structurally invalid.
class | NO_IMPLEMENT This exception indicates that even though the operation that was invoked exists (it has an IDL definition), no implementation for that operation exists.
class | NO_MEMORY Exception thrown when the ORB run time has run out of memory.
class | NO_PERMISSION Exception thrown when an invocation failed because the caller has insufficient privileges.
class | NO_RESOURCES Exception thrown when the ORB has encountered some general resource limitation.
class | NO_RESPONSE 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.
class | OBJ_ADAPTER 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.
class | OBJECT_NOT_EXIST Exception raised whenever an invocation on a deleted object was performed.
class | PERSIST_STORE This exception indicates a persistent storage failure, for example, failure to establish a database connection or corruption of a database.
class | TRANSACTION_REQUIRED Exception indicates that the request carried a null transaction context, but an active transaction is required.
class | TRANSACTION_ROLLEDBACK Exception thrown when the transaction associated with the request has already been rolled back or marked to roll back.
class | TRANSIENT Exception thrown when the ORB attempted to reach an object and failed.
class | UNKNOWN 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.

Uses of SystemException in org.omg.CORBA.portable

Subclasses of SystemException in org.omg.CORBA.portable
class | IndirectionException The Indirection exception is a Java specific system exception.
class | UnknownException The org.omg.CORBA.portable.UnknownException is used for reporting unknown exceptions between ties and ORBs and between ORBs and stubs.

Methods in org.omg.CORBA.portable that throw SystemException
 OutputStream InvokeHandler._invoke(String method, InputStream input, ResponseHandler handler)
Invoked by the ORB to dispatch a request to the servant.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.TCKind (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.TCKind

Packages that use TCKind
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.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.

Uses of TCKind in org.omg.CORBA

Fields in org.omg.CORBA declared as TCKind
static TCKind | TCKind.tk_null The TCKind constant whose value field is initialized with TCKind._tk_null.
static TCKind | TCKind.tk_void The TCKind constant whose value field is initialized with TCKind._tk_void.
static TCKind | TCKind.tk_short The TCKind constant whose value field is initialized with TCKind._tk_short.
static TCKind | TCKind.tk_long The TCKind constant whose value field is initialized with TCKind._tk_long.
static TCKind | TCKind.tk_ushort The TCKind constant whose value field is initialized with TCKind._tk_ushort.
static TCKind | TCKind.tk_ulong The TCKind constant whose value field is initialized with TCKind._tk_ulong.
static TCKind | TCKind.tk_float The TCKind constant whose value field is initialized with TCKind._tk_float.
static TCKind | TCKind.tk_double The TCKind constant whose value field is initialized with TCKind._tk_double.
static TCKind | TCKind.tk_boolean The TCKind constant whose value field is initialized with TCKind._tk_boolean.
static TCKind | TCKind.tk_char The TCKind constant whose value field is initialized with TCKind._tk_char.
static TCKind | TCKind.tk_octet The TCKind constant whose value field is initialized with TCKind._tk_octet.
static TCKind | TCKind.tk_any The TCKind constant whose value field is initialized with TCKind._tk_any.
static TCKind | TCKind.tk_TypeCode The TCKind constant whose value field is initialized with TCKind._tk_TypeCode.
static TCKind | TCKind.tk_Principal The TCKind constant whose value field is initialized with TCKind._tk_Principal.
static TCKind | TCKind.tk_objref The TCKind constant whose value field is initialized with TCKind._tk_objref.
static TCKind | TCKind.tk_struct The TCKind constant whose value field is initialized with TCKind._tk_struct.
static TCKind | TCKind.tk_union The TCKind constant whose value field is initialized with TCKind._tk_union.
static TCKind | TCKind.tk_enum The TCKind constant whose value field is initialized with TCKind._tk_enum.
static TCKind | TCKind.tk_string The TCKind constant whose value field is initialized with TCKind._tk_string.
static TCKind | TCKind.tk_sequence The TCKind constant whose value field is initialized with TCKind._tk_sequence.
static TCKind | TCKind.tk_array The TCKind constant whose value field is initialized with TCKind._tk_array.
static TCKind | TCKind.tk_alias The TCKind constant whose value field is initialized with TCKind._tk_alias.
static TCKind | TCKind.tk_except The TCKind constant whose value field is initialized with TCKind._tk_except.
static TCKind | TCKind.tk_longlong The TCKind constant whose value field is initialized with TCKind._tk_longlong.
static TCKind | TCKind.tk_ulonglong The TCKind constant whose value field is initialized with TCKind._tk_ulonglong.
static TCKind | TCKind.tk_longdouble The TCKind constant whose value field is initialized with TCKind._tk_longdouble.
static TCKind | TCKind.tk_wchar The TCKind constant whose value field is initialized with TCKind._tk_wchar.
static TCKind | TCKind.tk_wstring The TCKind constant whose value field is initialized with TCKind._tk_wstring.
static TCKind | TCKind.tk_fixed The TCKind constant whose value field is initialized with TCKind._tk_fixed.
static TCKind | TCKind.tk_value The TCKind constant whose value field is initialized with TCKind._tk_value.
static TCKind | TCKind.tk_value_box The TCKind constant whose value field is initialized with TCKind._tk_value_box.
static TCKind | TCKind.tk_native The TCKind constant whose value field is initialized with TCKind._tk_native.
static TCKind | TCKind.tk_abstract_interface The TCKind constant whose value field is initialized with TCKind._tk_abstract_interface.

Methods in org.omg.CORBA that return TCKind
TCKind | DynValue.current_member_kind() Returns the TCKind object that describes the current member.
TCKind | DynUnion.discriminator_kind() Returns the TCKind object associated with the discriminator of this union.
TCKind | DynUnion.member_kind() Returns the TCKind associated with the member of this union.
TCKind | DynStruct.current_member_kind() Returns the TCKind object that describes the kind of the current member.
static TCKind | TCKind.from_int(int i) Converts the given int to the corresponding TCKind instance.
abstract TCKind | TypeCode.kind() Retrieves the kind of this TypeCode object.

Methods in org.omg.CORBA with parameters of type TCKind
abstract  TypeCode ORB.get_primitive_tc(TCKind tcKind)
Retrieves the TypeCode object that represents the given primitive IDL type.

Uses of TCKind in org.omg.DynamicAny

Methods in org.omg.DynamicAny that return TCKind
TCKind | _DynValueStub.current_member_kind() Returns the TCKind associated with the member at the current position.
TCKind | _DynUnionStub.discriminator_kind() Returns the TCKind value of the discriminators TypeCode.
TCKind | _DynUnionStub.member_kind() Returns the TCKind value of the currently active members TypeCode.
TCKind | _DynStructStub.current_member_kind() Returns the TCKind associated with the member at the current position.
TCKind | DynValueOperations.current_member_kind() Returns the TCKind associated with the member at the current position.
TCKind | DynUnionOperations.discriminator_kind() Returns the TCKind value of the discriminators TypeCode.
TCKind | DynUnionOperations.member_kind() Returns the TCKind value of the currently active members TypeCode.
TCKind | DynStructOperations.current_member_kind() Returns the TCKind associated with the member at the current position.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.TRANSACTION_REQUIRED (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.TRANSACTION_REQUIRED

No usage of org.omg.CORBA.TRANSACTION_REQUIRED

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.TRANSACTION_ROLLEDBACK (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.TRANSACTION_ROLLEDBACK

No usage of org.omg.CORBA.TRANSACTION_ROLLEDBACK

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.TRANSIENT (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.TRANSIENT

No usage of org.omg.CORBA.TRANSIENT

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.TypeCode (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.TypeCode

Packages that use TypeCode
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.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.CosNaming | Provides a naming service for Java IDL.
org.omg.CosNaming.NamingContextExtPackage | This package contains the following classes, which are used in org.omg.CosNaming.NamingContextExt:
org.omg.CosNaming.NamingContextPackage | This package contains Exception classes for the org.omg.CosNaming 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 | 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 | 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 | 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 | This package contains the exceptions specified in the IOP::CodeFactory interface (as part of the Portable Interceptors spec).
org.omg.IOP.CodecPackage | This package is generated from the IOP::Codec IDL interface definition.
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 | 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 | 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 | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.
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 | Encapsulates the processing state of the POAs it is associated with.
org.omg.PortableServer.POAPackage | Allows programmers to construct object implementations that are portable between different ORB products.
org.omg.PortableServer.ServantLocatorPackage | Provides classes and interfaces for locating the servant.

Uses of TypeCode in org.omg.CORBA

Fields in org.omg.CORBA declared as TypeCode
TypeCode | TypeCodeHolder.value The TypeCode value held by this TypeCodeHolder object.
TypeCode | ValueMember.type The type of of this value member.
TypeCode | UnionMember.type The type of the union member described by this UnionMember object.
TypeCode | StructMember.type The type of the struct member described by this StructMember object.

Methods in org.omg.CORBA that return TypeCode
TypeCode | WrongTransactionHolder._type()
TypeCode | WStringSeqHolder._type()
static TypeCode | WStringSeqHelper.type()
TypeCode | UnknownUserExceptionHolder._type()
static TypeCode | UnknownUserExceptionHelper.type()
TypeCode | StringSeqHolder._type()
static TypeCode | StringSeqHelper.type()
TypeCode | PolicyErrorHolder._type()
static TypeCode | PolicyErrorHelper.type()
static TypeCode | PolicyErrorCodeHelper.type()
TypeCode | ParameterModeHolder._type()
static TypeCode | ParameterModeHelper.type()
TypeCode | _IDLTypeStub.type()
static TypeCode | WStringValueHelper.type()
static TypeCode | WCharSeqHelper.type()
static TypeCode | VisibilityHelper.type()
static TypeCode | VersionSpecHelper.type()
static TypeCode | ValueMemberHelper.type()
TypeCode | ValueBaseHolder._type() Returns the TypeCode object corresponding to the value held in the Holder.
static TypeCode | ValueBaseHelper.type()
static TypeCode | UnionMemberHelper.type()
static TypeCode | UShortSeqHelper.type()
static TypeCode | ULongSeqHelper.type()
static TypeCode | ULongLongSeqHelper.type()
static TypeCode | StructMemberHelper.type()
static TypeCode | StringValueHelper.type()
static TypeCode | ShortSeqHelper.type()
static TypeCode | SetOverrideTypeHelper.type()
static TypeCode | RepositoryIdHelper.type()
TypeCode | PolicyListHolder._type()
static TypeCode | PolicyListHelper.type()
static TypeCode | PolicyTypeHelper.type()
TypeCode | PolicyHolder._type()
static TypeCode | PolicyHelper.type()
static TypeCode | OctetSeqHelper.type()
static TypeCode | NameValuePairHelper.type()
static TypeCode | LongSeqHelper.type()
static TypeCode | LongLongSeqHelper.type()
static TypeCode | IdentifierHelper.type()
static TypeCode | IDLTypeHelper.type()
static TypeCode | FloatSeqHelper.type()
static TypeCode | FieldNameHelper.type()
static TypeCode | DoubleSeqHelper.type()
static TypeCode | DefinitionKindHelper.type()
TypeCode | DoubleSeqHolder._type()
TypeCode | FloatSeqHolder._type()
TypeCode | LongLongSeqHolder._type()
TypeCode | ULongLongSeqHolder._type()
TypeCode | ULongSeqHolder._type()
TypeCode | LongSeqHolder._type()
TypeCode | UShortSeqHolder._type()
TypeCode | ShortSeqHolder._type()
TypeCode | OctetSeqHolder._type()
TypeCode | WCharSeqHolder._type()
TypeCode | DataInputStream.read_TypeCode() Reads an IDL typecode from the input stream.
TypeCode | CurrentHolder._type()
static TypeCode | CurrentHelper.type()
static TypeCode | CompletionStatusHelper.type()
TypeCode | CharSeqHolder._type()
static TypeCode | CharSeqHelper.type()
TypeCode | BooleanSeqHolder._type()
static TypeCode | BooleanSeqHelper.type()
TypeCode | AnySeqHolder._type()
static TypeCode | AnySeqHelper.type()
TypeCode | TypeCodeHolder._type() Returns the TypeCode corresponding to the value held in this TypeCodeHolder object.
TypeCode | StringHolder._type() Retrieves the TypeCode object that corresponds to the value held in this StringHolder object.
TypeCode | ShortHolder._type() Returns the TypeCode corresponding to the value held in this ShortHolder object.
TypeCode | PrincipalHolder._type() Deprecated.
TypeCode | ObjectHolder._type() Returns the TypeCode corresponding to the value held in this ObjectHolder object
TypeCode | LongHolder._type() Returns the TypeCode object corresponding to the value held in the Holder.
TypeCode | IntHolder._type() Retrieves the TypeCode object that corresponds to the value held in this IntHolder object's value field.
TypeCode | FloatHolder._type() Return the TypeCode of this Streamable.
TypeCode | FixedHolder._type() Return the TypeCode of this holder object.
TypeCode | DoubleHolder._type() Return the TypeCode of this holder object.
TypeCode | CharHolder._type() Returns the TypeCode object corresponding to the value held in this CharHolder object.
TypeCode | ByteHolder._type() Returns the TypeCode corresponding to the value held in this ByteHolder object.
TypeCode | BooleanHolder._type() Retrieves the TypeCode object that corresponds to the value held in this BooleanHolder object.
TypeCode | AnyHolder._type() Returns the TypeCode object corresponding to the value held in this AnyHolder object.
static TypeCode | ServiceDetailHelper.type()
static TypeCode | ObjectHelper.type()
static TypeCode | ServiceInformationHelper.type()
static TypeCode | WrongTransactionHelper.type()
TypeCode | DynAny.type() Returns the TypeCode of the object inserted into this DynAny.
TypeCode | DynAny.get_typecode() Retrieves the org.omg.CORBA.TypeCode contained in this DynAny object.
TypeCode | ServiceInformationHolder._type() Retrieves the TypeCode object that corresponds to the value held in this ServiceInformationHolder object's value field.
TypeCode | IDLTypeOperations.type() The type attribute describes the type defined by an object derived from IDLType.
abstract TypeCode | ExceptionList.item(int index) Returns the TypeCode object at the given index.
abstract TypeCode | TypeCode.get_compact_typecode() Strips out all optional name and member name fields, but leaves all alias typecodes intact.
abstract TypeCode | TypeCode.member_type(int index) Retrieves the TypeCode object describing the type of the member identified by the given index.
abstract TypeCode | TypeCode.discriminator_type() Returns a TypeCode object describing all non-default member labels.
abstract TypeCode | TypeCode.content_type() Returns the TypeCode object representing the IDL type for the members of the object described by this TypeCode object.
abstract TypeCode | TypeCode.concrete_base_type() Returns the TypeCode object that describes the concrete base type of the value type that this TypeCode object describes.
abstract TypeCode | Any.type() Returns type information for the element contained in this Any object.
abstract TypeCode | Any.extract_TypeCode() Extracts the TypeCode object in this Any object's value field.
abstract TypeCode | ORB.get_primitive_tc(TCKind tcKind) Retrieves the TypeCode object that represents the given primitive IDL type.
abstract TypeCode | ORB.create_struct_tc(String id, String name, StructMember[] members) Creates a TypeCode object representing an IDL struct.
abstract TypeCode | ORB.create_union_tc(String id, String name, TypeCode discriminator_type, UnionMember[] members) Creates a TypeCode object representing an IDL union.
abstract TypeCode | ORB.create_enum_tc(String id, String name, String[] members) Creates a TypeCode object representing an IDL enum.
abstract TypeCode | ORB.create_alias_tc(String id, String name, TypeCode original_type) Creates a TypeCode object representing an IDL alias (typedef).
abstract TypeCode | ORB.create_exception_tc(String id, String name, StructMember[] members) Creates a TypeCode object representing an IDL exception.
abstract TypeCode | ORB.create_interface_tc(String id, String name) Creates a TypeCode object representing an IDL interface.
abstract TypeCode | ORB.create_string_tc(int bound) Creates a TypeCode object representing a bounded IDL string.
abstract TypeCode | ORB.create_wstring_tc(int bound) Creates a TypeCode object representing a bounded IDL wstring (wide string).
abstract TypeCode | ORB.create_sequence_tc(int bound, TypeCode element_type) Creates a TypeCode object representing an IDL sequence.
abstract TypeCode | ORB.create_recursive_sequence_tc(int bound, int offset) Deprecated. Use a combination of create_recursive_tc and create_sequence_tc instead
abstract TypeCode | ORB.create_array_tc(int length, TypeCode element_type) Creates a TypeCode object representing an IDL array.
TypeCode | ORB.create_native_tc(String id, String name) Create a TypeCode object for an IDL native type.
TypeCode | ORB.create_abstract_interface_tc(String id, String name) Create a TypeCode object for an IDL abstract interface.
TypeCode | ORB.create_fixed_tc(short digits, short scale) Create a TypeCode object for an IDL fixed type.
TypeCode | ORB.create_value_tc(String id, String name, short type_modifier, TypeCode concrete_base, ValueMember[] members) Create a TypeCode object for an IDL value type.
TypeCode | ORB.create_recursive_tc(String id) Create a recursive TypeCode object which serves as a placeholder for a concrete TypeCode during the process of creating TypeCodes which contain recursion.
TypeCode | ORB.create_value_box_tc(String id, String name, TypeCode boxed_type) Creates a TypeCode object for an IDL value box.

Methods in org.omg.CORBA with parameters of type TypeCode
void | DataOutputStream.write_TypeCode(TypeCode value) Writes the typecode to the output stream.
void | DynAny.insert_typecode(TypeCode value) Inserts the given org.omg.CORBA.TypeCode as the value for this DynAny object.
abstract void | ExceptionList.add(TypeCode exc) Adds a TypeCode object describing an exception to this ExceptionList object.
abstract boolean | TypeCode.equal(TypeCode tc) Compares this TypeCode object with the given one, testing for equality.
abstract boolean | TypeCode.equivalent(TypeCode tc) Tests to see if the given TypeCode object is equivalent to this TypeCode object.
abstract void | Any.type(TypeCode t) Sets this Any object's type field to the given TypeCode object and clears its value.
abstract void | Any.read_value(InputStream is, TypeCode t) Reads off (unmarshals) the value of an Any object from the given input stream using the given typecode.
abstract void | Any.insert_Value(Serializable v, TypeCode t) Inserts the given java.io.Serializable object into this Any object's value field.
abstract void | Any.insert_Object(Object o, TypeCode t) Inserts the given org.omg.CORBA.Object object into this Any object's value field.
abstract void | Any.insert_TypeCode(TypeCode t) Inserts the given TypeCode object into this Any object's value field.
void | Any.insert_fixed(BigDecimal value, TypeCode type) Throws an org.omg.CORBA.NO_IMPLEMENT exception.
abstract void | Request.set_return_type(TypeCode tc) Sets the typecode for the return value of the method.
abstract TypeCode | ORB.create_union_tc(String id, String name, TypeCode discriminator_type, UnionMember[] members) Creates a TypeCode object representing an IDL union.
abstract TypeCode | ORB.create_alias_tc(String id, String name, TypeCode original_type) Creates a TypeCode object representing an IDL alias (typedef).
abstract TypeCode | ORB.create_sequence_tc(int bound, TypeCode element_type) Creates a TypeCode object representing an IDL sequence.
abstract TypeCode | ORB.create_array_tc(int length, TypeCode element_type) Creates a TypeCode object representing an IDL array.
TypeCode | ORB.create_value_tc(String id, String name, short type_modifier, TypeCode concrete_base, ValueMember[] members) Create a TypeCode object for an IDL value type.
TypeCode | ORB.create_value_box_tc(String id, String name, TypeCode boxed_type) Creates a TypeCode object for an IDL value box.
DynAny | ORB.create_basic_dyn_any(TypeCode type) Creates a basic DynAny object from the given TypeCode object.
DynStruct | ORB.create_dyn_struct(TypeCode type) Creates a new DynStruct object from the given TypeCode object.
DynSequence | ORB.create_dyn_sequence(TypeCode type) Creates a new DynSequence object from the given TypeCode object.
DynArray | ORB.create_dyn_array(TypeCode type) Creates a new DynArray object from the given TypeCode object.
DynUnion | ORB.create_dyn_union(TypeCode type) Creates a new DynUnion object from the given TypeCode object.
DynEnum | ORB.create_dyn_enum(TypeCode type) Creates a new DynEnum object from the given TypeCode object.

Constructors in org.omg.CORBA with parameters of type TypeCode
TypeCodeHolder(TypeCode initial)
Constructs a new TypeCodeHolder object with its value field initialized to the given TypeCode object.
ValueMember(String __name, String __id, String __defined_in, String __version, TypeCode __type, IDLType __type_def, short __access)
Constructs a ValueMember object initialized with the given values.
UnionMember(String __name, Any __label, TypeCode __type, IDLType __type_def)
Constructs a new UnionMember object with its fields initialized to the given values.
StructMember(String __name, TypeCode __type, IDLType __type_def)
Constructs a StructMember object initialized with the given values.

Uses of TypeCode in org.omg.CORBA.portable

Methods in org.omg.CORBA.portable that return TypeCode
TypeCode | Streamable._type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
abstract TypeCode | InputStream.read_TypeCode() Reads a TypeCode from this input stream.

Methods in org.omg.CORBA.portable with parameters of type TypeCode
abstract  void OutputStream.write_TypeCode(TypeCode value)
Writes a TypeCode on this output stream.

Uses of TypeCode in org.omg.CosNaming

Methods in org.omg.CosNaming that return TypeCode
TypeCode | NamingContextExtHolder._type()
static TypeCode | NamingContextExtHelper.type()
TypeCode | NamingContextHolder._type()
static TypeCode | NamingContextHelper.type()
TypeCode | NameHolder._type()
static TypeCode | NameHelper.type()
TypeCode | NameComponentHolder._type()
static TypeCode | NameComponentHelper.type()
TypeCode | BindingTypeHolder._type()
static TypeCode | BindingTypeHelper.type()
static TypeCode | BindingListHelper.type()
TypeCode | BindingIteratorHolder._type()
static TypeCode | BindingIteratorHelper.type()
TypeCode | BindingListHolder._type()
TypeCode | BindingHolder._type()
static TypeCode | BindingHelper.type()
static TypeCode | IstringHelper.type()

Uses of TypeCode in org.omg.CosNaming.NamingContextExtPackage

Methods in org.omg.CosNaming.NamingContextExtPackage that return TypeCode
static TypeCode | URLStringHelper.type()
static TypeCode | StringNameHelper.type()
TypeCode | InvalidAddressHolder._type()
static TypeCode | InvalidAddressHelper.type()
static TypeCode | AddressHelper.type()

Uses of TypeCode in org.omg.CosNaming.NamingContextPackage

Methods in org.omg.CosNaming.NamingContextPackage that return TypeCode
TypeCode | NotFoundReasonHolder._type()
static TypeCode | NotFoundReasonHelper.type()
TypeCode | NotFoundHolder._type()
static TypeCode | NotFoundHelper.type()
TypeCode | NotEmptyHolder._type()
static TypeCode | NotEmptyHelper.type()
TypeCode | InvalidNameHolder._type()
static TypeCode | InvalidNameHelper.type()
TypeCode | CannotProceedHolder._type()
static TypeCode | CannotProceedHelper.type()
TypeCode | AlreadyBoundHolder._type()
static TypeCode | AlreadyBoundHelper.type()

Uses of TypeCode in org.omg.DynamicAny

Methods in org.omg.DynamicAny that return TypeCode
TypeCode | _DynSequenceStub.type() Returns the TypeCode associated with this DynAny object.
TypeCode | _DynSequenceStub.get_typecode() Extracts the TypeCode object from this DynAny.
TypeCode | _DynFixedStub.type() Returns the TypeCode associated with this DynAny object.
TypeCode | _DynFixedStub.get_typecode() Extracts the TypeCode object from this DynAny.
TypeCode | _DynEnumStub.type() Returns the TypeCode associated with this DynAny object.
TypeCode | _DynEnumStub.get_typecode() Extracts the TypeCode object from this DynAny.
TypeCode | _DynArrayStub.type() Returns the TypeCode associated with this DynAny object.
TypeCode | _DynArrayStub.get_typecode() Extracts the TypeCode object from this DynAny.
TypeCode | _DynValueStub.type() Returns the TypeCode associated with this DynAny object.
TypeCode | _DynValueStub.get_typecode() Extracts the TypeCode object from this DynAny.
TypeCode | _DynAnyStub.type() Returns the TypeCode associated with this DynAny object.
TypeCode | _DynAnyStub.get_typecode() Extracts the TypeCode object from this DynAny.
TypeCode | _DynUnionStub.type() Returns the TypeCode associated with this DynAny object.
TypeCode | _DynUnionStub.get_typecode() Extracts the TypeCode object from this DynAny.
TypeCode | _DynStructStub.type() Returns the TypeCode associated with this DynAny object.
TypeCode | _DynStructStub.get_typecode() Extracts the TypeCode object from this DynAny.
static TypeCode | NameValuePairSeqHelper.type()
static TypeCode | NameValuePairHelper.type()
static TypeCode | NameDynAnyPairSeqHelper.type()
static TypeCode | DynSequenceHelper.type()
static TypeCode | NameDynAnyPairHelper.type()
static TypeCode | FieldNameHelper.type()
static TypeCode | DynFixedHelper.type()
static TypeCode | DynEnumHelper.type()
static TypeCode | DynAnySeqHelper.type()
static TypeCode | DynArrayHelper.type()
static TypeCode | DynValueHelper.type()
static TypeCode | DynAnyHelper.type()
static TypeCode | DynUnionHelper.type()
static TypeCode | DynAnyFactoryHelper.type()
static TypeCode | DynStructHelper.type()
static TypeCode | AnySeqHelper.type()
TypeCode | DynAnyOperations.type() Returns the TypeCode associated with this DynAny object.
TypeCode | DynAnyOperations.get_typecode() Extracts the TypeCode object from this DynAny.

Methods in org.omg.DynamicAny with parameters of type TypeCode
void | _DynSequenceStub.insert_typecode(TypeCode value) Inserts a TypeCode object into the DynAny.
void | _DynFixedStub.insert_typecode(TypeCode value) Inserts a TypeCode object into the DynAny.
void | _DynEnumStub.insert_typecode(TypeCode value) Inserts a TypeCode object into the DynAny.
void | _DynArrayStub.insert_typecode(TypeCode value) Inserts a TypeCode object into the DynAny.
void | _DynValueStub.insert_typecode(TypeCode value) Inserts a TypeCode object into the DynAny.
void | _DynAnyStub.insert_typecode(TypeCode value) Inserts a TypeCode object into the DynAny.
void | _DynUnionStub.insert_typecode(TypeCode value) Inserts a TypeCode object into the DynAny.
DynAny | _DynAnyFactoryStub.create_dyn_any_from_type_code(TypeCode type) Creates a DynAny from a TypeCode.
void | _DynStructStub.insert_typecode(TypeCode value) Inserts a TypeCode object into the DynAny.
DynAny | DynAnyFactoryOperations.create_dyn_any_from_type_code(TypeCode type) Creates a DynAny from a TypeCode.
void | DynAnyOperations.insert_typecode(TypeCode value) Inserts a TypeCode object into the DynAny.

Uses of TypeCode in org.omg.DynamicAny.DynAnyFactoryPackage

Methods in org.omg.DynamicAny.DynAnyFactoryPackage that return TypeCode
static TypeCode InconsistentTypeCodeHelper.type()

Uses of TypeCode in org.omg.DynamicAny.DynAnyPackage

Methods in org.omg.DynamicAny.DynAnyPackage that return TypeCode
static TypeCode | TypeMismatchHelper.type()
static TypeCode | InvalidValueHelper.type()

Uses of TypeCode in org.omg.IOP

Methods in org.omg.IOP that return TypeCode
TypeCode | TaggedProfileHolder._type()
static TypeCode | TaggedProfileHelper.type()
TypeCode | TaggedComponentHolder._type()
static TypeCode | TaggedComponentHelper.type()
static TypeCode | ServiceIdHelper.type()
TypeCode | ServiceContextListHolder._type()
static TypeCode | ServiceContextListHelper.type()
TypeCode | ServiceContextHolder._type()
static TypeCode | ServiceContextHelper.type()
static TypeCode | ProfileIdHelper.type()
TypeCode | MultipleComponentProfileHolder._type()
static TypeCode | MultipleComponentProfileHelper.type()
TypeCode | IORHolder._type()
static TypeCode | IORHelper.type()
static TypeCode | ComponentIdHelper.type()
static TypeCode | CodecFactoryHelper.type()

Methods in org.omg.IOP with parameters of type TypeCode
 Any CodecOperations.decode_value(byte[] data, TypeCode tc)
Decodes the given byte array into an Any based on the given TypeCode and the encoding format effective for this Codec.

Uses of TypeCode in org.omg.IOP.CodecFactoryPackage

Methods in org.omg.IOP.CodecFactoryPackage that return TypeCode
static TypeCode UnknownEncodingHelper.type()

Uses of TypeCode in org.omg.IOP.CodecPackage

Methods in org.omg.IOP.CodecPackage that return TypeCode
static TypeCode | TypeMismatchHelper.type()
static TypeCode | InvalidTypeForEncodingHelper.type()
static TypeCode | FormatMismatchHelper.type()

Uses of TypeCode in org.omg.Messaging

Methods in org.omg.Messaging that return TypeCode
static TypeCode SyncScopeHelper.type()

Uses of TypeCode in org.omg.PortableInterceptor

Methods in org.omg.PortableInterceptor that return TypeCode
static TypeCode | InvalidSlotHelper.type()
static TypeCode | ForwardRequestHelper.type()
static TypeCode | CurrentHelper.type()
TypeCode[] | RequestInfoOperations.exceptions() Returns an array of TypeCode objects describing the TypeCodes of the user exceptions that this operation invocation may throw.

Uses of TypeCode in org.omg.PortableInterceptor.ORBInitInfoPackage

Methods in org.omg.PortableInterceptor.ORBInitInfoPackage that return TypeCode
static TypeCode | ObjectIdHelper.type()
static TypeCode | InvalidNameHelper.type()
static TypeCode | DuplicateNameHelper.type()

Uses of TypeCode in org.omg.PortableServer

Methods in org.omg.PortableServer that return TypeCode
static TypeCode | ServantLocatorHelper.type()
static TypeCode | ServantActivatorHelper.type()
static TypeCode | POAHelper.type()
static TypeCode | ForwardRequestHelper.type()
static TypeCode | CurrentHelper.type()

Uses of TypeCode in org.omg.PortableServer.CurrentPackage

Methods in org.omg.PortableServer.CurrentPackage that return TypeCode
static TypeCode NoContextHelper.type()

Uses of TypeCode in org.omg.PortableServer.POAManagerPackage

Methods in org.omg.PortableServer.POAManagerPackage that return TypeCode
static TypeCode AdapterInactiveHelper.type()

Uses of TypeCode in org.omg.PortableServer.POAPackage

Methods in org.omg.PortableServer.POAPackage that return TypeCode
static TypeCode | WrongPolicyHelper.type()
static TypeCode | WrongAdapterHelper.type()
static TypeCode | ServantNotActiveHelper.type()
static TypeCode | ServantAlreadyActiveHelper.type()
static TypeCode | ObjectNotActiveHelper.type()
static TypeCode | ObjectAlreadyActiveHelper.type()
static TypeCode | NoServantHelper.type()
static TypeCode | InvalidPolicyHelper.type()
static TypeCode | AdapterNonExistentHelper.type()
static TypeCode | AdapterAlreadyExistsHelper.type()

Uses of TypeCode in org.omg.PortableServer.ServantLocatorPackage

Methods in org.omg.PortableServer.ServantLocatorPackage that return TypeCode
 TypeCode CookieHolder._type()

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.TypeCodeHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.TypeCodeHolder

No usage of org.omg.CORBA.TypeCodeHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.ULongLongSeqHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.ULongLongSeqHelper

No usage of org.omg.CORBA.ULongLongSeqHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.ULongLongSeqHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.ULongLongSeqHolder

Packages that use ULongLongSeqHolder
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).

Uses of ULongLongSeqHolder in org.omg.CORBA

Methods in org.omg.CORBA with parameters of type ULongLongSeqHolder
 void DataInputStream.read_ulonglong_array(ULongLongSeqHolder seq, int offset, int length)
Reads array of IDL unsigned long longs from offset for length elements from the input stream.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.ULongSeqHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.ULongSeqHelper

No usage of org.omg.CORBA.ULongSeqHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.ULongSeqHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.ULongSeqHolder

Packages that use ULongSeqHolder
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).

Uses of ULongSeqHolder in org.omg.CORBA

Methods in org.omg.CORBA with parameters of type ULongSeqHolder
 void DataInputStream.read_ulong_array(ULongSeqHolder seq, int offset, int length)
Reads array of IDL unsigned longs from offset for length elements from the input stream.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.UnionMember (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.UnionMember

Packages that use UnionMember
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).

Uses of UnionMember in org.omg.CORBA

Methods in org.omg.CORBA that return UnionMember
static UnionMember | UnionMemberHelper.extract(Any a)
static UnionMember | UnionMemberHelper.read(InputStream istream)

Methods in org.omg.CORBA with parameters of type UnionMember
static void | UnionMemberHelper.insert(Any a, UnionMember that)
static void | UnionMemberHelper.write(OutputStream ostream, UnionMember value)
abstract TypeCode | ORB.create_union_tc(String id, String name, TypeCode discriminator_type, UnionMember[] members) Creates a TypeCode object representing an IDL union.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.UnionMemberHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.UnionMemberHelper

No usage of org.omg.CORBA.UnionMemberHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.UNKNOWN (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.UNKNOWN

No usage of org.omg.CORBA.UNKNOWN

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.UnknownUserException (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.UnknownUserException

Packages that use UnknownUserException
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).

Uses of UnknownUserException in org.omg.CORBA

Fields in org.omg.CORBA declared as UnknownUserException
 UnknownUserException UnknownUserExceptionHolder.value

Methods in org.omg.CORBA that return UnknownUserException
static UnknownUserException | UnknownUserExceptionHelper.extract(Any a)
static UnknownUserException | UnknownUserExceptionHelper.read(InputStream istream)

Methods in org.omg.CORBA with parameters of type UnknownUserException
static void | UnknownUserExceptionHelper.insert(Any a, UnknownUserException that)
static void | UnknownUserExceptionHelper.write(OutputStream ostream, UnknownUserException value)

Constructors in org.omg.CORBA with parameters of type UnknownUserException
UnknownUserExceptionHolder(UnknownUserException initialValue)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.UnknownUserExceptionHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.UnknownUserExceptionHelper

No usage of org.omg.CORBA.UnknownUserExceptionHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.UnknownUserExceptionHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.UnknownUserExceptionHolder

No usage of org.omg.CORBA.UnknownUserExceptionHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.UNSUPPORTED_POLICY (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.UNSUPPORTED_POLICY

No usage of org.omg.CORBA.UNSUPPORTED_POLICY

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.UNSUPPORTED_POLICY_VALUE (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.UNSUPPORTED_POLICY_VALUE

No usage of org.omg.CORBA.UNSUPPORTED_POLICY_VALUE

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.UserException (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.UserException

Packages that use UserException
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 | Provides the exceptions used with the DynAny interface (InvalidValue, Invalid, InvalidSeq, and TypeMismatch).
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.TypeCodePackage | Provides the user-defined exceptions BadKind and Bounds, which are thrown by methods in in the class TypeCode.
org.omg.CosNaming.NamingContextExtPackage | This package contains the following classes, which are used in org.omg.CosNaming.NamingContextExt:
org.omg.CosNaming.NamingContextPackage | This package contains Exception classes for the org.omg.CosNaming 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 | This package is generated from the IOP::Codec IDL interface definition.
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 | 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 | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.
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 | Encapsulates the processing state of the POAs it is associated with.
org.omg.PortableServer.POAPackage | Allows programmers to construct object implementations that are portable between different ORB products.

Uses of UserException in org.omg.CORBA

Subclasses of UserException in org.omg.CORBA
class | Bounds A user exception thrown when a parameter is not within the legal bounds for the object that a method is trying to access.
class | PolicyError A user exception thrown when a policy error occurs.
class | UnknownUserException A class that contains user exceptions returned by the server.
class | WrongTransaction The CORBA WrongTransaction user-defined exception.

Uses of UserException in org.omg.CORBA.DynAnyPackage

Subclasses of UserException in org.omg.CORBA.DynAnyPackage
class | Invalid Invalid is thrown by dynamic any operations when a bad DynAny or Any is passed as a parameter.
class | InvalidSeq The InvalidSeq exception is thrown by all operations on dynamic anys that take a sequence (Java array) as an argument, when that sequence is invalid.
class | InvalidValue
class | TypeMismatch TypeMismatch is thrown by dynamic any accessor methods when type of the actual contents do not match what is trying to be accessed.

Uses of UserException in org.omg.CORBA.ORBPackage

Subclasses of UserException in org.omg.CORBA.ORBPackage
class | InconsistentTypeCode InconsistentTypeCode is thrown when an attempt is made to create a dynamic any with a type code that does not match the particular subclass of DynAny.
class | InvalidName The InvalidName exception is raised when ORB.resolve_initial_references is passed a name for which there is no initial reference.

Uses of UserException in org.omg.CORBA.TypeCodePackage

Subclasses of UserException in org.omg.CORBA.TypeCodePackage
 class BadKind
The exception BadKind is thrown when an inappropriate operation is invoked on a TypeCode object.

Uses of UserException in org.omg.CosNaming.NamingContextExtPackage

Subclasses of UserException in org.omg.CosNaming.NamingContextExtPackage
 class InvalidAddress
org/omg/CosNaming/NamingContextExtPackage/InvalidAddress.java .

Uses of UserException in org.omg.CosNaming.NamingContextPackage

Subclasses of UserException in org.omg.CosNaming.NamingContextPackage
class | AlreadyBound org/omg/CosNaming/NamingContextPackage/AlreadyBound.java .
class | CannotProceed org/omg/CosNaming/NamingContextPackage/CannotProceed.java .
class | NotEmpty org/omg/CosNaming/NamingContextPackage/NotEmpty.java .
class | NotFound org/omg/CosNaming/NamingContextPackage/NotFound.java .

Uses of UserException in org.omg.IOP.CodecFactoryPackage

Subclasses of UserException in org.omg.IOP.CodecFactoryPackage
 class UnknownEncoding
org/omg/IOP/CodecFactoryPackage/UnknownEncoding.java .

Uses of UserException in org.omg.IOP.CodecPackage

Subclasses of UserException in org.omg.IOP.CodecPackage
class | FormatMismatch org/omg/IOP/CodecPackage/FormatMismatch.java .
class | InvalidTypeForEncoding org/omg/IOP/CodecPackage/InvalidTypeForEncoding.java .

Uses of UserException in org.omg.PortableInterceptor

Subclasses of UserException in org.omg.PortableInterceptor
 class InvalidSlot
org/omg/PortableInterceptor/InvalidSlot.java .

Uses of UserException in org.omg.PortableInterceptor.ORBInitInfoPackage

Subclasses of UserException in org.omg.PortableInterceptor.ORBInitInfoPackage
 class DuplicateName
org/omg/PortableInterceptor/ORBInitInfoPackage/DuplicateName.java .

Uses of UserException in org.omg.PortableServer

Subclasses of UserException in org.omg.PortableServer
 class ForwardRequest
org/omg/PortableServer/ForwardRequest.java .

Uses of UserException in org.omg.PortableServer.CurrentPackage

Subclasses of UserException in org.omg.PortableServer.CurrentPackage
 class NoContext
org/omg/PortableServer/CurrentPackage/NoContext.java .

Uses of UserException in org.omg.PortableServer.POAManagerPackage

Subclasses of UserException in org.omg.PortableServer.POAManagerPackage
 class AdapterInactive
org/omg/PortableServer/POAManagerPackage/AdapterInactive.java .

Uses of UserException in org.omg.PortableServer.POAPackage

Subclasses of UserException in org.omg.PortableServer.POAPackage
class | AdapterAlreadyExists org/omg/PortableServer/POAPackage/AdapterAlreadyExists.java .
class | AdapterNonExistent org/omg/PortableServer/POAPackage/AdapterNonExistent.java .
class | InvalidPolicy org/omg/PortableServer/POAPackage/InvalidPolicy.java .
class | NoServant org/omg/PortableServer/POAPackage/NoServant.java .
class | ObjectAlreadyActive org/omg/PortableServer/POAPackage/ObjectAlreadyActive.java .
class | ObjectNotActive org/omg/PortableServer/POAPackage/ObjectNotActive.java .
class | ServantAlreadyActive org/omg/PortableServer/POAPackage/ServantAlreadyActive.java .
class | ServantNotActive org/omg/PortableServer/POAPackage/ServantNotActive.java .
class | WrongAdapter org/omg/PortableServer/POAPackage/WrongAdapter.java .
class | WrongPolicy org/omg/PortableServer/POAPackage/WrongPolicy.java .

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.UShortSeqHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.UShortSeqHelper

No usage of org.omg.CORBA.UShortSeqHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.UShortSeqHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.UShortSeqHolder

Packages that use UShortSeqHolder
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).

Uses of UShortSeqHolder in org.omg.CORBA

Methods in org.omg.CORBA with parameters of type UShortSeqHolder
 void DataInputStream.read_ushort_array(UShortSeqHolder seq, int offset, int length)
Reads array of IDL unsigned shorts from offset for length elements from the input stream.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.ValueBaseHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.ValueBaseHelper

No usage of org.omg.CORBA.ValueBaseHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.ValueBaseHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.ValueBaseHolder

No usage of org.omg.CORBA.ValueBaseHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.ValueMember (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.ValueMember

Packages that use ValueMember
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).

Uses of ValueMember in org.omg.CORBA

Methods in org.omg.CORBA that return ValueMember
static ValueMember | ValueMemberHelper.extract(Any a)
static ValueMember | ValueMemberHelper.read(InputStream istream)

Methods in org.omg.CORBA with parameters of type ValueMember
static void | ValueMemberHelper.insert(Any a, ValueMember that)
static void | ValueMemberHelper.write(OutputStream ostream, ValueMember value)
TypeCode | ORB.create_value_tc(String id, String name, short type_modifier, TypeCode concrete_base, ValueMember[] members) Create a TypeCode object for an IDL value type.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.ValueMemberHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.ValueMemberHelper

No usage of org.omg.CORBA.ValueMemberHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.VersionSpecHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.VersionSpecHelper

No usage of org.omg.CORBA.VersionSpecHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.VisibilityHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.VisibilityHelper

No usage of org.omg.CORBA.VisibilityHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.VM_ABSTRACT (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.VM_ABSTRACT

No usage of org.omg.CORBA.VM_ABSTRACT

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.VM_CUSTOM (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.VM_CUSTOM

No usage of org.omg.CORBA.VM_CUSTOM

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.VM_NONE (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.VM_NONE

No usage of org.omg.CORBA.VM_NONE

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.VM_TRUNCATABLE (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.VM_TRUNCATABLE

No usage of org.omg.CORBA.VM_TRUNCATABLE

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.WCharSeqHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.WCharSeqHelper

No usage of org.omg.CORBA.WCharSeqHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.WCharSeqHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.WCharSeqHolder

Packages that use WCharSeqHolder
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).

Uses of WCharSeqHolder in org.omg.CORBA

Methods in org.omg.CORBA with parameters of type WCharSeqHolder
 void DataInputStream.read_wchar_array(WCharSeqHolder seq, int offset, int length)
Reads array of IDL wide characters from offset for length elements from the input stream.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.WrongTransaction (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.WrongTransaction

Packages that use WrongTransaction
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).

Uses of WrongTransaction in org.omg.CORBA

Fields in org.omg.CORBA declared as WrongTransaction
 WrongTransaction WrongTransactionHolder.value

Methods in org.omg.CORBA that return WrongTransaction
static WrongTransaction | WrongTransactionHelper.extract(Any a)
static WrongTransaction | WrongTransactionHelper.read(InputStream istream)

Methods in org.omg.CORBA with parameters of type WrongTransaction
static void | WrongTransactionHelper.insert(Any a, WrongTransaction that)
static void | WrongTransactionHelper.write(OutputStream ostream, WrongTransaction value)

Methods in org.omg.CORBA that throw WrongTransaction
abstract void | Request.get_response() Allows the user to access the response for the invocation triggered earlier with the send_deferred method.
abstract Request | ORB.get_next_response() Gets the next Request instance for which a response has been received.

Constructors in org.omg.CORBA with parameters of type WrongTransaction
WrongTransactionHolder(WrongTransaction initialValue)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.WrongTransactionHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.WrongTransactionHelper

No usage of org.omg.CORBA.WrongTransactionHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.WrongTransactionHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.WrongTransactionHolder

No usage of org.omg.CORBA.WrongTransactionHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.WStringSeqHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.WStringSeqHelper

No usage of org.omg.CORBA.WStringSeqHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.WStringSeqHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.WStringSeqHolder

No usage of org.omg.CORBA.WStringSeqHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.WStringValueHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.WStringValueHelper

No usage of org.omg.CORBA.WStringValueHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Official Specifications for CORBA support in J2SE 1.4

Specification References

The specifications with which the Java 2 Platform, Standard Edition (J2SE) v.1.4 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-03-04)
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 1.4. 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 1.4 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.


IDL-to-Java Generated Files

The files that are generated by the IDL-to-Java compiler, in accordance with the IDL-to-Java Language Mapping Specification, which is implemented in J2SE 1.4 according the compliance document.

In general IDL names and identifiers are mapped to Java names and identifiers with no change. Because of the nature of the Java language, a single IDL construct may be mapped to several (differently named) Java constructs. The additional names are constructed by appending a descriptive suffix. For example, the IDL interface foo is mapped to the Java interfaces foo and fooOperations, and additional Java classes fooHelper, fooHolder, fooPOA, and optionally fooPOATie.

The mapping in effect reserves the use of several names for its own purposes. These are:

  • The Java class <type>Helper, where <type> is the name of an IDL defined type.
  • The Java class <type>Holder, where <type> is the name of an IDL defined type (with certain exceptions such as typedef aliases).
  • The Java classes <basicJavaType>Holder, where <basicJavaType> is one of the Java primitive datatypes that is used by one of the IDL basic datatypes.
  • The Java classes <interface>Operations, <interface>POA, and <interface>POATie, where <interface> is the name of an IDL interface type.
  • The nested scope Java package name <interface>Package, where <interface> is the name of an IDL interface.

    Helper Files

    Helper files supply several static methods needed to manipulate the type. These include Any insert and extract operations for the type, getting the repository id, getting the typecode, and reading and writing the type from and to a stream.

    The helper class for a mapped IDL interface or abstract interface also include narrow operation(s). The static narrow method allows an org.omg.CORBA.Object to be narrowed to the object reference of a more specific type. The IDL exception CORBA::BAD_PARAM is thrown if the narrow fails because the object reference does not support the requested type. A different system exception is raised to indicate other kinds of errors. Trying to narrow a null will always succeed with a return value of null.

    Holder Files

    Support for out and inout parameter passing modes requires the use of additional holder classes. These classes are available for all of the basic IDL datatypes in the org.omg.CORBA package and are generated for all named user defined IDL types except those defined by typedefs. (Note that in this context user defined includes types that are defined in OMG specifications such as those for the Interface Repository, and other OMG services.)

    Each holder class has a constructor from an instance, a default constructor, and has a public instance member, value which is the typed value. The default constructor sets the value field to the default value for the type as defined by the Java language: false for boolean, 0 for numeric and char types, null for strings, null for object references.

    To support portable stubs and skeletons, holder classes also implement the org.omg.CORBA.portable.Streamable interface.

    Operations Files

    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. 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 client and servers.

    The Java operations interface contains the mapped operation signatures. The Java signature interface extends the operations interface, the (mapped) base org.omg.CORBA.Object, as well as org.omg.portable.IDLEntity. Methods can be invoked on the signature interface. Interface inheritance expressed in IDL is reflected in both the Java signature interface and operations interface hierarchies.

    Stubs

    For the mapping of a non-object-oriented language, there will be a programming interface to the stubs for each interface type. Generally, the stubs will present access to the OMG IDL-defined operations on an object in a way that is easy for programmers to predict once they are familiar with OMG IDL and the language mapping for the particular programming language. The stubs make calls on the rest of the ORB using interfaces that are private to, and presumably optimized for, the particular ORB Core. If more than one ORB is available, there may be different stubs corresponding to the different ORBs. In this case, it is necessary for the ORB and language mapping to cooperate to associate the correct stubs with the particular object reference.

    Object-oriented programming languages, such as Java, C++, and Smalltalk, do not require stub interfaces.


Invalid (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA.DynAnyPackage
Class Invalid

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.CORBA.DynAnyPackage.Invalid
All Implemented Interfaces:
IDLEntity, Serializable
public final class Invalid
extends UserException

Invalid is thrown by dynamic any operations when a bad DynAny or Any is passed as a parameter.

Constructor Summary
Invalid()
Constructs an Invalid object.
Invalid(String reason)
Constructs an Invalid object.
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

Invalid

public Invalid()
Constructs an Invalid object.

Invalid

public Invalid(String reason)
Constructs an Invalid object.

Parameters:
reason - a String giving more information regarding the bad parameter passed to a dynamic any operation.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


InvalidSeq (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA.DynAnyPackage
Class InvalidSeq

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.CORBA.DynAnyPackage.InvalidSeq
All Implemented Interfaces:
IDLEntity, Serializable
public final class InvalidSeq
extends UserException

The InvalidSeq exception is thrown by all operations on dynamic anys that take a sequence (Java array) as an argument, when that sequence is invalid.

Constructor Summary
InvalidSeq()
Constructs an InvalidSeq object.
InvalidSeq(String reason)
Constructs an InvalidSeq object.
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

InvalidSeq

public InvalidSeq()
Constructs an InvalidSeq object.

InvalidSeq

public InvalidSeq(String reason)
Constructs an InvalidSeq object.

Parameters:
reason - a String giving more information regarding the exception.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


InvalidValue (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA.DynAnyPackage
Class InvalidValue

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.CORBA.DynAnyPackage.InvalidValue
All Implemented Interfaces:
IDLEntity, Serializable
public final class InvalidValue
extends UserException

Constructor Summary
InvalidValue()
Constructs an InvalidValue object.
InvalidValue(String reason)
Constructs an InvalidValue object.
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

InvalidValue

public InvalidValue()
Constructs an InvalidValue object.

InvalidValue

public InvalidValue(String reason)
Constructs an InvalidValue object.

Parameters:
reason - a String giving more information regarding the exception.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


org.omg.CORBA.DynAnyPackage (Java 2 Platform SE v1.4.2)

 org.omg.CORBA.DynAnyPackage
Exceptions
Invalid
InvalidSeq
InvalidValue
TypeMismatch


org.omg.CORBA.DynAnyPackage (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package org.omg.CORBA.DynAnyPackage

Provides the exceptions used with the DynAny interface (InvalidValue, Invalid, InvalidSeq, and TypeMismatch).

See:
Description

Exception Summary
Invalid | Invalid is thrown by dynamic any operations when a bad DynAny or Any is passed as a parameter.
InvalidSeq | The InvalidSeq exception is thrown by all operations on dynamic anys that take a sequence (Java array) as an argument, when that sequence is invalid.
InvalidValue |
TypeMismatch | TypeMismatch is thrown by dynamic any accessor methods when type of the actual contents do not match what is trying to be accessed.

Package org.omg.CORBA.DynAnyPackage Description

Provides the exceptions used with the DynAny interface (InvalidValue, Invalid, InvalidSeq, and TypeMismatch).

Since:
JDK1.2
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


org.omg.CORBA.DynAnyPackage Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package org.omg.CORBA.DynAnyPackage

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class java.lang.Throwable (implements java.io.Serializable)
      • class java.lang.Exception
        • class org.omg.CORBA.UserException (implements org.omg.CORBA.portable.IDLEntity)
          • class org.omg.CORBA.DynAnyPackage.Invalid
          • class org.omg.CORBA.DynAnyPackage.InvalidSeq
          • class org.omg.CORBA.DynAnyPackage.InvalidValue
          • class org.omg.CORBA.DynAnyPackage.TypeMismatch
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package org.omg.CORBA.DynAnyPackage (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
org.omg.CORBA.DynAnyPackage

Packages that use org.omg.CORBA.DynAnyPackage
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).

Classes in org.omg.CORBA.DynAnyPackage used by org.omg.CORBA
Invalid
Invalid is thrown by dynamic any operations when a bad DynAny or Any is passed as a parameter.
InvalidSeq
The InvalidSeq exception is thrown by all operations on dynamic anys that take a sequence (Java array) as an argument, when that sequence is invalid.
InvalidValue
TypeMismatch
TypeMismatch is thrown by dynamic any accessor methods when type of the actual contents do not match what is trying to be accessed.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


TypeMismatch (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA.DynAnyPackage
Class TypeMismatch

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.CORBA.DynAnyPackage.TypeMismatch
All Implemented Interfaces:
IDLEntity, Serializable
public final class TypeMismatch
extends UserException

TypeMismatch is thrown by dynamic any accessor methods when type of the actual contents do not match what is trying to be accessed.

Constructor Summary
TypeMismatch()
Constructs a TypeMismatch object.
TypeMismatch(String reason)
Constructs a TypeMismatch object.
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

TypeMismatch

public TypeMismatch()
Constructs a TypeMismatch object.

TypeMismatch

public TypeMismatch(String reason)
Constructs a TypeMismatch object.

Parameters:
reason - a String giving more information regarding the exception.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Uses of Class org.omg.CORBA.DynAnyPackage.Invalid (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.DynAnyPackage.Invalid

Packages that use Invalid
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).

Uses of Invalid in org.omg.CORBA

Methods in org.omg.CORBA that throw Invalid
void | DynAny.assign(DynAny dyn_any) Copy the contents from one Dynamic Any into another.
void | DynAny.from_any(Any value) Make a DynAny object from an Any object.
Any | DynAny.to_any() Convert a DynAny object to an Any object.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.DynAnyPackage.InvalidSeq (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.DynAnyPackage.InvalidSeq

Packages that use InvalidSeq
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).

Uses of InvalidSeq in org.omg.CORBA

Methods in org.omg.CORBA that throw InvalidSeq
void | DynValue.set_members(NameValuePair[] value) Sets the members of the value object this DynValue object represents to the given array of NameValuePair objects.
void | DynArray.set_elements(Any[] value) Sets the value of this DynArray object to the given array.
void | DynSequence.set_elements(Any[] value) Sets the values of all elements in this sequence with the given array.
void | DynStruct.set_members(NameValuePair[] value) Set the members of the struct.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.DynAnyPackage.InvalidValue (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.DynAnyPackage.InvalidValue

Packages that use InvalidValue
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).

Uses of InvalidValue in org.omg.CORBA

Methods in org.omg.CORBA that throw InvalidValue
void | DynFixed.set_value(byte[] val) Sets the given fixed type instance as the value for this DynFixed object.
void | DynAny.insert_boolean(boolean value) Inserts the given boolean as the value for this DynAny object.
void | DynAny.insert_octet(byte value) Inserts the given byte as the value for this DynAny object.
void | DynAny.insert_char(char value) Inserts the given char as the value for this DynAny object.
void | DynAny.insert_short(short value) Inserts the given short as the value for this DynAny object.
void | DynAny.insert_ushort(short value) Inserts the given short as the value for this DynAny object.
void | DynAny.insert_long(int value) Inserts the given int as the value for this DynAny object.
void | DynAny.insert_ulong(int value) Inserts the given int as the value for this DynAny object.
void | DynAny.insert_float(float value) Inserts the given float as the value for this DynAny object.
void | DynAny.insert_double(double value) Inserts the given double as the value for this DynAny object.
void | DynAny.insert_string(String value) Inserts the given String object as the value for this DynAny object.
void | DynAny.insert_reference(Object value) Inserts the given org.omg.CORBA.Object as the value for this DynAny object.
void | DynAny.insert_typecode(TypeCode value) Inserts the given org.omg.CORBA.TypeCode as the value for this DynAny object.
void | DynAny.insert_longlong(long value) Inserts the given long as the value for this DynAny object.
void | DynAny.insert_ulonglong(long value) Inserts the given long as the value for this DynAny object.
void | DynAny.insert_wchar(char value) Inserts the given char as the value for this DynAny object.
void | DynAny.insert_wstring(String value) Inserts the given String as the value for this DynAny object.
void | DynAny.insert_any(Any value) Inserts the given org.omg.CORBA.Any object as the value for this DynAny object.
void | DynAny.insert_val(Serializable value) Inserts the given java.io.Serializable object as the value for this DynAny object.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.DynAnyPackage.TypeMismatch (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.DynAnyPackage.TypeMismatch

Packages that use TypeMismatch
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).

Uses of TypeMismatch in org.omg.CORBA

Methods in org.omg.CORBA that throw TypeMismatch
Serializable | DynAny.get_val() Retrieves the java.io.Serializable object contained in this DynAny object.
boolean | DynAny.get_boolean() Retrieves the boolean contained in this DynAny object.
byte | DynAny.get_octet() Retrieves the byte contained in this DynAny object.
char | DynAny.get_char() Retrieves the char contained in this DynAny object.
short | DynAny.get_short() Retrieves the short contained in this DynAny object.
short | DynAny.get_ushort() Retrieves the short contained in this DynAny object.
int | DynAny.get_long() Retrieves the int contained in this DynAny object.
int | DynAny.get_ulong() Retrieves the int contained in this DynAny object.
float | DynAny.get_float() Retrieves the float contained in this DynAny object.
double | DynAny.get_double() Retrieves the double contained in this DynAny object.
String | DynAny.get_string() Retrieves the String contained in this DynAny object.
Object | DynAny.get_reference() Retrieves the org.omg.CORBA.Other contained in this DynAny object.
TypeCode | DynAny.get_typecode() Retrieves the org.omg.CORBA.TypeCode contained in this DynAny object.
long | DynAny.get_longlong() Retrieves the long contained in this DynAny object.
long | DynAny.get_ulonglong() Retrieves the long contained in this DynAny object.
char | DynAny.get_wchar() Retrieves the char contained in this DynAny object.
String | DynAny.get_wstring() Retrieves the String contained in this DynAny object.
Any | DynAny.get_any() Retrieves the org.omg.CORBA.Any contained in this DynAny object.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


InconsistentTypeCode (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA.ORBPackage
Class InconsistentTypeCode

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.CORBA.ORBPackage.InconsistentTypeCode
All Implemented Interfaces:
IDLEntity, Serializable
public final class InconsistentTypeCode
extends UserException

InconsistentTypeCode is thrown when an attempt is made to create a dynamic any with a type code that does not match the particular subclass of DynAny.

Constructor Summary
InconsistentTypeCode()
Constructs an InconsistentTypeCode user exception with no reason message.
InconsistentTypeCode(String reason)
Constructs an InconsistentTypeCode user exception with the specified reason message.
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

InconsistentTypeCode

public InconsistentTypeCode()
Constructs an InconsistentTypeCode user exception with no reason message.

InconsistentTypeCode

public InconsistentTypeCode(String reason)
Constructs an InconsistentTypeCode user exception with the specified reason message.

Parameters:
reason - The String containing a reason message
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


InvalidName (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA.ORBPackage
Class InvalidName

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.CORBA.ORBPackage.InvalidName
All Implemented Interfaces:
IDLEntity, Serializable
public final class InvalidName
extends UserException

The InvalidName exception is raised when ORB.resolve_initial_references is passed a name for which there is no initial reference.

Since:
JDK1.2
See Also:
ORB.resolve_initial_references(String)

Constructor Summary
InvalidName()
Constructs an InvalidName exception with no reason message.
InvalidName(String reason)
Constructs an InvalidName exception with the specified reason message.
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

InvalidName

public InvalidName()
Constructs an InvalidName exception with no reason message.

InvalidName

public InvalidName(String reason)
Constructs an InvalidName exception with the specified reason message.

Parameters:
reason - the String containing a reason message
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


org.omg.CORBA.ORBPackage (Java 2 Platform SE v1.4.2)

 org.omg.CORBA.ORBPackage
Exceptions
InconsistentTypeCode
InvalidName


org.omg.CORBA.ORBPackage (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

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.

See:
Description

Exception Summary
InconsistentTypeCode | InconsistentTypeCode is thrown when an attempt is made to create a dynamic any with a type code that does not match the particular subclass of DynAny.
InvalidName | The InvalidName exception is raised when ORB.resolve_initial_references is passed a name for which there is no initial reference.

Package org.omg.CORBA.ORBPackage Description

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.

Related Documentation

For an overview, please see:
  • comments on the CORBA package

Since:
JDK1.2
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


org.omg.CORBA.ORBPackage Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package org.omg.CORBA.ORBPackage

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class java.lang.Throwable (implements java.io.Serializable)
      • class java.lang.Exception
        • class org.omg.CORBA.UserException (implements org.omg.CORBA.portable.IDLEntity)
          • class org.omg.CORBA.ORBPackage.InconsistentTypeCode
          • class org.omg.CORBA.ORBPackage.InvalidName
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package org.omg.CORBA.ORBPackage (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
org.omg.CORBA.ORBPackage

Packages that use org.omg.CORBA.ORBPackage
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).

Classes in org.omg.CORBA.ORBPackage used by org.omg.CORBA
InconsistentTypeCode
InconsistentTypeCode is thrown when an attempt is made to create a dynamic any with a type code that does not match the particular subclass of DynAny.
InvalidName
The InvalidName exception is raised when ORB.resolve_initial_references is passed a name for which there is no initial reference.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.ORBPackage.InconsistentTypeCode (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.ORBPackage.InconsistentTypeCode

Packages that use InconsistentTypeCode
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).

Uses of InconsistentTypeCode in org.omg.CORBA

Methods in org.omg.CORBA that throw InconsistentTypeCode
DynAny | ORB.create_basic_dyn_any(TypeCode type) Creates a basic DynAny object from the given TypeCode object.
DynStruct | ORB.create_dyn_struct(TypeCode type) Creates a new DynStruct object from the given TypeCode object.
DynSequence | ORB.create_dyn_sequence(TypeCode type) Creates a new DynSequence object from the given TypeCode object.
DynArray | ORB.create_dyn_array(TypeCode type) Creates a new DynArray object from the given TypeCode object.
DynUnion | ORB.create_dyn_union(TypeCode type) Creates a new DynUnion object from the given TypeCode object.
DynEnum | ORB.create_dyn_enum(TypeCode type) Creates a new DynEnum object from the given TypeCode object.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.ORBPackage.InvalidName (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.ORBPackage.InvalidName

Packages that use InvalidName
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).

Uses of InvalidName in org.omg.CORBA

Methods in org.omg.CORBA that throw InvalidName
abstract  Object ORB.resolve_initial_references(String object_name)
Resolves a specific object reference from the set of available initial service names.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


ApplicationException (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA.portable
Class ApplicationException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.portable.ApplicationException
All Implemented Interfaces:
Serializable
public class ApplicationException
extends Exception

This class is used for reporting application level exceptions between ORBs and stubs.

Constructor Summary
ApplicationException(String id, InputStream ins)
Constructs an ApplicationException from the CORBA repository ID of the exception and an input stream from which the exception data can be read as its parameters.
Method Summary
String | getId() Returns the CORBA repository ID of the exception without removing it from the exceptions input stream.
InputStream | getInputStream() Returns the input stream from which the exception data can be read as its parameters.
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

ApplicationException

public ApplicationException(String id,
                            InputStream ins)
Constructs an ApplicationException from the CORBA repository ID of the exception and an input stream from which the exception data can be read as its parameters.

Parameters:
id - the repository id of the user exception
ins - the stream which contains the user exception data
Method Detail

getId

public String getId()
Returns the CORBA repository ID of the exception without removing it from the exceptions input stream.

Returns:
The CORBA repository ID of this exception

getInputStream

public InputStream getInputStream()
Returns the input stream from which the exception data can be read as its parameters.

Returns:
The stream which contains the user exception data
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


BoxedValueHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA.portable
Interface BoxedValueHelper

All Known Implementing Classes:
StringValueHelper, WStringValueHelper
public interface BoxedValueHelper

Method Summary
String | get_id()
Serializable | read_value(InputStream is)
void | write_value(OutputStream os, Serializable value)

Method Detail

read_value

public Serializable read_value(InputStream is)

write_value

public void write_value(OutputStream os,
                        Serializable value)

get_id

public String get_id()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


CustomValue (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA.portable
Interface CustomValue

All Superinterfaces:
CustomMarshal, IDLEntity, Serializable, ValueBase
public interface CustomValue
extends ValueBase, CustomMarshal

An extension of ValueBase that is implemented by custom value types.

Methods inherited from interface org.omg.CORBA.portable.ValueBase
_truncatable_ids
Methods inherited from interface org.omg.CORBA.CustomMarshal
marshal, unmarshal

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Delegate (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA.portable
Class Delegate

java.lang.Object
    extended by org.omg.CORBA.portable.Delegate
Direct Known Subclasses:
Delegate
public abstract class Delegate
extends Object

Specifies a portable API for ORB-vendor-specific implementation of the org.omg.CORBA.Object methods. Each stub (proxy) contains a delegate object, to which all org.omg.CORBA.Object methods are forwarded. This allows a stub generated by one vendor's ORB to work with the delegate from another vendor's ORB.

See Also:
Object

Constructor Summary
Delegate()
Method Summary
abstract  Request create_request(Object obj, Context ctx, String operation, NVList arg_list, NamedValue result)
Creates a Request instance for use in the Dynamic Invocation Interface.
abstract  Request create_request(Object obj, Context ctx, String operation, NVList arg_list, NamedValue result, ExceptionList exclist, ContextList ctxlist)
Creates a Request instance for use in the Dynamic Invocation Interface.
abstract  Object duplicate(Object obj)
Returns a duplicate of the object reference provided.
 boolean equals(Object self, Object obj)
Provides the implementation to override the equals(java.lang.Object obj) method of the delegating CORBA object.
 DomainManager[] get_domain_managers(Object self)
Retrieves the DomainManagers of this object.
abstract  Object get_interface_def(Object self)
Return an InterfaceDef for the object reference provided.
 Policy get_policy(Object self, int policy_type)
Returns the Policy object of the specified type which applies to this object.
abstract  int hash(Object obj, int max)
Returns an ORB-internal identifier (hashcode) for this object reference.
 int hashCode(Object self)
Provides the implementation to override the hashCode() method of the delegating CORBA object.
 InputStream invoke(Object self, OutputStream output)
invoke is called by a stub to invoke an operation.
abstract  boolean is_a(Object obj, String repository_id)
Checks if the object reference is an instance of the given interface.
abstract  boolean is_equivalent(Object obj, Object other)
Determines if the two object references are equivalent.
 boolean is_local(Object self)
Returns true if this object is implemented by a local servant.
abstract  boolean non_existent(Object obj)
Determines whether the server object for the object reference has been destroyed.
 ORB orb(Object obj)
Provides a reference to the orb associated with its parameter.
abstract  void release(Object obj)
Releases resources associated with the object reference provided.
 void releaseReply(Object self, InputStream input)
releaseReply may optionally be called by a stub to release a reply stream back to the ORB when the unmarshaling has completed.
abstract  Request request(Object obj, String operation)
Creates a Request instance for use in the Dynamic Invocation Interface.
 OutputStream request(Object self, String operation, boolean responseExpected)
request is called by a stub to obtain an OutputStream for marshaling arguments.
 void servant_postinvoke(Object self, ServantObject servant)
servant_postinvoke() is invoked by the local stub after the operation has been invoked on the local servant.
 ServantObject servant_preinvoke(Object self, String operation, Class expectedType)
Returns a Java reference to the servant which should be used for this request.
 Object set_policy_override(Object self, Policy[] policies, SetOverrideType set_add)
Associates the policies passed in with a newly created object reference that it returns.
 String toString(Object self)
Provides the implementation to override the toString() method of the delegating CORBA object.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

Delegate

public Delegate()
Method Detail

get_interface_def

public abstract Object get_interface_def(Object self)
Return an InterfaceDef for the object reference provided.

Parameters:
self - The object reference whose InterfaceDef needs to be returned
Returns:
the InterfaceDef

duplicate

public abstract Object duplicate(Object obj)
Returns a duplicate of the object reference provided.

Parameters:
obj - The object reference whose duplicate needs to be returned
Returns:
the duplicate object reference

release

public abstract void release(Object obj)
Releases resources associated with the object reference provided.

Parameters:
obj - The object reference whose resources need to be released

is_a

public abstract boolean is_a(Object obj,
                             String repository_id)
Checks if the object reference is an instance of the given interface.

Parameters:
obj - The object reference to be checked.
repository_id - The repository identifier of the interface to check against.
Returns:
true if the object reference supports the interface

non_existent

public abstract boolean non_existent(Object obj)
Determines whether the server object for the object reference has been destroyed.

Parameters:
obj - The object reference which delegated to this delegate.
Returns:
true if the ORB knows authoritatively that the server object does not exist, false otherwise

is_equivalent

public abstract boolean is_equivalent(Object obj,
                                      Object other)
Determines if the two object references are equivalent.

Parameters:
obj - The object reference which delegated to this delegate.
other - The object reference to check equivalence against.
Returns:
true if the objects are CORBA-equivalent.

hash

public abstract int hash(Object obj,
                         int max)
Returns an ORB-internal identifier (hashcode) for this object reference.

Parameters:
obj - The object reference which delegated to this delegate.
max - specifies an upper bound on the hash value returned by the ORB.
Returns:
ORB-internal hash identifier for object reference

request

public abstract Request request(Object obj,
                                String operation)
Creates a Request instance for use in the Dynamic Invocation Interface.

Parameters:
obj - The object reference which delegated to this delegate.
operation - The name of the operation to be invoked using the Request instance.
Returns:
the created Request instance

create_request

public abstract Request create_request(Object obj,
                                       Context ctx,
                                       String operation,
                                       NVList arg_list,
                                       NamedValue result)
Creates a Request instance for use in the Dynamic Invocation Interface.

Parameters:
obj - The object reference which delegated to this delegate.
ctx - The context to be used.
operation - The name of the operation to be invoked.
arg_list - The arguments to the operation in the form of an NVList.
result - A container for the result as a NamedValue.
Returns:
The created Request object.

create_request

public abstract Request create_request(Object obj,
                                       Context ctx,
                                       String operation,
                                       NVList arg_list,
                                       NamedValue result,
                                       ExceptionList exclist,
                                       ContextList ctxlist)
Creates a Request instance for use in the Dynamic Invocation Interface.

Parameters:
obj - The object reference which delegated to this delegate.
ctx - The context to be used.
operation - The name of the operation to be invoked.
arg_list - The arguments to the operation in the form of an NVList.
result - A container for the result as a NamedValue.
exclist - A list of possible exceptions the operation can throw.
ctxlist - A list of context strings that need to be resolved and sent with the Request.
Returns:
The created Request object.

orb

public ORB orb(Object obj)
Provides a reference to the orb associated with its parameter.

Parameters:
obj - the object reference which delegated to this delegate.
Returns:
the associated orb.
See Also:
portable package comments for unimplemented features

get_policy

public Policy get_policy(Object self,
                         int policy_type)
Returns the Policy object of the specified type which applies to this object.

Parameters:
self - The object reference which delegated to this delegate.
policy_type - The type of policy to be obtained.
Returns:
A Policy object of the type specified by the policy_type parameter.
Throws:
BAD_PARAM - raised when the value of policy type is not valid either because the specified type is not supported by this ORB or because a policy object of that type is not associated with this Object.
See Also:
portable package comments for unimplemented features

get_domain_managers

public DomainManager[] get_domain_managers(Object self)
Retrieves the DomainManagers of this object. This allows administration services (and applications) to retrieve the domain managers, and hence the security and other policies applicable to individual objects that are members of the domain.

Parameters:
self - The object reference which delegated to this delegate.
Returns:
The list of immediately enclosing domain managers of this object. At least one domain manager is always returned in the list since by default each object is associated with at least one domain manager at creation.
See Also:
portable package comments for unimplemented features

set_policy_override

public Object set_policy_override(Object self,
                                  Policy[] policies,
                                  SetOverrideType set_add)
Associates the policies passed in with a newly created object reference that it returns. Only certain policies that pertain to the invocation of an operation at the client end can be overridden using this operation. Attempts to override any other policy will result in the raising of the CORBA::NO_PERMISSION exception.

Parameters:
self - The object reference which delegated to this delegate.
policies - A sequence of references to Policy objects.
set_add - Indicates whether these policies should be added onto any otheroverrides that already exist (ADD_OVERRIDE) in the object reference, or they should be added to a clean override free object reference (SET_OVERRIDE).
Returns:
A new object reference with the new policies associated with it.
See Also:
portable package comments for unimplemented features

is_local

public boolean is_local(Object self)
Returns true if this object is implemented by a local servant.

Parameters:
self - The object reference which delegated to this delegate.
Returns:
true only if the servant incarnating this object is located in this Java VM. Return false if the servant is not local or the ORB does not support local stubs for this particular servant. The default behavior of is_local() is to return false.

servant_preinvoke

public ServantObject servant_preinvoke(Object self,
                                       String operation,
                                       Class expectedType)
Returns a Java reference to the servant which should be used for this request. servant_preinvoke() is invoked by a local stub. If a ServantObject object is returned, then its servant field has been set to an object of the expected type (Note: the object may or may not be the actual servant instance). The local stub may cast the servant field to the expected type, and then invoke the operation directly. The ServantRequest object is valid for only one invocation, and cannot be used for more than one invocation.

Parameters:
self - The object reference which delegated to this delegate.
operation - a string containing the operation name. The operation name corresponds to the operation name as it would be encoded in a GIOP request.
expectedType - a Class object representing the expected type of the servant. The expected type is the Class object associated with the operations class of the stub's interface (e.g. A stub for an interface Foo, would pass the Class object for the FooOperations interface).
Returns:
a ServantObject object. The method may return a null value if it does not wish to support this optimization (e.g. due to security, transactions, etc). The method must return null if the servant is not of the expected type.

servant_postinvoke

public void servant_postinvoke(Object self,
                               ServantObject servant)
servant_postinvoke() is invoked by the local stub after the operation has been invoked on the local servant. This method must be called if servant_preinvoke() returned a non-null value, even if an exception was thrown by the servant's method. For this reason, the call to servant_postinvoke() should be placed in a Java finally clause.

Parameters:
self - The object reference which delegated to this delegate.
servant - the instance of the ServantObject returned from the servant_preinvoke() method.

request

public OutputStream request(Object self,
                            String operation,
                            boolean responseExpected)
request is called by a stub to obtain an OutputStream for marshaling arguments. The stub must supply the operation name, and indicate if a response is expected (i.e is this a oneway call).

Parameters:
self - The object reference which delegated to this delegate.
operation - a string containing the operation name. The operation name corresponds to the operation name as it would be encoded in a GIOP request.
responseExpected - false if the operation is a one way operation, and true otherwise.
Returns:
OutputStream the OutputStream into which request arguments can be marshaled.
See Also:
portable package comments for unimplemented features

invoke

public InputStream invoke(Object self,
                          OutputStream output)
                   throws ApplicationException,
                          RemarshalException
invoke is called by a stub to invoke an operation. The stub provides an OutputStream that was previously returned by a request() call. invoke returns an InputStream which contains the marshaled reply. If an exception occurs, invoke may throw an ApplicationException object which contains an InputStream from which the user exception state may be unmarshaled.

Parameters:
self - The object reference which delegated to this delegate.
output - the OutputStream which contains marshaled arguments
Returns:
input the InputStream from which reply parameters can be unmarshaled.
Throws:
ApplicationException - thrown when implementation throws (upon invocation) an exception defined as part of its remote method definition.
RemarshalException - thrown when remarshalling fails.
See Also:
portable package comments for unimplemented features

releaseReply

public void releaseReply(Object self,
                         InputStream input)
releaseReply may optionally be called by a stub to release a reply stream back to the ORB when the unmarshaling has completed. The stub passes the InputStream returned by invoke() or ApplicationException.getInputStream(). A null value may also be passed to releaseReply, in which case the method is a noop.

Parameters:
self - The object reference which delegated to this delegate.
input - the InputStream returned from invoke().
See Also:
portable package comments for unimplemented features

toString

public String toString(Object self)
Provides the implementation to override the toString() method of the delegating CORBA object.

Parameters:
self - the object reference that delegated to this delegate
Returns:
a String object that represents the object reference that delegated to this Delegate object

hashCode

public int hashCode(Object self)
Provides the implementation to override the hashCode() method of the delegating CORBA object.

Parameters:
self - the object reference that delegated to this delegate
Returns:
an int that represents the hashcode for the object reference that delegated to this Delegate object

equals

public boolean equals(Object self,
                      Object obj)
Provides the implementation to override the equals(java.lang.Object obj) method of the delegating CORBA object.

Parameters:
self - the object reference that delegated to this delegate
obj - the Object with which to compare
Returns:
true if obj equals self; false otherwise
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


IDLEntity (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA.portable
Interface IDLEntity

All Superinterfaces:
Serializable
All Known Subinterfaces:
AdapterActivator, BindingIterator, ClientRequestInfo, ClientRequestInterceptor, Codec, CodecFactory, Current, Current, Current, CustomValue, DataInputStream, DataOutputStream, DomainManager, DynAny, DynAnyFactory, DynArray, DynEnum, DynFixed, DynSequence, DynStruct, DynUnion, DynValue, DynValueBox, DynValueCommon, IdAssignmentPolicy, IDLType, IdUniquenessPolicy, ImplicitActivationPolicy, Interceptor, IORInfo, IORInterceptor, IRObject, LifespanPolicy, NamingContext, NamingContextExt, ORBInitializer, ORBInitInfo, POA, POAManager, Policy, PolicyFactory, RequestInfo, RequestProcessingPolicy, RunTime, ServantActivator, ServantLocator, ServantManager, ServantRetentionPolicy, ServerRequestInfo, ServerRequestInterceptor, StreamableValue, ThreadPolicy, ValueBase
All Known Implementing Classes:
_BindingIteratorImplBase, _BindingIteratorStub, _DynAnyFactoryStub, _DynAnyStub, _DynArrayStub, _DynEnumStub, _DynFixedStub, _DynSequenceStub, _DynStructStub, _DynUnionStub, _DynValueStub, _IDLTypeStub, _NamingContextExtStub, _NamingContextImplBase, _NamingContextStub, _PolicyStub, _ServantActivatorStub, _ServantLocatorStub, Any, Binding, BindingType, CompletionStatus, DefinitionKind, Encoding, IdAssignmentPolicyValue, IdUniquenessPolicyValue, ImplicitActivationPolicyValue, IOR, LifespanPolicyValue, NameComponent, NameDynAnyPair, NameValuePair, NameValuePair, NotFoundReason, Parameter, ParameterMode, RequestProcessingPolicyValue, ServantRetentionPolicyValue, ServiceContext, ServiceDetail, ServiceInformation, SetOverrideType, State, StructMember, TaggedComponent, TaggedProfile, ThreadPolicyValue, TypeCode, UnionMember, UserException, ValueMember
public interface IDLEntity
extends Serializable

An interface with no members whose only purpose is to serve as a marker indicating that an implementing class is a Java value type from IDL that has a corresponding Helper class. RMI IIOP serialization looks for such a marker to perform marshalling/unmarshalling.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


IndirectionException (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA.portable
Class IndirectionException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by org.omg.CORBA.SystemException
                    extended by org.omg.CORBA.portable.IndirectionException
All Implemented Interfaces:
Serializable
public class IndirectionException
extends SystemException

The Indirection exception is a Java specific system exception. It is thrown when the ORB's input stream is called to demarshal a value that is encoded as an indirection that is in the process of being demarshaled. This can occur when the ORB input stream calls the ValueHandler to demarshal an RMI value whose state contains a recursive reference to itself. Because the top-level ValueHandler.read_value() call has not yet returned a value, the ORB input stream's indirection table does not contain an entry for an object with the stream offset specified by the indirection tag. The stream offset is returned in the exception's offset field.

See Also:
InputStream, org.omg.CORBA_2_3.portable.OuputStream

Field Summary
 int offset
Points to the stream's offset.
Fields inherited from class org.omg.CORBA.SystemException
completed, minor
Constructor Summary
IndirectionException(int offset)
Creates an IndirectionException with the right offset value.
Methods inherited from class org.omg.CORBA.SystemException
toString
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

offset

public int offset
Points to the stream's offset.

Constructor Detail

IndirectionException

public IndirectionException(int offset)
Creates an IndirectionException with the right offset value. The stream offset is returned in the exception's offset field. This exception is constructed and thrown during reading recursively defined values off of a stream.

Parameters:
offset - the stream offset where recursion is detected.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


InputStream (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA.portable
Class InputStream

java.lang.Object
    extended by java.io.InputStream
        extended by org.omg.CORBA.portable.InputStream
Direct Known Subclasses:
InputStream
public abstract class InputStream
extends InputStream

InputStream is the Java API for reading IDL types from CDR marshal streams. These methods are used by the ORB to unmarshal IDL types as well as to extract IDL types out of Anys. The _array versions of the methods can be directly used to read sequences and arrays of IDL types.

Since:
JDK1.2

Constructor Summary
InputStream()
Method Summary
ORB | orb() Returns the ORB that created this InputStream.
abstract Any | read_any() Reads an Any from this input stream.
abstract void | read_boolean_array(boolean[] value, int offset, int length) Reads an array of booleans from this input stream.
abstract boolean | read_boolean() Reads a boolean value from this input stream.
abstract void | read_char_array(char[] value, int offset, int length) Reads an array of chars from this input stream.
abstract char | read_char() Reads a char value from this input stream.
Context | read_Context() Reads a CORBA context from the stream.
abstract void | read_double_array(double[] value, int offset, int length) Reads an array of boubles from this input stream.
abstract double | read_double() Reads a double value from this input stream.
BigDecimal | read_fixed() Reads a BigDecimal number.
abstract void | read_float_array(float[] value, int offset, int length) Reads an array of floats from this input stream.
abstract float | read_float() Reads a float value from this input stream.
abstract void | read_long_array(int[] value, int offset, int length) Reads an array of CORBA longs (that is, Java ints) from this input stream.
abstract int | read_long() Reads a CORBA long (that is, Java int) value from this input stream.
abstract void | read_longlong_array(long[] value, int offset, int length) Reads an array of CORBA longlongs (that is, Java longs) from this input stream.
abstract long | read_longlong() Reads a CORBA longlong (that is, Java long) value from this input stream.
abstract Object | read_Object() Reads a CORBA object from this input stream.
Object | read_Object(Class clz) Unmarshals an object and returns a CORBA Object, which is an instance of the class passed as its argument.
abstract void | read_octet_array(byte[] value, int offset, int length) Reads an array of octets (that is, bytes) from this input stream.
abstract byte | read_octet() Reads an octet (that is, a byte) value from this input stream.
Principal | read_Principal() Deprecated. Deprecated by CORBA 2.2.
abstract void | read_short_array(short[] value, int offset, int length) Reads an array of shorts from this input stream.
abstract short | read_short() Reads a short value from this input stream.
abstract String | read_string() Reads a string value from this input stream.
abstract TypeCode | read_TypeCode() Reads a TypeCode from this input stream.
abstract void | read_ulong_array(int[] value, int offset, int length) Reads an array of unsigned CORBA longs (that is, Java ints) from this input stream.
abstract int | read_ulong() Reads an unsigned CORBA long (that is, Java int) value from this input stream.
abstract void | read_ulonglong_array(long[] value, int offset, int length) Reads an array of unsigned CORBA longlongs (that is, Java longs) from this input stream.
abstract long | read_ulonglong() Reads a CORBA unsigned longlong (that is, Java long) value from this input stream.
abstract void | read_ushort_array(short[] value, int offset, int length) Reads an array of unsigned shorts from this input stream.
abstract short | read_ushort() Reads a unsigned short value from this input stream.
abstract void | read_wchar_array(char[] value, int offset, int length) Reads an array of wide chars from this input stream.
abstract char | read_wchar() Reads a wide char value from this input stream.
abstract String | read_wstring() Reads a wide string value from this input stream.
int | read() Reads the next byte of data from the input stream.
Methods inherited from class java.io.InputStream
available, close, mark, markSupported, read, read, reset, skip
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

InputStream

public InputStream()
Method Detail

read_boolean

public abstract boolean read_boolean()
Reads a boolean value from this input stream.

Returns:
the boolean value read from this input stream

read_char

public abstract char read_char()
Reads a char value from this input stream.

Returns:
the char value read from this input stream

read_wchar

public abstract char read_wchar()
Reads a wide char value from this input stream.

Returns:
the char value read from this input stream

read_octet

public abstract byte read_octet()
Reads an octet (that is, a byte) value from this input stream.

Returns:
the byte value read from this input stream

read_short

public abstract short read_short()
Reads a short value from this input stream.

Returns:
the short value read from this input stream

read_ushort

public abstract short read_ushort()
Reads a unsigned short value from this input stream.

Returns:
the short value read from this input stream

read_long

public abstract int read_long()
Reads a CORBA long (that is, Java int) value from this input stream.

Returns:
the int value read from this input stream

read_ulong

public abstract int read_ulong()
Reads an unsigned CORBA long (that is, Java int) value from this input stream.

Returns:
the int value read from this input stream

read_longlong

public abstract long read_longlong()
Reads a CORBA longlong (that is, Java long) value from this input stream.

Returns:
the long value read from this input stream

read_ulonglong

public abstract long read_ulonglong()
Reads a CORBA unsigned longlong (that is, Java long) value from this input stream.

Returns:
the long value read from this input stream

read_float

public abstract float read_float()
Reads a float value from this input stream.

Returns:
the float value read from this input stream

read_double

public abstract double read_double()
Reads a double value from this input stream.

Returns:
the double value read from this input stream

read_string

public abstract String read_string()
Reads a string value from this input stream.

Returns:
the String value read from this input stream

read_wstring

public abstract String read_wstring()
Reads a wide string value from this input stream.

Returns:
the String value read from this input stream

read_boolean_array

public abstract void read_boolean_array(boolean[] value,
                                        int offset,
                                        int length)
Reads an array of booleans from this input stream.

Parameters:
value - returned array of booleans.
offset - offset on the stream.
length - length of buffer to read

read_char_array

public abstract void read_char_array(char[] value,
                                     int offset,
                                     int length)
Reads an array of chars from this input stream.

Parameters:
value - returned array of chars.
offset - offset on the stream.
length - length of buffer to read

read_wchar_array

public abstract void read_wchar_array(char[] value,
                                      int offset,
                                      int length)
Reads an array of wide chars from this input stream.

Parameters:
value - returned array of wide chars.
offset - offset on the stream.
length - length of buffer to read

read_octet_array

public abstract void read_octet_array(byte[] value,
                                      int offset,
                                      int length)
Reads an array of octets (that is, bytes) from this input stream.

Parameters:
value - returned array of octets (that is, bytes).
offset - offset on the stream.
length - length of buffer to read

read_short_array

public abstract void read_short_array(short[] value,
                                      int offset,
                                      int length)
Reads an array of shorts from this input stream.

Parameters:
value - returned array of shorts.
offset - offset on the stream.
length - length of buffer to read

read_ushort_array

public abstract void read_ushort_array(short[] value,
                                       int offset,
                                       int length)
Reads an array of unsigned shorts from this input stream.

Parameters:
value - returned array of shorts.
offset - offset on the stream.
length - length of buffer to read

read_long_array

public abstract void read_long_array(int[] value,
                                     int offset,
                                     int length)
Reads an array of CORBA longs (that is, Java ints) from this input stream.

Parameters:
value - returned array of CORBA longs (that is, Java ints).
offset - offset on the stream.
length - length of buffer to read

read_ulong_array

public abstract void read_ulong_array(int[] value,
                                      int offset,
                                      int length)
Reads an array of unsigned CORBA longs (that is, Java ints) from this input stream.

Parameters:
value - returned array of CORBA longs (that is, Java ints).
offset - offset on the stream.
length - length of buffer to read

read_longlong_array

public abstract void read_longlong_array(long[] value,
                                         int offset,
                                         int length)
Reads an array of CORBA longlongs (that is, Java longs) from this input stream.

Parameters:
value - returned array of CORBA longs (that is, Java longs).
offset - offset on the stream.
length - length of buffer to read

read_ulonglong_array

public abstract void read_ulonglong_array(long[] value,
                                          int offset,
                                          int length)
Reads an array of unsigned CORBA longlongs (that is, Java longs) from this input stream.

Parameters:
value - returned array of CORBA longs (that is, Java longs).
offset - offset on the stream.
length - length of buffer to read

read_float_array

public abstract void read_float_array(float[] value,
                                      int offset,
                                      int length)
Reads an array of floats from this input stream.

Parameters:
value - returned array of floats.
offset - offset on the stream.
length - length of buffer to read

read_double_array

public abstract void read_double_array(double[] value,
                                       int offset,
                                       int length)
Reads an array of boubles from this input stream.

Parameters:
value - returned array of doubles.
offset - offset on the stream.
length - length of buffer to read

read_Object

public abstract Object read_Object()
Reads a CORBA object from this input stream.

Returns:
the Object instance read from this input stream

read_TypeCode

public abstract TypeCode read_TypeCode()
Reads a TypeCode from this input stream.

Returns:
the TypeCode instance read from this input stream

read_any

public abstract Any read_any()
Reads an Any from this input stream.

Returns:
the Any instance read from this input stream

read_Principal

public Principal read_Principal()
Deprecated. Deprecated by CORBA 2.2.

Returns principle for invocation.

Returns:
Principle for invocation

read

public int read()
         throws IOException
Description copied from class: InputStream
Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

A subclass must provide an implementation of this method.

Specified by:
read in class InputStream
Returns:
the next byte of data, or -1 if the end of the stream is reached.
Throws:
IOException - if an I/O error occurs.
See Also:
portable package comments for unimplemented features

read_fixed

public BigDecimal read_fixed()
Reads a BigDecimal number.

Returns:
a java.math.BigDecimal number

read_Context

public Context read_Context()
Reads a CORBA context from the stream.

Returns:
a CORBA context
See Also:
portable package comments for unimplemented features

read_Object

public Object read_Object(Class clz)
Unmarshals an object and returns a CORBA Object, which is an instance of the class passed as its argument. This class is the stub class of the expected type.

Parameters:
clz - The Class object for the stub class which corresponds to the type that is statistically expected, or the Class object for the RMI/IDL interface type that is statistically expected.
Returns:
an Object instance of clz read from this stream
See Also:
portable package comments for unimplemented features

orb

public ORB orb()
Returns the ORB that created this InputStream.

Returns:
the ORB object that created this stream
See Also:
portable package comments for unimplemented features
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


InvokeHandler (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA.portable
Interface InvokeHandler

All Known Subinterfaces:
Tie
All Known Implementing Classes:
BindingIteratorPOA, NamingContextExtPOA, NamingContextPOA, ServantActivatorPOA, ServantLocatorPOA
public interface InvokeHandler

This interface provides a dispatching mechanism for an incoming call. It is invoked by the ORB to dispatch a request to a servant.

Method Summary
 OutputStream _invoke(String method, InputStream input, ResponseHandler handler)
Invoked by the ORB to dispatch a request to the servant.

Method Detail

_invoke

public OutputStream _invoke(String method,
                            InputStream input,
                            ResponseHandler handler)
                     throws SystemException
Invoked by the ORB to dispatch a request to the servant. ORB passes the method name, an InputStream containing the marshalled arguments, and a ResponseHandler which the servant uses to construct a proper reply. Only CORBA SystemException may be thrown by this method. The method must return an OutputStream created by the ResponseHandler which contains the marshalled reply. A servant must not retain a reference to the ResponseHandler beyond the lifetime of a method invocation. Servant behaviour is defined as follows:

1. Determine correct method, and unmarshal parameters from InputStream.

2. Invoke method implementation.

3. If no user exception, create a normal reply using ResponseHandler.

4. If user exception occurred, create exception reply using ResponseHandler.

5. Marshal reply into OutputStream returned by ResponseHandler.

6. Return OutputStream to ORB.

Parameters:
method - The method name.
input - The InputStream containing the marshalled arguments.
handler - The ResponseHandler which the servant uses to construct a proper reply
Returns:
The OutputStream created by the ResponseHandler which contains the marshalled reply
Throws:
SystemException - is thrown when invocation fails due to a CORBA system exception.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ObjectImpl (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA.portable
Class ObjectImpl

java.lang.Object
    extended by org.omg.CORBA.portable.ObjectImpl
All Implemented Interfaces:
Object
Direct Known Subclasses:
_BindingIteratorStub, _DynAnyFactoryStub, _DynAnyStub, _DynArrayStub, _DynEnumStub, _DynFixedStub, _DynSequenceStub, _DynStructStub, _DynUnionStub, _DynValueStub, _IDLTypeStub, _NamingContextExtStub, _NamingContextStub, _PolicyStub, _ServantActivatorStub, _ServantLocatorStub, DynamicImplementation, ObjectImpl
public abstract class ObjectImpl
extends Object
implements Object

The common base class for all stub classes; provides default implementations of the org.omg.CORBA.Object methods. All method implementations are forwarded to a Delegate object stored in the ObjectImpl instance. ObjectImpl allows for portable stubs because the Delegate can be implemented by a different vendor-specific ORB.

Constructor Summary
ObjectImpl()
Method Summary
Request | _create_request(Context ctx, String operation, NVList arg_list, NamedValue result) Creates a Request object that contains the given context, method, argument list, and container for the result.
Request | _create_request(Context ctx, String operation, NVList arg_list, NamedValue result, ExceptionList exceptions, ContextList contexts) Creates a Request object that contains the given context, method, argument list, container for the result, exceptions, and list of property names to be used in resolving the context strings.
Object | _duplicate() Returns a duplicate of this ObjectImpl object.
Delegate | _get_delegate() Retrieves the reference to the vendor-specific Delegate object to which this ObjectImpl object delegates all methods invoked on it.
DomainManager[] | _get_domain_managers() Retrieves a list of the domain managers for this ObjectImpl object.
Object | _get_interface_def() Retrieves the interface definition for this ObjectImpl object.
Policy | _get_policy(int policy_type) Retrieves the Policy object for this ObjectImpl object that has the given policy type.
int | _hash(int maximum) Retrieves the hash code that serves as an ORB-internal identifier for this ObjectImpl object.
abstract String[] | _ids() Retrieves a string array containing the repository identifiers supported by this ObjectImpl object.
InputStream | _invoke(OutputStream output) Invokes an operation and returns an InputStream object for reading the response.
boolean | _is_a(String repository_id) Checks whether the object identified by the given repository identifier is an ObjectImpl object.
boolean | _is_equivalent(Object that) Checks whether the the given ObjectImpl object is equivalent to this ObjectImpl object.
boolean | _is_local() Checks whether this ObjectImpl object is implemented by a local servant.
boolean | _non_existent() Checks whether the server object for this ObjectImpl object has been destroyed.
ORB | _orb() Returns a reference to the ORB associated with this object and its delegate.
void | _release() Releases the resources associated with this ObjectImpl object.
void | _releaseReply(InputStream input) Releases the given reply stream back to the ORB when unmarshalling has completed after a call to the method _invoke.
Request | _request(String operation) Creates a Request object containing the given method that can be used with the Dynamic Invocation Interface.
OutputStream | _request(String operation, boolean responseExpected) Returns an OutputStream object to use for marshalling the arguments of the given method.
void | _servant_postinvoke(ServantObject servant) Is called by the local stub after it has invoked an operation on the local servant that was previously retrieved from a call to the method _servant_preinvoke.
ServantObject | _servant_preinvoke(String operation, Class expectedType) Returns a Java reference to the local servant that should be used for sending a request for the method specified.
void | _set_delegate(Delegate delegate) Sets the Delegate for this ObjectImpl instance to the given Delegate object.
Object | _set_policy_override(Policy[] policies, SetOverrideType set_add) Sets this ObjectImpl object's override type for the given policies to the given instance of SetOverrideType.
boolean | equals(Object obj) Compares this ObjectImpl object with the given one for equality.
int | hashCode() Returns the hash code for this ObjectImpl object.
String | toString() Returns a String object that represents this ObjectImpl object.
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait

Constructor Detail

ObjectImpl

public ObjectImpl()
Method Detail

_get_delegate

public Delegate _get_delegate()
Retrieves the reference to the vendor-specific Delegate object to which this ObjectImpl object delegates all methods invoked on it.

Returns:
the Delegate contained in this ObjectImpl instance
Throws:
BAD_OPERATION - if the delegate has not been set
See Also:
_set_delegate(org.omg.CORBA.portable.Delegate)

_set_delegate

public void _set_delegate(Delegate delegate)
Sets the Delegate for this ObjectImpl instance to the given Delegate object. All method invocations on this ObjectImpl object will be forwarded to this delegate.

Parameters:
delegate - the Delegate instance to which all method calls on this ObjectImpl object will be delegated; may be implemented by a third-party ORB
See Also:
_get_delegate()

_ids

public abstract String[] _ids()
Retrieves a string array containing the repository identifiers supported by this ObjectImpl object. For example, for a stub, this method returns information about all the interfaces supported by the stub.

Returns:
the array of all repository identifiers supported by this ObjectImpl instance

_duplicate

public Object _duplicate()
Returns a duplicate of this ObjectImpl object.

Specified by:
_duplicate in interface Object
Returns:
an orb.omg.CORBA.Object object that is a duplicate of this object

_release

public void _release()
Releases the resources associated with this ObjectImpl object.

Specified by:
_release in interface Object

_is_a

public boolean _is_a(String repository_id)
Checks whether the object identified by the given repository identifier is an ObjectImpl object.

Specified by:
_is_a in interface Object
Parameters:
repository_id - a String object with the repository identifier to check
Returns:
true if the object identified by the given repository id is an instance of ObjectImpl; false otherwise

_is_equivalent

public boolean _is_equivalent(Object that)
Checks whether the the given ObjectImpl object is equivalent to this ObjectImpl object.

Specified by:
_is_equivalent in interface Object
Parameters:
that - an instance of ObjectImpl to compare with this ObjectImpl object
Returns:
true if the given object is equivalent to this ObjectImpl object; false otherwise

_non_existent

public boolean _non_existent()
Checks whether the server object for this ObjectImpl object has been destroyed.

Specified by:
_non_existent in interface Object
Returns:
true if the ORB knows authoritatively that the server object does not exist; false otherwise

_hash

public int _hash(int maximum)
Retrieves the hash code that serves as an ORB-internal identifier for this ObjectImpl object.

Specified by:
_hash in interface Object
Parameters:
maximum - an int indicating the upper bound on the hash value returned by the ORB
Returns:
an int representing the hash code for this ObjectImpl object

_request

public Request _request(String operation)
Creates a Request object containing the given method that can be used with the Dynamic Invocation Interface.

Specified by:
_request in interface Object
Parameters:
operation - the method to be invoked by the new Request object
Returns:
a new Request object initialized with the given method

_create_request

public Request _create_request(Context ctx,
                               String operation,
                               NVList arg_list,
                               NamedValue result)
Creates a Request object that contains the given context, method, argument list, and container for the result.

Specified by:
_create_request in interface Object
Parameters:
ctx - the Context for the request
operation - the method that the new Request object will invoke
arg_list - the arguments for the method; an NVList in which each argument is a NamedValue object
result - a NamedValue object to be used for returning the result of executing the request's method
Returns:
a new Request object initialized with the given context, method, argument list, and container for the return value
See Also:
Request, NVList, NamedValue

_create_request

public Request _create_request(Context ctx,
                               String operation,
                               NVList arg_list,
                               NamedValue result,
                               ExceptionList exceptions,
                               ContextList contexts)
Creates a Request object that contains the given context, method, argument list, container for the result, exceptions, and list of property names to be used in resolving the context strings. This Request object is for use in the Dynamic Invocation Interface.

Specified by:
_create_request in interface Object
Parameters:
ctx - the Context object that contains the context strings that must be resolved before they are sent along with the request
operation - the method that the new Request object will invoke
arg_list - the arguments for the method; an NVList in which each argument is a NamedValue object
result - a NamedValue object to be used for returning the result of executing the request's method
exceptions - a list of the exceptions that the given method throws
contexts - a list of the properties that are needed to resolve the contexts in ctx; the strings in contexts are used as arguments to the method Context.get_values, which returns the value associated with the given property
Returns:
a new Request object initialized with the given context strings to resolve, method, argument list, container for the result, exceptions, and list of property names to be used in resolving the context strings
See Also:
Request, NVList, NamedValue, ExceptionList, ContextList

_get_interface_def

public Object _get_interface_def()
Retrieves the interface definition for this ObjectImpl object.

Specified by:
_get_interface_def in interface Object
Returns:
the org.omg.CORBA.Object instance that is the interface definition for this ObjectImpl object

_orb

public ORB _orb()
Returns a reference to the ORB associated with this object and its delegate. This is the ORB object that created the delegate.

Returns:
the ORB instance that created the Delegate object contained in this ObjectImpl object

_get_policy

public Policy _get_policy(int policy_type)
Retrieves the Policy object for this ObjectImpl object that has the given policy type.

Specified by:
_get_policy in interface Object
Parameters:
policy_type - an int indicating the policy type
Returns:
the Policy object that is the specified policy type and that applies to this ObjectImpl object
See Also:
PolicyOperations.policy_type()

_get_domain_managers

public DomainManager[] _get_domain_managers()
Retrieves a list of the domain managers for this ObjectImpl object.

Specified by:
_get_domain_managers in interface Object
Returns:
an array containing the DomainManager objects for this instance of ObjectImpl

_set_policy_override

public Object _set_policy_override(Policy[] policies,
                                   SetOverrideType set_add)
Sets this ObjectImpl object's override type for the given policies to the given instance of SetOverrideType.

Specified by:
_set_policy_override in interface Object
Parameters:
policies - an array of Policy objects with the policies that will replace the current policies or be added to the current policies
set_add - either SetOverrideType.SET_OVERRIDE, indicating that the given policies will replace any existing ones, or SetOverrideType.ADD_OVERRIDE, indicating that the given policies should be added to any existing ones
Returns:
an Object with the given policies replacing or added to its previous policies

_is_local

public boolean _is_local()
Checks whether this ObjectImpl object is implemented by a local servant. If so, local invocation API's may be used.

Returns:
true if this object is implemented by a local servant; false otherwise

_servant_preinvoke

public ServantObject _servant_preinvoke(String operation,
                                        Class expectedType)
Returns a Java reference to the local servant that should be used for sending a request for the method specified. If this ObjectImpl object is a local stub, it will invoke the _servant_preinvoke method before sending a request in order to obtain the ServantObject instance to use.

If a ServantObject object is returned, its servant field has been set to an object of the expected type (Note: the object may or may not be the actual servant instance). The local stub may cast the servant field to the expected type, and then invoke the operation directly. The ServantRequest object is valid for only one invocation and cannot be used for more than one invocation.

Parameters:
operation - a String containing the name of the method to be invoked. This name should correspond to the method name as it would be encoded in a GIOP request.
expectedType - a Class object representing the expected type of the servant that is returned. This expected type is the Class object associated with the operations class for the stub's interface. For example, a stub for an interface Foo would pass the Class object for the FooOperations interface.
Returns:
(1) a ServantObject object, which may or may not be the actual servant instance, or (2) null if (a) the servant is not local or (b) the servant has ceased to be local due to a ForwardRequest from a POA ServantManager
Throws:
BAD_PARAM - if the servant is not the expected type

_servant_postinvoke

public void _servant_postinvoke(ServantObject servant)
Is called by the local stub after it has invoked an operation on the local servant that was previously retrieved from a call to the method _servant_preinvoke. The _servant_postinvoke method must be called if the _servant_preinvoke method returned a non-null value, even if an exception was thrown by the method invoked by the servant. For this reason, the call to the method _servant_postinvoke should be placed in a Java finally clause.

Parameters:
servant - the instance of the ServantObject returned by the _servant_preinvoke method

_request

public OutputStream _request(String operation,
                             boolean responseExpected)
Returns an OutputStream object to use for marshalling the arguments of the given method. This method is called by a stub, which must indicate if a response is expected, that is, whether or not the call is oneway.

Parameters:
operation - a String giving the name of the method.
responseExpected - a boolean -- true if the request is not one way, that is, a response is expected
Returns:
an OutputStream object for dispatching the request

_invoke

public InputStream _invoke(OutputStream output)
                    throws ApplicationException,
                           RemarshalException
Invokes an operation and returns an InputStream object for reading the response. The stub provides the OutputStream object that was previously returned by a call to the _request method. The method specified as an argument to _request when it was called previously is the method that this method invokes.

If an exception occurs, the _invoke method may throw an ApplicationException object that contains an InputStream from which the user exception state may be unmarshalled.

Parameters:
output - an OutputStream object for dispatching the request
Returns:
an InputStream object containing the marshalled response to the method invoked
Throws:
ApplicationException - if the invocation meets application-defined exception
RemarshalException - if the invocation leads to a remarshalling error
See Also:
_request(java.lang.String)

_releaseReply

public void _releaseReply(InputStream input)
Releases the given reply stream back to the ORB when unmarshalling has completed after a call to the method _invoke. Calling this method is optional for the stub.

Parameters:
input - the InputStream object that was returned by the _invoke method or the ApplicationException.getInputStream method; may be null, in which case this method does nothing
See Also:
_invoke(org.omg.CORBA.portable.OutputStream)

toString

public String toString()
Returns a String object that represents this ObjectImpl object.

Overrides:
toString in class Object
Returns:
the String representation of this object

hashCode

public int hashCode()
Returns the hash code for this ObjectImpl object.

Overrides:
hashCode in class Object
Returns:
the hash code for this object
See Also:
Object.equals(java.lang.Object), Hashtable

equals

public boolean equals(Object obj)
Compares this ObjectImpl object with the given one for equality.

Overrides:
equals in class Object
Parameters:
obj - the object with which to compare this object
Returns:
true if the two objects are equal; false otherwise
See Also:
Object.hashCode(), Hashtable
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


OutputStream (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA.portable
Class OutputStream

java.lang.Object
    extended by java.io.OutputStream
        extended by org.omg.CORBA.portable.OutputStream
Direct Known Subclasses:
OutputStream
public abstract class OutputStream
extends OutputStream

OuputStream is the Java API for writing IDL types to CDR marshal streams. These methods are used by the ORB to marshal IDL types as well as to insert IDL types into Anys. The _array versions of the methods can be directly used to write sequences and arrays of IDL types.

Since:
JDK1.2

Constructor Summary
OutputStream()
Method Summary
abstract InputStream | create_input_stream() Returns an input stream with the same buffer.
ORB | orb() Returns the ORB that created this OutputStream.
abstract void | write_any(Any value) Writes an Any on this output stream.
abstract void | write_boolean_array(boolean[] value, int offset, int length) Writes an array of booleans on this output stream.
abstract void | write_boolean(boolean value) Writes a boolean value to this stream.
abstract void | write_char_array(char[] value, int offset, int length) Writes an array of chars on this output stream.
abstract void | write_char(char value) Writes a char value to this stream.
void | write_Context(Context ctx, ContextList contexts) Writes a CORBA context on this stream.
abstract void | write_double_array(double[] value, int offset, int length) Writes an array of doubles on this output stream.
abstract void | write_double(double value) Writes a double value to this stream.
void | write_fixed(BigDecimal value) Writes a BigDecimal number.
abstract void | write_float_array(float[] value, int offset, int length) Writes an array of floats on this output stream.
abstract void | write_float(float value) Writes a float value to this stream.
abstract void | write_long_array(int[] value, int offset, int length) Writes an array of CORBA longs (i.e.
abstract void | write_long(int value) Writes a CORBA long (i.e.
abstract void | write_longlong_array(long[] value, int offset, int length) Writes an array of CORBA longlongs (i.e.
abstract void | write_longlong(long value) Writes a CORBA longlong (i.e.
abstract void | write_Object(Object value) Writes a CORBA Object on this output stream.
abstract void | write_octet_array(byte[] value, int offset, int length) Writes an array of CORBA octets (bytes) on this output stream.
abstract void | write_octet(byte value) Writes a CORBA octet (i.e.
void | write_Principal(Principal value) Deprecated. Deprecated by CORBA 2.2.
abstract void | write_short_array(short[] value, int offset, int length) Writes an array of shorts on this output stream.
abstract void | write_short(short value) Writes a short value to this stream.
abstract void | write_string(String value) Writes a string value to this stream.
abstract void | write_TypeCode(TypeCode value) Writes a TypeCode on this output stream.
abstract void | write_ulong_array(int[] value, int offset, int length) Writes an array of unsigned CORBA longs (i.e.
abstract void | write_ulong(int value) Writes an unsigned CORBA long (i.e.
abstract void | write_ulonglong_array(long[] value, int offset, int length) Writes an array of unsigned CORBA longlongs (i.e.
abstract void | write_ulonglong(long value) Writes an unsigned CORBA longlong (i.e.
abstract void | write_ushort_array(short[] value, int offset, int length) Writes an array of unsigned shorts on this output stream.
abstract void | write_ushort(short value) Writes an unsigned short value to this stream.
abstract void | write_wchar_array(char[] value, int offset, int length) Writes an array of wide chars on this output stream.
abstract void | write_wchar(char value) Writes a wide char value to this stream.
abstract void | write_wstring(String value) Writes a wide string value to this stream.
void | write(int b) Writes an integer (length of arrays) onto this stream.
Methods inherited from class java.io.OutputStream
close, flush, write, write
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

OutputStream

public OutputStream()
Method Detail

create_input_stream

public abstract InputStream create_input_stream()
Returns an input stream with the same buffer.

Returns:
an input stream with the same buffer.

write_boolean

public abstract void write_boolean(boolean value)
Writes a boolean value to this stream.

Parameters:
value - the value to be written.

write_char

public abstract void write_char(char value)
Writes a char value to this stream.

Parameters:
value - the value to be written.

write_wchar

public abstract void write_wchar(char value)
Writes a wide char value to this stream.

Parameters:
value - the value to be written.

write_octet

public abstract void write_octet(byte value)
Writes a CORBA octet (i.e. byte) value to this stream.

Parameters:
value - the value to be written.

write_short

public abstract void write_short(short value)
Writes a short value to this stream.

Parameters:
value - the value to be written.

write_ushort

public abstract void write_ushort(short value)
Writes an unsigned short value to this stream.

Parameters:
value - the value to be written.

write_long

public abstract void write_long(int value)
Writes a CORBA long (i.e. Java int) value to this stream.

Parameters:
value - the value to be written.

write_ulong

public abstract void write_ulong(int value)
Writes an unsigned CORBA long (i.e. Java int) value to this stream.

Parameters:
value - the value to be written.

write_longlong

public abstract void write_longlong(long value)
Writes a CORBA longlong (i.e. Java long) value to this stream.

Parameters:
value - the value to be written.

write_ulonglong

public abstract void write_ulonglong(long value)
Writes an unsigned CORBA longlong (i.e. Java long) value to this stream.

Parameters:
value - the value to be written.

write_float

public abstract void write_float(float value)
Writes a float value to this stream.

Parameters:
value - the value to be written.

write_double

public abstract void write_double(double value)
Writes a double value to this stream.

Parameters:
value - the value to be written.

write_string

public abstract void write_string(String value)
Writes a string value to this stream.

Parameters:
value - the value to be written.

write_wstring

public abstract void write_wstring(String value)
Writes a wide string value to this stream.

Parameters:
value - the value to be written.

write_boolean_array

public abstract void write_boolean_array(boolean[] value,
                                         int offset,
                                         int length)
Writes an array of booleans on this output stream.

Parameters:
value - the array to be written.
offset - offset on the stream.
length - length of buffer to write.

write_char_array

public abstract void write_char_array(char[] value,
                                      int offset,
                                      int length)
Writes an array of chars on this output stream.

Parameters:
value - the array to be written.
offset - offset on the stream.
length - length of buffer to write.

write_wchar_array

public abstract void write_wchar_array(char[] value,
                                       int offset,
                                       int length)
Writes an array of wide chars on this output stream.

Parameters:
value - the array to be written.
offset - offset on the stream.
length - length of buffer to write.

write_octet_array

public abstract void write_octet_array(byte[] value,
                                       int offset,
                                       int length)
Writes an array of CORBA octets (bytes) on this output stream.

Parameters:
value - the array to be written.
offset - offset on the stream.
length - length of buffer to write.

write_short_array

public abstract void write_short_array(short[] value,
                                       int offset,
                                       int length)
Writes an array of shorts on this output stream.

Parameters:
value - the array to be written.
offset - offset on the stream.
length - length of buffer to write.

write_ushort_array

public abstract void write_ushort_array(short[] value,
                                        int offset,
                                        int length)
Writes an array of unsigned shorts on this output stream.

Parameters:
value - the array to be written.
offset - offset on the stream.
length - length of buffer to write.

write_long_array

public abstract void write_long_array(int[] value,
                                      int offset,
                                      int length)
Writes an array of CORBA longs (i.e. Java ints) on this output stream.

Parameters:
value - the array to be written.
offset - offset on the stream.
length - length of buffer to write.

write_ulong_array

public abstract void write_ulong_array(int[] value,
                                       int offset,
                                       int length)
Writes an array of unsigned CORBA longs (i.e. Java ints) on this output stream.

Parameters:
value - the array to be written.
offset - offset on the stream.
length - length of buffer to write.

write_longlong_array

public abstract void write_longlong_array(long[] value,
                                          int offset,
                                          int length)
Writes an array of CORBA longlongs (i.e. Java longs) on this output stream.

Parameters:
value - the array to be written.
offset - offset on the stream.
length - length of buffer to write.

write_ulonglong_array

public abstract void write_ulonglong_array(long[] value,
                                           int offset,
                                           int length)
Writes an array of unsigned CORBA longlongs (i.e. Java ints) on this output stream.

Parameters:
value - the array to be written.
offset - offset on the stream.
length - length of buffer to write.

write_float_array

public abstract void write_float_array(float[] value,
                                       int offset,
                                       int length)
Writes an array of floats on this output stream.

Parameters:
value - the array to be written.
offset - offset on the stream.
length - length of buffer to write.

write_double_array

public abstract void write_double_array(double[] value,
                                        int offset,
                                        int length)
Writes an array of doubles on this output stream.

Parameters:
value - the array to be written.
offset - offset on the stream.
length - length of buffer to write.

write_Object

public abstract void write_Object(Object value)
Writes a CORBA Object on this output stream.

Parameters:
value - the value to be written.

write_TypeCode

public abstract void write_TypeCode(TypeCode value)
Writes a TypeCode on this output stream.

Parameters:
value - the value to be written.

write_any

public abstract void write_any(Any value)
Writes an Any on this output stream.

Parameters:
value - the value to be written.

write_Principal

public void write_Principal(Principal value)
Deprecated. Deprecated by CORBA 2.2.

Writes a Principle on this output stream.

Parameters:
value - the value to be written.

write

public void write(int b)
           throws IOException
Writes an integer (length of arrays) onto this stream.

Specified by:
write in class OutputStream
Parameters:
b - the value to be written.
Throws:
IOException - if there is an input/output error
See Also:
portable package comments for unimplemented features

write_fixed

public void write_fixed(BigDecimal value)
Writes a BigDecimal number.

Parameters:
value - a BidDecimal--value to be written.

write_Context

public void write_Context(Context ctx,
                          ContextList contexts)
Writes a CORBA context on this stream. The Context is marshaled as a sequence of strings. Only those Context values specified in the contexts parameter are actually written.

Parameters:
ctx - a CORBA context
contexts - a ContextList object containing the list of contexts to be written
See Also:
portable package comments for unimplemented features

orb

public ORB orb()
Returns the ORB that created this OutputStream.

Returns:
the ORB that created this OutputStream
See Also:
portable package comments for unimplemented features
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


org.omg.CORBA.portable (Java 2 Platform SE v1.4.2)

 org.omg.CORBA.portable
Interfaces
BoxedValueHelper
CustomValue
IDLEntity
InvokeHandler
ResponseHandler
Streamable
StreamableValue
ValueBase
ValueFactory
Classes
Delegate
InputStream
ObjectImpl
OutputStream
ServantObject
Exceptions
ApplicationException
IndirectionException
RemarshalException
UnknownException


org.omg.CORBA.portable (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

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.

See:
Description

Interface Summary
BoxedValueHelper |
CustomValue | An extension of ValueBase that is implemented by custom value types.
IDLEntity | An interface with no members whose only purpose is to serve as a marker indicating that an implementing class is a Java value type from IDL that has a corresponding Helper class.
InvokeHandler | This interface provides a dispatching mechanism for an incoming call.
ResponseHandler | 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.
Streamable | The base class for the Holder classess of all complex IDL types.
StreamableValue | Defines the base type for all non-boxed IDL valuetypes that are not custom marshaled.
ValueBase | The generated Java classes corresponding to valuetype IDL types implement this interface.
ValueFactory | The ValueFactory interface is the native mapping for the IDL type CORBA::ValueFactory.

Class Summary
Delegate | Specifies a portable API for ORB-vendor-specific implementation of the org.omg.CORBA.Object methods.
InputStream | InputStream is the Java API for reading IDL types from CDR marshal streams.
ObjectImpl | The common base class for all stub classes; provides default implementations of the org.omg.CORBA.Object methods.
OutputStream | OuputStream is the Java API for writing IDL types to CDR marshal streams.
ServantObject | 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.

Exception Summary
ApplicationException | This class is used for reporting application level exceptions between ORBs and stubs.
IndirectionException | The Indirection exception is a Java specific system exception.
RemarshalException | This class is used for reporting locate forward exceptions and object forward GIOP messages back to the ORB.
UnknownException | The org.omg.CORBA.portable.UnknownException is used for reporting unknown exceptions between ties and ORBs and between ORBs and stubs.

Package org.omg.CORBA.portable Description

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. Stubs and other code, generated either from IDL or interfaces written in the Java programming language, can call into these ORB APIs.

CORBA Features Throwing NO_IMPLEMENT() Exceptions

Some methods throw NO_IMPLEMENT() exceptions by default, but ORB vendors can override them to provide real implementations. The ORB included in Sun's release of the Java[tm] 2 Platform, Standard Edition, includes implementations for the following methods.

List of Unimplemented Features in Package org.omg.CORBA.portable

Unimplemented Interfaces in package org.omg.CORBA.portable

  • InvokeHandler
  • ResponseHandler

Unimplemented Methods in package org.omg.CORBA.portable

  • InputStream
    • public int read()
    • public.math.BigDecimal read_fixed()
    • public org.omg.CORBA.Context read_Context()
    • public org.omg.CORBA.Object read_Object(java.lang.Class clz)
    • public org.omg.CORBA.ORB orb()
  • OutputStream
    • public org.omg.CORBA.ORB orb()
    • public void write_Context(org.omg.CORBA.Context ctx, org.omg.CORBA.ContextList contexts)
    • public void write_fixed(java.math.BigDecimal value)
    • public void write(int b)
  • Delegate
    • public void releaseReply(org.omg.CORBA.Object self, InputStream input)
    • public InputStream invoke(org.omg.CORBA.Object self, OutputStream output)
    • public OutputStream request(org.omg.CORBA.Object self, String operation, boolean responseExpected)
    • public org.omg.CORBA.Object set_policy_override(org.omg.CORBA.Object self, org.omg.CORBA.Policy[] policies, org.omg.CORBA.SetOverrideType set_add)
    • public org.omg.CORBA.DomainManager[] get_domain_managers( org.omg.CORBA.Object self)
    • public org.omg.CORBA.Policy get_policy(org.omg.CORBA.Object self, int policy_type)

Since:
JDK1.2
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


org.omg.CORBA.portable Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package org.omg.CORBA.portable

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class org.omg.CORBA.portable.Delegate
    • class java.io.InputStream
      • class org.omg.CORBA.portable.InputStream
    • class org.omg.CORBA.portable.ObjectImpl (implements org.omg.CORBA.Object)
    • class java.io.OutputStream
      • class org.omg.CORBA.portable.OutputStream
    • class org.omg.CORBA.portable.ServantObject
    • class java.lang.Throwable (implements java.io.Serializable)
      • class java.lang.Exception
        • class org.omg.CORBA.portable.ApplicationException
        • class org.omg.CORBA.portable.RemarshalException
        • class java.lang.RuntimeException
          • class org.omg.CORBA.SystemException
            • class org.omg.CORBA.portable.IndirectionException
            • class org.omg.CORBA.portable.UnknownException

Interface Hierarchy

  • interface org.omg.CORBA.portable.BoxedValueHelper
  • interface org.omg.CORBA.CustomMarshal
    • interface org.omg.CORBA.portable.CustomValue (also extends org.omg.CORBA.portable.ValueBase)
  • interface org.omg.CORBA.portable.InvokeHandler
  • interface org.omg.CORBA.portable.ResponseHandler
  • interface java.io.Serializable
    • interface org.omg.CORBA.portable.IDLEntity
      • interface org.omg.CORBA.portable.ValueBase
        • interface org.omg.CORBA.portable.CustomValue (also extends org.omg.CORBA.CustomMarshal)
        • interface org.omg.CORBA.portable.StreamableValue (also extends org.omg.CORBA.portable.Streamable)
  • interface org.omg.CORBA.portable.Streamable
    • interface org.omg.CORBA.portable.StreamableValue (also extends org.omg.CORBA.portable.ValueBase)
  • interface org.omg.CORBA.portable.ValueFactory
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package org.omg.CORBA.portable (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
org.omg.CORBA.portable

Packages that use org.omg.CORBA.portable
javax.rmi.CORBA | Contains portability APIs for RMI-IIOP.
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 | Provides the exceptions used with the DynAny interface (InvalidValue, Invalid, InvalidSeq, and TypeMismatch).
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.TypeCodePackage | Provides the user-defined exceptions BadKind and Bounds, which are thrown by methods in in the class TypeCode.
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_2_3 | The CORBA_2_3 package defines additions to existing CORBA interfaces in the Java 2 Standard Edition. 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 | Provides methods for the input and output of value types, and contains other updates to the org/omg/CORBA/portable package.
org.omg.CosNaming | Provides a naming service for Java IDL.
org.omg.CosNaming.NamingContextExtPackage | This package contains the following classes, which are used in org.omg.CosNaming.NamingContextExt:
org.omg.CosNaming.NamingContextPackage | This package contains Exception classes for the org.omg.CosNaming 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 | 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 | 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 | 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 | 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 | This package contains the exceptions specified in the IOP::CodeFactory interface (as part of the Portable Interceptors spec).
org.omg.IOP.CodecPackage | This package is generated from the IOP::Codec IDL interface definition.
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 | 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 | 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 | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.
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 | Encapsulates the processing state of the POAs it is associated with.
org.omg.PortableServer.POAPackage | Allows programmers to construct object implementations that are portable between different ORB products.
org.omg.PortableServer.ServantLocatorPackage | Provides classes and interfaces for locating the servant.
org.omg.SendingContext | Provides support for the marshalling of value types.
org.omg.stub.java.rmi | Contains RMI-IIOP Stubs for the Remote types that occur in the java.rmi package.

Classes in org.omg.CORBA.portable used by javax.rmi.CORBA
InputStream
InputStream is the Java API for reading IDL types from CDR marshal streams.
InvokeHandler
This interface provides a dispatching mechanism for an incoming call.
ObjectImpl
The common base class for all stub classes; provides default implementations of the org.omg.CORBA.Object methods.
OutputStream
OuputStream is the Java API for writing IDL types to CDR marshal streams.

Classes in org.omg.CORBA.portable used by org.omg.CORBA
ApplicationException
This class is used for reporting application level exceptions between ORBs and stubs.
BoxedValueHelper
Delegate
Specifies a portable API for ORB-vendor-specific implementation of the org.omg.CORBA.Object methods.
IDLEntity
An interface with no members whose only purpose is to serve as a marker indicating that an implementing class is a Java value type from IDL that has a corresponding Helper class.
InputStream
InputStream is the Java API for reading IDL types from CDR marshal streams.
ObjectImpl
The common base class for all stub classes; provides default implementations of the org.omg.CORBA.Object methods.
OutputStream
OuputStream is the Java API for writing IDL types to CDR marshal streams.
RemarshalException
This class is used for reporting locate forward exceptions and object forward GIOP messages back to the ORB.
ServantObject
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.
Streamable
The base class for the Holder classess of all complex IDL types.
ValueBase
The generated Java classes corresponding to valuetype IDL types implement this interface.

Classes in org.omg.CORBA.portable used by org.omg.CORBA.DynAnyPackage
IDLEntity
An interface with no members whose only purpose is to serve as a marker indicating that an implementing class is a Java value type from IDL that has a corresponding Helper class.

Classes in org.omg.CORBA.portable used by org.omg.CORBA.ORBPackage
IDLEntity
An interface with no members whose only purpose is to serve as a marker indicating that an implementing class is a Java value type from IDL that has a corresponding Helper class.

Classes in org.omg.CORBA.portable used by org.omg.CORBA.TypeCodePackage
IDLEntity
An interface with no members whose only purpose is to serve as a marker indicating that an implementing class is a Java value type from IDL that has a corresponding Helper class.

Classes in org.omg.CORBA.portable used by org.omg.CORBA.portable
ApplicationException
This class is used for reporting application level exceptions between ORBs and stubs.
Delegate
Specifies a portable API for ORB-vendor-specific implementation of the org.omg.CORBA.Object methods.
IDLEntity
An interface with no members whose only purpose is to serve as a marker indicating that an implementing class is a Java value type from IDL that has a corresponding Helper class.
InputStream
InputStream is the Java API for reading IDL types from CDR marshal streams.
OutputStream
OuputStream is the Java API for writing IDL types to CDR marshal streams.
RemarshalException
This class is used for reporting locate forward exceptions and object forward GIOP messages back to the ORB.
ResponseHandler
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.
ServantObject
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.
Streamable
The base class for the Holder classess of all complex IDL types.
ValueBase
The generated Java classes corresponding to valuetype IDL types implement this interface.

Classes in org.omg.CORBA.portable used by org.omg.CORBA_2_3
ValueFactory
The ValueFactory interface is the native mapping for the IDL type CORBA::ValueFactory.

Classes in org.omg.CORBA.portable used by org.omg.CORBA_2_3.portable
BoxedValueHelper
Delegate
Specifies a portable API for ORB-vendor-specific implementation of the org.omg.CORBA.Object methods.
InputStream
InputStream is the Java API for reading IDL types from CDR marshal streams.
ObjectImpl
The common base class for all stub classes; provides default implementations of the org.omg.CORBA.Object methods.
OutputStream
OuputStream is the Java API for writing IDL types to CDR marshal streams.

Classes in org.omg.CORBA.portable used by org.omg.CosNaming
IDLEntity
An interface with no members whose only purpose is to serve as a marker indicating that an implementing class is a Java value type from IDL that has a corresponding Helper class.
InputStream
InputStream is the Java API for reading IDL types from CDR marshal streams.
InvokeHandler
This interface provides a dispatching mechanism for an incoming call.
ObjectImpl
The common base class for all stub classes; provides default implementations of the org.omg.CORBA.Object methods.
OutputStream
OuputStream is the Java API for writing IDL types to CDR marshal streams.
ResponseHandler
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.
Streamable
The base class for the Holder classess of all complex IDL types.

Classes in org.omg.CORBA.portable used by org.omg.CosNaming.NamingContextExtPackage
IDLEntity
An interface with no members whose only purpose is to serve as a marker indicating that an implementing class is a Java value type from IDL that has a corresponding Helper class.
InputStream
InputStream is the Java API for reading IDL types from CDR marshal streams.
OutputStream
OuputStream is the Java API for writing IDL types to CDR marshal streams.
Streamable
The base class for the Holder classess of all complex IDL types.

Classes in org.omg.CORBA.portable used by org.omg.CosNaming.NamingContextPackage
IDLEntity
An interface with no members whose only purpose is to serve as a marker indicating that an implementing class is a Java value type from IDL that has a corresponding Helper class.
InputStream
InputStream is the Java API for reading IDL types from CDR marshal streams.
OutputStream
OuputStream is the Java API for writing IDL types to CDR marshal streams.
Streamable
The base class for the Holder classess of all complex IDL types.

Classes in org.omg.CORBA.portable used by org.omg.Dynamic
IDLEntity
An interface with no members whose only purpose is to serve as a marker indicating that an implementing class is a Java value type from IDL that has a corresponding Helper class.

Classes in org.omg.CORBA.portable used by org.omg.DynamicAny
IDLEntity
An interface with no members whose only purpose is to serve as a marker indicating that an implementing class is a Java value type from IDL that has a corresponding Helper class.
InputStream
InputStream is the Java API for reading IDL types from CDR marshal streams.
ObjectImpl
The common base class for all stub classes; provides default implementations of the org.omg.CORBA.Object methods.
OutputStream
OuputStream is the Java API for writing IDL types to CDR marshal streams.

Classes in org.omg.CORBA.portable used by org.omg.DynamicAny.DynAnyFactoryPackage
InputStream
InputStream is the Java API for reading IDL types from CDR marshal streams.
OutputStream
OuputStream is the Java API for writing IDL types to CDR marshal streams.

Classes in org.omg.CORBA.portable used by org.omg.DynamicAny.DynAnyPackage
InputStream
InputStream is the Java API for reading IDL types from CDR marshal streams.
OutputStream
OuputStream is the Java API for writing IDL types to CDR marshal streams.

Classes in org.omg.CORBA.portable used by org.omg.IOP
IDLEntity
An interface with no members whose only purpose is to serve as a marker indicating that an implementing class is a Java value type from IDL that has a corresponding Helper class.
InputStream
InputStream is the Java API for reading IDL types from CDR marshal streams.
OutputStream
OuputStream is the Java API for writing IDL types to CDR marshal streams.
Streamable
The base class for the Holder classess of all complex IDL types.

Classes in org.omg.CORBA.portable used by org.omg.IOP.CodecFactoryPackage
IDLEntity
An interface with no members whose only purpose is to serve as a marker indicating that an implementing class is a Java value type from IDL that has a corresponding Helper class.
InputStream
InputStream is the Java API for reading IDL types from CDR marshal streams.
OutputStream
OuputStream is the Java API for writing IDL types to CDR marshal streams.

Classes in org.omg.CORBA.portable used by org.omg.IOP.CodecPackage
IDLEntity
An interface with no members whose only purpose is to serve as a marker indicating that an implementing class is a Java value type from IDL that has a corresponding Helper class.
InputStream
InputStream is the Java API for reading IDL types from CDR marshal streams.
OutputStream
OuputStream is the Java API for writing IDL types to CDR marshal streams.

Classes in org.omg.CORBA.portable used by org.omg.Messaging
InputStream
InputStream is the Java API for reading IDL types from CDR marshal streams.
OutputStream
OuputStream is the Java API for writing IDL types to CDR marshal streams.

Classes in org.omg.CORBA.portable used by org.omg.PortableInterceptor
IDLEntity
An interface with no members whose only purpose is to serve as a marker indicating that an implementing class is a Java value type from IDL that has a corresponding Helper class.
InputStream
InputStream is the Java API for reading IDL types from CDR marshal streams.
OutputStream
OuputStream is the Java API for writing IDL types to CDR marshal streams.

Classes in org.omg.CORBA.portable used by org.omg.PortableInterceptor.ORBInitInfoPackage
IDLEntity
An interface with no members whose only purpose is to serve as a marker indicating that an implementing class is a Java value type from IDL that has a corresponding Helper class.
InputStream
InputStream is the Java API for reading IDL types from CDR marshal streams.
OutputStream
OuputStream is the Java API for writing IDL types to CDR marshal streams.

Classes in org.omg.CORBA.portable used by org.omg.PortableServer
IDLEntity
An interface with no members whose only purpose is to serve as a marker indicating that an implementing class is a Java value type from IDL that has a corresponding Helper class.
InputStream
InputStream is the Java API for reading IDL types from CDR marshal streams.
InvokeHandler
This interface provides a dispatching mechanism for an incoming call.
ObjectImpl
The common base class for all stub classes; provides default implementations of the org.omg.CORBA.Object methods.
OutputStream
OuputStream is the Java API for writing IDL types to CDR marshal streams.
ResponseHandler
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.

Classes in org.omg.CORBA.portable used by org.omg.PortableServer.CurrentPackage
IDLEntity
An interface with no members whose only purpose is to serve as a marker indicating that an implementing class is a Java value type from IDL that has a corresponding Helper class.
InputStream
InputStream is the Java API for reading IDL types from CDR marshal streams.
OutputStream
OuputStream is the Java API for writing IDL types to CDR marshal streams.

Classes in org.omg.CORBA.portable used by org.omg.PortableServer.POAManagerPackage
IDLEntity
An interface with no members whose only purpose is to serve as a marker indicating that an implementing class is a Java value type from IDL that has a corresponding Helper class.
InputStream
InputStream is the Java API for reading IDL types from CDR marshal streams.
OutputStream
OuputStream is the Java API for writing IDL types to CDR marshal streams.

Classes in org.omg.CORBA.portable used by org.omg.PortableServer.POAPackage
IDLEntity
An interface with no members whose only purpose is to serve as a marker indicating that an implementing class is a Java value type from IDL that has a corresponding Helper class.
InputStream
InputStream is the Java API for reading IDL types from CDR marshal streams.
OutputStream
OuputStream is the Java API for writing IDL types to CDR marshal streams.

Classes in org.omg.CORBA.portable used by org.omg.PortableServer.ServantLocatorPackage
InputStream
InputStream is the Java API for reading IDL types from CDR marshal streams.
OutputStream
OuputStream is the Java API for writing IDL types to CDR marshal streams.
Streamable
The base class for the Holder classess of all complex IDL types.

Classes in org.omg.CORBA.portable used by org.omg.SendingContext
IDLEntity
An interface with no members whose only purpose is to serve as a marker indicating that an implementing class is a Java value type from IDL that has a corresponding Helper class.

Classes in org.omg.CORBA.portable used by org.omg.stub.java.rmi
ObjectImpl
The common base class for all stub classes; provides default implementations of the org.omg.CORBA.Object methods.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


RemarshalException (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA.portable
Class RemarshalException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.portable.RemarshalException
All Implemented Interfaces:
Serializable
public final class RemarshalException
extends Exception

This class is used for reporting locate forward exceptions and object forward GIOP messages back to the ORB. In this case the ORB must remarshal the request before trying again. Stubs which use the stream-based model shall catch the RemarshalException which is potentially thrown from the _invoke() method of ObjectImpl. Upon catching the exception, the stub shall immediately remarshal the request by calling _request(), marshalling the arguments (if any), and then calling _invoke(). The stub shall repeat this process until _invoke() returns normally or raises some exception other than RemarshalException.

Constructor Summary
RemarshalException()
Constructs a RemarshalException.
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

RemarshalException

public RemarshalException()
Constructs a RemarshalException.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ResponseHandler (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA.portable
Interface ResponseHandler

public interface ResponseHandler

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.

Method Summary
OutputStream | createExceptionReply() Called by the servant during a method invocation.
OutputStream | createReply() Called by the servant during a method invocation.

Method Detail

createReply

public OutputStream createReply()
Called by the servant during a method invocation. The servant should call this method to create a reply marshal buffer if no exception occurred.

Returns:
an OutputStream suitable for marshalling the reply.
See Also:
portable package comments for unimplemented features

createExceptionReply

public OutputStream createExceptionReply()
Called by the servant during a method invocation. The servant should call this method to create a reply marshal buffer if a user exception occurred.

Returns:
an OutputStream suitable for marshalling the exception ID and the user exception body.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ServantObject (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA.portable
Class ServantObject

java.lang.Object
    extended by org.omg.CORBA.portable.ServantObject
public class ServantObject
extends Object

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. clients and servers residing in the same Java VM). The local stub API is supported via three additional methods on ObjectImpl and Delegate. ORB vendors may subclass this class to return additional request state that may be required by their implementations.

See Also:
ObjectImpl, Delegate

Field Summary
 Object servant
The real servant.
Constructor Summary
ServantObject()
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

servant

public Object servant
The real servant. The local stub may cast this field to the expected type, and then invoke the operation directly. Note, the object may or may not be the actual servant instance.

Constructor Detail

ServantObject

public ServantObject()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Streamable (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA.portable
Interface Streamable

All Known Subinterfaces:
StreamableValue
All Known Implementing Classes:
AlreadyBoundHolder, AnyHolder, AnySeqHolder, BindingHolder, BindingIteratorHolder, BindingListHolder, BindingTypeHolder, BooleanHolder, BooleanSeqHolder, ByteHolder, CannotProceedHolder, CharHolder, CharSeqHolder, CookieHolder, CurrentHolder, DoubleHolder, DoubleSeqHolder, FixedHolder, FloatHolder, FloatSeqHolder, IntHolder, InvalidAddressHolder, InvalidNameHolder, IORHolder, LongHolder, LongLongSeqHolder, LongSeqHolder, MultipleComponentProfileHolder, NameComponentHolder, NameHolder, NamingContextExtHolder, NamingContextHolder, NotEmptyHolder, NotFoundHolder, NotFoundReasonHolder, ObjectHolder, OctetSeqHolder, ParameterModeHolder, PolicyErrorHolder, PolicyHolder, PolicyListHolder, PrincipalHolder, ServiceContextHolder, ServiceContextListHolder, ServiceInformationHolder, ShortHolder, ShortSeqHolder, StringHolder, StringSeqHolder, TaggedComponentHolder, TaggedProfileHolder, TypeCodeHolder, ULongLongSeqHolder, ULongSeqHolder, UnknownUserExceptionHolder, UShortSeqHolder, ValueBaseHolder, WCharSeqHolder, WrongTransactionHolder, WStringSeqHolder
public interface Streamable

The base class for the Holder classess of all complex IDL types. The ORB treats all generated Holders as Streamable to invoke the methods for marshalling and unmarshalling.

Since:
JDK1.2

Method Summary
void | _read(InputStream istream) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream ostream) Marshals to ostream the value in the value field of the Holder.

Method Detail

_read

public void _read(InputStream istream)
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Parameters:
istream - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream ostream)
Marshals to ostream the value in the value field of the Holder.

Parameters:
ostream - the CDR OutputStream

_type

public TypeCode _type()
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


StreamableValue (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA.portable
Interface StreamableValue

All Superinterfaces:
IDLEntity, Serializable, Streamable, ValueBase
public interface StreamableValue
extends Streamable, ValueBase

Defines the base type for all non-boxed IDL valuetypes that are not custom marshaled. All value types implement ValueBase either directly or indirectly by implementing either the StreamableValue or CustomValue interface.

Methods inherited from interface org.omg.CORBA.portable.Streamable
_read, _type, _write
Methods inherited from interface org.omg.CORBA.portable.ValueBase
_truncatable_ids

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


UnknownException (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA.portable
Class UnknownException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by org.omg.CORBA.SystemException
                    extended by org.omg.CORBA.portable.UnknownException
All Implemented Interfaces:
Serializable
public class UnknownException
extends SystemException

The org.omg.CORBA.portable.UnknownException is used for reporting unknown exceptions between ties and ORBs and between ORBs and stubs. It provides a Java representation of an UNKNOWN system exception that has an UnknownExceptionInfo service context. If the CORBA system exception org.omg.CORBA.portable.UnknownException is thrown, then the stub does one of the following: (1) Translates it to org.omg.CORBA.UNKNOWN. (2) Translates it to the nested exception that the UnknownException contains. (3) Passes it on directly to the user.

Field Summary
 Throwable originalEx
A throwable--the original exception that was wrapped in a CORBA UnknownException.
Fields inherited from class org.omg.CORBA.SystemException
completed, minor
Constructor Summary
UnknownException(Throwable ex)
Constructs an UnknownException object.
Methods inherited from class org.omg.CORBA.SystemException
toString
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

originalEx

public Throwable originalEx
A throwable--the original exception that was wrapped in a CORBA UnknownException.

Constructor Detail

UnknownException

public UnknownException(Throwable ex)
Constructs an UnknownException object.

Parameters:
ex - a Throwable object--to be wrapped in this exception.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


ValueBase (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA.portable
Interface ValueBase

All Superinterfaces:
IDLEntity, Serializable
All Known Subinterfaces:
CustomValue, DataInputStream, DataOutputStream, StreamableValue
public interface ValueBase
extends IDLEntity

The generated Java classes corresponding to valuetype IDL types implement this interface. In other words, the Java mapping of valuetype objects implement the ValueBase interface. The generated Java class for valuetype's shall provide an implementation of the ValueBase interface for the corresponding value type. For value types that are streamable (i.e. non-custom), the generated Java class shall also provide an implementation for the org.omg.CORBA.portable.Streamable interface. (CORBA::ValueBase is mapped to java.io.Serializable.)

Method Summary
 String[] _truncatable_ids()
Provides truncatable repository ids.

Method Detail

_truncatable_ids

public String[] _truncatable_ids()
Provides truncatable repository ids.

Returns:
a String array--list of truncatable repository ids.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ValueFactory (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA.portable
Interface ValueFactory

public interface ValueFactory

The ValueFactory interface is the native mapping for the IDL type CORBA::ValueFactory. The read_value() method is called by the ORB runtime while in the process of unmarshaling a value type. A user shall implement this method as part of implementing a type specific value factory. In the implementation, the user shall call is.read_value(java.io.Serializable) with a uninitialized valuetype to use for unmarshaling. The value returned by the stream is the same value passed in, with all the data unmarshaled.

See Also:
ORB

Method Summary
 Serializable read_value(InputStream is)
Is called by the ORB runtime while in the process of unmarshaling a value type.

Method Detail

read_value

public Serializable read_value(InputStream is)
Is called by the ORB runtime while in the process of unmarshaling a value type. A user shall implement this method as part of implementing a type specific value factory.

Parameters:
is - an InputStream object--from which the value will be read.
Returns:
a Serializable object--the value read off of "is" Input stream.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Uses of Class org.omg.CORBA.portable.ApplicationException (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.portable.ApplicationException

Packages that use ApplicationException
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.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.

Uses of ApplicationException in org.omg.CORBA

Methods in org.omg.CORBA that throw ApplicationException
 InputStream LocalObject._invoke(OutputStream output)
Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.

Uses of ApplicationException in org.omg.CORBA.portable

Methods in org.omg.CORBA.portable that throw ApplicationException
InputStream | Delegate.invoke(Object self, OutputStream output) invoke is called by a stub to invoke an operation.
InputStream | ObjectImpl._invoke(OutputStream output) Invokes an operation and returns an InputStream object for reading the response.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.portable.BoxedValueHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.portable.BoxedValueHelper

Packages that use BoxedValueHelper
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_2_3.portable | Provides methods for the input and output of value types, and contains other updates to the org/omg/CORBA/portable package.

Uses of BoxedValueHelper in org.omg.CORBA

Classes in org.omg.CORBA that implement BoxedValueHelper
class | StringValueHelper The Helper for StringValue.
class | WStringValueHelper 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

Uses of BoxedValueHelper in org.omg.CORBA_2_3.portable

Methods in org.omg.CORBA_2_3.portable with parameters of type BoxedValueHelper
void | OutputStream.write_value(Serializable value, BoxedValueHelper factory) Marshals a value type to the output stream.
Serializable | InputStream.read_value(BoxedValueHelper factory) Unmarshalls a value type from the input stream.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.portable.CustomValue (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.portable.CustomValue

No usage of org.omg.CORBA.portable.CustomValue

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.portable.Delegate (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.portable.Delegate

Packages that use Delegate
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_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.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.

Uses of Delegate in org.omg.CORBA

Constructors in org.omg.CORBA with parameters of type Delegate
_PolicyStub(Delegate delegate)
Constructs a _PolicyStub object initialized with the given Delegate object.
_IDLTypeStub(Delegate delegate)
Constructs an _IDLTypeStub object initialized with the given Delegate object.

Uses of Delegate in org.omg.CORBA_2_3.portable

Subclasses of Delegate in org.omg.CORBA_2_3.portable
 class Delegate
Delegate class provides the ORB vendor specific implementation of CORBA object.

Uses of Delegate in org.omg.CORBA.portable

Methods in org.omg.CORBA.portable that return Delegate
 Delegate ObjectImpl._get_delegate()
Retrieves the reference to the vendor-specific Delegate object to which this ObjectImpl object delegates all methods invoked on it.

Methods in org.omg.CORBA.portable with parameters of type Delegate
 void ObjectImpl._set_delegate(Delegate delegate)
Sets the Delegate for this ObjectImpl instance to the given Delegate object.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.portable.IDLEntity (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.portable.IDLEntity

Packages that use IDLEntity
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 | Provides the exceptions used with the DynAny interface (InvalidValue, Invalid, InvalidSeq, and TypeMismatch).
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 | 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 | Provides the user-defined exceptions BadKind and Bounds, which are thrown by methods in in the class TypeCode.
org.omg.CosNaming | Provides a naming service for Java IDL.
org.omg.CosNaming.NamingContextExtPackage | This package contains the following classes, which are used in org.omg.CosNaming.NamingContextExt:
org.omg.CosNaming.NamingContextPackage | This package contains Exception classes for the org.omg.CosNaming 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 | 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.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 | This package contains the exceptions specified in the IOP::CodeFactory interface (as part of the Portable Interceptors spec).
org.omg.IOP.CodecPackage | This package is generated from the IOP::Codec IDL interface definition.
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 | 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 | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.
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 | Encapsulates the processing state of the POAs it is associated with.
org.omg.PortableServer.POAPackage | Allows programmers to construct object implementations that are portable between different ORB products.
org.omg.SendingContext | Provides support for the marshalling of value types.

Uses of IDLEntity in org.omg.CORBA

Subinterfaces of IDLEntity in org.omg.CORBA
interface | Current Interfaces derived from the Current interface enable ORB and CORBA services to provide access to information (context) associated with the thread of execution in which they are running.
interface | DataInputStream Defines the methods used to read primitive data types from input streams for unmarshaling custom value types.
interface | DataOutputStream Defines the methods used to write primitive data types to output streams for marshalling custom value types.
interface | DomainManager Provides mechanisms for establishing and navigating relationships to superior and subordinate domains, as well as for creating and accessing policies.
interface | IDLType An abstract interface inherited by all Interface Repository (IR) objects that represent OMG IDL types.
interface | IRObject An IRObject IDL interface represents the most generic interface from which all other Interface Repository interfaces are derived, even the Repository itself.
interface | Policy Interfaces derived from the Policy interface allow an ORB or CORBA service access to certain choices that affect its operation.

Classes in org.omg.CORBA that implement IDLEntity
class | _IDLTypeStub The Stub for IDLType.
class | _PolicyStub The Stub for Policy.
class | Any Serves as a container for any data that can be described in IDL or for any IDL primitive type.
class | Bounds A user exception thrown when a parameter is not within the legal bounds for the object that a method is trying to access.
class | CompletionStatus An object that indicates whether a method had completed running when a SystemException was thrown.
class | DefinitionKind The class that provides the constants used to identify the type of an Interface Repository object.
class | NameValuePair Associates a name with a value that is an attribute of an IDL struct, and is used in the DynStruct APIs.
class | ParameterMode Enumeration of parameter modes for Parameter.
class | PolicyError A user exception thrown when a policy error occurs.
class | ServiceDetail 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.
class | ServiceInformation 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.
class | SetOverrideType 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.
class | StructMember 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.
class | TypeCode A container for information about a specific CORBA data type.
class | UnionMember A description in the Interface Repository of a member of an IDL union.
class | UnknownUserException A class that contains user exceptions returned by the server.
class | UserException The root class for CORBA IDL-defined user exceptions.
class | ValueMember A description in the Interface Repository of a member of a value object.
class | WrongTransaction The CORBA WrongTransaction user-defined exception.

Uses of IDLEntity in org.omg.CORBA.DynAnyPackage

Classes in org.omg.CORBA.DynAnyPackage that implement IDLEntity
class | Invalid Invalid is thrown by dynamic any operations when a bad DynAny or Any is passed as a parameter.
class | InvalidSeq The InvalidSeq exception is thrown by all operations on dynamic anys that take a sequence (Java array) as an argument, when that sequence is invalid.
class | InvalidValue
class | TypeMismatch TypeMismatch is thrown by dynamic any accessor methods when type of the actual contents do not match what is trying to be accessed.

Uses of IDLEntity in org.omg.CORBA.ORBPackage

Classes in org.omg.CORBA.ORBPackage that implement IDLEntity
class | InconsistentTypeCode InconsistentTypeCode is thrown when an attempt is made to create a dynamic any with a type code that does not match the particular subclass of DynAny.
class | InvalidName The InvalidName exception is raised when ORB.resolve_initial_references is passed a name for which there is no initial reference.

Uses of IDLEntity in org.omg.CORBA.portable

Subinterfaces of IDLEntity in org.omg.CORBA.portable
interface | CustomValue An extension of ValueBase that is implemented by custom value types.
interface | StreamableValue Defines the base type for all non-boxed IDL valuetypes that are not custom marshaled.
interface | ValueBase The generated Java classes corresponding to valuetype IDL types implement this interface.

Uses of IDLEntity in org.omg.CORBA.TypeCodePackage

Classes in org.omg.CORBA.TypeCodePackage that implement IDLEntity
 class BadKind
The exception BadKind is thrown when an inappropriate operation is invoked on a TypeCode object.

Uses of IDLEntity in org.omg.CosNaming

Subinterfaces of IDLEntity in org.omg.CosNaming
interface | BindingIterator The BindingIterator interface allows a client to iterate through the bindings using the next_one or next_n operations.
interface | NamingContext A naming context is an object that contains a set of name bindings in which each name is unique.
interface | NamingContextExt 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.

Classes in org.omg.CosNaming that implement IDLEntity
class | _BindingIteratorImplBase
class | _BindingIteratorStub The BindingIterator interface allows a client to iterate through the bindings using the next_one or next_n operations.
class | _NamingContextExtStub 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.
class | _NamingContextImplBase
class | _NamingContextStub A naming context is an object that contains a set of name bindings in which each name is unique.
class | Binding A name-to-object association is called a Binding.
class | BindingType Specifies whether the given binding is for a object (that is not a naming context) or for a naming context.
class | NameComponent Many of the operations defined on a naming context take names as parameters.

Uses of IDLEntity in org.omg.CosNaming.NamingContextExtPackage

Classes in org.omg.CosNaming.NamingContextExtPackage that implement IDLEntity
 class InvalidAddress
org/omg/CosNaming/NamingContextExtPackage/InvalidAddress.java .

Uses of IDLEntity in org.omg.CosNaming.NamingContextPackage

Classes in org.omg.CosNaming.NamingContextPackage that implement IDLEntity
class | AlreadyBound org/omg/CosNaming/NamingContextPackage/AlreadyBound.java .
class | CannotProceed org/omg/CosNaming/NamingContextPackage/CannotProceed.java .
class | NotEmpty org/omg/CosNaming/NamingContextPackage/NotEmpty.java .
class | NotFound org/omg/CosNaming/NamingContextPackage/NotFound.java .
class | NotFoundReason Indicates the reason for not able to resolve.

Uses of IDLEntity in org.omg.Dynamic

Classes in org.omg.Dynamic that implement IDLEntity
 class Parameter
NVList PIDL represented by ParameterList IDL.

Uses of IDLEntity in org.omg.DynamicAny

Subinterfaces of IDLEntity in org.omg.DynamicAny
interface | DynAny Any values can be dynamically interpreted (traversed) and constructed through DynAny objects.
interface | DynAnyFactory DynAny objects can be created by invoking operations on the DynAnyFactory object.
interface | DynArray DynArray objects support the manipulation of IDL arrays.
interface | DynEnum DynEnum objects support the manipulation of IDL enumerated values.
interface | DynFixed DynFixed objects support the manipulation of IDL fixed values.
interface | DynSequence DynSequence objects support the manipulation of IDL sequences.
interface | DynStruct DynStruct objects support the manipulation of IDL struct and exception values.
interface | DynUnion DynUnion objects support the manipulation of IDL unions.
interface | DynValue DynValue objects support the manipulation of IDL non-boxed value types.
interface | DynValueBox DynValueBox objects support the manipulation of IDL boxed value types.
interface | DynValueCommon DynValueCommon provides operations supported by both the DynValue and DynValueBox interfaces.

Classes in org.omg.DynamicAny that implement IDLEntity
class | _DynAnyFactoryStub DynAny objects can be created by invoking operations on the DynAnyFactory object.
class | _DynAnyStub Any values can be dynamically interpreted (traversed) and constructed through DynAny objects.
class | _DynArrayStub DynArray objects support the manipulation of IDL arrays.
class | _DynEnumStub DynEnum objects support the manipulation of IDL enumerated values.
class | _DynFixedStub DynFixed objects support the manipulation of IDL fixed values.
class | _DynSequenceStub DynSequence objects support the manipulation of IDL sequences.
class | _DynStructStub DynStruct objects support the manipulation of IDL struct and exception values.
class | _DynUnionStub DynUnion objects support the manipulation of IDL unions.
class | _DynValueStub DynValue objects support the manipulation of IDL non-boxed value types.
class | NameDynAnyPair NameDynAnyPairs associate a name with an DynAny object.

Uses of IDLEntity in org.omg.IOP

Subinterfaces of IDLEntity in org.omg.IOP
interface | Codec The formats of IOR components and service context data used by ORB services are often defined as CDR encapsulations encoding instances of IDL defined data types.
interface | CodecFactory Codecs are obtained from the CodecFactory.

Classes in org.omg.IOP that implement IDLEntity
class | Encoding Defines the encoding format of a Codec.
class | IOR Captures information about a object references, such as whether the object is null, what type it is, what protocols are supported, and what ORB services are available.
class | ServiceContext Service-specific information to be passed implicitly with requests and replies.
class | TaggedComponent TaggedComponents contained in TAG_INTERNET_IOP and TAG_MULTIPLE_COMPONENTS profiles are identified by unique numeric tags using a namespace distinct form that is used for profile tags.
class | TaggedProfile Object references have at least one tagged profile.

Uses of IDLEntity in org.omg.IOP.CodecFactoryPackage

Classes in org.omg.IOP.CodecFactoryPackage that implement IDLEntity
 class UnknownEncoding
org/omg/IOP/CodecFactoryPackage/UnknownEncoding.java .

Uses of IDLEntity in org.omg.IOP.CodecPackage

Classes in org.omg.IOP.CodecPackage that implement IDLEntity
class | FormatMismatch org/omg/IOP/CodecPackage/FormatMismatch.java .
class | InvalidTypeForEncoding org/omg/IOP/CodecPackage/InvalidTypeForEncoding.java .

Uses of IDLEntity in org.omg.PortableInterceptor

Subinterfaces of IDLEntity in org.omg.PortableInterceptor
interface | ClientRequestInfo Request Information, accessible to client-side request interceptors.
interface | ClientRequestInterceptor Client-side request interceptor.
interface | Interceptor All Portable Interceptors implement Interceptor.
interface | IORInfo Provides the server-side ORB service with access to the applicable policies during IOR construction and the ability to add components.
interface | IORInterceptor Interceptor used to establish tagged components in the profiles within an IOR.
interface | ORBInitializer Facilitates interceptor registration and ORB initialization.
interface | ORBInitInfo Passed to each ORBInitializer, allowing it to to register interceptors and perform other duties while the ORB is initializing.
interface | PolicyFactory Enables policy types to be constructed using CORBA.ORB.create_policy.
interface | RequestInfo Request Information, accessible to Interceptors.
interface | ServerRequestInfo Request Information, accessible to server-side request interceptors.
interface | ServerRequestInterceptor Server-side request interceptor.

Classes in org.omg.PortableInterceptor that implement IDLEntity
 class InvalidSlot
org/omg/PortableInterceptor/InvalidSlot.java .

Uses of IDLEntity in org.omg.PortableInterceptor.ORBInitInfoPackage

Classes in org.omg.PortableInterceptor.ORBInitInfoPackage that implement IDLEntity
 class DuplicateName
org/omg/PortableInterceptor/ORBInitInfoPackage/DuplicateName.java .

Uses of IDLEntity in org.omg.PortableServer

Subinterfaces of IDLEntity in org.omg.PortableServer
interface | AdapterActivator 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 find_POA is called with an activate parameter value of TRUE.
interface | IdAssignmentPolicy IdAssignmentPolicy specifies whether Object Ids in the created POA are generated by the application or by the ORB.
interface | IdUniquenessPolicy The IdUniquenessPolicy specifies whether the servants activated in the created POA must have unique object i identities.
interface | ImplicitActivationPolicy This policy specifies whether implicit activation of servants is supported in the created POA.
interface | LifespanPolicy The LifespanPolicy specifies the lifespan of the objects implemented in the created POA.
interface | POA A POA object manages the implementation of a collection of objects.
interface | POAManager Each POA object has an associated POAManager object.
interface | RequestProcessingPolicy This policy specifies how requests are processed by the created POA.
interface | ServantActivator When the POA has the RETAIN policy it uses servant managers that are ServantActivators.
interface | ServantLocator When the POA has the NON_RETAIN policy it uses servant managers that are ServantLocators.
interface | ServantManager 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.
interface | ServantRetentionPolicy This policy specifies whether the created POA retains active servants in an Active Object Map.
interface | ThreadPolicy The ThreadPolicy specifies the threading model used with the created POA.

Classes in org.omg.PortableServer that implement IDLEntity
class | _ServantActivatorStub When the POA has the RETAIN policy it uses servant managers that are ServantActivators.
class | _ServantLocatorStub When the POA has the NON_RETAIN policy it uses servant managers that are ServantLocators.
class | ForwardRequest org/omg/PortableServer/ForwardRequest.java .
class | IdAssignmentPolicyValue The IdAssignmentPolicyValue can have the following values.
class | IdUniquenessPolicyValue IdUniquenessPolicyValue can have the following values.
class | ImplicitActivationPolicyValue ImplicitActivationPolicyValue has the following semantics.
class | LifespanPolicyValue The LifespanPolicyValue can have the following values.
class | RequestProcessingPolicyValue The RequestProcessingPolicyValue can have the following values.
class | ServantRetentionPolicyValue ServantRetentionPolicyValue can have the following values.
class | ThreadPolicyValue The ThreadPolicyValue can have the following values.

Uses of IDLEntity in org.omg.PortableServer.CurrentPackage

Classes in org.omg.PortableServer.CurrentPackage that implement IDLEntity
 class NoContext
org/omg/PortableServer/CurrentPackage/NoContext.java .

Uses of IDLEntity in org.omg.PortableServer.POAManagerPackage

Classes in org.omg.PortableServer.POAManagerPackage that implement IDLEntity
class | AdapterInactive org/omg/PortableServer/POAManagerPackage/AdapterInactive.java .
class | State Specifies the states for the POAManager

Uses of IDLEntity in org.omg.PortableServer.POAPackage

Classes in org.omg.PortableServer.POAPackage that implement IDLEntity
class | AdapterAlreadyExists org/omg/PortableServer/POAPackage/AdapterAlreadyExists.java .
class | AdapterNonExistent org/omg/PortableServer/POAPackage/AdapterNonExistent.java .
class | InvalidPolicy org/omg/PortableServer/POAPackage/InvalidPolicy.java .
class | NoServant org/omg/PortableServer/POAPackage/NoServant.java .
class | ObjectAlreadyActive org/omg/PortableServer/POAPackage/ObjectAlreadyActive.java .
class | ObjectNotActive org/omg/PortableServer/POAPackage/ObjectNotActive.java .
class | ServantAlreadyActive org/omg/PortableServer/POAPackage/ServantAlreadyActive.java .
class | ServantNotActive org/omg/PortableServer/POAPackage/ServantNotActive.java .
class | WrongAdapter org/omg/PortableServer/POAPackage/WrongAdapter.java .
class | WrongPolicy org/omg/PortableServer/POAPackage/WrongPolicy.java .

Uses of IDLEntity in org.omg.SendingContext

Subinterfaces of IDLEntity in org.omg.SendingContext
 interface RunTime
Defines the base class that represents the Sending Context of a request.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.portable.IndirectionException (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.portable.IndirectionException

No usage of org.omg.CORBA.portable.IndirectionException

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.portable.InputStream (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.portable.InputStream

Packages that use InputStream
javax.rmi.CORBA | Contains portability APIs for RMI-IIOP.
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_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.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.CosNaming | Provides a naming service for Java IDL.
org.omg.CosNaming.NamingContextExtPackage | This package contains the following classes, which are used in org.omg.CosNaming.NamingContextExt:
org.omg.CosNaming.NamingContextPackage | This package contains Exception classes for the org.omg.CosNaming 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 | 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 | 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 | 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 | This package contains the exceptions specified in the IOP::CodeFactory interface (as part of the Portable Interceptors spec).
org.omg.IOP.CodecPackage | This package is generated from the IOP::Codec IDL interface definition.
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 | 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 | 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 | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.
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 | Encapsulates the processing state of the POAs it is associated with.
org.omg.PortableServer.POAPackage | Allows programmers to construct object implementations that are portable between different ORB products.
org.omg.PortableServer.ServantLocatorPackage | Provides classes and interfaces for locating the servant.

Uses of InputStream in javax.rmi.CORBA

Methods in javax.rmi.CORBA with parameters of type InputStream
 Serializable ValueHandler.readValue(InputStream in, int offset, Class clz, String repositoryID, RunTime sender)
Reads a value from the stream using Java semantics.
 Object UtilDelegate.readAny(InputStream in)
Delegation call for Util.readAny(org.omg.CORBA.portable.InputStream).
static Object Util.readAny(InputStream in)
Reads a java.lang.Object as a CORBA any.

Uses of InputStream in org.omg.CORBA

Methods in org.omg.CORBA that return InputStream
InputStream | LocalObject._invoke(OutputStream output) Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.
abstract InputStream | Any.create_input_stream() Creates an input stream from which this Any object's value can be unmarshalled.

Methods in org.omg.CORBA with parameters of type InputStream
void | WrongTransactionHolder._read(InputStream i)
void | WStringSeqHolder._read(InputStream i)
static String[] | WStringSeqHelper.read(InputStream istream)
void | UnknownUserExceptionHolder._read(InputStream i)
static UnknownUserException | UnknownUserExceptionHelper.read(InputStream istream)
void | StringSeqHolder._read(InputStream i)
static String[] | StringSeqHelper.read(InputStream istream)
void | PolicyErrorHolder._read(InputStream i)
static PolicyError | PolicyErrorHelper.read(InputStream istream)
static short | PolicyErrorCodeHelper.read(InputStream istream)
void | ParameterModeHolder._read(InputStream i)
static ParameterMode | ParameterModeHelper.read(InputStream istream)
void | LocalObject._releaseReply(InputStream input) Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.
static String | WStringValueHelper.read(InputStream istream)
Serializable | WStringValueHelper.read_value(InputStream istream)
static char[] | WCharSeqHelper.read(InputStream istream)
static short | VisibilityHelper.read(InputStream istream)
static String | VersionSpecHelper.read(InputStream istream)
static ValueMember | ValueMemberHelper.read(InputStream istream)
void | ValueBaseHolder._read(InputStream input) Reads from input and initalizes the value in the Holder with the unmarshalled data.
static Serializable | ValueBaseHelper.read(InputStream istream)
static UnionMember | UnionMemberHelper.read(InputStream istream)
static short[] | UShortSeqHelper.read(InputStream istream)
static int[] | ULongSeqHelper.read(InputStream istream)
static long[] | ULongLongSeqHelper.read(InputStream istream)
static StructMember | StructMemberHelper.read(InputStream istream)
static String | StringValueHelper.read(InputStream istream)
Serializable | StringValueHelper.read_value(InputStream istream)
static short[] | ShortSeqHelper.read(InputStream istream)
static SetOverrideType | SetOverrideTypeHelper.read(InputStream istream)
static String | RepositoryIdHelper.read(InputStream istream)
void | PolicyListHolder._read(InputStream i)
static Policy[] | PolicyListHelper.read(InputStream istream)
static int | PolicyTypeHelper.read(InputStream istream)
void | PolicyHolder._read(InputStream i)
static Policy | PolicyHelper.read(InputStream istream)
static byte[] | OctetSeqHelper.read(InputStream istream)
static NameValuePair | NameValuePairHelper.read(InputStream istream)
static int[] | LongSeqHelper.read(InputStream istream)
static long[] | LongLongSeqHelper.read(InputStream istream)
static String | IdentifierHelper.read(InputStream istream)
static IDLType | IDLTypeHelper.read(InputStream istream)
static float[] | FloatSeqHelper.read(InputStream istream)
static String | FieldNameHelper.read(InputStream istream)
static double[] | DoubleSeqHelper.read(InputStream istream)
static DefinitionKind | DefinitionKindHelper.read(InputStream istream)
void | DoubleSeqHolder._read(InputStream i)
void | FloatSeqHolder._read(InputStream i)
void | LongLongSeqHolder._read(InputStream i)
void | ULongLongSeqHolder._read(InputStream i)
void | ULongSeqHolder._read(InputStream i)
void | LongSeqHolder._read(InputStream i)
void | UShortSeqHolder._read(InputStream i)
void | ShortSeqHolder._read(InputStream i)
void | OctetSeqHolder._read(InputStream i)
void | WCharSeqHolder._read(InputStream i)
void | CurrentHolder._read(InputStream i)
static Current | CurrentHelper.read(InputStream istream)
static CompletionStatus | CompletionStatusHelper.read(InputStream istream)
void | CharSeqHolder._read(InputStream i)
static char[] | CharSeqHelper.read(InputStream istream)
void | BooleanSeqHolder._read(InputStream i)
static boolean[] | BooleanSeqHelper.read(InputStream istream)
void | AnySeqHolder._read(InputStream i)
static Any[] | AnySeqHelper.read(InputStream istream)
void | TypeCodeHolder._read(InputStream input) Reads from input and initalizes the value in this TypeCodeHolder object with the unmarshalled data.
void | StringHolder._read(InputStream input) Reads the unmarshalled data from input and assigns it to the value field of this StringHolder object.
void | ShortHolder._read(InputStream input) Reads from input and initalizes the value in this ShortHolder object with the unmarshalled data.
void | PrincipalHolder._read(InputStream input) Deprecated.
void | ObjectHolder._read(InputStream input) Reads from input and initalizes the value in this ObjectHolder object with the unmarshalled data.
void | LongHolder._read(InputStream input) Reads from input and initalizes the value in the Holder with the unmarshalled data.
void | IntHolder._read(InputStream input) Reads unmarshalled data from input and assigns it to the value field in this IntHolder object.
void | FloatHolder._read(InputStream input) Read a float from an input stream and initialize the value member with the float value.
void | FixedHolder._read(InputStream input) Read a fixed point value from the input stream and store it in the value member.
void | DoubleHolder._read(InputStream input) Read a double value from the input stream and store it in the value member.
void | CharHolder._read(InputStream input) Reads from input and initalizes the value in this CharHolder object with the unmarshalled data.
void | ByteHolder._read(InputStream input) Reads from input and initalizes the value in this ByteHolder object with the unmarshalled data.
void | BooleanHolder._read(InputStream input) Reads unmarshalled data from input and assigns it to this BooleanHolder object's value field.
void | AnyHolder._read(InputStream input) Reads from input and initalizes the value in the Holder with the unmarshalled data.
static ServiceDetail | ServiceDetailHelper.read(InputStream in)
static Object | ObjectHelper.read(InputStream istream)
static ServiceInformation | ServiceInformationHelper.read(InputStream in)
static WrongTransaction | WrongTransactionHelper.read(InputStream istream)
void | ServiceInformationHolder._read(InputStream in) Reads unmarshalled data from the input stream in and assigns it to the value field in this ServiceInformationHolder object.
abstract void | Any.read_value(InputStream is, TypeCode t) Reads off (unmarshals) the value of an Any object from the given input stream using the given typecode.

Uses of InputStream in org.omg.CORBA_2_3.portable

Subclasses of InputStream in org.omg.CORBA_2_3.portable
 class InputStream
InputStream provides for the reading of all of the mapped IDL types from the stream.

Uses of InputStream in org.omg.CORBA.portable

Methods in org.omg.CORBA.portable that return InputStream
InputStream | ApplicationException.getInputStream() Returns the input stream from which the exception data can be read as its parameters.
InputStream | Delegate.invoke(Object self, OutputStream output) invoke is called by a stub to invoke an operation.
InputStream | ObjectImpl._invoke(OutputStream output) Invokes an operation and returns an InputStream object for reading the response.
abstract InputStream | OutputStream.create_input_stream() Returns an input stream with the same buffer.

Methods in org.omg.CORBA.portable with parameters of type InputStream
Serializable | BoxedValueHelper.read_value(InputStream is)
void | Delegate.releaseReply(Object self, InputStream input) releaseReply may optionally be called by a stub to release a reply stream back to the ORB when the unmarshaling has completed.
void | ObjectImpl._releaseReply(InputStream input) Releases the given reply stream back to the ORB when unmarshalling has completed after a call to the method _invoke.
OutputStream | InvokeHandler._invoke(String method, InputStream input, ResponseHandler handler) Invoked by the ORB to dispatch a request to the servant.
void | Streamable._read(InputStream istream) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Constructors in org.omg.CORBA.portable with parameters of type InputStream
ApplicationException(String id, InputStream ins)
Constructs an ApplicationException from the CORBA repository ID of the exception and an input stream from which the exception data can be read as its parameters.

Uses of InputStream in org.omg.CosNaming

Methods in org.omg.CosNaming with parameters of type InputStream
OutputStream | NamingContextExtPOA._invoke(String $method, InputStream in, ResponseHandler $rh)
void | NamingContextExtHolder._read(InputStream i)
static NamingContextExt | NamingContextExtHelper.read(InputStream istream)
OutputStream | NamingContextPOA._invoke(String $method, InputStream in, ResponseHandler $rh)
void | NamingContextHolder._read(InputStream i)
static NamingContext | NamingContextHelper.read(InputStream istream)
void | NameHolder._read(InputStream i)
static NameComponent[] | NameHelper.read(InputStream istream)
void | NameComponentHolder._read(InputStream i)
static NameComponent | NameComponentHelper.read(InputStream istream)
void | BindingTypeHolder._read(InputStream i)
static BindingType | BindingTypeHelper.read(InputStream istream)
static Binding[] | BindingListHelper.read(InputStream istream)
void | BindingIteratorHolder._read(InputStream i)
static BindingIterator | BindingIteratorHelper.read(InputStream istream)
OutputStream | BindingIteratorPOA._invoke(String $method, InputStream in, ResponseHandler $rh)
void | BindingListHolder._read(InputStream i)
void | BindingHolder._read(InputStream i)
static Binding | BindingHelper.read(InputStream istream)
static String | IstringHelper.read(InputStream istream)

Uses of InputStream in org.omg.CosNaming.NamingContextExtPackage

Methods in org.omg.CosNaming.NamingContextExtPackage with parameters of type InputStream
static String | URLStringHelper.read(InputStream istream)
static String | StringNameHelper.read(InputStream istream)
void | InvalidAddressHolder._read(InputStream i)
static InvalidAddress | InvalidAddressHelper.read(InputStream istream)
static String | AddressHelper.read(InputStream istream)

Uses of InputStream in org.omg.CosNaming.NamingContextPackage

Methods in org.omg.CosNaming.NamingContextPackage with parameters of type InputStream
void | NotFoundReasonHolder._read(InputStream i)
static NotFoundReason | NotFoundReasonHelper.read(InputStream istream)
void | NotFoundHolder._read(InputStream i)
static NotFound | NotFoundHelper.read(InputStream istream)
void | NotEmptyHolder._read(InputStream i)
static NotEmpty | NotEmptyHelper.read(InputStream istream)
void | InvalidNameHolder._read(InputStream i)
static InvalidName | InvalidNameHelper.read(InputStream istream)
void | CannotProceedHolder._read(InputStream i)
static CannotProceed | CannotProceedHelper.read(InputStream istream)
void | AlreadyBoundHolder._read(InputStream i)
static AlreadyBound | AlreadyBoundHelper.read(InputStream istream)

Uses of InputStream in org.omg.DynamicAny

Methods in org.omg.DynamicAny with parameters of type InputStream
static NameValuePair[] | NameValuePairSeqHelper.read(InputStream istream)
static NameValuePair | NameValuePairHelper.read(InputStream istream)
static NameDynAnyPair[] | NameDynAnyPairSeqHelper.read(InputStream istream)
static DynSequence | DynSequenceHelper.read(InputStream istream)
static NameDynAnyPair | NameDynAnyPairHelper.read(InputStream istream)
static String | FieldNameHelper.read(InputStream istream)
static DynFixed | DynFixedHelper.read(InputStream istream)
static DynEnum | DynEnumHelper.read(InputStream istream)
static DynAny[] | DynAnySeqHelper.read(InputStream istream)
static DynArray | DynArrayHelper.read(InputStream istream)
static DynValue | DynValueHelper.read(InputStream istream)
static DynAny | DynAnyHelper.read(InputStream istream)
static DynUnion | DynUnionHelper.read(InputStream istream)
static DynAnyFactory | DynAnyFactoryHelper.read(InputStream istream)
static DynStruct | DynStructHelper.read(InputStream istream)
static Any[] | AnySeqHelper.read(InputStream istream)

Uses of InputStream in org.omg.DynamicAny.DynAnyFactoryPackage

Methods in org.omg.DynamicAny.DynAnyFactoryPackage with parameters of type InputStream
static InconsistentTypeCode InconsistentTypeCodeHelper.read(InputStream istream)

Uses of InputStream in org.omg.DynamicAny.DynAnyPackage

Methods in org.omg.DynamicAny.DynAnyPackage with parameters of type InputStream
static TypeMismatch | TypeMismatchHelper.read(InputStream istream)
static InvalidValue | InvalidValueHelper.read(InputStream istream)

Uses of InputStream in org.omg.IOP

Methods in org.omg.IOP with parameters of type InputStream
void | TaggedProfileHolder._read(InputStream i)
static TaggedProfile | TaggedProfileHelper.read(InputStream istream)
void | TaggedComponentHolder._read(InputStream i)
static TaggedComponent | TaggedComponentHelper.read(InputStream istream)
static int | ServiceIdHelper.read(InputStream istream)
void | ServiceContextListHolder._read(InputStream i)
static ServiceContext[] | ServiceContextListHelper.read(InputStream istream)
void | ServiceContextHolder._read(InputStream i)
static ServiceContext | ServiceContextHelper.read(InputStream istream)
static int | ProfileIdHelper.read(InputStream istream)
void | MultipleComponentProfileHolder._read(InputStream i)
static TaggedComponent[] | MultipleComponentProfileHelper.read(InputStream istream)
void | IORHolder._read(InputStream i)
static IOR | IORHelper.read(InputStream istream)
static int | ComponentIdHelper.read(InputStream istream)
static CodecFactory | CodecFactoryHelper.read(InputStream istream)

Uses of InputStream in org.omg.IOP.CodecFactoryPackage

Methods in org.omg.IOP.CodecFactoryPackage with parameters of type InputStream
static UnknownEncoding UnknownEncodingHelper.read(InputStream istream)

Uses of InputStream in org.omg.IOP.CodecPackage

Methods in org.omg.IOP.CodecPackage with parameters of type InputStream
static TypeMismatch | TypeMismatchHelper.read(InputStream istream)
static InvalidTypeForEncoding | InvalidTypeForEncodingHelper.read(InputStream istream)
static FormatMismatch | FormatMismatchHelper.read(InputStream istream)

Uses of InputStream in org.omg.Messaging

Methods in org.omg.Messaging with parameters of type InputStream
static short SyncScopeHelper.read(InputStream istream)

Uses of InputStream in org.omg.PortableInterceptor

Methods in org.omg.PortableInterceptor with parameters of type InputStream
static InvalidSlot | InvalidSlotHelper.read(InputStream istream)
static ForwardRequest | ForwardRequestHelper.read(InputStream istream)
static Current | CurrentHelper.read(InputStream istream)

Uses of InputStream in org.omg.PortableInterceptor.ORBInitInfoPackage

Methods in org.omg.PortableInterceptor.ORBInitInfoPackage with parameters of type InputStream
static String | ObjectIdHelper.read(InputStream istream)
static InvalidName | InvalidNameHelper.read(InputStream istream)
static DuplicateName | DuplicateNameHelper.read(InputStream istream)

Uses of InputStream in org.omg.PortableServer

Methods in org.omg.PortableServer with parameters of type InputStream
OutputStream | ServantLocatorPOA._invoke(String $method, InputStream in, ResponseHandler $rh)
static ServantLocator | ServantLocatorHelper.read(InputStream istream)
OutputStream | ServantActivatorPOA._invoke(String $method, InputStream in, ResponseHandler $rh)
static ServantActivator | ServantActivatorHelper.read(InputStream istream)
static POA | POAHelper.read(InputStream istream)
static ForwardRequest | ForwardRequestHelper.read(InputStream istream)
static Current | CurrentHelper.read(InputStream istream)

Uses of InputStream in org.omg.PortableServer.CurrentPackage

Methods in org.omg.PortableServer.CurrentPackage with parameters of type InputStream
static NoContext NoContextHelper.read(InputStream istream)

Uses of InputStream in org.omg.PortableServer.POAManagerPackage

Methods in org.omg.PortableServer.POAManagerPackage with parameters of type InputStream
static AdapterInactive AdapterInactiveHelper.read(InputStream istream)

Uses of InputStream in org.omg.PortableServer.POAPackage

Methods in org.omg.PortableServer.POAPackage with parameters of type InputStream
static WrongPolicy | WrongPolicyHelper.read(InputStream istream)
static WrongAdapter | WrongAdapterHelper.read(InputStream istream)
static ServantNotActive | ServantNotActiveHelper.read(InputStream istream)
static ServantAlreadyActive | ServantAlreadyActiveHelper.read(InputStream istream)
static ObjectNotActive | ObjectNotActiveHelper.read(InputStream istream)
static ObjectAlreadyActive | ObjectAlreadyActiveHelper.read(InputStream istream)
static NoServant | NoServantHelper.read(InputStream istream)
static InvalidPolicy | InvalidPolicyHelper.read(InputStream istream)
static AdapterNonExistent | AdapterNonExistentHelper.read(InputStream istream)
static AdapterAlreadyExists | AdapterAlreadyExistsHelper.read(InputStream istream)

Uses of InputStream in org.omg.PortableServer.ServantLocatorPackage

Methods in org.omg.PortableServer.ServantLocatorPackage with parameters of type InputStream
 void CookieHolder._read(InputStream is)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.portable.InvokeHandler (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.portable.InvokeHandler

Packages that use InvokeHandler
javax.rmi.CORBA | Contains portability APIs for RMI-IIOP.
org.omg.CosNaming | Provides a naming service for Java IDL.
org.omg.PortableServer | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of InvokeHandler in javax.rmi.CORBA

Subinterfaces of InvokeHandler in javax.rmi.CORBA
 interface Tie
Defines methods which all RMI-IIOP server side ties must implement.

Uses of InvokeHandler in org.omg.CosNaming

Classes in org.omg.CosNaming that implement InvokeHandler
class | BindingIteratorPOA The BindingIterator interface allows a client to iterate through the bindings using the next_one or next_n operations.
class | NamingContextExtPOA 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.
class | NamingContextPOA A naming context is an object that contains a set of name bindings in which each name is unique.

Uses of InvokeHandler in org.omg.PortableServer

Classes in org.omg.PortableServer that implement InvokeHandler
class | ServantActivatorPOA When the POA has the RETAIN policy it uses servant managers that are ServantActivators.
class | ServantLocatorPOA When the POA has the NON_RETAIN policy it uses servant managers that are ServantLocators.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.portable.ObjectImpl (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.portable.ObjectImpl

Packages that use ObjectImpl
javax.rmi.CORBA | Contains portability APIs for RMI-IIOP.
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_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 | Provides a naming service for Java IDL.
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.PortableServer | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.
org.omg.stub.java.rmi | Contains RMI-IIOP Stubs for the Remote types that occur in the java.rmi package.

Uses of ObjectImpl in javax.rmi.CORBA

Subclasses of ObjectImpl in javax.rmi.CORBA
 class Stub
Base class from which all RMI-IIOP stubs must inherit.

Uses of ObjectImpl in org.omg.CORBA

Subclasses of ObjectImpl in org.omg.CORBA
class | _IDLTypeStub The Stub for IDLType.
class | _PolicyStub The Stub for Policy.
class | DynamicImplementation Deprecated. org.omg.CORBA.DynamicImplementation

Uses of ObjectImpl in org.omg.CORBA_2_3.portable

Subclasses of ObjectImpl in org.omg.CORBA_2_3.portable
 class ObjectImpl
ObjectImpl class is the base class for all stubs.

Uses of ObjectImpl in org.omg.CosNaming

Subclasses of ObjectImpl in org.omg.CosNaming
class | _BindingIteratorImplBase
class | _BindingIteratorStub The BindingIterator interface allows a client to iterate through the bindings using the next_one or next_n operations.
class | _NamingContextExtStub 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.
class | _NamingContextImplBase
class | _NamingContextStub A naming context is an object that contains a set of name bindings in which each name is unique.

Uses of ObjectImpl in org.omg.DynamicAny

Subclasses of ObjectImpl in org.omg.DynamicAny
class | _DynAnyFactoryStub DynAny objects can be created by invoking operations on the DynAnyFactory object.
class | _DynAnyStub Any values can be dynamically interpreted (traversed) and constructed through DynAny objects.
class | _DynArrayStub DynArray objects support the manipulation of IDL arrays.
class | _DynEnumStub DynEnum objects support the manipulation of IDL enumerated values.
class | _DynFixedStub DynFixed objects support the manipulation of IDL fixed values.
class | _DynSequenceStub DynSequence objects support the manipulation of IDL sequences.
class | _DynStructStub DynStruct objects support the manipulation of IDL struct and exception values.
class | _DynUnionStub DynUnion objects support the manipulation of IDL unions.
class | _DynValueStub DynValue objects support the manipulation of IDL non-boxed value types.

Uses of ObjectImpl in org.omg.PortableServer

Subclasses of ObjectImpl in org.omg.PortableServer
class | _ServantActivatorStub When the POA has the RETAIN policy it uses servant managers that are ServantActivators.
class | _ServantLocatorStub When the POA has the NON_RETAIN policy it uses servant managers that are ServantLocators.

Uses of ObjectImpl in org.omg.stub.java.rmi

Subclasses of ObjectImpl in org.omg.stub.java.rmi
 class _Remote_Stub
This class provides the Stub for the Remote Type.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.portable.OutputStream (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.portable.OutputStream

Packages that use OutputStream
javax.rmi.CORBA | Contains portability APIs for RMI-IIOP.
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_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.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.CosNaming | Provides a naming service for Java IDL.
org.omg.CosNaming.NamingContextExtPackage | This package contains the following classes, which are used in org.omg.CosNaming.NamingContextExt:
org.omg.CosNaming.NamingContextPackage | This package contains Exception classes for the org.omg.CosNaming 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 | 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 | 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 | 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 | This package contains the exceptions specified in the IOP::CodeFactory interface (as part of the Portable Interceptors spec).
org.omg.IOP.CodecPackage | This package is generated from the IOP::Codec IDL interface definition.
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 | 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 | 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 | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.
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 | Encapsulates the processing state of the POAs it is associated with.
org.omg.PortableServer.POAPackage | Allows programmers to construct object implementations that are portable between different ORB products.
org.omg.PortableServer.ServantLocatorPackage | Provides classes and interfaces for locating the servant.

Uses of OutputStream in javax.rmi.CORBA

Methods in javax.rmi.CORBA with parameters of type OutputStream
 void ValueHandler.writeValue(OutputStream out, Serializable value)
Writes a value to the stream using Java semantics.
 void UtilDelegate.writeAny(OutputStream out, Object obj)
Delegation call for Util.writeAny(org.omg.CORBA.portable.OutputStream, java.lang.Object).
 void UtilDelegate.writeRemoteObject(OutputStream out, Object obj)
Delegation call for Util.writeRemoteObject(org.omg.CORBA.portable.OutputStream, java.lang.Object).
 void UtilDelegate.writeAbstractObject(OutputStream out, Object obj)
Delegation call for Util.writeAbstractObject(org.omg.CORBA.portable.OutputStream, java.lang.Object).
static void Util.writeAny(OutputStream out, Object obj)
Writes any java.lang.Object as a CORBA any.
static void Util.writeRemoteObject(OutputStream out, Object obj)
Writes a java.lang.Object as a CORBA Object.
static void Util.writeAbstractObject(OutputStream out, Object obj)
Writes a java.lang.Object as either a value or a CORBA Object.

Uses of OutputStream in org.omg.CORBA

Methods in org.omg.CORBA that return OutputStream
OutputStream | LocalObject._request(String operation, boolean responseExpected) Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.
abstract OutputStream | Any.create_output_stream() Creates an output stream into which this Any object's value can be marshalled.
abstract OutputStream | ORB.create_output_stream() Creates a new org.omg.CORBA.portable.OutputStream into which IDL method parameters can be marshalled during method invocation.

Methods in org.omg.CORBA with parameters of type OutputStream
void | WrongTransactionHolder._write(OutputStream o)
void | WStringSeqHolder._write(OutputStream o)
static void | WStringSeqHelper.write(OutputStream ostream, String[] value)
void | UnknownUserExceptionHolder._write(OutputStream o)
static void | UnknownUserExceptionHelper.write(OutputStream ostream, UnknownUserException value)
void | StringSeqHolder._write(OutputStream o)
static void | StringSeqHelper.write(OutputStream ostream, String[] value)
void | PolicyErrorHolder._write(OutputStream o)
static void | PolicyErrorHelper.write(OutputStream ostream, PolicyError value)
static void | PolicyErrorCodeHelper.write(OutputStream ostream, short value)
void | ParameterModeHolder._write(OutputStream o)
static void | ParameterModeHelper.write(OutputStream ostream, ParameterMode value)
InputStream | LocalObject._invoke(OutputStream output) Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.
static void | WStringValueHelper.write(OutputStream ostream, String value)
void | WStringValueHelper.write_value(OutputStream ostream, Serializable value)
static void | WCharSeqHelper.write(OutputStream ostream, char[] value)
static void | VisibilityHelper.write(OutputStream ostream, short value)
static void | VersionSpecHelper.write(OutputStream ostream, String value)
static void | ValueMemberHelper.write(OutputStream ostream, ValueMember value)
void | ValueBaseHolder._write(OutputStream output) Marshals to output the value in the Holder.
static void | ValueBaseHelper.write(OutputStream ostream, Serializable value)
static void | UnionMemberHelper.write(OutputStream ostream, UnionMember value)
static void | UShortSeqHelper.write(OutputStream ostream, short[] value)
static void | ULongSeqHelper.write(OutputStream ostream, int[] value)
static void | ULongLongSeqHelper.write(OutputStream ostream, long[] value)
static void | StructMemberHelper.write(OutputStream ostream, StructMember value)
static void | StringValueHelper.write(OutputStream ostream, String value)
void | StringValueHelper.write_value(OutputStream ostream, Serializable value)
static void | ShortSeqHelper.write(OutputStream ostream, short[] value)
static void | SetOverrideTypeHelper.write(OutputStream ostream, SetOverrideType value)
static void | RepositoryIdHelper.write(OutputStream ostream, String value)
void | PolicyListHolder._write(OutputStream o)
static void | PolicyListHelper.write(OutputStream ostream, Policy[] value)
static void | PolicyTypeHelper.write(OutputStream ostream, int value)
void | PolicyHolder._write(OutputStream o)
static void | PolicyHelper.write(OutputStream ostream, Policy value)
static void | OctetSeqHelper.write(OutputStream ostream, byte[] value)
static void | NameValuePairHelper.write(OutputStream ostream, NameValuePair value)
static void | LongSeqHelper.write(OutputStream ostream, int[] value)
static void | LongLongSeqHelper.write(OutputStream ostream, long[] value)
static void | IdentifierHelper.write(OutputStream ostream, String value)
static void | IDLTypeHelper.write(OutputStream ostream, IDLType value)
static void | FloatSeqHelper.write(OutputStream ostream, float[] value)
static void | FieldNameHelper.write(OutputStream ostream, String value)
static void | DoubleSeqHelper.write(OutputStream ostream, double[] value)
static void | DefinitionKindHelper.write(OutputStream ostream, DefinitionKind value)
void | DoubleSeqHolder._write(OutputStream o)
void | FloatSeqHolder._write(OutputStream o)
void | LongLongSeqHolder._write(OutputStream o)
void | ULongLongSeqHolder._write(OutputStream o)
void | ULongSeqHolder._write(OutputStream o)
void | LongSeqHolder._write(OutputStream o)
void | UShortSeqHolder._write(OutputStream o)
void | ShortSeqHolder._write(OutputStream o)
void | OctetSeqHolder._write(OutputStream o)
void | WCharSeqHolder._write(OutputStream o)
void | CurrentHolder._write(OutputStream o)
static void | CurrentHelper.write(OutputStream ostream, Current value)
static void | CompletionStatusHelper.write(OutputStream ostream, CompletionStatus value)
void | CharSeqHolder._write(OutputStream o)
static void | CharSeqHelper.write(OutputStream ostream, char[] value)
void | BooleanSeqHolder._write(OutputStream o)
static void | BooleanSeqHelper.write(OutputStream ostream, boolean[] value)
void | AnySeqHolder._write(OutputStream o)
static void | AnySeqHelper.write(OutputStream ostream, Any[] value)
void | TypeCodeHolder._write(OutputStream output) Marshals to output the value in this TypeCodeHolder object.
void | StringHolder._write(OutputStream output) Marshals the value held by this StringHolder object to the output stream output.
void | ShortHolder._write(OutputStream output) Marshals to output the value in this ShortHolder object.
void | PrincipalHolder._write(OutputStream output) Deprecated.
void | ObjectHolder._write(OutputStream output) Marshals to output the value in this ObjectHolder object.
void | LongHolder._write(OutputStream output) Marshals to output the value in the Holder.
void | IntHolder._write(OutputStream output) Marshals the value in this IntHolder object's value field to the output stream output.
void | FloatHolder._write(OutputStream output) Write the float value into an output stream.
void | FixedHolder._write(OutputStream output) Write the fixed point value stored in this holder to an OutputStream.
void | DoubleHolder._write(OutputStream output) Write the double value stored in this holder to an OutputStream.
void | CharHolder._write(OutputStream output) Marshals to output the value in this CharHolder object.
void | ByteHolder._write(OutputStream output) Marshals to output the value in this ByteHolder object.
void | BooleanHolder._write(OutputStream output) Marshals the value in this BooleanHolder object's value field to the output stream output.
void | AnyHolder._write(OutputStream output) Marshals to output the value in this AnyHolder object.
static void | ServiceDetailHelper.write(OutputStream out, ServiceDetail that)
static void | ObjectHelper.write(OutputStream ostream, Object value)
static void | ServiceInformationHelper.write(OutputStream out, ServiceInformation that)
static void | WrongTransactionHelper.write(OutputStream ostream, WrongTransaction value)
void | ServiceInformationHolder._write(OutputStream out) Marshals the value in this ServiceInformationHolder object's value field to the output stream out.
abstract void | Any.write_value(OutputStream os) Writes out the value of this Any object to the given output stream.

Uses of OutputStream in org.omg.CORBA_2_3.portable

Subclasses of OutputStream in org.omg.CORBA_2_3.portable
 class OutputStream
OutputStream provides interface for writing of all of the mapped IDL type to the stream.

Uses of OutputStream in org.omg.CORBA.portable

Methods in org.omg.CORBA.portable that return OutputStream
OutputStream | Delegate.request(Object self, String operation, boolean responseExpected) request is called by a stub to obtain an OutputStream for marshaling arguments.
OutputStream | ObjectImpl._request(String operation, boolean responseExpected) Returns an OutputStream object to use for marshalling the arguments of the given method.
OutputStream | ResponseHandler.createReply() Called by the servant during a method invocation.
OutputStream | ResponseHandler.createExceptionReply() Called by the servant during a method invocation.
OutputStream | InvokeHandler._invoke(String method, InputStream input, ResponseHandler handler) Invoked by the ORB to dispatch a request to the servant.

Methods in org.omg.CORBA.portable with parameters of type OutputStream
void | BoxedValueHelper.write_value(OutputStream os, Serializable value)
InputStream | Delegate.invoke(Object self, OutputStream output) invoke is called by a stub to invoke an operation.
InputStream | ObjectImpl._invoke(OutputStream output) Invokes an operation and returns an InputStream object for reading the response.
void | Streamable._write(OutputStream ostream) Marshals to ostream the value in the value field of the Holder.

Uses of OutputStream in org.omg.CosNaming

Methods in org.omg.CosNaming that return OutputStream
OutputStream | NamingContextExtPOA._invoke(String $method, InputStream in, ResponseHandler $rh)
OutputStream | NamingContextPOA._invoke(String $method, InputStream in, ResponseHandler $rh)
OutputStream | BindingIteratorPOA._invoke(String $method, InputStream in, ResponseHandler $rh)

Methods in org.omg.CosNaming with parameters of type OutputStream
void | NamingContextExtHolder._write(OutputStream o)
static void | NamingContextExtHelper.write(OutputStream ostream, NamingContextExt value)
void | NamingContextHolder._write(OutputStream o)
static void | NamingContextHelper.write(OutputStream ostream, NamingContext value)
void | NameHolder._write(OutputStream o)
static void | NameHelper.write(OutputStream ostream, NameComponent[] value)
void | NameComponentHolder._write(OutputStream o)
static void | NameComponentHelper.write(OutputStream ostream, NameComponent value)
void | BindingTypeHolder._write(OutputStream o)
static void | BindingTypeHelper.write(OutputStream ostream, BindingType value)
static void | BindingListHelper.write(OutputStream ostream, Binding[] value)
void | BindingIteratorHolder._write(OutputStream o)
static void | BindingIteratorHelper.write(OutputStream ostream, BindingIterator value)
void | BindingListHolder._write(OutputStream o)
void | BindingHolder._write(OutputStream o)
static void | BindingHelper.write(OutputStream ostream, Binding value)
static void | IstringHelper.write(OutputStream ostream, String value)

Uses of OutputStream in org.omg.CosNaming.NamingContextExtPackage

Methods in org.omg.CosNaming.NamingContextExtPackage with parameters of type OutputStream
static void | URLStringHelper.write(OutputStream ostream, String value)
static void | StringNameHelper.write(OutputStream ostream, String value)
void | InvalidAddressHolder._write(OutputStream o)
static void | InvalidAddressHelper.write(OutputStream ostream, InvalidAddress value)
static void | AddressHelper.write(OutputStream ostream, String value)

Uses of OutputStream in org.omg.CosNaming.NamingContextPackage

Methods in org.omg.CosNaming.NamingContextPackage with parameters of type OutputStream
void | NotFoundReasonHolder._write(OutputStream o)
static void | NotFoundReasonHelper.write(OutputStream ostream, NotFoundReason value)
void | NotFoundHolder._write(OutputStream o)
static void | NotFoundHelper.write(OutputStream ostream, NotFound value)
void | NotEmptyHolder._write(OutputStream o)
static void | NotEmptyHelper.write(OutputStream ostream, NotEmpty value)
void | InvalidNameHolder._write(OutputStream o)
static void | InvalidNameHelper.write(OutputStream ostream, InvalidName value)
void | CannotProceedHolder._write(OutputStream o)
static void | CannotProceedHelper.write(OutputStream ostream, CannotProceed value)
void | AlreadyBoundHolder._write(OutputStream o)
static void | AlreadyBoundHelper.write(OutputStream ostream, AlreadyBound value)

Uses of OutputStream in org.omg.DynamicAny

Methods in org.omg.DynamicAny with parameters of type OutputStream
static void | NameValuePairSeqHelper.write(OutputStream ostream, NameValuePair[] value)
static void | NameValuePairHelper.write(OutputStream ostream, NameValuePair value)
static void | NameDynAnyPairSeqHelper.write(OutputStream ostream, NameDynAnyPair[] value)
static void | DynSequenceHelper.write(OutputStream ostream, DynSequence value)
static void | NameDynAnyPairHelper.write(OutputStream ostream, NameDynAnyPair value)
static void | FieldNameHelper.write(OutputStream ostream, String value)
static void | DynFixedHelper.write(OutputStream ostream, DynFixed value)
static void | DynEnumHelper.write(OutputStream ostream, DynEnum value)
static void | DynAnySeqHelper.write(OutputStream ostream, DynAny[] value)
static void | DynArrayHelper.write(OutputStream ostream, DynArray value)
static void | DynValueHelper.write(OutputStream ostream, DynValue value)
static void | DynAnyHelper.write(OutputStream ostream, DynAny value)
static void | DynUnionHelper.write(OutputStream ostream, DynUnion value)
static void | DynAnyFactoryHelper.write(OutputStream ostream, DynAnyFactory value)
static void | DynStructHelper.write(OutputStream ostream, DynStruct value)
static void | AnySeqHelper.write(OutputStream ostream, Any[] value)

Uses of OutputStream in org.omg.DynamicAny.DynAnyFactoryPackage

Methods in org.omg.DynamicAny.DynAnyFactoryPackage with parameters of type OutputStream
static void InconsistentTypeCodeHelper.write(OutputStream ostream, InconsistentTypeCode value)

Uses of OutputStream in org.omg.DynamicAny.DynAnyPackage

Methods in org.omg.DynamicAny.DynAnyPackage with parameters of type OutputStream
static void | TypeMismatchHelper.write(OutputStream ostream, TypeMismatch value)
static void | InvalidValueHelper.write(OutputStream ostream, InvalidValue value)

Uses of OutputStream in org.omg.IOP

Methods in org.omg.IOP with parameters of type OutputStream
void | TaggedProfileHolder._write(OutputStream o)
static void | TaggedProfileHelper.write(OutputStream ostream, TaggedProfile value)
void | TaggedComponentHolder._write(OutputStream o)
static void | TaggedComponentHelper.write(OutputStream ostream, TaggedComponent value)
static void | ServiceIdHelper.write(OutputStream ostream, int value)
void | ServiceContextListHolder._write(OutputStream o)
static void | ServiceContextListHelper.write(OutputStream ostream, ServiceContext[] value)
void | ServiceContextHolder._write(OutputStream o)
static void | ServiceContextHelper.write(OutputStream ostream, ServiceContext value)
static void | ProfileIdHelper.write(OutputStream ostream, int value)
void | MultipleComponentProfileHolder._write(OutputStream o)
static void | MultipleComponentProfileHelper.write(OutputStream ostream, TaggedComponent[] value)
void | IORHolder._write(OutputStream o)
static void | IORHelper.write(OutputStream ostream, IOR value)
static void | ComponentIdHelper.write(OutputStream ostream, int value)
static void | CodecFactoryHelper.write(OutputStream ostream, CodecFactory value)

Uses of OutputStream in org.omg.IOP.CodecFactoryPackage

Methods in org.omg.IOP.CodecFactoryPackage with parameters of type OutputStream
static void UnknownEncodingHelper.write(OutputStream ostream, UnknownEncoding value)

Uses of OutputStream in org.omg.IOP.CodecPackage

Methods in org.omg.IOP.CodecPackage with parameters of type OutputStream
static void | TypeMismatchHelper.write(OutputStream ostream, TypeMismatch value)
static void | InvalidTypeForEncodingHelper.write(OutputStream ostream, InvalidTypeForEncoding value)
static void | FormatMismatchHelper.write(OutputStream ostream, FormatMismatch value)

Uses of OutputStream in org.omg.Messaging

Methods in org.omg.Messaging with parameters of type OutputStream
static void SyncScopeHelper.write(OutputStream ostream, short value)

Uses of OutputStream in org.omg.PortableInterceptor

Methods in org.omg.PortableInterceptor with parameters of type OutputStream
static void | InvalidSlotHelper.write(OutputStream ostream, InvalidSlot value)
static void | ForwardRequestHelper.write(OutputStream ostream, ForwardRequest value)
static void | CurrentHelper.write(OutputStream ostream, Current value)

Uses of OutputStream in org.omg.PortableInterceptor.ORBInitInfoPackage

Methods in org.omg.PortableInterceptor.ORBInitInfoPackage with parameters of type OutputStream
static void | ObjectIdHelper.write(OutputStream ostream, String value)
static void | InvalidNameHelper.write(OutputStream ostream, InvalidName value)
static void | DuplicateNameHelper.write(OutputStream ostream, DuplicateName value)

Uses of OutputStream in org.omg.PortableServer

Methods in org.omg.PortableServer that return OutputStream
OutputStream | ServantLocatorPOA._invoke(String $method, InputStream in, ResponseHandler $rh)
OutputStream | ServantActivatorPOA._invoke(String $method, InputStream in, ResponseHandler $rh)

Methods in org.omg.PortableServer with parameters of type OutputStream
static void | ServantLocatorHelper.write(OutputStream ostream, ServantLocator value)
static void | ServantActivatorHelper.write(OutputStream ostream, ServantActivator value)
static void | POAHelper.write(OutputStream ostream, POA value)
static void | ForwardRequestHelper.write(OutputStream ostream, ForwardRequest value)
static void | CurrentHelper.write(OutputStream ostream, Current value)

Uses of OutputStream in org.omg.PortableServer.CurrentPackage

Methods in org.omg.PortableServer.CurrentPackage with parameters of type OutputStream
static void NoContextHelper.write(OutputStream ostream, NoContext value)

Uses of OutputStream in org.omg.PortableServer.POAManagerPackage

Methods in org.omg.PortableServer.POAManagerPackage with parameters of type OutputStream
static void AdapterInactiveHelper.write(OutputStream ostream, AdapterInactive value)

Uses of OutputStream in org.omg.PortableServer.POAPackage

Methods in org.omg.PortableServer.POAPackage with parameters of type OutputStream
static void | WrongPolicyHelper.write(OutputStream ostream, WrongPolicy value)
static void | WrongAdapterHelper.write(OutputStream ostream, WrongAdapter value)
static void | ServantNotActiveHelper.write(OutputStream ostream, ServantNotActive value)
static void | ServantAlreadyActiveHelper.write(OutputStream ostream, ServantAlreadyActive value)
static void | ObjectNotActiveHelper.write(OutputStream ostream, ObjectNotActive value)
static void | ObjectAlreadyActiveHelper.write(OutputStream ostream, ObjectAlreadyActive value)
static void | NoServantHelper.write(OutputStream ostream, NoServant value)
static void | InvalidPolicyHelper.write(OutputStream ostream, InvalidPolicy value)
static void | AdapterNonExistentHelper.write(OutputStream ostream, AdapterNonExistent value)
static void | AdapterAlreadyExistsHelper.write(OutputStream ostream, AdapterAlreadyExists value)

Uses of OutputStream in org.omg.PortableServer.ServantLocatorPackage

Methods in org.omg.PortableServer.ServantLocatorPackage with parameters of type OutputStream
 void CookieHolder._write(OutputStream os)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.portable.RemarshalException (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.portable.RemarshalException

Packages that use RemarshalException
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.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.

Uses of RemarshalException in org.omg.CORBA

Methods in org.omg.CORBA that throw RemarshalException
 InputStream LocalObject._invoke(OutputStream output)
Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.

Uses of RemarshalException in org.omg.CORBA.portable

Methods in org.omg.CORBA.portable that throw RemarshalException
InputStream | Delegate.invoke(Object self, OutputStream output) invoke is called by a stub to invoke an operation.
InputStream | ObjectImpl._invoke(OutputStream output) Invokes an operation and returns an InputStream object for reading the response.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.portable.ResponseHandler (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.portable.ResponseHandler

Packages that use ResponseHandler
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.CosNaming | Provides a naming service for Java IDL.
org.omg.PortableServer | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of ResponseHandler in org.omg.CORBA.portable

Methods in org.omg.CORBA.portable with parameters of type ResponseHandler
 OutputStream InvokeHandler._invoke(String method, InputStream input, ResponseHandler handler)
Invoked by the ORB to dispatch a request to the servant.

Uses of ResponseHandler in org.omg.CosNaming

Methods in org.omg.CosNaming with parameters of type ResponseHandler
OutputStream | NamingContextExtPOA._invoke(String $method, InputStream in, ResponseHandler $rh)
OutputStream | NamingContextPOA._invoke(String $method, InputStream in, ResponseHandler $rh)
OutputStream | BindingIteratorPOA._invoke(String $method, InputStream in, ResponseHandler $rh)

Uses of ResponseHandler in org.omg.PortableServer

Methods in org.omg.PortableServer with parameters of type ResponseHandler
OutputStream | ServantLocatorPOA._invoke(String $method, InputStream in, ResponseHandler $rh)
OutputStream | ServantActivatorPOA._invoke(String $method, InputStream in, ResponseHandler $rh)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.portable.ServantObject (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.portable.ServantObject

Packages that use ServantObject
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.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.

Uses of ServantObject in org.omg.CORBA

Methods in org.omg.CORBA that return ServantObject
 ServantObject LocalObject._servant_preinvoke(String operation, Class expectedType)
Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.

Methods in org.omg.CORBA with parameters of type ServantObject
 void LocalObject._servant_postinvoke(ServantObject servant)
Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method is the default implementation of the org.omg.CORBA.Object method.

Uses of ServantObject in org.omg.CORBA.portable

Methods in org.omg.CORBA.portable that return ServantObject
ServantObject | Delegate.servant_preinvoke(Object self, String operation, Class expectedType) Returns a Java reference to the servant which should be used for this request.
ServantObject | ObjectImpl._servant_preinvoke(String operation, Class expectedType) Returns a Java reference to the local servant that should be used for sending a request for the method specified.

Methods in org.omg.CORBA.portable with parameters of type ServantObject
 void Delegate.servant_postinvoke(Object self, ServantObject servant)
servant_postinvoke() is invoked by the local stub after the operation has been invoked on the local servant.
 void ObjectImpl._servant_postinvoke(ServantObject servant)
Is called by the local stub after it has invoked an operation on the local servant that was previously retrieved from a call to the method _servant_preinvoke.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.portable.Streamable (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.portable.Streamable

Packages that use Streamable
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.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.CosNaming | Provides a naming service for Java IDL.
org.omg.CosNaming.NamingContextExtPackage | This package contains the following classes, which are used in org.omg.CosNaming.NamingContextExt:
org.omg.CosNaming.NamingContextPackage | This package contains Exception classes for the org.omg.CosNaming 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.PortableServer.ServantLocatorPackage | Provides classes and interfaces for locating the servant.

Uses of Streamable in org.omg.CORBA

Classes in org.omg.CORBA that implement Streamable
class | AnyHolder The Holder for Any.
class | AnySeqHolder The Holder for AnySeq.
class | BooleanHolder The Holder for Boolean.
class | BooleanSeqHolder The Holder for BooleanSeq.
class | ByteHolder The Holder for Byte.
class | CharHolder The Holder for Char.
class | CharSeqHolder The Holder for CharSeq.
class | CurrentHolder The Holder for Current.
class | DoubleHolder The Holder for Double.
class | DoubleSeqHolder The Holder for DoubleSeq.
class | FixedHolder The Holder for Fixed.
class | FloatHolder The Holder for Float.
class | FloatSeqHolder The Holder for FloatSeq.
class | IntHolder The Holder for Int.
class | LongHolder The Holder for Long.
class | LongLongSeqHolder The Holder for LongLongSeq.
class | LongSeqHolder The Holder for LongSeq.
class | ObjectHolder The Holder for Object.
class | OctetSeqHolder The Holder for OctetSeq.
class | ParameterModeHolder Enumeration of parameter modes for Parameter.
class | PolicyErrorHolder Thrown to indicate problems with parameter values passed to the ORB.create_policy operation.
class | PolicyHolder The Holder for Policy.
class | PolicyListHolder The Holder for PolicyList.
class | PrincipalHolder Deprecated. Deprecated by CORBA 2.2.
class | ServiceInformationHolder The Holder for ServiceInformation.
class | ShortHolder The Holder for Short.
class | ShortSeqHolder The Holder for ShortSeq.
class | StringHolder The Holder for String.
class | StringSeqHolder An array of Strings
class | TypeCodeHolder The Holder for TypeCode.
class | ULongLongSeqHolder The Holder for ULongLongSeq.
class | ULongSeqHolder The Holder for ULongSeq.
class | UnknownUserExceptionHolder The Holder for UnknownUserException.
class | UShortSeqHolder The Holder for UShortSeq.
class | ValueBaseHolder The Holder for ValueBase.
class | WCharSeqHolder The Holder for WCharSeq.
class | WrongTransactionHolder The Holder for WrongTransaction.
class | WStringSeqHolder An array of WStrings

Methods in org.omg.CORBA that return Streamable
 Streamable Any.extract_Streamable()
Extracts a Streamable from this Any object's value field.

Methods in org.omg.CORBA with parameters of type Streamable
 void Any.insert_Streamable(Streamable s)
Inserts the given Streamable object into this Any object's value field.

Uses of Streamable in org.omg.CORBA.portable

Subinterfaces of Streamable in org.omg.CORBA.portable
 interface StreamableValue
Defines the base type for all non-boxed IDL valuetypes that are not custom marshaled.

Uses of Streamable in org.omg.CosNaming

Classes in org.omg.CosNaming that implement Streamable
class | BindingHolder A name-to-object association is called a Binding.
class | BindingIteratorHolder The BindingIterator interface allows a client to iterate through the bindings using the next_one or next_n operations.
class | BindingListHolder List of Bindings.
class | BindingTypeHolder Specifies whether the given binding is for a object (that is not a naming context) or for a naming context.
class | NameComponentHolder Many of the operations defined on a naming context take names as parameters.
class | NameHolder A name is a sequence of name components.
class | NamingContextExtHolder 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.
class | NamingContextHolder A naming context is an object that contains a set of name bindings in which each name is unique.

Uses of Streamable in org.omg.CosNaming.NamingContextExtPackage

Classes in org.omg.CosNaming.NamingContextExtPackage that implement Streamable
 class InvalidAddressHolder
org/omg/CosNaming/NamingContextExtPackage/InvalidAddressHolder.java .

Uses of Streamable in org.omg.CosNaming.NamingContextPackage

Classes in org.omg.CosNaming.NamingContextPackage that implement Streamable
class | AlreadyBoundHolder org/omg/CosNaming/NamingContextPackage/AlreadyBoundHolder.java .
class | CannotProceedHolder org/omg/CosNaming/NamingContextPackage/CannotProceedHolder.java .
class | InvalidNameHolder org/omg/CosNaming/NamingContextPackage/InvalidNameHolder.java .
class | NotEmptyHolder org/omg/CosNaming/NamingContextPackage/NotEmptyHolder.java .
class | NotFoundHolder org/omg/CosNaming/NamingContextPackage/NotFoundHolder.java .
class | NotFoundReasonHolder Indicates the reason for not able to resolve.

Uses of Streamable in org.omg.IOP

Classes in org.omg.IOP that implement Streamable
class | IORHolder Captures information about a object references, such as whether the object is null, what type it is, what protocols are supported, and what ORB services are available.
class | MultipleComponentProfileHolder An array of tagged components, forming a multiple component profile.
class | ServiceContextHolder Service-specific information to be passed implicitly with requests and replies.
class | ServiceContextListHolder An array of service contexts, forming a service context list.
class | TaggedComponentHolder TaggedComponents contained in TAG_INTERNET_IOP and TAG_MULTIPLE_COMPONENTS profiles are identified by unique numeric tags using a namespace distinct form that is used for profile tags.
class | TaggedProfileHolder Object references have at least one tagged profile.

Uses of Streamable in org.omg.PortableServer.ServantLocatorPackage

Classes in org.omg.PortableServer.ServantLocatorPackage that implement Streamable
 class CookieHolder
The native type PortableServer::ServantLocator::Cookie is mapped to java.lang.Object.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.portable.StreamableValue (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.portable.StreamableValue

No usage of org.omg.CORBA.portable.StreamableValue

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.portable.UnknownException (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.portable.UnknownException

No usage of org.omg.CORBA.portable.UnknownException

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.portable.ValueBase (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.portable.ValueBase

Packages that use ValueBase
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.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.

Uses of ValueBase in org.omg.CORBA

Subinterfaces of ValueBase in org.omg.CORBA
interface | DataInputStream Defines the methods used to read primitive data types from input streams for unmarshaling custom value types.
interface | DataOutputStream Defines the methods used to write primitive data types to output streams for marshalling custom value types.

Uses of ValueBase in org.omg.CORBA.portable

Subinterfaces of ValueBase in org.omg.CORBA.portable
interface | CustomValue An extension of ValueBase that is implemented by custom value types.
interface | StreamableValue Defines the base type for all non-boxed IDL valuetypes that are not custom marshaled.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CORBA.portable.ValueFactory (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CORBA.portable.ValueFactory

Packages that use ValueFactory
org.omg.CORBA_2_3 The CORBA_2_3 package defines additions to existing CORBA interfaces in the Java 2 Standard Edition. 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.

Uses of ValueFactory in org.omg.CORBA_2_3

Methods in org.omg.CORBA_2_3 that return ValueFactory
ValueFactory | ORB.register_value_factory(String id, ValueFactory factory)
ValueFactory | ORB.lookup_value_factory(String id)

Methods in org.omg.CORBA_2_3 with parameters of type ValueFactory
 ValueFactory ORB.register_value_factory(String id, ValueFactory factory)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


BadKind (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA.TypeCodePackage
Class BadKind

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.CORBA.TypeCodePackage.BadKind
All Implemented Interfaces:
IDLEntity, Serializable
public final class BadKind
extends UserException

The exception BadKind is thrown when an inappropriate operation is invoked on a TypeCode object. For example, invoking the method discriminator_type() on an instance of TypeCode that does not represent an IDL union will cause the exception BadKind to be thrown.

Since:
JDK1.2
See Also:
TypeCode

Constructor Summary
BadKind()
Constructs a BadKind exception with no reason message.
BadKind(String reason)
Constructs a BadKind exception with the specified reason message.
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

BadKind

public BadKind()
Constructs a BadKind exception with no reason message.

BadKind

public BadKind(String reason)
Constructs a BadKind exception with the specified reason message.

Parameters:
reason - the String containing a reason message
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Bounds (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA.TypeCodePackage
Class Bounds

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.CORBA.TypeCodePackage.Bounds
All Implemented Interfaces:
IDLEntity, Serializable
public final class Bounds
extends UserException

Provides the TypeCode operations member_name(), member_type(), and member_label. These methods raise Bounds when the index parameter is greater than or equal to the number of members constituting the type.

Since:
JDK1.2

Constructor Summary
Bounds()
Constructs a Bounds exception with no reason message.
Bounds(String reason)
Constructs a Bounds exception with the specified reason message.
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

Bounds

public Bounds()
Constructs a Bounds exception with no reason message.

Bounds

public Bounds(String reason)
Constructs a Bounds exception with the specified reason message.

Parameters:
reason - the String containing a reason message
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


org.omg.CORBA.TypeCodePackage (Java 2 Platform SE v1.4.2)

 org.omg.CORBA.TypeCodePackage
Exceptions
BadKind
Bounds


org.omg.CORBA.TypeCodePackage (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package org.omg.CORBA.TypeCodePackage

Provides the user-defined exceptions BadKind and Bounds, which are thrown by methods in in the class TypeCode.

See:
Description

Exception Summary
BadKind | The exception BadKind is thrown when an inappropriate operation is invoked on a TypeCode object.
Bounds | Provides the TypeCode operations member_name(), member_type(), and member_label.

Package org.omg.CORBA.TypeCodePackage Description

Provides the user-defined exceptions BadKind and Bounds, which are thrown by methods in in the class TypeCode.

Related Documentation

For an overview, please see:
  • comments on the CORBA package

Since:
JDK1.2
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


org.omg.CORBA.TypeCodePackage Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package org.omg.CORBA.TypeCodePackage

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class java.lang.Throwable (implements java.io.Serializable)
      • class java.lang.Exception
        • class org.omg.CORBA.UserException (implements org.omg.CORBA.portable.IDLEntity)
          • class org.omg.CORBA.TypeCodePackage.BadKind
          • class org.omg.CORBA.TypeCodePackage.Bounds
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package org.omg.CORBA.TypeCodePackage (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
org.omg.CORBA.TypeCodePackage

Packages that use org.omg.CORBA.TypeCodePackage
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).

Classes in org.omg.CORBA.TypeCodePackage used by org.omg.CORBA
BadKind
The exception BadKind is thrown when an inappropriate operation is invoked on a TypeCode object.
Bounds
Provides the TypeCode operations member_name(), member_type(), and member_label.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.TypeCodePackage.BadKind (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.TypeCodePackage.BadKind

Packages that use BadKind
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).

Uses of BadKind in org.omg.CORBA

Methods in org.omg.CORBA that throw BadKind
abstract String | TypeCode.id() Retrieves the RepositoryId globally identifying the type of this TypeCode object.
abstract String | TypeCode.name() Retrieves the simple name identifying this TypeCode object within its enclosing scope.
abstract int | TypeCode.member_count() Retrieves the number of members in the type described by this TypeCode object.
abstract String | TypeCode.member_name(int index) Retrieves the simple name of the member identified by the given index.
abstract TypeCode | TypeCode.member_type(int index) Retrieves the TypeCode object describing the type of the member identified by the given index.
abstract Any | TypeCode.member_label(int index) Retrieves the label of the union member identified by the given index.
abstract TypeCode | TypeCode.discriminator_type() Returns a TypeCode object describing all non-default member labels.
abstract int | TypeCode.default_index() Returns the index of the default member, or -1 if there is no default member.
abstract int | TypeCode.length() Returns the number of elements in the type described by this TypeCode object.
abstract TypeCode | TypeCode.content_type() Returns the TypeCode object representing the IDL type for the members of the object described by this TypeCode object.
abstract short | TypeCode.fixed_digits() Returns the number of digits in the fixed type described by this TypeCode object.
abstract short | TypeCode.fixed_scale() Returns the scale of the fixed type described by this TypeCode object.
abstract short | TypeCode.member_visibility(int index) Returns the constant that indicates the visibility of the member at the given index.
abstract short | TypeCode.type_modifier() Returns a constant indicating the modifier of the value type that this TypeCode object describes.
abstract TypeCode | TypeCode.concrete_base_type() Returns the TypeCode object that describes the concrete base type of the value type that this TypeCode object describes.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA.TypeCodePackage.Bounds (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA.TypeCodePackage.Bounds

Packages that use Bounds
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).

Uses of Bounds in org.omg.CORBA

Methods in org.omg.CORBA that throw Bounds
abstract String | TypeCode.member_name(int index) Retrieves the simple name of the member identified by the given index.
abstract TypeCode | TypeCode.member_type(int index) Retrieves the TypeCode object describing the type of the member identified by the given index.
abstract Any | TypeCode.member_label(int index) Retrieves the label of the union member identified by the given index.
abstract short | TypeCode.member_visibility(int index) Returns the constant that indicates the visibility of the member at the given index.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


ORB (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA_2_3
Class ORB

java.lang.Object
    extended by org.omg.CORBA.ORB
        extended by org.omg.CORBA_2_3.ORB
public abstract class ORB
extends ORB

A class extending org.omg.CORBA.ORB to make the ORB portable under the OMG CORBA version 2.3 specification.

Constructor Summary
ORB()
Method Summary
Object | get_value_def(String repid)
ValueFactory | lookup_value_factory(String id)
ValueFactory | register_value_factory(String id, ValueFactory factory)
void | set_delegate(Object wrapper)
void | unregister_value_factory(String id)
Methods inherited from class org.omg.CORBA.ORB
connect, create_abstract_interface_tc, create_alias_tc, create_any, create_array_tc, create_basic_dyn_any, create_context_list, create_dyn_any, create_dyn_array, create_dyn_enum, create_dyn_sequence, create_dyn_struct, create_dyn_union, create_enum_tc, create_environment, create_exception_list, create_exception_tc, create_fixed_tc, create_interface_tc, create_list, create_named_value, create_native_tc, create_operation_list, create_output_stream, create_policy, create_recursive_sequence_tc, create_recursive_tc, create_sequence_tc, create_string_tc, create_struct_tc, create_union_tc, create_value_box_tc, create_value_tc, create_wstring_tc, destroy, disconnect, get_current, get_default_context, get_next_response, get_primitive_tc, get_service_information, init, init, init, list_initial_services, object_to_string, perform_work, poll_next_response, resolve_initial_references, run, send_multiple_requests_deferred, send_multiple_requests_oneway, set_parameters, set_parameters, shutdown, string_to_object, work_pending
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ORB

public ORB()
Method Detail

register_value_factory

public ValueFactory register_value_factory(String id,
                                           ValueFactory factory)
See Also:
CORBA_2_3 package comments for unimplemented features

unregister_value_factory

public void unregister_value_factory(String id)
See Also:
CORBA_2_3 package comments for unimplemented features

lookup_value_factory

public ValueFactory lookup_value_factory(String id)
See Also:
CORBA_2_3 package comments for unimplemented features

get_value_def

public Object get_value_def(String repid)
                     throws BAD_PARAM
Throws:
BAD_PARAM
See Also:
CORBA_2_3 package comments for unimplemented features

set_delegate

public void set_delegate(Object wrapper)
See Also:
CORBA_2_3 package comments for unimplemented features
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


org.omg.CORBA_2_3 (Java 2 Platform SE v1.4.2)

 org.omg.CORBA_2_3
Classes
ORB


org.omg.CORBA_2_3 (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package org.omg.CORBA_2_3

The CORBA_2_3 package defines additions to existing CORBA interfaces in the Java 2 Standard Edition. 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.

See:
Description

Class Summary
ORB A class extending org.omg.CORBA.ORB to make the ORB portable under the OMG CORBA version 2.3 specification.

Package org.omg.CORBA_2_3 Description

The CORBA_2_3 package defines additions to existing CORBA interfaces in the Java 2 Standard Edition. 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.

Package Specification

For a precise list of supported sections of official specifications with which the Java 2 Platform, Standard Edition, v.1.4 ORB complies, see Official Specifications for CORBA support in J2SE 1.4.

The following methods in the abstract class org.omg.CORBA_2_3.ORB are unimplemented:

  • public org.omg.CORBA.portable.ValueFactory register_value_factory(String id, org.omg.CORBA.portable.ValueFactory factory)
  • public void unregister_value_factory(String id)
  • public org.omg.CORBA.portable.ValueFactory lookup_value_factory(String id)
  • public org.omg.CORBA.Object get_value_def(String repid)
  • public void set_delegate(java.lang.Object wrapper)

Since:
JDK 1.3
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


org.omg.CORBA_2_3 Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package org.omg.CORBA_2_3

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class org.omg.CORBA.ORB
      • class org.omg.CORBA_2_3.ORB
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package org.omg.CORBA_2_3 (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
org.omg.CORBA_2_3

No usage of org.omg.CORBA_2_3

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA_2_3.ORB (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA_2_3.ORB

No usage of org.omg.CORBA_2_3.ORB

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Delegate (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA_2_3.portable
Class Delegate

java.lang.Object
    extended by org.omg.CORBA.portable.Delegate
        extended by org.omg.CORBA_2_3.portable.Delegate
public abstract class Delegate
extends Delegate

Delegate class provides the ORB vendor specific implementation of CORBA object. It extends org.omg.CORBA.portable.Delegate and provides new methods that were defined by CORBA 2.3.

Since:
JDK1.2
See Also:
Delegate

Constructor Summary
Delegate()
Method Summary
 String get_codebase(Object self)
Returns the codebase for object reference provided.
Methods inherited from class org.omg.CORBA.portable.Delegate
create_request, create_request, duplicate, equals, get_domain_managers, get_interface_def, get_policy, hash, hashCode, invoke, is_a, is_equivalent, is_local, non_existent, orb, release, releaseReply, request, request, servant_postinvoke, servant_preinvoke, set_policy_override, toString
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

Delegate

public Delegate()
Method Detail

get_codebase

public String get_codebase(Object self)
Returns the codebase for object reference provided.

Parameters:
self - the object reference whose codebase needs to be returned.
Returns:
the codebase as a space delimited list of url strings or null if none.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


InputStream (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA_2_3.portable
Class InputStream

java.lang.Object
    extended by java.io.InputStream
        extended by org.omg.CORBA.portable.InputStream
            extended by org.omg.CORBA_2_3.portable.InputStream
public abstract class InputStream
extends InputStream

InputStream provides for the reading of all of the mapped IDL types from the stream. It extends org.omg.CORBA.portable.InputStream. This class defines new methods that were added for CORBA 2.3.

Since:
JDK1.2
See Also:
InputStream

Constructor Summary
InputStream()
Method Summary
Object | read_abstract_interface() Unmarshal the value object or a suitable stub object.
Object | read_abstract_interface(Class clz) Unmarshal the class object or the stub class corresponding to the passed type.
Serializable | read_value() Unmarshalls a value type from the input stream.
Serializable | read_value(BoxedValueHelper factory) Unmarshalls a value type from the input stream.
Serializable | read_value(Class clz) Unmarshalls a value type from the input stream.
Serializable | read_value(Serializable value) Unmarshalls a value type from the input stream.
Serializable | read_value(String rep_id) Unmarshalls a value type from the input stream.
Methods inherited from class org.omg.CORBA.portable.InputStream
orb, read_any, read_boolean_array, read_boolean, read_char_array, read_char, read_Context, read_double_array, read_double, read_fixed, read_float_array, read_float, read_long_array, read_long, read_longlong_array, read_longlong, read_Object, read_Object, read_octet_array, read_octet, read_Principal, read_short_array, read_short, read_string, read_TypeCode, read_ulong_array, read_ulong, read_ulonglong_array, read_ulonglong, read_ushort_array, read_ushort, read_wchar_array, read_wchar, read_wstring, read
Methods inherited from class java.io.InputStream
available, close, mark, markSupported, read, read, reset, skip
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

InputStream

public InputStream()
Method Detail

read_value

public Serializable read_value()
Unmarshalls a value type from the input stream.

Returns:
the value type unmarshalled from the input stream

read_value

public Serializable read_value(Class clz)
Unmarshalls a value type from the input stream.

Parameters:
clz - is the declared type of the value to be unmarshalled
Returns:
the value unmarshalled from the input stream

read_value

public Serializable read_value(BoxedValueHelper factory)
Unmarshalls a value type from the input stream.

Parameters:
factory - is the instance fo the helper to be used for unmarshalling the value type
Returns:
the value unmarshalled from the input stream

read_value

public Serializable read_value(String rep_id)
Unmarshalls a value type from the input stream.

Parameters:
rep_id - identifies the type of the value to be unmarshalled
Returns:
value type unmarshalled from the input stream

read_value

public Serializable read_value(Serializable value)
Unmarshalls a value type from the input stream.

Parameters:
value - is an uninitialized value which is added to the orb's indirection table before calling Streamable._read() or CustomMarshal.unmarshal() to unmarshal the value.
Returns:
value type unmarshalled from the input stream

read_abstract_interface

public Object read_abstract_interface()
Unmarshal the value object or a suitable stub object.

Returns:
ORB runtime returns the value object or a suitable stub object.

read_abstract_interface

public Object read_abstract_interface(Class clz)
Unmarshal the class object or the stub class corresponding to the passed type.

Parameters:
clz - is the Class object for the stub class which corresponds to the type that is statically expected.
Returns:
ORB runtime returns the value object or a suitable stub object.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ObjectImpl (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA_2_3.portable
Class ObjectImpl

java.lang.Object
    extended by org.omg.CORBA.portable.ObjectImpl
        extended by org.omg.CORBA_2_3.portable.ObjectImpl
All Implemented Interfaces:
Object
Direct Known Subclasses:
Stub
public abstract class ObjectImpl
extends ObjectImpl

ObjectImpl class is the base class for all stubs. It provides the basic delegation mechanism. It extends org.omg.CORBA.portable.ObjectImpl and provides new methods defined by CORBA 2.3.

Since:
JDK1.2
See Also:
ObjectImpl

Constructor Summary
ObjectImpl()
Method Summary
 String _get_codebase()
Returns the codebase for this object reference.
Methods inherited from class org.omg.CORBA.portable.ObjectImpl
_create_request, _create_request, _duplicate, _get_delegate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _ids, _invoke, _is_a, _is_equivalent, _is_local, _non_existent, _orb, _release, _releaseReply, _request, _request, _servant_postinvoke, _servant_preinvoke, _set_delegate, _set_policy_override, equals, hashCode, toString
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait

Constructor Detail

ObjectImpl

public ObjectImpl()
Method Detail

_get_codebase

public String _get_codebase()
Returns the codebase for this object reference.

Returns:
the codebase as a space delimited list of url strings or null if none.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


OutputStream (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.CORBA_2_3.portable
Class OutputStream

java.lang.Object
    extended by java.io.OutputStream
        extended by org.omg.CORBA.portable.OutputStream
            extended by org.omg.CORBA_2_3.portable.OutputStream
public abstract class OutputStream
extends OutputStream

OutputStream provides interface for writing of all of the mapped IDL type to the stream. It extends org.omg.CORBA.portable.OutputStream, and defines new methods defined by CORBA 2.3.

Since:
JDK1.2
See Also:
OutputStream

Constructor Summary
OutputStream()
Method Summary
void | write_abstract_interface(Object obj) Marshals a value object or a stub object.
void | write_value(Serializable value) Marshals a value type to the output stream.
void | write_value(Serializable value, BoxedValueHelper factory) Marshals a value type to the output stream.
void | write_value(Serializable value, Class clz) Marshals a value type to the output stream.
void | write_value(Serializable value, String repository_id) Marshals a value type to the output stream.
Methods inherited from class org.omg.CORBA.portable.OutputStream
create_input_stream, orb, write_any, write_boolean_array, write_boolean, write_char_array, write_char, write_Context, write_double_array, write_double, write_fixed, write_float_array, write_float, write_long_array, write_long, write_longlong_array, write_longlong, write_Object, write_octet_array, write_octet, write_Principal, write_short_array, write_short, write_string, write_TypeCode, write_ulong_array, write_ulong, write_ulonglong_array, write_ulonglong, write_ushort_array, write_ushort, write_wchar_array, write_wchar, write_wstring, write
Methods inherited from class java.io.OutputStream
close, flush, write, write
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

OutputStream

public OutputStream()
Method Detail

write_value

public void write_value(Serializable value)
Marshals a value type to the output stream.

Parameters:
value - is the acutal value to write

write_value

public void write_value(Serializable value,
                        Class clz)
Marshals a value type to the output stream.

Parameters:
value - is the acutal value to write
clz - is the declared type of the value to be marshaled

write_value

public void write_value(Serializable value,
                        String repository_id)
Marshals a value type to the output stream.

Parameters:
value - is the acutal value to write
repository_id - identifies the type of the value type to be marshaled

write_value

public void write_value(Serializable value,
                        BoxedValueHelper factory)
Marshals a value type to the output stream.

Parameters:
value - is the acutal value to write
factory - is the instance of the helper to be used for marshaling the boxed value

write_abstract_interface

public void write_abstract_interface(Object obj)
Marshals a value object or a stub object.

Parameters:
obj - the actual value object to marshal or the stub to be marshalled
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


org.omg.CORBA_2_3.portable (Java 2 Platform SE v1.4.2)

 org.omg.CORBA_2_3.portable
Classes
Delegate
InputStream
ObjectImpl
OutputStream


org.omg.CORBA_2_3.portable (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

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.

See:
Description

Class Summary
Delegate | Delegate class provides the ORB vendor specific implementation of CORBA object.
InputStream | InputStream provides for the reading of all of the mapped IDL types from the stream.
ObjectImpl | ObjectImpl class is the base class for all stubs.
OutputStream | OutputStream provides interface for writing of all of the mapped IDL type to the stream.

Package org.omg.CORBA_2_3.portable Description

Provides methods for the input and output of value types, and contains other updates to the org/omg/CORBA/portable package.

Since:
1.3
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


org.omg.CORBA_2_3.portable Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package org.omg.CORBA_2_3.portable

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class org.omg.CORBA.portable.Delegate
      • class org.omg.CORBA_2_3.portable.Delegate
    • class java.io.InputStream
      • class org.omg.CORBA.portable.InputStream
        • class org.omg.CORBA_2_3.portable.InputStream
    • class org.omg.CORBA.portable.ObjectImpl (implements org.omg.CORBA.Object)
      • class org.omg.CORBA_2_3.portable.ObjectImpl
    • class java.io.OutputStream
      • class org.omg.CORBA.portable.OutputStream
        • class org.omg.CORBA_2_3.portable.OutputStream
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package org.omg.CORBA_2_3.portable (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
org.omg.CORBA_2_3.portable

Packages that use org.omg.CORBA_2_3.portable
javax.rmi.CORBA | Contains portability APIs for RMI-IIOP.
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.stub.java.rmi | Contains RMI-IIOP Stubs for the Remote types that occur in the java.rmi package.

Classes in org.omg.CORBA_2_3.portable used by javax.rmi.CORBA
ObjectImpl
ObjectImpl class is the base class for all stubs.

Classes in org.omg.CORBA_2_3.portable used by org.omg.CORBA.portable
InputStream
InputStream provides for the reading of all of the mapped IDL types from the stream.

Classes in org.omg.CORBA_2_3.portable used by org.omg.stub.java.rmi
ObjectImpl
ObjectImpl class is the base class for all stubs.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA_2_3.portable.Delegate (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA_2_3.portable.Delegate

No usage of org.omg.CORBA_2_3.portable.Delegate

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA_2_3.portable.InputStream (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA_2_3.portable.InputStream

Packages that use InputStream
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.

Uses of InputStream in org.omg.CORBA.portable

Methods in org.omg.CORBA.portable with parameters of type InputStream
 Serializable ValueFactory.read_value(InputStream is)
Is called by the ORB runtime while in the process of unmarshaling a value type.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA_2_3.portable.ObjectImpl (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA_2_3.portable.ObjectImpl

Packages that use ObjectImpl
javax.rmi.CORBA | Contains portability APIs for RMI-IIOP.
org.omg.stub.java.rmi | Contains RMI-IIOP Stubs for the Remote types that occur in the java.rmi package.

Uses of ObjectImpl in javax.rmi.CORBA

Subclasses of ObjectImpl in javax.rmi.CORBA
 class Stub
Base class from which all RMI-IIOP stubs must inherit.

Uses of ObjectImpl in org.omg.stub.java.rmi

Subclasses of ObjectImpl in org.omg.stub.java.rmi
 class _Remote_Stub
This class provides the Stub for the Remote Type.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CORBA_2_3.portable.OutputStream (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CORBA_2_3.portable.OutputStream

No usage of org.omg.CORBA_2_3.portable.OutputStream

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


_BindingIteratorImplBase (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming
Class _BindingIteratorImplBase

java.lang.Object
    extended by org.omg.CORBA.portable.ObjectImpl
        extended by org.omg.CORBA.DynamicImplementation
            extended by org.omg.CosNaming._BindingIteratorImplBase
All Implemented Interfaces:
BindingIterator, BindingIteratorOperations, IDLEntity, Object, Serializable
public abstract class _BindingIteratorImplBase
extends DynamicImplementation
implements BindingIterator

Constructor Summary
_BindingIteratorImplBase()
Method Summary
String[] | _ids() Retrieves a string array containing the repository identifiers supported by this ObjectImpl object.
void | invoke(ServerRequest r)
Methods inherited from class org.omg.CORBA.portable.ObjectImpl
_create_request, _create_request, _duplicate, _get_delegate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _invoke, _is_a, _is_equivalent, _is_local, _non_existent, _orb, _release, _releaseReply, _request, _request, _servant_postinvoke, _servant_preinvoke, _set_delegate, _set_policy_override, equals, hashCode, toString
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
Methods inherited from interface org.omg.CosNaming.BindingIteratorOperations
destroy, next_n, next_one
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Constructor Detail

_BindingIteratorImplBase

public _BindingIteratorImplBase()
Method Detail

_ids

public String[] _ids()
Description copied from class: ObjectImpl
Retrieves a string array containing the repository identifiers supported by this ObjectImpl object. For example, for a stub, this method returns information about all the interfaces supported by the stub.

Overrides:
_ids in class DynamicImplementation

invoke

public void invoke(ServerRequest r)
Overrides:
invoke in class DynamicImplementation
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


_BindingIteratorStub (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming
Class _BindingIteratorStub

java.lang.Object
    extended by org.omg.CORBA.portable.ObjectImpl
        extended by org.omg.CosNaming._BindingIteratorStub
All Implemented Interfaces:
BindingIterator, BindingIteratorOperations, IDLEntity, Object, Serializable
public class _BindingIteratorStub
extends ObjectImpl
implements BindingIterator

The BindingIterator interface allows a client to iterate through the bindings using the next_one or next_n operations. The bindings iterator is obtained by using the list method on the NamingContext.

See Also:
NamingContextOperations.list(int, org.omg.CosNaming.BindingListHolder, org.omg.CosNaming.BindingIteratorHolder)

Constructor Summary
_BindingIteratorStub()
Method Summary
String[] | _ids() Retrieves a string array containing the repository identifiers supported by this ObjectImpl object.
void | destroy() This operation destroys the iterator.
boolean | next_n(int how_many, BindingListHolder bl) This operation returns at most the requested number of bindings.
boolean | next_one(BindingHolder b) This operation returns the next binding.
Methods inherited from class org.omg.CORBA.portable.ObjectImpl
_create_request, _create_request, _duplicate, _get_delegate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _invoke, _is_a, _is_equivalent, _is_local, _non_existent, _orb, _release, _releaseReply, _request, _request, _servant_postinvoke, _servant_preinvoke, _set_delegate, _set_policy_override, equals, hashCode, toString
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Constructor Detail

_BindingIteratorStub

public _BindingIteratorStub()
Method Detail

next_one

public boolean next_one(BindingHolder b)
This operation returns the next binding. If there are no more bindings, false is returned.

Specified by:
next_one in interface BindingIteratorOperations
Parameters:
b - the returned binding

next_n

public boolean next_n(int how_many,
                      BindingListHolder bl)
This operation returns at most the requested number of bindings.

Specified by:
next_n in interface BindingIteratorOperations
Parameters:
how_many - the maximum number of bindings tro return

bl - the returned bindings

destroy

public void destroy()
This operation destroys the iterator.

Specified by:
destroy in interface BindingIteratorOperations

_ids

public String[] _ids()
Description copied from class: ObjectImpl
Retrieves a string array containing the repository identifiers supported by this ObjectImpl object. For example, for a stub, this method returns information about all the interfaces supported by the stub.

Specified by:
_ids in class ObjectImpl
Returns:
the array of all repository identifiers supported by this ObjectImpl instance
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


_NamingContextExtStub (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming
Class _NamingContextExtStub

java.lang.Object
    extended by org.omg.CORBA.portable.ObjectImpl
        extended by org.omg.CosNaming._NamingContextExtStub
All Implemented Interfaces:
IDLEntity, NamingContext, NamingContextExt, NamingContextExtOperations, NamingContextOperations, Object, Serializable
public class _NamingContextExtStub
extends ObjectImpl
implements NamingContextExt

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. 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.

See CORBA COS Naming Specification.

Constructor Summary
_NamingContextExtStub()
Method Summary
String[] | _ids() Retrieves a string array containing the repository identifiers supported by this ObjectImpl object.
void | bind_context(NameComponent[] n, NamingContext nc) Names an object that is a naming context.
NamingContext | bind_new_context(NameComponent[] n) This operation creates a new context and binds it to the name supplied as an argument.
void | bind(NameComponent[] n, Object obj) Creates a binding of a name and an object in the naming context.
void | destroy() The destroy operation deletes a naming context.
void | list(int how_many, BindingListHolder bl, BindingIteratorHolder bi) The list operation allows a client to iterate through a set of bindings in a naming context.
NamingContext | new_context() This operation returns a naming context implemented by the same naming server as the context on which the operation was invoked.
void | rebind_context(NameComponent[] n, NamingContext nc) Creates a binding of a name and a naming context in the naming context even if the name is already bound in the context.
void | rebind(NameComponent[] n, Object obj) Creates a binding of a name and an object in the naming context even if the name is already bound in the context.
Object | resolve_str(String sn) This operation resolves the Stringified name into the object reference.
Object | resolve(NameComponent[] n) The resolve operation is the process of retrieving an object bound to a name in a given context.
NameComponent[] | to_name(String sn) This operation converts a Stringified Name into an equivalent array of Name Components.
String | to_string(NameComponent[] n) This operation creates a stringified name from the array of Name components.
String | to_url(String addr, String sn) This operation creates a URL based "iiopname://" format name from the Stringified Name of the object.
void | unbind(NameComponent[] n) The unbind operation removes a name binding from a context.
Methods inherited from class org.omg.CORBA.portable.ObjectImpl
_create_request, _create_request, _duplicate, _get_delegate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _invoke, _is_a, _is_equivalent, _is_local, _non_existent, _orb, _release, _releaseReply, _request, _request, _servant_postinvoke, _servant_preinvoke, _set_delegate, _set_policy_override, equals, hashCode, toString
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Constructor Detail

_NamingContextExtStub

public _NamingContextExtStub()
Method Detail

to_string

public String to_string(NameComponent[] n)
                 throws InvalidName
This operation creates a stringified name from the array of Name components.

Specified by:
to_string in interface NamingContextExtOperations
Parameters:
n - Name of the object

Throws:
org.omg.CosNaming.NamingContextExtPackage.InvalidName - Indicates the name does not identify a binding.

InvalidName

to_name

public NameComponent[] to_name(String sn)
                        throws InvalidName
This operation converts a Stringified Name into an equivalent array of Name Components.

Specified by:
to_name in interface NamingContextExtOperations
Parameters:
sn - Stringified Name of the object

Throws:
org.omg.CosNaming.NamingContextExtPackage.InvalidName - Indicates the name does not identify a binding.

InvalidName

to_url

public String to_url(String addr,
                     String sn)
              throws InvalidAddress,
                     InvalidName
This operation creates a URL based "iiopname://" format name from the Stringified Name of the object.

Specified by:
to_url in interface NamingContextExtOperations
Parameters:
addr - internet based address of the host machine where Name Service is running

sn - Stringified Name of the object

Throws:
org.omg.CosNaming.NamingContextExtPackage.InvalidName - Indicates the name does not identify a binding.

org.omg.CosNaming.NamingContextPackage.InvalidAddress - Indicates the internet based address of the host machine is incorrect

InvalidAddress
InvalidName

resolve_str

public Object resolve_str(String sn)
                   throws NotFound,
                          CannotProceed,
                          InvalidName
This operation resolves the Stringified name into the object reference.

Specified by:
resolve_str in interface NamingContextExtOperations
Parameters:
sn - Stringified Name of the object

Throws:
NotFound - Indicates there is no object reference for the given name.

CannotProceed - Indicates that the given compound name is incorrect

org.omg.CosNaming.NamingContextExtPackage.InvalidName - Indicates the name does not identify a binding.

InvalidName

bind

public void bind(NameComponent[] n,
                 Object obj)
          throws NotFound,
                 CannotProceed,
                 InvalidName,
                 AlreadyBound
Creates a binding of a name and an object in the naming context. Naming contexts that are bound using bind do not participate in name resolution when compound names are passed to be resolved.

Specified by:
bind in interface NamingContextOperations
Parameters:
n - Name of the object

obj - The Object to bind with the given name

Throws:
NotFound - Indicates the name does not identify a binding.

CannotProceed - Indicates that the implementation has given up for some reason. The client, however, may be able to continue the operation at the returned naming context.

InvalidName - Indicates that the name is invalid.

AlreadyBound - Indicates an object is already bound to the specified name.

bind_context

public void bind_context(NameComponent[] n,
                         NamingContext nc)
                  throws NotFound,
                         CannotProceed,
                         InvalidName,
                         AlreadyBound
Names an object that is a naming context. Naming contexts that are bound using bind_context() participate in name resolution when compound names are passed to be resolved.

Specified by:
bind_context in interface NamingContextOperations
Parameters:
n - Name of the object

nc - NamingContect object to bind with the given name

Throws:
NotFound - Indicates the name does not identify a binding.

CannotProceed - Indicates that the implementation has given up for some reason. The client, however, may be able to continue the operation at the returned naming context.

InvalidName - Indicates that the name is invalid.

AlreadyBound - Indicates an object is already bound to the specified name.

rebind

public void rebind(NameComponent[] n,
                   Object obj)
            throws NotFound,
                   CannotProceed,
                   InvalidName
Creates a binding of a name and an object in the naming context even if the name is already bound in the context. Naming contexts that are bound using rebind do not participate in name resolution when compound names are passed to be resolved.

Specified by:
rebind in interface NamingContextOperations
Parameters:
n - Name of the object

Throws:
NotFound - Indicates the name does not identify a binding.

CannotProceed - Indicates that the implementation has given up for some reason. The client, however, may be able to continue the operation at the returned naming context.

InvalidName - Indicates that the name is invalid.

rebind_context

public void rebind_context(NameComponent[] n,
                           NamingContext nc)
                    throws NotFound,
                           CannotProceed,
                           InvalidName
Creates a binding of a name and a naming context in the naming context even if the name is already bound in the context. Naming contexts that are bound using rebind_context() participate in name resolution when compound names are passed to be resolved.

Specified by:
rebind_context in interface NamingContextOperations
Parameters:
n - Name of the object

nc - NamingContect object to rebind with the given name

Throws:
NotFound - Indicates the name does not identify a binding.

CannotProceed - Indicates that the implementation has given up for some reason. The client, however, may be able to continue the operation at the returned naming context.

InvalidName - Indicates that the name is invalid.

resolve

public Object resolve(NameComponent[] n)
               throws NotFound,
                      CannotProceed,
                      InvalidName
The resolve operation is the process of retrieving an object bound to a name in a given context. The given name must exactly match the bound name. The naming service does not return the type of the object. Clients are responsible for "narrowing" the object to the appropriate type. That is, clients typically cast the returned object from Object to a more specialized interface.

Specified by:
resolve in interface NamingContextOperations
Parameters:
n - Name of the object

Throws:
NotFound - Indicates the name does not identify a binding.

CannotProceed - Indicates that the implementation has given up for some reason. The client, however, may be able to continue the operation at the returned naming context.

InvalidName - Indicates that the name is invalid.

unbind

public void unbind(NameComponent[] n)
            throws NotFound,
                   CannotProceed,
                   InvalidName
The unbind operation removes a name binding from a context.

Specified by:
unbind in interface NamingContextOperations
Parameters:
n - Name of the object

Throws:
NotFound - Indicates the name does not identify a binding.

CannotProceed - Indicates that the implementation has given up for some reason. The client, however, may be able to continue the operation at the returned naming context.

InvalidName - Indicates that the name is invalid.

list

public void list(int how_many,
                 BindingListHolder bl,
                 BindingIteratorHolder bi)
The list operation allows a client to iterate through a set of bindings in a naming context.

The list operation returns at most the requested number of bindings in BindingList bl.

  • If the naming context contains additional bindings, the list operation returns a BindingIterator with the additional bindings.
  • If the naming context does not contain additional bindings, the binding iterator is a nil object reference.

Specified by:
list in interface NamingContextOperations
Parameters:
how_many - the maximum number of bindings to return

bl - the returned list of bindings

bi - the returned binding iterator

new_context

public NamingContext new_context()
This operation returns a naming context implemented by the same naming server as the context on which the operation was invoked. The new context is not bound to any name.

Specified by:
new_context in interface NamingContextOperations

bind_new_context

public NamingContext bind_new_context(NameComponent[] n)
                               throws NotFound,
                                      AlreadyBound,
                                      CannotProceed,
                                      InvalidName
This operation creates a new context and binds it to the name supplied as an argument. The newly-created context is implemented by the same naming server as the context in which it was bound (that is, the naming server that implements the context denoted by the name argument excluding the last component).

Specified by:
bind_new_context in interface NamingContextOperations
Parameters:
n - Name of the object

Throws:
NotFound - Indicates the name does not identify a binding.

AlreadyBound - Indicates an object is already bound to the specified name.

CannotProceed - Indicates that the implementation has given up for some reason. The client, however, may be able to continue the operation at the returned naming context.

InvalidName - Indicates that the name is invalid.

destroy

public void destroy()
             throws NotEmpty
The destroy operation deletes a naming context. If the naming context contains bindings, the NotEmpty exception is raised.

Specified by:
destroy in interface NamingContextOperations
Throws:
NotEmpty - Indicates that the Naming Context contains bindings.

_ids

public String[] _ids()
Description copied from class: ObjectImpl
Retrieves a string array containing the repository identifiers supported by this ObjectImpl object. For example, for a stub, this method returns information about all the interfaces supported by the stub.

Specified by:
_ids in class ObjectImpl
Returns:
the array of all repository identifiers supported by this ObjectImpl instance
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


_NamingContextImplBase (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming
Class _NamingContextImplBase

java.lang.Object
    extended by org.omg.CORBA.portable.ObjectImpl
        extended by org.omg.CORBA.DynamicImplementation
            extended by org.omg.CosNaming._NamingContextImplBase
All Implemented Interfaces:
IDLEntity, NamingContext, NamingContextOperations, Object, Serializable
public abstract class _NamingContextImplBase
extends DynamicImplementation
implements NamingContext

Constructor Summary
_NamingContextImplBase()
Method Summary
String[] | _ids() Retrieves a string array containing the repository identifiers supported by this ObjectImpl object.
void | invoke(ServerRequest r)
Methods inherited from class org.omg.CORBA.portable.ObjectImpl
_create_request, _create_request, _duplicate, _get_delegate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _invoke, _is_a, _is_equivalent, _is_local, _non_existent, _orb, _release, _releaseReply, _request, _request, _servant_postinvoke, _servant_preinvoke, _set_delegate, _set_policy_override, equals, hashCode, toString
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
Methods inherited from interface org.omg.CosNaming.NamingContextOperations
bind_context, bind_new_context, bind, destroy, list, new_context, rebind_context, rebind, resolve, unbind
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Constructor Detail

_NamingContextImplBase

public _NamingContextImplBase()
Method Detail

_ids

public String[] _ids()
Description copied from class: ObjectImpl
Retrieves a string array containing the repository identifiers supported by this ObjectImpl object. For example, for a stub, this method returns information about all the interfaces supported by the stub.

Overrides:
_ids in class DynamicImplementation

invoke

public void invoke(ServerRequest r)
Overrides:
invoke in class DynamicImplementation
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


_NamingContextStub (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming
Class _NamingContextStub

java.lang.Object
    extended by org.omg.CORBA.portable.ObjectImpl
        extended by org.omg.CosNaming._NamingContextStub
All Implemented Interfaces:
IDLEntity, NamingContext, NamingContextOperations, Object, Serializable
public class _NamingContextStub
extends ObjectImpl
implements NamingContext

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.

See CORBA COS Naming Specification.

Constructor Summary
_NamingContextStub()
Method Summary
String[] | _ids() Retrieves a string array containing the repository identifiers supported by this ObjectImpl object.
void | bind_context(NameComponent[] n, NamingContext nc) Names an object that is a naming context.
NamingContext | bind_new_context(NameComponent[] n) This operation creates a new context and binds it to the name supplied as an argument.
void | bind(NameComponent[] n, Object obj) Creates a binding of a name and an object in the naming context.
void | destroy() The destroy operation deletes a naming context.
void | list(int how_many, BindingListHolder bl, BindingIteratorHolder bi) The list operation allows a client to iterate through a set of bindings in a naming context.
NamingContext | new_context() This operation returns a naming context implemented by the same naming server as the context on which the operation was invoked.
void | rebind_context(NameComponent[] n, NamingContext nc) Creates a binding of a name and a naming context in the naming context even if the name is already bound in the context.
void | rebind(NameComponent[] n, Object obj) Creates a binding of a name and an object in the naming context even if the name is already bound in the context.
Object | resolve(NameComponent[] n) The resolve operation is the process of retrieving an object bound to a name in a given context.
void | unbind(NameComponent[] n) The unbind operation removes a name binding from a context.
Methods inherited from class org.omg.CORBA.portable.ObjectImpl
_create_request, _create_request, _duplicate, _get_delegate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _invoke, _is_a, _is_equivalent, _is_local, _non_existent, _orb, _release, _releaseReply, _request, _request, _servant_postinvoke, _servant_preinvoke, _set_delegate, _set_policy_override, equals, hashCode, toString
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Constructor Detail

_NamingContextStub

public _NamingContextStub()
Method Detail

bind

public void bind(NameComponent[] n,
                 Object obj)
          throws NotFound,
                 CannotProceed,
                 InvalidName,
                 AlreadyBound
Creates a binding of a name and an object in the naming context. Naming contexts that are bound using bind do not participate in name resolution when compound names are passed to be resolved.

Specified by:
bind in interface NamingContextOperations
Parameters:
n - Name of the object

obj - The Object to bind with the given name

Throws:
NotFound - Indicates the name does not identify a binding.

CannotProceed - Indicates that the implementation has given up for some reason. The client, however, may be able to continue the operation at the returned naming context.

InvalidName - Indicates that the name is invalid.

AlreadyBound - Indicates an object is already bound to the specified name.

bind_context

public void bind_context(NameComponent[] n,
                         NamingContext nc)
                  throws NotFound,
                         CannotProceed,
                         InvalidName,
                         AlreadyBound
Names an object that is a naming context. Naming contexts that are bound using bind_context() participate in name resolution when compound names are passed to be resolved.

Specified by:
bind_context in interface NamingContextOperations
Parameters:
n - Name of the object

nc - NamingContect object to bind with the given name

Throws:
NotFound - Indicates the name does not identify a binding.

CannotProceed - Indicates that the implementation has given up for some reason. The client, however, may be able to continue the operation at the returned naming context.

InvalidName - Indicates that the name is invalid.

AlreadyBound - Indicates an object is already bound to the specified name.

rebind

public void rebind(NameComponent[] n,
                   Object obj)
            throws NotFound,
                   CannotProceed,
                   InvalidName
Creates a binding of a name and an object in the naming context even if the name is already bound in the context. Naming contexts that are bound using rebind do not participate in name resolution when compound names are passed to be resolved.

Specified by:
rebind in interface NamingContextOperations
Parameters:
n - Name of the object

Throws:
NotFound - Indicates the name does not identify a binding.

CannotProceed - Indicates that the implementation has given up for some reason. The client, however, may be able to continue the operation at the returned naming context.

InvalidName - Indicates that the name is invalid.

rebind_context

public void rebind_context(NameComponent[] n,
                           NamingContext nc)
                    throws NotFound,
                           CannotProceed,
                           InvalidName
Creates a binding of a name and a naming context in the naming context even if the name is already bound in the context. Naming contexts that are bound using rebind_context() participate in name resolution when compound names are passed to be resolved.

Specified by:
rebind_context in interface NamingContextOperations
Parameters:
n - Name of the object

nc - NamingContect object to rebind with the given name

Throws:
NotFound - Indicates the name does not identify a binding.

CannotProceed - Indicates that the implementation has given up for some reason. The client, however, may be able to continue the operation at the returned naming context.

InvalidName - Indicates that the name is invalid.

resolve

public Object resolve(NameComponent[] n)
               throws NotFound,
                      CannotProceed,
                      InvalidName
The resolve operation is the process of retrieving an object bound to a name in a given context. The given name must exactly match the bound name. The naming service does not return the type of the object. Clients are responsible for "narrowing" the object to the appropriate type. That is, clients typically cast the returned object from Object to a more specialized interface.

Specified by:
resolve in interface NamingContextOperations
Parameters:
n - Name of the object

Throws:
NotFound - Indicates the name does not identify a binding.

CannotProceed - Indicates that the implementation has given up for some reason. The client, however, may be able to continue the operation at the returned naming context.

InvalidName - Indicates that the name is invalid.

unbind

public void unbind(NameComponent[] n)
            throws NotFound,
                   CannotProceed,
                   InvalidName
The unbind operation removes a name binding from a context.

Specified by:
unbind in interface NamingContextOperations
Parameters:
n - Name of the object

Throws:
NotFound - Indicates the name does not identify a binding.

CannotProceed - Indicates that the implementation has given up for some reason. The client, however, may be able to continue the operation at the returned naming context.

InvalidName - Indicates that the name is invalid.

list

public void list(int how_many,
                 BindingListHolder bl,
                 BindingIteratorHolder bi)
The list operation allows a client to iterate through a set of bindings in a naming context.

The list operation returns at most the requested number of bindings in BindingList bl.

  • If the naming context contains additional bindings, the list operation returns a BindingIterator with the additional bindings.
  • If the naming context does not contain additional bindings, the binding iterator is a nil object reference.

Specified by:
list in interface NamingContextOperations
Parameters:
how_many - the maximum number of bindings to return

bl - the returned list of bindings

bi - the returned binding iterator

new_context

public NamingContext new_context()
This operation returns a naming context implemented by the same naming server as the context on which the operation was invoked. The new context is not bound to any name.

Specified by:
new_context in interface NamingContextOperations

bind_new_context

public NamingContext bind_new_context(NameComponent[] n)
                               throws NotFound,
                                      AlreadyBound,
                                      CannotProceed,
                                      InvalidName
This operation creates a new context and binds it to the name supplied as an argument. The newly-created context is implemented by the same naming server as the context in which it was bound (that is, the naming server that implements the context denoted by the name argument excluding the last component).

Specified by:
bind_new_context in interface NamingContextOperations
Parameters:
n - Name of the object

Throws:
NotFound - Indicates the name does not identify a binding.

AlreadyBound - Indicates an object is already bound to the specified name.

CannotProceed - Indicates that the implementation has given up for some reason. The client, however, may be able to continue the operation at the returned naming context.

InvalidName - Indicates that the name is invalid.

destroy

public void destroy()
             throws NotEmpty
The destroy operation deletes a naming context. If the naming context contains bindings, the NotEmpty exception is raised.

Specified by:
destroy in interface NamingContextOperations
Throws:
NotEmpty - Indicates that the Naming Context contains bindings.

_ids

public String[] _ids()
Description copied from class: ObjectImpl
Retrieves a string array containing the repository identifiers supported by this ObjectImpl object. For example, for a stub, this method returns information about all the interfaces supported by the stub.

Specified by:
_ids in class ObjectImpl
Returns:
the array of all repository identifiers supported by this ObjectImpl instance
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Binding (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming
Class Binding

java.lang.Object
    extended by org.omg.CosNaming.Binding
All Implemented Interfaces:
IDLEntity, Serializable
public final class Binding
extends Object
implements IDLEntity

A name-to-object association is called a Binding.

Field Summary
NameComponent[] | binding_name
BindingType | binding_type
Constructor Summary
Binding()
Binding(NameComponent[] _binding_name, BindingType _binding_type)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

binding_name

public NameComponent[] binding_name

binding_type

public BindingType binding_type
Constructor Detail

Binding

public Binding()

Binding

public Binding(NameComponent[] _binding_name,
               BindingType _binding_type)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


BindingHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming
Class BindingHelper

java.lang.Object
    extended by org.omg.CosNaming.BindingHelper
public abstract class BindingHelper
extends Object

A name-to-object association is called a Binding.

Constructor Summary
BindingHelper()
Method Summary
static Binding | extract(Any a)
static String | id()
static void | insert(Any a, Binding that)
static Binding | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, Binding value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

BindingHelper

public BindingHelper()
Method Detail

insert

public static void insert(Any a,
                          Binding that)

extract

public static Binding extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static Binding read(InputStream istream)

write

public static void write(OutputStream ostream,
                         Binding value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


BindingHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming
Class BindingHolder

java.lang.Object
    extended by org.omg.CosNaming.BindingHolder
All Implemented Interfaces:
Streamable
public final class BindingHolder
extends Object
implements Streamable

A name-to-object association is called a Binding.

Field Summary
 Binding value
Constructor Summary
BindingHolder()
BindingHolder(Binding initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public Binding value
Constructor Detail

BindingHolder

public BindingHolder()

BindingHolder

public BindingHolder(Binding initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


BindingIterator (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming
Interface BindingIterator

All Superinterfaces:
BindingIteratorOperations, IDLEntity, Object, Serializable
All Known Implementing Classes:
_BindingIteratorImplBase, _BindingIteratorStub
public interface BindingIterator
extends BindingIteratorOperations, Object, IDLEntity

The BindingIterator interface allows a client to iterate through the bindings using the next_one or next_n operations. The bindings iterator is obtained by using the list method on the NamingContext.

See Also:
NamingContextOperations.list(int, org.omg.CosNaming.BindingListHolder, org.omg.CosNaming.BindingIteratorHolder)

Methods inherited from interface org.omg.CosNaming.BindingIteratorOperations
destroy, next_n, next_one
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


BindingIteratorHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming
Class BindingIteratorHelper

java.lang.Object
    extended by org.omg.CosNaming.BindingIteratorHelper
public abstract class BindingIteratorHelper
extends Object

The BindingIterator interface allows a client to iterate through the bindings using the next_one or next_n operations. The bindings iterator is obtained by using the list method on the NamingContext.

See Also:
NamingContextOperations.list(int, org.omg.CosNaming.BindingListHolder, org.omg.CosNaming.BindingIteratorHolder)

Constructor Summary
BindingIteratorHelper()
Method Summary
static BindingIterator | extract(Any a)
static String | id()
static void | insert(Any a, BindingIterator that)
static BindingIterator | narrow(Object obj)
static BindingIterator | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, BindingIterator value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

BindingIteratorHelper

public BindingIteratorHelper()
Method Detail

insert

public static void insert(Any a,
                          BindingIterator that)

extract

public static BindingIterator extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static BindingIterator read(InputStream istream)

write

public static void write(OutputStream ostream,
                         BindingIterator value)

narrow

public static BindingIterator narrow(Object obj)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


BindingIteratorHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming
Class BindingIteratorHolder

java.lang.Object
    extended by org.omg.CosNaming.BindingIteratorHolder
All Implemented Interfaces:
Streamable
public final class BindingIteratorHolder
extends Object
implements Streamable

The BindingIterator interface allows a client to iterate through the bindings using the next_one or next_n operations. The bindings iterator is obtained by using the list method on the NamingContext.

See Also:
NamingContextOperations.list(int, org.omg.CosNaming.BindingListHolder, org.omg.CosNaming.BindingIteratorHolder)

Field Summary
 BindingIterator value
Constructor Summary
BindingIteratorHolder()
BindingIteratorHolder(BindingIterator initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public BindingIterator value
Constructor Detail

BindingIteratorHolder

public BindingIteratorHolder()

BindingIteratorHolder

public BindingIteratorHolder(BindingIterator initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


BindingIteratorOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming
Interface BindingIteratorOperations

All Known Subinterfaces:
BindingIterator
All Known Implementing Classes:
_BindingIteratorImplBase, _BindingIteratorStub, BindingIteratorPOA
public interface BindingIteratorOperations

The BindingIterator interface allows a client to iterate through the bindings using the next_one or next_n operations. The bindings iterator is obtained by using the list method on the NamingContext.

See Also:
NamingContextOperations.list(int, org.omg.CosNaming.BindingListHolder, org.omg.CosNaming.BindingIteratorHolder)

Method Summary
void | destroy() This operation destroys the iterator.
boolean | next_n(int how_many, BindingListHolder bl) This operation returns at most the requested number of bindings.
boolean | next_one(BindingHolder b) This operation returns the next binding.

Method Detail

next_one

public boolean next_one(BindingHolder b)
This operation returns the next binding. If there are no more bindings, false is returned.

Parameters:
b - the returned binding

next_n

public boolean next_n(int how_many,
                      BindingListHolder bl)
This operation returns at most the requested number of bindings.

Parameters:
how_many - the maximum number of bindings tro return

bl - the returned bindings

destroy

public void destroy()
This operation destroys the iterator.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


BindingIteratorPOA (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming
Class BindingIteratorPOA

java.lang.Object
    extended by org.omg.PortableServer.Servant
        extended by org.omg.CosNaming.BindingIteratorPOA
All Implemented Interfaces:
BindingIteratorOperations, InvokeHandler
public abstract class BindingIteratorPOA
extends Servant
implements BindingIteratorOperations, InvokeHandler

The BindingIterator interface allows a client to iterate through the bindings using the next_one or next_n operations. The bindings iterator is obtained by using the list method on the NamingContext.

See Also:
NamingContextOperations.list(int, org.omg.CosNaming.BindingListHolder, org.omg.CosNaming.BindingIteratorHolder)

Constructor Summary
BindingIteratorPOA()
Method Summary
String[] | _all_interfaces(POA poa, byte[] objectId) Used by the ORB to obtain complete type information from the servant.
OutputStream | _invoke(String $method, InputStream in, ResponseHandler $rh) Invoked by the ORB to dispatch a request to the servant.
BindingIterator | _this()
BindingIterator | _this(ORB orb)
Methods inherited from class org.omg.PortableServer.Servant
_default_POA, _get_delegate, _get_interface_def, _is_a, _non_existent, _object_id, _orb, _poa, _set_delegate, _this_object, _this_object
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Methods inherited from interface org.omg.CosNaming.BindingIteratorOperations
destroy, next_n, next_one

Constructor Detail

BindingIteratorPOA

public BindingIteratorPOA()
Method Detail

_invoke

public OutputStream _invoke(String $method,
                            InputStream in,
                            ResponseHandler $rh)
Description copied from interface: InvokeHandler
Invoked by the ORB to dispatch a request to the servant. ORB passes the method name, an InputStream containing the marshalled arguments, and a ResponseHandler which the servant uses to construct a proper reply. Only CORBA SystemException may be thrown by this method. The method must return an OutputStream created by the ResponseHandler which contains the marshalled reply. A servant must not retain a reference to the ResponseHandler beyond the lifetime of a method invocation. Servant behaviour is defined as follows:

1. Determine correct method, and unmarshal parameters from InputStream.

2. Invoke method implementation.

3. If no user exception, create a normal reply using ResponseHandler.

4. If user exception occurred, create exception reply using ResponseHandler.

5. Marshal reply into OutputStream returned by ResponseHandler.

6. Return OutputStream to ORB.

Specified by:
_invoke in interface InvokeHandler
Parameters:
$method - The method name.
in - The InputStream containing the marshalled arguments.
$rh - The ResponseHandler which the servant uses to construct a proper reply
Returns:
The OutputStream created by the ResponseHandler which contains the marshalled reply

_all_interfaces

public String[] _all_interfaces(POA poa,
                                byte[] objectId)
Description copied from class: Servant
Used by the ORB to obtain complete type information from the servant.

Specified by:
_all_interfaces in class Servant
Parameters:
poa - POA with which the servant is associated.
objectId - is the id corresponding to the object associated with this servant.
Returns:
list of type information for the object.

_this

public BindingIterator _this()

_this

public BindingIterator _this(ORB orb)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


BindingListHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming
Class BindingListHelper

java.lang.Object
    extended by org.omg.CosNaming.BindingListHelper
public abstract class BindingListHelper
extends Object

List of Bindings.

Constructor Summary
BindingListHelper()
Method Summary
static Binding[] | extract(Any a)
static String | id()
static void | insert(Any a, Binding[] that)
static Binding[] | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, Binding[] value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

BindingListHelper

public BindingListHelper()
Method Detail

insert

public static void insert(Any a,
                          Binding[] that)

extract

public static Binding[] extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static Binding[] read(InputStream istream)

write

public static void write(OutputStream ostream,
                         Binding[] value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


BindingListHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming
Class BindingListHolder

java.lang.Object
    extended by org.omg.CosNaming.BindingListHolder
All Implemented Interfaces:
Streamable
public final class BindingListHolder
extends Object
implements Streamable

List of Bindings.

Field Summary
 Binding[] value
Constructor Summary
BindingListHolder()
BindingListHolder(Binding[] initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public Binding[] value
Constructor Detail

BindingListHolder

public BindingListHolder()

BindingListHolder

public BindingListHolder(Binding[] initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


BindingType (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming
Class BindingType

java.lang.Object
    extended by org.omg.CosNaming.BindingType
All Implemented Interfaces:
IDLEntity, Serializable
public class BindingType
extends Object
implements IDLEntity

Specifies whether the given binding is for a object (that is not a naming context) or for a naming context.

Field Summary
static int | _ncontext
static int | _nobject
static BindingType | ncontext
static BindingType | nobject
Constructor Summary
protected BindingType(int value)
Method Summary
static BindingType | from_int(int value)
int | value()
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

_nobject

public static final int _nobject
See Also:
Constant Field Values

nobject

public static final BindingType nobject

_ncontext

public static final int _ncontext
See Also:
Constant Field Values

ncontext

public static final BindingType ncontext
Constructor Detail

BindingType

protected BindingType(int value)
Method Detail

value

public int value()

from_int

public static BindingType from_int(int value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


BindingTypeHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming
Class BindingTypeHelper

java.lang.Object
    extended by org.omg.CosNaming.BindingTypeHelper
public abstract class BindingTypeHelper
extends Object

Specifies whether the given binding is for a object (that is not a naming context) or for a naming context.

Constructor Summary
BindingTypeHelper()
Method Summary
static BindingType | extract(Any a)
static String | id()
static void | insert(Any a, BindingType that)
static BindingType | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, BindingType value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

BindingTypeHelper

public BindingTypeHelper()
Method Detail

insert

public static void insert(Any a,
                          BindingType that)

extract

public static BindingType extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static BindingType read(InputStream istream)

write

public static void write(OutputStream ostream,
                         BindingType value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


BindingTypeHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming
Class BindingTypeHolder

java.lang.Object
    extended by org.omg.CosNaming.BindingTypeHolder
All Implemented Interfaces:
Streamable
public final class BindingTypeHolder
extends Object
implements Streamable

Specifies whether the given binding is for a object (that is not a naming context) or for a naming context.

Field Summary
 BindingType value
Constructor Summary
BindingTypeHolder()
BindingTypeHolder(BindingType initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public BindingType value
Constructor Detail

BindingTypeHolder

public BindingTypeHolder()

BindingTypeHolder

public BindingTypeHolder(BindingType initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


IstringHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming
Class IstringHelper

java.lang.Object
    extended by org.omg.CosNaming.IstringHelper
public abstract class IstringHelper
extends Object

org/omg/CosNaming/IstringHelper.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/CosNaming/nameservice.idl Thursday, June 12, 2003 9:59:21 PM GMT-08:00

Constructor Summary
IstringHelper()
Method Summary
static String | extract(Any a)
static String | id()
static void | insert(Any a, String that)
static String | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, String value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

IstringHelper

public IstringHelper()
Method Detail

insert

public static void insert(Any a,
                          String that)

extract

public static String extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static String read(InputStream istream)

write

public static void write(OutputStream ostream,
                         String value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NameComponent (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming
Class NameComponent

java.lang.Object
    extended by org.omg.CosNaming.NameComponent
All Implemented Interfaces:
IDLEntity, Serializable
public final class NameComponent
extends Object
implements IDLEntity

Many of the operations defined on a naming context take names as parameters. Names have structure. A name is an ordered sequence of components.

A name with a single component is called a simple name; a name with multiple components is called a compound name. Each component except the last is used to name a context; the last component denotes the bound object.

A name component consists of two attributes: the identifier attribute and the kind attribute. Both the identifier attribute and the kind attribute are represented as IDL strings. The kind attribute adds descriptive power to names in a syntax-independent way. Examples of the value of the kind attribute include c_source, object_code, executable, postscript, or " ".

Field Summary
String | id
String | kind
Constructor Summary
NameComponent()
NameComponent(String _id, String _kind)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

id

public String id

kind

public String kind
Constructor Detail

NameComponent

public NameComponent()

NameComponent

public NameComponent(String _id,
                     String _kind)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NameComponentHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming
Class NameComponentHelper

java.lang.Object
    extended by org.omg.CosNaming.NameComponentHelper
public abstract class NameComponentHelper
extends Object

Many of the operations defined on a naming context take names as parameters. Names have structure. A name is an ordered sequence of components.

A name with a single component is called a simple name; a name with multiple components is called a compound name. Each component except the last is used to name a context; the last component denotes the bound object.

A name component consists of two attributes: the identifier attribute and the kind attribute. Both the identifier attribute and the kind attribute are represented as IDL strings. The kind attribute adds descriptive power to names in a syntax-independent way. Examples of the value of the kind attribute include c_source, object_code, executable, postscript, or " ".

Constructor Summary
NameComponentHelper()
Method Summary
static NameComponent | extract(Any a)
static String | id()
static void | insert(Any a, NameComponent that)
static NameComponent | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, NameComponent value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

NameComponentHelper

public NameComponentHelper()
Method Detail

insert

public static void insert(Any a,
                          NameComponent that)

extract

public static NameComponent extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static NameComponent read(InputStream istream)

write

public static void write(OutputStream ostream,
                         NameComponent value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NameComponentHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming
Class NameComponentHolder

java.lang.Object
    extended by org.omg.CosNaming.NameComponentHolder
All Implemented Interfaces:
Streamable
public final class NameComponentHolder
extends Object
implements Streamable

Many of the operations defined on a naming context take names as parameters. Names have structure. A name is an ordered sequence of components.

A name with a single component is called a simple name; a name with multiple components is called a compound name. Each component except the last is used to name a context; the last component denotes the bound object.

A name component consists of two attributes: the identifier attribute and the kind attribute. Both the identifier attribute and the kind attribute are represented as IDL strings. The kind attribute adds descriptive power to names in a syntax-independent way. Examples of the value of the kind attribute include c_source, object_code, executable, postscript, or " ".

Field Summary
 NameComponent value
Constructor Summary
NameComponentHolder()
NameComponentHolder(NameComponent initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public NameComponent value
Constructor Detail

NameComponentHolder

public NameComponentHolder()

NameComponentHolder

public NameComponentHolder(NameComponent initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NameHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming
Class NameHelper

java.lang.Object
    extended by org.omg.CosNaming.NameHelper
public abstract class NameHelper
extends Object

A name is a sequence of name components.

Constructor Summary
NameHelper()
Method Summary
static NameComponent[] | extract(Any a)
static String | id()
static void | insert(Any a, NameComponent[] that)
static NameComponent[] | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, NameComponent[] value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

NameHelper

public NameHelper()
Method Detail

insert

public static void insert(Any a,
                          NameComponent[] that)

extract

public static NameComponent[] extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static NameComponent[] read(InputStream istream)

write

public static void write(OutputStream ostream,
                         NameComponent[] value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NameHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming
Class NameHolder

java.lang.Object
    extended by org.omg.CosNaming.NameHolder
All Implemented Interfaces:
Streamable
public final class NameHolder
extends Object
implements Streamable

A name is a sequence of name components.

Field Summary
 NameComponent[] value
Constructor Summary
NameHolder()
NameHolder(NameComponent[] initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public NameComponent[] value
Constructor Detail

NameHolder

public NameHolder()

NameHolder

public NameHolder(NameComponent[] initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NamingContext (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming
Interface NamingContext

All Superinterfaces:
IDLEntity, NamingContextOperations, Object, Serializable
All Known Subinterfaces:
NamingContextExt
All Known Implementing Classes:
_NamingContextExtStub, _NamingContextImplBase, _NamingContextStub
public interface NamingContext
extends NamingContextOperations, Object, IDLEntity

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.

See CORBA COS Naming Specification.

Methods inherited from interface org.omg.CosNaming.NamingContextOperations
bind_context, bind_new_context, bind, destroy, list, new_context, rebind_context, rebind, resolve, unbind
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NamingContextExt (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming
Interface NamingContextExt

All Superinterfaces:
IDLEntity, NamingContext, NamingContextExtOperations, NamingContextOperations, Object, Serializable
All Known Implementing Classes:
_NamingContextExtStub
public interface NamingContextExt
extends NamingContextExtOperations, NamingContext, IDLEntity

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. 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.

See CORBA COS Naming Specification.

Methods inherited from interface org.omg.CosNaming.NamingContextExtOperations
resolve_str, to_name, to_string, to_url
Methods inherited from interface org.omg.CosNaming.NamingContextOperations
bind_context, bind_new_context, bind, destroy, list, new_context, rebind_context, rebind, resolve, unbind
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NamingContextExtHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming
Class NamingContextExtHelper

java.lang.Object
    extended by org.omg.CosNaming.NamingContextExtHelper
public abstract class NamingContextExtHelper
extends Object

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. 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.

See CORBA COS Naming Specification.

Constructor Summary
NamingContextExtHelper()
Method Summary
static NamingContextExt | extract(Any a)
static String | id()
static void | insert(Any a, NamingContextExt that)
static NamingContextExt | narrow(Object obj)
static NamingContextExt | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, NamingContextExt value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

NamingContextExtHelper

public NamingContextExtHelper()
Method Detail

insert

public static void insert(Any a,
                          NamingContextExt that)

extract

public static NamingContextExt extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static NamingContextExt read(InputStream istream)

write

public static void write(OutputStream ostream,
                         NamingContextExt value)

narrow

public static NamingContextExt narrow(Object obj)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NamingContextExtHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming
Class NamingContextExtHolder

java.lang.Object
    extended by org.omg.CosNaming.NamingContextExtHolder
All Implemented Interfaces:
Streamable
public final class NamingContextExtHolder
extends Object
implements Streamable

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. 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.

See CORBA COS Naming Specification.

Field Summary
 NamingContextExt value
Constructor Summary
NamingContextExtHolder()
NamingContextExtHolder(NamingContextExt initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public NamingContextExt value
Constructor Detail

NamingContextExtHolder

public NamingContextExtHolder()

NamingContextExtHolder

public NamingContextExtHolder(NamingContextExt initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NamingContextExtOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming
Interface NamingContextExtOperations

All Superinterfaces:
NamingContextOperations
All Known Subinterfaces:
NamingContextExt
All Known Implementing Classes:
_NamingContextExtStub, NamingContextExtPOA
public interface NamingContextExtOperations
extends NamingContextOperations

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. 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.

See CORBA COS Naming Specification.

Method Summary
Object | resolve_str(String sn) This operation resolves the Stringified name into the object reference.
NameComponent[] | to_name(String sn) This operation converts a Stringified Name into an equivalent array of Name Components.
String | to_string(NameComponent[] n) This operation creates a stringified name from the array of Name components.
String | to_url(String addr, String sn) This operation creates a URL based "iiopname://" format name from the Stringified Name of the object.
Methods inherited from interface org.omg.CosNaming.NamingContextOperations
bind_context, bind_new_context, bind, destroy, list, new_context, rebind_context, rebind, resolve, unbind

Method Detail

to_string

public String to_string(NameComponent[] n)
                 throws InvalidName
This operation creates a stringified name from the array of Name components.

Parameters:
n - Name of the object

Throws:
org.omg.CosNaming.NamingContextExtPackage.InvalidName - Indicates the name does not identify a binding.

InvalidName

to_name

public NameComponent[] to_name(String sn)
                        throws InvalidName
This operation converts a Stringified Name into an equivalent array of Name Components.

Parameters:
sn - Stringified Name of the object

Throws:
org.omg.CosNaming.NamingContextExtPackage.InvalidName - Indicates the name does not identify a binding.

InvalidName

to_url

public String to_url(String addr,
                     String sn)
              throws InvalidAddress,
                     InvalidName
This operation creates a URL based "iiopname://" format name from the Stringified Name of the object.

Parameters:
addr - internet based address of the host machine where Name Service is running

sn - Stringified Name of the object

Throws:
org.omg.CosNaming.NamingContextExtPackage.InvalidName - Indicates the name does not identify a binding.

org.omg.CosNaming.NamingContextPackage.InvalidAddress - Indicates the internet based address of the host machine is incorrect

InvalidAddress
InvalidName

resolve_str

public Object resolve_str(String sn)
                   throws NotFound,
                          CannotProceed,
                          InvalidName
This operation resolves the Stringified name into the object reference.

Parameters:
sn - Stringified Name of the object

Throws:
NotFound - Indicates there is no object reference for the given name.

CannotProceed - Indicates that the given compound name is incorrect

org.omg.CosNaming.NamingContextExtPackage.InvalidName - Indicates the name does not identify a binding.

InvalidName
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NamingContextExtPOA (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming
Class NamingContextExtPOA

java.lang.Object
    extended by org.omg.PortableServer.Servant
        extended by org.omg.CosNaming.NamingContextExtPOA
All Implemented Interfaces:
InvokeHandler, NamingContextExtOperations, NamingContextOperations
public abstract class NamingContextExtPOA
extends Servant
implements NamingContextExtOperations, InvokeHandler

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. 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.

See CORBA COS Naming Specification.

Constructor Summary
NamingContextExtPOA()
Method Summary
String[] | _all_interfaces(POA poa, byte[] objectId) Used by the ORB to obtain complete type information from the servant.
OutputStream | _invoke(String $method, InputStream in, ResponseHandler $rh) Invoked by the ORB to dispatch a request to the servant.
NamingContextExt | _this()
NamingContextExt | _this(ORB orb)
Methods inherited from class org.omg.PortableServer.Servant
_default_POA, _get_delegate, _get_interface_def, _is_a, _non_existent, _object_id, _orb, _poa, _set_delegate, _this_object, _this_object
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Methods inherited from interface org.omg.CosNaming.NamingContextExtOperations
resolve_str, to_name, to_string, to_url
Methods inherited from interface org.omg.CosNaming.NamingContextOperations
bind_context, bind_new_context, bind, destroy, list, new_context, rebind_context, rebind, resolve, unbind

Constructor Detail

NamingContextExtPOA

public NamingContextExtPOA()
Method Detail

_invoke

public OutputStream _invoke(String $method,
                            InputStream in,
                            ResponseHandler $rh)
Description copied from interface: InvokeHandler
Invoked by the ORB to dispatch a request to the servant. ORB passes the method name, an InputStream containing the marshalled arguments, and a ResponseHandler which the servant uses to construct a proper reply. Only CORBA SystemException may be thrown by this method. The method must return an OutputStream created by the ResponseHandler which contains the marshalled reply. A servant must not retain a reference to the ResponseHandler beyond the lifetime of a method invocation. Servant behaviour is defined as follows:

1. Determine correct method, and unmarshal parameters from InputStream.

2. Invoke method implementation.

3. If no user exception, create a normal reply using ResponseHandler.

4. If user exception occurred, create exception reply using ResponseHandler.

5. Marshal reply into OutputStream returned by ResponseHandler.

6. Return OutputStream to ORB.

Specified by:
_invoke in interface InvokeHandler
Parameters:
$method - The method name.
in - The InputStream containing the marshalled arguments.
$rh - The ResponseHandler which the servant uses to construct a proper reply
Returns:
The OutputStream created by the ResponseHandler which contains the marshalled reply

_all_interfaces

public String[] _all_interfaces(POA poa,
                                byte[] objectId)
Description copied from class: Servant
Used by the ORB to obtain complete type information from the servant.

Specified by:
_all_interfaces in class Servant
Parameters:
poa - POA with which the servant is associated.
objectId - is the id corresponding to the object associated with this servant.
Returns:
list of type information for the object.

_this

public NamingContextExt _this()

_this

public NamingContextExt _this(ORB orb)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NamingContextHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming
Class NamingContextHelper

java.lang.Object
    extended by org.omg.CosNaming.NamingContextHelper
public abstract class NamingContextHelper
extends Object

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.

See CORBA COS Naming Specification.

Constructor Summary
NamingContextHelper()
Method Summary
static NamingContext | extract(Any a)
static String | id()
static void | insert(Any a, NamingContext that)
static NamingContext | narrow(Object obj)
static NamingContext | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, NamingContext value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

NamingContextHelper

public NamingContextHelper()
Method Detail

insert

public static void insert(Any a,
                          NamingContext that)

extract

public static NamingContext extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static NamingContext read(InputStream istream)

write

public static void write(OutputStream ostream,
                         NamingContext value)

narrow

public static NamingContext narrow(Object obj)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NamingContextHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming
Class NamingContextHolder

java.lang.Object
    extended by org.omg.CosNaming.NamingContextHolder
All Implemented Interfaces:
Streamable
public final class NamingContextHolder
extends Object
implements Streamable

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.

See CORBA COS Naming Specification.

Field Summary
 NamingContext value
Constructor Summary
NamingContextHolder()
NamingContextHolder(NamingContext initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public NamingContext value
Constructor Detail

NamingContextHolder

public NamingContextHolder()

NamingContextHolder

public NamingContextHolder(NamingContext initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NamingContextOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming
Interface NamingContextOperations

All Known Subinterfaces:
NamingContext, NamingContextExt, NamingContextExtOperations
All Known Implementing Classes:
_NamingContextExtStub, _NamingContextImplBase, _NamingContextStub, NamingContextExtPOA, NamingContextPOA
public interface NamingContextOperations

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.

See CORBA COS Naming Specification.

Method Summary
void | bind_context(NameComponent[] n, NamingContext nc) Names an object that is a naming context.
NamingContext | bind_new_context(NameComponent[] n) This operation creates a new context and binds it to the name supplied as an argument.
void | bind(NameComponent[] n, Object obj) Creates a binding of a name and an object in the naming context.
void | destroy() The destroy operation deletes a naming context.
void | list(int how_many, BindingListHolder bl, BindingIteratorHolder bi) The list operation allows a client to iterate through a set of bindings in a naming context.
NamingContext | new_context() This operation returns a naming context implemented by the same naming server as the context on which the operation was invoked.
void | rebind_context(NameComponent[] n, NamingContext nc) Creates a binding of a name and a naming context in the naming context even if the name is already bound in the context.
void | rebind(NameComponent[] n, Object obj) Creates a binding of a name and an object in the naming context even if the name is already bound in the context.
Object | resolve(NameComponent[] n) The resolve operation is the process of retrieving an object bound to a name in a given context.
void | unbind(NameComponent[] n) The unbind operation removes a name binding from a context.

Method Detail

bind

public void bind(NameComponent[] n,
                 Object obj)
          throws NotFound,
                 CannotProceed,
                 InvalidName,
                 AlreadyBound
Creates a binding of a name and an object in the naming context. Naming contexts that are bound using bind do not participate in name resolution when compound names are passed to be resolved.

Parameters:
n - Name of the object

obj - The Object to bind with the given name

Throws:
NotFound - Indicates the name does not identify a binding.

CannotProceed - Indicates that the implementation has given up for some reason. The client, however, may be able to continue the operation at the returned naming context.

InvalidName - Indicates that the name is invalid.

AlreadyBound - Indicates an object is already bound to the specified name.

bind_context

public void bind_context(NameComponent[] n,
                         NamingContext nc)
                  throws NotFound,
                         CannotProceed,
                         InvalidName,
                         AlreadyBound
Names an object that is a naming context. Naming contexts that are bound using bind_context() participate in name resolution when compound names are passed to be resolved.

Parameters:
n - Name of the object

nc - NamingContect object to bind with the given name

Throws:
NotFound - Indicates the name does not identify a binding.

CannotProceed - Indicates that the implementation has given up for some reason. The client, however, may be able to continue the operation at the returned naming context.

InvalidName - Indicates that the name is invalid.

AlreadyBound - Indicates an object is already bound to the specified name.

rebind

public void rebind(NameComponent[] n,
                   Object obj)
            throws NotFound,
                   CannotProceed,
                   InvalidName
Creates a binding of a name and an object in the naming context even if the name is already bound in the context. Naming contexts that are bound using rebind do not participate in name resolution when compound names are passed to be resolved.

Parameters:
n - Name of the object

Throws:
NotFound - Indicates the name does not identify a binding.

CannotProceed - Indicates that the implementation has given up for some reason. The client, however, may be able to continue the operation at the returned naming context.

InvalidName - Indicates that the name is invalid.

rebind_context

public void rebind_context(NameComponent[] n,
                           NamingContext nc)
                    throws NotFound,
                           CannotProceed,
                           InvalidName
Creates a binding of a name and a naming context in the naming context even if the name is already bound in the context. Naming contexts that are bound using rebind_context() participate in name resolution when compound names are passed to be resolved.

Parameters:
n - Name of the object

nc - NamingContect object to rebind with the given name

Throws:
NotFound - Indicates the name does not identify a binding.

CannotProceed - Indicates that the implementation has given up for some reason. The client, however, may be able to continue the operation at the returned naming context.

InvalidName - Indicates that the name is invalid.

resolve

public Object resolve(NameComponent[] n)
               throws NotFound,
                      CannotProceed,
                      InvalidName
The resolve operation is the process of retrieving an object bound to a name in a given context. The given name must exactly match the bound name. The naming service does not return the type of the object. Clients are responsible for "narrowing" the object to the appropriate type. That is, clients typically cast the returned object from Object to a more specialized interface.

Parameters:
n - Name of the object

Throws:
NotFound - Indicates the name does not identify a binding.

CannotProceed - Indicates that the implementation has given up for some reason. The client, however, may be able to continue the operation at the returned naming context.

InvalidName - Indicates that the name is invalid.

unbind

public void unbind(NameComponent[] n)
            throws NotFound,
                   CannotProceed,
                   InvalidName
The unbind operation removes a name binding from a context.

Parameters:
n - Name of the object

Throws:
NotFound - Indicates the name does not identify a binding.

CannotProceed - Indicates that the implementation has given up for some reason. The client, however, may be able to continue the operation at the returned naming context.

InvalidName - Indicates that the name is invalid.

list

public void list(int how_many,
                 BindingListHolder bl,
                 BindingIteratorHolder bi)
The list operation allows a client to iterate through a set of bindings in a naming context.

The list operation returns at most the requested number of bindings in BindingList bl.

  • If the naming context contains additional bindings, the list operation returns a BindingIterator with the additional bindings.
  • If the naming context does not contain additional bindings, the binding iterator is a nil object reference.

Parameters:
how_many - the maximum number of bindings to return

bl - the returned list of bindings

bi - the returned binding iterator

new_context

public NamingContext new_context()
This operation returns a naming context implemented by the same naming server as the context on which the operation was invoked. The new context is not bound to any name.

bind_new_context

public NamingContext bind_new_context(NameComponent[] n)
                               throws NotFound,
                                      AlreadyBound,
                                      CannotProceed,
                                      InvalidName
This operation creates a new context and binds it to the name supplied as an argument. The newly-created context is implemented by the same naming server as the context in which it was bound (that is, the naming server that implements the context denoted by the name argument excluding the last component).

Parameters:
n - Name of the object

Throws:
NotFound - Indicates the name does not identify a binding.

AlreadyBound - Indicates an object is already bound to the specified name.

CannotProceed - Indicates that the implementation has given up for some reason. The client, however, may be able to continue the operation at the returned naming context.

InvalidName - Indicates that the name is invalid.

destroy

public void destroy()
             throws NotEmpty
The destroy operation deletes a naming context. If the naming context contains bindings, the NotEmpty exception is raised.

Throws:
NotEmpty - Indicates that the Naming Context contains bindings.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


NamingContextPOA (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming
Class NamingContextPOA

java.lang.Object
    extended by org.omg.PortableServer.Servant
        extended by org.omg.CosNaming.NamingContextPOA
All Implemented Interfaces:
InvokeHandler, NamingContextOperations
public abstract class NamingContextPOA
extends Servant
implements NamingContextOperations, InvokeHandler

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.

See CORBA COS Naming Specification.

Constructor Summary
NamingContextPOA()
Method Summary
String[] | _all_interfaces(POA poa, byte[] objectId) Used by the ORB to obtain complete type information from the servant.
OutputStream | _invoke(String $method, InputStream in, ResponseHandler $rh) Invoked by the ORB to dispatch a request to the servant.
NamingContext | _this()
NamingContext | _this(ORB orb)
Methods inherited from class org.omg.PortableServer.Servant
_default_POA, _get_delegate, _get_interface_def, _is_a, _non_existent, _object_id, _orb, _poa, _set_delegate, _this_object, _this_object
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Methods inherited from interface org.omg.CosNaming.NamingContextOperations
bind_context, bind_new_context, bind, destroy, list, new_context, rebind_context, rebind, resolve, unbind

Constructor Detail

NamingContextPOA

public NamingContextPOA()
Method Detail

_invoke

public OutputStream _invoke(String $method,
                            InputStream in,
                            ResponseHandler $rh)
Description copied from interface: InvokeHandler
Invoked by the ORB to dispatch a request to the servant. ORB passes the method name, an InputStream containing the marshalled arguments, and a ResponseHandler which the servant uses to construct a proper reply. Only CORBA SystemException may be thrown by this method. The method must return an OutputStream created by the ResponseHandler which contains the marshalled reply. A servant must not retain a reference to the ResponseHandler beyond the lifetime of a method invocation. Servant behaviour is defined as follows:

1. Determine correct method, and unmarshal parameters from InputStream.

2. Invoke method implementation.

3. If no user exception, create a normal reply using ResponseHandler.

4. If user exception occurred, create exception reply using ResponseHandler.

5. Marshal reply into OutputStream returned by ResponseHandler.

6. Return OutputStream to ORB.

Specified by:
_invoke in interface InvokeHandler
Parameters:
$method - The method name.
in - The InputStream containing the marshalled arguments.
$rh - The ResponseHandler which the servant uses to construct a proper reply
Returns:
The OutputStream created by the ResponseHandler which contains the marshalled reply

_all_interfaces

public String[] _all_interfaces(POA poa,
                                byte[] objectId)
Description copied from class: Servant
Used by the ORB to obtain complete type information from the servant.

Specified by:
_all_interfaces in class Servant
Parameters:
poa - POA with which the servant is associated.
objectId - is the id corresponding to the object associated with this servant.
Returns:
list of type information for the object.

_this

public NamingContext _this()

_this

public NamingContext _this(ORB orb)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


org.omg.CosNaming (Java 2 Platform SE v1.4.2)

 org.omg.CosNaming
Interfaces
BindingIterator
BindingIteratorOperations
NamingContext
NamingContextExt
NamingContextExtOperations
NamingContextOperations
Classes
_BindingIteratorImplBase
_BindingIteratorStub
_NamingContextExtStub
_NamingContextImplBase
_NamingContextStub
Binding
BindingHelper
BindingHolder
BindingIteratorHelper
BindingIteratorHolder
BindingIteratorPOA
BindingListHelper
BindingListHolder
BindingType
BindingTypeHelper
BindingTypeHolder
IstringHelper
NameComponent
NameComponentHelper
NameComponentHolder
NameHelper
NameHolder
NamingContextExtHelper
NamingContextExtHolder
NamingContextExtPOA
NamingContextHelper
NamingContextHolder
NamingContextPOA


org.omg.CosNaming (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package org.omg.CosNaming

Provides a naming service for Java IDL.

See:
Description

Interface Summary
BindingIterator | The BindingIterator interface allows a client to iterate through the bindings using the next_one or next_n operations.
BindingIteratorOperations | The BindingIterator interface allows a client to iterate through the bindings using the next_one or next_n operations.
NamingContext | A naming context is an object that contains a set of name bindings in which each name is unique.
NamingContextExt | 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.
NamingContextExtOperations | 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.
NamingContextOperations | A naming context is an object that contains a set of name bindings in which each name is unique.

Class Summary
_BindingIteratorImplBase |
_BindingIteratorStub | The BindingIterator interface allows a client to iterate through the bindings using the next_one or next_n operations.
_NamingContextExtStub | 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.
_NamingContextImplBase |
_NamingContextStub | A naming context is an object that contains a set of name bindings in which each name is unique.
Binding | A name-to-object association is called a Binding.
BindingHelper | A name-to-object association is called a Binding.
BindingHolder | A name-to-object association is called a Binding.
BindingIteratorHelper | The BindingIterator interface allows a client to iterate through the bindings using the next_one or next_n operations.
BindingIteratorHolder | The BindingIterator interface allows a client to iterate through the bindings using the next_one or next_n operations.
BindingIteratorPOA | The BindingIterator interface allows a client to iterate through the bindings using the next_one or next_n operations.
BindingListHelper | List of Bindings.
BindingListHolder | List of Bindings.
BindingType | Specifies whether the given binding is for a object (that is not a naming context) or for a naming context.
BindingTypeHelper | Specifies whether the given binding is for a object (that is not a naming context) or for a naming context.
BindingTypeHolder | Specifies whether the given binding is for a object (that is not a naming context) or for a naming context.
IstringHelper | org/omg/CosNaming/IstringHelper.java .
NameComponent | Many of the operations defined on a naming context take names as parameters.
NameComponentHelper | Many of the operations defined on a naming context take names as parameters.
NameComponentHolder | Many of the operations defined on a naming context take names as parameters.
NameHelper | A name is a sequence of name components.
NameHolder | A name is a sequence of name components.
NamingContextExtHelper | 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 | 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 | 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.
NamingContextHelper | A naming context is an object that contains a set of name bindings in which each name is unique.
NamingContextHolder | A naming context is an object that contains a set of name bindings in which each name is unique.
NamingContextPOA | A naming context is an object that contains a set of name bindings in which each name is unique.

Package org.omg.CosNaming Description

Provides a naming service for Java IDL. The Object Request Broker Daemon (ORBD) also includes both a transient and persistent naming service.

The package and all its classes and interfaces were generated by running the tool idlj on the file nameservice.idl, which is a module written in OMG IDL.

Package Specification

For a precise list of supported sections of official specifications with which the Java 2 Platform, Standard Edition, v.1.4 ORB complies, see Official Specifications for CORBA support in J2SE 1.4.

Interfaces

The package org.omg.CosNaming contains two public interfaces and several auxiliary classes.

The interfaces are:

  • NamingContext
  • BindingIterator

These two interfaces provide the means to bind/unbind names and object references, to retrieve bound object references, and to iterate through a list of bindings. The NamingContext interface supplies the main functionality for the naming service, and BindingIterator provides a means of iterating through a list of name/object reference bindings.

Auxiliary Classes

In order to map an OMG IDL interface to the Java programming language, the idlj compiler creates Java classes that can be thought of as auxiliary classes. Comments for the generated auxiliary classes used by the interfaces NamingContext and BindingIterator are included here.

Classes Used by NamingContext and BindingIterator

The following are classes used by the naming service. (Helper and holder classes, which are generated for each of the classes listed here, are discussed below.)
  • public final class NameComponent -- a building block for names. (Names are bound to object references in a naming context.)

    A name is an array of one or more NameComponent objects. A name with a single NameComponent is called a simple name; a name with multiple NameComponent objects is called a compound name.

    A NameComponent object consists of two fields:

    1. id -- a String used as an identifier
    2. kind -- a String that can be used for any descriptive purpose. Its importance is that it can be used to describe an object without affecting syntax. The C programming language, for example, uses the the syntactic convention of appending the extension ".c" to a file name to indicate that it is a source code file. In a NameComponent object, the kind field can be used to describe the type of object rather than a file extension or some other syntactic convention. Examples of the value of the kind field include the strings "c_source", "object_code", "executable", "postscript", and "". It is not unusual for the kind field to be the empty string.

    In a name, each NameComponent object except the last denotes a NamingContext object; the last NameComponent object denotes the bound object reference. This is similar to a path name, in which the last name is the file name, and all names before it are directory names.

  • public final class Binding -- an object that associates a name with an object reference or a naming context. A Binding object has two fields:
    1. binding_name - an array of one or more NameComponent objects that represents the bound name
    2. binding_type - a BindingType object indicating whether the binding is between a name and an object reference or between a name and a naming context

    The interface NamingContext has methods for binding/unbinding names with object references or naming contexts, for listing bindings, and for resolving bindings (given a name, the method resolve returns the object reference bound to it).

  • public final class BindingType -- an object that specifies whether the given Binding object is a binding between a name and an object reference (that is, not a naming context) or between a name and a naming context.

    The classBindingType consists of two methods and four constants. Two of these constants are BindingType objects, and two are ints.

    The BindingType objects can be passed to the constructor for the class Binding or used as parameters or return values. These BindingType objects are:

    • public static final BindingType nobject -- to indicate that the binding is with an object reference
    • public static final BindingType ncontext -- to indicate that the binding is with a naming context

    The int constants can be supplied to the method from_int to create BindingType objects, or they can be return values for the method value. These constants are:

    • public static final int _nobject
    • public static final int _ncontext
    If the method from_int is supplied with anything other than _nobject or _ncontext, it will throw the exception org.omg.CORBA.BAD_PARAM.

    Usage is as follows:

           BindingType btObject = from_int(_nobject);
       BindingType btContext = from_int(_ncontext);
    The variable btObject refers to a BindingType object initialized to represent a binding with an object reference. The variable btContext refers to a BindingType object initialized to represent a binding with a NamingContex object.

    The method value returns either _nobject or _ncontext, so in the following line of code, the variable bt will contain _nobject or _ncontext:

           int bt = BindingType.value();

Holder Classes

OMG IDL uses OUT and INOUT parameters for returning values from operations. The mapping to the Java programming language, which does not have OUT and INOUT parameters, creates a special class for each type, called a holder class. An instance of a holder class can be passed to a Java method as a parameter, and a value can be assigned to its value field. This allows it to perform the function of an OUT or INOUT parameter.

The following holder classes are generated for the package org.omg.CosNaming:

  • NamingContextHolder
  • BindingIteratorHolder
  • BindingHolder
  • BindingListHolder
  • BindingTypeHolder
  • NameComponentHolder
  • NameHolder

Note that in the org.omg.CORBA package, there is a holder class for each of the basic Java types: IntHolder, ShortHolder, StringHolder, and so on.

Note also that there is a NameHolder class even though there is no Name class; similarly, there is a BindingListHolder class even though there is no BindingList class. This is true because in the OMG IDL interface, Name and BindingList are typedefs. There is no mapping from an IDL typedef to a Java construct, but holder classes are generated if the typedef is for a sequence or an array. As mapped to the Java programming language, Name is an array of NameComponent objects, and a BindingList is an array of Binding objects. All holder classes have at least two constructors and one field:

  • value field -- an instance of the type being used as an OUT or INOUT parameter. For example, the value field of a NamingContextHolder will be a NamingContext object.
  • default constructor -- a constructor that creates a new holder object initialized with the default value for the type. For example, a new BindingHolder object created with the default constructor will have its value field set to null because that is the default value for an object. Other defaults are false for boolean, 0 for numeric and char types, and null for object references.
  • constructor from an instance -- a constructor that creates a new holder object whose value field is initialized with the instance supplied

A holder class for a user-defined type (a Java class) has three more methods, but application developers do not use them directly.

Helper Classes

Helper classes, which are generated for all user-defined types in an OMG IDL interface, supply static methods needed to manipulate those types.

There is only one method in a helper class that an application programmer uses: the method narrow. Only Java interfaces mapped from IDL interfaces will have a helper class that includes a narrow method, so in the CosNaming package, only the classes NamingContextHelper and BindingIteratorHelper have a narrow method.

  • public static NamingContext narrow(org.omg.CORBA.Object obj) -- converts the given CORBA object to a NamingContext object
  • public static BindingIterator narrow(org.omg.CORBA.Object obj) -- converts the given CORBA object to a BindingIterator object

Package org.omg.CosNaming.NamingContextPackage

This package supplies Helper and Holder classes for the exceptions used in the package org.omg.CosNaming and also for the class NotFoundReason, which supplies a reason for the exception NotFound.

There are Helper and Holder classes for the following exceptions:

  • AlreadyBound
  • CannotProceed
  • InvalidName
  • NotEmpty
  • NotFound

Naming Service Compatibility

Sun's implementation of the CosNaming package complies with the OMG COSNaming specification. In other words, the APIs in Sun's naming service are implemented according to the guidelines for a naming service provided by OMG. Therefore, if a third-party vendor has implemented a naming service that is OMG compliant, it is possible to switch between Sun's implementation of CosNaming and the third-party vendor's implementation. However, it is important to understand that there can be minor variations in the way different vendors implement the naming service, such as differences in the exception strings.

Instructions for Using a Third Party's Naming Service

Although we encourage using an ORB and ORB services that are both from one vendor, it is possible to plug in a third party's COSNaming implementation with Sun's RMI-IIOP ORB. Here are the steps to follow:
  1. Create a properties file for the Bootstrap server and give it two entries. For example, you could call this properties file /tmp/services and put the following in it: NameService, <Stringified IOR of the Root Naming Context>.

    This associates NameService with the Root Naming Context of the CosNaming implementation that you want to use.

  2. Start the standalone Bootstrap server using the following command:

      java -classpath $(CLASSPATH)
      com.sun.corba.ee.internal.CosNaming.BootstrapServer -InitialServicesFile
      "/tmp/services" [-ORBInitialPort port]

    Note that the square brackets at the end of the command indicate that specifying a port number is optional.

Now when an application calls the method org.omg.CORBA.ORB.resolve_initial_references, CORBA processes will contact the Bootstrap Server to get the Root Naming Context.

Package Specification

  • Interoperable Naming Service (ptc/00-08-07)

Related Documentation

For an overview and examples of how to use the CosNaming API, please see:
  • Naming Service

For an overview of Java IDL, please see:

  • Java IDL home page

Since:
JDK1.3
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


org.omg.CosNaming Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package org.omg.CosNaming

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class org.omg.CosNaming.Binding (implements org.omg.CORBA.portable.IDLEntity)
    • class org.omg.CosNaming.BindingHelper
    • class org.omg.CosNaming.BindingHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CosNaming.BindingIteratorHelper
    • class org.omg.CosNaming.BindingIteratorHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CosNaming.BindingListHelper
    • class org.omg.CosNaming.BindingListHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CosNaming.BindingType (implements org.omg.CORBA.portable.IDLEntity)
    • class org.omg.CosNaming.BindingTypeHelper
    • class org.omg.CosNaming.BindingTypeHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CosNaming.IstringHelper
    • class org.omg.CosNaming.NameComponent (implements org.omg.CORBA.portable.IDLEntity)
    • class org.omg.CosNaming.NameComponentHelper
    • class org.omg.CosNaming.NameComponentHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CosNaming.NameHelper
    • class org.omg.CosNaming.NameHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CosNaming.NamingContextExtHelper
    • class org.omg.CosNaming.NamingContextExtHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CosNaming.NamingContextHelper
    • class org.omg.CosNaming.NamingContextHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CORBA.portable.ObjectImpl (implements org.omg.CORBA.Object)
      • class org.omg.CosNaming._BindingIteratorStub (implements org.omg.CosNaming.BindingIterator)
      • class org.omg.CosNaming._NamingContextExtStub (implements org.omg.CosNaming.NamingContextExt)
      • class org.omg.CosNaming._NamingContextStub (implements org.omg.CosNaming.NamingContext)
      • class org.omg.CORBA.DynamicImplementation
        • class org.omg.CosNaming._BindingIteratorImplBase (implements org.omg.CosNaming.BindingIterator)
        • class org.omg.CosNaming._NamingContextImplBase (implements org.omg.CosNaming.NamingContext)
    • class org.omg.PortableServer.Servant
      • class org.omg.CosNaming.BindingIteratorPOA (implements org.omg.CosNaming.BindingIteratorOperations, org.omg.CORBA.portable.InvokeHandler)
      • class org.omg.CosNaming.NamingContextExtPOA (implements org.omg.CORBA.portable.InvokeHandler, org.omg.CosNaming.NamingContextExtOperations)
      • class org.omg.CosNaming.NamingContextPOA (implements org.omg.CORBA.portable.InvokeHandler, org.omg.CosNaming.NamingContextOperations)

Interface Hierarchy

  • interface org.omg.CosNaming.BindingIteratorOperations
    • interface org.omg.CosNaming.BindingIterator (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CORBA.Object)
  • interface org.omg.CosNaming.NamingContextOperations
    • interface org.omg.CosNaming.NamingContext (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CORBA.Object)
      • interface org.omg.CosNaming.NamingContextExt (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CosNaming.NamingContextExtOperations)
    • interface org.omg.CosNaming.NamingContextExtOperations
      • interface org.omg.CosNaming.NamingContextExt (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CosNaming.NamingContext)
  • interface org.omg.CORBA.Object
    • interface org.omg.CosNaming.BindingIterator (also extends org.omg.CosNaming.BindingIteratorOperations, org.omg.CORBA.portable.IDLEntity)
    • interface org.omg.CosNaming.NamingContext (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CosNaming.NamingContextOperations)
      • interface org.omg.CosNaming.NamingContextExt (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CosNaming.NamingContextExtOperations)
  • interface java.io.Serializable
    • interface org.omg.CORBA.portable.IDLEntity
      • interface org.omg.CosNaming.BindingIterator (also extends org.omg.CosNaming.BindingIteratorOperations, org.omg.CORBA.Object)
      • interface org.omg.CosNaming.NamingContext (also extends org.omg.CosNaming.NamingContextOperations, org.omg.CORBA.Object)
        • interface org.omg.CosNaming.NamingContextExt (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CosNaming.NamingContextExtOperations)
      • interface org.omg.CosNaming.NamingContextExt (also extends org.omg.CosNaming.NamingContext, org.omg.CosNaming.NamingContextExtOperations)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package org.omg.CosNaming (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
org.omg.CosNaming

Packages that use org.omg.CosNaming
org.omg.CosNaming | Provides a naming service for Java IDL.
org.omg.CosNaming.NamingContextPackage | This package contains Exception classes for the org.omg.CosNaming package.

Classes in org.omg.CosNaming used by org.omg.CosNaming
Binding
A name-to-object association is called a Binding.
BindingHolder
A name-to-object association is called a Binding.
BindingIterator
The BindingIterator interface allows a client to iterate through the bindings using the next_one or next_n operations.
BindingIteratorHolder
The BindingIterator interface allows a client to iterate through the bindings using the next_one or next_n operations.
BindingIteratorOperations
The BindingIterator interface allows a client to iterate through the bindings using the next_one or next_n operations.
BindingListHolder
List of Bindings.
BindingType
Specifies whether the given binding is for a object (that is not a naming context) or for a naming context.
NameComponent
Many of the operations defined on a naming context take names as parameters.
NamingContext
A naming context is an object that contains a set of name bindings in which each name is unique.
NamingContextExt
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.
NamingContextExtOperations
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.
NamingContextOperations
A naming context is an object that contains a set of name bindings in which each name is unique.

Classes in org.omg.CosNaming used by org.omg.CosNaming.NamingContextPackage
NameComponent
Many of the operations defined on a naming context take names as parameters.
NamingContext
A naming context is an object that contains a set of name bindings in which each name is unique.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming._BindingIteratorImplBase (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming._BindingIteratorImplBase

No usage of org.omg.CosNaming._BindingIteratorImplBase

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming._BindingIteratorStub (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming._BindingIteratorStub

No usage of org.omg.CosNaming._BindingIteratorStub

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming._NamingContextExtStub (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming._NamingContextExtStub

No usage of org.omg.CosNaming._NamingContextExtStub

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming._NamingContextImplBase (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming._NamingContextImplBase

No usage of org.omg.CosNaming._NamingContextImplBase

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming._NamingContextStub (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming._NamingContextStub

No usage of org.omg.CosNaming._NamingContextStub

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.Binding (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.Binding

Packages that use Binding
org.omg.CosNaming Provides a naming service for Java IDL.

Uses of Binding in org.omg.CosNaming

Fields in org.omg.CosNaming declared as Binding
Binding[] | BindingListHolder.value
Binding | BindingHolder.value

Methods in org.omg.CosNaming that return Binding
static Binding[] | BindingListHelper.extract(Any a)
static Binding[] | BindingListHelper.read(InputStream istream)
static Binding | BindingHelper.extract(Any a)
static Binding | BindingHelper.read(InputStream istream)

Methods in org.omg.CosNaming with parameters of type Binding
static void | BindingListHelper.insert(Any a, Binding[] that)
static void | BindingListHelper.write(OutputStream ostream, Binding[] value)
static void | BindingHelper.insert(Any a, Binding that)
static void | BindingHelper.write(OutputStream ostream, Binding value)

Constructors in org.omg.CosNaming with parameters of type Binding
BindingListHolder(Binding[] initialValue)
BindingHolder(Binding initialValue)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.BindingHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.BindingHelper

No usage of org.omg.CosNaming.BindingHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.BindingHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.BindingHolder

Packages that use BindingHolder
org.omg.CosNaming Provides a naming service for Java IDL.

Uses of BindingHolder in org.omg.CosNaming

Methods in org.omg.CosNaming with parameters of type BindingHolder
boolean | _BindingIteratorStub.next_one(BindingHolder b) This operation returns the next binding.
boolean | BindingIteratorOperations.next_one(BindingHolder b) This operation returns the next binding.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CosNaming.BindingIterator (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CosNaming.BindingIterator

Packages that use BindingIterator
org.omg.CosNaming Provides a naming service for Java IDL.

Uses of BindingIterator in org.omg.CosNaming

Classes in org.omg.CosNaming that implement BindingIterator
class | _BindingIteratorImplBase
class | _BindingIteratorStub The BindingIterator interface allows a client to iterate through the bindings using the next_one or next_n operations.

Fields in org.omg.CosNaming declared as BindingIterator
 BindingIterator BindingIteratorHolder.value

Methods in org.omg.CosNaming that return BindingIterator
static BindingIterator | BindingIteratorHelper.extract(Any a)
static BindingIterator | BindingIteratorHelper.read(InputStream istream)
static BindingIterator | BindingIteratorHelper.narrow(Object obj)
BindingIterator | BindingIteratorPOA._this()
BindingIterator | BindingIteratorPOA._this(ORB orb)

Methods in org.omg.CosNaming with parameters of type BindingIterator
static void | BindingIteratorHelper.insert(Any a, BindingIterator that)
static void | BindingIteratorHelper.write(OutputStream ostream, BindingIterator value)

Constructors in org.omg.CosNaming with parameters of type BindingIterator
BindingIteratorHolder(BindingIterator initialValue)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.BindingIteratorHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.BindingIteratorHelper

No usage of org.omg.CosNaming.BindingIteratorHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.BindingIteratorHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.BindingIteratorHolder

Packages that use BindingIteratorHolder
org.omg.CosNaming Provides a naming service for Java IDL.

Uses of BindingIteratorHolder in org.omg.CosNaming

Methods in org.omg.CosNaming with parameters of type BindingIteratorHolder
void | _NamingContextExtStub.list(int how_many, BindingListHolder bl, BindingIteratorHolder bi) The list operation allows a client to iterate through a set of bindings in a naming context.
void | _NamingContextStub.list(int how_many, BindingListHolder bl, BindingIteratorHolder bi) The list operation allows a client to iterate through a set of bindings in a naming context.
void | NamingContextOperations.list(int how_many, BindingListHolder bl, BindingIteratorHolder bi) The list operation allows a client to iterate through a set of bindings in a naming context.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CosNaming.BindingIteratorOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CosNaming.BindingIteratorOperations

Packages that use BindingIteratorOperations
org.omg.CosNaming Provides a naming service for Java IDL.

Uses of BindingIteratorOperations in org.omg.CosNaming

Subinterfaces of BindingIteratorOperations in org.omg.CosNaming
 interface BindingIterator
The BindingIterator interface allows a client to iterate through the bindings using the next_one or next_n operations.

Classes in org.omg.CosNaming that implement BindingIteratorOperations
class | _BindingIteratorImplBase
class | _BindingIteratorStub The BindingIterator interface allows a client to iterate through the bindings using the next_one or next_n operations.
class | BindingIteratorPOA The BindingIterator interface allows a client to iterate through the bindings using the next_one or next_n operations.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.BindingIteratorPOA (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.BindingIteratorPOA

No usage of org.omg.CosNaming.BindingIteratorPOA

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.BindingListHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.BindingListHelper

No usage of org.omg.CosNaming.BindingListHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.BindingListHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.BindingListHolder

Packages that use BindingListHolder
org.omg.CosNaming Provides a naming service for Java IDL.

Uses of BindingListHolder in org.omg.CosNaming

Methods in org.omg.CosNaming with parameters of type BindingListHolder
void | _NamingContextExtStub.list(int how_many, BindingListHolder bl, BindingIteratorHolder bi) The list operation allows a client to iterate through a set of bindings in a naming context.
void | _NamingContextStub.list(int how_many, BindingListHolder bl, BindingIteratorHolder bi) The list operation allows a client to iterate through a set of bindings in a naming context.
void | NamingContextOperations.list(int how_many, BindingListHolder bl, BindingIteratorHolder bi) The list operation allows a client to iterate through a set of bindings in a naming context.
boolean | _BindingIteratorStub.next_n(int how_many, BindingListHolder bl) This operation returns at most the requested number of bindings.
boolean | BindingIteratorOperations.next_n(int how_many, BindingListHolder bl) This operation returns at most the requested number of bindings.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.BindingType (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.BindingType

Packages that use BindingType
org.omg.CosNaming Provides a naming service for Java IDL.

Uses of BindingType in org.omg.CosNaming

Fields in org.omg.CosNaming declared as BindingType
BindingType | BindingTypeHolder.value
static BindingType | BindingType.nobject
static BindingType | BindingType.ncontext
BindingType | Binding.binding_type

Methods in org.omg.CosNaming that return BindingType
static BindingType | BindingTypeHelper.extract(Any a)
static BindingType | BindingTypeHelper.read(InputStream istream)
static BindingType | BindingType.from_int(int value)

Methods in org.omg.CosNaming with parameters of type BindingType
static void | BindingTypeHelper.insert(Any a, BindingType that)
static void | BindingTypeHelper.write(OutputStream ostream, BindingType value)

Constructors in org.omg.CosNaming with parameters of type BindingType
BindingTypeHolder(BindingType initialValue)
Binding(NameComponent[] _binding_name, BindingType _binding_type)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.BindingTypeHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.BindingTypeHelper

No usage of org.omg.CosNaming.BindingTypeHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.BindingTypeHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.BindingTypeHolder

No usage of org.omg.CosNaming.BindingTypeHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.IstringHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.IstringHelper

No usage of org.omg.CosNaming.IstringHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.NameComponent (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.NameComponent

Packages that use NameComponent
org.omg.CosNaming | Provides a naming service for Java IDL.
org.omg.CosNaming.NamingContextPackage | This package contains Exception classes for the org.omg.CosNaming package.

Uses of NameComponent in org.omg.CosNaming

Fields in org.omg.CosNaming declared as NameComponent
NameComponent[] | NameHolder.value
NameComponent | NameComponentHolder.value
NameComponent[] | Binding.binding_name

Methods in org.omg.CosNaming that return NameComponent
NameComponent[] | _NamingContextExtStub.to_name(String sn) This operation converts a Stringified Name into an equivalent array of Name Components.
NameComponent[] | NamingContextExtOperations.to_name(String sn) This operation converts a Stringified Name into an equivalent array of Name Components.
static NameComponent[] | NameHelper.extract(Any a)
static NameComponent[] | NameHelper.read(InputStream istream)
static NameComponent | NameComponentHelper.extract(Any a)
static NameComponent | NameComponentHelper.read(InputStream istream)

Methods in org.omg.CosNaming with parameters of type NameComponent
String | _NamingContextExtStub.to_string(NameComponent[] n) This operation creates a stringified name from the array of Name components.
void | _NamingContextExtStub.bind(NameComponent[] n, Object obj) Creates a binding of a name and an object in the naming context.
void | _NamingContextExtStub.bind_context(NameComponent[] n, NamingContext nc) Names an object that is a naming context.
void | _NamingContextExtStub.rebind(NameComponent[] n, Object obj) Creates a binding of a name and an object in the naming context even if the name is already bound in the context.
void | _NamingContextExtStub.rebind_context(NameComponent[] n, NamingContext nc) Creates a binding of a name and a naming context in the naming context even if the name is already bound in the context.
Object | _NamingContextExtStub.resolve(NameComponent[] n) The resolve operation is the process of retrieving an object bound to a name in a given context.
void | _NamingContextExtStub.unbind(NameComponent[] n) The unbind operation removes a name binding from a context.
NamingContext | _NamingContextExtStub.bind_new_context(NameComponent[] n) This operation creates a new context and binds it to the name supplied as an argument.
String | NamingContextExtOperations.to_string(NameComponent[] n) This operation creates a stringified name from the array of Name components.
void | _NamingContextStub.bind(NameComponent[] n, Object obj) Creates a binding of a name and an object in the naming context.
void | _NamingContextStub.bind_context(NameComponent[] n, NamingContext nc) Names an object that is a naming context.
void | _NamingContextStub.rebind(NameComponent[] n, Object obj) Creates a binding of a name and an object in the naming context even if the name is already bound in the context.
void | _NamingContextStub.rebind_context(NameComponent[] n, NamingContext nc) Creates a binding of a name and a naming context in the naming context even if the name is already bound in the context.
Object | _NamingContextStub.resolve(NameComponent[] n) The resolve operation is the process of retrieving an object bound to a name in a given context.
void | _NamingContextStub.unbind(NameComponent[] n) The unbind operation removes a name binding from a context.
NamingContext | _NamingContextStub.bind_new_context(NameComponent[] n) This operation creates a new context and binds it to the name supplied as an argument.
void | NamingContextOperations.bind(NameComponent[] n, Object obj) Creates a binding of a name and an object in the naming context.
void | NamingContextOperations.bind_context(NameComponent[] n, NamingContext nc) Names an object that is a naming context.
void | NamingContextOperations.rebind(NameComponent[] n, Object obj) Creates a binding of a name and an object in the naming context even if the name is already bound in the context.
void | NamingContextOperations.rebind_context(NameComponent[] n, NamingContext nc) Creates a binding of a name and a naming context in the naming context even if the name is already bound in the context.
Object | NamingContextOperations.resolve(NameComponent[] n) The resolve operation is the process of retrieving an object bound to a name in a given context.
void | NamingContextOperations.unbind(NameComponent[] n) The unbind operation removes a name binding from a context.
NamingContext | NamingContextOperations.bind_new_context(NameComponent[] n) This operation creates a new context and binds it to the name supplied as an argument.
static void | NameHelper.insert(Any a, NameComponent[] that)
static void | NameHelper.write(OutputStream ostream, NameComponent[] value)
static void | NameComponentHelper.insert(Any a, NameComponent that)
static void | NameComponentHelper.write(OutputStream ostream, NameComponent value)

Constructors in org.omg.CosNaming with parameters of type NameComponent
NameHolder(NameComponent[] initialValue)
NameComponentHolder(NameComponent initialValue)
Binding(NameComponent[] _binding_name, BindingType _binding_type)

Uses of NameComponent in org.omg.CosNaming.NamingContextPackage

Fields in org.omg.CosNaming.NamingContextPackage declared as NameComponent
NameComponent[] | CannotProceed.rest_of_name
NameComponent[] | NotFound.rest_of_name

Constructors in org.omg.CosNaming.NamingContextPackage with parameters of type NameComponent
CannotProceed(NamingContext _cxt, NameComponent[] _rest_of_name)
CannotProceed(String $reason, NamingContext _cxt, NameComponent[] _rest_of_name)
NotFound(NotFoundReason _why, NameComponent[] _rest_of_name)
NotFound(String $reason, NotFoundReason _why, NameComponent[] _rest_of_name)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.NameComponentHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.NameComponentHelper

No usage of org.omg.CosNaming.NameComponentHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.NameComponentHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.NameComponentHolder

No usage of org.omg.CosNaming.NameComponentHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.NameHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.NameHelper

No usage of org.omg.CosNaming.NameHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.NameHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.NameHolder

No usage of org.omg.CosNaming.NameHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CosNaming.NamingContext (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CosNaming.NamingContext

Packages that use NamingContext
org.omg.CosNaming | Provides a naming service for Java IDL.
org.omg.CosNaming.NamingContextPackage | This package contains Exception classes for the org.omg.CosNaming package.

Uses of NamingContext in org.omg.CosNaming

Subinterfaces of NamingContext in org.omg.CosNaming
 interface NamingContextExt
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.

Classes in org.omg.CosNaming that implement NamingContext
class | _NamingContextExtStub 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.
class | _NamingContextImplBase
class | _NamingContextStub A naming context is an object that contains a set of name bindings in which each name is unique.

Fields in org.omg.CosNaming declared as NamingContext
 NamingContext NamingContextHolder.value

Methods in org.omg.CosNaming that return NamingContext
NamingContext | _NamingContextExtStub.new_context() This operation returns a naming context implemented by the same naming server as the context on which the operation was invoked.
NamingContext | _NamingContextExtStub.bind_new_context(NameComponent[] n) This operation creates a new context and binds it to the name supplied as an argument.
NamingContext | NamingContextPOA._this()
NamingContext | NamingContextPOA._this(ORB orb)
NamingContext | _NamingContextStub.new_context() This operation returns a naming context implemented by the same naming server as the context on which the operation was invoked.
NamingContext | _NamingContextStub.bind_new_context(NameComponent[] n) This operation creates a new context and binds it to the name supplied as an argument.
static NamingContext | NamingContextHelper.extract(Any a)
static NamingContext | NamingContextHelper.read(InputStream istream)
static NamingContext | NamingContextHelper.narrow(Object obj)
NamingContext | NamingContextOperations.new_context() This operation returns a naming context implemented by the same naming server as the context on which the operation was invoked.
NamingContext | NamingContextOperations.bind_new_context(NameComponent[] n) This operation creates a new context and binds it to the name supplied as an argument.

Methods in org.omg.CosNaming with parameters of type NamingContext
void | _NamingContextExtStub.bind_context(NameComponent[] n, NamingContext nc) Names an object that is a naming context.
void | _NamingContextExtStub.rebind_context(NameComponent[] n, NamingContext nc) Creates a binding of a name and a naming context in the naming context even if the name is already bound in the context.
void | _NamingContextStub.bind_context(NameComponent[] n, NamingContext nc) Names an object that is a naming context.
void | _NamingContextStub.rebind_context(NameComponent[] n, NamingContext nc) Creates a binding of a name and a naming context in the naming context even if the name is already bound in the context.
static void | NamingContextHelper.insert(Any a, NamingContext that)
static void | NamingContextHelper.write(OutputStream ostream, NamingContext value)
void | NamingContextOperations.bind_context(NameComponent[] n, NamingContext nc) Names an object that is a naming context.
void | NamingContextOperations.rebind_context(NameComponent[] n, NamingContext nc) Creates a binding of a name and a naming context in the naming context even if the name is already bound in the context.

Constructors in org.omg.CosNaming with parameters of type NamingContext
NamingContextHolder(NamingContext initialValue)

Uses of NamingContext in org.omg.CosNaming.NamingContextPackage

Fields in org.omg.CosNaming.NamingContextPackage declared as NamingContext
 NamingContext CannotProceed.cxt

Constructors in org.omg.CosNaming.NamingContextPackage with parameters of type NamingContext
CannotProceed(NamingContext _cxt, NameComponent[] _rest_of_name)
CannotProceed(String $reason, NamingContext _cxt, NameComponent[] _rest_of_name)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CosNaming.NamingContextExt (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CosNaming.NamingContextExt

Packages that use NamingContextExt
org.omg.CosNaming Provides a naming service for Java IDL.

Uses of NamingContextExt in org.omg.CosNaming

Classes in org.omg.CosNaming that implement NamingContextExt
 class _NamingContextExtStub
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.

Fields in org.omg.CosNaming declared as NamingContextExt
 NamingContextExt NamingContextExtHolder.value

Methods in org.omg.CosNaming that return NamingContextExt
NamingContextExt | NamingContextExtPOA._this()
NamingContextExt | NamingContextExtPOA._this(ORB orb)
static NamingContextExt | NamingContextExtHelper.extract(Any a)
static NamingContextExt | NamingContextExtHelper.read(InputStream istream)
static NamingContextExt | NamingContextExtHelper.narrow(Object obj)

Methods in org.omg.CosNaming with parameters of type NamingContextExt
static void | NamingContextExtHelper.insert(Any a, NamingContextExt that)
static void | NamingContextExtHelper.write(OutputStream ostream, NamingContextExt value)

Constructors in org.omg.CosNaming with parameters of type NamingContextExt
NamingContextExtHolder(NamingContextExt initialValue)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.NamingContextExtHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.NamingContextExtHelper

No usage of org.omg.CosNaming.NamingContextExtHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.NamingContextExtHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.NamingContextExtHolder

No usage of org.omg.CosNaming.NamingContextExtHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CosNaming.NamingContextExtOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CosNaming.NamingContextExtOperations

Packages that use NamingContextExtOperations
org.omg.CosNaming Provides a naming service for Java IDL.

Uses of NamingContextExtOperations in org.omg.CosNaming

Subinterfaces of NamingContextExtOperations in org.omg.CosNaming
 interface NamingContextExt
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.

Classes in org.omg.CosNaming that implement NamingContextExtOperations
class | _NamingContextExtStub 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.
class | NamingContextExtPOA 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.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.NamingContextExtPOA (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.NamingContextExtPOA

No usage of org.omg.CosNaming.NamingContextExtPOA

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.NamingContextHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.NamingContextHelper

No usage of org.omg.CosNaming.NamingContextHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.NamingContextHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.NamingContextHolder

No usage of org.omg.CosNaming.NamingContextHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.CosNaming.NamingContextOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.CosNaming.NamingContextOperations

Packages that use NamingContextOperations
org.omg.CosNaming Provides a naming service for Java IDL.

Uses of NamingContextOperations in org.omg.CosNaming

Subinterfaces of NamingContextOperations in org.omg.CosNaming
interface | NamingContext A naming context is an object that contains a set of name bindings in which each name is unique.
interface | NamingContextExt 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.
interface | NamingContextExtOperations 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.

Classes in org.omg.CosNaming that implement NamingContextOperations
class | _NamingContextExtStub 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.
class | _NamingContextImplBase
class | _NamingContextStub A naming context is an object that contains a set of name bindings in which each name is unique.
class | NamingContextExtPOA 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.
class | NamingContextPOA A naming context is an object that contains a set of name bindings in which each name is unique.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.NamingContextPOA (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.NamingContextPOA

No usage of org.omg.CosNaming.NamingContextPOA

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


AddressHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming.NamingContextExtPackage
Class AddressHelper

java.lang.Object
    extended by org.omg.CosNaming.NamingContextExtPackage.AddressHelper
public abstract class AddressHelper
extends Object

Address is the Host and Port information represented as a String.

Constructor Summary
AddressHelper()
Method Summary
static String | extract(Any a)
static String | id()
static void | insert(Any a, String that)
static String | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, String value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

AddressHelper

public AddressHelper()
Method Detail

insert

public static void insert(Any a,
                          String that)

extract

public static String extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static String read(InputStream istream)

write

public static void write(OutputStream ostream,
                         String value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


InvalidAddress (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming.NamingContextExtPackage
Class InvalidAddress

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.CosNaming.NamingContextExtPackage.InvalidAddress
All Implemented Interfaces:
IDLEntity, Serializable
public final class InvalidAddress
extends UserException

org/omg/CosNaming/NamingContextExtPackage/InvalidAddress.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/CosNaming/nameservice.idl Thursday, June 12, 2003 9:59:22 PM GMT-08:00

Constructor Summary
InvalidAddress()
InvalidAddress(String $reason)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

InvalidAddress

public InvalidAddress()

InvalidAddress

public InvalidAddress(String $reason)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


InvalidAddressHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming.NamingContextExtPackage
Class InvalidAddressHelper

java.lang.Object
    extended by org.omg.CosNaming.NamingContextExtPackage.InvalidAddressHelper
public abstract class InvalidAddressHelper
extends Object

org/omg/CosNaming/NamingContextExtPackage/InvalidAddressHelper.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/CosNaming/nameservice.idl Thursday, June 12, 2003 9:59:22 PM GMT-08:00

Constructor Summary
InvalidAddressHelper()
Method Summary
static InvalidAddress | extract(Any a)
static String | id()
static void | insert(Any a, InvalidAddress that)
static InvalidAddress | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, InvalidAddress value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

InvalidAddressHelper

public InvalidAddressHelper()
Method Detail

insert

public static void insert(Any a,
                          InvalidAddress that)

extract

public static InvalidAddress extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static InvalidAddress read(InputStream istream)

write

public static void write(OutputStream ostream,
                         InvalidAddress value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


InvalidAddressHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming.NamingContextExtPackage
Class InvalidAddressHolder

java.lang.Object
    extended by org.omg.CosNaming.NamingContextExtPackage.InvalidAddressHolder
All Implemented Interfaces:
Streamable
public final class InvalidAddressHolder
extends Object
implements Streamable

org/omg/CosNaming/NamingContextExtPackage/InvalidAddressHolder.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/CosNaming/nameservice.idl Thursday, June 12, 2003 9:59:22 PM GMT-08:00

Field Summary
 InvalidAddress value
Constructor Summary
InvalidAddressHolder()
InvalidAddressHolder(InvalidAddress initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public InvalidAddress value
Constructor Detail

InvalidAddressHolder

public InvalidAddressHolder()

InvalidAddressHolder

public InvalidAddressHolder(InvalidAddress initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


org.omg.CosNaming.NamingContextExtPackage (Java 2 Platform SE v1.4.2)

 org.omg.CosNaming.NamingContextExtPackage
Classes
AddressHelper
InvalidAddressHelper
InvalidAddressHolder
StringNameHelper
URLStringHelper
Exceptions
InvalidAddress


org.omg.CosNaming.NamingContextExtPackage (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package org.omg.CosNaming.NamingContextExtPackage

This package contains the following classes, which are used in org.omg.CosNaming.NamingContextExt:

See:
Description

Class Summary
AddressHelper | Address is the Host and Port information represented as a String.
InvalidAddressHelper | org/omg/CosNaming/NamingContextExtPackage/InvalidAddressHelper.java .
InvalidAddressHolder | org/omg/CosNaming/NamingContextExtPackage/InvalidAddressHolder.java .
StringNameHelper | StringName is the Stringified Name, Array of Name Components represented as a String.
URLStringHelper | URLString is the URL address (corbaloc: or corbaname:) represented as a String.

Exception Summary
InvalidAddress org/omg/CosNaming/NamingContextExtPackage/InvalidAddress.java .

Package org.omg.CosNaming.NamingContextExtPackage Description

This package contains the following classes, which are used in org.omg.CosNaming.NamingContextExt:

  • AddressHelper
  • StringNameHelper
  • URLStringHelper
  • InvalidAddress

    Package Specification

    For a precise list of supported sections of official specifications with which the Java 2 Platform, Standard Edition, v.1.4 ORB complies, see Official Specifications for CORBA support in J2SE 1.4.

    Since:
    1.4
    Overview Package Class Use Tree Deprecated Index Help
            JavaTM 2 Platform
    Std. Ed. v1.4.2
    PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


org.omg.CosNaming.NamingContextExtPackage Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package org.omg.CosNaming.NamingContextExtPackage

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class org.omg.CosNaming.NamingContextExtPackage.AddressHelper
    • class org.omg.CosNaming.NamingContextExtPackage.InvalidAddressHelper
    • class org.omg.CosNaming.NamingContextExtPackage.InvalidAddressHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CosNaming.NamingContextExtPackage.StringNameHelper
    • class java.lang.Throwable (implements java.io.Serializable)
      • class java.lang.Exception
        • class org.omg.CORBA.UserException (implements org.omg.CORBA.portable.IDLEntity)
          • class org.omg.CosNaming.NamingContextExtPackage.InvalidAddress
    • class org.omg.CosNaming.NamingContextExtPackage.URLStringHelper
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package org.omg.CosNaming.NamingContextExtPackage (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
org.omg.CosNaming.NamingContextExtPackage

Packages that use org.omg.CosNaming.NamingContextExtPackage
org.omg.CosNaming | Provides a naming service for Java IDL.
org.omg.CosNaming.NamingContextExtPackage | This package contains the following classes, which are used in org.omg.CosNaming.NamingContextExt:

Classes in org.omg.CosNaming.NamingContextExtPackage used by org.omg.CosNaming
InvalidAddress
org/omg/CosNaming/NamingContextExtPackage/InvalidAddress.java .

Classes in org.omg.CosNaming.NamingContextExtPackage used by org.omg.CosNaming.NamingContextExtPackage
InvalidAddress
org/omg/CosNaming/NamingContextExtPackage/InvalidAddress.java .

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


StringNameHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming.NamingContextExtPackage
Class StringNameHelper

java.lang.Object
    extended by org.omg.CosNaming.NamingContextExtPackage.StringNameHelper
public abstract class StringNameHelper
extends Object

StringName is the Stringified Name, Array of Name Components represented as a String.

Constructor Summary
StringNameHelper()
Method Summary
static String | extract(Any a)
static String | id()
static void | insert(Any a, String that)
static String | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, String value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

StringNameHelper

public StringNameHelper()
Method Detail

insert

public static void insert(Any a,
                          String that)

extract

public static String extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static String read(InputStream istream)

write

public static void write(OutputStream ostream,
                         String value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


URLStringHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming.NamingContextExtPackage
Class URLStringHelper

java.lang.Object
    extended by org.omg.CosNaming.NamingContextExtPackage.URLStringHelper
public abstract class URLStringHelper
extends Object

URLString is the URL address (corbaloc: or corbaname:) represented as a String.

Constructor Summary
URLStringHelper()
Method Summary
static String | extract(Any a)
static String | id()
static void | insert(Any a, String that)
static String | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, String value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

URLStringHelper

public URLStringHelper()
Method Detail

insert

public static void insert(Any a,
                          String that)

extract

public static String extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static String read(InputStream istream)

write

public static void write(OutputStream ostream,
                         String value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Uses of Class org.omg.CosNaming.NamingContextExtPackage.AddressHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.NamingContextExtPackage.AddressHelper

No usage of org.omg.CosNaming.NamingContextExtPackage.AddressHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.NamingContextExtPackage.InvalidAddress (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.NamingContextExtPackage.InvalidAddress

Packages that use InvalidAddress
org.omg.CosNaming | Provides a naming service for Java IDL.
org.omg.CosNaming.NamingContextExtPackage | This package contains the following classes, which are used in org.omg.CosNaming.NamingContextExt:

Uses of InvalidAddress in org.omg.CosNaming

Methods in org.omg.CosNaming that throw InvalidAddress
String | _NamingContextExtStub.to_url(String addr, String sn) This operation creates a URL based "iiopname://" format name from the Stringified Name of the object.
String | NamingContextExtOperations.to_url(String addr, String sn) This operation creates a URL based "iiopname://" format name from the Stringified Name of the object.

Uses of InvalidAddress in org.omg.CosNaming.NamingContextExtPackage

Fields in org.omg.CosNaming.NamingContextExtPackage declared as InvalidAddress
 InvalidAddress InvalidAddressHolder.value

Methods in org.omg.CosNaming.NamingContextExtPackage that return InvalidAddress
static InvalidAddress | InvalidAddressHelper.extract(Any a)
static InvalidAddress | InvalidAddressHelper.read(InputStream istream)

Methods in org.omg.CosNaming.NamingContextExtPackage with parameters of type InvalidAddress
static void | InvalidAddressHelper.insert(Any a, InvalidAddress that)
static void | InvalidAddressHelper.write(OutputStream ostream, InvalidAddress value)

Constructors in org.omg.CosNaming.NamingContextExtPackage with parameters of type InvalidAddress
InvalidAddressHolder(InvalidAddress initialValue)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.NamingContextExtPackage.InvalidAddressHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.NamingContextExtPackage.InvalidAddressHelper

No usage of org.omg.CosNaming.NamingContextExtPackage.InvalidAddressHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.NamingContextExtPackage.InvalidAddressHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.NamingContextExtPackage.InvalidAddressHolder

No usage of org.omg.CosNaming.NamingContextExtPackage.InvalidAddressHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.NamingContextExtPackage.StringNameHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.NamingContextExtPackage.StringNameHelper

No usage of org.omg.CosNaming.NamingContextExtPackage.StringNameHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.NamingContextExtPackage.URLStringHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.NamingContextExtPackage.URLStringHelper

No usage of org.omg.CosNaming.NamingContextExtPackage.URLStringHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


AlreadyBound (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming.NamingContextPackage
Class AlreadyBound

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.CosNaming.NamingContextPackage.AlreadyBound
All Implemented Interfaces:
IDLEntity, Serializable
public final class AlreadyBound
extends UserException

org/omg/CosNaming/NamingContextPackage/AlreadyBound.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/CosNaming/nameservice.idl Thursday, June 12, 2003 9:59:22 PM GMT-08:00

Constructor Summary
AlreadyBound()
AlreadyBound(String $reason)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

AlreadyBound

public AlreadyBound()

AlreadyBound

public AlreadyBound(String $reason)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


AlreadyBoundHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming.NamingContextPackage
Class AlreadyBoundHelper

java.lang.Object
    extended by org.omg.CosNaming.NamingContextPackage.AlreadyBoundHelper
public abstract class AlreadyBoundHelper
extends Object

org/omg/CosNaming/NamingContextPackage/AlreadyBoundHelper.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/CosNaming/nameservice.idl Thursday, June 12, 2003 9:59:22 PM GMT-08:00

Constructor Summary
AlreadyBoundHelper()
Method Summary
static AlreadyBound | extract(Any a)
static String | id()
static void | insert(Any a, AlreadyBound that)
static AlreadyBound | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, AlreadyBound value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

AlreadyBoundHelper

public AlreadyBoundHelper()
Method Detail

insert

public static void insert(Any a,
                          AlreadyBound that)

extract

public static AlreadyBound extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static AlreadyBound read(InputStream istream)

write

public static void write(OutputStream ostream,
                         AlreadyBound value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


AlreadyBoundHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming.NamingContextPackage
Class AlreadyBoundHolder

java.lang.Object
    extended by org.omg.CosNaming.NamingContextPackage.AlreadyBoundHolder
All Implemented Interfaces:
Streamable
public final class AlreadyBoundHolder
extends Object
implements Streamable

org/omg/CosNaming/NamingContextPackage/AlreadyBoundHolder.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/CosNaming/nameservice.idl Thursday, June 12, 2003 9:59:22 PM GMT-08:00

Field Summary
 AlreadyBound value
Constructor Summary
AlreadyBoundHolder()
AlreadyBoundHolder(AlreadyBound initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public AlreadyBound value
Constructor Detail

AlreadyBoundHolder

public AlreadyBoundHolder()

AlreadyBoundHolder

public AlreadyBoundHolder(AlreadyBound initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


CannotProceed (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming.NamingContextPackage
Class CannotProceed

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.CosNaming.NamingContextPackage.CannotProceed
All Implemented Interfaces:
IDLEntity, Serializable
public final class CannotProceed
extends UserException

org/omg/CosNaming/NamingContextPackage/CannotProceed.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/CosNaming/nameservice.idl Thursday, June 12, 2003 9:59:22 PM GMT-08:00

Field Summary
NamingContext | cxt
NameComponent[] | rest_of_name
Constructor Summary
CannotProceed()
CannotProceed(NamingContext _cxt, NameComponent[] _rest_of_name)
CannotProceed(String $reason, NamingContext _cxt, NameComponent[] _rest_of_name)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

cxt

public NamingContext cxt

rest_of_name

public NameComponent[] rest_of_name
Constructor Detail

CannotProceed

public CannotProceed()

CannotProceed

public CannotProceed(NamingContext _cxt,
                     NameComponent[] _rest_of_name)

CannotProceed

public CannotProceed(String $reason,
                     NamingContext _cxt,
                     NameComponent[] _rest_of_name)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


CannotProceedHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming.NamingContextPackage
Class CannotProceedHelper

java.lang.Object
    extended by org.omg.CosNaming.NamingContextPackage.CannotProceedHelper
public abstract class CannotProceedHelper
extends Object

org/omg/CosNaming/NamingContextPackage/CannotProceedHelper.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/CosNaming/nameservice.idl Thursday, June 12, 2003 9:59:22 PM GMT-08:00

Constructor Summary
CannotProceedHelper()
Method Summary
static CannotProceed | extract(Any a)
static String | id()
static void | insert(Any a, CannotProceed that)
static CannotProceed | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, CannotProceed value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

CannotProceedHelper

public CannotProceedHelper()
Method Detail

insert

public static void insert(Any a,
                          CannotProceed that)

extract

public static CannotProceed extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static CannotProceed read(InputStream istream)

write

public static void write(OutputStream ostream,
                         CannotProceed value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


CannotProceedHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming.NamingContextPackage
Class CannotProceedHolder

java.lang.Object
    extended by org.omg.CosNaming.NamingContextPackage.CannotProceedHolder
All Implemented Interfaces:
Streamable
public final class CannotProceedHolder
extends Object
implements Streamable

org/omg/CosNaming/NamingContextPackage/CannotProceedHolder.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/CosNaming/nameservice.idl Thursday, June 12, 2003 9:59:22 PM GMT-08:00

Field Summary
 CannotProceed value
Constructor Summary
CannotProceedHolder()
CannotProceedHolder(CannotProceed initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public CannotProceed value
Constructor Detail

CannotProceedHolder

public CannotProceedHolder()

CannotProceedHolder

public CannotProceedHolder(CannotProceed initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


InvalidName (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming.NamingContextPackage
Class InvalidName

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.CosNaming.NamingContextPackage.InvalidName
All Implemented Interfaces:
IDLEntity, Serializable
public final class InvalidName
extends UserException

org/omg/CosNaming/NamingContextPackage/InvalidName.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/CosNaming/nameservice.idl Thursday, June 12, 2003 9:59:22 PM GMT-08:00

Constructor Summary
InvalidName()
InvalidName(String $reason)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

InvalidName

public InvalidName()

InvalidName

public InvalidName(String $reason)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


InvalidNameHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming.NamingContextPackage
Class InvalidNameHelper

java.lang.Object
    extended by org.omg.CosNaming.NamingContextPackage.InvalidNameHelper
public abstract class InvalidNameHelper
extends Object

org/omg/CosNaming/NamingContextPackage/InvalidNameHelper.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/CosNaming/nameservice.idl Thursday, June 12, 2003 9:59:22 PM GMT-08:00

Constructor Summary
InvalidNameHelper()
Method Summary
static InvalidName | extract(Any a)
static String | id()
static void | insert(Any a, InvalidName that)
static InvalidName | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, InvalidName value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

InvalidNameHelper

public InvalidNameHelper()
Method Detail

insert

public static void insert(Any a,
                          InvalidName that)

extract

public static InvalidName extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static InvalidName read(InputStream istream)

write

public static void write(OutputStream ostream,
                         InvalidName value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


InvalidNameHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming.NamingContextPackage
Class InvalidNameHolder

java.lang.Object
    extended by org.omg.CosNaming.NamingContextPackage.InvalidNameHolder
All Implemented Interfaces:
Streamable
public final class InvalidNameHolder
extends Object
implements Streamable

org/omg/CosNaming/NamingContextPackage/InvalidNameHolder.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/CosNaming/nameservice.idl Thursday, June 12, 2003 9:59:22 PM GMT-08:00

Field Summary
 InvalidName value
Constructor Summary
InvalidNameHolder()
InvalidNameHolder(InvalidName initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public InvalidName value
Constructor Detail

InvalidNameHolder

public InvalidNameHolder()

InvalidNameHolder

public InvalidNameHolder(InvalidName initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NotEmpty (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming.NamingContextPackage
Class NotEmpty

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.CosNaming.NamingContextPackage.NotEmpty
All Implemented Interfaces:
IDLEntity, Serializable
public final class NotEmpty
extends UserException

org/omg/CosNaming/NamingContextPackage/NotEmpty.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/CosNaming/nameservice.idl Thursday, June 12, 2003 9:59:22 PM GMT-08:00

Constructor Summary
NotEmpty()
NotEmpty(String $reason)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

NotEmpty

public NotEmpty()

NotEmpty

public NotEmpty(String $reason)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NotEmptyHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming.NamingContextPackage
Class NotEmptyHelper

java.lang.Object
    extended by org.omg.CosNaming.NamingContextPackage.NotEmptyHelper
public abstract class NotEmptyHelper
extends Object

org/omg/CosNaming/NamingContextPackage/NotEmptyHelper.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/CosNaming/nameservice.idl Thursday, June 12, 2003 9:59:22 PM GMT-08:00

Constructor Summary
NotEmptyHelper()
Method Summary
static NotEmpty | extract(Any a)
static String | id()
static void | insert(Any a, NotEmpty that)
static NotEmpty | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, NotEmpty value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

NotEmptyHelper

public NotEmptyHelper()
Method Detail

insert

public static void insert(Any a,
                          NotEmpty that)

extract

public static NotEmpty extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static NotEmpty read(InputStream istream)

write

public static void write(OutputStream ostream,
                         NotEmpty value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NotEmptyHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming.NamingContextPackage
Class NotEmptyHolder

java.lang.Object
    extended by org.omg.CosNaming.NamingContextPackage.NotEmptyHolder
All Implemented Interfaces:
Streamable
public final class NotEmptyHolder
extends Object
implements Streamable

org/omg/CosNaming/NamingContextPackage/NotEmptyHolder.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/CosNaming/nameservice.idl Thursday, June 12, 2003 9:59:22 PM GMT-08:00

Field Summary
 NotEmpty value
Constructor Summary
NotEmptyHolder()
NotEmptyHolder(NotEmpty initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public NotEmpty value
Constructor Detail

NotEmptyHolder

public NotEmptyHolder()

NotEmptyHolder

public NotEmptyHolder(NotEmpty initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NotFound (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming.NamingContextPackage
Class NotFound

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.CosNaming.NamingContextPackage.NotFound
All Implemented Interfaces:
IDLEntity, Serializable
public final class NotFound
extends UserException

org/omg/CosNaming/NamingContextPackage/NotFound.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/CosNaming/nameservice.idl Thursday, June 12, 2003 9:59:22 PM GMT-08:00

Field Summary
NameComponent[] | rest_of_name
NotFoundReason | why
Constructor Summary
NotFound()
NotFound(NotFoundReason _why, NameComponent[] _rest_of_name)
NotFound(String $reason, NotFoundReason _why, NameComponent[] _rest_of_name)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

why

public NotFoundReason why

rest_of_name

public NameComponent[] rest_of_name
Constructor Detail

NotFound

public NotFound()

NotFound

public NotFound(NotFoundReason _why,
                NameComponent[] _rest_of_name)

NotFound

public NotFound(String $reason,
                NotFoundReason _why,
                NameComponent[] _rest_of_name)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


NotFoundHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming.NamingContextPackage
Class NotFoundHelper

java.lang.Object
    extended by org.omg.CosNaming.NamingContextPackage.NotFoundHelper
public abstract class NotFoundHelper
extends Object

org/omg/CosNaming/NamingContextPackage/NotFoundHelper.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/CosNaming/nameservice.idl Thursday, June 12, 2003 9:59:22 PM GMT-08:00

Constructor Summary
NotFoundHelper()
Method Summary
static NotFound | extract(Any a)
static String | id()
static void | insert(Any a, NotFound that)
static NotFound | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, NotFound value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

NotFoundHelper

public NotFoundHelper()
Method Detail

insert

public static void insert(Any a,
                          NotFound that)

extract

public static NotFound extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static NotFound read(InputStream istream)

write

public static void write(OutputStream ostream,
                         NotFound value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NotFoundHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming.NamingContextPackage
Class NotFoundHolder

java.lang.Object
    extended by org.omg.CosNaming.NamingContextPackage.NotFoundHolder
All Implemented Interfaces:
Streamable
public final class NotFoundHolder
extends Object
implements Streamable

org/omg/CosNaming/NamingContextPackage/NotFoundHolder.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/CosNaming/nameservice.idl Thursday, June 12, 2003 9:59:22 PM GMT-08:00

Field Summary
 NotFound value
Constructor Summary
NotFoundHolder()
NotFoundHolder(NotFound initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public NotFound value
Constructor Detail

NotFoundHolder

public NotFoundHolder()

NotFoundHolder

public NotFoundHolder(NotFound initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NotFoundReason (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming.NamingContextPackage
Class NotFoundReason

java.lang.Object
    extended by org.omg.CosNaming.NamingContextPackage.NotFoundReason
All Implemented Interfaces:
IDLEntity, Serializable
public class NotFoundReason
extends Object
implements IDLEntity

Indicates the reason for not able to resolve.

Field Summary
static int | _missing_node
static int | _not_context
static int | _not_object
static NotFoundReason | missing_node
static NotFoundReason | not_context
static NotFoundReason | not_object
Constructor Summary
protected NotFoundReason(int value)
Method Summary
static NotFoundReason | from_int(int value)
int | value()
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

_missing_node

public static final int _missing_node
See Also:
Constant Field Values

missing_node

public static final NotFoundReason missing_node

_not_context

public static final int _not_context
See Also:
Constant Field Values

not_context

public static final NotFoundReason not_context

_not_object

public static final int _not_object
See Also:
Constant Field Values

not_object

public static final NotFoundReason not_object
Constructor Detail

NotFoundReason

protected NotFoundReason(int value)
Method Detail

value

public int value()

from_int

public static NotFoundReason from_int(int value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NotFoundReasonHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming.NamingContextPackage
Class NotFoundReasonHelper

java.lang.Object
    extended by org.omg.CosNaming.NamingContextPackage.NotFoundReasonHelper
public abstract class NotFoundReasonHelper
extends Object

Indicates the reason for not able to resolve.

Constructor Summary
NotFoundReasonHelper()
Method Summary
static NotFoundReason | extract(Any a)
static String | id()
static void | insert(Any a, NotFoundReason that)
static NotFoundReason | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, NotFoundReason value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

NotFoundReasonHelper

public NotFoundReasonHelper()
Method Detail

insert

public static void insert(Any a,
                          NotFoundReason that)

extract

public static NotFoundReason extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static NotFoundReason read(InputStream istream)

write

public static void write(OutputStream ostream,
                         NotFoundReason value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NotFoundReasonHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.CosNaming.NamingContextPackage
Class NotFoundReasonHolder

java.lang.Object
    extended by org.omg.CosNaming.NamingContextPackage.NotFoundReasonHolder
All Implemented Interfaces:
Streamable
public final class NotFoundReasonHolder
extends Object
implements Streamable

Indicates the reason for not able to resolve.

Field Summary
 NotFoundReason value
Constructor Summary
NotFoundReasonHolder()
NotFoundReasonHolder(NotFoundReason initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public NotFoundReason value
Constructor Detail

NotFoundReasonHolder

public NotFoundReasonHolder()

NotFoundReasonHolder

public NotFoundReasonHolder(NotFoundReason initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


org.omg.CosNaming.NamingContextPackage (Java 2 Platform SE v1.4.2)

 org.omg.CosNaming.NamingContextPackage
Classes
AlreadyBoundHelper
AlreadyBoundHolder
CannotProceedHelper
CannotProceedHolder
InvalidNameHelper
InvalidNameHolder
NotEmptyHelper
NotEmptyHolder
NotFoundHelper
NotFoundHolder
NotFoundReason
NotFoundReasonHelper
NotFoundReasonHolder
Exceptions
AlreadyBound
CannotProceed
InvalidName
NotEmpty
NotFound


org.omg.CosNaming.NamingContextPackage (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package org.omg.CosNaming.NamingContextPackage

This package contains Exception classes for the org.omg.CosNaming package.

See:
Description

Class Summary
AlreadyBoundHelper | org/omg/CosNaming/NamingContextPackage/AlreadyBoundHelper.java .
AlreadyBoundHolder | org/omg/CosNaming/NamingContextPackage/AlreadyBoundHolder.java .
CannotProceedHelper | org/omg/CosNaming/NamingContextPackage/CannotProceedHelper.java .
CannotProceedHolder | org/omg/CosNaming/NamingContextPackage/CannotProceedHolder.java .
InvalidNameHelper | org/omg/CosNaming/NamingContextPackage/InvalidNameHelper.java .
InvalidNameHolder | org/omg/CosNaming/NamingContextPackage/InvalidNameHolder.java .
NotEmptyHelper | org/omg/CosNaming/NamingContextPackage/NotEmptyHelper.java .
NotEmptyHolder | org/omg/CosNaming/NamingContextPackage/NotEmptyHolder.java .
NotFoundHelper | org/omg/CosNaming/NamingContextPackage/NotFoundHelper.java .
NotFoundHolder | org/omg/CosNaming/NamingContextPackage/NotFoundHolder.java .
NotFoundReason | Indicates the reason for not able to resolve.
NotFoundReasonHelper | Indicates the reason for not able to resolve.
NotFoundReasonHolder | Indicates the reason for not able to resolve.

Exception Summary
AlreadyBound | org/omg/CosNaming/NamingContextPackage/AlreadyBound.java .
CannotProceed | org/omg/CosNaming/NamingContextPackage/CannotProceed.java .
InvalidName | org/omg/CosNaming/NamingContextPackage/InvalidName.java .
NotEmpty | org/omg/CosNaming/NamingContextPackage/NotEmpty.java .
NotFound | org/omg/CosNaming/NamingContextPackage/NotFound.java .

Package org.omg.CosNaming.NamingContextPackage Description

This package contains Exception classes for the org.omg.CosNaming package. The list of exception classes are:

  • AlreadyBound
  • CannotProceed
  • InvalidName
  • NotEmpty
  • NotFound
  • NotFoundReason

    Package Specification

    For a precise list of supported sections of official specifications with which the Java 2 Platform, Standard Edition, v.1.4 ORB complies, see Official Specifications for CORBA support in J2SE 1.4.

    Since:
    1.4
    Overview Package Class Use Tree Deprecated Index Help
            JavaTM 2 Platform
    Std. Ed. v1.4.2
    PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


org.omg.CosNaming.NamingContextPackage Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package org.omg.CosNaming.NamingContextPackage

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class org.omg.CosNaming.NamingContextPackage.AlreadyBoundHelper
    • class org.omg.CosNaming.NamingContextPackage.AlreadyBoundHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CosNaming.NamingContextPackage.CannotProceedHelper
    • class org.omg.CosNaming.NamingContextPackage.CannotProceedHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CosNaming.NamingContextPackage.InvalidNameHelper
    • class org.omg.CosNaming.NamingContextPackage.InvalidNameHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CosNaming.NamingContextPackage.NotEmptyHelper
    • class org.omg.CosNaming.NamingContextPackage.NotEmptyHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CosNaming.NamingContextPackage.NotFoundHelper
    • class org.omg.CosNaming.NamingContextPackage.NotFoundHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.CosNaming.NamingContextPackage.NotFoundReason (implements org.omg.CORBA.portable.IDLEntity)
    • class org.omg.CosNaming.NamingContextPackage.NotFoundReasonHelper
    • class org.omg.CosNaming.NamingContextPackage.NotFoundReasonHolder (implements org.omg.CORBA.portable.Streamable)
    • class java.lang.Throwable (implements java.io.Serializable)
      • class java.lang.Exception
        • class org.omg.CORBA.UserException (implements org.omg.CORBA.portable.IDLEntity)
          • class org.omg.CosNaming.NamingContextPackage.AlreadyBound
          • class org.omg.CosNaming.NamingContextPackage.CannotProceed
          • class org.omg.CosNaming.NamingContextPackage.InvalidName
          • class org.omg.CosNaming.NamingContextPackage.NotEmpty
          • class org.omg.CosNaming.NamingContextPackage.NotFound
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package org.omg.CosNaming.NamingContextPackage (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
org.omg.CosNaming.NamingContextPackage

Packages that use org.omg.CosNaming.NamingContextPackage
org.omg.CosNaming | Provides a naming service for Java IDL.
org.omg.CosNaming.NamingContextPackage | This package contains Exception classes for the org.omg.CosNaming package.

Classes in org.omg.CosNaming.NamingContextPackage used by org.omg.CosNaming
AlreadyBound
org/omg/CosNaming/NamingContextPackage/AlreadyBound.java .
CannotProceed
org/omg/CosNaming/NamingContextPackage/CannotProceed.java .
InvalidName
org/omg/CosNaming/NamingContextPackage/InvalidName.java .
NotEmpty
org/omg/CosNaming/NamingContextPackage/NotEmpty.java .
NotFound
org/omg/CosNaming/NamingContextPackage/NotFound.java .

Classes in org.omg.CosNaming.NamingContextPackage used by org.omg.CosNaming.NamingContextPackage
AlreadyBound
org/omg/CosNaming/NamingContextPackage/AlreadyBound.java .
CannotProceed
org/omg/CosNaming/NamingContextPackage/CannotProceed.java .
InvalidName
org/omg/CosNaming/NamingContextPackage/InvalidName.java .
NotEmpty
org/omg/CosNaming/NamingContextPackage/NotEmpty.java .
NotFound
org/omg/CosNaming/NamingContextPackage/NotFound.java .
NotFoundReason
Indicates the reason for not able to resolve.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.NamingContextPackage.AlreadyBound (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.NamingContextPackage.AlreadyBound

Packages that use AlreadyBound
org.omg.CosNaming | Provides a naming service for Java IDL.
org.omg.CosNaming.NamingContextPackage | This package contains Exception classes for the org.omg.CosNaming package.

Uses of AlreadyBound in org.omg.CosNaming

Methods in org.omg.CosNaming that throw AlreadyBound
void | _NamingContextExtStub.bind(NameComponent[] n, Object obj) Creates a binding of a name and an object in the naming context.
void | _NamingContextExtStub.bind_context(NameComponent[] n, NamingContext nc) Names an object that is a naming context.
NamingContext | _NamingContextExtStub.bind_new_context(NameComponent[] n) This operation creates a new context and binds it to the name supplied as an argument.
void | _NamingContextStub.bind(NameComponent[] n, Object obj) Creates a binding of a name and an object in the naming context.
void | _NamingContextStub.bind_context(NameComponent[] n, NamingContext nc) Names an object that is a naming context.
NamingContext | _NamingContextStub.bind_new_context(NameComponent[] n) This operation creates a new context and binds it to the name supplied as an argument.
void | NamingContextOperations.bind(NameComponent[] n, Object obj) Creates a binding of a name and an object in the naming context.
void | NamingContextOperations.bind_context(NameComponent[] n, NamingContext nc) Names an object that is a naming context.
NamingContext | NamingContextOperations.bind_new_context(NameComponent[] n) This operation creates a new context and binds it to the name supplied as an argument.

Uses of AlreadyBound in org.omg.CosNaming.NamingContextPackage

Fields in org.omg.CosNaming.NamingContextPackage declared as AlreadyBound
 AlreadyBound AlreadyBoundHolder.value

Methods in org.omg.CosNaming.NamingContextPackage that return AlreadyBound
static AlreadyBound | AlreadyBoundHelper.extract(Any a)
static AlreadyBound | AlreadyBoundHelper.read(InputStream istream)

Methods in org.omg.CosNaming.NamingContextPackage with parameters of type AlreadyBound
static void | AlreadyBoundHelper.insert(Any a, AlreadyBound that)
static void | AlreadyBoundHelper.write(OutputStream ostream, AlreadyBound value)

Constructors in org.omg.CosNaming.NamingContextPackage with parameters of type AlreadyBound
AlreadyBoundHolder(AlreadyBound initialValue)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.NamingContextPackage.AlreadyBoundHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.NamingContextPackage.AlreadyBoundHelper

No usage of org.omg.CosNaming.NamingContextPackage.AlreadyBoundHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.NamingContextPackage.AlreadyBoundHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.NamingContextPackage.AlreadyBoundHolder

No usage of org.omg.CosNaming.NamingContextPackage.AlreadyBoundHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.NamingContextPackage.CannotProceed (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.NamingContextPackage.CannotProceed

Packages that use CannotProceed
org.omg.CosNaming | Provides a naming service for Java IDL.
org.omg.CosNaming.NamingContextPackage | This package contains Exception classes for the org.omg.CosNaming package.

Uses of CannotProceed in org.omg.CosNaming

Methods in org.omg.CosNaming that throw CannotProceed
Object | _NamingContextExtStub.resolve_str(String sn) This operation resolves the Stringified name into the object reference.
void | _NamingContextExtStub.bind(NameComponent[] n, Object obj) Creates a binding of a name and an object in the naming context.
void | _NamingContextExtStub.bind_context(NameComponent[] n, NamingContext nc) Names an object that is a naming context.
void | _NamingContextExtStub.rebind(NameComponent[] n, Object obj) Creates a binding of a name and an object in the naming context even if the name is already bound in the context.
void | _NamingContextExtStub.rebind_context(NameComponent[] n, NamingContext nc) Creates a binding of a name and a naming context in the naming context even if the name is already bound in the context.
Object | _NamingContextExtStub.resolve(NameComponent[] n) The resolve operation is the process of retrieving an object bound to a name in a given context.
void | _NamingContextExtStub.unbind(NameComponent[] n) The unbind operation removes a name binding from a context.
NamingContext | _NamingContextExtStub.bind_new_context(NameComponent[] n) This operation creates a new context and binds it to the name supplied as an argument.
Object | NamingContextExtOperations.resolve_str(String sn) This operation resolves the Stringified name into the object reference.
void | _NamingContextStub.bind(NameComponent[] n, Object obj) Creates a binding of a name and an object in the naming context.
void | _NamingContextStub.bind_context(NameComponent[] n, NamingContext nc) Names an object that is a naming context.
void | _NamingContextStub.rebind(NameComponent[] n, Object obj) Creates a binding of a name and an object in the naming context even if the name is already bound in the context.
void | _NamingContextStub.rebind_context(NameComponent[] n, NamingContext nc) Creates a binding of a name and a naming context in the naming context even if the name is already bound in the context.
Object | _NamingContextStub.resolve(NameComponent[] n) The resolve operation is the process of retrieving an object bound to a name in a given context.
void | _NamingContextStub.unbind(NameComponent[] n) The unbind operation removes a name binding from a context.
NamingContext | _NamingContextStub.bind_new_context(NameComponent[] n) This operation creates a new context and binds it to the name supplied as an argument.
void | NamingContextOperations.bind(NameComponent[] n, Object obj) Creates a binding of a name and an object in the naming context.
void | NamingContextOperations.bind_context(NameComponent[] n, NamingContext nc) Names an object that is a naming context.
void | NamingContextOperations.rebind(NameComponent[] n, Object obj) Creates a binding of a name and an object in the naming context even if the name is already bound in the context.
void | NamingContextOperations.rebind_context(NameComponent[] n, NamingContext nc) Creates a binding of a name and a naming context in the naming context even if the name is already bound in the context.
Object | NamingContextOperations.resolve(NameComponent[] n) The resolve operation is the process of retrieving an object bound to a name in a given context.
void | NamingContextOperations.unbind(NameComponent[] n) The unbind operation removes a name binding from a context.
NamingContext | NamingContextOperations.bind_new_context(NameComponent[] n) This operation creates a new context and binds it to the name supplied as an argument.

Uses of CannotProceed in org.omg.CosNaming.NamingContextPackage

Fields in org.omg.CosNaming.NamingContextPackage declared as CannotProceed
 CannotProceed CannotProceedHolder.value

Methods in org.omg.CosNaming.NamingContextPackage that return CannotProceed
static CannotProceed | CannotProceedHelper.extract(Any a)
static CannotProceed | CannotProceedHelper.read(InputStream istream)

Methods in org.omg.CosNaming.NamingContextPackage with parameters of type CannotProceed
static void | CannotProceedHelper.insert(Any a, CannotProceed that)
static void | CannotProceedHelper.write(OutputStream ostream, CannotProceed value)

Constructors in org.omg.CosNaming.NamingContextPackage with parameters of type CannotProceed
CannotProceedHolder(CannotProceed initialValue)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.NamingContextPackage.CannotProceedHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.NamingContextPackage.CannotProceedHelper

No usage of org.omg.CosNaming.NamingContextPackage.CannotProceedHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.NamingContextPackage.CannotProceedHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.NamingContextPackage.CannotProceedHolder

No usage of org.omg.CosNaming.NamingContextPackage.CannotProceedHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.NamingContextPackage.InvalidName (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.NamingContextPackage.InvalidName

Packages that use InvalidName
org.omg.CosNaming | Provides a naming service for Java IDL.
org.omg.CosNaming.NamingContextPackage | This package contains Exception classes for the org.omg.CosNaming package.

Uses of InvalidName in org.omg.CosNaming

Methods in org.omg.CosNaming that throw InvalidName
String | _NamingContextExtStub.to_string(NameComponent[] n) This operation creates a stringified name from the array of Name components.
NameComponent[] | _NamingContextExtStub.to_name(String sn) This operation converts a Stringified Name into an equivalent array of Name Components.
String | _NamingContextExtStub.to_url(String addr, String sn) This operation creates a URL based "iiopname://" format name from the Stringified Name of the object.
Object | _NamingContextExtStub.resolve_str(String sn) This operation resolves the Stringified name into the object reference.
void | _NamingContextExtStub.bind(NameComponent[] n, Object obj) Creates a binding of a name and an object in the naming context.
void | _NamingContextExtStub.bind_context(NameComponent[] n, NamingContext nc) Names an object that is a naming context.
void | _NamingContextExtStub.rebind(NameComponent[] n, Object obj) Creates a binding of a name and an object in the naming context even if the name is already bound in the context.
void | _NamingContextExtStub.rebind_context(NameComponent[] n, NamingContext nc) Creates a binding of a name and a naming context in the naming context even if the name is already bound in the context.
Object | _NamingContextExtStub.resolve(NameComponent[] n) The resolve operation is the process of retrieving an object bound to a name in a given context.
void | _NamingContextExtStub.unbind(NameComponent[] n) The unbind operation removes a name binding from a context.
NamingContext | _NamingContextExtStub.bind_new_context(NameComponent[] n) This operation creates a new context and binds it to the name supplied as an argument.
String | NamingContextExtOperations.to_string(NameComponent[] n) This operation creates a stringified name from the array of Name components.
NameComponent[] | NamingContextExtOperations.to_name(String sn) This operation converts a Stringified Name into an equivalent array of Name Components.
String | NamingContextExtOperations.to_url(String addr, String sn) This operation creates a URL based "iiopname://" format name from the Stringified Name of the object.
Object | NamingContextExtOperations.resolve_str(String sn) This operation resolves the Stringified name into the object reference.
void | _NamingContextStub.bind(NameComponent[] n, Object obj) Creates a binding of a name and an object in the naming context.
void | _NamingContextStub.bind_context(NameComponent[] n, NamingContext nc) Names an object that is a naming context.
void | _NamingContextStub.rebind(NameComponent[] n, Object obj) Creates a binding of a name and an object in the naming context even if the name is already bound in the context.
void | _NamingContextStub.rebind_context(NameComponent[] n, NamingContext nc) Creates a binding of a name and a naming context in the naming context even if the name is already bound in the context.
Object | _NamingContextStub.resolve(NameComponent[] n) The resolve operation is the process of retrieving an object bound to a name in a given context.
void | _NamingContextStub.unbind(NameComponent[] n) The unbind operation removes a name binding from a context.
NamingContext | _NamingContextStub.bind_new_context(NameComponent[] n) This operation creates a new context and binds it to the name supplied as an argument.
void | NamingContextOperations.bind(NameComponent[] n, Object obj) Creates a binding of a name and an object in the naming context.
void | NamingContextOperations.bind_context(NameComponent[] n, NamingContext nc) Names an object that is a naming context.
void | NamingContextOperations.rebind(NameComponent[] n, Object obj) Creates a binding of a name and an object in the naming context even if the name is already bound in the context.
void | NamingContextOperations.rebind_context(NameComponent[] n, NamingContext nc) Creates a binding of a name and a naming context in the naming context even if the name is already bound in the context.
Object | NamingContextOperations.resolve(NameComponent[] n) The resolve operation is the process of retrieving an object bound to a name in a given context.
void | NamingContextOperations.unbind(NameComponent[] n) The unbind operation removes a name binding from a context.
NamingContext | NamingContextOperations.bind_new_context(NameComponent[] n) This operation creates a new context and binds it to the name supplied as an argument.

Uses of InvalidName in org.omg.CosNaming.NamingContextPackage

Fields in org.omg.CosNaming.NamingContextPackage declared as InvalidName
 InvalidName InvalidNameHolder.value

Methods in org.omg.CosNaming.NamingContextPackage that return InvalidName
static InvalidName | InvalidNameHelper.extract(Any a)
static InvalidName | InvalidNameHelper.read(InputStream istream)

Methods in org.omg.CosNaming.NamingContextPackage with parameters of type InvalidName
static void | InvalidNameHelper.insert(Any a, InvalidName that)
static void | InvalidNameHelper.write(OutputStream ostream, InvalidName value)

Constructors in org.omg.CosNaming.NamingContextPackage with parameters of type InvalidName
InvalidNameHolder(InvalidName initialValue)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.NamingContextPackage.InvalidNameHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.NamingContextPackage.InvalidNameHelper

No usage of org.omg.CosNaming.NamingContextPackage.InvalidNameHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.NamingContextPackage.InvalidNameHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.NamingContextPackage.InvalidNameHolder

No usage of org.omg.CosNaming.NamingContextPackage.InvalidNameHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.NamingContextPackage.NotEmpty (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.NamingContextPackage.NotEmpty

Packages that use NotEmpty
org.omg.CosNaming | Provides a naming service for Java IDL.
org.omg.CosNaming.NamingContextPackage | This package contains Exception classes for the org.omg.CosNaming package.

Uses of NotEmpty in org.omg.CosNaming

Methods in org.omg.CosNaming that throw NotEmpty
void | _NamingContextExtStub.destroy() The destroy operation deletes a naming context.
void | _NamingContextStub.destroy() The destroy operation deletes a naming context.
void | NamingContextOperations.destroy() The destroy operation deletes a naming context.

Uses of NotEmpty in org.omg.CosNaming.NamingContextPackage

Fields in org.omg.CosNaming.NamingContextPackage declared as NotEmpty
 NotEmpty NotEmptyHolder.value

Methods in org.omg.CosNaming.NamingContextPackage that return NotEmpty
static NotEmpty | NotEmptyHelper.extract(Any a)
static NotEmpty | NotEmptyHelper.read(InputStream istream)

Methods in org.omg.CosNaming.NamingContextPackage with parameters of type NotEmpty
static void | NotEmptyHelper.insert(Any a, NotEmpty that)
static void | NotEmptyHelper.write(OutputStream ostream, NotEmpty value)

Constructors in org.omg.CosNaming.NamingContextPackage with parameters of type NotEmpty
NotEmptyHolder(NotEmpty initialValue)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.NamingContextPackage.NotEmptyHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.NamingContextPackage.NotEmptyHelper

No usage of org.omg.CosNaming.NamingContextPackage.NotEmptyHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.NamingContextPackage.NotEmptyHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.NamingContextPackage.NotEmptyHolder

No usage of org.omg.CosNaming.NamingContextPackage.NotEmptyHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.NamingContextPackage.NotFound (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.NamingContextPackage.NotFound

Packages that use NotFound
org.omg.CosNaming | Provides a naming service for Java IDL.
org.omg.CosNaming.NamingContextPackage | This package contains Exception classes for the org.omg.CosNaming package.

Uses of NotFound in org.omg.CosNaming

Methods in org.omg.CosNaming that throw NotFound
Object | _NamingContextExtStub.resolve_str(String sn) This operation resolves the Stringified name into the object reference.
void | _NamingContextExtStub.bind(NameComponent[] n, Object obj) Creates a binding of a name and an object in the naming context.
void | _NamingContextExtStub.bind_context(NameComponent[] n, NamingContext nc) Names an object that is a naming context.
void | _NamingContextExtStub.rebind(NameComponent[] n, Object obj) Creates a binding of a name and an object in the naming context even if the name is already bound in the context.
void | _NamingContextExtStub.rebind_context(NameComponent[] n, NamingContext nc) Creates a binding of a name and a naming context in the naming context even if the name is already bound in the context.
Object | _NamingContextExtStub.resolve(NameComponent[] n) The resolve operation is the process of retrieving an object bound to a name in a given context.
void | _NamingContextExtStub.unbind(NameComponent[] n) The unbind operation removes a name binding from a context.
NamingContext | _NamingContextExtStub.bind_new_context(NameComponent[] n) This operation creates a new context and binds it to the name supplied as an argument.
Object | NamingContextExtOperations.resolve_str(String sn) This operation resolves the Stringified name into the object reference.
void | _NamingContextStub.bind(NameComponent[] n, Object obj) Creates a binding of a name and an object in the naming context.
void | _NamingContextStub.bind_context(NameComponent[] n, NamingContext nc) Names an object that is a naming context.
void | _NamingContextStub.rebind(NameComponent[] n, Object obj) Creates a binding of a name and an object in the naming context even if the name is already bound in the context.
void | _NamingContextStub.rebind_context(NameComponent[] n, NamingContext nc) Creates a binding of a name and a naming context in the naming context even if the name is already bound in the context.
Object | _NamingContextStub.resolve(NameComponent[] n) The resolve operation is the process of retrieving an object bound to a name in a given context.
void | _NamingContextStub.unbind(NameComponent[] n) The unbind operation removes a name binding from a context.
NamingContext | _NamingContextStub.bind_new_context(NameComponent[] n) This operation creates a new context and binds it to the name supplied as an argument.
void | NamingContextOperations.bind(NameComponent[] n, Object obj) Creates a binding of a name and an object in the naming context.
void | NamingContextOperations.bind_context(NameComponent[] n, NamingContext nc) Names an object that is a naming context.
void | NamingContextOperations.rebind(NameComponent[] n, Object obj) Creates a binding of a name and an object in the naming context even if the name is already bound in the context.
void | NamingContextOperations.rebind_context(NameComponent[] n, NamingContext nc) Creates a binding of a name and a naming context in the naming context even if the name is already bound in the context.
Object | NamingContextOperations.resolve(NameComponent[] n) The resolve operation is the process of retrieving an object bound to a name in a given context.
void | NamingContextOperations.unbind(NameComponent[] n) The unbind operation removes a name binding from a context.
NamingContext | NamingContextOperations.bind_new_context(NameComponent[] n) This operation creates a new context and binds it to the name supplied as an argument.

Uses of NotFound in org.omg.CosNaming.NamingContextPackage

Fields in org.omg.CosNaming.NamingContextPackage declared as NotFound
 NotFound NotFoundHolder.value

Methods in org.omg.CosNaming.NamingContextPackage that return NotFound
static NotFound | NotFoundHelper.extract(Any a)
static NotFound | NotFoundHelper.read(InputStream istream)

Methods in org.omg.CosNaming.NamingContextPackage with parameters of type NotFound
static void | NotFoundHelper.insert(Any a, NotFound that)
static void | NotFoundHelper.write(OutputStream ostream, NotFound value)

Constructors in org.omg.CosNaming.NamingContextPackage with parameters of type NotFound
NotFoundHolder(NotFound initialValue)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.NamingContextPackage.NotFoundHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.NamingContextPackage.NotFoundHelper

No usage of org.omg.CosNaming.NamingContextPackage.NotFoundHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.NamingContextPackage.NotFoundHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.NamingContextPackage.NotFoundHolder

No usage of org.omg.CosNaming.NamingContextPackage.NotFoundHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.NamingContextPackage.NotFoundReason (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.NamingContextPackage.NotFoundReason

Packages that use NotFoundReason
org.omg.CosNaming.NamingContextPackage This package contains Exception classes for the org.omg.CosNaming package.

Uses of NotFoundReason in org.omg.CosNaming.NamingContextPackage

Fields in org.omg.CosNaming.NamingContextPackage declared as NotFoundReason
NotFoundReason | NotFoundReasonHolder.value
static NotFoundReason | NotFoundReason.missing_node
static NotFoundReason | NotFoundReason.not_context
static NotFoundReason | NotFoundReason.not_object
NotFoundReason | NotFound.why

Methods in org.omg.CosNaming.NamingContextPackage that return NotFoundReason
static NotFoundReason | NotFoundReasonHelper.extract(Any a)
static NotFoundReason | NotFoundReasonHelper.read(InputStream istream)
static NotFoundReason | NotFoundReason.from_int(int value)

Methods in org.omg.CosNaming.NamingContextPackage with parameters of type NotFoundReason
static void | NotFoundReasonHelper.insert(Any a, NotFoundReason that)
static void | NotFoundReasonHelper.write(OutputStream ostream, NotFoundReason value)

Constructors in org.omg.CosNaming.NamingContextPackage with parameters of type NotFoundReason
NotFoundReasonHolder(NotFoundReason initialValue)
NotFound(NotFoundReason _why, NameComponent[] _rest_of_name)
NotFound(String $reason, NotFoundReason _why, NameComponent[] _rest_of_name)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.NamingContextPackage.NotFoundReasonHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.NamingContextPackage.NotFoundReasonHelper

No usage of org.omg.CosNaming.NamingContextPackage.NotFoundReasonHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.CosNaming.NamingContextPackage.NotFoundReasonHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.CosNaming.NamingContextPackage.NotFoundReasonHolder

No usage of org.omg.CosNaming.NamingContextPackage.NotFoundReasonHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


org.omg.Dynamic (Java 2 Platform SE v1.4.2)

 org.omg.Dynamic
Classes
Parameter


org.omg.Dynamic (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

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.

See:
Description

Class Summary
Parameter NVList PIDL represented by ParameterList IDL.

Package org.omg.Dynamic Description

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. Please refer to that OMG specification for further details.

Package Specification

For a precise list of supported sections of official specifications with which the Java 2 Platform, Standard Edition, v.1.4 ORB complies, see Official Specifications for CORBA support in J2SE 1.4.

Since:
1.4
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


org.omg.Dynamic Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package org.omg.Dynamic

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class org.omg.Dynamic.Parameter (implements org.omg.CORBA.portable.IDLEntity)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package org.omg.Dynamic (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
org.omg.Dynamic

Packages that use org.omg.Dynamic
org.omg.PortableInterceptor Provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.

Classes in org.omg.Dynamic used by org.omg.PortableInterceptor
Parameter
NVList PIDL represented by ParameterList IDL.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Parameter (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.Dynamic
Class Parameter

java.lang.Object
    extended by org.omg.Dynamic.Parameter
All Implemented Interfaces:
IDLEntity, Serializable
public final class Parameter
extends Object
implements IDLEntity

NVList PIDL represented by ParameterList IDL. This exists in order to keep the Portable Interceptor IDL from becoming PIDL.

Field Summary
Any | argument
ParameterMode | mode
Constructor Summary
Parameter()
Parameter(Any _argument, ParameterMode _mode)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

argument

public Any argument

mode

public ParameterMode mode
Constructor Detail

Parameter

public Parameter()

Parameter

public Parameter(Any _argument,
                 ParameterMode _mode)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Uses of Class org.omg.Dynamic.Parameter (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.Dynamic.Parameter

Packages that use Parameter
org.omg.PortableInterceptor Provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.

Uses of Parameter in org.omg.PortableInterceptor

Methods in org.omg.PortableInterceptor that return Parameter
 Parameter[] RequestInfoOperations.arguments()
Returns an array of Parameter objects, containing the arguments on the operation being invoked.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


_DynAnyFactoryStub (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Class _DynAnyFactoryStub

java.lang.Object
    extended by org.omg.CORBA.portable.ObjectImpl
        extended by org.omg.DynamicAny._DynAnyFactoryStub
All Implemented Interfaces:
DynAnyFactory, DynAnyFactoryOperations, IDLEntity, Object, Serializable
public class _DynAnyFactoryStub
extends ObjectImpl
implements DynAnyFactory

DynAny objects can be created by invoking operations on the DynAnyFactory object. Generally there are only two ways to create a DynAny object:

  • invoking an operation on an existing DynAny object
  • invoking an operation on a DynAnyFactory object
A constructed DynAny object supports operations that enable the creation of new DynAny objects encapsulating access to the value of some constituent. DynAny objects also support the copy operation for creating new DynAny objects. A reference to the DynAnyFactory object is obtained by calling ORB.resolve_initial_references() with the identifier parameter set to the string constant "DynAnyFactory".

Dynamic interpretation of an any usually involves creating a DynAny object using create_dyn_any() as the first step. Depending on the type of the any, the resulting DynAny object reference can be narrowed to a DynFixed, DynStruct, DynSequence, DynArray, DynUnion, DynEnum, or DynValue object reference.

Dynamic creation of an any involves creating a DynAny object using create_dyn_any_from_type_code(), passing the TypeCode associated with the value to be created. The returned reference is narrowed to one of the complex types, such as DynStruct, if appropriate. Then, the value can be initialized by means of invoking operations on the resulting object. Finally, the to_any operation can be invoked to create an any value from the constructed DynAny.

Field Summary
static Class _opsClass
Constructor Summary
_DynAnyFactoryStub()
Method Summary
String[] | _ids() Retrieves a string array containing the repository identifiers supported by this ObjectImpl object.
DynAny | create_dyn_any_from_type_code(TypeCode type) Creates a DynAny from a TypeCode.
DynAny | create_dyn_any(Any value) Creates a new DynAny object from an any value.
Methods inherited from class org.omg.CORBA.portable.ObjectImpl
_create_request, _create_request, _duplicate, _get_delegate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _invoke, _is_a, _is_equivalent, _is_local, _non_existent, _orb, _release, _releaseReply, _request, _request, _servant_postinvoke, _servant_preinvoke, _set_delegate, _set_policy_override, equals, hashCode, toString
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Field Detail

_opsClass

public static final Class _opsClass
Constructor Detail

_DynAnyFactoryStub

public _DynAnyFactoryStub()
Method Detail

create_dyn_any

public DynAny create_dyn_any(Any value)
                      throws InconsistentTypeCode
Creates a new DynAny object from an any value. A copy of the TypeCode associated with the any value is assigned to the resulting DynAny object. The value associated with the DynAny object is a copy of the value in the original any. The current position of the created DynAny is set to zero if the passed value has components, to -1 otherwise

Specified by:
create_dyn_any in interface DynAnyFactoryOperations
Throws:
InconsistentTypeCode - if value has a TypeCode with a TCKind of tk_Principal, tk_native, or tk_abstract_interface

create_dyn_any_from_type_code

public DynAny create_dyn_any_from_type_code(TypeCode type)
                                     throws InconsistentTypeCode
Creates a DynAny from a TypeCode. Depending on the TypeCode, the created object may be of type DynAny, or one of its derived types, such as DynStruct. The returned reference can be narrowed to the derived type. In all cases, a DynAny constructed from a TypeCode has an initial default value. The default values of basic types are:
  • false for boolean
  • zero for numeric types
  • zero for types octet, char, and wchar
  • the empty string for string and wstring
  • null for object references
  • a type code with a TCKind value of tk_null for type codes
  • for any values, an any containing a type code with a TCKind value of tk_null type and no value
For complex types, creation of the corresponding DynAny assigns a default value as follows:
  • For DynSequence it sets the current position to -1 and creates an empty sequence.
  • For DynEnum it sets the current position to -1 and sets the value of the enumerator to the first enumerator value indicated by the TypeCode.
  • For DynFixed it sets the current position to -1 and sets the value zero.
  • For DynStruct it sets the current position to -1 for empty exceptions and to zero for all other TypeCodes. The members (if any) are (recursively) initialized to their default values.
  • For DynArray sets the current position to zero and (recursively) initializes elements to their default value.
  • For DynUnion sets the current position to zero. The discriminator value is set to a value consistent with the first named member of the union. That member is activated and (recursively) initialized to its default value.
  • For DynValue and DynValueBox it initializes to a null value.

Specified by:
create_dyn_any_from_type_code in interface DynAnyFactoryOperations
Throws:
InconsistentTypeCode

_ids

public String[] _ids()
Description copied from class: ObjectImpl
Retrieves a string array containing the repository identifiers supported by this ObjectImpl object. For example, for a stub, this method returns information about all the interfaces supported by the stub.

Specified by:
_ids in class ObjectImpl
Returns:
the array of all repository identifiers supported by this ObjectImpl instance
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


_DynAnyStub (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Class _DynAnyStub

java.lang.Object
    extended by org.omg.CORBA.portable.ObjectImpl
        extended by org.omg.DynamicAny._DynAnyStub
All Implemented Interfaces:
DynAny, DynAnyOperations, IDLEntity, Object, Serializable
public class _DynAnyStub
extends ObjectImpl
implements DynAny

Any values can be dynamically interpreted (traversed) and constructed through DynAny objects. A DynAny object is associated with a data value which corresponds to a copy of the value inserted into an any.

A DynAny object may be viewed as an ordered collection of component DynAnys. For DynAnys representing a basic type, such as long, or a type without components, such as an empty exception, the ordered collection of components is empty. Each DynAny object maintains the notion of a current position into its collection of component DynAnys. The current position is identified by an index value that runs from 0 to n-1, where n is the number of components. The special index value -1 indicates a current position that points nowhere. For values that cannot have a current position (such as an empty exception), the index value is fixed at -1. If a DynAny is initialized with a value that has components, the index is initialized to 0. After creation of an uninitialized DynAny (that is, a DynAny that has no value but a TypeCode that permits components), the current position depends on the type of value represented by the DynAny. (The current position is set to 0 or -1, depending on whether the new DynAny gets default values for its components.)

The iteration operations rewind, seek, and next can be used to change the current position and the current_component operation returns the component at the current position. The component_count operation returns the number of components of a DynAny. Collectively, these operations enable iteration over the components of a DynAny, for example, to (recursively) examine its contents.

A constructed DynAny object is a DynAny object associated with a constructed type. There is a different interface, inheriting from the DynAny interface, associated with each kind of constructed type in IDL (fixed, enum, struct, sequence, union, array, exception, and value type).

A constructed DynAny object exports operations that enable the creation of new DynAny objects, each of them associated with a component of the constructed data value. As an example, a DynStruct is associated with a struct value. This means that the DynStruct may be seen as owning an ordered collection of components, one for each structure member. The DynStruct object exports operations that enable the creation of new DynAny objects, each of them associated with a member of the struct.

If a DynAny object has been obtained from another (constructed) DynAny object, such as a DynAny representing a structure member that was created from a DynStruct, the member DynAny is logically contained in the DynStruct. Calling an insert or get operation leaves the current position unchanged. Destroying a top-level DynAny object (one that was not obtained as a component of another DynAny) also destroys any component DynAny objects obtained from it. Destroying a non-top level DynAny object does nothing. Invoking operations on a destroyed top-level DynAny or any of its descendants raises OBJECT_NOT_EXIST. If the programmer wants to destroy a DynAny object but still wants to manipulate some component of the data value associated with it, then he or she should first create a DynAny for the component and, after that, make a copy of the created DynAny object.

The behavior of DynAny objects has been defined in order to enable efficient implementations in terms of allocated memory space and speed of access. DynAny objects are intended to be used for traversing values extracted from anys or constructing values of anys at runtime. Their use for other purposes is not recommended.

Insert and get operations are necessary to handle basic DynAny objects but are also helpful to handle constructed DynAny objects. Inserting a basic data type value into a constructed DynAny object implies initializing the current component of the constructed data value associated with the DynAny object. For example, invoking insert_boolean on a DynStruct implies inserting a boolean data value at the current position of the associated struct data value. A type is consistent for inserting or extracting a value if its TypeCode is equivalent to the TypeCode contained in the DynAny or, if the DynAny has components, is equivalent to the TypeCode of the DynAny at the current position.

DynAny and DynAnyFactory objects are intended to be local to the process in which they are created and used. This means that references to DynAny and DynAnyFactory objects cannot be exported to other processes, or externalized with ORB.object_to_string(). If any attempt is made to do so, the offending operation will raise a MARSHAL system exception. Since their interfaces are specified in IDL, DynAny objects export operations defined in the standard org.omg.CORBA.Object interface. However, any attempt to invoke operations exported through the Object interface may raise the standard NO_IMPLEMENT exception. An attempt to use a DynAny object with the DII may raise the NO_IMPLEMENT exception.

Field Summary
static Class _opsClass
Constructor Summary
_DynAnyStub()
Method Summary
 String[] _ids()
Retrieves a string array containing the repository identifiers supported by this ObjectImpl object.
 void assign(DynAny dyn_any)
Initializes the value associated with a DynAny object with the value associated with another DynAny object.
 int component_count()
Returns the number of components of a DynAny.
 DynAny copy()
Creates a new DynAny object whose value is a deep copy of the DynAny on which it is invoked.
 DynAny current_component()
Returns the DynAny for the component at the current position.
 void destroy()
Destroys a DynAny object.
 boolean equal(DynAny dyn_any)
Compares two DynAny values for equality.
 void from_any(Any value)
Initializes the value associated with a DynAny object with the value contained in an any.
 Any get_any()
Extracts an Any value contained in the Any represented by this DynAny.
 boolean get_boolean()
Extracts the boolean value from this DynAny.
 char get_char()
Extracts the char value from this DynAny.
 double get_double()
Extracts the double value from this DynAny.
 DynAny get_dyn_any()
Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.
 float get_float()
Extracts the float value from this DynAny.
 int get_long()
Extracts the integer value from this DynAny.
 long get_longlong()
Extracts the long value from this DynAny.
 byte get_octet()
Extracts the byte value from this DynAny.
 Object get_reference()
Extracts the reference to a CORBA Object from this DynAny.
 short get_short()
Extracts the short value from this DynAny.
 String get_string()
Extracts the string value from this DynAny.
 TypeCode get_typecode()
Extracts the TypeCode object from this DynAny.
 int get_ulong()
Extracts the integer value from this DynAny.
 long get_ulonglong()
Extracts the long value from this DynAny.
 short get_ushort()
Extracts the short value from this DynAny.
 Serializable get_val()
Extracts a Serializable object from this DynAny.
 char get_wchar()
Extracts the long value from this DynAny.
 String get_wstring()
Extracts the string value from this DynAny.
 void insert_any(Any value)
Inserts an Any value into the Any represented by this DynAny.
 void insert_boolean(boolean value)
Inserts a boolean value into the DynAny.
 void insert_char(char value)
Inserts a char value into the DynAny.
 void insert_double(double value)
Inserts a double value into the DynAny.
 void insert_dyn_any(DynAny value)
Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.
 void insert_float(float value)
Inserts a float value into the DynAny.
 void insert_long(int value)
Inserts an integer value into the DynAny.
 void insert_longlong(long value)
Inserts a long value into the DynAny.
 void insert_octet(byte value)
Inserts a byte value into the DynAny.
 void insert_reference(Object value)
Inserts a reference to a CORBA object into the DynAny.
 void insert_short(short value)
Inserts a short value into the DynAny.
 void insert_string(String value)
Inserts a string value into the DynAny.
 void insert_typecode(TypeCode value)
Inserts a TypeCode object into the DynAny.
 void insert_ulong(int value)
Inserts an integer value into the DynAny.
 void insert_ulonglong(long value)
Inserts a long value into the DynAny.
 void insert_ushort(short value)
Inserts a short value into the DynAny.
 void insert_val(Serializable value)
Inserts a reference to a Serializable object into this DynAny.
 void insert_wchar(char value)
Inserts a char value into the DynAny.
 void insert_wstring(String value)
Inserts a string value into the DynAny.
 boolean next()
Advances the current position to the next component.
 void rewind()
Is equivalent to seek(0).
 boolean seek(int index)
Sets the current position to index.
 Any to_any()
Creates an any value from a DynAny object.
 TypeCode type()
Returns the TypeCode associated with this DynAny object.
Methods inherited from class org.omg.CORBA.portable.ObjectImpl
_create_request, _create_request, _duplicate, _get_delegate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _invoke, _is_a, _is_equivalent, _is_local, _non_existent, _orb, _release, _releaseReply, _request, _request, _servant_postinvoke, _servant_preinvoke, _set_delegate, _set_policy_override, equals, hashCode, toString
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Field Detail

_opsClass

public static final Class _opsClass
Constructor Detail

_DynAnyStub

public _DynAnyStub()
Method Detail

type

public TypeCode type()
Returns the TypeCode associated with this DynAny object. A DynAny object is created with a TypeCode value assigned to it. This TypeCode value determines the type of the value handled through the DynAny object. Note that the TypeCode associated with a DynAny object is initialized at the time the DynAny is created and cannot be changed during lifetime of the DynAny object.

Specified by:
type in interface DynAnyOperations
Returns:
The TypeCode associated with this DynAny object

assign

public void assign(DynAny dyn_any)
            throws TypeMismatch
Initializes the value associated with a DynAny object with the value associated with another DynAny object. The current position of the target DynAny is set to zero for values that have components and to -1 for values that do not have components.

Specified by:
assign in interface DynAnyOperations
Parameters:
dyn_any -
Throws:
TypeMismatch - if the type of the passed DynAny is not equivalent to the type of target DynAny

from_any

public void from_any(Any value)
              throws TypeMismatch,
                     InvalidValue
Initializes the value associated with a DynAny object with the value contained in an any. The current position of the target DynAny is set to zero for values that have components and to -1 for values that do not have components.

Specified by:
from_any in interface DynAnyOperations
Throws:
TypeMismatch - if the type of the passed Any is not equivalent to the type of target DynAny
InvalidValue - if the passed Any does not contain a legal value (such as a null string)

to_any

public Any to_any()
Creates an any value from a DynAny object. A copy of the TypeCode associated with the DynAny object is assigned to the resulting any. The value associated with the DynAny object is copied into the any.

Specified by:
to_any in interface DynAnyOperations
Returns:
a new Any object with the same value and TypeCode

equal

public boolean equal(DynAny dyn_any)
Compares two DynAny values for equality. Two DynAny values are equal if their TypeCodes are equivalent and, recursively, all component DynAnys have equal values. The current position of the two DynAnys being compared has no effect on the result of equal.

Specified by:
equal in interface DynAnyOperations
Returns:
true of the DynAnys are equal, false otherwise

destroy

public void destroy()
Destroys a DynAny object. This operation frees any resources used to represent the data value associated with a DynAny object. It must be invoked on references obtained from one of the creation operations on the ORB interface or on a reference returned by DynAny.copy() to avoid resource leaks. Invoking destroy on component DynAny objects (for example, on objects returned by the current_component operation) does nothing. Destruction of a DynAny object implies destruction of all DynAny objects obtained from it. That is, references to components of a destroyed DynAny become invalid. Invocations on such references raise OBJECT_NOT_EXIST. It is possible to manipulate a component of a DynAny beyond the life time of the DynAny from which the component was obtained by making a copy of the component with the copy operation before destroying the DynAny from which the component was obtained.

Specified by:
destroy in interface DynAnyOperations

copy

public DynAny copy()
Creates a new DynAny object whose value is a deep copy of the DynAny on which it is invoked. The operation is polymorphic, that is, invoking it on one of the types derived from DynAny, such as DynStruct, creates the derived type but returns its reference as the DynAny base type.

Specified by:
copy in interface DynAnyOperations
Returns:
a deep copy of the DynAny object

insert_boolean

public void insert_boolean(boolean value)
                    throws TypeMismatch,
                           InvalidValue
Inserts a boolean value into the DynAny.

Specified by:
insert_boolean in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_octet

public void insert_octet(byte value)
                  throws TypeMismatch,
                         InvalidValue
Inserts a byte value into the DynAny. The IDL octet data type is mapped to the Java byte data type.

Specified by:
insert_octet in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_char

public void insert_char(char value)
                 throws TypeMismatch,
                        InvalidValue
Inserts a char value into the DynAny.

Specified by:
insert_char in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_short

public void insert_short(short value)
                  throws TypeMismatch,
                         InvalidValue
Inserts a short value into the DynAny.

Specified by:
insert_short in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_ushort

public void insert_ushort(short value)
                   throws TypeMismatch,
                          InvalidValue
Inserts a short value into the DynAny. The IDL ushort data type is mapped to the Java short data type.

Specified by:
insert_ushort in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_long

public void insert_long(int value)
                 throws TypeMismatch,
                        InvalidValue
Inserts an integer value into the DynAny. The IDL long data type is mapped to the Java int data type.

Specified by:
insert_long in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_ulong

public void insert_ulong(int value)
                  throws TypeMismatch,
                         InvalidValue
Inserts an integer value into the DynAny. The IDL ulong data type is mapped to the Java int data type.

Specified by:
insert_ulong in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_float

public void insert_float(float value)
                  throws TypeMismatch,
                         InvalidValue
Inserts a float value into the DynAny.

Specified by:
insert_float in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_double

public void insert_double(double value)
                   throws TypeMismatch,
                          InvalidValue
Inserts a double value into the DynAny.

Specified by:
insert_double in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_string

public void insert_string(String value)
                   throws TypeMismatch,
                          InvalidValue
Inserts a string value into the DynAny. Both bounded and unbounded strings are inserted using this method.

Specified by:
insert_string in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
InvalidValue - if the string inserted is longer than the bound of a bounded string
TypeMismatch - if called on a DynAny whose current component itself has components

insert_reference

public void insert_reference(Object value)
                      throws TypeMismatch,
                             InvalidValue
Inserts a reference to a CORBA object into the DynAny.

Specified by:
insert_reference in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_typecode

public void insert_typecode(TypeCode value)
                     throws TypeMismatch,
                            InvalidValue
Inserts a TypeCode object into the DynAny.

Specified by:
insert_typecode in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_longlong

public void insert_longlong(long value)
                     throws TypeMismatch,
                            InvalidValue
Inserts a long value into the DynAny. The IDL long long data type is mapped to the Java long data type.

Specified by:
insert_longlong in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_ulonglong

public void insert_ulonglong(long value)
                      throws TypeMismatch,
                             InvalidValue
Inserts a long value into the DynAny. The IDL unsigned long long data type is mapped to the Java long data type.

Specified by:
insert_ulonglong in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_wchar

public void insert_wchar(char value)
                  throws TypeMismatch,
                         InvalidValue
Inserts a char value into the DynAny. The IDL wchar data type is mapped to the Java char data type.

Specified by:
insert_wchar in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_wstring

public void insert_wstring(String value)
                    throws TypeMismatch,
                           InvalidValue
Inserts a string value into the DynAny. Both bounded and unbounded strings are inserted using this method.

Specified by:
insert_wstring in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
InvalidValue - if the string inserted is longer than the bound of a bounded string
TypeMismatch

insert_any

public void insert_any(Any value)
                throws TypeMismatch,
                       InvalidValue
Inserts an Any value into the Any represented by this DynAny.

Specified by:
insert_any in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_dyn_any

public void insert_dyn_any(DynAny value)
                    throws TypeMismatch,
                           InvalidValue
Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.

Specified by:
insert_dyn_any in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_val

public void insert_val(Serializable value)
                throws TypeMismatch,
                       InvalidValue
Inserts a reference to a Serializable object into this DynAny. The IDL ValueBase type is mapped to the Java Serializable type.

Specified by:
insert_val in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

get_boolean

public boolean get_boolean()
                    throws TypeMismatch,
                           InvalidValue
Extracts the boolean value from this DynAny.

Specified by:
get_boolean in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_octet

public byte get_octet()
               throws TypeMismatch,
                      InvalidValue
Extracts the byte value from this DynAny. The IDL octet data type is mapped to the Java byte data type.

Specified by:
get_octet in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_char

public char get_char()
              throws TypeMismatch,
                     InvalidValue
Extracts the char value from this DynAny.

Specified by:
get_char in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_short

public short get_short()
                throws TypeMismatch,
                       InvalidValue
Extracts the short value from this DynAny.

Specified by:
get_short in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_ushort

public short get_ushort()
                 throws TypeMismatch,
                        InvalidValue
Extracts the short value from this DynAny. The IDL ushort data type is mapped to the Java short data type.

Specified by:
get_ushort in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_long

public int get_long()
             throws TypeMismatch,
                    InvalidValue
Extracts the integer value from this DynAny. The IDL long data type is mapped to the Java int data type.

Specified by:
get_long in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_ulong

public int get_ulong()
              throws TypeMismatch,
                     InvalidValue
Extracts the integer value from this DynAny. The IDL ulong data type is mapped to the Java int data type.

Specified by:
get_ulong in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_float

public float get_float()
                throws TypeMismatch,
                       InvalidValue
Extracts the float value from this DynAny.

Specified by:
get_float in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_double

public double get_double()
                  throws TypeMismatch,
                         InvalidValue
Extracts the double value from this DynAny.

Specified by:
get_double in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_string

public String get_string()
                  throws TypeMismatch,
                         InvalidValue
Extracts the string value from this DynAny. Both bounded and unbounded strings are extracted using this method.

Specified by:
get_string in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_reference

public Object get_reference()
                     throws TypeMismatch,
                            InvalidValue
Extracts the reference to a CORBA Object from this DynAny.

Specified by:
get_reference in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_typecode

public TypeCode get_typecode()
                      throws TypeMismatch,
                             InvalidValue
Extracts the TypeCode object from this DynAny.

Specified by:
get_typecode in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_longlong

public long get_longlong()
                  throws TypeMismatch,
                         InvalidValue
Extracts the long value from this DynAny. The IDL long long data type is mapped to the Java long data type.

Specified by:
get_longlong in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_ulonglong

public long get_ulonglong()
                   throws TypeMismatch,
                          InvalidValue
Extracts the long value from this DynAny. The IDL unsigned long long data type is mapped to the Java long data type.

Specified by:
get_ulonglong in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_wchar

public char get_wchar()
               throws TypeMismatch,
                      InvalidValue
Extracts the long value from this DynAny. The IDL wchar data type is mapped to the Java char data type.

Specified by:
get_wchar in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_wstring

public String get_wstring()
                   throws TypeMismatch,
                          InvalidValue
Extracts the string value from this DynAny. Both bounded and unbounded strings are extracted using this method.

Specified by:
get_wstring in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue

get_any

public Any get_any()
            throws TypeMismatch,
                   InvalidValue
Extracts an Any value contained in the Any represented by this DynAny.

Specified by:
get_any in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_dyn_any

public DynAny get_dyn_any()
                   throws TypeMismatch,
                          InvalidValue
Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.

Specified by:
get_dyn_any in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_val

public Serializable get_val()
                     throws TypeMismatch,
                            InvalidValue
Extracts a Serializable object from this DynAny. The IDL ValueBase type is mapped to the Java Serializable type.

Specified by:
get_val in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

seek

public boolean seek(int index)
Sets the current position to index. The current position is indexed 0 to n-1, that is, index zero corresponds to the first component. The operation returns true if the resulting current position indicates a component of the DynAny and false if index indicates a position that does not correspond to a component. Calling seek with a negative index is legal. It sets the current position to -1 to indicate no component and returns false. Passing a non-negative index value for a DynAny that does not have a component at the corresponding position sets the current position to -1 and returns false.

Specified by:
seek in interface DynAnyOperations

rewind

public void rewind()
Is equivalent to seek(0).

Specified by:
rewind in interface DynAnyOperations

next

public boolean next()
Advances the current position to the next component. The operation returns true while the resulting current position indicates a component, false otherwise. A false return value leaves the current position at -1. Invoking next on a DynAny without components leaves the current position at -1 and returns false.

Specified by:
next in interface DynAnyOperations

component_count

public int component_count()
Returns the number of components of a DynAny. For a DynAny without components, it returns zero. The operation only counts the components at the top level. For example, if component_count is invoked on a DynStruct with a single member, the return value is 1, irrespective of the type of the member.
  • For sequences, the operation returns the current number of elements.
  • For structures, exceptions, and value types, the operation returns the number of members.
  • For arrays, the operation returns the number of elements.
  • For unions, the operation returns 2 if the discriminator indicates that a named member is active, otherwise, it returns 1.
  • For DynFixed and DynEnum, the operation returns zero.

Specified by:
component_count in interface DynAnyOperations

current_component

public DynAny current_component()
                         throws TypeMismatch
Returns the DynAny for the component at the current position. It does not advance the current position, so repeated calls to current_component without an intervening call to rewind, next, or seek return the same component. The returned DynAny object reference can be used to get/set the value of the current component. If the current component represents a complex type, the returned reference can be narrowed based on the TypeCode to get the interface corresponding to the to the complex type. Calling current_component on a DynAny that cannot have components, such as a DynEnum or an empty exception, raises TypeMismatch. Calling current_component on a DynAny whose current position is -1 returns a nil reference. The iteration operations, together with current_component, can be used to dynamically compose an any value. After creating a dynamic any, such as a DynStruct, current_component and next can be used to initialize all the components of the value. Once the dynamic value is completely initialized, to_any creates the corresponding any value.

Specified by:
current_component in interface DynAnyOperations
Throws:
TypeMismatch - If called on a DynAny that cannot have components, such as a DynEnum or an empty exception

_ids

public String[] _ids()
Description copied from class: ObjectImpl
Retrieves a string array containing the repository identifiers supported by this ObjectImpl object. For example, for a stub, this method returns information about all the interfaces supported by the stub.

Specified by:
_ids in class ObjectImpl
Returns:
the array of all repository identifiers supported by this ObjectImpl instance
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


_DynArrayStub (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Class _DynArrayStub

java.lang.Object
    extended by org.omg.CORBA.portable.ObjectImpl
        extended by org.omg.DynamicAny._DynArrayStub
All Implemented Interfaces:
DynAny, DynAnyOperations, DynArray, DynArrayOperations, IDLEntity, Object, Serializable
public class _DynArrayStub
extends ObjectImpl
implements DynArray

DynArray objects support the manipulation of IDL arrays. Note that the dimension of the array is contained in the TypeCode which is accessible through the type attribute. It can also be obtained by calling the component_count operation.

Field Summary
static Class _opsClass
Constructor Summary
_DynArrayStub()
Method Summary
 String[] _ids()
Retrieves a string array containing the repository identifiers supported by this ObjectImpl object.
 void assign(DynAny dyn_any)
Initializes the value associated with a DynAny object with the value associated with another DynAny object.
 int component_count()
Returns the number of components of a DynAny.
 DynAny copy()
Creates a new DynAny object whose value is a deep copy of the DynAny on which it is invoked.
 DynAny current_component()
Returns the DynAny for the component at the current position.
 void destroy()
Destroys a DynAny object.
 boolean equal(DynAny dyn_any)
Compares two DynAny values for equality.
 void from_any(Any value)
Initializes the value associated with a DynAny object with the value contained in an any.
 Any get_any()
Extracts an Any value contained in the Any represented by this DynAny.
 boolean get_boolean()
Extracts the boolean value from this DynAny.
 char get_char()
Extracts the char value from this DynAny.
 double get_double()
Extracts the double value from this DynAny.
 DynAny get_dyn_any()
Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.
 DynAny[] get_elements_as_dyn_any()
Returns the elements of the DynArray as DynAnys.
 Any[] get_elements()
Returns the elements of the DynArray.
 float get_float()
Extracts the float value from this DynAny.
 int get_long()
Extracts the integer value from this DynAny.
 long get_longlong()
Extracts the long value from this DynAny.
 byte get_octet()
Extracts the byte value from this DynAny.
 Object get_reference()
Extracts the reference to a CORBA Object from this DynAny.
 short get_short()
Extracts the short value from this DynAny.
 String get_string()
Extracts the string value from this DynAny.
 TypeCode get_typecode()
Extracts the TypeCode object from this DynAny.
 int get_ulong()
Extracts the integer value from this DynAny.
 long get_ulonglong()
Extracts the long value from this DynAny.
 short get_ushort()
Extracts the short value from this DynAny.
 Serializable get_val()
Extracts a Serializable object from this DynAny.
 char get_wchar()
Extracts the long value from this DynAny.
 String get_wstring()
Extracts the string value from this DynAny.
 void insert_any(Any value)
Inserts an Any value into the Any represented by this DynAny.
 void insert_boolean(boolean value)
Inserts a boolean value into the DynAny.
 void insert_char(char value)
Inserts a char value into the DynAny.
 void insert_double(double value)
Inserts a double value into the DynAny.
 void insert_dyn_any(DynAny value)
Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.
 void insert_float(float value)
Inserts a float value into the DynAny.
 void insert_long(int value)
Inserts an integer value into the DynAny.
 void insert_longlong(long value)
Inserts a long value into the DynAny.
 void insert_octet(byte value)
Inserts a byte value into the DynAny.
 void insert_reference(Object value)
Inserts a reference to a CORBA object into the DynAny.
 void insert_short(short value)
Inserts a short value into the DynAny.
 void insert_string(String value)
Inserts a string value into the DynAny.
 void insert_typecode(TypeCode value)
Inserts a TypeCode object into the DynAny.
 void insert_ulong(int value)
Inserts an integer value into the DynAny.
 void insert_ulonglong(long value)
Inserts a long value into the DynAny.
 void insert_ushort(short value)
Inserts a short value into the DynAny.
 void insert_val(Serializable value)
Inserts a reference to a Serializable object into this DynAny.
 void insert_wchar(char value)
Inserts a char value into the DynAny.
 void insert_wstring(String value)
Inserts a string value into the DynAny.
 boolean next()
Advances the current position to the next component.
 void rewind()
Is equivalent to seek(0).
 boolean seek(int index)
Sets the current position to index.
 void set_elements_as_dyn_any(DynAny[] value)
Sets the DynArray to contain the passed elements.
 void set_elements(Any[] value)
Sets the DynArray to contain the passed elements.
 Any to_any()
Creates an any value from a DynAny object.
 TypeCode type()
Returns the TypeCode associated with this DynAny object.
Methods inherited from class org.omg.CORBA.portable.ObjectImpl
_create_request, _create_request, _duplicate, _get_delegate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _invoke, _is_a, _is_equivalent, _is_local, _non_existent, _orb, _release, _releaseReply, _request, _request, _servant_postinvoke, _servant_preinvoke, _set_delegate, _set_policy_override, equals, hashCode, toString
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Field Detail

_opsClass

public static final Class _opsClass
Constructor Detail

_DynArrayStub

public _DynArrayStub()
Method Detail

get_elements

public Any[] get_elements()
Returns the elements of the DynArray.

Specified by:
get_elements in interface DynArrayOperations

set_elements

public void set_elements(Any[] value)
                  throws TypeMismatch,
                         InvalidValue
Sets the DynArray to contain the passed elements.

Specified by:
set_elements in interface DynArrayOperations
Throws:
TypeMismatch - if one or more elements have a type that is inconsistent with the DynArrays TypeCode
InvalidValue - if the sequence does not contain the same number of elements as the array dimension

get_elements_as_dyn_any

public DynAny[] get_elements_as_dyn_any()
Returns the elements of the DynArray as DynAnys.

Specified by:
get_elements_as_dyn_any in interface DynArrayOperations

set_elements_as_dyn_any

public void set_elements_as_dyn_any(DynAny[] value)
                             throws TypeMismatch,
                                    InvalidValue
Sets the DynArray to contain the passed elements.

Specified by:
set_elements_as_dyn_any in interface DynArrayOperations
Throws:
TypeMismatch - if one or more elements have a type that is inconsistent with the DynArrays TypeCode
InvalidValue - if the sequence does not contain the same number of elements as the array dimension

type

public TypeCode type()
Returns the TypeCode associated with this DynAny object. A DynAny object is created with a TypeCode value assigned to it. This TypeCode value determines the type of the value handled through the DynAny object. Note that the TypeCode associated with a DynAny object is initialized at the time the DynAny is created and cannot be changed during lifetime of the DynAny object.

Specified by:
type in interface DynAnyOperations
Returns:
The TypeCode associated with this DynAny object

assign

public void assign(DynAny dyn_any)
            throws TypeMismatch
Initializes the value associated with a DynAny object with the value associated with another DynAny object. The current position of the target DynAny is set to zero for values that have components and to -1 for values that do not have components.

Specified by:
assign in interface DynAnyOperations
Parameters:
dyn_any -
Throws:
TypeMismatch - if the type of the passed DynAny is not equivalent to the type of target DynAny

from_any

public void from_any(Any value)
              throws TypeMismatch,
                     InvalidValue
Initializes the value associated with a DynAny object with the value contained in an any. The current position of the target DynAny is set to zero for values that have components and to -1 for values that do not have components.

Specified by:
from_any in interface DynAnyOperations
Throws:
TypeMismatch - if the type of the passed Any is not equivalent to the type of target DynAny
InvalidValue - if the passed Any does not contain a legal value (such as a null string)

to_any

public Any to_any()
Creates an any value from a DynAny object. A copy of the TypeCode associated with the DynAny object is assigned to the resulting any. The value associated with the DynAny object is copied into the any.

Specified by:
to_any in interface DynAnyOperations
Returns:
a new Any object with the same value and TypeCode

equal

public boolean equal(DynAny dyn_any)
Compares two DynAny values for equality. Two DynAny values are equal if their TypeCodes are equivalent and, recursively, all component DynAnys have equal values. The current position of the two DynAnys being compared has no effect on the result of equal.

Specified by:
equal in interface DynAnyOperations
Returns:
true of the DynAnys are equal, false otherwise

destroy

public void destroy()
Destroys a DynAny object. This operation frees any resources used to represent the data value associated with a DynAny object. It must be invoked on references obtained from one of the creation operations on the ORB interface or on a reference returned by DynAny.copy() to avoid resource leaks. Invoking destroy on component DynAny objects (for example, on objects returned by the current_component operation) does nothing. Destruction of a DynAny object implies destruction of all DynAny objects obtained from it. That is, references to components of a destroyed DynAny become invalid. Invocations on such references raise OBJECT_NOT_EXIST. It is possible to manipulate a component of a DynAny beyond the life time of the DynAny from which the component was obtained by making a copy of the component with the copy operation before destroying the DynAny from which the component was obtained.

Specified by:
destroy in interface DynAnyOperations

copy

public DynAny copy()
Creates a new DynAny object whose value is a deep copy of the DynAny on which it is invoked. The operation is polymorphic, that is, invoking it on one of the types derived from DynAny, such as DynStruct, creates the derived type but returns its reference as the DynAny base type.

Specified by:
copy in interface DynAnyOperations
Returns:
a deep copy of the DynAny object

insert_boolean

public void insert_boolean(boolean value)
                    throws TypeMismatch,
                           InvalidValue
Inserts a boolean value into the DynAny.

Specified by:
insert_boolean in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_octet

public void insert_octet(byte value)
                  throws TypeMismatch,
                         InvalidValue
Inserts a byte value into the DynAny. The IDL octet data type is mapped to the Java byte data type.

Specified by:
insert_octet in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_char

public void insert_char(char value)
                 throws TypeMismatch,
                        InvalidValue
Inserts a char value into the DynAny.

Specified by:
insert_char in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_short

public void insert_short(short value)
                  throws TypeMismatch,
                         InvalidValue
Inserts a short value into the DynAny.

Specified by:
insert_short in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_ushort

public void insert_ushort(short value)
                   throws TypeMismatch,
                          InvalidValue
Inserts a short value into the DynAny. The IDL ushort data type is mapped to the Java short data type.

Specified by:
insert_ushort in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_long

public void insert_long(int value)
                 throws TypeMismatch,
                        InvalidValue
Inserts an integer value into the DynAny. The IDL long data type is mapped to the Java int data type.

Specified by:
insert_long in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_ulong

public void insert_ulong(int value)
                  throws TypeMismatch,
                         InvalidValue
Inserts an integer value into the DynAny. The IDL ulong data type is mapped to the Java int data type.

Specified by:
insert_ulong in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_float

public void insert_float(float value)
                  throws TypeMismatch,
                         InvalidValue
Inserts a float value into the DynAny.

Specified by:
insert_float in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_double

public void insert_double(double value)
                   throws TypeMismatch,
                          InvalidValue
Inserts a double value into the DynAny.

Specified by:
insert_double in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_string

public void insert_string(String value)
                   throws TypeMismatch,
                          InvalidValue
Inserts a string value into the DynAny. Both bounded and unbounded strings are inserted using this method.

Specified by:
insert_string in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
InvalidValue - if the string inserted is longer than the bound of a bounded string
TypeMismatch - if called on a DynAny whose current component itself has components

insert_reference

public void insert_reference(Object value)
                      throws TypeMismatch,
                             InvalidValue
Inserts a reference to a CORBA object into the DynAny.

Specified by:
insert_reference in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_typecode

public void insert_typecode(TypeCode value)
                     throws TypeMismatch,
                            InvalidValue
Inserts a TypeCode object into the DynAny.

Specified by:
insert_typecode in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_longlong

public void insert_longlong(long value)
                     throws TypeMismatch,
                            InvalidValue
Inserts a long value into the DynAny. The IDL long long data type is mapped to the Java long data type.

Specified by:
insert_longlong in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_ulonglong

public void insert_ulonglong(long value)
                      throws TypeMismatch,
                             InvalidValue
Inserts a long value into the DynAny. The IDL unsigned long long data type is mapped to the Java long data type.

Specified by:
insert_ulonglong in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_wchar

public void insert_wchar(char value)
                  throws TypeMismatch,
                         InvalidValue
Inserts a char value into the DynAny. The IDL wchar data type is mapped to the Java char data type.

Specified by:
insert_wchar in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_wstring

public void insert_wstring(String value)
                    throws TypeMismatch,
                           InvalidValue
Inserts a string value into the DynAny. Both bounded and unbounded strings are inserted using this method.

Specified by:
insert_wstring in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
InvalidValue - if the string inserted is longer than the bound of a bounded string
TypeMismatch

insert_any

public void insert_any(Any value)
                throws TypeMismatch,
                       InvalidValue
Inserts an Any value into the Any represented by this DynAny.

Specified by:
insert_any in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_dyn_any

public void insert_dyn_any(DynAny value)
                    throws TypeMismatch,
                           InvalidValue
Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.

Specified by:
insert_dyn_any in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_val

public void insert_val(Serializable value)
                throws TypeMismatch,
                       InvalidValue
Inserts a reference to a Serializable object into this DynAny. The IDL ValueBase type is mapped to the Java Serializable type.

Specified by:
insert_val in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

get_boolean

public boolean get_boolean()
                    throws TypeMismatch,
                           InvalidValue
Extracts the boolean value from this DynAny.

Specified by:
get_boolean in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_octet

public byte get_octet()
               throws TypeMismatch,
                      InvalidValue
Extracts the byte value from this DynAny. The IDL octet data type is mapped to the Java byte data type.

Specified by:
get_octet in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_char

public char get_char()
              throws TypeMismatch,
                     InvalidValue
Extracts the char value from this DynAny.

Specified by:
get_char in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_short

public short get_short()
                throws TypeMismatch,
                       InvalidValue
Extracts the short value from this DynAny.

Specified by:
get_short in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_ushort

public short get_ushort()
                 throws TypeMismatch,
                        InvalidValue
Extracts the short value from this DynAny. The IDL ushort data type is mapped to the Java short data type.

Specified by:
get_ushort in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_long

public int get_long()
             throws TypeMismatch,
                    InvalidValue
Extracts the integer value from this DynAny. The IDL long data type is mapped to the Java int data type.

Specified by:
get_long in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_ulong

public int get_ulong()
              throws TypeMismatch,
                     InvalidValue
Extracts the integer value from this DynAny. The IDL ulong data type is mapped to the Java int data type.

Specified by:
get_ulong in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_float

public float get_float()
                throws TypeMismatch,
                       InvalidValue
Extracts the float value from this DynAny.

Specified by:
get_float in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_double

public double get_double()
                  throws TypeMismatch,
                         InvalidValue
Extracts the double value from this DynAny.

Specified by:
get_double in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_string

public String get_string()
                  throws TypeMismatch,
                         InvalidValue
Extracts the string value from this DynAny. Both bounded and unbounded strings are extracted using this method.

Specified by:
get_string in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_reference

public Object get_reference()
                     throws TypeMismatch,
                            InvalidValue
Extracts the reference to a CORBA Object from this DynAny.

Specified by:
get_reference in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_typecode

public TypeCode get_typecode()
                      throws TypeMismatch,
                             InvalidValue
Extracts the TypeCode object from this DynAny.

Specified by:
get_typecode in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_longlong

public long get_longlong()
                  throws TypeMismatch,
                         InvalidValue
Extracts the long value from this DynAny. The IDL long long data type is mapped to the Java long data type.

Specified by:
get_longlong in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_ulonglong

public long get_ulonglong()
                   throws TypeMismatch,
                          InvalidValue
Extracts the long value from this DynAny. The IDL unsigned long long data type is mapped to the Java long data type.

Specified by:
get_ulonglong in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_wchar

public char get_wchar()
               throws TypeMismatch,
                      InvalidValue
Extracts the long value from this DynAny. The IDL wchar data type is mapped to the Java char data type.

Specified by:
get_wchar in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_wstring

public String get_wstring()
                   throws TypeMismatch,
                          InvalidValue
Extracts the string value from this DynAny. Both bounded and unbounded strings are extracted using this method.

Specified by:
get_wstring in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue

get_any

public Any get_any()
            throws TypeMismatch,
                   InvalidValue
Extracts an Any value contained in the Any represented by this DynAny.

Specified by:
get_any in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_dyn_any

public DynAny get_dyn_any()
                   throws TypeMismatch,
                          InvalidValue
Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.

Specified by:
get_dyn_any in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_val

public Serializable get_val()
                     throws TypeMismatch,
                            InvalidValue
Extracts a Serializable object from this DynAny. The IDL ValueBase type is mapped to the Java Serializable type.

Specified by:
get_val in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

seek

public boolean seek(int index)
Sets the current position to index. The current position is indexed 0 to n-1, that is, index zero corresponds to the first component. The operation returns true if the resulting current position indicates a component of the DynAny and false if index indicates a position that does not correspond to a component. Calling seek with a negative index is legal. It sets the current position to -1 to indicate no component and returns false. Passing a non-negative index value for a DynAny that does not have a component at the corresponding position sets the current position to -1 and returns false.

Specified by:
seek in interface DynAnyOperations

rewind

public void rewind()
Is equivalent to seek(0).

Specified by:
rewind in interface DynAnyOperations

next

public boolean next()
Advances the current position to the next component. The operation returns true while the resulting current position indicates a component, false otherwise. A false return value leaves the current position at -1. Invoking next on a DynAny without components leaves the current position at -1 and returns false.

Specified by:
next in interface DynAnyOperations

component_count

public int component_count()
Returns the number of components of a DynAny. For a DynAny without components, it returns zero. The operation only counts the components at the top level. For example, if component_count is invoked on a DynStruct with a single member, the return value is 1, irrespective of the type of the member.
  • For sequences, the operation returns the current number of elements.
  • For structures, exceptions, and value types, the operation returns the number of members.
  • For arrays, the operation returns the number of elements.
  • For unions, the operation returns 2 if the discriminator indicates that a named member is active, otherwise, it returns 1.
  • For DynFixed and DynEnum, the operation returns zero.

Specified by:
component_count in interface DynAnyOperations

current_component

public DynAny current_component()
                         throws TypeMismatch
Returns the DynAny for the component at the current position. It does not advance the current position, so repeated calls to current_component without an intervening call to rewind, next, or seek return the same component. The returned DynAny object reference can be used to get/set the value of the current component. If the current component represents a complex type, the returned reference can be narrowed based on the TypeCode to get the interface corresponding to the to the complex type. Calling current_component on a DynAny that cannot have components, such as a DynEnum or an empty exception, raises TypeMismatch. Calling current_component on a DynAny whose current position is -1 returns a nil reference. The iteration operations, together with current_component, can be used to dynamically compose an any value. After creating a dynamic any, such as a DynStruct, current_component and next can be used to initialize all the components of the value. Once the dynamic value is completely initialized, to_any creates the corresponding any value.

Specified by:
current_component in interface DynAnyOperations
Throws:
TypeMismatch - If called on a DynAny that cannot have components, such as a DynEnum or an empty exception

_ids

public String[] _ids()
Description copied from class: ObjectImpl
Retrieves a string array containing the repository identifiers supported by this ObjectImpl object. For example, for a stub, this method returns information about all the interfaces supported by the stub.

Specified by:
_ids in class ObjectImpl
Returns:
the array of all repository identifiers supported by this ObjectImpl instance
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


_DynEnumStub (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Class _DynEnumStub

java.lang.Object
    extended by org.omg.CORBA.portable.ObjectImpl
        extended by org.omg.DynamicAny._DynEnumStub
All Implemented Interfaces:
DynAny, DynAnyOperations, DynEnum, DynEnumOperations, IDLEntity, Object, Serializable
public class _DynEnumStub
extends ObjectImpl
implements DynEnum

DynEnum objects support the manipulation of IDL enumerated values. The current position of a DynEnum is always -1.

Field Summary
static Class _opsClass
Constructor Summary
_DynEnumStub()
Method Summary
 String[] _ids()
Retrieves a string array containing the repository identifiers supported by this ObjectImpl object.
 void assign(DynAny dyn_any)
Initializes the value associated with a DynAny object with the value associated with another DynAny object.
 int component_count()
Returns the number of components of a DynAny.
 DynAny copy()
Creates a new DynAny object whose value is a deep copy of the DynAny on which it is invoked.
 DynAny current_component()
Returns the DynAny for the component at the current position.
 void destroy()
Destroys a DynAny object.
 boolean equal(DynAny dyn_any)
Compares two DynAny values for equality.
 void from_any(Any value)
Initializes the value associated with a DynAny object with the value contained in an any.
 Any get_any()
Extracts an Any value contained in the Any represented by this DynAny.
 String get_as_string()
Returns the value of the DynEnum as an IDL identifier.
 int get_as_ulong()
Returns the value of the DynEnum as the enumerated value's ordinal value.
 boolean get_boolean()
Extracts the boolean value from this DynAny.
 char get_char()
Extracts the char value from this DynAny.
 double get_double()
Extracts the double value from this DynAny.
 DynAny get_dyn_any()
Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.
 float get_float()
Extracts the float value from this DynAny.
 int get_long()
Extracts the integer value from this DynAny.
 long get_longlong()
Extracts the long value from this DynAny.
 byte get_octet()
Extracts the byte value from this DynAny.
 Object get_reference()
Extracts the reference to a CORBA Object from this DynAny.
 short get_short()
Extracts the short value from this DynAny.
 String get_string()
Extracts the string value from this DynAny.
 TypeCode get_typecode()
Extracts the TypeCode object from this DynAny.
 int get_ulong()
Extracts the integer value from this DynAny.
 long get_ulonglong()
Extracts the long value from this DynAny.
 short get_ushort()
Extracts the short value from this DynAny.
 Serializable get_val()
Extracts a Serializable object from this DynAny.
 char get_wchar()
Extracts the long value from this DynAny.
 String get_wstring()
Extracts the string value from this DynAny.
 void insert_any(Any value)
Inserts an Any value into the Any represented by this DynAny.
 void insert_boolean(boolean value)
Inserts a boolean value into the DynAny.
 void insert_char(char value)
Inserts a char value into the DynAny.
 void insert_double(double value)
Inserts a double value into the DynAny.
 void insert_dyn_any(DynAny value)
Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.
 void insert_float(float value)
Inserts a float value into the DynAny.
 void insert_long(int value)
Inserts an integer value into the DynAny.
 void insert_longlong(long value)
Inserts a long value into the DynAny.
 void insert_octet(byte value)
Inserts a byte value into the DynAny.
 void insert_reference(Object value)
Inserts a reference to a CORBA object into the DynAny.
 void insert_short(short value)
Inserts a short value into the DynAny.
 void insert_string(String value)
Inserts a string value into the DynAny.
 void insert_typecode(TypeCode value)
Inserts a TypeCode object into the DynAny.
 void insert_ulong(int value)
Inserts an integer value into the DynAny.
 void insert_ulonglong(long value)
Inserts a long value into the DynAny.
 void insert_ushort(short value)
Inserts a short value into the DynAny.
 void insert_val(Serializable value)
Inserts a reference to a Serializable object into this DynAny.
 void insert_wchar(char value)
Inserts a char value into the DynAny.
 void insert_wstring(String value)
Inserts a string value into the DynAny.
 boolean next()
Advances the current position to the next component.
 void rewind()
Is equivalent to seek(0).
 boolean seek(int index)
Sets the current position to index.
 void set_as_string(String value)
Sets the value of the DynEnum to the enumerated value whose IDL identifier is passed in the value parameter.
 void set_as_ulong(int value)
Sets the value of the DynEnum as the enumerated value's ordinal value.
 Any to_any()
Creates an any value from a DynAny object.
 TypeCode type()
Returns the TypeCode associated with this DynAny object.
Methods inherited from class org.omg.CORBA.portable.ObjectImpl
_create_request, _create_request, _duplicate, _get_delegate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _invoke, _is_a, _is_equivalent, _is_local, _non_existent, _orb, _release, _releaseReply, _request, _request, _servant_postinvoke, _servant_preinvoke, _set_delegate, _set_policy_override, equals, hashCode, toString
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Field Detail

_opsClass

public static final Class _opsClass
Constructor Detail

_DynEnumStub

public _DynEnumStub()
Method Detail

get_as_string

public String get_as_string()
Returns the value of the DynEnum as an IDL identifier.

Specified by:
get_as_string in interface DynEnumOperations

set_as_string

public void set_as_string(String value)
                   throws InvalidValue
Sets the value of the DynEnum to the enumerated value whose IDL identifier is passed in the value parameter.

Specified by:
set_as_string in interface DynEnumOperations
Throws:
InvalidValue - If value contains a string that is not a valid IDL identifier for the corresponding enumerated type

get_as_ulong

public int get_as_ulong()
Returns the value of the DynEnum as the enumerated value's ordinal value. Enumerators have ordinal values 0 to n-1, as they appear from left to right in the corresponding IDL definition.

Specified by:
get_as_ulong in interface DynEnumOperations

set_as_ulong

public void set_as_ulong(int value)
                  throws InvalidValue
Sets the value of the DynEnum as the enumerated value's ordinal value.

Specified by:
set_as_ulong in interface DynEnumOperations
Throws:
InvalidValue - If value contains a value that is outside the range of ordinal values for the corresponding enumerated type

type

public TypeCode type()
Returns the TypeCode associated with this DynAny object. A DynAny object is created with a TypeCode value assigned to it. This TypeCode value determines the type of the value handled through the DynAny object. Note that the TypeCode associated with a DynAny object is initialized at the time the DynAny is created and cannot be changed during lifetime of the DynAny object.

Specified by:
type in interface DynAnyOperations
Returns:
The TypeCode associated with this DynAny object

assign

public void assign(DynAny dyn_any)
            throws TypeMismatch
Initializes the value associated with a DynAny object with the value associated with another DynAny object. The current position of the target DynAny is set to zero for values that have components and to -1 for values that do not have components.

Specified by:
assign in interface DynAnyOperations
Parameters:
dyn_any -
Throws:
TypeMismatch - if the type of the passed DynAny is not equivalent to the type of target DynAny

from_any

public void from_any(Any value)
              throws TypeMismatch,
                     InvalidValue
Initializes the value associated with a DynAny object with the value contained in an any. The current position of the target DynAny is set to zero for values that have components and to -1 for values that do not have components.

Specified by:
from_any in interface DynAnyOperations
Throws:
TypeMismatch - if the type of the passed Any is not equivalent to the type of target DynAny
InvalidValue - if the passed Any does not contain a legal value (such as a null string)

to_any

public Any to_any()
Creates an any value from a DynAny object. A copy of the TypeCode associated with the DynAny object is assigned to the resulting any. The value associated with the DynAny object is copied into the any.

Specified by:
to_any in interface DynAnyOperations
Returns:
a new Any object with the same value and TypeCode

equal

public boolean equal(DynAny dyn_any)
Compares two DynAny values for equality. Two DynAny values are equal if their TypeCodes are equivalent and, recursively, all component DynAnys have equal values. The current position of the two DynAnys being compared has no effect on the result of equal.

Specified by:
equal in interface DynAnyOperations
Returns:
true of the DynAnys are equal, false otherwise

destroy

public void destroy()
Destroys a DynAny object. This operation frees any resources used to represent the data value associated with a DynAny object. It must be invoked on references obtained from one of the creation operations on the ORB interface or on a reference returned by DynAny.copy() to avoid resource leaks. Invoking destroy on component DynAny objects (for example, on objects returned by the current_component operation) does nothing. Destruction of a DynAny object implies destruction of all DynAny objects obtained from it. That is, references to components of a destroyed DynAny become invalid. Invocations on such references raise OBJECT_NOT_EXIST. It is possible to manipulate a component of a DynAny beyond the life time of the DynAny from which the component was obtained by making a copy of the component with the copy operation before destroying the DynAny from which the component was obtained.

Specified by:
destroy in interface DynAnyOperations

copy

public DynAny copy()
Creates a new DynAny object whose value is a deep copy of the DynAny on which it is invoked. The operation is polymorphic, that is, invoking it on one of the types derived from DynAny, such as DynStruct, creates the derived type but returns its reference as the DynAny base type.

Specified by:
copy in interface DynAnyOperations
Returns:
a deep copy of the DynAny object

insert_boolean

public void insert_boolean(boolean value)
                    throws TypeMismatch,
                           InvalidValue
Inserts a boolean value into the DynAny.

Specified by:
insert_boolean in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_octet

public void insert_octet(byte value)
                  throws TypeMismatch,
                         InvalidValue
Inserts a byte value into the DynAny. The IDL octet data type is mapped to the Java byte data type.

Specified by:
insert_octet in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_char

public void insert_char(char value)
                 throws TypeMismatch,
                        InvalidValue
Inserts a char value into the DynAny.

Specified by:
insert_char in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_short

public void insert_short(short value)
                  throws TypeMismatch,
                         InvalidValue
Inserts a short value into the DynAny.

Specified by:
insert_short in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_ushort

public void insert_ushort(short value)
                   throws TypeMismatch,
                          InvalidValue
Inserts a short value into the DynAny. The IDL ushort data type is mapped to the Java short data type.

Specified by:
insert_ushort in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_long

public void insert_long(int value)
                 throws TypeMismatch,
                        InvalidValue
Inserts an integer value into the DynAny. The IDL long data type is mapped to the Java int data type.

Specified by:
insert_long in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_ulong

public void insert_ulong(int value)
                  throws TypeMismatch,
                         InvalidValue
Inserts an integer value into the DynAny. The IDL ulong data type is mapped to the Java int data type.

Specified by:
insert_ulong in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_float

public void insert_float(float value)
                  throws TypeMismatch,
                         InvalidValue
Inserts a float value into the DynAny.

Specified by:
insert_float in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_double

public void insert_double(double value)
                   throws TypeMismatch,
                          InvalidValue
Inserts a double value into the DynAny.

Specified by:
insert_double in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_string

public void insert_string(String value)
                   throws TypeMismatch,
                          InvalidValue
Inserts a string value into the DynAny. Both bounded and unbounded strings are inserted using this method.

Specified by:
insert_string in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
InvalidValue - if the string inserted is longer than the bound of a bounded string
TypeMismatch - if called on a DynAny whose current component itself has components

insert_reference

public void insert_reference(Object value)
                      throws TypeMismatch,
                             InvalidValue
Inserts a reference to a CORBA object into the DynAny.

Specified by:
insert_reference in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_typecode

public void insert_typecode(TypeCode value)
                     throws TypeMismatch,
                            InvalidValue
Inserts a TypeCode object into the DynAny.

Specified by:
insert_typecode in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_longlong

public void insert_longlong(long value)
                     throws TypeMismatch,
                            InvalidValue
Inserts a long value into the DynAny. The IDL long long data type is mapped to the Java long data type.

Specified by:
insert_longlong in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_ulonglong

public void insert_ulonglong(long value)
                      throws TypeMismatch,
                             InvalidValue
Inserts a long value into the DynAny. The IDL unsigned long long data type is mapped to the Java long data type.

Specified by:
insert_ulonglong in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_wchar

public void insert_wchar(char value)
                  throws TypeMismatch,
                         InvalidValue
Inserts a char value into the DynAny. The IDL wchar data type is mapped to the Java char data type.

Specified by:
insert_wchar in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_wstring

public void insert_wstring(String value)
                    throws TypeMismatch,
                           InvalidValue
Inserts a string value into the DynAny. Both bounded and unbounded strings are inserted using this method.

Specified by:
insert_wstring in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
InvalidValue - if the string inserted is longer than the bound of a bounded string
TypeMismatch

insert_any

public void insert_any(Any value)
                throws TypeMismatch,
                       InvalidValue
Inserts an Any value into the Any represented by this DynAny.

Specified by:
insert_any in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_dyn_any

public void insert_dyn_any(DynAny value)
                    throws TypeMismatch,
                           InvalidValue
Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.

Specified by:
insert_dyn_any in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_val

public void insert_val(Serializable value)
                throws TypeMismatch,
                       InvalidValue
Inserts a reference to a Serializable object into this DynAny. The IDL ValueBase type is mapped to the Java Serializable type.

Specified by:
insert_val in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

get_boolean

public boolean get_boolean()
                    throws TypeMismatch,
                           InvalidValue
Extracts the boolean value from this DynAny.

Specified by:
get_boolean in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_octet

public byte get_octet()
               throws TypeMismatch,
                      InvalidValue
Extracts the byte value from this DynAny. The IDL octet data type is mapped to the Java byte data type.

Specified by:
get_octet in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_char

public char get_char()
              throws TypeMismatch,
                     InvalidValue
Extracts the char value from this DynAny.

Specified by:
get_char in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_short

public short get_short()
                throws TypeMismatch,
                       InvalidValue
Extracts the short value from this DynAny.

Specified by:
get_short in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_ushort

public short get_ushort()
                 throws TypeMismatch,
                        InvalidValue
Extracts the short value from this DynAny. The IDL ushort data type is mapped to the Java short data type.

Specified by:
get_ushort in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_long

public int get_long()
             throws TypeMismatch,
                    InvalidValue
Extracts the integer value from this DynAny. The IDL long data type is mapped to the Java int data type.

Specified by:
get_long in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_ulong

public int get_ulong()
              throws TypeMismatch,
                     InvalidValue
Extracts the integer value from this DynAny. The IDL ulong data type is mapped to the Java int data type.

Specified by:
get_ulong in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_float

public float get_float()
                throws TypeMismatch,
                       InvalidValue
Extracts the float value from this DynAny.

Specified by:
get_float in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_double

public double get_double()
                  throws TypeMismatch,
                         InvalidValue
Extracts the double value from this DynAny.

Specified by:
get_double in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_string

public String get_string()
                  throws TypeMismatch,
                         InvalidValue
Extracts the string value from this DynAny. Both bounded and unbounded strings are extracted using this method.

Specified by:
get_string in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_reference

public Object get_reference()
                     throws TypeMismatch,
                            InvalidValue
Extracts the reference to a CORBA Object from this DynAny.

Specified by:
get_reference in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_typecode

public TypeCode get_typecode()
                      throws TypeMismatch,
                             InvalidValue
Extracts the TypeCode object from this DynAny.

Specified by:
get_typecode in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_longlong

public long get_longlong()
                  throws TypeMismatch,
                         InvalidValue
Extracts the long value from this DynAny. The IDL long long data type is mapped to the Java long data type.

Specified by:
get_longlong in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_ulonglong

public long get_ulonglong()
                   throws TypeMismatch,
                          InvalidValue
Extracts the long value from this DynAny. The IDL unsigned long long data type is mapped to the Java long data type.

Specified by:
get_ulonglong in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_wchar

public char get_wchar()
               throws TypeMismatch,
                      InvalidValue
Extracts the long value from this DynAny. The IDL wchar data type is mapped to the Java char data type.

Specified by:
get_wchar in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_wstring

public String get_wstring()
                   throws TypeMismatch,
                          InvalidValue
Extracts the string value from this DynAny. Both bounded and unbounded strings are extracted using this method.

Specified by:
get_wstring in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue

get_any

public Any get_any()
            throws TypeMismatch,
                   InvalidValue
Extracts an Any value contained in the Any represented by this DynAny.

Specified by:
get_any in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_dyn_any

public DynAny get_dyn_any()
                   throws TypeMismatch,
                          InvalidValue
Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.

Specified by:
get_dyn_any in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_val

public Serializable get_val()
                     throws TypeMismatch,
                            InvalidValue
Extracts a Serializable object from this DynAny. The IDL ValueBase type is mapped to the Java Serializable type.

Specified by:
get_val in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

seek

public boolean seek(int index)
Sets the current position to index. The current position is indexed 0 to n-1, that is, index zero corresponds to the first component. The operation returns true if the resulting current position indicates a component of the DynAny and false if index indicates a position that does not correspond to a component. Calling seek with a negative index is legal. It sets the current position to -1 to indicate no component and returns false. Passing a non-negative index value for a DynAny that does not have a component at the corresponding position sets the current position to -1 and returns false.

Specified by:
seek in interface DynAnyOperations

rewind

public void rewind()
Is equivalent to seek(0).

Specified by:
rewind in interface DynAnyOperations

next

public boolean next()
Advances the current position to the next component. The operation returns true while the resulting current position indicates a component, false otherwise. A false return value leaves the current position at -1. Invoking next on a DynAny without components leaves the current position at -1 and returns false.

Specified by:
next in interface DynAnyOperations

component_count

public int component_count()
Returns the number of components of a DynAny. For a DynAny without components, it returns zero. The operation only counts the components at the top level. For example, if component_count is invoked on a DynStruct with a single member, the return value is 1, irrespective of the type of the member.
  • For sequences, the operation returns the current number of elements.
  • For structures, exceptions, and value types, the operation returns the number of members.
  • For arrays, the operation returns the number of elements.
  • For unions, the operation returns 2 if the discriminator indicates that a named member is active, otherwise, it returns 1.
  • For DynFixed and DynEnum, the operation returns zero.

Specified by:
component_count in interface DynAnyOperations

current_component

public DynAny current_component()
                         throws TypeMismatch
Returns the DynAny for the component at the current position. It does not advance the current position, so repeated calls to current_component without an intervening call to rewind, next, or seek return the same component. The returned DynAny object reference can be used to get/set the value of the current component. If the current component represents a complex type, the returned reference can be narrowed based on the TypeCode to get the interface corresponding to the to the complex type. Calling current_component on a DynAny that cannot have components, such as a DynEnum or an empty exception, raises TypeMismatch. Calling current_component on a DynAny whose current position is -1 returns a nil reference. The iteration operations, together with current_component, can be used to dynamically compose an any value. After creating a dynamic any, such as a DynStruct, current_component and next can be used to initialize all the components of the value. Once the dynamic value is completely initialized, to_any creates the corresponding any value.

Specified by:
current_component in interface DynAnyOperations
Throws:
TypeMismatch - If called on a DynAny that cannot have components, such as a DynEnum or an empty exception

_ids

public String[] _ids()
Description copied from class: ObjectImpl
Retrieves a string array containing the repository identifiers supported by this ObjectImpl object. For example, for a stub, this method returns information about all the interfaces supported by the stub.

Specified by:
_ids in class ObjectImpl
Returns:
the array of all repository identifiers supported by this ObjectImpl instance
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


_DynFixedStub (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Class _DynFixedStub

java.lang.Object
    extended by org.omg.CORBA.portable.ObjectImpl
        extended by org.omg.DynamicAny._DynFixedStub
All Implemented Interfaces:
DynAny, DynAnyOperations, DynFixed, DynFixedOperations, IDLEntity, Object, Serializable
public class _DynFixedStub
extends ObjectImpl
implements DynFixed

DynFixed objects support the manipulation of IDL fixed values. Because IDL does not have a generic type that can represent fixed types with arbitrary number of digits and arbitrary scale, the operations use the IDL string type.

Field Summary
static Class _opsClass
Constructor Summary
_DynFixedStub()
Method Summary
 String[] _ids()
Retrieves a string array containing the repository identifiers supported by this ObjectImpl object.
 void assign(DynAny dyn_any)
Initializes the value associated with a DynAny object with the value associated with another DynAny object.
 int component_count()
Returns the number of components of a DynAny.
 DynAny copy()
Creates a new DynAny object whose value is a deep copy of the DynAny on which it is invoked.
 DynAny current_component()
Returns the DynAny for the component at the current position.
 void destroy()
Destroys a DynAny object.
 boolean equal(DynAny dyn_any)
Compares two DynAny values for equality.
 void from_any(Any value)
Initializes the value associated with a DynAny object with the value contained in an any.
 Any get_any()
Extracts an Any value contained in the Any represented by this DynAny.
 boolean get_boolean()
Extracts the boolean value from this DynAny.
 char get_char()
Extracts the char value from this DynAny.
 double get_double()
Extracts the double value from this DynAny.
 DynAny get_dyn_any()
Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.
 float get_float()
Extracts the float value from this DynAny.
 int get_long()
Extracts the integer value from this DynAny.
 long get_longlong()
Extracts the long value from this DynAny.
 byte get_octet()
Extracts the byte value from this DynAny.
 Object get_reference()
Extracts the reference to a CORBA Object from this DynAny.
 short get_short()
Extracts the short value from this DynAny.
 String get_string()
Extracts the string value from this DynAny.
 TypeCode get_typecode()
Extracts the TypeCode object from this DynAny.
 int get_ulong()
Extracts the integer value from this DynAny.
 long get_ulonglong()
Extracts the long value from this DynAny.
 short get_ushort()
Extracts the short value from this DynAny.
 Serializable get_val()
Extracts a Serializable object from this DynAny.
 String get_value()
Returns the value of a DynFixed.
 char get_wchar()
Extracts the long value from this DynAny.
 String get_wstring()
Extracts the string value from this DynAny.
 void insert_any(Any value)
Inserts an Any value into the Any represented by this DynAny.
 void insert_boolean(boolean value)
Inserts a boolean value into the DynAny.
 void insert_char(char value)
Inserts a char value into the DynAny.
 void insert_double(double value)
Inserts a double value into the DynAny.
 void insert_dyn_any(DynAny value)
Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.
 void insert_float(float value)
Inserts a float value into the DynAny.
 void insert_long(int value)
Inserts an integer value into the DynAny.
 void insert_longlong(long value)
Inserts a long value into the DynAny.
 void insert_octet(byte value)
Inserts a byte value into the DynAny.
 void insert_reference(Object value)
Inserts a reference to a CORBA object into the DynAny.
 void insert_short(short value)
Inserts a short value into the DynAny.
 void insert_string(String value)
Inserts a string value into the DynAny.
 void insert_typecode(TypeCode value)
Inserts a TypeCode object into the DynAny.
 void insert_ulong(int value)
Inserts an integer value into the DynAny.
 void insert_ulonglong(long value)
Inserts a long value into the DynAny.
 void insert_ushort(short value)
Inserts a short value into the DynAny.
 void insert_val(Serializable value)
Inserts a reference to a Serializable object into this DynAny.
 void insert_wchar(char value)
Inserts a char value into the DynAny.
 void insert_wstring(String value)
Inserts a string value into the DynAny.
 boolean next()
Advances the current position to the next component.
 void rewind()
Is equivalent to seek(0).
 boolean seek(int index)
Sets the current position to index.
 boolean set_value(String val)
Sets the value of the DynFixed.
 Any to_any()
Creates an any value from a DynAny object.
 TypeCode type()
Returns the TypeCode associated with this DynAny object.
Methods inherited from class org.omg.CORBA.portable.ObjectImpl
_create_request, _create_request, _duplicate, _get_delegate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _invoke, _is_a, _is_equivalent, _is_local, _non_existent, _orb, _release, _releaseReply, _request, _request, _servant_postinvoke, _servant_preinvoke, _set_delegate, _set_policy_override, equals, hashCode, toString
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Field Detail

_opsClass

public static final Class _opsClass
Constructor Detail

_DynFixedStub

public _DynFixedStub()
Method Detail

get_value

public String get_value()
Returns the value of a DynFixed.

Specified by:
get_value in interface DynFixedOperations

set_value

public boolean set_value(String val)
                  throws TypeMismatch,
                         InvalidValue
Sets the value of the DynFixed. The val string must contain a fixed string constant in the same format as used for IDL fixed-point literals. However, the trailing d or D is optional. The return value is true if val can be represented as the DynFixed without loss of precision. If val has more fractional digits than can be represented in the DynFixed, fractional digits are truncated and the return value is false.

Specified by:
set_value in interface DynFixedOperations
Throws:
TypeMismatch - If val does not contain a valid fixed-point literal or contains extraneous characters other than leading or trailing white space
InvalidValue - If val contains a value whose scale exceeds that of the DynFixed or is not initialized

type

public TypeCode type()
Returns the TypeCode associated with this DynAny object. A DynAny object is created with a TypeCode value assigned to it. This TypeCode value determines the type of the value handled through the DynAny object. Note that the TypeCode associated with a DynAny object is initialized at the time the DynAny is created and cannot be changed during lifetime of the DynAny object.

Specified by:
type in interface DynAnyOperations
Returns:
The TypeCode associated with this DynAny object

assign

public void assign(DynAny dyn_any)
            throws TypeMismatch
Initializes the value associated with a DynAny object with the value associated with another DynAny object. The current position of the target DynAny is set to zero for values that have components and to -1 for values that do not have components.

Specified by:
assign in interface DynAnyOperations
Parameters:
dyn_any -
Throws:
TypeMismatch - if the type of the passed DynAny is not equivalent to the type of target DynAny

from_any

public void from_any(Any value)
              throws TypeMismatch,
                     InvalidValue
Initializes the value associated with a DynAny object with the value contained in an any. The current position of the target DynAny is set to zero for values that have components and to -1 for values that do not have components.

Specified by:
from_any in interface DynAnyOperations
Throws:
TypeMismatch - if the type of the passed Any is not equivalent to the type of target DynAny
InvalidValue - if the passed Any does not contain a legal value (such as a null string)

to_any

public Any to_any()
Creates an any value from a DynAny object. A copy of the TypeCode associated with the DynAny object is assigned to the resulting any. The value associated with the DynAny object is copied into the any.

Specified by:
to_any in interface DynAnyOperations
Returns:
a new Any object with the same value and TypeCode

equal

public boolean equal(DynAny dyn_any)
Compares two DynAny values for equality. Two DynAny values are equal if their TypeCodes are equivalent and, recursively, all component DynAnys have equal values. The current position of the two DynAnys being compared has no effect on the result of equal.

Specified by:
equal in interface DynAnyOperations
Returns:
true of the DynAnys are equal, false otherwise

destroy

public void destroy()
Destroys a DynAny object. This operation frees any resources used to represent the data value associated with a DynAny object. It must be invoked on references obtained from one of the creation operations on the ORB interface or on a reference returned by DynAny.copy() to avoid resource leaks. Invoking destroy on component DynAny objects (for example, on objects returned by the current_component operation) does nothing. Destruction of a DynAny object implies destruction of all DynAny objects obtained from it. That is, references to components of a destroyed DynAny become invalid. Invocations on such references raise OBJECT_NOT_EXIST. It is possible to manipulate a component of a DynAny beyond the life time of the DynAny from which the component was obtained by making a copy of the component with the copy operation before destroying the DynAny from which the component was obtained.

Specified by:
destroy in interface DynAnyOperations

copy

public DynAny copy()
Creates a new DynAny object whose value is a deep copy of the DynAny on which it is invoked. The operation is polymorphic, that is, invoking it on one of the types derived from DynAny, such as DynStruct, creates the derived type but returns its reference as the DynAny base type.

Specified by:
copy in interface DynAnyOperations
Returns:
a deep copy of the DynAny object

insert_boolean

public void insert_boolean(boolean value)
                    throws TypeMismatch,
                           InvalidValue
Inserts a boolean value into the DynAny.

Specified by:
insert_boolean in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_octet

public void insert_octet(byte value)
                  throws TypeMismatch,
                         InvalidValue
Inserts a byte value into the DynAny. The IDL octet data type is mapped to the Java byte data type.

Specified by:
insert_octet in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_char

public void insert_char(char value)
                 throws TypeMismatch,
                        InvalidValue
Inserts a char value into the DynAny.

Specified by:
insert_char in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_short

public void insert_short(short value)
                  throws TypeMismatch,
                         InvalidValue
Inserts a short value into the DynAny.

Specified by:
insert_short in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_ushort

public void insert_ushort(short value)
                   throws TypeMismatch,
                          InvalidValue
Inserts a short value into the DynAny. The IDL ushort data type is mapped to the Java short data type.

Specified by:
insert_ushort in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_long

public void insert_long(int value)
                 throws TypeMismatch,
                        InvalidValue
Inserts an integer value into the DynAny. The IDL long data type is mapped to the Java int data type.

Specified by:
insert_long in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_ulong

public void insert_ulong(int value)
                  throws TypeMismatch,
                         InvalidValue
Inserts an integer value into the DynAny. The IDL ulong data type is mapped to the Java int data type.

Specified by:
insert_ulong in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_float

public void insert_float(float value)
                  throws TypeMismatch,
                         InvalidValue
Inserts a float value into the DynAny.

Specified by:
insert_float in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_double

public void insert_double(double value)
                   throws TypeMismatch,
                          InvalidValue
Inserts a double value into the DynAny.

Specified by:
insert_double in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_string

public void insert_string(String value)
                   throws TypeMismatch,
                          InvalidValue
Inserts a string value into the DynAny. Both bounded and unbounded strings are inserted using this method.

Specified by:
insert_string in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
InvalidValue - if the string inserted is longer than the bound of a bounded string
TypeMismatch - if called on a DynAny whose current component itself has components

insert_reference

public void insert_reference(Object value)
                      throws TypeMismatch,
                             InvalidValue
Inserts a reference to a CORBA object into the DynAny.

Specified by:
insert_reference in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_typecode

public void insert_typecode(TypeCode value)
                     throws TypeMismatch,
                            InvalidValue
Inserts a TypeCode object into the DynAny.

Specified by:
insert_typecode in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_longlong

public void insert_longlong(long value)
                     throws TypeMismatch,
                            InvalidValue
Inserts a long value into the DynAny. The IDL long long data type is mapped to the Java long data type.

Specified by:
insert_longlong in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_ulonglong

public void insert_ulonglong(long value)
                      throws TypeMismatch,
                             InvalidValue
Inserts a long value into the DynAny. The IDL unsigned long long data type is mapped to the Java long data type.

Specified by:
insert_ulonglong in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_wchar

public void insert_wchar(char value)
                  throws TypeMismatch,
                         InvalidValue
Inserts a char value into the DynAny. The IDL wchar data type is mapped to the Java char data type.

Specified by:
insert_wchar in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_wstring

public void insert_wstring(String value)
                    throws TypeMismatch,
                           InvalidValue
Inserts a string value into the DynAny. Both bounded and unbounded strings are inserted using this method.

Specified by:
insert_wstring in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
InvalidValue - if the string inserted is longer than the bound of a bounded string
TypeMismatch

insert_any

public void insert_any(Any value)
                throws TypeMismatch,
                       InvalidValue
Inserts an Any value into the Any represented by this DynAny.

Specified by:
insert_any in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_dyn_any

public void insert_dyn_any(DynAny value)
                    throws TypeMismatch,
                           InvalidValue
Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.

Specified by:
insert_dyn_any in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_val

public void insert_val(Serializable value)
                throws TypeMismatch,
                       InvalidValue
Inserts a reference to a Serializable object into this DynAny. The IDL ValueBase type is mapped to the Java Serializable type.

Specified by:
insert_val in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

get_boolean

public boolean get_boolean()
                    throws TypeMismatch,
                           InvalidValue
Extracts the boolean value from this DynAny.

Specified by:
get_boolean in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_octet

public byte get_octet()
               throws TypeMismatch,
                      InvalidValue
Extracts the byte value from this DynAny. The IDL octet data type is mapped to the Java byte data type.

Specified by:
get_octet in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_char

public char get_char()
              throws TypeMismatch,
                     InvalidValue
Extracts the char value from this DynAny.

Specified by:
get_char in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_short

public short get_short()
                throws TypeMismatch,
                       InvalidValue
Extracts the short value from this DynAny.

Specified by:
get_short in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_ushort

public short get_ushort()
                 throws TypeMismatch,
                        InvalidValue
Extracts the short value from this DynAny. The IDL ushort data type is mapped to the Java short data type.

Specified by:
get_ushort in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_long

public int get_long()
             throws TypeMismatch,
                    InvalidValue
Extracts the integer value from this DynAny. The IDL long data type is mapped to the Java int data type.

Specified by:
get_long in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_ulong

public int get_ulong()
              throws TypeMismatch,
                     InvalidValue
Extracts the integer value from this DynAny. The IDL ulong data type is mapped to the Java int data type.

Specified by:
get_ulong in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_float

public float get_float()
                throws TypeMismatch,
                       InvalidValue
Extracts the float value from this DynAny.

Specified by:
get_float in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_double

public double get_double()
                  throws TypeMismatch,
                         InvalidValue
Extracts the double value from this DynAny.

Specified by:
get_double in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_string

public String get_string()
                  throws TypeMismatch,
                         InvalidValue
Extracts the string value from this DynAny. Both bounded and unbounded strings are extracted using this method.

Specified by:
get_string in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_reference

public Object get_reference()
                     throws TypeMismatch,
                            InvalidValue
Extracts the reference to a CORBA Object from this DynAny.

Specified by:
get_reference in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_typecode

public TypeCode get_typecode()
                      throws TypeMismatch,
                             InvalidValue
Extracts the TypeCode object from this DynAny.

Specified by:
get_typecode in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_longlong

public long get_longlong()
                  throws TypeMismatch,
                         InvalidValue
Extracts the long value from this DynAny. The IDL long long data type is mapped to the Java long data type.

Specified by:
get_longlong in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_ulonglong

public long get_ulonglong()
                   throws TypeMismatch,
                          InvalidValue
Extracts the long value from this DynAny. The IDL unsigned long long data type is mapped to the Java long data type.

Specified by:
get_ulonglong in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_wchar

public char get_wchar()
               throws TypeMismatch,
                      InvalidValue
Extracts the long value from this DynAny. The IDL wchar data type is mapped to the Java char data type.

Specified by:
get_wchar in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_wstring

public String get_wstring()
                   throws TypeMismatch,
                          InvalidValue
Extracts the string value from this DynAny. Both bounded and unbounded strings are extracted using this method.

Specified by:
get_wstring in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue

get_any

public Any get_any()
            throws TypeMismatch,
                   InvalidValue
Extracts an Any value contained in the Any represented by this DynAny.

Specified by:
get_any in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_dyn_any

public DynAny get_dyn_any()
                   throws TypeMismatch,
                          InvalidValue
Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.

Specified by:
get_dyn_any in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_val

public Serializable get_val()
                     throws TypeMismatch,
                            InvalidValue
Extracts a Serializable object from this DynAny. The IDL ValueBase type is mapped to the Java Serializable type.

Specified by:
get_val in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

seek

public boolean seek(int index)
Sets the current position to index. The current position is indexed 0 to n-1, that is, index zero corresponds to the first component. The operation returns true if the resulting current position indicates a component of the DynAny and false if index indicates a position that does not correspond to a component. Calling seek with a negative index is legal. It sets the current position to -1 to indicate no component and returns false. Passing a non-negative index value for a DynAny that does not have a component at the corresponding position sets the current position to -1 and returns false.

Specified by:
seek in interface DynAnyOperations

rewind

public void rewind()
Is equivalent to seek(0).

Specified by:
rewind in interface DynAnyOperations

next

public boolean next()
Advances the current position to the next component. The operation returns true while the resulting current position indicates a component, false otherwise. A false return value leaves the current position at -1. Invoking next on a DynAny without components leaves the current position at -1 and returns false.

Specified by:
next in interface DynAnyOperations

component_count

public int component_count()
Returns the number of components of a DynAny. For a DynAny without components, it returns zero. The operation only counts the components at the top level. For example, if component_count is invoked on a DynStruct with a single member, the return value is 1, irrespective of the type of the member.
  • For sequences, the operation returns the current number of elements.
  • For structures, exceptions, and value types, the operation returns the number of members.
  • For arrays, the operation returns the number of elements.
  • For unions, the operation returns 2 if the discriminator indicates that a named member is active, otherwise, it returns 1.
  • For DynFixed and DynEnum, the operation returns zero.

Specified by:
component_count in interface DynAnyOperations

current_component

public DynAny current_component()
                         throws TypeMismatch
Returns the DynAny for the component at the current position. It does not advance the current position, so repeated calls to current_component without an intervening call to rewind, next, or seek return the same component. The returned DynAny object reference can be used to get/set the value of the current component. If the current component represents a complex type, the returned reference can be narrowed based on the TypeCode to get the interface corresponding to the to the complex type. Calling current_component on a DynAny that cannot have components, such as a DynEnum or an empty exception, raises TypeMismatch. Calling current_component on a DynAny whose current position is -1 returns a nil reference. The iteration operations, together with current_component, can be used to dynamically compose an any value. After creating a dynamic any, such as a DynStruct, current_component and next can be used to initialize all the components of the value. Once the dynamic value is completely initialized, to_any creates the corresponding any value.

Specified by:
current_component in interface DynAnyOperations
Throws:
TypeMismatch - If called on a DynAny that cannot have components, such as a DynEnum or an empty exception

_ids

public String[] _ids()
Description copied from class: ObjectImpl
Retrieves a string array containing the repository identifiers supported by this ObjectImpl object. For example, for a stub, this method returns information about all the interfaces supported by the stub.

Specified by:
_ids in class ObjectImpl
Returns:
the array of all repository identifiers supported by this ObjectImpl instance
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


_DynSequenceStub (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Class _DynSequenceStub

java.lang.Object
    extended by org.omg.CORBA.portable.ObjectImpl
        extended by org.omg.DynamicAny._DynSequenceStub
All Implemented Interfaces:
DynAny, DynAnyOperations, DynSequence, DynSequenceOperations, IDLEntity, Object, Serializable
public class _DynSequenceStub
extends ObjectImpl
implements DynSequence

DynSequence objects support the manipulation of IDL sequences.

Field Summary
static Class _opsClass
Constructor Summary
_DynSequenceStub()
Method Summary
 String[] _ids()
Retrieves a string array containing the repository identifiers supported by this ObjectImpl object.
 void assign(DynAny dyn_any)
Initializes the value associated with a DynAny object with the value associated with another DynAny object.
 int component_count()
Returns the number of components of a DynAny.
 DynAny copy()
Creates a new DynAny object whose value is a deep copy of the DynAny on which it is invoked.
 DynAny current_component()
Returns the DynAny for the component at the current position.
 void destroy()
Destroys a DynAny object.
 boolean equal(DynAny dyn_any)
Compares two DynAny values for equality.
 void from_any(Any value)
Initializes the value associated with a DynAny object with the value contained in an any.
 Any get_any()
Extracts an Any value contained in the Any represented by this DynAny.
 boolean get_boolean()
Extracts the boolean value from this DynAny.
 char get_char()
Extracts the char value from this DynAny.
 double get_double()
Extracts the double value from this DynAny.
 DynAny get_dyn_any()
Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.
 DynAny[] get_elements_as_dyn_any()
Returns the DynAnys representing the elements of the sequence.
 Any[] get_elements()
Returns the elements of the sequence.
 float get_float()
Extracts the float value from this DynAny.
 int get_length()
Returns the current length of the sequence.
 int get_long()
Extracts the integer value from this DynAny.
 long get_longlong()
Extracts the long value from this DynAny.
 byte get_octet()
Extracts the byte value from this DynAny.
 Object get_reference()
Extracts the reference to a CORBA Object from this DynAny.
 short get_short()
Extracts the short value from this DynAny.
 String get_string()
Extracts the string value from this DynAny.
 TypeCode get_typecode()
Extracts the TypeCode object from this DynAny.
 int get_ulong()
Extracts the integer value from this DynAny.
 long get_ulonglong()
Extracts the long value from this DynAny.
 short get_ushort()
Extracts the short value from this DynAny.
 Serializable get_val()
Extracts a Serializable object from this DynAny.
 char get_wchar()
Extracts the long value from this DynAny.
 String get_wstring()
Extracts the string value from this DynAny.
 void insert_any(Any value)
Inserts an Any value into the Any represented by this DynAny.
 void insert_boolean(boolean value)
Inserts a boolean value into the DynAny.
 void insert_char(char value)
Inserts a char value into the DynAny.
 void insert_double(double value)
Inserts a double value into the DynAny.
 void insert_dyn_any(DynAny value)
Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.
 void insert_float(float value)
Inserts a float value into the DynAny.
 void insert_long(int value)
Inserts an integer value into the DynAny.
 void insert_longlong(long value)
Inserts a long value into the DynAny.
 void insert_octet(byte value)
Inserts a byte value into the DynAny.
 void insert_reference(Object value)
Inserts a reference to a CORBA object into the DynAny.
 void insert_short(short value)
Inserts a short value into the DynAny.
 void insert_string(String value)
Inserts a string value into the DynAny.
 void insert_typecode(TypeCode value)
Inserts a TypeCode object into the DynAny.
 void insert_ulong(int value)
Inserts an integer value into the DynAny.
 void insert_ulonglong(long value)
Inserts a long value into the DynAny.
 void insert_ushort(short value)
Inserts a short value into the DynAny.
 void insert_val(Serializable value)
Inserts a reference to a Serializable object into this DynAny.
 void insert_wchar(char value)
Inserts a char value into the DynAny.
 void insert_wstring(String value)
Inserts a string value into the DynAny.
 boolean next()
Advances the current position to the next component.
 void rewind()
Is equivalent to seek(0).
 boolean seek(int index)
Sets the current position to index.
 void set_elements_as_dyn_any(DynAny[] value)
Sets the elements of a sequence using DynAnys.
 void set_elements(Any[] value)
Sets the elements of a sequence.
 void set_length(int len)
Sets the length of the sequence.
 Any to_any()
Creates an any value from a DynAny object.
 TypeCode type()
Returns the TypeCode associated with this DynAny object.
Methods inherited from class org.omg.CORBA.portable.ObjectImpl
_create_request, _create_request, _duplicate, _get_delegate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _invoke, _is_a, _is_equivalent, _is_local, _non_existent, _orb, _release, _releaseReply, _request, _request, _servant_postinvoke, _servant_preinvoke, _set_delegate, _set_policy_override, equals, hashCode, toString
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Field Detail

_opsClass

public static final Class _opsClass
Constructor Detail

_DynSequenceStub

public _DynSequenceStub()
Method Detail

get_length

public int get_length()
Returns the current length of the sequence.

Specified by:
get_length in interface DynSequenceOperations

set_length

public void set_length(int len)
                throws InvalidValue
Sets the length of the sequence. Increasing the length of a sequence adds new elements at the tail without affecting the values of already existing elements. Newly added elements are default-initialized. Increasing the length of a sequence sets the current position to the first newly-added element if the previous current position was -1. Otherwise, if the previous current position was not -1, the current position is not affected. Decreasing the length of a sequence removes elements from the tail without affecting the value of those elements that remain. The new current position after decreasing the length of a sequence is determined as follows:
  • If the length of the sequence is set to zero, the current position is set to -1.
  • If the current position is -1 before decreasing the length, it remains at -1.
  • If the current position indicates a valid element and that element is not removed when the length is decreased, the current position remains unaffected.
  • If the current position indicates a valid element and that element is removed, the current position is set to -1.

Specified by:
set_length in interface DynSequenceOperations
Throws:
InvalidValue - if this is a bounded sequence and len is larger than the bound

get_elements

public Any[] get_elements()
Returns the elements of the sequence.

Specified by:
get_elements in interface DynSequenceOperations

set_elements

public void set_elements(Any[] value)
                  throws TypeMismatch,
                         InvalidValue
Sets the elements of a sequence. The length of the DynSequence is set to the length of value. The current position is set to zero if value has non-zero length and to -1 if value is a zero-length sequence.

Specified by:
set_elements in interface DynSequenceOperations
Throws:
TypeMismatch - if value contains one or more elements whose TypeCode is not equivalent to the element TypeCode of the DynSequence
InvalidValue - if the length of value exceeds the bound of a bounded sequence

get_elements_as_dyn_any

public DynAny[] get_elements_as_dyn_any()
Returns the DynAnys representing the elements of the sequence.

Specified by:
get_elements_as_dyn_any in interface DynSequenceOperations

set_elements_as_dyn_any

public void set_elements_as_dyn_any(DynAny[] value)
                             throws TypeMismatch,
                                    InvalidValue
Sets the elements of a sequence using DynAnys. The length of the DynSequence is set to the length of value. The current position is set to zero if value has non-zero length and to -1 if value is a zero-length sequence.

Specified by:
set_elements_as_dyn_any in interface DynSequenceOperations
Throws:
TypeMismatch - if value contains one or more elements whose TypeCode is not equivalent to the element TypeCode of the DynSequence
InvalidValue - if the length of value exceeds the bound of a bounded sequence

type

public TypeCode type()
Returns the TypeCode associated with this DynAny object. A DynAny object is created with a TypeCode value assigned to it. This TypeCode value determines the type of the value handled through the DynAny object. Note that the TypeCode associated with a DynAny object is initialized at the time the DynAny is created and cannot be changed during lifetime of the DynAny object.

Specified by:
type in interface DynAnyOperations
Returns:
The TypeCode associated with this DynAny object

assign

public void assign(DynAny dyn_any)
            throws TypeMismatch
Initializes the value associated with a DynAny object with the value associated with another DynAny object. The current position of the target DynAny is set to zero for values that have components and to -1 for values that do not have components.

Specified by:
assign in interface DynAnyOperations
Parameters:
dyn_any -
Throws:
TypeMismatch - if the type of the passed DynAny is not equivalent to the type of target DynAny

from_any

public void from_any(Any value)
              throws TypeMismatch,
                     InvalidValue
Initializes the value associated with a DynAny object with the value contained in an any. The current position of the target DynAny is set to zero for values that have components and to -1 for values that do not have components.

Specified by:
from_any in interface DynAnyOperations
Throws:
TypeMismatch - if the type of the passed Any is not equivalent to the type of target DynAny
InvalidValue - if the passed Any does not contain a legal value (such as a null string)

to_any

public Any to_any()
Creates an any value from a DynAny object. A copy of the TypeCode associated with the DynAny object is assigned to the resulting any. The value associated with the DynAny object is copied into the any.

Specified by:
to_any in interface DynAnyOperations
Returns:
a new Any object with the same value and TypeCode

equal

public boolean equal(DynAny dyn_any)
Compares two DynAny values for equality. Two DynAny values are equal if their TypeCodes are equivalent and, recursively, all component DynAnys have equal values. The current position of the two DynAnys being compared has no effect on the result of equal.

Specified by:
equal in interface DynAnyOperations
Returns:
true of the DynAnys are equal, false otherwise

destroy

public void destroy()
Destroys a DynAny object. This operation frees any resources used to represent the data value associated with a DynAny object. It must be invoked on references obtained from one of the creation operations on the ORB interface or on a reference returned by DynAny.copy() to avoid resource leaks. Invoking destroy on component DynAny objects (for example, on objects returned by the current_component operation) does nothing. Destruction of a DynAny object implies destruction of all DynAny objects obtained from it. That is, references to components of a destroyed DynAny become invalid. Invocations on such references raise OBJECT_NOT_EXIST. It is possible to manipulate a component of a DynAny beyond the life time of the DynAny from which the component was obtained by making a copy of the component with the copy operation before destroying the DynAny from which the component was obtained.

Specified by:
destroy in interface DynAnyOperations

copy

public DynAny copy()
Creates a new DynAny object whose value is a deep copy of the DynAny on which it is invoked. The operation is polymorphic, that is, invoking it on one of the types derived from DynAny, such as DynStruct, creates the derived type but returns its reference as the DynAny base type.

Specified by:
copy in interface DynAnyOperations
Returns:
a deep copy of the DynAny object

insert_boolean

public void insert_boolean(boolean value)
                    throws TypeMismatch,
                           InvalidValue
Inserts a boolean value into the DynAny.

Specified by:
insert_boolean in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_octet

public void insert_octet(byte value)
                  throws TypeMismatch,
                         InvalidValue
Inserts a byte value into the DynAny. The IDL octet data type is mapped to the Java byte data type.

Specified by:
insert_octet in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_char

public void insert_char(char value)
                 throws TypeMismatch,
                        InvalidValue
Inserts a char value into the DynAny.

Specified by:
insert_char in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_short

public void insert_short(short value)
                  throws TypeMismatch,
                         InvalidValue
Inserts a short value into the DynAny.

Specified by:
insert_short in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_ushort

public void insert_ushort(short value)
                   throws TypeMismatch,
                          InvalidValue
Inserts a short value into the DynAny. The IDL ushort data type is mapped to the Java short data type.

Specified by:
insert_ushort in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_long

public void insert_long(int value)
                 throws TypeMismatch,
                        InvalidValue
Inserts an integer value into the DynAny. The IDL long data type is mapped to the Java int data type.

Specified by:
insert_long in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_ulong

public void insert_ulong(int value)
                  throws TypeMismatch,
                         InvalidValue
Inserts an integer value into the DynAny. The IDL ulong data type is mapped to the Java int data type.

Specified by:
insert_ulong in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_float

public void insert_float(float value)
                  throws TypeMismatch,
                         InvalidValue
Inserts a float value into the DynAny.

Specified by:
insert_float in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_double

public void insert_double(double value)
                   throws TypeMismatch,
                          InvalidValue
Inserts a double value into the DynAny.

Specified by:
insert_double in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_string

public void insert_string(String value)
                   throws TypeMismatch,
                          InvalidValue
Inserts a string value into the DynAny. Both bounded and unbounded strings are inserted using this method.

Specified by:
insert_string in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
InvalidValue - if the string inserted is longer than the bound of a bounded string
TypeMismatch - if called on a DynAny whose current component itself has components

insert_reference

public void insert_reference(Object value)
                      throws TypeMismatch,
                             InvalidValue
Inserts a reference to a CORBA object into the DynAny.

Specified by:
insert_reference in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_typecode

public void insert_typecode(TypeCode value)
                     throws TypeMismatch,
                            InvalidValue
Inserts a TypeCode object into the DynAny.

Specified by:
insert_typecode in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_longlong

public void insert_longlong(long value)
                     throws TypeMismatch,
                            InvalidValue
Inserts a long value into the DynAny. The IDL long long data type is mapped to the Java long data type.

Specified by:
insert_longlong in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_ulonglong

public void insert_ulonglong(long value)
                      throws TypeMismatch,
                             InvalidValue
Inserts a long value into the DynAny. The IDL unsigned long long data type is mapped to the Java long data type.

Specified by:
insert_ulonglong in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_wchar

public void insert_wchar(char value)
                  throws TypeMismatch,
                         InvalidValue
Inserts a char value into the DynAny. The IDL wchar data type is mapped to the Java char data type.

Specified by:
insert_wchar in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_wstring

public void insert_wstring(String value)
                    throws TypeMismatch,
                           InvalidValue
Inserts a string value into the DynAny. Both bounded and unbounded strings are inserted using this method.

Specified by:
insert_wstring in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
InvalidValue - if the string inserted is longer than the bound of a bounded string
TypeMismatch

insert_any

public void insert_any(Any value)
                throws TypeMismatch,
                       InvalidValue
Inserts an Any value into the Any represented by this DynAny.

Specified by:
insert_any in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_dyn_any

public void insert_dyn_any(DynAny value)
                    throws TypeMismatch,
                           InvalidValue
Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.

Specified by:
insert_dyn_any in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_val

public void insert_val(Serializable value)
                throws TypeMismatch,
                       InvalidValue
Inserts a reference to a Serializable object into this DynAny. The IDL ValueBase type is mapped to the Java Serializable type.

Specified by:
insert_val in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

get_boolean

public boolean get_boolean()
                    throws TypeMismatch,
                           InvalidValue
Extracts the boolean value from this DynAny.

Specified by:
get_boolean in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_octet

public byte get_octet()
               throws TypeMismatch,
                      InvalidValue
Extracts the byte value from this DynAny. The IDL octet data type is mapped to the Java byte data type.

Specified by:
get_octet in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_char

public char get_char()
              throws TypeMismatch,
                     InvalidValue
Extracts the char value from this DynAny.

Specified by:
get_char in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_short

public short get_short()
                throws TypeMismatch,
                       InvalidValue
Extracts the short value from this DynAny.

Specified by:
get_short in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_ushort

public short get_ushort()
                 throws TypeMismatch,
                        InvalidValue
Extracts the short value from this DynAny. The IDL ushort data type is mapped to the Java short data type.

Specified by:
get_ushort in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_long

public int get_long()
             throws TypeMismatch,
                    InvalidValue
Extracts the integer value from this DynAny. The IDL long data type is mapped to the Java int data type.

Specified by:
get_long in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_ulong

public int get_ulong()
              throws TypeMismatch,
                     InvalidValue
Extracts the integer value from this DynAny. The IDL ulong data type is mapped to the Java int data type.

Specified by:
get_ulong in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_float

public float get_float()
                throws TypeMismatch,
                       InvalidValue
Extracts the float value from this DynAny.

Specified by:
get_float in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_double

public double get_double()
                  throws TypeMismatch,
                         InvalidValue
Extracts the double value from this DynAny.

Specified by:
get_double in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_string

public String get_string()
                  throws TypeMismatch,
                         InvalidValue
Extracts the string value from this DynAny. Both bounded and unbounded strings are extracted using this method.

Specified by:
get_string in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_reference

public Object get_reference()
                     throws TypeMismatch,
                            InvalidValue
Extracts the reference to a CORBA Object from this DynAny.

Specified by:
get_reference in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_typecode

public TypeCode get_typecode()
                      throws TypeMismatch,
                             InvalidValue
Extracts the TypeCode object from this DynAny.

Specified by:
get_typecode in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_longlong

public long get_longlong()
                  throws TypeMismatch,
                         InvalidValue
Extracts the long value from this DynAny. The IDL long long data type is mapped to the Java long data type.

Specified by:
get_longlong in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_ulonglong

public long get_ulonglong()
                   throws TypeMismatch,
                          InvalidValue
Extracts the long value from this DynAny. The IDL unsigned long long data type is mapped to the Java long data type.

Specified by:
get_ulonglong in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_wchar

public char get_wchar()
               throws TypeMismatch,
                      InvalidValue
Extracts the long value from this DynAny. The IDL wchar data type is mapped to the Java char data type.

Specified by:
get_wchar in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_wstring

public String get_wstring()
                   throws TypeMismatch,
                          InvalidValue
Extracts the string value from this DynAny. Both bounded and unbounded strings are extracted using this method.

Specified by:
get_wstring in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue

get_any

public Any get_any()
            throws TypeMismatch,
                   InvalidValue
Extracts an Any value contained in the Any represented by this DynAny.

Specified by:
get_any in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_dyn_any

public DynAny get_dyn_any()
                   throws TypeMismatch,
                          InvalidValue
Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.

Specified by:
get_dyn_any in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_val

public Serializable get_val()
                     throws TypeMismatch,
                            InvalidValue
Extracts a Serializable object from this DynAny. The IDL ValueBase type is mapped to the Java Serializable type.

Specified by:
get_val in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

seek

public boolean seek(int index)
Sets the current position to index. The current position is indexed 0 to n-1, that is, index zero corresponds to the first component. The operation returns true if the resulting current position indicates a component of the DynAny and false if index indicates a position that does not correspond to a component. Calling seek with a negative index is legal. It sets the current position to -1 to indicate no component and returns false. Passing a non-negative index value for a DynAny that does not have a component at the corresponding position sets the current position to -1 and returns false.

Specified by:
seek in interface DynAnyOperations

rewind

public void rewind()
Is equivalent to seek(0).

Specified by:
rewind in interface DynAnyOperations

next

public boolean next()
Advances the current position to the next component. The operation returns true while the resulting current position indicates a component, false otherwise. A false return value leaves the current position at -1. Invoking next on a DynAny without components leaves the current position at -1 and returns false.

Specified by:
next in interface DynAnyOperations

component_count

public int component_count()
Returns the number of components of a DynAny. For a DynAny without components, it returns zero. The operation only counts the components at the top level. For example, if component_count is invoked on a DynStruct with a single member, the return value is 1, irrespective of the type of the member.
  • For sequences, the operation returns the current number of elements.
  • For structures, exceptions, and value types, the operation returns the number of members.
  • For arrays, the operation returns the number of elements.
  • For unions, the operation returns 2 if the discriminator indicates that a named member is active, otherwise, it returns 1.
  • For DynFixed and DynEnum, the operation returns zero.

Specified by:
component_count in interface DynAnyOperations

current_component

public DynAny current_component()
                         throws TypeMismatch
Returns the DynAny for the component at the current position. It does not advance the current position, so repeated calls to current_component without an intervening call to rewind, next, or seek return the same component. The returned DynAny object reference can be used to get/set the value of the current component. If the current component represents a complex type, the returned reference can be narrowed based on the TypeCode to get the interface corresponding to the to the complex type. Calling current_component on a DynAny that cannot have components, such as a DynEnum or an empty exception, raises TypeMismatch. Calling current_component on a DynAny whose current position is -1 returns a nil reference. The iteration operations, together with current_component, can be used to dynamically compose an any value. After creating a dynamic any, such as a DynStruct, current_component and next can be used to initialize all the components of the value. Once the dynamic value is completely initialized, to_any creates the corresponding any value.

Specified by:
current_component in interface DynAnyOperations
Throws:
TypeMismatch - If called on a DynAny that cannot have components, such as a DynEnum or an empty exception

_ids

public String[] _ids()
Description copied from class: ObjectImpl
Retrieves a string array containing the repository identifiers supported by this ObjectImpl object. For example, for a stub, this method returns information about all the interfaces supported by the stub.

Specified by:
_ids in class ObjectImpl
Returns:
the array of all repository identifiers supported by this ObjectImpl instance
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


_DynStructStub (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Class _DynStructStub

java.lang.Object
    extended by org.omg.CORBA.portable.ObjectImpl
        extended by org.omg.DynamicAny._DynStructStub
All Implemented Interfaces:
DynAny, DynAnyOperations, DynStruct, DynStructOperations, IDLEntity, Object, Serializable
public class _DynStructStub
extends ObjectImpl
implements DynStruct

DynStruct objects support the manipulation of IDL struct and exception values. Members of the exceptions are handled in the same way as members of a struct.

Field Summary
static Class _opsClass
Constructor Summary
_DynStructStub()
Method Summary
 String[] _ids()
Retrieves a string array containing the repository identifiers supported by this ObjectImpl object.
 void assign(DynAny dyn_any)
Initializes the value associated with a DynAny object with the value associated with another DynAny object.
 int component_count()
Returns the number of components of a DynAny.
 DynAny copy()
Creates a new DynAny object whose value is a deep copy of the DynAny on which it is invoked.
 DynAny current_component()
Returns the DynAny for the component at the current position.
 TCKind current_member_kind()
Returns the TCKind associated with the member at the current position.
 String current_member_name()
Returns the name of the member at the current position.
 void destroy()
Destroys a DynAny object.
 boolean equal(DynAny dyn_any)
Compares two DynAny values for equality.
 void from_any(Any value)
Initializes the value associated with a DynAny object with the value contained in an any.
 Any get_any()
Extracts an Any value contained in the Any represented by this DynAny.
 boolean get_boolean()
Extracts the boolean value from this DynAny.
 char get_char()
Extracts the char value from this DynAny.
 double get_double()
Extracts the double value from this DynAny.
 DynAny get_dyn_any()
Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.
 float get_float()
Extracts the float value from this DynAny.
 int get_long()
Extracts the integer value from this DynAny.
 long get_longlong()
Extracts the long value from this DynAny.
 NameDynAnyPair[] get_members_as_dyn_any()
Returns a sequence of NameDynAnyPairs describing the name and the value of each member in the struct associated with a DynStruct object.
 NameValuePair[] get_members()
Returns a sequence of NameValuePairs describing the name and the value of each member in the struct associated with a DynStruct object.
 byte get_octet()
Extracts the byte value from this DynAny.
 Object get_reference()
Extracts the reference to a CORBA Object from this DynAny.
 short get_short()
Extracts the short value from this DynAny.
 String get_string()
Extracts the string value from this DynAny.
 TypeCode get_typecode()
Extracts the TypeCode object from this DynAny.
 int get_ulong()
Extracts the integer value from this DynAny.
 long get_ulonglong()
Extracts the long value from this DynAny.
 short get_ushort()
Extracts the short value from this DynAny.
 Serializable get_val()
Extracts a Serializable object from this DynAny.
 char get_wchar()
Extracts the long value from this DynAny.
 String get_wstring()
Extracts the string value from this DynAny.
 void insert_any(Any value)
Inserts an Any value into the Any represented by this DynAny.
 void insert_boolean(boolean value)
Inserts a boolean value into the DynAny.
 void insert_char(char value)
Inserts a char value into the DynAny.
 void insert_double(double value)
Inserts a double value into the DynAny.
 void insert_dyn_any(DynAny value)
Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.
 void insert_float(float value)
Inserts a float value into the DynAny.
 void insert_long(int value)
Inserts an integer value into the DynAny.
 void insert_longlong(long value)
Inserts a long value into the DynAny.
 void insert_octet(byte value)
Inserts a byte value into the DynAny.
 void insert_reference(Object value)
Inserts a reference to a CORBA object into the DynAny.
 void insert_short(short value)
Inserts a short value into the DynAny.
 void insert_string(String value)
Inserts a string value into the DynAny.
 void insert_typecode(TypeCode value)
Inserts a TypeCode object into the DynAny.
 void insert_ulong(int value)
Inserts an integer value into the DynAny.
 void insert_ulonglong(long value)
Inserts a long value into the DynAny.
 void insert_ushort(short value)
Inserts a short value into the DynAny.
 void insert_val(Serializable value)
Inserts a reference to a Serializable object into this DynAny.
 void insert_wchar(char value)
Inserts a char value into the DynAny.
 void insert_wstring(String value)
Inserts a string value into the DynAny.
 boolean next()
Advances the current position to the next component.
 void rewind()
Is equivalent to seek(0).
 boolean seek(int index)
Sets the current position to index.
 void set_members_as_dyn_any(NameDynAnyPair[] value)
Initializes the struct data value associated with a DynStruct object from a sequence of NameDynAnyPairs.
 void set_members(NameValuePair[] value)
Initializes the struct data value associated with a DynStruct object from a sequence of NameValuePairs.
 Any to_any()
Creates an any value from a DynAny object.
 TypeCode type()
Returns the TypeCode associated with this DynAny object.
Methods inherited from class org.omg.CORBA.portable.ObjectImpl
_create_request, _create_request, _duplicate, _get_delegate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _invoke, _is_a, _is_equivalent, _is_local, _non_existent, _orb, _release, _releaseReply, _request, _request, _servant_postinvoke, _servant_preinvoke, _set_delegate, _set_policy_override, equals, hashCode, toString
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Field Detail

_opsClass

public static final Class _opsClass
Constructor Detail

_DynStructStub

public _DynStructStub()
Method Detail

current_member_name

public String current_member_name()
                           throws TypeMismatch,
                                  InvalidValue
Returns the name of the member at the current position. This operation may return an empty string since the TypeCode of the value being manipulated may not contain the names of members.

Specified by:
current_member_name in interface DynStructOperations
Throws:
TypeMismatch - if the DynStruct represents an empty exception.
InvalidValue - if the current position does not indicate a member

current_member_kind

public TCKind current_member_kind()
                           throws TypeMismatch,
                                  InvalidValue
Returns the TCKind associated with the member at the current position.

Specified by:
current_member_kind in interface DynStructOperations
Throws:
TypeMismatch - if the DynStruct represents an empty exception.
InvalidValue - if the current position does not indicate a member

get_members

public NameValuePair[] get_members()
Returns a sequence of NameValuePairs describing the name and the value of each member in the struct associated with a DynStruct object. The sequence contains members in the same order as the declaration order of members as indicated by the DynStruct's TypeCode. The current position is not affected. The member names in the returned sequence will be empty strings if the DynStruct's TypeCode does not contain member names.

Specified by:
get_members in interface DynStructOperations

set_members

public void set_members(NameValuePair[] value)
                 throws TypeMismatch,
                        InvalidValue
Initializes the struct data value associated with a DynStruct object from a sequence of NameValuePairs. The operation sets the current position to zero if the passed sequences has non-zero length. Otherwise, if an empty sequence is passed, the current position is set to -1.

Members must appear in the NameValuePairs in the order in which they appear in the IDL specification of the struct as indicated by the DynStruct's TypeCode or they must be empty strings. The operation makes no attempt to assign member values based on member names.

Specified by:
set_members in interface DynStructOperations
Throws:
TypeMismatch - if the member names supplied in the passed sequence do not match the corresponding member name in the DynStruct's TypeCode and they are not empty strings
InvalidValue - if the passed sequence has a number of elements that disagrees with the number of members as indicated by the DynStruct's TypeCode

get_members_as_dyn_any

public NameDynAnyPair[] get_members_as_dyn_any()
Returns a sequence of NameDynAnyPairs describing the name and the value of each member in the struct associated with a DynStruct object. The sequence contains members in the same order as the declaration order of members as indicated by the DynStruct's TypeCode. The current position is not affected. The member names in the returned sequence will be empty strings if the DynStruct's TypeCode does not contain member names.

Specified by:
get_members_as_dyn_any in interface DynStructOperations

set_members_as_dyn_any

public void set_members_as_dyn_any(NameDynAnyPair[] value)
                            throws TypeMismatch,
                                   InvalidValue
Initializes the struct data value associated with a DynStruct object from a sequence of NameDynAnyPairs. The operation sets the current position to zero if the passed sequences has non-zero length. Otherwise, if an empty sequence is passed, the current position is set to -1.

Members must appear in the NameDynAnyPairs in the order in which they appear in the IDL specification of the struct as indicated by the DynStruct's TypeCode or they must be empty strings. The operation makes no attempt to assign member values based on member names.

Specified by:
set_members_as_dyn_any in interface DynStructOperations
Throws:
TypeMismatch - if the member names supplied in the passed sequence do not match the corresponding member name in the DynStruct's TypeCode and they are not empty strings
InvalidValue - if the passed sequence has a number of elements that disagrees with the number of members as indicated by the DynStruct's TypeCode

type

public TypeCode type()
Returns the TypeCode associated with this DynAny object. A DynAny object is created with a TypeCode value assigned to it. This TypeCode value determines the type of the value handled through the DynAny object. Note that the TypeCode associated with a DynAny object is initialized at the time the DynAny is created and cannot be changed during lifetime of the DynAny object.

Specified by:
type in interface DynAnyOperations
Returns:
The TypeCode associated with this DynAny object

assign

public void assign(DynAny dyn_any)
            throws TypeMismatch
Initializes the value associated with a DynAny object with the value associated with another DynAny object. The current position of the target DynAny is set to zero for values that have components and to -1 for values that do not have components.

Specified by:
assign in interface DynAnyOperations
Parameters:
dyn_any -
Throws:
TypeMismatch - if the type of the passed DynAny is not equivalent to the type of target DynAny

from_any

public void from_any(Any value)
              throws TypeMismatch,
                     InvalidValue
Initializes the value associated with a DynAny object with the value contained in an any. The current position of the target DynAny is set to zero for values that have components and to -1 for values that do not have components.

Specified by:
from_any in interface DynAnyOperations
Throws:
TypeMismatch - if the type of the passed Any is not equivalent to the type of target DynAny
InvalidValue - if the passed Any does not contain a legal value (such as a null string)

to_any

public Any to_any()
Creates an any value from a DynAny object. A copy of the TypeCode associated with the DynAny object is assigned to the resulting any. The value associated with the DynAny object is copied into the any.

Specified by:
to_any in interface DynAnyOperations
Returns:
a new Any object with the same value and TypeCode

equal

public boolean equal(DynAny dyn_any)
Compares two DynAny values for equality. Two DynAny values are equal if their TypeCodes are equivalent and, recursively, all component DynAnys have equal values. The current position of the two DynAnys being compared has no effect on the result of equal.

Specified by:
equal in interface DynAnyOperations
Returns:
true of the DynAnys are equal, false otherwise

destroy

public void destroy()
Destroys a DynAny object. This operation frees any resources used to represent the data value associated with a DynAny object. It must be invoked on references obtained from one of the creation operations on the ORB interface or on a reference returned by DynAny.copy() to avoid resource leaks. Invoking destroy on component DynAny objects (for example, on objects returned by the current_component operation) does nothing. Destruction of a DynAny object implies destruction of all DynAny objects obtained from it. That is, references to components of a destroyed DynAny become invalid. Invocations on such references raise OBJECT_NOT_EXIST. It is possible to manipulate a component of a DynAny beyond the life time of the DynAny from which the component was obtained by making a copy of the component with the copy operation before destroying the DynAny from which the component was obtained.

Specified by:
destroy in interface DynAnyOperations

copy

public DynAny copy()
Creates a new DynAny object whose value is a deep copy of the DynAny on which it is invoked. The operation is polymorphic, that is, invoking it on one of the types derived from DynAny, such as DynStruct, creates the derived type but returns its reference as the DynAny base type.

Specified by:
copy in interface DynAnyOperations
Returns:
a deep copy of the DynAny object

insert_boolean

public void insert_boolean(boolean value)
                    throws TypeMismatch,
                           InvalidValue
Inserts a boolean value into the DynAny.

Specified by:
insert_boolean in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_octet

public void insert_octet(byte value)
                  throws TypeMismatch,
                         InvalidValue
Inserts a byte value into the DynAny. The IDL octet data type is mapped to the Java byte data type.

Specified by:
insert_octet in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_char

public void insert_char(char value)
                 throws TypeMismatch,
                        InvalidValue
Inserts a char value into the DynAny.

Specified by:
insert_char in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_short

public void insert_short(short value)
                  throws TypeMismatch,
                         InvalidValue
Inserts a short value into the DynAny.

Specified by:
insert_short in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_ushort

public void insert_ushort(short value)
                   throws TypeMismatch,
                          InvalidValue
Inserts a short value into the DynAny. The IDL ushort data type is mapped to the Java short data type.

Specified by:
insert_ushort in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_long

public void insert_long(int value)
                 throws TypeMismatch,
                        InvalidValue
Inserts an integer value into the DynAny. The IDL long data type is mapped to the Java int data type.

Specified by:
insert_long in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_ulong

public void insert_ulong(int value)
                  throws TypeMismatch,
                         InvalidValue
Inserts an integer value into the DynAny. The IDL ulong data type is mapped to the Java int data type.

Specified by:
insert_ulong in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_float

public void insert_float(float value)
                  throws TypeMismatch,
                         InvalidValue
Inserts a float value into the DynAny.

Specified by:
insert_float in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_double

public void insert_double(double value)
                   throws TypeMismatch,
                          InvalidValue
Inserts a double value into the DynAny.

Specified by:
insert_double in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_string

public void insert_string(String value)
                   throws TypeMismatch,
                          InvalidValue
Inserts a string value into the DynAny. Both bounded and unbounded strings are inserted using this method.

Specified by:
insert_string in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
InvalidValue - if the string inserted is longer than the bound of a bounded string
TypeMismatch - if called on a DynAny whose current component itself has components

insert_reference

public void insert_reference(Object value)
                      throws TypeMismatch,
                             InvalidValue
Inserts a reference to a CORBA object into the DynAny.

Specified by:
insert_reference in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_typecode

public void insert_typecode(TypeCode value)
                     throws TypeMismatch,
                            InvalidValue
Inserts a TypeCode object into the DynAny.

Specified by:
insert_typecode in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_longlong

public void insert_longlong(long value)
                     throws TypeMismatch,
                            InvalidValue
Inserts a long value into the DynAny. The IDL long long data type is mapped to the Java long data type.

Specified by:
insert_longlong in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_ulonglong

public void insert_ulonglong(long value)
                      throws TypeMismatch,
                             InvalidValue
Inserts a long value into the DynAny. The IDL unsigned long long data type is mapped to the Java long data type.

Specified by:
insert_ulonglong in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_wchar

public void insert_wchar(char value)
                  throws TypeMismatch,
                         InvalidValue
Inserts a char value into the DynAny. The IDL wchar data type is mapped to the Java char data type.

Specified by:
insert_wchar in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_wstring

public void insert_wstring(String value)
                    throws TypeMismatch,
                           InvalidValue
Inserts a string value into the DynAny. Both bounded and unbounded strings are inserted using this method.

Specified by:
insert_wstring in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
InvalidValue - if the string inserted is longer than the bound of a bounded string
TypeMismatch

insert_any

public void insert_any(Any value)
                throws TypeMismatch,
                       InvalidValue
Inserts an Any value into the Any represented by this DynAny.

Specified by:
insert_any in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_dyn_any

public void insert_dyn_any(DynAny value)
                    throws TypeMismatch,
                           InvalidValue
Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.

Specified by:
insert_dyn_any in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_val

public void insert_val(Serializable value)
                throws TypeMismatch,
                       InvalidValue
Inserts a reference to a Serializable object into this DynAny. The IDL ValueBase type is mapped to the Java Serializable type.

Specified by:
insert_val in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

get_boolean

public boolean get_boolean()
                    throws TypeMismatch,
                           InvalidValue
Extracts the boolean value from this DynAny.

Specified by:
get_boolean in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_octet

public byte get_octet()
               throws TypeMismatch,
                      InvalidValue
Extracts the byte value from this DynAny. The IDL octet data type is mapped to the Java byte data type.

Specified by:
get_octet in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_char

public char get_char()
              throws TypeMismatch,
                     InvalidValue
Extracts the char value from this DynAny.

Specified by:
get_char in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_short

public short get_short()
                throws TypeMismatch,
                       InvalidValue
Extracts the short value from this DynAny.

Specified by:
get_short in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_ushort

public short get_ushort()
                 throws TypeMismatch,
                        InvalidValue
Extracts the short value from this DynAny. The IDL ushort data type is mapped to the Java short data type.

Specified by:
get_ushort in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_long

public int get_long()
             throws TypeMismatch,
                    InvalidValue
Extracts the integer value from this DynAny. The IDL long data type is mapped to the Java int data type.

Specified by:
get_long in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_ulong

public int get_ulong()
              throws TypeMismatch,
                     InvalidValue
Extracts the integer value from this DynAny. The IDL ulong data type is mapped to the Java int data type.

Specified by:
get_ulong in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_float

public float get_float()
                throws TypeMismatch,
                       InvalidValue
Extracts the float value from this DynAny.

Specified by:
get_float in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_double

public double get_double()
                  throws TypeMismatch,
                         InvalidValue
Extracts the double value from this DynAny.

Specified by:
get_double in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_string

public String get_string()
                  throws TypeMismatch,
                         InvalidValue
Extracts the string value from this DynAny. Both bounded and unbounded strings are extracted using this method.

Specified by:
get_string in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_reference

public Object get_reference()
                     throws TypeMismatch,
                            InvalidValue
Extracts the reference to a CORBA Object from this DynAny.

Specified by:
get_reference in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_typecode

public TypeCode get_typecode()
                      throws TypeMismatch,
                             InvalidValue
Extracts the TypeCode object from this DynAny.

Specified by:
get_typecode in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_longlong

public long get_longlong()
                  throws TypeMismatch,
                         InvalidValue
Extracts the long value from this DynAny. The IDL long long data type is mapped to the Java long data type.

Specified by:
get_longlong in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_ulonglong

public long get_ulonglong()
                   throws TypeMismatch,
                          InvalidValue
Extracts the long value from this DynAny. The IDL unsigned long long data type is mapped to the Java long data type.

Specified by:
get_ulonglong in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_wchar

public char get_wchar()
               throws TypeMismatch,
                      InvalidValue
Extracts the long value from this DynAny. The IDL wchar data type is mapped to the Java char data type.

Specified by:
get_wchar in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_wstring

public String get_wstring()
                   throws TypeMismatch,
                          InvalidValue
Extracts the string value from this DynAny. Both bounded and unbounded strings are extracted using this method.

Specified by:
get_wstring in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue

get_any

public Any get_any()
            throws TypeMismatch,
                   InvalidValue
Extracts an Any value contained in the Any represented by this DynAny.

Specified by:
get_any in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_dyn_any

public DynAny get_dyn_any()
                   throws TypeMismatch,
                          InvalidValue
Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.

Specified by:
get_dyn_any in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_val

public Serializable get_val()
                     throws TypeMismatch,
                            InvalidValue
Extracts a Serializable object from this DynAny. The IDL ValueBase type is mapped to the Java Serializable type.

Specified by:
get_val in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

seek

public boolean seek(int index)
Sets the current position to index. The current position is indexed 0 to n-1, that is, index zero corresponds to the first component. The operation returns true if the resulting current position indicates a component of the DynAny and false if index indicates a position that does not correspond to a component. Calling seek with a negative index is legal. It sets the current position to -1 to indicate no component and returns false. Passing a non-negative index value for a DynAny that does not have a component at the corresponding position sets the current position to -1 and returns false.

Specified by:
seek in interface DynAnyOperations

rewind

public void rewind()
Is equivalent to seek(0).

Specified by:
rewind in interface DynAnyOperations

next

public boolean next()
Advances the current position to the next component. The operation returns true while the resulting current position indicates a component, false otherwise. A false return value leaves the current position at -1. Invoking next on a DynAny without components leaves the current position at -1 and returns false.

Specified by:
next in interface DynAnyOperations

component_count

public int component_count()
Returns the number of components of a DynAny. For a DynAny without components, it returns zero. The operation only counts the components at the top level. For example, if component_count is invoked on a DynStruct with a single member, the return value is 1, irrespective of the type of the member.
  • For sequences, the operation returns the current number of elements.
  • For structures, exceptions, and value types, the operation returns the number of members.
  • For arrays, the operation returns the number of elements.
  • For unions, the operation returns 2 if the discriminator indicates that a named member is active, otherwise, it returns 1.
  • For DynFixed and DynEnum, the operation returns zero.

Specified by:
component_count in interface DynAnyOperations

current_component

public DynAny current_component()
                         throws TypeMismatch
Returns the DynAny for the component at the current position. It does not advance the current position, so repeated calls to current_component without an intervening call to rewind, next, or seek return the same component. The returned DynAny object reference can be used to get/set the value of the current component. If the current component represents a complex type, the returned reference can be narrowed based on the TypeCode to get the interface corresponding to the to the complex type. Calling current_component on a DynAny that cannot have components, such as a DynEnum or an empty exception, raises TypeMismatch. Calling current_component on a DynAny whose current position is -1 returns a nil reference. The iteration operations, together with current_component, can be used to dynamically compose an any value. After creating a dynamic any, such as a DynStruct, current_component and next can be used to initialize all the components of the value. Once the dynamic value is completely initialized, to_any creates the corresponding any value.

Specified by:
current_component in interface DynAnyOperations
Throws:
TypeMismatch - If called on a DynAny that cannot have components, such as a DynEnum or an empty exception

_ids

public String[] _ids()
Description copied from class: ObjectImpl
Retrieves a string array containing the repository identifiers supported by this ObjectImpl object. For example, for a stub, this method returns information about all the interfaces supported by the stub.

Specified by:
_ids in class ObjectImpl
Returns:
the array of all repository identifiers supported by this ObjectImpl instance
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


_DynUnionStub (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Class _DynUnionStub

java.lang.Object
    extended by org.omg.CORBA.portable.ObjectImpl
        extended by org.omg.DynamicAny._DynUnionStub
All Implemented Interfaces:
DynAny, DynAnyOperations, DynUnion, DynUnionOperations, IDLEntity, Object, Serializable
public class _DynUnionStub
extends ObjectImpl
implements DynUnion

DynUnion objects support the manipulation of IDL unions. A union can have only two valid current positions:

  • zero, which denotes the discriminator
  • one, which denotes the active member
The component_count value for a union depends on the current discriminator: it is 2 for a union whose discriminator indicates a named member, and 1 otherwise.

Field Summary
static Class _opsClass
Constructor Summary
_DynUnionStub()
Method Summary
 String[] _ids()
Retrieves a string array containing the repository identifiers supported by this ObjectImpl object.
 void assign(DynAny dyn_any)
Initializes the value associated with a DynAny object with the value associated with another DynAny object.
 int component_count()
Returns the number of components of a DynAny.
 DynAny copy()
Creates a new DynAny object whose value is a deep copy of the DynAny on which it is invoked.
 DynAny current_component()
Returns the DynAny for the component at the current position.
 void destroy()
Destroys a DynAny object.
 TCKind discriminator_kind()
Returns the TCKind value of the discriminators TypeCode.
 boolean equal(DynAny dyn_any)
Compares two DynAny values for equality.
 void from_any(Any value)
Initializes the value associated with a DynAny object with the value contained in an any.
 Any get_any()
Extracts an Any value contained in the Any represented by this DynAny.
 boolean get_boolean()
Extracts the boolean value from this DynAny.
 char get_char()
Extracts the char value from this DynAny.
 DynAny get_discriminator()
Returns the current discriminator value.
 double get_double()
Extracts the double value from this DynAny.
 DynAny get_dyn_any()
Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.
 float get_float()
Extracts the float value from this DynAny.
 int get_long()
Extracts the integer value from this DynAny.
 long get_longlong()
Extracts the long value from this DynAny.
 byte get_octet()
Extracts the byte value from this DynAny.
 Object get_reference()
Extracts the reference to a CORBA Object from this DynAny.
 short get_short()
Extracts the short value from this DynAny.
 String get_string()
Extracts the string value from this DynAny.
 TypeCode get_typecode()
Extracts the TypeCode object from this DynAny.
 int get_ulong()
Extracts the integer value from this DynAny.
 long get_ulonglong()
Extracts the long value from this DynAny.
 short get_ushort()
Extracts the short value from this DynAny.
 Serializable get_val()
Extracts a Serializable object from this DynAny.
 char get_wchar()
Extracts the long value from this DynAny.
 String get_wstring()
Extracts the string value from this DynAny.
 boolean has_no_active_member()
Returns true if the union has no active member, that is, the unions value consists solely of its discriminator because the discriminator has a value that is not listed as an explicit case label.
 void insert_any(Any value)
Inserts an Any value into the Any represented by this DynAny.
 void insert_boolean(boolean value)
Inserts a boolean value into the DynAny.
 void insert_char(char value)
Inserts a char value into the DynAny.
 void insert_double(double value)
Inserts a double value into the DynAny.
 void insert_dyn_any(DynAny value)
Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.
 void insert_float(float value)
Inserts a float value into the DynAny.
 void insert_long(int value)
Inserts an integer value into the DynAny.
 void insert_longlong(long value)
Inserts a long value into the DynAny.
 void insert_octet(byte value)
Inserts a byte value into the DynAny.
 void insert_reference(Object value)
Inserts a reference to a CORBA object into the DynAny.
 void insert_short(short value)
Inserts a short value into the DynAny.
 void insert_string(String value)
Inserts a string value into the DynAny.
 void insert_typecode(TypeCode value)
Inserts a TypeCode object into the DynAny.
 void insert_ulong(int value)
Inserts an integer value into the DynAny.
 void insert_ulonglong(long value)
Inserts a long value into the DynAny.
 void insert_ushort(short value)
Inserts a short value into the DynAny.
 void insert_val(Serializable value)
Inserts a reference to a Serializable object into this DynAny.
 void insert_wchar(char value)
Inserts a char value into the DynAny.
 void insert_wstring(String value)
Inserts a string value into the DynAny.
 TCKind member_kind()
Returns the TCKind value of the currently active members TypeCode.
 String member_name()
Returns the name of the currently active member.
 DynAny member()
Returns the currently active member.
 boolean next()
Advances the current position to the next component.
 void rewind()
Is equivalent to seek(0).
 boolean seek(int index)
Sets the current position to index.
 void set_discriminator(DynAny d)
Sets the discriminator of the DynUnion to the specified value.
 void set_to_default_member()
Sets the discriminator to a value that is consistent with the value of the default case of a union.
 void set_to_no_active_member()
Sets the discriminator to a value that does not correspond to any of the unions case labels.
 Any to_any()
Creates an any value from a DynAny object.
 TypeCode type()
Returns the TypeCode associated with this DynAny object.
Methods inherited from class org.omg.CORBA.portable.ObjectImpl
_create_request, _create_request, _duplicate, _get_delegate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _invoke, _is_a, _is_equivalent, _is_local, _non_existent, _orb, _release, _releaseReply, _request, _request, _servant_postinvoke, _servant_preinvoke, _set_delegate, _set_policy_override, equals, hashCode, toString
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Field Detail

_opsClass

public static final Class _opsClass
Constructor Detail

_DynUnionStub

public _DynUnionStub()
Method Detail

get_discriminator

public DynAny get_discriminator()
Returns the current discriminator value.

Specified by:
get_discriminator in interface DynUnionOperations

set_discriminator

public void set_discriminator(DynAny d)
                       throws TypeMismatch
Sets the discriminator of the DynUnion to the specified value. Setting the discriminator to a value that is consistent with the currently active union member does not affect the currently active member. Setting the discriminator to a value that is inconsistent with the currently active member deactivates the member and activates the member that is consistent with the new discriminator value (if there is a member for that value) by initializing the member to its default value. Setting the discriminator of a union sets the current position to 0 if the discriminator value indicates a non-existent union member (has_no_active_member returns true in this case). Otherwise, if the discriminator value indicates a named union member, the current position is set to 1 (has_no_active_member returns false and component_count returns 2 in this case).

Specified by:
set_discriminator in interface DynUnionOperations
Throws:
TypeMismatch - if the TypeCode of the parameter is not equivalent to the TypeCode of the union?s discriminator

set_to_default_member

public void set_to_default_member()
                           throws TypeMismatch
Sets the discriminator to a value that is consistent with the value of the default case of a union. It sets the current position to zero and causes component_count to return 2.

Specified by:
set_to_default_member in interface DynUnionOperations
Throws:
TypeMismatch - if the union does not have an explicit default case

set_to_no_active_member

public void set_to_no_active_member()
                             throws TypeMismatch
Sets the discriminator to a value that does not correspond to any of the unions case labels. It sets the current position to zero and causes component_count to return 1.

Specified by:
set_to_no_active_member in interface DynUnionOperations
Throws:
TypeMismatch - if the union has an explicit default case or if it uses the entire range of discriminator values for explicit case labels

has_no_active_member

public boolean has_no_active_member()
Returns true if the union has no active member, that is, the unions value consists solely of its discriminator because the discriminator has a value that is not listed as an explicit case label. Calling this operation on a union that has a default case returns false. Calling this operation on a union that uses the entire range of discriminator values for explicit case labels returns false.

Specified by:
has_no_active_member in interface DynUnionOperations

discriminator_kind

public TCKind discriminator_kind()
Returns the TCKind value of the discriminators TypeCode.

Specified by:
discriminator_kind in interface DynUnionOperations

member_kind

public TCKind member_kind()
                   throws InvalidValue
Returns the TCKind value of the currently active members TypeCode.

Specified by:
member_kind in interface DynUnionOperations
Throws:
InvalidValue - if the union does not have a currently active member

member

public DynAny member()
              throws InvalidValue
Returns the currently active member. Note that the returned reference remains valid only for as long as the currently active member does not change. Using the returned reference beyond the life time of the currently active member raises OBJECT_NOT_EXIST.

Specified by:
member in interface DynUnionOperations
Throws:
InvalidValue - if the union has no active member

member_name

public String member_name()
                   throws InvalidValue
Returns the name of the currently active member. If the unions TypeCode does not contain a member name for the currently active member, the operation returns an empty string.

Specified by:
member_name in interface DynUnionOperations
Throws:
InvalidValue - if the union has no active member

type

public TypeCode type()
Returns the TypeCode associated with this DynAny object. A DynAny object is created with a TypeCode value assigned to it. This TypeCode value determines the type of the value handled through the DynAny object. Note that the TypeCode associated with a DynAny object is initialized at the time the DynAny is created and cannot be changed during lifetime of the DynAny object.

Specified by:
type in interface DynAnyOperations
Returns:
The TypeCode associated with this DynAny object

assign

public void assign(DynAny dyn_any)
            throws TypeMismatch
Initializes the value associated with a DynAny object with the value associated with another DynAny object. The current position of the target DynAny is set to zero for values that have components and to -1 for values that do not have components.

Specified by:
assign in interface DynAnyOperations
Parameters:
dyn_any -
Throws:
TypeMismatch - if the type of the passed DynAny is not equivalent to the type of target DynAny

from_any

public void from_any(Any value)
              throws TypeMismatch,
                     InvalidValue
Initializes the value associated with a DynAny object with the value contained in an any. The current position of the target DynAny is set to zero for values that have components and to -1 for values that do not have components.

Specified by:
from_any in interface DynAnyOperations
Throws:
TypeMismatch - if the type of the passed Any is not equivalent to the type of target DynAny
InvalidValue - if the passed Any does not contain a legal value (such as a null string)

to_any

public Any to_any()
Creates an any value from a DynAny object. A copy of the TypeCode associated with the DynAny object is assigned to the resulting any. The value associated with the DynAny object is copied into the any.

Specified by:
to_any in interface DynAnyOperations
Returns:
a new Any object with the same value and TypeCode

equal

public boolean equal(DynAny dyn_any)
Compares two DynAny values for equality. Two DynAny values are equal if their TypeCodes are equivalent and, recursively, all component DynAnys have equal values. The current position of the two DynAnys being compared has no effect on the result of equal.

Specified by:
equal in interface DynAnyOperations
Returns:
true of the DynAnys are equal, false otherwise

destroy

public void destroy()
Destroys a DynAny object. This operation frees any resources used to represent the data value associated with a DynAny object. It must be invoked on references obtained from one of the creation operations on the ORB interface or on a reference returned by DynAny.copy() to avoid resource leaks. Invoking destroy on component DynAny objects (for example, on objects returned by the current_component operation) does nothing. Destruction of a DynAny object implies destruction of all DynAny objects obtained from it. That is, references to components of a destroyed DynAny become invalid. Invocations on such references raise OBJECT_NOT_EXIST. It is possible to manipulate a component of a DynAny beyond the life time of the DynAny from which the component was obtained by making a copy of the component with the copy operation before destroying the DynAny from which the component was obtained.

Specified by:
destroy in interface DynAnyOperations

copy

public DynAny copy()
Creates a new DynAny object whose value is a deep copy of the DynAny on which it is invoked. The operation is polymorphic, that is, invoking it on one of the types derived from DynAny, such as DynStruct, creates the derived type but returns its reference as the DynAny base type.

Specified by:
copy in interface DynAnyOperations
Returns:
a deep copy of the DynAny object

insert_boolean

public void insert_boolean(boolean value)
                    throws TypeMismatch,
                           InvalidValue
Inserts a boolean value into the DynAny.

Specified by:
insert_boolean in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_octet

public void insert_octet(byte value)
                  throws TypeMismatch,
                         InvalidValue
Inserts a byte value into the DynAny. The IDL octet data type is mapped to the Java byte data type.

Specified by:
insert_octet in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_char

public void insert_char(char value)
                 throws TypeMismatch,
                        InvalidValue
Inserts a char value into the DynAny.

Specified by:
insert_char in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_short

public void insert_short(short value)
                  throws TypeMismatch,
                         InvalidValue
Inserts a short value into the DynAny.

Specified by:
insert_short in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_ushort

public void insert_ushort(short value)
                   throws TypeMismatch,
                          InvalidValue
Inserts a short value into the DynAny. The IDL ushort data type is mapped to the Java short data type.

Specified by:
insert_ushort in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_long

public void insert_long(int value)
                 throws TypeMismatch,
                        InvalidValue
Inserts an integer value into the DynAny. The IDL long data type is mapped to the Java int data type.

Specified by:
insert_long in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_ulong

public void insert_ulong(int value)
                  throws TypeMismatch,
                         InvalidValue
Inserts an integer value into the DynAny. The IDL ulong data type is mapped to the Java int data type.

Specified by:
insert_ulong in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_float

public void insert_float(float value)
                  throws TypeMismatch,
                         InvalidValue
Inserts a float value into the DynAny.

Specified by:
insert_float in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_double

public void insert_double(double value)
                   throws TypeMismatch,
                          InvalidValue
Inserts a double value into the DynAny.

Specified by:
insert_double in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_string

public void insert_string(String value)
                   throws TypeMismatch,
                          InvalidValue
Inserts a string value into the DynAny. Both bounded and unbounded strings are inserted using this method.

Specified by:
insert_string in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
InvalidValue - if the string inserted is longer than the bound of a bounded string
TypeMismatch - if called on a DynAny whose current component itself has components

insert_reference

public void insert_reference(Object value)
                      throws TypeMismatch,
                             InvalidValue
Inserts a reference to a CORBA object into the DynAny.

Specified by:
insert_reference in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_typecode

public void insert_typecode(TypeCode value)
                     throws TypeMismatch,
                            InvalidValue
Inserts a TypeCode object into the DynAny.

Specified by:
insert_typecode in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_longlong

public void insert_longlong(long value)
                     throws TypeMismatch,
                            InvalidValue
Inserts a long value into the DynAny. The IDL long long data type is mapped to the Java long data type.

Specified by:
insert_longlong in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_ulonglong

public void insert_ulonglong(long value)
                      throws TypeMismatch,
                             InvalidValue
Inserts a long value into the DynAny. The IDL unsigned long long data type is mapped to the Java long data type.

Specified by:
insert_ulonglong in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_wchar

public void insert_wchar(char value)
                  throws TypeMismatch,
                         InvalidValue
Inserts a char value into the DynAny. The IDL wchar data type is mapped to the Java char data type.

Specified by:
insert_wchar in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_wstring

public void insert_wstring(String value)
                    throws TypeMismatch,
                           InvalidValue
Inserts a string value into the DynAny. Both bounded and unbounded strings are inserted using this method.

Specified by:
insert_wstring in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
InvalidValue - if the string inserted is longer than the bound of a bounded string
TypeMismatch

insert_any

public void insert_any(Any value)
                throws TypeMismatch,
                       InvalidValue
Inserts an Any value into the Any represented by this DynAny.

Specified by:
insert_any in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_dyn_any

public void insert_dyn_any(DynAny value)
                    throws TypeMismatch,
                           InvalidValue
Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.

Specified by:
insert_dyn_any in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_val

public void insert_val(Serializable value)
                throws TypeMismatch,
                       InvalidValue
Inserts a reference to a Serializable object into this DynAny. The IDL ValueBase type is mapped to the Java Serializable type.

Specified by:
insert_val in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

get_boolean

public boolean get_boolean()
                    throws TypeMismatch,
                           InvalidValue
Extracts the boolean value from this DynAny.

Specified by:
get_boolean in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_octet

public byte get_octet()
               throws TypeMismatch,
                      InvalidValue
Extracts the byte value from this DynAny. The IDL octet data type is mapped to the Java byte data type.

Specified by:
get_octet in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_char

public char get_char()
              throws TypeMismatch,
                     InvalidValue
Extracts the char value from this DynAny.

Specified by:
get_char in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_short

public short get_short()
                throws TypeMismatch,
                       InvalidValue
Extracts the short value from this DynAny.

Specified by:
get_short in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_ushort

public short get_ushort()
                 throws TypeMismatch,
                        InvalidValue
Extracts the short value from this DynAny. The IDL ushort data type is mapped to the Java short data type.

Specified by:
get_ushort in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_long

public int get_long()
             throws TypeMismatch,
                    InvalidValue
Extracts the integer value from this DynAny. The IDL long data type is mapped to the Java int data type.

Specified by:
get_long in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_ulong

public int get_ulong()
              throws TypeMismatch,
                     InvalidValue
Extracts the integer value from this DynAny. The IDL ulong data type is mapped to the Java int data type.

Specified by:
get_ulong in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_float

public float get_float()
                throws TypeMismatch,
                       InvalidValue
Extracts the float value from this DynAny.

Specified by:
get_float in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_double

public double get_double()
                  throws TypeMismatch,
                         InvalidValue
Extracts the double value from this DynAny.

Specified by:
get_double in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_string

public String get_string()
                  throws TypeMismatch,
                         InvalidValue
Extracts the string value from this DynAny. Both bounded and unbounded strings are extracted using this method.

Specified by:
get_string in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_reference

public Object get_reference()
                     throws TypeMismatch,
                            InvalidValue
Extracts the reference to a CORBA Object from this DynAny.

Specified by:
get_reference in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_typecode

public TypeCode get_typecode()
                      throws TypeMismatch,
                             InvalidValue
Extracts the TypeCode object from this DynAny.

Specified by:
get_typecode in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_longlong

public long get_longlong()
                  throws TypeMismatch,
                         InvalidValue
Extracts the long value from this DynAny. The IDL long long data type is mapped to the Java long data type.

Specified by:
get_longlong in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_ulonglong

public long get_ulonglong()
                   throws TypeMismatch,
                          InvalidValue
Extracts the long value from this DynAny. The IDL unsigned long long data type is mapped to the Java long data type.

Specified by:
get_ulonglong in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_wchar

public char get_wchar()
               throws TypeMismatch,
                      InvalidValue
Extracts the long value from this DynAny. The IDL wchar data type is mapped to the Java char data type.

Specified by:
get_wchar in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_wstring

public String get_wstring()
                   throws TypeMismatch,
                          InvalidValue
Extracts the string value from this DynAny. Both bounded and unbounded strings are extracted using this method.

Specified by:
get_wstring in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue

get_any

public Any get_any()
            throws TypeMismatch,
                   InvalidValue
Extracts an Any value contained in the Any represented by this DynAny.

Specified by:
get_any in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_dyn_any

public DynAny get_dyn_any()
                   throws TypeMismatch,
                          InvalidValue
Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.

Specified by:
get_dyn_any in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_val

public Serializable get_val()
                     throws TypeMismatch,
                            InvalidValue
Extracts a Serializable object from this DynAny. The IDL ValueBase type is mapped to the Java Serializable type.

Specified by:
get_val in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

seek

public boolean seek(int index)
Sets the current position to index. The current position is indexed 0 to n-1, that is, index zero corresponds to the first component. The operation returns true if the resulting current position indicates a component of the DynAny and false if index indicates a position that does not correspond to a component. Calling seek with a negative index is legal. It sets the current position to -1 to indicate no component and returns false. Passing a non-negative index value for a DynAny that does not have a component at the corresponding position sets the current position to -1 and returns false.

Specified by:
seek in interface DynAnyOperations

rewind

public void rewind()
Is equivalent to seek(0).

Specified by:
rewind in interface DynAnyOperations

next

public boolean next()
Advances the current position to the next component. The operation returns true while the resulting current position indicates a component, false otherwise. A false return value leaves the current position at -1. Invoking next on a DynAny without components leaves the current position at -1 and returns false.

Specified by:
next in interface DynAnyOperations

component_count

public int component_count()
Returns the number of components of a DynAny. For a DynAny without components, it returns zero. The operation only counts the components at the top level. For example, if component_count is invoked on a DynStruct with a single member, the return value is 1, irrespective of the type of the member.
  • For sequences, the operation returns the current number of elements.
  • For structures, exceptions, and value types, the operation returns the number of members.
  • For arrays, the operation returns the number of elements.
  • For unions, the operation returns 2 if the discriminator indicates that a named member is active, otherwise, it returns 1.
  • For DynFixed and DynEnum, the operation returns zero.

Specified by:
component_count in interface DynAnyOperations

current_component

public DynAny current_component()
                         throws TypeMismatch
Returns the DynAny for the component at the current position. It does not advance the current position, so repeated calls to current_component without an intervening call to rewind, next, or seek return the same component. The returned DynAny object reference can be used to get/set the value of the current component. If the current component represents a complex type, the returned reference can be narrowed based on the TypeCode to get the interface corresponding to the to the complex type. Calling current_component on a DynAny that cannot have components, such as a DynEnum or an empty exception, raises TypeMismatch. Calling current_component on a DynAny whose current position is -1 returns a nil reference. The iteration operations, together with current_component, can be used to dynamically compose an any value. After creating a dynamic any, such as a DynStruct, current_component and next can be used to initialize all the components of the value. Once the dynamic value is completely initialized, to_any creates the corresponding any value.

Specified by:
current_component in interface DynAnyOperations
Throws:
TypeMismatch - If called on a DynAny that cannot have components, such as a DynEnum or an empty exception

_ids

public String[] _ids()
Description copied from class: ObjectImpl
Retrieves a string array containing the repository identifiers supported by this ObjectImpl object. For example, for a stub, this method returns information about all the interfaces supported by the stub.

Specified by:
_ids in class ObjectImpl
Returns:
the array of all repository identifiers supported by this ObjectImpl instance
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


_DynValueStub (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Class _DynValueStub

java.lang.Object
    extended by org.omg.CORBA.portable.ObjectImpl
        extended by org.omg.DynamicAny._DynValueStub
All Implemented Interfaces:
DynAny, DynAnyOperations, DynValue, DynValueCommon, DynValueCommonOperations, DynValueOperations, IDLEntity, Object, Serializable
public class _DynValueStub
extends ObjectImpl
implements DynValue

DynValue objects support the manipulation of IDL non-boxed value types. The DynValue interface can represent both null and non-null value types. For a DynValue representing a non-null value type, the DynValue's components comprise the public and private members of the value type, including those inherited from concrete base value types, in the order of definition. A DynValue representing a null value type has no components and a current position of -1.

Warning: Indiscriminantly changing the contents of private value type members can cause the value type implementation to break by violating internal constraints. Access to private members is provided to support such activities as ORB bridging and debugging and should not be used to arbitrarily violate the encapsulation of the value type.

Field Summary
static Class _opsClass
Constructor Summary
_DynValueStub()
Method Summary
 String[] _ids()
Retrieves a string array containing the repository identifiers supported by this ObjectImpl object.
 void assign(DynAny dyn_any)
Initializes the value associated with a DynAny object with the value associated with another DynAny object.
 int component_count()
Returns the number of components of a DynAny.
 DynAny copy()
Creates a new DynAny object whose value is a deep copy of the DynAny on which it is invoked.
 DynAny current_component()
Returns the DynAny for the component at the current position.
 TCKind current_member_kind()
Returns the TCKind associated with the member at the current position.
 String current_member_name()
Returns the name of the member at the current position.
 void destroy()
Destroys a DynAny object.
 boolean equal(DynAny dyn_any)
Compares two DynAny values for equality.
 void from_any(Any value)
Initializes the value associated with a DynAny object with the value contained in an any.
 Any get_any()
Extracts an Any value contained in the Any represented by this DynAny.
 boolean get_boolean()
Extracts the boolean value from this DynAny.
 char get_char()
Extracts the char value from this DynAny.
 double get_double()
Extracts the double value from this DynAny.
 DynAny get_dyn_any()
Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.
 float get_float()
Extracts the float value from this DynAny.
 int get_long()
Extracts the integer value from this DynAny.
 long get_longlong()
Extracts the long value from this DynAny.
 NameDynAnyPair[] get_members_as_dyn_any()
Returns a sequence of NameDynAnyPairs describing the name and the value of each member in the value type.
 NameValuePair[] get_members()
Returns a sequence of NameValuePairs describing the name and the value of each member in the value type.
 byte get_octet()
Extracts the byte value from this DynAny.
 Object get_reference()
Extracts the reference to a CORBA Object from this DynAny.
 short get_short()
Extracts the short value from this DynAny.
 String get_string()
Extracts the string value from this DynAny.
 TypeCode get_typecode()
Extracts the TypeCode object from this DynAny.
 int get_ulong()
Extracts the integer value from this DynAny.
 long get_ulonglong()
Extracts the long value from this DynAny.
 short get_ushort()
Extracts the short value from this DynAny.
 Serializable get_val()
Extracts a Serializable object from this DynAny.
 char get_wchar()
Extracts the long value from this DynAny.
 String get_wstring()
Extracts the string value from this DynAny.
 void insert_any(Any value)
Inserts an Any value into the Any represented by this DynAny.
 void insert_boolean(boolean value)
Inserts a boolean value into the DynAny.
 void insert_char(char value)
Inserts a char value into the DynAny.
 void insert_double(double value)
Inserts a double value into the DynAny.
 void insert_dyn_any(DynAny value)
Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.
 void insert_float(float value)
Inserts a float value into the DynAny.
 void insert_long(int value)
Inserts an integer value into the DynAny.
 void insert_longlong(long value)
Inserts a long value into the DynAny.
 void insert_octet(byte value)
Inserts a byte value into the DynAny.
 void insert_reference(Object value)
Inserts a reference to a CORBA object into the DynAny.
 void insert_short(short value)
Inserts a short value into the DynAny.
 void insert_string(String value)
Inserts a string value into the DynAny.
 void insert_typecode(TypeCode value)
Inserts a TypeCode object into the DynAny.
 void insert_ulong(int value)
Inserts an integer value into the DynAny.
 void insert_ulonglong(long value)
Inserts a long value into the DynAny.
 void insert_ushort(short value)
Inserts a short value into the DynAny.
 void insert_val(Serializable value)
Inserts a reference to a Serializable object into this DynAny.
 void insert_wchar(char value)
Inserts a char value into the DynAny.
 void insert_wstring(String value)
Inserts a string value into the DynAny.
 boolean is_null()
Returns true if the DynValueCommon represents a null value type.
 boolean next()
Advances the current position to the next component.
 void rewind()
Is equivalent to seek(0).
 boolean seek(int index)
Sets the current position to index.
 void set_members_as_dyn_any(NameDynAnyPair[] value)
Initializes the value type's members from a sequence of NameDynAnyPairs.
 void set_members(NameValuePair[] value)
Initializes the value type's members from a sequence of NameValuePairs.
 void set_to_null()
Changes the representation of a DynValueCommon to a null value type.
 void set_to_value()
Replaces a null value type with a newly constructed value.
 Any to_any()
Creates an any value from a DynAny object.
 TypeCode type()
Returns the TypeCode associated with this DynAny object.
Methods inherited from class org.omg.CORBA.portable.ObjectImpl
_create_request, _create_request, _duplicate, _get_delegate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _invoke, _is_a, _is_equivalent, _is_local, _non_existent, _orb, _release, _releaseReply, _request, _request, _servant_postinvoke, _servant_preinvoke, _set_delegate, _set_policy_override, equals, hashCode, toString
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Field Detail

_opsClass

public static final Class _opsClass
Constructor Detail

_DynValueStub

public _DynValueStub()
Method Detail

current_member_name

public String current_member_name()
                           throws TypeMismatch,
                                  InvalidValue
Returns the name of the member at the current position. This operation may return an empty string since the TypeCode of the value being manipulated may not contain the names of members.

Specified by:
current_member_name in interface DynValueOperations
Throws:
TypeMismatch - if the DynValue represents a null value type.
InvalidValue - if the current position does not indicate a member

current_member_kind

public TCKind current_member_kind()
                           throws TypeMismatch,
                                  InvalidValue
Returns the TCKind associated with the member at the current position.

Specified by:
current_member_kind in interface DynValueOperations
Throws:
TypeMismatch - if the DynValue represents a null value type.
InvalidValue - if the current position does not indicate a member

get_members

public NameValuePair[] get_members()
                            throws InvalidValue
Returns a sequence of NameValuePairs describing the name and the value of each member in the value type. The sequence contains members in the same order as the declaration order of members as indicated by the DynValue's TypeCode. The current position is not affected. The member names in the returned sequence will be empty strings if the DynValue's TypeCode does not contain member names.

Specified by:
get_members in interface DynValueOperations
Throws:
InvalidValue - if this object represents a null value type

set_members

public void set_members(NameValuePair[] value)
                 throws TypeMismatch,
                        InvalidValue
Initializes the value type's members from a sequence of NameValuePairs. The operation sets the current position to zero if the passed sequences has non-zero length. Otherwise, if an empty sequence is passed, the current position is set to -1. A null value type can be initialized to a non-null value type using this method.

Members must appear in the NameValuePairs in the order in which they appear in the IDL specification of the value type as indicated by the DynValue's TypeCode or they must be empty strings. The operation makes no attempt to assign member values based on member names.

Specified by:
set_members in interface DynValueOperations
Throws:
TypeMismatch - if the member names supplied in the passed sequence do not match the corresponding member name in the DynValue's TypeCode and they are not empty strings
InvalidValue - if the passed sequence has a number of elements that disagrees with the number of members as indicated by the DynValue's TypeCode

get_members_as_dyn_any

public NameDynAnyPair[] get_members_as_dyn_any()
                                        throws InvalidValue
Returns a sequence of NameDynAnyPairs describing the name and the value of each member in the value type. The sequence contains members in the same order as the declaration order of members as indicated by the DynValue's TypeCode. The current position is not affected. The member names in the returned sequence will be empty strings if the DynValue's TypeCode does not contain member names.

Specified by:
get_members_as_dyn_any in interface DynValueOperations
Throws:
InvalidValue - if this object represents a null value type

set_members_as_dyn_any

public void set_members_as_dyn_any(NameDynAnyPair[] value)
                            throws TypeMismatch,
                                   InvalidValue
Initializes the value type's members from a sequence of NameDynAnyPairs. The operation sets the current position to zero if the passed sequences has non-zero length. Otherwise, if an empty sequence is passed, the current position is set to -1. A null value type can be initialized to a non-null value type using this method.

Members must appear in the NameDynAnyPairs in the order in which they appear in the IDL specification of the value type as indicated by the DynValue's TypeCode or they must be empty strings. The operation makes no attempt to assign member values based on member names.

Specified by:
set_members_as_dyn_any in interface DynValueOperations
Throws:
TypeMismatch - if the member names supplied in the passed sequence do not match the corresponding member name in the DynValue's TypeCode and they are not empty strings
InvalidValue - if the passed sequence has a number of elements that disagrees with the number of members as indicated by the DynValue's TypeCode

is_null

public boolean is_null()
Returns true if the DynValueCommon represents a null value type.

Specified by:
is_null in interface DynValueCommonOperations

set_to_null

public void set_to_null()
Changes the representation of a DynValueCommon to a null value type.

Specified by:
set_to_null in interface DynValueCommonOperations

set_to_value

public void set_to_value()
Replaces a null value type with a newly constructed value. Its components are initialized to default values as in DynAnyFactory.create_dyn_any_from_type_code. If the DynValueCommon represents a non-null value type, then this operation has no effect.

Specified by:
set_to_value in interface DynValueCommonOperations

type

public TypeCode type()
Returns the TypeCode associated with this DynAny object. A DynAny object is created with a TypeCode value assigned to it. This TypeCode value determines the type of the value handled through the DynAny object. Note that the TypeCode associated with a DynAny object is initialized at the time the DynAny is created and cannot be changed during lifetime of the DynAny object.

Specified by:
type in interface DynAnyOperations
Returns:
The TypeCode associated with this DynAny object

assign

public void assign(DynAny dyn_any)
            throws TypeMismatch
Initializes the value associated with a DynAny object with the value associated with another DynAny object. The current position of the target DynAny is set to zero for values that have components and to -1 for values that do not have components.

Specified by:
assign in interface DynAnyOperations
Parameters:
dyn_any -
Throws:
TypeMismatch - if the type of the passed DynAny is not equivalent to the type of target DynAny

from_any

public void from_any(Any value)
              throws TypeMismatch,
                     InvalidValue
Initializes the value associated with a DynAny object with the value contained in an any. The current position of the target DynAny is set to zero for values that have components and to -1 for values that do not have components.

Specified by:
from_any in interface DynAnyOperations
Throws:
TypeMismatch - if the type of the passed Any is not equivalent to the type of target DynAny
InvalidValue - if the passed Any does not contain a legal value (such as a null string)

to_any

public Any to_any()
Creates an any value from a DynAny object. A copy of the TypeCode associated with the DynAny object is assigned to the resulting any. The value associated with the DynAny object is copied into the any.

Specified by:
to_any in interface DynAnyOperations
Returns:
a new Any object with the same value and TypeCode

equal

public boolean equal(DynAny dyn_any)
Compares two DynAny values for equality. Two DynAny values are equal if their TypeCodes are equivalent and, recursively, all component DynAnys have equal values. The current position of the two DynAnys being compared has no effect on the result of equal.

Specified by:
equal in interface DynAnyOperations
Returns:
true of the DynAnys are equal, false otherwise

destroy

public void destroy()
Destroys a DynAny object. This operation frees any resources used to represent the data value associated with a DynAny object. It must be invoked on references obtained from one of the creation operations on the ORB interface or on a reference returned by DynAny.copy() to avoid resource leaks. Invoking destroy on component DynAny objects (for example, on objects returned by the current_component operation) does nothing. Destruction of a DynAny object implies destruction of all DynAny objects obtained from it. That is, references to components of a destroyed DynAny become invalid. Invocations on such references raise OBJECT_NOT_EXIST. It is possible to manipulate a component of a DynAny beyond the life time of the DynAny from which the component was obtained by making a copy of the component with the copy operation before destroying the DynAny from which the component was obtained.

Specified by:
destroy in interface DynAnyOperations

copy

public DynAny copy()
Creates a new DynAny object whose value is a deep copy of the DynAny on which it is invoked. The operation is polymorphic, that is, invoking it on one of the types derived from DynAny, such as DynStruct, creates the derived type but returns its reference as the DynAny base type.

Specified by:
copy in interface DynAnyOperations
Returns:
a deep copy of the DynAny object

insert_boolean

public void insert_boolean(boolean value)
                    throws TypeMismatch,
                           InvalidValue
Inserts a boolean value into the DynAny.

Specified by:
insert_boolean in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_octet

public void insert_octet(byte value)
                  throws TypeMismatch,
                         InvalidValue
Inserts a byte value into the DynAny. The IDL octet data type is mapped to the Java byte data type.

Specified by:
insert_octet in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_char

public void insert_char(char value)
                 throws TypeMismatch,
                        InvalidValue
Inserts a char value into the DynAny.

Specified by:
insert_char in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_short

public void insert_short(short value)
                  throws TypeMismatch,
                         InvalidValue
Inserts a short value into the DynAny.

Specified by:
insert_short in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_ushort

public void insert_ushort(short value)
                   throws TypeMismatch,
                          InvalidValue
Inserts a short value into the DynAny. The IDL ushort data type is mapped to the Java short data type.

Specified by:
insert_ushort in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_long

public void insert_long(int value)
                 throws TypeMismatch,
                        InvalidValue
Inserts an integer value into the DynAny. The IDL long data type is mapped to the Java int data type.

Specified by:
insert_long in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_ulong

public void insert_ulong(int value)
                  throws TypeMismatch,
                         InvalidValue
Inserts an integer value into the DynAny. The IDL ulong data type is mapped to the Java int data type.

Specified by:
insert_ulong in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_float

public void insert_float(float value)
                  throws TypeMismatch,
                         InvalidValue
Inserts a float value into the DynAny.

Specified by:
insert_float in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_double

public void insert_double(double value)
                   throws TypeMismatch,
                          InvalidValue
Inserts a double value into the DynAny.

Specified by:
insert_double in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_string

public void insert_string(String value)
                   throws TypeMismatch,
                          InvalidValue
Inserts a string value into the DynAny. Both bounded and unbounded strings are inserted using this method.

Specified by:
insert_string in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
InvalidValue - if the string inserted is longer than the bound of a bounded string
TypeMismatch - if called on a DynAny whose current component itself has components

insert_reference

public void insert_reference(Object value)
                      throws TypeMismatch,
                             InvalidValue
Inserts a reference to a CORBA object into the DynAny.

Specified by:
insert_reference in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_typecode

public void insert_typecode(TypeCode value)
                     throws TypeMismatch,
                            InvalidValue
Inserts a TypeCode object into the DynAny.

Specified by:
insert_typecode in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_longlong

public void insert_longlong(long value)
                     throws TypeMismatch,
                            InvalidValue
Inserts a long value into the DynAny. The IDL long long data type is mapped to the Java long data type.

Specified by:
insert_longlong in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_ulonglong

public void insert_ulonglong(long value)
                      throws TypeMismatch,
                             InvalidValue
Inserts a long value into the DynAny. The IDL unsigned long long data type is mapped to the Java long data type.

Specified by:
insert_ulonglong in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_wchar

public void insert_wchar(char value)
                  throws TypeMismatch,
                         InvalidValue
Inserts a char value into the DynAny. The IDL wchar data type is mapped to the Java char data type.

Specified by:
insert_wchar in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_wstring

public void insert_wstring(String value)
                    throws TypeMismatch,
                           InvalidValue
Inserts a string value into the DynAny. Both bounded and unbounded strings are inserted using this method.

Specified by:
insert_wstring in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
InvalidValue - if the string inserted is longer than the bound of a bounded string
TypeMismatch

insert_any

public void insert_any(Any value)
                throws TypeMismatch,
                       InvalidValue
Inserts an Any value into the Any represented by this DynAny.

Specified by:
insert_any in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_dyn_any

public void insert_dyn_any(DynAny value)
                    throws TypeMismatch,
                           InvalidValue
Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.

Specified by:
insert_dyn_any in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_val

public void insert_val(Serializable value)
                throws TypeMismatch,
                       InvalidValue
Inserts a reference to a Serializable object into this DynAny. The IDL ValueBase type is mapped to the Java Serializable type.

Specified by:
insert_val in interface DynAnyOperations
Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

get_boolean

public boolean get_boolean()
                    throws TypeMismatch,
                           InvalidValue
Extracts the boolean value from this DynAny.

Specified by:
get_boolean in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_octet

public byte get_octet()
               throws TypeMismatch,
                      InvalidValue
Extracts the byte value from this DynAny. The IDL octet data type is mapped to the Java byte data type.

Specified by:
get_octet in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_char

public char get_char()
              throws TypeMismatch,
                     InvalidValue
Extracts the char value from this DynAny.

Specified by:
get_char in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_short

public short get_short()
                throws TypeMismatch,
                       InvalidValue
Extracts the short value from this DynAny.

Specified by:
get_short in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_ushort

public short get_ushort()
                 throws TypeMismatch,
                        InvalidValue
Extracts the short value from this DynAny. The IDL ushort data type is mapped to the Java short data type.

Specified by:
get_ushort in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_long

public int get_long()
             throws TypeMismatch,
                    InvalidValue
Extracts the integer value from this DynAny. The IDL long data type is mapped to the Java int data type.

Specified by:
get_long in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_ulong

public int get_ulong()
              throws TypeMismatch,
                     InvalidValue
Extracts the integer value from this DynAny. The IDL ulong data type is mapped to the Java int data type.

Specified by:
get_ulong in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_float

public float get_float()
                throws TypeMismatch,
                       InvalidValue
Extracts the float value from this DynAny.

Specified by:
get_float in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_double

public double get_double()
                  throws TypeMismatch,
                         InvalidValue
Extracts the double value from this DynAny.

Specified by:
get_double in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_string

public String get_string()
                  throws TypeMismatch,
                         InvalidValue
Extracts the string value from this DynAny. Both bounded and unbounded strings are extracted using this method.

Specified by:
get_string in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_reference

public Object get_reference()
                     throws TypeMismatch,
                            InvalidValue
Extracts the reference to a CORBA Object from this DynAny.

Specified by:
get_reference in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_typecode

public TypeCode get_typecode()
                      throws TypeMismatch,
                             InvalidValue
Extracts the TypeCode object from this DynAny.

Specified by:
get_typecode in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_longlong

public long get_longlong()
                  throws TypeMismatch,
                         InvalidValue
Extracts the long value from this DynAny. The IDL long long data type is mapped to the Java long data type.

Specified by:
get_longlong in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_ulonglong

public long get_ulonglong()
                   throws TypeMismatch,
                          InvalidValue
Extracts the long value from this DynAny. The IDL unsigned long long data type is mapped to the Java long data type.

Specified by:
get_ulonglong in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_wchar

public char get_wchar()
               throws TypeMismatch,
                      InvalidValue
Extracts the long value from this DynAny. The IDL wchar data type is mapped to the Java char data type.

Specified by:
get_wchar in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_wstring

public String get_wstring()
                   throws TypeMismatch,
                          InvalidValue
Extracts the string value from this DynAny. Both bounded and unbounded strings are extracted using this method.

Specified by:
get_wstring in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue

get_any

public Any get_any()
            throws TypeMismatch,
                   InvalidValue
Extracts an Any value contained in the Any represented by this DynAny.

Specified by:
get_any in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_dyn_any

public DynAny get_dyn_any()
                   throws TypeMismatch,
                          InvalidValue
Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.

Specified by:
get_dyn_any in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_val

public Serializable get_val()
                     throws TypeMismatch,
                            InvalidValue
Extracts a Serializable object from this DynAny. The IDL ValueBase type is mapped to the Java Serializable type.

Specified by:
get_val in interface DynAnyOperations
Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

seek

public boolean seek(int index)
Sets the current position to index. The current position is indexed 0 to n-1, that is, index zero corresponds to the first component. The operation returns true if the resulting current position indicates a component of the DynAny and false if index indicates a position that does not correspond to a component. Calling seek with a negative index is legal. It sets the current position to -1 to indicate no component and returns false. Passing a non-negative index value for a DynAny that does not have a component at the corresponding position sets the current position to -1 and returns false.

Specified by:
seek in interface DynAnyOperations

rewind

public void rewind()
Is equivalent to seek(0).

Specified by:
rewind in interface DynAnyOperations

next

public boolean next()
Advances the current position to the next component. The operation returns true while the resulting current position indicates a component, false otherwise. A false return value leaves the current position at -1. Invoking next on a DynAny without components leaves the current position at -1 and returns false.

Specified by:
next in interface DynAnyOperations

component_count

public int component_count()
Returns the number of components of a DynAny. For a DynAny without components, it returns zero. The operation only counts the components at the top level. For example, if component_count is invoked on a DynStruct with a single member, the return value is 1, irrespective of the type of the member.
  • For sequences, the operation returns the current number of elements.
  • For structures, exceptions, and value types, the operation returns the number of members.
  • For arrays, the operation returns the number of elements.
  • For unions, the operation returns 2 if the discriminator indicates that a named member is active, otherwise, it returns 1.
  • For DynFixed and DynEnum, the operation returns zero.

Specified by:
component_count in interface DynAnyOperations

current_component

public DynAny current_component()
                         throws TypeMismatch
Returns the DynAny for the component at the current position. It does not advance the current position, so repeated calls to current_component without an intervening call to rewind, next, or seek return the same component. The returned DynAny object reference can be used to get/set the value of the current component. If the current component represents a complex type, the returned reference can be narrowed based on the TypeCode to get the interface corresponding to the to the complex type. Calling current_component on a DynAny that cannot have components, such as a DynEnum or an empty exception, raises TypeMismatch. Calling current_component on a DynAny whose current position is -1 returns a nil reference. The iteration operations, together with current_component, can be used to dynamically compose an any value. After creating a dynamic any, such as a DynStruct, current_component and next can be used to initialize all the components of the value. Once the dynamic value is completely initialized, to_any creates the corresponding any value.

Specified by:
current_component in interface DynAnyOperations
Throws:
TypeMismatch - If called on a DynAny that cannot have components, such as a DynEnum or an empty exception

_ids

public String[] _ids()
Description copied from class: ObjectImpl
Retrieves a string array containing the repository identifiers supported by this ObjectImpl object. For example, for a stub, this method returns information about all the interfaces supported by the stub.

Specified by:
_ids in class ObjectImpl
Returns:
the array of all repository identifiers supported by this ObjectImpl instance
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


AnySeqHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Class AnySeqHelper

java.lang.Object
    extended by org.omg.DynamicAny.AnySeqHelper
public abstract class AnySeqHelper
extends Object

org/omg/DynamicAny/AnySeqHelper.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/DynamicAny/DynamicAny.idl Thursday, June 12, 2003 9:59:26 PM GMT-08:00

Constructor Summary
AnySeqHelper()
Method Summary
static Any[] | extract(Any a)
static String | id()
static void | insert(Any a, Any[] that)
static Any[] | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, Any[] value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

AnySeqHelper

public AnySeqHelper()
Method Detail

insert

public static void insert(Any a,
                          Any[] that)

extract

public static Any[] extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static Any[] read(InputStream istream)

write

public static void write(OutputStream ostream,
                         Any[] value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynAny (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Interface DynAny

All Superinterfaces:
DynAnyOperations, IDLEntity, Object, Serializable
All Known Subinterfaces:
DynArray, DynEnum, DynFixed, DynSequence, DynStruct, DynUnion, DynValue, DynValueBox, DynValueCommon
All Known Implementing Classes:
_DynAnyStub, _DynArrayStub, _DynEnumStub, _DynFixedStub, _DynSequenceStub, _DynStructStub, _DynUnionStub, _DynValueStub
public interface DynAny
extends DynAnyOperations, Object, IDLEntity

Any values can be dynamically interpreted (traversed) and constructed through DynAny objects. A DynAny object is associated with a data value which corresponds to a copy of the value inserted into an any.

A DynAny object may be viewed as an ordered collection of component DynAnys. For DynAnys representing a basic type, such as long, or a type without components, such as an empty exception, the ordered collection of components is empty. Each DynAny object maintains the notion of a current position into its collection of component DynAnys. The current position is identified by an index value that runs from 0 to n-1, where n is the number of components. The special index value -1 indicates a current position that points nowhere. For values that cannot have a current position (such as an empty exception), the index value is fixed at -1. If a DynAny is initialized with a value that has components, the index is initialized to 0. After creation of an uninitialized DynAny (that is, a DynAny that has no value but a TypeCode that permits components), the current position depends on the type of value represented by the DynAny. (The current position is set to 0 or -1, depending on whether the new DynAny gets default values for its components.)

The iteration operations rewind, seek, and next can be used to change the current position and the current_component operation returns the component at the current position. The component_count operation returns the number of components of a DynAny. Collectively, these operations enable iteration over the components of a DynAny, for example, to (recursively) examine its contents.

A constructed DynAny object is a DynAny object associated with a constructed type. There is a different interface, inheriting from the DynAny interface, associated with each kind of constructed type in IDL (fixed, enum, struct, sequence, union, array, exception, and value type).

A constructed DynAny object exports operations that enable the creation of new DynAny objects, each of them associated with a component of the constructed data value. As an example, a DynStruct is associated with a struct value. This means that the DynStruct may be seen as owning an ordered collection of components, one for each structure member. The DynStruct object exports operations that enable the creation of new DynAny objects, each of them associated with a member of the struct.

If a DynAny object has been obtained from another (constructed) DynAny object, such as a DynAny representing a structure member that was created from a DynStruct, the member DynAny is logically contained in the DynStruct. Calling an insert or get operation leaves the current position unchanged. Destroying a top-level DynAny object (one that was not obtained as a component of another DynAny) also destroys any component DynAny objects obtained from it. Destroying a non-top level DynAny object does nothing. Invoking operations on a destroyed top-level DynAny or any of its descendants raises OBJECT_NOT_EXIST. If the programmer wants to destroy a DynAny object but still wants to manipulate some component of the data value associated with it, then he or she should first create a DynAny for the component and, after that, make a copy of the created DynAny object.

The behavior of DynAny objects has been defined in order to enable efficient implementations in terms of allocated memory space and speed of access. DynAny objects are intended to be used for traversing values extracted from anys or constructing values of anys at runtime. Their use for other purposes is not recommended.

Insert and get operations are necessary to handle basic DynAny objects but are also helpful to handle constructed DynAny objects. Inserting a basic data type value into a constructed DynAny object implies initializing the current component of the constructed data value associated with the DynAny object. For example, invoking insert_boolean on a DynStruct implies inserting a boolean data value at the current position of the associated struct data value. A type is consistent for inserting or extracting a value if its TypeCode is equivalent to the TypeCode contained in the DynAny or, if the DynAny has components, is equivalent to the TypeCode of the DynAny at the current position.

DynAny and DynAnyFactory objects are intended to be local to the process in which they are created and used. This means that references to DynAny and DynAnyFactory objects cannot be exported to other processes, or externalized with ORB.object_to_string(). If any attempt is made to do so, the offending operation will raise a MARSHAL system exception. Since their interfaces are specified in IDL, DynAny objects export operations defined in the standard org.omg.CORBA.Object interface. However, any attempt to invoke operations exported through the Object interface may raise the standard NO_IMPLEMENT exception. An attempt to use a DynAny object with the DII may raise the NO_IMPLEMENT exception.

Methods inherited from interface org.omg.DynamicAny.DynAnyOperations
assign, component_count, copy, current_component, destroy, equal, from_any, get_any, get_boolean, get_char, get_double, get_dyn_any, get_float, get_long, get_longlong, get_octet, get_reference, get_short, get_string, get_typecode, get_ulong, get_ulonglong, get_ushort, get_val, get_wchar, get_wstring, insert_any, insert_boolean, insert_char, insert_double, insert_dyn_any, insert_float, insert_long, insert_longlong, insert_octet, insert_reference, insert_short, insert_string, insert_typecode, insert_ulong, insert_ulonglong, insert_ushort, insert_val, insert_wchar, insert_wstring, next, rewind, seek, to_any, type
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


DynAnyFactory (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Interface DynAnyFactory

All Superinterfaces:
DynAnyFactoryOperations, IDLEntity, Object, Serializable
All Known Implementing Classes:
_DynAnyFactoryStub
public interface DynAnyFactory
extends DynAnyFactoryOperations, Object, IDLEntity

DynAny objects can be created by invoking operations on the DynAnyFactory object. Generally there are only two ways to create a DynAny object:

  • invoking an operation on an existing DynAny object
  • invoking an operation on a DynAnyFactory object
A constructed DynAny object supports operations that enable the creation of new DynAny objects encapsulating access to the value of some constituent. DynAny objects also support the copy operation for creating new DynAny objects. A reference to the DynAnyFactory object is obtained by calling ORB.resolve_initial_references() with the identifier parameter set to the string constant "DynAnyFactory".

Dynamic interpretation of an any usually involves creating a DynAny object using create_dyn_any() as the first step. Depending on the type of the any, the resulting DynAny object reference can be narrowed to a DynFixed, DynStruct, DynSequence, DynArray, DynUnion, DynEnum, or DynValue object reference.

Dynamic creation of an any involves creating a DynAny object using create_dyn_any_from_type_code(), passing the TypeCode associated with the value to be created. The returned reference is narrowed to one of the complex types, such as DynStruct, if appropriate. Then, the value can be initialized by means of invoking operations on the resulting object. Finally, the to_any operation can be invoked to create an any value from the constructed DynAny.

Methods inherited from interface org.omg.DynamicAny.DynAnyFactoryOperations
create_dyn_any_from_type_code, create_dyn_any
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynAnyFactoryHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Class DynAnyFactoryHelper

java.lang.Object
    extended by org.omg.DynamicAny.DynAnyFactoryHelper
public abstract class DynAnyFactoryHelper
extends Object

DynAny objects can be created by invoking operations on the DynAnyFactory object. Generally there are only two ways to create a DynAny object:

  • invoking an operation on an existing DynAny object
  • invoking an operation on a DynAnyFactory object
A constructed DynAny object supports operations that enable the creation of new DynAny objects encapsulating access to the value of some constituent. DynAny objects also support the copy operation for creating new DynAny objects. A reference to the DynAnyFactory object is obtained by calling ORB.resolve_initial_references() with the identifier parameter set to the string constant "DynAnyFactory".

Dynamic interpretation of an any usually involves creating a DynAny object using create_dyn_any() as the first step. Depending on the type of the any, the resulting DynAny object reference can be narrowed to a DynFixed, DynStruct, DynSequence, DynArray, DynUnion, DynEnum, or DynValue object reference.

Dynamic creation of an any involves creating a DynAny object using create_dyn_any_from_type_code(), passing the TypeCode associated with the value to be created. The returned reference is narrowed to one of the complex types, such as DynStruct, if appropriate. Then, the value can be initialized by means of invoking operations on the resulting object. Finally, the to_any operation can be invoked to create an any value from the constructed DynAny.

Constructor Summary
DynAnyFactoryHelper()
Method Summary
static DynAnyFactory | extract(Any a)
static String | id()
static void | insert(Any a, DynAnyFactory that)
static DynAnyFactory | narrow(Object obj)
static DynAnyFactory | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, DynAnyFactory value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DynAnyFactoryHelper

public DynAnyFactoryHelper()
Method Detail

insert

public static void insert(Any a,
                          DynAnyFactory that)

extract

public static DynAnyFactory extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static DynAnyFactory read(InputStream istream)

write

public static void write(OutputStream ostream,
                         DynAnyFactory value)

narrow

public static DynAnyFactory narrow(Object obj)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynAnyFactoryOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Interface DynAnyFactoryOperations

All Known Subinterfaces:
DynAnyFactory
All Known Implementing Classes:
_DynAnyFactoryStub
public interface DynAnyFactoryOperations

DynAny objects can be created by invoking operations on the DynAnyFactory object. Generally there are only two ways to create a DynAny object:

  • invoking an operation on an existing DynAny object
  • invoking an operation on a DynAnyFactory object
A constructed DynAny object supports operations that enable the creation of new DynAny objects encapsulating access to the value of some constituent. DynAny objects also support the copy operation for creating new DynAny objects. A reference to the DynAnyFactory object is obtained by calling ORB.resolve_initial_references() with the identifier parameter set to the string constant "DynAnyFactory".

Dynamic interpretation of an any usually involves creating a DynAny object using create_dyn_any() as the first step. Depending on the type of the any, the resulting DynAny object reference can be narrowed to a DynFixed, DynStruct, DynSequence, DynArray, DynUnion, DynEnum, or DynValue object reference.

Dynamic creation of an any involves creating a DynAny object using create_dyn_any_from_type_code(), passing the TypeCode associated with the value to be created. The returned reference is narrowed to one of the complex types, such as DynStruct, if appropriate. Then, the value can be initialized by means of invoking operations on the resulting object. Finally, the to_any operation can be invoked to create an any value from the constructed DynAny.

Method Summary
DynAny | create_dyn_any_from_type_code(TypeCode type) Creates a DynAny from a TypeCode.
DynAny | create_dyn_any(Any value) Creates a new DynAny object from an any value.

Method Detail

create_dyn_any

public DynAny create_dyn_any(Any value)
                      throws InconsistentTypeCode
Creates a new DynAny object from an any value. A copy of the TypeCode associated with the any value is assigned to the resulting DynAny object. The value associated with the DynAny object is a copy of the value in the original any. The current position of the created DynAny is set to zero if the passed value has components, to -1 otherwise

Throws:
InconsistentTypeCode - if value has a TypeCode with a TCKind of tk_Principal, tk_native, or tk_abstract_interface

create_dyn_any_from_type_code

public DynAny create_dyn_any_from_type_code(TypeCode type)
                                     throws InconsistentTypeCode
Creates a DynAny from a TypeCode. Depending on the TypeCode, the created object may be of type DynAny, or one of its derived types, such as DynStruct. The returned reference can be narrowed to the derived type. In all cases, a DynAny constructed from a TypeCode has an initial default value. The default values of basic types are:
  • false for boolean
  • zero for numeric types
  • zero for types octet, char, and wchar
  • the empty string for string and wstring
  • null for object references
  • a type code with a TCKind value of tk_null for type codes
  • for any values, an any containing a type code with a TCKind value of tk_null type and no value
For complex types, creation of the corresponding DynAny assigns a default value as follows:
  • For DynSequence it sets the current position to -1 and creates an empty sequence.
  • For DynEnum it sets the current position to -1 and sets the value of the enumerator to the first enumerator value indicated by the TypeCode.
  • For DynFixed it sets the current position to -1 and sets the value zero.
  • For DynStruct it sets the current position to -1 for empty exceptions and to zero for all other TypeCodes. The members (if any) are (recursively) initialized to their default values.
  • For DynArray sets the current position to zero and (recursively) initializes elements to their default value.
  • For DynUnion sets the current position to zero. The discriminator value is set to a value consistent with the first named member of the union. That member is activated and (recursively) initialized to its default value.
  • For DynValue and DynValueBox it initializes to a null value.

Throws:
InconsistentTypeCode
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynAnyHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Class DynAnyHelper

java.lang.Object
    extended by org.omg.DynamicAny.DynAnyHelper
public abstract class DynAnyHelper
extends Object

Any values can be dynamically interpreted (traversed) and constructed through DynAny objects. A DynAny object is associated with a data value which corresponds to a copy of the value inserted into an any.

A DynAny object may be viewed as an ordered collection of component DynAnys. For DynAnys representing a basic type, such as long, or a type without components, such as an empty exception, the ordered collection of components is empty. Each DynAny object maintains the notion of a current position into its collection of component DynAnys. The current position is identified by an index value that runs from 0 to n-1, where n is the number of components. The special index value -1 indicates a current position that points nowhere. For values that cannot have a current position (such as an empty exception), the index value is fixed at -1. If a DynAny is initialized with a value that has components, the index is initialized to 0. After creation of an uninitialized DynAny (that is, a DynAny that has no value but a TypeCode that permits components), the current position depends on the type of value represented by the DynAny. (The current position is set to 0 or -1, depending on whether the new DynAny gets default values for its components.)

The iteration operations rewind, seek, and next can be used to change the current position and the current_component operation returns the component at the current position. The component_count operation returns the number of components of a DynAny. Collectively, these operations enable iteration over the components of a DynAny, for example, to (recursively) examine its contents.

A constructed DynAny object is a DynAny object associated with a constructed type. There is a different interface, inheriting from the DynAny interface, associated with each kind of constructed type in IDL (fixed, enum, struct, sequence, union, array, exception, and value type).

A constructed DynAny object exports operations that enable the creation of new DynAny objects, each of them associated with a component of the constructed data value. As an example, a DynStruct is associated with a struct value. This means that the DynStruct may be seen as owning an ordered collection of components, one for each structure member. The DynStruct object exports operations that enable the creation of new DynAny objects, each of them associated with a member of the struct.

If a DynAny object has been obtained from another (constructed) DynAny object, such as a DynAny representing a structure member that was created from a DynStruct, the member DynAny is logically contained in the DynStruct. Calling an insert or get operation leaves the current position unchanged. Destroying a top-level DynAny object (one that was not obtained as a component of another DynAny) also destroys any component DynAny objects obtained from it. Destroying a non-top level DynAny object does nothing. Invoking operations on a destroyed top-level DynAny or any of its descendants raises OBJECT_NOT_EXIST. If the programmer wants to destroy a DynAny object but still wants to manipulate some component of the data value associated with it, then he or she should first create a DynAny for the component and, after that, make a copy of the created DynAny object.

The behavior of DynAny objects has been defined in order to enable efficient implementations in terms of allocated memory space and speed of access. DynAny objects are intended to be used for traversing values extracted from anys or constructing values of anys at runtime. Their use for other purposes is not recommended.

Insert and get operations are necessary to handle basic DynAny objects but are also helpful to handle constructed DynAny objects. Inserting a basic data type value into a constructed DynAny object implies initializing the current component of the constructed data value associated with the DynAny object. For example, invoking insert_boolean on a DynStruct implies inserting a boolean data value at the current position of the associated struct data value. A type is consistent for inserting or extracting a value if its TypeCode is equivalent to the TypeCode contained in the DynAny or, if the DynAny has components, is equivalent to the TypeCode of the DynAny at the current position.

DynAny and DynAnyFactory objects are intended to be local to the process in which they are created and used. This means that references to DynAny and DynAnyFactory objects cannot be exported to other processes, or externalized with ORB.object_to_string(). If any attempt is made to do so, the offending operation will raise a MARSHAL system exception. Since their interfaces are specified in IDL, DynAny objects export operations defined in the standard org.omg.CORBA.Object interface. However, any attempt to invoke operations exported through the Object interface may raise the standard NO_IMPLEMENT exception. An attempt to use a DynAny object with the DII may raise the NO_IMPLEMENT exception.

Constructor Summary
DynAnyHelper()
Method Summary
static DynAny | extract(Any a)
static String | id()
static void | insert(Any a, DynAny that)
static DynAny | narrow(Object obj)
static DynAny | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, DynAny value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DynAnyHelper

public DynAnyHelper()
Method Detail

insert

public static void insert(Any a,
                          DynAny that)

extract

public static DynAny extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static DynAny read(InputStream istream)

write

public static void write(OutputStream ostream,
                         DynAny value)

narrow

public static DynAny narrow(Object obj)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynAnyOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Interface DynAnyOperations

All Known Subinterfaces:
DynAny, DynArray, DynArrayOperations, DynEnum, DynEnumOperations, DynFixed, DynFixedOperations, DynSequence, DynSequenceOperations, DynStruct, DynStructOperations, DynUnion, DynUnionOperations, DynValue, DynValueBox, DynValueBoxOperations, DynValueCommon, DynValueCommonOperations, DynValueOperations
All Known Implementing Classes:
_DynAnyStub, _DynArrayStub, _DynEnumStub, _DynFixedStub, _DynSequenceStub, _DynStructStub, _DynUnionStub, _DynValueStub
public interface DynAnyOperations

Any values can be dynamically interpreted (traversed) and constructed through DynAny objects. A DynAny object is associated with a data value which corresponds to a copy of the value inserted into an any.

A DynAny object may be viewed as an ordered collection of component DynAnys. For DynAnys representing a basic type, such as long, or a type without components, such as an empty exception, the ordered collection of components is empty. Each DynAny object maintains the notion of a current position into its collection of component DynAnys. The current position is identified by an index value that runs from 0 to n-1, where n is the number of components. The special index value -1 indicates a current position that points nowhere. For values that cannot have a current position (such as an empty exception), the index value is fixed at -1. If a DynAny is initialized with a value that has components, the index is initialized to 0. After creation of an uninitialized DynAny (that is, a DynAny that has no value but a TypeCode that permits components), the current position depends on the type of value represented by the DynAny. (The current position is set to 0 or -1, depending on whether the new DynAny gets default values for its components.)

The iteration operations rewind, seek, and next can be used to change the current position and the current_component operation returns the component at the current position. The component_count operation returns the number of components of a DynAny. Collectively, these operations enable iteration over the components of a DynAny, for example, to (recursively) examine its contents.

A constructed DynAny object is a DynAny object associated with a constructed type. There is a different interface, inheriting from the DynAny interface, associated with each kind of constructed type in IDL (fixed, enum, struct, sequence, union, array, exception, and value type).

A constructed DynAny object exports operations that enable the creation of new DynAny objects, each of them associated with a component of the constructed data value. As an example, a DynStruct is associated with a struct value. This means that the DynStruct may be seen as owning an ordered collection of components, one for each structure member. The DynStruct object exports operations that enable the creation of new DynAny objects, each of them associated with a member of the struct.

If a DynAny object has been obtained from another (constructed) DynAny object, such as a DynAny representing a structure member that was created from a DynStruct, the member DynAny is logically contained in the DynStruct. Calling an insert or get operation leaves the current position unchanged. Destroying a top-level DynAny object (one that was not obtained as a component of another DynAny) also destroys any component DynAny objects obtained from it. Destroying a non-top level DynAny object does nothing. Invoking operations on a destroyed top-level DynAny or any of its descendants raises OBJECT_NOT_EXIST. If the programmer wants to destroy a DynAny object but still wants to manipulate some component of the data value associated with it, then he or she should first create a DynAny for the component and, after that, make a copy of the created DynAny object.

The behavior of DynAny objects has been defined in order to enable efficient implementations in terms of allocated memory space and speed of access. DynAny objects are intended to be used for traversing values extracted from anys or constructing values of anys at runtime. Their use for other purposes is not recommended.

Insert and get operations are necessary to handle basic DynAny objects but are also helpful to handle constructed DynAny objects. Inserting a basic data type value into a constructed DynAny object implies initializing the current component of the constructed data value associated with the DynAny object. For example, invoking insert_boolean on a DynStruct implies inserting a boolean data value at the current position of the associated struct data value. A type is consistent for inserting or extracting a value if its TypeCode is equivalent to the TypeCode contained in the DynAny or, if the DynAny has components, is equivalent to the TypeCode of the DynAny at the current position.

DynAny and DynAnyFactory objects are intended to be local to the process in which they are created and used. This means that references to DynAny and DynAnyFactory objects cannot be exported to other processes, or externalized with ORB.object_to_string(). If any attempt is made to do so, the offending operation will raise a MARSHAL system exception. Since their interfaces are specified in IDL, DynAny objects export operations defined in the standard org.omg.CORBA.Object interface. However, any attempt to invoke operations exported through the Object interface may raise the standard NO_IMPLEMENT exception. An attempt to use a DynAny object with the DII may raise the NO_IMPLEMENT exception.

Method Summary
 void assign(DynAny dyn_any)
Initializes the value associated with a DynAny object with the value associated with another DynAny object.
 int component_count()
Returns the number of components of a DynAny.
 DynAny copy()
Creates a new DynAny object whose value is a deep copy of the DynAny on which it is invoked.
 DynAny current_component()
Returns the DynAny for the component at the current position.
 void destroy()
Destroys a DynAny object.
 boolean equal(DynAny dyn_any)
Compares two DynAny values for equality.
 void from_any(Any value)
Initializes the value associated with a DynAny object with the value contained in an any.
 Any get_any()
Extracts an Any value contained in the Any represented by this DynAny.
 boolean get_boolean()
Extracts the boolean value from this DynAny.
 char get_char()
Extracts the char value from this DynAny.
 double get_double()
Extracts the double value from this DynAny.
 DynAny get_dyn_any()
Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.
 float get_float()
Extracts the float value from this DynAny.
 int get_long()
Extracts the integer value from this DynAny.
 long get_longlong()
Extracts the long value from this DynAny.
 byte get_octet()
Extracts the byte value from this DynAny.
 Object get_reference()
Extracts the reference to a CORBA Object from this DynAny.
 short get_short()
Extracts the short value from this DynAny.
 String get_string()
Extracts the string value from this DynAny.
 TypeCode get_typecode()
Extracts the TypeCode object from this DynAny.
 int get_ulong()
Extracts the integer value from this DynAny.
 long get_ulonglong()
Extracts the long value from this DynAny.
 short get_ushort()
Extracts the short value from this DynAny.
 Serializable get_val()
Extracts a Serializable object from this DynAny.
 char get_wchar()
Extracts the long value from this DynAny.
 String get_wstring()
Extracts the string value from this DynAny.
 void insert_any(Any value)
Inserts an Any value into the Any represented by this DynAny.
 void insert_boolean(boolean value)
Inserts a boolean value into the DynAny.
 void insert_char(char value)
Inserts a char value into the DynAny.
 void insert_double(double value)
Inserts a double value into the DynAny.
 void insert_dyn_any(DynAny value)
Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.
 void insert_float(float value)
Inserts a float value into the DynAny.
 void insert_long(int value)
Inserts an integer value into the DynAny.
 void insert_longlong(long value)
Inserts a long value into the DynAny.
 void insert_octet(byte value)
Inserts a byte value into the DynAny.
 void insert_reference(Object value)
Inserts a reference to a CORBA object into the DynAny.
 void insert_short(short value)
Inserts a short value into the DynAny.
 void insert_string(String value)
Inserts a string value into the DynAny.
 void insert_typecode(TypeCode value)
Inserts a TypeCode object into the DynAny.
 void insert_ulong(int value)
Inserts an integer value into the DynAny.
 void insert_ulonglong(long value)
Inserts a long value into the DynAny.
 void insert_ushort(short value)
Inserts a short value into the DynAny.
 void insert_val(Serializable value)
Inserts a reference to a Serializable object into this DynAny.
 void insert_wchar(char value)
Inserts a char value into the DynAny.
 void insert_wstring(String value)
Inserts a string value into the DynAny.
 boolean next()
Advances the current position to the next component.
 void rewind()
Is equivalent to seek(0).
 boolean seek(int index)
Sets the current position to index.
 Any to_any()
Creates an any value from a DynAny object.
 TypeCode type()
Returns the TypeCode associated with this DynAny object.

Method Detail

type

public TypeCode type()
Returns the TypeCode associated with this DynAny object. A DynAny object is created with a TypeCode value assigned to it. This TypeCode value determines the type of the value handled through the DynAny object. Note that the TypeCode associated with a DynAny object is initialized at the time the DynAny is created and cannot be changed during lifetime of the DynAny object.

Returns:
The TypeCode associated with this DynAny object

assign

public void assign(DynAny dyn_any)
            throws TypeMismatch
Initializes the value associated with a DynAny object with the value associated with another DynAny object. The current position of the target DynAny is set to zero for values that have components and to -1 for values that do not have components.

Parameters:
dyn_any -
Throws:
TypeMismatch - if the type of the passed DynAny is not equivalent to the type of target DynAny

from_any

public void from_any(Any value)
              throws TypeMismatch,
                     InvalidValue
Initializes the value associated with a DynAny object with the value contained in an any. The current position of the target DynAny is set to zero for values that have components and to -1 for values that do not have components.

Throws:
TypeMismatch - if the type of the passed Any is not equivalent to the type of target DynAny
InvalidValue - if the passed Any does not contain a legal value (such as a null string)

to_any

public Any to_any()
Creates an any value from a DynAny object. A copy of the TypeCode associated with the DynAny object is assigned to the resulting any. The value associated with the DynAny object is copied into the any.

Returns:
a new Any object with the same value and TypeCode

equal

public boolean equal(DynAny dyn_any)
Compares two DynAny values for equality. Two DynAny values are equal if their TypeCodes are equivalent and, recursively, all component DynAnys have equal values. The current position of the two DynAnys being compared has no effect on the result of equal.

Returns:
true of the DynAnys are equal, false otherwise

destroy

public void destroy()
Destroys a DynAny object. This operation frees any resources used to represent the data value associated with a DynAny object. It must be invoked on references obtained from one of the creation operations on the ORB interface or on a reference returned by DynAny.copy() to avoid resource leaks. Invoking destroy on component DynAny objects (for example, on objects returned by the current_component operation) does nothing. Destruction of a DynAny object implies destruction of all DynAny objects obtained from it. That is, references to components of a destroyed DynAny become invalid. Invocations on such references raise OBJECT_NOT_EXIST. It is possible to manipulate a component of a DynAny beyond the life time of the DynAny from which the component was obtained by making a copy of the component with the copy operation before destroying the DynAny from which the component was obtained.

copy

public DynAny copy()
Creates a new DynAny object whose value is a deep copy of the DynAny on which it is invoked. The operation is polymorphic, that is, invoking it on one of the types derived from DynAny, such as DynStruct, creates the derived type but returns its reference as the DynAny base type.

Returns:
a deep copy of the DynAny object

insert_boolean

public void insert_boolean(boolean value)
                    throws TypeMismatch,
                           InvalidValue
Inserts a boolean value into the DynAny.

Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_octet

public void insert_octet(byte value)
                  throws TypeMismatch,
                         InvalidValue
Inserts a byte value into the DynAny. The IDL octet data type is mapped to the Java byte data type.

Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_char

public void insert_char(char value)
                 throws TypeMismatch,
                        InvalidValue
Inserts a char value into the DynAny.

Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_short

public void insert_short(short value)
                  throws TypeMismatch,
                         InvalidValue
Inserts a short value into the DynAny.

Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_ushort

public void insert_ushort(short value)
                   throws TypeMismatch,
                          InvalidValue
Inserts a short value into the DynAny. The IDL ushort data type is mapped to the Java short data type.

Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_long

public void insert_long(int value)
                 throws TypeMismatch,
                        InvalidValue
Inserts an integer value into the DynAny. The IDL long data type is mapped to the Java int data type.

Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_ulong

public void insert_ulong(int value)
                  throws TypeMismatch,
                         InvalidValue
Inserts an integer value into the DynAny. The IDL ulong data type is mapped to the Java int data type.

Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_float

public void insert_float(float value)
                  throws TypeMismatch,
                         InvalidValue
Inserts a float value into the DynAny.

Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_double

public void insert_double(double value)
                   throws TypeMismatch,
                          InvalidValue
Inserts a double value into the DynAny.

Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_string

public void insert_string(String value)
                   throws TypeMismatch,
                          InvalidValue
Inserts a string value into the DynAny. Both bounded and unbounded strings are inserted using this method.

Throws:
InvalidValue - if this DynAny has components but has a current position of -1
InvalidValue - if the string inserted is longer than the bound of a bounded string
TypeMismatch - if called on a DynAny whose current component itself has components

insert_reference

public void insert_reference(Object value)
                      throws TypeMismatch,
                             InvalidValue
Inserts a reference to a CORBA object into the DynAny.

Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_typecode

public void insert_typecode(TypeCode value)
                     throws TypeMismatch,
                            InvalidValue
Inserts a TypeCode object into the DynAny.

Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_longlong

public void insert_longlong(long value)
                     throws TypeMismatch,
                            InvalidValue
Inserts a long value into the DynAny. The IDL long long data type is mapped to the Java long data type.

Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_ulonglong

public void insert_ulonglong(long value)
                      throws TypeMismatch,
                             InvalidValue
Inserts a long value into the DynAny. The IDL unsigned long long data type is mapped to the Java long data type.

Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_wchar

public void insert_wchar(char value)
                  throws TypeMismatch,
                         InvalidValue
Inserts a char value into the DynAny. The IDL wchar data type is mapped to the Java char data type.

Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_wstring

public void insert_wstring(String value)
                    throws TypeMismatch,
                           InvalidValue
Inserts a string value into the DynAny. Both bounded and unbounded strings are inserted using this method.

Throws:
InvalidValue - if this DynAny has components but has a current position of -1
InvalidValue - if the string inserted is longer than the bound of a bounded string
TypeMismatch

insert_any

public void insert_any(Any value)
                throws TypeMismatch,
                       InvalidValue
Inserts an Any value into the Any represented by this DynAny.

Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_dyn_any

public void insert_dyn_any(DynAny value)
                    throws TypeMismatch,
                           InvalidValue
Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.

Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

insert_val

public void insert_val(Serializable value)
                throws TypeMismatch,
                       InvalidValue
Inserts a reference to a Serializable object into this DynAny. The IDL ValueBase type is mapped to the Java Serializable type.

Throws:
InvalidValue - if this DynAny has components but has a current position of -1
TypeMismatch - if called on a DynAny whose current component itself has components

get_boolean

public boolean get_boolean()
                    throws TypeMismatch,
                           InvalidValue
Extracts the boolean value from this DynAny.

Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_octet

public byte get_octet()
               throws TypeMismatch,
                      InvalidValue
Extracts the byte value from this DynAny. The IDL octet data type is mapped to the Java byte data type.

Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_char

public char get_char()
              throws TypeMismatch,
                     InvalidValue
Extracts the char value from this DynAny.

Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_short

public short get_short()
                throws TypeMismatch,
                       InvalidValue
Extracts the short value from this DynAny.

Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_ushort

public short get_ushort()
                 throws TypeMismatch,
                        InvalidValue
Extracts the short value from this DynAny. The IDL ushort data type is mapped to the Java short data type.

Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_long

public int get_long()
             throws TypeMismatch,
                    InvalidValue
Extracts the integer value from this DynAny. The IDL long data type is mapped to the Java int data type.

Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_ulong

public int get_ulong()
              throws TypeMismatch,
                     InvalidValue
Extracts the integer value from this DynAny. The IDL ulong data type is mapped to the Java int data type.

Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_float

public float get_float()
                throws TypeMismatch,
                       InvalidValue
Extracts the float value from this DynAny.

Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_double

public double get_double()
                  throws TypeMismatch,
                         InvalidValue
Extracts the double value from this DynAny.

Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_string

public String get_string()
                  throws TypeMismatch,
                         InvalidValue
Extracts the string value from this DynAny. Both bounded and unbounded strings are extracted using this method.

Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_reference

public Object get_reference()
                     throws TypeMismatch,
                            InvalidValue
Extracts the reference to a CORBA Object from this DynAny.

Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_typecode

public TypeCode get_typecode()
                      throws TypeMismatch,
                             InvalidValue
Extracts the TypeCode object from this DynAny.

Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_longlong

public long get_longlong()
                  throws TypeMismatch,
                         InvalidValue
Extracts the long value from this DynAny. The IDL long long data type is mapped to the Java long data type.

Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_ulonglong

public long get_ulonglong()
                   throws TypeMismatch,
                          InvalidValue
Extracts the long value from this DynAny. The IDL unsigned long long data type is mapped to the Java long data type.

Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_wchar

public char get_wchar()
               throws TypeMismatch,
                      InvalidValue
Extracts the long value from this DynAny. The IDL wchar data type is mapped to the Java char data type.

Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_wstring

public String get_wstring()
                   throws TypeMismatch,
                          InvalidValue
Extracts the string value from this DynAny. Both bounded and unbounded strings are extracted using this method.

Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue

get_any

public Any get_any()
            throws TypeMismatch,
                   InvalidValue
Extracts an Any value contained in the Any represented by this DynAny.

Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_dyn_any

public DynAny get_dyn_any()
                   throws TypeMismatch,
                          InvalidValue
Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.

Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

get_val

public Serializable get_val()
                     throws TypeMismatch,
                            InvalidValue
Extracts a Serializable object from this DynAny. The IDL ValueBase type is mapped to the Java Serializable type.

Throws:
TypeMismatch - if the accessed component in the DynAny is of a type that is not equivalent to the requested type.
TypeMismatch - if called on a DynAny whose current component itself has components
InvalidValue - if this DynAny has components but has a current position of -1

seek

public boolean seek(int index)
Sets the current position to index. The current position is indexed 0 to n-1, that is, index zero corresponds to the first component. The operation returns true if the resulting current position indicates a component of the DynAny and false if index indicates a position that does not correspond to a component. Calling seek with a negative index is legal. It sets the current position to -1 to indicate no component and returns false. Passing a non-negative index value for a DynAny that does not have a component at the corresponding position sets the current position to -1 and returns false.

rewind

public void rewind()
Is equivalent to seek(0).

next

public boolean next()
Advances the current position to the next component. The operation returns true while the resulting current position indicates a component, false otherwise. A false return value leaves the current position at -1. Invoking next on a DynAny without components leaves the current position at -1 and returns false.

component_count

public int component_count()
Returns the number of components of a DynAny. For a DynAny without components, it returns zero. The operation only counts the components at the top level. For example, if component_count is invoked on a DynStruct with a single member, the return value is 1, irrespective of the type of the member.
  • For sequences, the operation returns the current number of elements.
  • For structures, exceptions, and value types, the operation returns the number of members.
  • For arrays, the operation returns the number of elements.
  • For unions, the operation returns 2 if the discriminator indicates that a named member is active, otherwise, it returns 1.
  • For DynFixed and DynEnum, the operation returns zero.

current_component

public DynAny current_component()
                         throws TypeMismatch
Returns the DynAny for the component at the current position. It does not advance the current position, so repeated calls to current_component without an intervening call to rewind, next, or seek return the same component. The returned DynAny object reference can be used to get/set the value of the current component. If the current component represents a complex type, the returned reference can be narrowed based on the TypeCode to get the interface corresponding to the to the complex type. Calling current_component on a DynAny that cannot have components, such as a DynEnum or an empty exception, raises TypeMismatch. Calling current_component on a DynAny whose current position is -1 returns a nil reference. The iteration operations, together with current_component, can be used to dynamically compose an any value. After creating a dynamic any, such as a DynStruct, current_component and next can be used to initialize all the components of the value. Once the dynamic value is completely initialized, to_any creates the corresponding any value.

Throws:
TypeMismatch - If called on a DynAny that cannot have components, such as a DynEnum or an empty exception
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynAnySeqHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Class DynAnySeqHelper

java.lang.Object
    extended by org.omg.DynamicAny.DynAnySeqHelper
public abstract class DynAnySeqHelper
extends Object

org/omg/DynamicAny/DynAnySeqHelper.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/DynamicAny/DynamicAny.idl Thursday, June 12, 2003 9:59:26 PM GMT-08:00

Constructor Summary
DynAnySeqHelper()
Method Summary
static DynAny[] | extract(Any a)
static String | id()
static void | insert(Any a, DynAny[] that)
static DynAny[] | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, DynAny[] value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DynAnySeqHelper

public DynAnySeqHelper()
Method Detail

insert

public static void insert(Any a,
                          DynAny[] that)

extract

public static DynAny[] extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static DynAny[] read(InputStream istream)

write

public static void write(OutputStream ostream,
                         DynAny[] value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynArray (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Interface DynArray

All Superinterfaces:
DynAny, DynAnyOperations, DynArrayOperations, IDLEntity, Object, Serializable
All Known Implementing Classes:
_DynArrayStub
public interface DynArray
extends DynArrayOperations, DynAny, IDLEntity

DynArray objects support the manipulation of IDL arrays. Note that the dimension of the array is contained in the TypeCode which is accessible through the type attribute. It can also be obtained by calling the component_count operation.

Methods inherited from interface org.omg.DynamicAny.DynArrayOperations
get_elements_as_dyn_any, get_elements, set_elements_as_dyn_any, set_elements
Methods inherited from interface org.omg.DynamicAny.DynAnyOperations
assign, component_count, copy, current_component, destroy, equal, from_any, get_any, get_boolean, get_char, get_double, get_dyn_any, get_float, get_long, get_longlong, get_octet, get_reference, get_short, get_string, get_typecode, get_ulong, get_ulonglong, get_ushort, get_val, get_wchar, get_wstring, insert_any, insert_boolean, insert_char, insert_double, insert_dyn_any, insert_float, insert_long, insert_longlong, insert_octet, insert_reference, insert_short, insert_string, insert_typecode, insert_ulong, insert_ulonglong, insert_ushort, insert_val, insert_wchar, insert_wstring, next, rewind, seek, to_any, type
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynArrayHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Class DynArrayHelper

java.lang.Object
    extended by org.omg.DynamicAny.DynArrayHelper
public abstract class DynArrayHelper
extends Object

DynArray objects support the manipulation of IDL arrays. Note that the dimension of the array is contained in the TypeCode which is accessible through the type attribute. It can also be obtained by calling the component_count operation.

Constructor Summary
DynArrayHelper()
Method Summary
static DynArray | extract(Any a)
static String | id()
static void | insert(Any a, DynArray that)
static DynArray | narrow(Object obj)
static DynArray | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, DynArray value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DynArrayHelper

public DynArrayHelper()
Method Detail

insert

public static void insert(Any a,
                          DynArray that)

extract

public static DynArray extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static DynArray read(InputStream istream)

write

public static void write(OutputStream ostream,
                         DynArray value)

narrow

public static DynArray narrow(Object obj)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynArrayOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Interface DynArrayOperations

All Superinterfaces:
DynAnyOperations
All Known Subinterfaces:
DynArray
All Known Implementing Classes:
_DynArrayStub
public interface DynArrayOperations
extends DynAnyOperations

DynArray objects support the manipulation of IDL arrays. Note that the dimension of the array is contained in the TypeCode which is accessible through the type attribute. It can also be obtained by calling the component_count operation.

Method Summary
DynAny[] | get_elements_as_dyn_any() Returns the elements of the DynArray as DynAnys.
Any[] | get_elements() Returns the elements of the DynArray.
void | set_elements_as_dyn_any(DynAny[] value) Sets the DynArray to contain the passed elements.
void | set_elements(Any[] value) Sets the DynArray to contain the passed elements.
Methods inherited from interface org.omg.DynamicAny.DynAnyOperations
assign, component_count, copy, current_component, destroy, equal, from_any, get_any, get_boolean, get_char, get_double, get_dyn_any, get_float, get_long, get_longlong, get_octet, get_reference, get_short, get_string, get_typecode, get_ulong, get_ulonglong, get_ushort, get_val, get_wchar, get_wstring, insert_any, insert_boolean, insert_char, insert_double, insert_dyn_any, insert_float, insert_long, insert_longlong, insert_octet, insert_reference, insert_short, insert_string, insert_typecode, insert_ulong, insert_ulonglong, insert_ushort, insert_val, insert_wchar, insert_wstring, next, rewind, seek, to_any, type

Method Detail

get_elements

public Any[] get_elements()
Returns the elements of the DynArray.

set_elements

public void set_elements(Any[] value)
                  throws TypeMismatch,
                         InvalidValue
Sets the DynArray to contain the passed elements.

Throws:
TypeMismatch - if one or more elements have a type that is inconsistent with the DynArrays TypeCode
InvalidValue - if the sequence does not contain the same number of elements as the array dimension

get_elements_as_dyn_any

public DynAny[] get_elements_as_dyn_any()
Returns the elements of the DynArray as DynAnys.

set_elements_as_dyn_any

public void set_elements_as_dyn_any(DynAny[] value)
                             throws TypeMismatch,
                                    InvalidValue
Sets the DynArray to contain the passed elements.

Throws:
TypeMismatch - if one or more elements have a type that is inconsistent with the DynArrays TypeCode
InvalidValue - if the sequence does not contain the same number of elements as the array dimension
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynEnum (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Interface DynEnum

All Superinterfaces:
DynAny, DynAnyOperations, DynEnumOperations, IDLEntity, Object, Serializable
All Known Implementing Classes:
_DynEnumStub
public interface DynEnum
extends DynEnumOperations, DynAny, IDLEntity

DynEnum objects support the manipulation of IDL enumerated values. The current position of a DynEnum is always -1.

Methods inherited from interface org.omg.DynamicAny.DynEnumOperations
get_as_string, get_as_ulong, set_as_string, set_as_ulong
Methods inherited from interface org.omg.DynamicAny.DynAnyOperations
assign, component_count, copy, current_component, destroy, equal, from_any, get_any, get_boolean, get_char, get_double, get_dyn_any, get_float, get_long, get_longlong, get_octet, get_reference, get_short, get_string, get_typecode, get_ulong, get_ulonglong, get_ushort, get_val, get_wchar, get_wstring, insert_any, insert_boolean, insert_char, insert_double, insert_dyn_any, insert_float, insert_long, insert_longlong, insert_octet, insert_reference, insert_short, insert_string, insert_typecode, insert_ulong, insert_ulonglong, insert_ushort, insert_val, insert_wchar, insert_wstring, next, rewind, seek, to_any, type
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynEnumHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Class DynEnumHelper

java.lang.Object
    extended by org.omg.DynamicAny.DynEnumHelper
public abstract class DynEnumHelper
extends Object

DynEnum objects support the manipulation of IDL enumerated values. The current position of a DynEnum is always -1.

Constructor Summary
DynEnumHelper()
Method Summary
static DynEnum | extract(Any a)
static String | id()
static void | insert(Any a, DynEnum that)
static DynEnum | narrow(Object obj)
static DynEnum | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, DynEnum value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DynEnumHelper

public DynEnumHelper()
Method Detail

insert

public static void insert(Any a,
                          DynEnum that)

extract

public static DynEnum extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static DynEnum read(InputStream istream)

write

public static void write(OutputStream ostream,
                         DynEnum value)

narrow

public static DynEnum narrow(Object obj)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynEnumOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Interface DynEnumOperations

All Superinterfaces:
DynAnyOperations
All Known Subinterfaces:
DynEnum
All Known Implementing Classes:
_DynEnumStub
public interface DynEnumOperations
extends DynAnyOperations

DynEnum objects support the manipulation of IDL enumerated values. The current position of a DynEnum is always -1.

Method Summary
String | get_as_string() Returns the value of the DynEnum as an IDL identifier.
int | get_as_ulong() Returns the value of the DynEnum as the enumerated value's ordinal value.
void | set_as_string(String value) Sets the value of the DynEnum to the enumerated value whose IDL identifier is passed in the value parameter.
void | set_as_ulong(int value) Sets the value of the DynEnum as the enumerated value's ordinal value.
Methods inherited from interface org.omg.DynamicAny.DynAnyOperations
assign, component_count, copy, current_component, destroy, equal, from_any, get_any, get_boolean, get_char, get_double, get_dyn_any, get_float, get_long, get_longlong, get_octet, get_reference, get_short, get_string, get_typecode, get_ulong, get_ulonglong, get_ushort, get_val, get_wchar, get_wstring, insert_any, insert_boolean, insert_char, insert_double, insert_dyn_any, insert_float, insert_long, insert_longlong, insert_octet, insert_reference, insert_short, insert_string, insert_typecode, insert_ulong, insert_ulonglong, insert_ushort, insert_val, insert_wchar, insert_wstring, next, rewind, seek, to_any, type

Method Detail

get_as_string

public String get_as_string()
Returns the value of the DynEnum as an IDL identifier.

set_as_string

public void set_as_string(String value)
                   throws InvalidValue
Sets the value of the DynEnum to the enumerated value whose IDL identifier is passed in the value parameter.

Throws:
InvalidValue - If value contains a string that is not a valid IDL identifier for the corresponding enumerated type

get_as_ulong

public int get_as_ulong()
Returns the value of the DynEnum as the enumerated value's ordinal value. Enumerators have ordinal values 0 to n-1, as they appear from left to right in the corresponding IDL definition.

set_as_ulong

public void set_as_ulong(int value)
                  throws InvalidValue
Sets the value of the DynEnum as the enumerated value's ordinal value.

Throws:
InvalidValue - If value contains a value that is outside the range of ordinal values for the corresponding enumerated type
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynFixed (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Interface DynFixed

All Superinterfaces:
DynAny, DynAnyOperations, DynFixedOperations, IDLEntity, Object, Serializable
All Known Implementing Classes:
_DynFixedStub
public interface DynFixed
extends DynFixedOperations, DynAny, IDLEntity

DynFixed objects support the manipulation of IDL fixed values. Because IDL does not have a generic type that can represent fixed types with arbitrary number of digits and arbitrary scale, the operations use the IDL string type.

Methods inherited from interface org.omg.DynamicAny.DynFixedOperations
get_value, set_value
Methods inherited from interface org.omg.DynamicAny.DynAnyOperations
assign, component_count, copy, current_component, destroy, equal, from_any, get_any, get_boolean, get_char, get_double, get_dyn_any, get_float, get_long, get_longlong, get_octet, get_reference, get_short, get_string, get_typecode, get_ulong, get_ulonglong, get_ushort, get_val, get_wchar, get_wstring, insert_any, insert_boolean, insert_char, insert_double, insert_dyn_any, insert_float, insert_long, insert_longlong, insert_octet, insert_reference, insert_short, insert_string, insert_typecode, insert_ulong, insert_ulonglong, insert_ushort, insert_val, insert_wchar, insert_wstring, next, rewind, seek, to_any, type
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynFixedHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Class DynFixedHelper

java.lang.Object
    extended by org.omg.DynamicAny.DynFixedHelper
public abstract class DynFixedHelper
extends Object

DynFixed objects support the manipulation of IDL fixed values. Because IDL does not have a generic type that can represent fixed types with arbitrary number of digits and arbitrary scale, the operations use the IDL string type.

Constructor Summary
DynFixedHelper()
Method Summary
static DynFixed | extract(Any a)
static String | id()
static void | insert(Any a, DynFixed that)
static DynFixed | narrow(Object obj)
static DynFixed | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, DynFixed value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DynFixedHelper

public DynFixedHelper()
Method Detail

insert

public static void insert(Any a,
                          DynFixed that)

extract

public static DynFixed extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static DynFixed read(InputStream istream)

write

public static void write(OutputStream ostream,
                         DynFixed value)

narrow

public static DynFixed narrow(Object obj)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynFixedOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Interface DynFixedOperations

All Superinterfaces:
DynAnyOperations
All Known Subinterfaces:
DynFixed
All Known Implementing Classes:
_DynFixedStub
public interface DynFixedOperations
extends DynAnyOperations

DynFixed objects support the manipulation of IDL fixed values. Because IDL does not have a generic type that can represent fixed types with arbitrary number of digits and arbitrary scale, the operations use the IDL string type.

Method Summary
String | get_value() Returns the value of a DynFixed.
boolean | set_value(String val) Sets the value of the DynFixed.
Methods inherited from interface org.omg.DynamicAny.DynAnyOperations
assign, component_count, copy, current_component, destroy, equal, from_any, get_any, get_boolean, get_char, get_double, get_dyn_any, get_float, get_long, get_longlong, get_octet, get_reference, get_short, get_string, get_typecode, get_ulong, get_ulonglong, get_ushort, get_val, get_wchar, get_wstring, insert_any, insert_boolean, insert_char, insert_double, insert_dyn_any, insert_float, insert_long, insert_longlong, insert_octet, insert_reference, insert_short, insert_string, insert_typecode, insert_ulong, insert_ulonglong, insert_ushort, insert_val, insert_wchar, insert_wstring, next, rewind, seek, to_any, type

Method Detail

get_value

public String get_value()
Returns the value of a DynFixed.

set_value

public boolean set_value(String val)
                  throws TypeMismatch,
                         InvalidValue
Sets the value of the DynFixed. The val string must contain a fixed string constant in the same format as used for IDL fixed-point literals. However, the trailing d or D is optional. The return value is true if val can be represented as the DynFixed without loss of precision. If val has more fractional digits than can be represented in the DynFixed, fractional digits are truncated and the return value is false.

Throws:
TypeMismatch - If val does not contain a valid fixed-point literal or contains extraneous characters other than leading or trailing white space
InvalidValue - If val contains a value whose scale exceeds that of the DynFixed or is not initialized
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynSequence (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Interface DynSequence

All Superinterfaces:
DynAny, DynAnyOperations, DynSequenceOperations, IDLEntity, Object, Serializable
All Known Implementing Classes:
_DynSequenceStub
public interface DynSequence
extends DynSequenceOperations, DynAny, IDLEntity

DynSequence objects support the manipulation of IDL sequences.

Methods inherited from interface org.omg.DynamicAny.DynSequenceOperations
get_elements_as_dyn_any, get_elements, get_length, set_elements_as_dyn_any, set_elements, set_length
Methods inherited from interface org.omg.DynamicAny.DynAnyOperations
assign, component_count, copy, current_component, destroy, equal, from_any, get_any, get_boolean, get_char, get_double, get_dyn_any, get_float, get_long, get_longlong, get_octet, get_reference, get_short, get_string, get_typecode, get_ulong, get_ulonglong, get_ushort, get_val, get_wchar, get_wstring, insert_any, insert_boolean, insert_char, insert_double, insert_dyn_any, insert_float, insert_long, insert_longlong, insert_octet, insert_reference, insert_short, insert_string, insert_typecode, insert_ulong, insert_ulonglong, insert_ushort, insert_val, insert_wchar, insert_wstring, next, rewind, seek, to_any, type
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynSequenceHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Class DynSequenceHelper

java.lang.Object
    extended by org.omg.DynamicAny.DynSequenceHelper
public abstract class DynSequenceHelper
extends Object

DynSequence objects support the manipulation of IDL sequences.

Constructor Summary
DynSequenceHelper()
Method Summary
static DynSequence | extract(Any a)
static String | id()
static void | insert(Any a, DynSequence that)
static DynSequence | narrow(Object obj)
static DynSequence | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, DynSequence value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DynSequenceHelper

public DynSequenceHelper()
Method Detail

insert

public static void insert(Any a,
                          DynSequence that)

extract

public static DynSequence extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static DynSequence read(InputStream istream)

write

public static void write(OutputStream ostream,
                         DynSequence value)

narrow

public static DynSequence narrow(Object obj)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynSequenceOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Interface DynSequenceOperations

All Superinterfaces:
DynAnyOperations
All Known Subinterfaces:
DynSequence
All Known Implementing Classes:
_DynSequenceStub
public interface DynSequenceOperations
extends DynAnyOperations

DynSequence objects support the manipulation of IDL sequences.

Method Summary
DynAny[] | get_elements_as_dyn_any() Returns the DynAnys representing the elements of the sequence.
Any[] | get_elements() Returns the elements of the sequence.
int | get_length() Returns the current length of the sequence.
void | set_elements_as_dyn_any(DynAny[] value) Sets the elements of a sequence using DynAnys.
void | set_elements(Any[] value) Sets the elements of a sequence.
void | set_length(int len) Sets the length of the sequence.
Methods inherited from interface org.omg.DynamicAny.DynAnyOperations
assign, component_count, copy, current_component, destroy, equal, from_any, get_any, get_boolean, get_char, get_double, get_dyn_any, get_float, get_long, get_longlong, get_octet, get_reference, get_short, get_string, get_typecode, get_ulong, get_ulonglong, get_ushort, get_val, get_wchar, get_wstring, insert_any, insert_boolean, insert_char, insert_double, insert_dyn_any, insert_float, insert_long, insert_longlong, insert_octet, insert_reference, insert_short, insert_string, insert_typecode, insert_ulong, insert_ulonglong, insert_ushort, insert_val, insert_wchar, insert_wstring, next, rewind, seek, to_any, type

Method Detail

get_length

public int get_length()
Returns the current length of the sequence.

set_length

public void set_length(int len)
                throws InvalidValue
Sets the length of the sequence. Increasing the length of a sequence adds new elements at the tail without affecting the values of already existing elements. Newly added elements are default-initialized. Increasing the length of a sequence sets the current position to the first newly-added element if the previous current position was -1. Otherwise, if the previous current position was not -1, the current position is not affected. Decreasing the length of a sequence removes elements from the tail without affecting the value of those elements that remain. The new current position after decreasing the length of a sequence is determined as follows:
  • If the length of the sequence is set to zero, the current position is set to -1.
  • If the current position is -1 before decreasing the length, it remains at -1.
  • If the current position indicates a valid element and that element is not removed when the length is decreased, the current position remains unaffected.
  • If the current position indicates a valid element and that element is removed, the current position is set to -1.

Throws:
InvalidValue - if this is a bounded sequence and len is larger than the bound

get_elements

public Any[] get_elements()
Returns the elements of the sequence.

set_elements

public void set_elements(Any[] value)
                  throws TypeMismatch,
                         InvalidValue
Sets the elements of a sequence. The length of the DynSequence is set to the length of value. The current position is set to zero if value has non-zero length and to -1 if value is a zero-length sequence.

Throws:
TypeMismatch - if value contains one or more elements whose TypeCode is not equivalent to the element TypeCode of the DynSequence
InvalidValue - if the length of value exceeds the bound of a bounded sequence

get_elements_as_dyn_any

public DynAny[] get_elements_as_dyn_any()
Returns the DynAnys representing the elements of the sequence.

set_elements_as_dyn_any

public void set_elements_as_dyn_any(DynAny[] value)
                             throws TypeMismatch,
                                    InvalidValue
Sets the elements of a sequence using DynAnys. The length of the DynSequence is set to the length of value. The current position is set to zero if value has non-zero length and to -1 if value is a zero-length sequence.

Throws:
TypeMismatch - if value contains one or more elements whose TypeCode is not equivalent to the element TypeCode of the DynSequence
InvalidValue - if the length of value exceeds the bound of a bounded sequence
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynStruct (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Interface DynStruct

All Superinterfaces:
DynAny, DynAnyOperations, DynStructOperations, IDLEntity, Object, Serializable
All Known Implementing Classes:
_DynStructStub
public interface DynStruct
extends DynStructOperations, DynAny, IDLEntity

DynStruct objects support the manipulation of IDL struct and exception values. Members of the exceptions are handled in the same way as members of a struct.

Methods inherited from interface org.omg.DynamicAny.DynStructOperations
current_member_kind, current_member_name, get_members_as_dyn_any, get_members, set_members_as_dyn_any, set_members
Methods inherited from interface org.omg.DynamicAny.DynAnyOperations
assign, component_count, copy, current_component, destroy, equal, from_any, get_any, get_boolean, get_char, get_double, get_dyn_any, get_float, get_long, get_longlong, get_octet, get_reference, get_short, get_string, get_typecode, get_ulong, get_ulonglong, get_ushort, get_val, get_wchar, get_wstring, insert_any, insert_boolean, insert_char, insert_double, insert_dyn_any, insert_float, insert_long, insert_longlong, insert_octet, insert_reference, insert_short, insert_string, insert_typecode, insert_ulong, insert_ulonglong, insert_ushort, insert_val, insert_wchar, insert_wstring, next, rewind, seek, to_any, type
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynStructHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Class DynStructHelper

java.lang.Object
    extended by org.omg.DynamicAny.DynStructHelper
public abstract class DynStructHelper
extends Object

DynStruct objects support the manipulation of IDL struct and exception values. Members of the exceptions are handled in the same way as members of a struct.

Constructor Summary
DynStructHelper()
Method Summary
static DynStruct | extract(Any a)
static String | id()
static void | insert(Any a, DynStruct that)
static DynStruct | narrow(Object obj)
static DynStruct | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, DynStruct value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DynStructHelper

public DynStructHelper()
Method Detail

insert

public static void insert(Any a,
                          DynStruct that)

extract

public static DynStruct extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static DynStruct read(InputStream istream)

write

public static void write(OutputStream ostream,
                         DynStruct value)

narrow

public static DynStruct narrow(Object obj)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynStructOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Interface DynStructOperations

All Superinterfaces:
DynAnyOperations
All Known Subinterfaces:
DynStruct
All Known Implementing Classes:
_DynStructStub
public interface DynStructOperations
extends DynAnyOperations

DynStruct objects support the manipulation of IDL struct and exception values. Members of the exceptions are handled in the same way as members of a struct.

Method Summary
TCKind | current_member_kind() Returns the TCKind associated with the member at the current position.
String | current_member_name() Returns the name of the member at the current position.
NameDynAnyPair[] | get_members_as_dyn_any() Returns a sequence of NameDynAnyPairs describing the name and the value of each member in the struct associated with a DynStruct object.
NameValuePair[] | get_members() Returns a sequence of NameValuePairs describing the name and the value of each member in the struct associated with a DynStruct object.
void | set_members_as_dyn_any(NameDynAnyPair[] value) Initializes the struct data value associated with a DynStruct object from a sequence of NameDynAnyPairs.
void | set_members(NameValuePair[] value) Initializes the struct data value associated with a DynStruct object from a sequence of NameValuePairs.
Methods inherited from interface org.omg.DynamicAny.DynAnyOperations
assign, component_count, copy, current_component, destroy, equal, from_any, get_any, get_boolean, get_char, get_double, get_dyn_any, get_float, get_long, get_longlong, get_octet, get_reference, get_short, get_string, get_typecode, get_ulong, get_ulonglong, get_ushort, get_val, get_wchar, get_wstring, insert_any, insert_boolean, insert_char, insert_double, insert_dyn_any, insert_float, insert_long, insert_longlong, insert_octet, insert_reference, insert_short, insert_string, insert_typecode, insert_ulong, insert_ulonglong, insert_ushort, insert_val, insert_wchar, insert_wstring, next, rewind, seek, to_any, type

Method Detail

current_member_name

public String current_member_name()
                           throws TypeMismatch,
                                  InvalidValue
Returns the name of the member at the current position. This operation may return an empty string since the TypeCode of the value being manipulated may not contain the names of members.

Throws:
TypeMismatch - if the DynStruct represents an empty exception.
InvalidValue - if the current position does not indicate a member

current_member_kind

public TCKind current_member_kind()
                           throws TypeMismatch,
                                  InvalidValue
Returns the TCKind associated with the member at the current position.

Throws:
TypeMismatch - if the DynStruct represents an empty exception.
InvalidValue - if the current position does not indicate a member

get_members

public NameValuePair[] get_members()
Returns a sequence of NameValuePairs describing the name and the value of each member in the struct associated with a DynStruct object. The sequence contains members in the same order as the declaration order of members as indicated by the DynStruct's TypeCode. The current position is not affected. The member names in the returned sequence will be empty strings if the DynStruct's TypeCode does not contain member names.

set_members

public void set_members(NameValuePair[] value)
                 throws TypeMismatch,
                        InvalidValue
Initializes the struct data value associated with a DynStruct object from a sequence of NameValuePairs. The operation sets the current position to zero if the passed sequences has non-zero length. Otherwise, if an empty sequence is passed, the current position is set to -1.

Members must appear in the NameValuePairs in the order in which they appear in the IDL specification of the struct as indicated by the DynStruct's TypeCode or they must be empty strings. The operation makes no attempt to assign member values based on member names.

Throws:
TypeMismatch - if the member names supplied in the passed sequence do not match the corresponding member name in the DynStruct's TypeCode and they are not empty strings
InvalidValue - if the passed sequence has a number of elements that disagrees with the number of members as indicated by the DynStruct's TypeCode

get_members_as_dyn_any

public NameDynAnyPair[] get_members_as_dyn_any()
Returns a sequence of NameDynAnyPairs describing the name and the value of each member in the struct associated with a DynStruct object. The sequence contains members in the same order as the declaration order of members as indicated by the DynStruct's TypeCode. The current position is not affected. The member names in the returned sequence will be empty strings if the DynStruct's TypeCode does not contain member names.

set_members_as_dyn_any

public void set_members_as_dyn_any(NameDynAnyPair[] value)
                            throws TypeMismatch,
                                   InvalidValue
Initializes the struct data value associated with a DynStruct object from a sequence of NameDynAnyPairs. The operation sets the current position to zero if the passed sequences has non-zero length. Otherwise, if an empty sequence is passed, the current position is set to -1.

Members must appear in the NameDynAnyPairs in the order in which they appear in the IDL specification of the struct as indicated by the DynStruct's TypeCode or they must be empty strings. The operation makes no attempt to assign member values based on member names.

Throws:
TypeMismatch - if the member names supplied in the passed sequence do not match the corresponding member name in the DynStruct's TypeCode and they are not empty strings
InvalidValue - if the passed sequence has a number of elements that disagrees with the number of members as indicated by the DynStruct's TypeCode
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynUnion (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Interface DynUnion

All Superinterfaces:
DynAny, DynAnyOperations, DynUnionOperations, IDLEntity, Object, Serializable
All Known Implementing Classes:
_DynUnionStub
public interface DynUnion
extends DynUnionOperations, DynAny, IDLEntity

DynUnion objects support the manipulation of IDL unions. A union can have only two valid current positions:

  • zero, which denotes the discriminator
  • one, which denotes the active member
The component_count value for a union depends on the current discriminator: it is 2 for a union whose discriminator indicates a named member, and 1 otherwise.

Methods inherited from interface org.omg.DynamicAny.DynUnionOperations
discriminator_kind, get_discriminator, has_no_active_member, member_kind, member_name, member, set_discriminator, set_to_default_member, set_to_no_active_member
Methods inherited from interface org.omg.DynamicAny.DynAnyOperations
assign, component_count, copy, current_component, destroy, equal, from_any, get_any, get_boolean, get_char, get_double, get_dyn_any, get_float, get_long, get_longlong, get_octet, get_reference, get_short, get_string, get_typecode, get_ulong, get_ulonglong, get_ushort, get_val, get_wchar, get_wstring, insert_any, insert_boolean, insert_char, insert_double, insert_dyn_any, insert_float, insert_long, insert_longlong, insert_octet, insert_reference, insert_short, insert_string, insert_typecode, insert_ulong, insert_ulonglong, insert_ushort, insert_val, insert_wchar, insert_wstring, next, rewind, seek, to_any, type
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynUnionHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Class DynUnionHelper

java.lang.Object
    extended by org.omg.DynamicAny.DynUnionHelper
public abstract class DynUnionHelper
extends Object

DynUnion objects support the manipulation of IDL unions. A union can have only two valid current positions:

  • zero, which denotes the discriminator
  • one, which denotes the active member
The component_count value for a union depends on the current discriminator: it is 2 for a union whose discriminator indicates a named member, and 1 otherwise.

Constructor Summary
DynUnionHelper()
Method Summary
static DynUnion | extract(Any a)
static String | id()
static void | insert(Any a, DynUnion that)
static DynUnion | narrow(Object obj)
static DynUnion | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, DynUnion value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DynUnionHelper

public DynUnionHelper()
Method Detail

insert

public static void insert(Any a,
                          DynUnion that)

extract

public static DynUnion extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static DynUnion read(InputStream istream)

write

public static void write(OutputStream ostream,
                         DynUnion value)

narrow

public static DynUnion narrow(Object obj)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynUnionOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Interface DynUnionOperations

All Superinterfaces:
DynAnyOperations
All Known Subinterfaces:
DynUnion
All Known Implementing Classes:
_DynUnionStub
public interface DynUnionOperations
extends DynAnyOperations

DynUnion objects support the manipulation of IDL unions. A union can have only two valid current positions:

  • zero, which denotes the discriminator
  • one, which denotes the active member
The component_count value for a union depends on the current discriminator: it is 2 for a union whose discriminator indicates a named member, and 1 otherwise.

Method Summary
TCKind | discriminator_kind() Returns the TCKind value of the discriminators TypeCode.
DynAny | get_discriminator() Returns the current discriminator value.
boolean | has_no_active_member() Returns true if the union has no active member, that is, the unions value consists solely of its discriminator because the discriminator has a value that is not listed as an explicit case label.
TCKind | member_kind() Returns the TCKind value of the currently active members TypeCode.
String | member_name() Returns the name of the currently active member.
DynAny | member() Returns the currently active member.
void | set_discriminator(DynAny d) Sets the discriminator of the DynUnion to the specified value.
void | set_to_default_member() Sets the discriminator to a value that is consistent with the value of the default case of a union.
void | set_to_no_active_member() Sets the discriminator to a value that does not correspond to any of the unions case labels.
Methods inherited from interface org.omg.DynamicAny.DynAnyOperations
assign, component_count, copy, current_component, destroy, equal, from_any, get_any, get_boolean, get_char, get_double, get_dyn_any, get_float, get_long, get_longlong, get_octet, get_reference, get_short, get_string, get_typecode, get_ulong, get_ulonglong, get_ushort, get_val, get_wchar, get_wstring, insert_any, insert_boolean, insert_char, insert_double, insert_dyn_any, insert_float, insert_long, insert_longlong, insert_octet, insert_reference, insert_short, insert_string, insert_typecode, insert_ulong, insert_ulonglong, insert_ushort, insert_val, insert_wchar, insert_wstring, next, rewind, seek, to_any, type

Method Detail

get_discriminator

public DynAny get_discriminator()
Returns the current discriminator value.

set_discriminator

public void set_discriminator(DynAny d)
                       throws TypeMismatch
Sets the discriminator of the DynUnion to the specified value. Setting the discriminator to a value that is consistent with the currently active union member does not affect the currently active member. Setting the discriminator to a value that is inconsistent with the currently active member deactivates the member and activates the member that is consistent with the new discriminator value (if there is a member for that value) by initializing the member to its default value. Setting the discriminator of a union sets the current position to 0 if the discriminator value indicates a non-existent union member (has_no_active_member returns true in this case). Otherwise, if the discriminator value indicates a named union member, the current position is set to 1 (has_no_active_member returns false and component_count returns 2 in this case).

Throws:
TypeMismatch - if the TypeCode of the parameter is not equivalent to the TypeCode of the union?s discriminator

set_to_default_member

public void set_to_default_member()
                           throws TypeMismatch
Sets the discriminator to a value that is consistent with the value of the default case of a union. It sets the current position to zero and causes component_count to return 2.

Throws:
TypeMismatch - if the union does not have an explicit default case

set_to_no_active_member

public void set_to_no_active_member()
                             throws TypeMismatch
Sets the discriminator to a value that does not correspond to any of the unions case labels. It sets the current position to zero and causes component_count to return 1.

Throws:
TypeMismatch - if the union has an explicit default case or if it uses the entire range of discriminator values for explicit case labels

has_no_active_member

public boolean has_no_active_member()
Returns true if the union has no active member, that is, the unions value consists solely of its discriminator because the discriminator has a value that is not listed as an explicit case label. Calling this operation on a union that has a default case returns false. Calling this operation on a union that uses the entire range of discriminator values for explicit case labels returns false.

discriminator_kind

public TCKind discriminator_kind()
Returns the TCKind value of the discriminators TypeCode.

member_kind

public TCKind member_kind()
                   throws InvalidValue
Returns the TCKind value of the currently active members TypeCode.

Throws:
InvalidValue - if the union does not have a currently active member

member

public DynAny member()
              throws InvalidValue
Returns the currently active member. Note that the returned reference remains valid only for as long as the currently active member does not change. Using the returned reference beyond the life time of the currently active member raises OBJECT_NOT_EXIST.

Throws:
InvalidValue - if the union has no active member

member_name

public String member_name()
                   throws InvalidValue
Returns the name of the currently active member. If the unions TypeCode does not contain a member name for the currently active member, the operation returns an empty string.

Throws:
InvalidValue - if the union has no active member
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynValue (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Interface DynValue

All Superinterfaces:
DynAny, DynAnyOperations, DynValueCommon, DynValueCommonOperations, DynValueOperations, IDLEntity, Object, Serializable
All Known Implementing Classes:
_DynValueStub
public interface DynValue
extends DynValueOperations, DynValueCommon, IDLEntity

DynValue objects support the manipulation of IDL non-boxed value types. The DynValue interface can represent both null and non-null value types. For a DynValue representing a non-null value type, the DynValue's components comprise the public and private members of the value type, including those inherited from concrete base value types, in the order of definition. A DynValue representing a null value type has no components and a current position of -1.

Warning: Indiscriminantly changing the contents of private value type members can cause the value type implementation to break by violating internal constraints. Access to private members is provided to support such activities as ORB bridging and debugging and should not be used to arbitrarily violate the encapsulation of the value type.

Methods inherited from interface org.omg.DynamicAny.DynValueOperations
current_member_kind, current_member_name, get_members_as_dyn_any, get_members, set_members_as_dyn_any, set_members
Methods inherited from interface org.omg.DynamicAny.DynValueCommonOperations
is_null, set_to_null, set_to_value
Methods inherited from interface org.omg.DynamicAny.DynAnyOperations
assign, component_count, copy, current_component, destroy, equal, from_any, get_any, get_boolean, get_char, get_double, get_dyn_any, get_float, get_long, get_longlong, get_octet, get_reference, get_short, get_string, get_typecode, get_ulong, get_ulonglong, get_ushort, get_val, get_wchar, get_wstring, insert_any, insert_boolean, insert_char, insert_double, insert_dyn_any, insert_float, insert_long, insert_longlong, insert_octet, insert_reference, insert_short, insert_string, insert_typecode, insert_ulong, insert_ulonglong, insert_ushort, insert_val, insert_wchar, insert_wstring, next, rewind, seek, to_any, type
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynValueBox (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Interface DynValueBox

All Superinterfaces:
DynAny, DynAnyOperations, DynValueBoxOperations, DynValueCommon, DynValueCommonOperations, IDLEntity, Object, Serializable
public interface DynValueBox
extends DynValueBoxOperations, DynValueCommon, IDLEntity

DynValueBox objects support the manipulation of IDL boxed value types. The DynValueBox interface can represent both null and non-null value types. For a DynValueBox representing a non-null value type, the DynValueBox has a single component of the boxed type. A DynValueBox representing a null value type has no components and a current position of -1.

Methods inherited from interface org.omg.DynamicAny.DynValueBoxOperations
get_boxed_value_as_dyn_any, get_boxed_value, set_boxed_value_as_dyn_any, set_boxed_value
Methods inherited from interface org.omg.DynamicAny.DynValueCommonOperations
is_null, set_to_null, set_to_value
Methods inherited from interface org.omg.DynamicAny.DynAnyOperations
assign, component_count, copy, current_component, destroy, equal, from_any, get_any, get_boolean, get_char, get_double, get_dyn_any, get_float, get_long, get_longlong, get_octet, get_reference, get_short, get_string, get_typecode, get_ulong, get_ulonglong, get_ushort, get_val, get_wchar, get_wstring, insert_any, insert_boolean, insert_char, insert_double, insert_dyn_any, insert_float, insert_long, insert_longlong, insert_octet, insert_reference, insert_short, insert_string, insert_typecode, insert_ulong, insert_ulonglong, insert_ushort, insert_val, insert_wchar, insert_wstring, next, rewind, seek, to_any, type
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynValueBoxOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Interface DynValueBoxOperations

All Superinterfaces:
DynAnyOperations, DynValueCommonOperations
All Known Subinterfaces:
DynValueBox
public interface DynValueBoxOperations
extends DynValueCommonOperations

DynValueBox objects support the manipulation of IDL boxed value types. The DynValueBox interface can represent both null and non-null value types. For a DynValueBox representing a non-null value type, the DynValueBox has a single component of the boxed type. A DynValueBox representing a null value type has no components and a current position of -1.

Method Summary
DynAny | get_boxed_value_as_dyn_any() Returns the boxed value as a DynAny.
Any | get_boxed_value() Returns the boxed value as an Any.
void | set_boxed_value_as_dyn_any(DynAny boxed) Replaces the boxed value with the value contained in the parameter.
void | set_boxed_value(Any boxed) Replaces the boxed value with the specified value.
Methods inherited from interface org.omg.DynamicAny.DynValueCommonOperations
is_null, set_to_null, set_to_value
Methods inherited from interface org.omg.DynamicAny.DynAnyOperations
assign, component_count, copy, current_component, destroy, equal, from_any, get_any, get_boolean, get_char, get_double, get_dyn_any, get_float, get_long, get_longlong, get_octet, get_reference, get_short, get_string, get_typecode, get_ulong, get_ulonglong, get_ushort, get_val, get_wchar, get_wstring, insert_any, insert_boolean, insert_char, insert_double, insert_dyn_any, insert_float, insert_long, insert_longlong, insert_octet, insert_reference, insert_short, insert_string, insert_typecode, insert_ulong, insert_ulonglong, insert_ushort, insert_val, insert_wchar, insert_wstring, next, rewind, seek, to_any, type

Method Detail

get_boxed_value

public Any get_boxed_value()
                    throws InvalidValue
Returns the boxed value as an Any.

Throws:
InvalidValue - if this object represents a null value box type

set_boxed_value

public void set_boxed_value(Any boxed)
                     throws TypeMismatch
Replaces the boxed value with the specified value. If the DynBoxedValue represents a null valuetype, it is converted to a non-null value.

Throws:
TypeMismatch - if this object represents a non-null value box type and the type of the parameter is not matching the current boxed value type.

get_boxed_value_as_dyn_any

public DynAny get_boxed_value_as_dyn_any()
                                  throws InvalidValue
Returns the boxed value as a DynAny.

Throws:
InvalidValue - if this object represents a null value box type

set_boxed_value_as_dyn_any

public void set_boxed_value_as_dyn_any(DynAny boxed)
                                throws TypeMismatch
Replaces the boxed value with the value contained in the parameter. If the DynBoxedValue represents a null valuetype, it is converted to a non-null value.

Throws:
TypeMismatch - if this object represents a non-null value box type and the type of the parameter is not matching the current boxed value type.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynValueCommon (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Interface DynValueCommon

All Superinterfaces:
DynAny, DynAnyOperations, DynValueCommonOperations, IDLEntity, Object, Serializable
All Known Subinterfaces:
DynValue, DynValueBox
All Known Implementing Classes:
_DynValueStub
public interface DynValueCommon
extends DynValueCommonOperations, DynAny, IDLEntity

DynValueCommon provides operations supported by both the DynValue and DynValueBox interfaces.

Methods inherited from interface org.omg.DynamicAny.DynValueCommonOperations
is_null, set_to_null, set_to_value
Methods inherited from interface org.omg.DynamicAny.DynAnyOperations
assign, component_count, copy, current_component, destroy, equal, from_any, get_any, get_boolean, get_char, get_double, get_dyn_any, get_float, get_long, get_longlong, get_octet, get_reference, get_short, get_string, get_typecode, get_ulong, get_ulonglong, get_ushort, get_val, get_wchar, get_wstring, insert_any, insert_boolean, insert_char, insert_double, insert_dyn_any, insert_float, insert_long, insert_longlong, insert_octet, insert_reference, insert_short, insert_string, insert_typecode, insert_ulong, insert_ulonglong, insert_ushort, insert_val, insert_wchar, insert_wstring, next, rewind, seek, to_any, type
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynValueCommonOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Interface DynValueCommonOperations

All Superinterfaces:
DynAnyOperations
All Known Subinterfaces:
DynValue, DynValueBox, DynValueBoxOperations, DynValueCommon, DynValueOperations
All Known Implementing Classes:
_DynValueStub
public interface DynValueCommonOperations
extends DynAnyOperations

DynValueCommon provides operations supported by both the DynValue and DynValueBox interfaces.

Method Summary
boolean | is_null() Returns true if the DynValueCommon represents a null value type.
void | set_to_null() Changes the representation of a DynValueCommon to a null value type.
void | set_to_value() Replaces a null value type with a newly constructed value.
Methods inherited from interface org.omg.DynamicAny.DynAnyOperations
assign, component_count, copy, current_component, destroy, equal, from_any, get_any, get_boolean, get_char, get_double, get_dyn_any, get_float, get_long, get_longlong, get_octet, get_reference, get_short, get_string, get_typecode, get_ulong, get_ulonglong, get_ushort, get_val, get_wchar, get_wstring, insert_any, insert_boolean, insert_char, insert_double, insert_dyn_any, insert_float, insert_long, insert_longlong, insert_octet, insert_reference, insert_short, insert_string, insert_typecode, insert_ulong, insert_ulonglong, insert_ushort, insert_val, insert_wchar, insert_wstring, next, rewind, seek, to_any, type

Method Detail

is_null

public boolean is_null()
Returns true if the DynValueCommon represents a null value type.

set_to_null

public void set_to_null()
Changes the representation of a DynValueCommon to a null value type.

set_to_value

public void set_to_value()
Replaces a null value type with a newly constructed value. Its components are initialized to default values as in DynAnyFactory.create_dyn_any_from_type_code. If the DynValueCommon represents a non-null value type, then this operation has no effect.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynValueHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Class DynValueHelper

java.lang.Object
    extended by org.omg.DynamicAny.DynValueHelper
public abstract class DynValueHelper
extends Object

DynValue objects support the manipulation of IDL non-boxed value types. The DynValue interface can represent both null and non-null value types. For a DynValue representing a non-null value type, the DynValue's components comprise the public and private members of the value type, including those inherited from concrete base value types, in the order of definition. A DynValue representing a null value type has no components and a current position of -1.

Warning: Indiscriminantly changing the contents of private value type members can cause the value type implementation to break by violating internal constraints. Access to private members is provided to support such activities as ORB bridging and debugging and should not be used to arbitrarily violate the encapsulation of the value type.

Constructor Summary
DynValueHelper()
Method Summary
static DynValue | extract(Any a)
static String | id()
static void | insert(Any a, DynValue that)
static DynValue | narrow(Object obj)
static DynValue | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, DynValue value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DynValueHelper

public DynValueHelper()
Method Detail

insert

public static void insert(Any a,
                          DynValue that)

extract

public static DynValue extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static DynValue read(InputStream istream)

write

public static void write(OutputStream ostream,
                         DynValue value)

narrow

public static DynValue narrow(Object obj)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynValueOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Interface DynValueOperations

All Superinterfaces:
DynAnyOperations, DynValueCommonOperations
All Known Subinterfaces:
DynValue
All Known Implementing Classes:
_DynValueStub
public interface DynValueOperations
extends DynValueCommonOperations

DynValue objects support the manipulation of IDL non-boxed value types. The DynValue interface can represent both null and non-null value types. For a DynValue representing a non-null value type, the DynValue's components comprise the public and private members of the value type, including those inherited from concrete base value types, in the order of definition. A DynValue representing a null value type has no components and a current position of -1.

Warning: Indiscriminantly changing the contents of private value type members can cause the value type implementation to break by violating internal constraints. Access to private members is provided to support such activities as ORB bridging and debugging and should not be used to arbitrarily violate the encapsulation of the value type.

Method Summary
TCKind | current_member_kind() Returns the TCKind associated with the member at the current position.
String | current_member_name() Returns the name of the member at the current position.
NameDynAnyPair[] | get_members_as_dyn_any() Returns a sequence of NameDynAnyPairs describing the name and the value of each member in the value type.
NameValuePair[] | get_members() Returns a sequence of NameValuePairs describing the name and the value of each member in the value type.
void | set_members_as_dyn_any(NameDynAnyPair[] value) Initializes the value type's members from a sequence of NameDynAnyPairs.
void | set_members(NameValuePair[] value) Initializes the value type's members from a sequence of NameValuePairs.
Methods inherited from interface org.omg.DynamicAny.DynValueCommonOperations
is_null, set_to_null, set_to_value
Methods inherited from interface org.omg.DynamicAny.DynAnyOperations
assign, component_count, copy, current_component, destroy, equal, from_any, get_any, get_boolean, get_char, get_double, get_dyn_any, get_float, get_long, get_longlong, get_octet, get_reference, get_short, get_string, get_typecode, get_ulong, get_ulonglong, get_ushort, get_val, get_wchar, get_wstring, insert_any, insert_boolean, insert_char, insert_double, insert_dyn_any, insert_float, insert_long, insert_longlong, insert_octet, insert_reference, insert_short, insert_string, insert_typecode, insert_ulong, insert_ulonglong, insert_ushort, insert_val, insert_wchar, insert_wstring, next, rewind, seek, to_any, type

Method Detail

current_member_name

public String current_member_name()
                           throws TypeMismatch,
                                  InvalidValue
Returns the name of the member at the current position. This operation may return an empty string since the TypeCode of the value being manipulated may not contain the names of members.

Throws:
TypeMismatch - if the DynValue represents a null value type.
InvalidValue - if the current position does not indicate a member

current_member_kind

public TCKind current_member_kind()
                           throws TypeMismatch,
                                  InvalidValue
Returns the TCKind associated with the member at the current position.

Throws:
TypeMismatch - if the DynValue represents a null value type.
InvalidValue - if the current position does not indicate a member

get_members

public NameValuePair[] get_members()
                            throws InvalidValue
Returns a sequence of NameValuePairs describing the name and the value of each member in the value type. The sequence contains members in the same order as the declaration order of members as indicated by the DynValue's TypeCode. The current position is not affected. The member names in the returned sequence will be empty strings if the DynValue's TypeCode does not contain member names.

Throws:
InvalidValue - if this object represents a null value type

set_members

public void set_members(NameValuePair[] value)
                 throws TypeMismatch,
                        InvalidValue
Initializes the value type's members from a sequence of NameValuePairs. The operation sets the current position to zero if the passed sequences has non-zero length. Otherwise, if an empty sequence is passed, the current position is set to -1. A null value type can be initialized to a non-null value type using this method.

Members must appear in the NameValuePairs in the order in which they appear in the IDL specification of the value type as indicated by the DynValue's TypeCode or they must be empty strings. The operation makes no attempt to assign member values based on member names.

Throws:
TypeMismatch - if the member names supplied in the passed sequence do not match the corresponding member name in the DynValue's TypeCode and they are not empty strings
InvalidValue - if the passed sequence has a number of elements that disagrees with the number of members as indicated by the DynValue's TypeCode

get_members_as_dyn_any

public NameDynAnyPair[] get_members_as_dyn_any()
                                        throws InvalidValue
Returns a sequence of NameDynAnyPairs describing the name and the value of each member in the value type. The sequence contains members in the same order as the declaration order of members as indicated by the DynValue's TypeCode. The current position is not affected. The member names in the returned sequence will be empty strings if the DynValue's TypeCode does not contain member names.

Throws:
InvalidValue - if this object represents a null value type

set_members_as_dyn_any

public void set_members_as_dyn_any(NameDynAnyPair[] value)
                            throws TypeMismatch,
                                   InvalidValue
Initializes the value type's members from a sequence of NameDynAnyPairs. The operation sets the current position to zero if the passed sequences has non-zero length. Otherwise, if an empty sequence is passed, the current position is set to -1. A null value type can be initialized to a non-null value type using this method.

Members must appear in the NameDynAnyPairs in the order in which they appear in the IDL specification of the value type as indicated by the DynValue's TypeCode or they must be empty strings. The operation makes no attempt to assign member values based on member names.

Throws:
TypeMismatch - if the member names supplied in the passed sequence do not match the corresponding member name in the DynValue's TypeCode and they are not empty strings
InvalidValue - if the passed sequence has a number of elements that disagrees with the number of members as indicated by the DynValue's TypeCode
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


FieldNameHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Class FieldNameHelper

java.lang.Object
    extended by org.omg.DynamicAny.FieldNameHelper
public abstract class FieldNameHelper
extends Object

org/omg/DynamicAny/FieldNameHelper.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/DynamicAny/DynamicAny.idl Thursday, June 12, 2003 9:59:25 PM GMT-08:00

Constructor Summary
FieldNameHelper()
Method Summary
static String | extract(Any a)
static String | id()
static void | insert(Any a, String that)
static String | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, String value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

FieldNameHelper

public FieldNameHelper()
Method Detail

insert

public static void insert(Any a,
                          String that)

extract

public static String extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static String read(InputStream istream)

write

public static void write(OutputStream ostream,
                         String value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NameDynAnyPair (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Class NameDynAnyPair

java.lang.Object
    extended by org.omg.DynamicAny.NameDynAnyPair
All Implemented Interfaces:
IDLEntity, Serializable
public final class NameDynAnyPair
extends Object
implements IDLEntity

NameDynAnyPairs associate a name with an DynAny object.

Field Summary
String | id The name associated with the DynAny.
DynAny | value The DynAny value associated with the name.
Constructor Summary
NameDynAnyPair()
NameDynAnyPair(String _id, DynAny _value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

id

public String id
The name associated with the DynAny.

value

public DynAny value
The DynAny value associated with the name.

Constructor Detail

NameDynAnyPair

public NameDynAnyPair()

NameDynAnyPair

public NameDynAnyPair(String _id,
                      DynAny _value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NameDynAnyPairHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Class NameDynAnyPairHelper

java.lang.Object
    extended by org.omg.DynamicAny.NameDynAnyPairHelper
public abstract class NameDynAnyPairHelper
extends Object

NameDynAnyPairs associate a name with an DynAny object.

Constructor Summary
NameDynAnyPairHelper()
Method Summary
static NameDynAnyPair | extract(Any a)
static String | id()
static void | insert(Any a, NameDynAnyPair that)
static NameDynAnyPair | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, NameDynAnyPair value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

NameDynAnyPairHelper

public NameDynAnyPairHelper()
Method Detail

insert

public static void insert(Any a,
                          NameDynAnyPair that)

extract

public static NameDynAnyPair extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static NameDynAnyPair read(InputStream istream)

write

public static void write(OutputStream ostream,
                         NameDynAnyPair value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NameDynAnyPairSeqHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Class NameDynAnyPairSeqHelper

java.lang.Object
    extended by org.omg.DynamicAny.NameDynAnyPairSeqHelper
public abstract class NameDynAnyPairSeqHelper
extends Object

org/omg/DynamicAny/NameDynAnyPairSeqHelper.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/DynamicAny/DynamicAny.idl Thursday, June 12, 2003 9:59:25 PM GMT-08:00

Constructor Summary
NameDynAnyPairSeqHelper()
Method Summary
static NameDynAnyPair[] | extract(Any a)
static String | id()
static void | insert(Any a, NameDynAnyPair[] that)
static NameDynAnyPair[] | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, NameDynAnyPair[] value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

NameDynAnyPairSeqHelper

public NameDynAnyPairSeqHelper()
Method Detail

insert

public static void insert(Any a,
                          NameDynAnyPair[] that)

extract

public static NameDynAnyPair[] extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static NameDynAnyPair[] read(InputStream istream)

write

public static void write(OutputStream ostream,
                         NameDynAnyPair[] value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NameValuePair (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Class NameValuePair

java.lang.Object
    extended by org.omg.DynamicAny.NameValuePair
All Implemented Interfaces:
IDLEntity, Serializable
public final class NameValuePair
extends Object
implements IDLEntity

NameValuePairs associate a name with an Any object.

Field Summary
String | id The name associated with the Any.
Any | value The Any value associated with the name.
Constructor Summary
NameValuePair()
NameValuePair(String _id, Any _value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

id

public String id
The name associated with the Any.

value

public Any value
The Any value associated with the name.

Constructor Detail

NameValuePair

public NameValuePair()

NameValuePair

public NameValuePair(String _id,
                     Any _value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NameValuePairHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Class NameValuePairHelper

java.lang.Object
    extended by org.omg.DynamicAny.NameValuePairHelper
public abstract class NameValuePairHelper
extends Object

NameValuePairs associate a name with an Any object.

Constructor Summary
NameValuePairHelper()
Method Summary
static NameValuePair | extract(Any a)
static String | id()
static void | insert(Any a, NameValuePair that)
static NameValuePair | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, NameValuePair value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

NameValuePairHelper

public NameValuePairHelper()
Method Detail

insert

public static void insert(Any a,
                          NameValuePair that)

extract

public static NameValuePair extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static NameValuePair read(InputStream istream)

write

public static void write(OutputStream ostream,
                         NameValuePair value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NameValuePairSeqHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny
Class NameValuePairSeqHelper

java.lang.Object
    extended by org.omg.DynamicAny.NameValuePairSeqHelper
public abstract class NameValuePairSeqHelper
extends Object

org/omg/DynamicAny/NameValuePairSeqHelper.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/DynamicAny/DynamicAny.idl Thursday, June 12, 2003 9:59:25 PM GMT-08:00

Constructor Summary
NameValuePairSeqHelper()
Method Summary
static NameValuePair[] | extract(Any a)
static String | id()
static void | insert(Any a, NameValuePair[] that)
static NameValuePair[] | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, NameValuePair[] value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

NameValuePairSeqHelper

public NameValuePairSeqHelper()
Method Detail

insert

public static void insert(Any a,
                          NameValuePair[] that)

extract

public static NameValuePair[] extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static NameValuePair[] read(InputStream istream)

write

public static void write(OutputStream ostream,
                         NameValuePair[] value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


org.omg.DynamicAny (Java 2 Platform SE v1.4.2)

 org.omg.DynamicAny
Interfaces
DynAny
DynAnyFactory
DynAnyFactoryOperations
DynAnyOperations
DynArray
DynArrayOperations
DynEnum
DynEnumOperations
DynFixed
DynFixedOperations
DynSequence
DynSequenceOperations
DynStruct
DynStructOperations
DynUnion
DynUnionOperations
DynValue
DynValueBox
DynValueBoxOperations
DynValueCommon
DynValueCommonOperations
DynValueOperations
Classes
_DynAnyFactoryStub
_DynAnyStub
_DynArrayStub
_DynEnumStub
_DynFixedStub
_DynSequenceStub
_DynStructStub
_DynUnionStub
_DynValueStub
AnySeqHelper
DynAnyFactoryHelper
DynAnyHelper
DynAnySeqHelper
DynArrayHelper
DynEnumHelper
DynFixedHelper
DynSequenceHelper
DynStructHelper
DynUnionHelper
DynValueHelper
FieldNameHelper
NameDynAnyPair
NameDynAnyPairHelper
NameDynAnyPairSeqHelper
NameValuePair
NameValuePairHelper
NameValuePairSeqHelper


org.omg.DynamicAny (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

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.

See:
Description

Interface Summary
DynAny | Any values can be dynamically interpreted (traversed) and constructed through DynAny objects.
DynAnyFactory | DynAny objects can be created by invoking operations on the DynAnyFactory object.
DynAnyFactoryOperations | DynAny objects can be created by invoking operations on the DynAnyFactory object.
DynAnyOperations | Any values can be dynamically interpreted (traversed) and constructed through DynAny objects.
DynArray | DynArray objects support the manipulation of IDL arrays.
DynArrayOperations | DynArray objects support the manipulation of IDL arrays.
DynEnum | DynEnum objects support the manipulation of IDL enumerated values.
DynEnumOperations | DynEnum objects support the manipulation of IDL enumerated values.
DynFixed | DynFixed objects support the manipulation of IDL fixed values.
DynFixedOperations | DynFixed objects support the manipulation of IDL fixed values.
DynSequence | DynSequence objects support the manipulation of IDL sequences.
DynSequenceOperations | DynSequence objects support the manipulation of IDL sequences.
DynStruct | DynStruct objects support the manipulation of IDL struct and exception values.
DynStructOperations | DynStruct objects support the manipulation of IDL struct and exception values.
DynUnion | DynUnion objects support the manipulation of IDL unions.
DynUnionOperations | DynUnion objects support the manipulation of IDL unions.
DynValue | DynValue objects support the manipulation of IDL non-boxed value types.
DynValueBox | DynValueBox objects support the manipulation of IDL boxed value types.
DynValueBoxOperations | DynValueBox objects support the manipulation of IDL boxed value types.
DynValueCommon | DynValueCommon provides operations supported by both the DynValue and DynValueBox interfaces.
DynValueCommonOperations | DynValueCommon provides operations supported by both the DynValue and DynValueBox interfaces.
DynValueOperations | DynValue objects support the manipulation of IDL non-boxed value types.

Class Summary
_DynAnyFactoryStub | DynAny objects can be created by invoking operations on the DynAnyFactory object.
_DynAnyStub | Any values can be dynamically interpreted (traversed) and constructed through DynAny objects.
_DynArrayStub | DynArray objects support the manipulation of IDL arrays.
_DynEnumStub | DynEnum objects support the manipulation of IDL enumerated values.
_DynFixedStub | DynFixed objects support the manipulation of IDL fixed values.
_DynSequenceStub | DynSequence objects support the manipulation of IDL sequences.
_DynStructStub | DynStruct objects support the manipulation of IDL struct and exception values.
_DynUnionStub | DynUnion objects support the manipulation of IDL unions.
_DynValueStub | DynValue objects support the manipulation of IDL non-boxed value types.
AnySeqHelper | org/omg/DynamicAny/AnySeqHelper.java .
DynAnyFactoryHelper | DynAny objects can be created by invoking operations on the DynAnyFactory object.
DynAnyHelper | Any values can be dynamically interpreted (traversed) and constructed through DynAny objects.
DynAnySeqHelper | org/omg/DynamicAny/DynAnySeqHelper.java .
DynArrayHelper | DynArray objects support the manipulation of IDL arrays.
DynEnumHelper | DynEnum objects support the manipulation of IDL enumerated values.
DynFixedHelper | DynFixed objects support the manipulation of IDL fixed values.
DynSequenceHelper | DynSequence objects support the manipulation of IDL sequences.
DynStructHelper | DynStruct objects support the manipulation of IDL struct and exception values.
DynUnionHelper | DynUnion objects support the manipulation of IDL unions.
DynValueHelper | DynValue objects support the manipulation of IDL non-boxed value types.
FieldNameHelper | org/omg/DynamicAny/FieldNameHelper.java .
NameDynAnyPair | NameDynAnyPairs associate a name with an DynAny object.
NameDynAnyPairHelper | NameDynAnyPairs associate a name with an DynAny object.
NameDynAnyPairSeqHelper | org/omg/DynamicAny/NameDynAnyPairSeqHelper.java .
NameValuePair | NameValuePairs associate a name with an Any object.
NameValuePairHelper | NameValuePairs associate a name with an Any object.
NameValuePairSeqHelper | org/omg/DynamicAny/NameValuePairSeqHelper.java .

Package org.omg.DynamicAny Description

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.

An any can be passed to a program that doesn't have any static information for the type of the any (code generated for the type by an IDL compiler has not been compiled with the object implementation). As a result, the object receiving the any does not have a portable method of using it.

DynAnys enable traversal of the data value associated with an any at runtime, and extraction of the primitive constituents of the data value. This is especially helpful for writing powerful generic servers (bridges, event channels supporting filtering). Similarly, this facility enables the construction of an any at runtime, without having static knowledge of its type. This is especially helpful for writing generic clients (bridges, browsers, debuggers, user interface tools).

Any values can be dynamically interpreted (traversed) and constructed through DynAny objects. A DynAny object is associated with a data value which corresponds to a copy of the value inserted into an Any. A DynAny object may be viewed as an ordered collection of component DynAnys. For DynAnys representing a basic type, such as long, or a type without components, such as an empty exception, the ordered collection of components is empty.

Each DynAny object maintains the notion of a current position into its collection of component DynAnys. The current position is identified by an index value that runs from 0 to n-1, where n is the number of components. The special index value -1 indicates a current position that points nowhere. For values that cannot have a current position (such as an empty exception), the index value is fixed at -1. If a DynAny is initialized with a value that has components, the index is initialized to 0. After creation of an uninitialized DynAny (that is, a DynAny that has no value but a TypeCode that permits components), the current position depends on the type of value represented by the DynAny. (The current position is set to 0 or -1, depending on whether the new DynAny gets default values for its components.)

The iteration operations rewind, seek, and next can be used to change the current position and the current_component operation returns the component at the current position. The component_count operation returns the number of components of a DynAny. Collectively, these operations enable iteration over the components of a DynAny, for example, to (recursively) examine its contents.

A constructed DynAny object is a DynAny object associated with a constructed type. There is a different interface, inheriting from the DynAny interface, associated with each kind of constructed type in IDL (fixed, enum, struct, sequence, union, array, exception, and value type). A constructed DynAny object exports operations that enable the creation of new DynAny objects, each of them associated with a component of the constructed data value. As an example, a DynStruct is associated with a struct value. This means that the DynStruct may be seen as owning an ordered collection of components, one for each structure member. The DynStruct object exports operations that enable the creation of new DynAny objects, each of them associated with a member of the struct.

If a DynAny object has been obtained from another (constructed) DynAny object, such as a DynAny representing a structure member that was created from a DynStruct, the member DynAny is logically contained in the DynStruct. Calling an insert or get operation leaves the current position unchanged. Destroying a top-level DynAny object (one that was not obtained as a component of another DynAny) also destroys any component DynAny objects obtained from it. Destroying a non-top level DynAny object does nothing. Invoking operations on a destroyed top-level DynAny or any of its descendants raises OBJECT_NOT_EXIST. If the programmer wants to destroy a DynAny object but still wants to manipulate some component of the data value associated with it, then he or she should first create a DynAny for the component and, after that, make a copy of the created DynAny object.

The behavior of DynAny objects has been defined in order to enable efficient implementations in terms of allocated memory space and speed of access. DynAny objects are intended to be used for traversing values extracted from anys or constructing values of anys at runtime. Their use for other purposes is not recommended.

Handling DynAny objects

Insert and get operations are necessary to handle basic DynAny objects but are also helpful to handle constructed DynAny objects. Inserting a basic data type value into a constructed DynAny object implies initializing the current component of the constructed data value associated with the DynAny object. For example, invoking insert_boolean on a DynStruct implies inserting a boolean data value at the current position of the associated struct data value. A type is consistent for inserting or extracting a value if its TypeCode is equivalent to the TypeCode contained in the DynAny or, if the DynAny has components, is equivalent to the TypeCode of the DynAny at the current position.

Basic operations include:

  • insert_boolean, get_boolean
  • insert_char, get_char
  • insert_short, get_short
  • insert_ushort, get_ushort
  • insert_long, get_long
  • insert_ulong, get_ulong
  • insert_double, get_double
  • insert_string, get_string
  • insert_reference, get_reference
  • insert_typecode, get_typecode
  • insert_longlong, get_longlong
  • insert_ulonglong, get_ulonglong
  • insert_longdouble, get_longdouble
  • insert_wchar, get_wchar
  • insert_wstring, get_wstring
  • insert_any, get_any
  • insert_dyn_any, get_dyn_any
  • insert_val, get_val
  • insert_octet, get_octet
  • insert_float, get_float
  • get_value
  • get_as_string
  • get_as_ulong
  • get_members
  • get_members_as_dyn_any
  • get_discriminator
  • get_length
  • get_elements
  • get_elements_as_dyn_any
  • get_boxed_value
  • get_boxed_value_as_dyn_any

DynAny and DynAnyFactory objects are intended to be local to the process in which they are created and used. This means that references to DynAny and DynAnyFactory objects cannot be exported to other processes, or externalized with ORB.object_to_string(). If any attempt is made to do so, the offending operation will raise a MARSHAL system exception. Since their interfaces are specified in IDL, DynAny objects export operations defined in the standard org.omg.CORBA.Object interface. However, any attempt to invoke operations exported through the Object interface may raise the standard NO_IMPLEMENT exception. An attempt to use a DynAny object with the DII may raise the NO_IMPLEMENT exception.

Package Specification

For a precise list of supported sections of official specifications with which the Java 2 Platform, Standard Edition, v.1.4 ORB complies, see Official Specifications for CORBA support in J2SE 1.4.

Since:
1.4
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


org.omg.DynamicAny Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package org.omg.DynamicAny

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class org.omg.DynamicAny.AnySeqHelper
    • class org.omg.DynamicAny.DynAnyFactoryHelper
    • class org.omg.DynamicAny.DynAnyHelper
    • class org.omg.DynamicAny.DynAnySeqHelper
    • class org.omg.DynamicAny.DynArrayHelper
    • class org.omg.DynamicAny.DynEnumHelper
    • class org.omg.DynamicAny.DynFixedHelper
    • class org.omg.DynamicAny.DynSequenceHelper
    • class org.omg.DynamicAny.DynStructHelper
    • class org.omg.DynamicAny.DynUnionHelper
    • class org.omg.DynamicAny.DynValueHelper
    • class org.omg.DynamicAny.FieldNameHelper
    • class org.omg.DynamicAny.NameDynAnyPair (implements org.omg.CORBA.portable.IDLEntity)
    • class org.omg.DynamicAny.NameDynAnyPairHelper
    • class org.omg.DynamicAny.NameDynAnyPairSeqHelper
    • class org.omg.DynamicAny.NameValuePair (implements org.omg.CORBA.portable.IDLEntity)
    • class org.omg.DynamicAny.NameValuePairHelper
    • class org.omg.DynamicAny.NameValuePairSeqHelper
    • class org.omg.CORBA.portable.ObjectImpl (implements org.omg.CORBA.Object)
      • class org.omg.DynamicAny._DynAnyFactoryStub (implements org.omg.DynamicAny.DynAnyFactory)
      • class org.omg.DynamicAny._DynAnyStub (implements org.omg.DynamicAny.DynAny)
      • class org.omg.DynamicAny._DynArrayStub (implements org.omg.DynamicAny.DynArray)
      • class org.omg.DynamicAny._DynEnumStub (implements org.omg.DynamicAny.DynEnum)
      • class org.omg.DynamicAny._DynFixedStub (implements org.omg.DynamicAny.DynFixed)
      • class org.omg.DynamicAny._DynSequenceStub (implements org.omg.DynamicAny.DynSequence)
      • class org.omg.DynamicAny._DynStructStub (implements org.omg.DynamicAny.DynStruct)
      • class org.omg.DynamicAny._DynUnionStub (implements org.omg.DynamicAny.DynUnion)
      • class org.omg.DynamicAny._DynValueStub (implements org.omg.DynamicAny.DynValue)

Interface Hierarchy

  • interface org.omg.DynamicAny.DynAnyFactoryOperations
    • interface org.omg.DynamicAny.DynAnyFactory (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CORBA.Object)
  • interface org.omg.DynamicAny.DynAnyOperations
    • interface org.omg.DynamicAny.DynAny (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CORBA.Object)
      • interface org.omg.DynamicAny.DynArray (also extends org.omg.DynamicAny.DynArrayOperations, org.omg.CORBA.portable.IDLEntity)
      • interface org.omg.DynamicAny.DynEnum (also extends org.omg.DynamicAny.DynEnumOperations, org.omg.CORBA.portable.IDLEntity)
      • interface org.omg.DynamicAny.DynFixed (also extends org.omg.DynamicAny.DynFixedOperations, org.omg.CORBA.portable.IDLEntity)
      • interface org.omg.DynamicAny.DynSequence (also extends org.omg.DynamicAny.DynSequenceOperations, org.omg.CORBA.portable.IDLEntity)
      • interface org.omg.DynamicAny.DynStruct (also extends org.omg.DynamicAny.DynStructOperations, org.omg.CORBA.portable.IDLEntity)
      • interface org.omg.DynamicAny.DynUnion (also extends org.omg.DynamicAny.DynUnionOperations, org.omg.CORBA.portable.IDLEntity)
      • interface org.omg.DynamicAny.DynValueCommon (also extends org.omg.DynamicAny.DynValueCommonOperations, org.omg.CORBA.portable.IDLEntity)
        • interface org.omg.DynamicAny.DynValue (also extends org.omg.DynamicAny.DynValueOperations, org.omg.CORBA.portable.IDLEntity)
        • interface org.omg.DynamicAny.DynValueBox (also extends org.omg.DynamicAny.DynValueBoxOperations, org.omg.CORBA.portable.IDLEntity)
    • interface org.omg.DynamicAny.DynArrayOperations
      • interface org.omg.DynamicAny.DynArray (also extends org.omg.DynamicAny.DynAny, org.omg.CORBA.portable.IDLEntity)
    • interface org.omg.DynamicAny.DynEnumOperations
      • interface org.omg.DynamicAny.DynEnum (also extends org.omg.DynamicAny.DynAny, org.omg.CORBA.portable.IDLEntity)
    • interface org.omg.DynamicAny.DynFixedOperations
      • interface org.omg.DynamicAny.DynFixed (also extends org.omg.DynamicAny.DynAny, org.omg.CORBA.portable.IDLEntity)
    • interface org.omg.DynamicAny.DynSequenceOperations
      • interface org.omg.DynamicAny.DynSequence (also extends org.omg.DynamicAny.DynAny, org.omg.CORBA.portable.IDLEntity)
    • interface org.omg.DynamicAny.DynStructOperations
      • interface org.omg.DynamicAny.DynStruct (also extends org.omg.DynamicAny.DynAny, org.omg.CORBA.portable.IDLEntity)
    • interface org.omg.DynamicAny.DynUnionOperations
      • interface org.omg.DynamicAny.DynUnion (also extends org.omg.DynamicAny.DynAny, org.omg.CORBA.portable.IDLEntity)
    • interface org.omg.DynamicAny.DynValueCommonOperations
      • interface org.omg.DynamicAny.DynValueBoxOperations
        • interface org.omg.DynamicAny.DynValueBox (also extends org.omg.DynamicAny.DynValueCommon, org.omg.CORBA.portable.IDLEntity)
      • interface org.omg.DynamicAny.DynValueCommon (also extends org.omg.DynamicAny.DynAny, org.omg.CORBA.portable.IDLEntity)
        • interface org.omg.DynamicAny.DynValue (also extends org.omg.DynamicAny.DynValueOperations, org.omg.CORBA.portable.IDLEntity)
        • interface org.omg.DynamicAny.DynValueBox (also extends org.omg.DynamicAny.DynValueBoxOperations, org.omg.CORBA.portable.IDLEntity)
      • interface org.omg.DynamicAny.DynValueOperations
        • interface org.omg.DynamicAny.DynValue (also extends org.omg.DynamicAny.DynValueCommon, org.omg.CORBA.portable.IDLEntity)
  • interface org.omg.CORBA.Object
    • interface org.omg.DynamicAny.DynAny (also extends org.omg.DynamicAny.DynAnyOperations, org.omg.CORBA.portable.IDLEntity)
      • interface org.omg.DynamicAny.DynArray (also extends org.omg.DynamicAny.DynArrayOperations, org.omg.CORBA.portable.IDLEntity)
      • interface org.omg.DynamicAny.DynEnum (also extends org.omg.DynamicAny.DynEnumOperations, org.omg.CORBA.portable.IDLEntity)
      • interface org.omg.DynamicAny.DynFixed (also extends org.omg.DynamicAny.DynFixedOperations, org.omg.CORBA.portable.IDLEntity)
      • interface org.omg.DynamicAny.DynSequence (also extends org.omg.DynamicAny.DynSequenceOperations, org.omg.CORBA.portable.IDLEntity)
      • interface org.omg.DynamicAny.DynStruct (also extends org.omg.DynamicAny.DynStructOperations, org.omg.CORBA.portable.IDLEntity)
      • interface org.omg.DynamicAny.DynUnion (also extends org.omg.DynamicAny.DynUnionOperations, org.omg.CORBA.portable.IDLEntity)
      • interface org.omg.DynamicAny.DynValueCommon (also extends org.omg.DynamicAny.DynValueCommonOperations, org.omg.CORBA.portable.IDLEntity)
        • interface org.omg.DynamicAny.DynValue (also extends org.omg.DynamicAny.DynValueOperations, org.omg.CORBA.portable.IDLEntity)
        • interface org.omg.DynamicAny.DynValueBox (also extends org.omg.DynamicAny.DynValueBoxOperations, org.omg.CORBA.portable.IDLEntity)
    • interface org.omg.DynamicAny.DynAnyFactory (also extends org.omg.DynamicAny.DynAnyFactoryOperations, org.omg.CORBA.portable.IDLEntity)
  • interface java.io.Serializable
    • interface org.omg.CORBA.portable.IDLEntity
      • interface org.omg.DynamicAny.DynAny (also extends org.omg.DynamicAny.DynAnyOperations, org.omg.CORBA.Object)
        • interface org.omg.DynamicAny.DynArray (also extends org.omg.DynamicAny.DynArrayOperations, org.omg.CORBA.portable.IDLEntity)
        • interface org.omg.DynamicAny.DynEnum (also extends org.omg.DynamicAny.DynEnumOperations, org.omg.CORBA.portable.IDLEntity)
        • interface org.omg.DynamicAny.DynFixed (also extends org.omg.DynamicAny.DynFixedOperations, org.omg.CORBA.portable.IDLEntity)
        • interface org.omg.DynamicAny.DynSequence (also extends org.omg.DynamicAny.DynSequenceOperations, org.omg.CORBA.portable.IDLEntity)
        • interface org.omg.DynamicAny.DynStruct (also extends org.omg.DynamicAny.DynStructOperations, org.omg.CORBA.portable.IDLEntity)
        • interface org.omg.DynamicAny.DynUnion (also extends org.omg.DynamicAny.DynUnionOperations, org.omg.CORBA.portable.IDLEntity)
        • interface org.omg.DynamicAny.DynValueCommon (also extends org.omg.DynamicAny.DynValueCommonOperations, org.omg.CORBA.portable.IDLEntity)
          • interface org.omg.DynamicAny.DynValue (also extends org.omg.DynamicAny.DynValueOperations, org.omg.CORBA.portable.IDLEntity)
          • interface org.omg.DynamicAny.DynValueBox (also extends org.omg.DynamicAny.DynValueBoxOperations, org.omg.CORBA.portable.IDLEntity)
      • interface org.omg.DynamicAny.DynAnyFactory (also extends org.omg.DynamicAny.DynAnyFactoryOperations, org.omg.CORBA.Object)
      • interface org.omg.DynamicAny.DynArray (also extends org.omg.DynamicAny.DynAny, org.omg.DynamicAny.DynArrayOperations)
      • interface org.omg.DynamicAny.DynEnum (also extends org.omg.DynamicAny.DynAny, org.omg.DynamicAny.DynEnumOperations)
      • interface org.omg.DynamicAny.DynFixed (also extends org.omg.DynamicAny.DynAny, org.omg.DynamicAny.DynFixedOperations)
      • interface org.omg.DynamicAny.DynSequence (also extends org.omg.DynamicAny.DynAny, org.omg.DynamicAny.DynSequenceOperations)
      • interface org.omg.DynamicAny.DynStruct (also extends org.omg.DynamicAny.DynAny, org.omg.DynamicAny.DynStructOperations)
      • interface org.omg.DynamicAny.DynUnion (also extends org.omg.DynamicAny.DynAny, org.omg.DynamicAny.DynUnionOperations)
      • interface org.omg.DynamicAny.DynValue (also extends org.omg.DynamicAny.DynValueCommon, org.omg.DynamicAny.DynValueOperations)
      • interface org.omg.DynamicAny.DynValueBox (also extends org.omg.DynamicAny.DynValueBoxOperations, org.omg.DynamicAny.DynValueCommon)
      • interface org.omg.DynamicAny.DynValueCommon (also extends org.omg.DynamicAny.DynAny, org.omg.DynamicAny.DynValueCommonOperations)
        • interface org.omg.DynamicAny.DynValue (also extends org.omg.DynamicAny.DynValueOperations, org.omg.CORBA.portable.IDLEntity)
        • interface org.omg.DynamicAny.DynValueBox (also extends org.omg.DynamicAny.DynValueBoxOperations, org.omg.CORBA.portable.IDLEntity)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package org.omg.DynamicAny (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
org.omg.DynamicAny

Packages that use org.omg.DynamicAny
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.

Classes in org.omg.DynamicAny used by org.omg.DynamicAny
DynAny
Any values can be dynamically interpreted (traversed) and constructed through DynAny objects.
DynAnyFactory
DynAny objects can be created by invoking operations on the DynAnyFactory object.
DynAnyFactoryOperations
DynAny objects can be created by invoking operations on the DynAnyFactory object.
DynAnyOperations
Any values can be dynamically interpreted (traversed) and constructed through DynAny objects.
DynArray
DynArray objects support the manipulation of IDL arrays.
DynArrayOperations
DynArray objects support the manipulation of IDL arrays.
DynEnum
DynEnum objects support the manipulation of IDL enumerated values.
DynEnumOperations
DynEnum objects support the manipulation of IDL enumerated values.
DynFixed
DynFixed objects support the manipulation of IDL fixed values.
DynFixedOperations
DynFixed objects support the manipulation of IDL fixed values.
DynSequence
DynSequence objects support the manipulation of IDL sequences.
DynSequenceOperations
DynSequence objects support the manipulation of IDL sequences.
DynStruct
DynStruct objects support the manipulation of IDL struct and exception values.
DynStructOperations
DynStruct objects support the manipulation of IDL struct and exception values.
DynUnion
DynUnion objects support the manipulation of IDL unions.
DynUnionOperations
DynUnion objects support the manipulation of IDL unions.
DynValue
DynValue objects support the manipulation of IDL non-boxed value types.
DynValueBoxOperations
DynValueBox objects support the manipulation of IDL boxed value types.
DynValueCommon
DynValueCommon provides operations supported by both the DynValue and DynValueBox interfaces.
DynValueCommonOperations
DynValueCommon provides operations supported by both the DynValue and DynValueBox interfaces.
DynValueOperations
DynValue objects support the manipulation of IDL non-boxed value types.
NameDynAnyPair
NameDynAnyPairs associate a name with an DynAny object.
NameValuePair
NameValuePairs associate a name with an Any object.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.DynamicAny._DynAnyFactoryStub (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.DynamicAny._DynAnyFactoryStub

No usage of org.omg.DynamicAny._DynAnyFactoryStub

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.DynamicAny._DynAnyStub (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.DynamicAny._DynAnyStub

No usage of org.omg.DynamicAny._DynAnyStub

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.DynamicAny._DynArrayStub (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.DynamicAny._DynArrayStub

No usage of org.omg.DynamicAny._DynArrayStub

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.DynamicAny._DynEnumStub (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.DynamicAny._DynEnumStub

No usage of org.omg.DynamicAny._DynEnumStub

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.DynamicAny._DynFixedStub (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.DynamicAny._DynFixedStub

No usage of org.omg.DynamicAny._DynFixedStub

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.DynamicAny._DynSequenceStub (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.DynamicAny._DynSequenceStub

No usage of org.omg.DynamicAny._DynSequenceStub

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.DynamicAny._DynStructStub (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.DynamicAny._DynStructStub

No usage of org.omg.DynamicAny._DynStructStub

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.DynamicAny._DynUnionStub (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.DynamicAny._DynUnionStub

No usage of org.omg.DynamicAny._DynUnionStub

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.DynamicAny._DynValueStub (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.DynamicAny._DynValueStub

No usage of org.omg.DynamicAny._DynValueStub

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.DynamicAny.AnySeqHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.DynamicAny.AnySeqHelper

No usage of org.omg.DynamicAny.AnySeqHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.DynamicAny.DynAny (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.DynamicAny.DynAny

Packages that use DynAny
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.

Uses of DynAny in org.omg.DynamicAny

Subinterfaces of DynAny in org.omg.DynamicAny
interface | DynArray DynArray objects support the manipulation of IDL arrays.
interface | DynEnum DynEnum objects support the manipulation of IDL enumerated values.
interface | DynFixed DynFixed objects support the manipulation of IDL fixed values.
interface | DynSequence DynSequence objects support the manipulation of IDL sequences.
interface | DynStruct DynStruct objects support the manipulation of IDL struct and exception values.
interface | DynUnion DynUnion objects support the manipulation of IDL unions.
interface | DynValue DynValue objects support the manipulation of IDL non-boxed value types.
interface | DynValueBox DynValueBox objects support the manipulation of IDL boxed value types.
interface | DynValueCommon DynValueCommon provides operations supported by both the DynValue and DynValueBox interfaces.

Classes in org.omg.DynamicAny that implement DynAny
class | _DynAnyStub Any values can be dynamically interpreted (traversed) and constructed through DynAny objects.
class | _DynArrayStub DynArray objects support the manipulation of IDL arrays.
class | _DynEnumStub DynEnum objects support the manipulation of IDL enumerated values.
class | _DynFixedStub DynFixed objects support the manipulation of IDL fixed values.
class | _DynSequenceStub DynSequence objects support the manipulation of IDL sequences.
class | _DynStructStub DynStruct objects support the manipulation of IDL struct and exception values.
class | _DynUnionStub DynUnion objects support the manipulation of IDL unions.
class | _DynValueStub DynValue objects support the manipulation of IDL non-boxed value types.

Fields in org.omg.DynamicAny declared as DynAny
 DynAny NameDynAnyPair.value
The DynAny value associated with the name.

Methods in org.omg.DynamicAny that return DynAny
DynAny | DynValueBoxOperations.get_boxed_value_as_dyn_any() Returns the boxed value as a DynAny.
DynAny[] | _DynSequenceStub.get_elements_as_dyn_any() Returns the DynAnys representing the elements of the sequence.
DynAny | _DynSequenceStub.copy() Creates a new DynAny object whose value is a deep copy of the DynAny on which it is invoked.
DynAny | _DynSequenceStub.get_dyn_any() Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.
DynAny | _DynSequenceStub.current_component() Returns the DynAny for the component at the current position.
DynAny | _DynFixedStub.copy() Creates a new DynAny object whose value is a deep copy of the DynAny on which it is invoked.
DynAny | _DynFixedStub.get_dyn_any() Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.
DynAny | _DynFixedStub.current_component() Returns the DynAny for the component at the current position.
DynAny | _DynEnumStub.copy() Creates a new DynAny object whose value is a deep copy of the DynAny on which it is invoked.
DynAny | _DynEnumStub.get_dyn_any() Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.
DynAny | _DynEnumStub.current_component() Returns the DynAny for the component at the current position.
DynAny[] | _DynArrayStub.get_elements_as_dyn_any() Returns the elements of the DynArray as DynAnys.
DynAny | _DynArrayStub.copy() Creates a new DynAny object whose value is a deep copy of the DynAny on which it is invoked.
DynAny | _DynArrayStub.get_dyn_any() Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.
DynAny | _DynArrayStub.current_component() Returns the DynAny for the component at the current position.
DynAny | _DynValueStub.copy() Creates a new DynAny object whose value is a deep copy of the DynAny on which it is invoked.
DynAny | _DynValueStub.get_dyn_any() Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.
DynAny | _DynValueStub.current_component() Returns the DynAny for the component at the current position.
DynAny | _DynAnyStub.copy() Creates a new DynAny object whose value is a deep copy of the DynAny on which it is invoked.
DynAny | _DynAnyStub.get_dyn_any() Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.
DynAny | _DynAnyStub.current_component() Returns the DynAny for the component at the current position.
DynAny | _DynUnionStub.get_discriminator() Returns the current discriminator value.
DynAny | _DynUnionStub.member() Returns the currently active member.
DynAny | _DynUnionStub.copy() Creates a new DynAny object whose value is a deep copy of the DynAny on which it is invoked.
DynAny | _DynUnionStub.get_dyn_any() Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.
DynAny | _DynUnionStub.current_component() Returns the DynAny for the component at the current position.
DynAny | _DynAnyFactoryStub.create_dyn_any(Any value) Creates a new DynAny object from an any value.
DynAny | _DynAnyFactoryStub.create_dyn_any_from_type_code(TypeCode type) Creates a DynAny from a TypeCode.
DynAny | _DynStructStub.copy() Creates a new DynAny object whose value is a deep copy of the DynAny on which it is invoked.
DynAny | _DynStructStub.get_dyn_any() Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.
DynAny | _DynStructStub.current_component() Returns the DynAny for the component at the current position.
static DynAny[] | DynAnySeqHelper.extract(Any a)
static DynAny[] | DynAnySeqHelper.read(InputStream istream)
static DynAny | DynAnyHelper.extract(Any a)
static DynAny | DynAnyHelper.read(InputStream istream)
static DynAny | DynAnyHelper.narrow(Object obj)
DynAny | DynUnionOperations.get_discriminator() Returns the current discriminator value.
DynAny | DynUnionOperations.member() Returns the currently active member.
DynAny[] | DynSequenceOperations.get_elements_as_dyn_any() Returns the DynAnys representing the elements of the sequence.
DynAny[] | DynArrayOperations.get_elements_as_dyn_any() Returns the elements of the DynArray as DynAnys.
DynAny | DynAnyFactoryOperations.create_dyn_any(Any value) Creates a new DynAny object from an any value.
DynAny | DynAnyFactoryOperations.create_dyn_any_from_type_code(TypeCode type) Creates a DynAny from a TypeCode.
DynAny | DynAnyOperations.copy() Creates a new DynAny object whose value is a deep copy of the DynAny on which it is invoked.
DynAny | DynAnyOperations.get_dyn_any() Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.
DynAny | DynAnyOperations.current_component() Returns the DynAny for the component at the current position.

Methods in org.omg.DynamicAny with parameters of type DynAny
void | DynValueBoxOperations.set_boxed_value_as_dyn_any(DynAny boxed) Replaces the boxed value with the value contained in the parameter.
void | _DynSequenceStub.set_elements_as_dyn_any(DynAny[] value) Sets the elements of a sequence using DynAnys.
void | _DynSequenceStub.assign(DynAny dyn_any) Initializes the value associated with a DynAny object with the value associated with another DynAny object.
boolean | _DynSequenceStub.equal(DynAny dyn_any) Compares two DynAny values for equality.
void | _DynSequenceStub.insert_dyn_any(DynAny value) Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.
void | _DynFixedStub.assign(DynAny dyn_any) Initializes the value associated with a DynAny object with the value associated with another DynAny object.
boolean | _DynFixedStub.equal(DynAny dyn_any) Compares two DynAny values for equality.
void | _DynFixedStub.insert_dyn_any(DynAny value) Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.
void | _DynEnumStub.assign(DynAny dyn_any) Initializes the value associated with a DynAny object with the value associated with another DynAny object.
boolean | _DynEnumStub.equal(DynAny dyn_any) Compares two DynAny values for equality.
void | _DynEnumStub.insert_dyn_any(DynAny value) Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.
void | _DynArrayStub.set_elements_as_dyn_any(DynAny[] value) Sets the DynArray to contain the passed elements.
void | _DynArrayStub.assign(DynAny dyn_any) Initializes the value associated with a DynAny object with the value associated with another DynAny object.
boolean | _DynArrayStub.equal(DynAny dyn_any) Compares two DynAny values for equality.
void | _DynArrayStub.insert_dyn_any(DynAny value) Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.
void | _DynValueStub.assign(DynAny dyn_any) Initializes the value associated with a DynAny object with the value associated with another DynAny object.
boolean | _DynValueStub.equal(DynAny dyn_any) Compares two DynAny values for equality.
void | _DynValueStub.insert_dyn_any(DynAny value) Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.
void | _DynAnyStub.assign(DynAny dyn_any) Initializes the value associated with a DynAny object with the value associated with another DynAny object.
boolean | _DynAnyStub.equal(DynAny dyn_any) Compares two DynAny values for equality.
void | _DynAnyStub.insert_dyn_any(DynAny value) Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.
void | _DynUnionStub.set_discriminator(DynAny d) Sets the discriminator of the DynUnion to the specified value.
void | _DynUnionStub.assign(DynAny dyn_any) Initializes the value associated with a DynAny object with the value associated with another DynAny object.
boolean | _DynUnionStub.equal(DynAny dyn_any) Compares two DynAny values for equality.
void | _DynUnionStub.insert_dyn_any(DynAny value) Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.
void | _DynStructStub.assign(DynAny dyn_any) Initializes the value associated with a DynAny object with the value associated with another DynAny object.
boolean | _DynStructStub.equal(DynAny dyn_any) Compares two DynAny values for equality.
void | _DynStructStub.insert_dyn_any(DynAny value) Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.
static void | DynAnySeqHelper.insert(Any a, DynAny[] that)
static void | DynAnySeqHelper.write(OutputStream ostream, DynAny[] value)
static void | DynAnyHelper.insert(Any a, DynAny that)
static void | DynAnyHelper.write(OutputStream ostream, DynAny value)
void | DynUnionOperations.set_discriminator(DynAny d) Sets the discriminator of the DynUnion to the specified value.
void | DynSequenceOperations.set_elements_as_dyn_any(DynAny[] value) Sets the elements of a sequence using DynAnys.
void | DynArrayOperations.set_elements_as_dyn_any(DynAny[] value) Sets the DynArray to contain the passed elements.
void | DynAnyOperations.assign(DynAny dyn_any) Initializes the value associated with a DynAny object with the value associated with another DynAny object.
boolean | DynAnyOperations.equal(DynAny dyn_any) Compares two DynAny values for equality.
void | DynAnyOperations.insert_dyn_any(DynAny value) Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.

Constructors in org.omg.DynamicAny with parameters of type DynAny
NameDynAnyPair(String _id, DynAny _value)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.DynamicAny.DynAnyFactory (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.DynamicAny.DynAnyFactory

Packages that use DynAnyFactory
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.

Uses of DynAnyFactory in org.omg.DynamicAny

Classes in org.omg.DynamicAny that implement DynAnyFactory
 class _DynAnyFactoryStub
DynAny objects can be created by invoking operations on the DynAnyFactory object.

Methods in org.omg.DynamicAny that return DynAnyFactory
static DynAnyFactory | DynAnyFactoryHelper.extract(Any a)
static DynAnyFactory | DynAnyFactoryHelper.read(InputStream istream)
static DynAnyFactory | DynAnyFactoryHelper.narrow(Object obj)

Methods in org.omg.DynamicAny with parameters of type DynAnyFactory
static void | DynAnyFactoryHelper.insert(Any a, DynAnyFactory that)
static void | DynAnyFactoryHelper.write(OutputStream ostream, DynAnyFactory value)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.DynamicAny.DynAnyFactoryHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.DynamicAny.DynAnyFactoryHelper

No usage of org.omg.DynamicAny.DynAnyFactoryHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.DynamicAny.DynAnyFactoryOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.DynamicAny.DynAnyFactoryOperations

Packages that use DynAnyFactoryOperations
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.

Uses of DynAnyFactoryOperations in org.omg.DynamicAny

Subinterfaces of DynAnyFactoryOperations in org.omg.DynamicAny
 interface DynAnyFactory
DynAny objects can be created by invoking operations on the DynAnyFactory object.

Classes in org.omg.DynamicAny that implement DynAnyFactoryOperations
 class _DynAnyFactoryStub
DynAny objects can be created by invoking operations on the DynAnyFactory object.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.DynamicAny.DynAnyHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.DynamicAny.DynAnyHelper

No usage of org.omg.DynamicAny.DynAnyHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.DynamicAny.DynAnyOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.DynamicAny.DynAnyOperations

Packages that use DynAnyOperations
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.

Uses of DynAnyOperations in org.omg.DynamicAny

Subinterfaces of DynAnyOperations in org.omg.DynamicAny
interface | DynAny Any values can be dynamically interpreted (traversed) and constructed through DynAny objects.
interface | DynArray DynArray objects support the manipulation of IDL arrays.
interface | DynArrayOperations DynArray objects support the manipulation of IDL arrays.
interface | DynEnum DynEnum objects support the manipulation of IDL enumerated values.
interface | DynEnumOperations DynEnum objects support the manipulation of IDL enumerated values.
interface | DynFixed DynFixed objects support the manipulation of IDL fixed values.
interface | DynFixedOperations DynFixed objects support the manipulation of IDL fixed values.
interface | DynSequence DynSequence objects support the manipulation of IDL sequences.
interface | DynSequenceOperations DynSequence objects support the manipulation of IDL sequences.
interface | DynStruct DynStruct objects support the manipulation of IDL struct and exception values.
interface | DynStructOperations DynStruct objects support the manipulation of IDL struct and exception values.
interface | DynUnion DynUnion objects support the manipulation of IDL unions.
interface | DynUnionOperations DynUnion objects support the manipulation of IDL unions.
interface | DynValue DynValue objects support the manipulation of IDL non-boxed value types.
interface | DynValueBox DynValueBox objects support the manipulation of IDL boxed value types.
interface | DynValueBoxOperations DynValueBox objects support the manipulation of IDL boxed value types.
interface | DynValueCommon DynValueCommon provides operations supported by both the DynValue and DynValueBox interfaces.
interface | DynValueCommonOperations DynValueCommon provides operations supported by both the DynValue and DynValueBox interfaces.
interface | DynValueOperations DynValue objects support the manipulation of IDL non-boxed value types.

Classes in org.omg.DynamicAny that implement DynAnyOperations
class | _DynAnyStub Any values can be dynamically interpreted (traversed) and constructed through DynAny objects.
class | _DynArrayStub DynArray objects support the manipulation of IDL arrays.
class | _DynEnumStub DynEnum objects support the manipulation of IDL enumerated values.
class | _DynFixedStub DynFixed objects support the manipulation of IDL fixed values.
class | _DynSequenceStub DynSequence objects support the manipulation of IDL sequences.
class | _DynStructStub DynStruct objects support the manipulation of IDL struct and exception values.
class | _DynUnionStub DynUnion objects support the manipulation of IDL unions.
class | _DynValueStub DynValue objects support the manipulation of IDL non-boxed value types.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.DynamicAny.DynAnySeqHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.DynamicAny.DynAnySeqHelper

No usage of org.omg.DynamicAny.DynAnySeqHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.DynamicAny.DynArray (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.DynamicAny.DynArray

Packages that use DynArray
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.

Uses of DynArray in org.omg.DynamicAny

Classes in org.omg.DynamicAny that implement DynArray
 class _DynArrayStub
DynArray objects support the manipulation of IDL arrays.

Methods in org.omg.DynamicAny that return DynArray
static DynArray | DynArrayHelper.extract(Any a)
static DynArray | DynArrayHelper.read(InputStream istream)
static DynArray | DynArrayHelper.narrow(Object obj)

Methods in org.omg.DynamicAny with parameters of type DynArray
static void | DynArrayHelper.insert(Any a, DynArray that)
static void | DynArrayHelper.write(OutputStream ostream, DynArray value)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.DynamicAny.DynArrayHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.DynamicAny.DynArrayHelper

No usage of org.omg.DynamicAny.DynArrayHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.DynamicAny.DynArrayOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.DynamicAny.DynArrayOperations

Packages that use DynArrayOperations
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.

Uses of DynArrayOperations in org.omg.DynamicAny

Subinterfaces of DynArrayOperations in org.omg.DynamicAny
 interface DynArray
DynArray objects support the manipulation of IDL arrays.

Classes in org.omg.DynamicAny that implement DynArrayOperations
 class _DynArrayStub
DynArray objects support the manipulation of IDL arrays.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.DynamicAny.DynEnum (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.DynamicAny.DynEnum

Packages that use DynEnum
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.

Uses of DynEnum in org.omg.DynamicAny

Classes in org.omg.DynamicAny that implement DynEnum
 class _DynEnumStub
DynEnum objects support the manipulation of IDL enumerated values.

Methods in org.omg.DynamicAny that return DynEnum
static DynEnum | DynEnumHelper.extract(Any a)
static DynEnum | DynEnumHelper.read(InputStream istream)
static DynEnum | DynEnumHelper.narrow(Object obj)

Methods in org.omg.DynamicAny with parameters of type DynEnum
static void | DynEnumHelper.insert(Any a, DynEnum that)
static void | DynEnumHelper.write(OutputStream ostream, DynEnum value)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.DynamicAny.DynEnumHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.DynamicAny.DynEnumHelper

No usage of org.omg.DynamicAny.DynEnumHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.DynamicAny.DynEnumOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.DynamicAny.DynEnumOperations

Packages that use DynEnumOperations
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.

Uses of DynEnumOperations in org.omg.DynamicAny

Subinterfaces of DynEnumOperations in org.omg.DynamicAny
 interface DynEnum
DynEnum objects support the manipulation of IDL enumerated values.

Classes in org.omg.DynamicAny that implement DynEnumOperations
 class _DynEnumStub
DynEnum objects support the manipulation of IDL enumerated values.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.DynamicAny.DynFixed (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.DynamicAny.DynFixed

Packages that use DynFixed
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.

Uses of DynFixed in org.omg.DynamicAny

Classes in org.omg.DynamicAny that implement DynFixed
 class _DynFixedStub
DynFixed objects support the manipulation of IDL fixed values.

Methods in org.omg.DynamicAny that return DynFixed
static DynFixed | DynFixedHelper.extract(Any a)
static DynFixed | DynFixedHelper.read(InputStream istream)
static DynFixed | DynFixedHelper.narrow(Object obj)

Methods in org.omg.DynamicAny with parameters of type DynFixed
static void | DynFixedHelper.insert(Any a, DynFixed that)
static void | DynFixedHelper.write(OutputStream ostream, DynFixed value)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.DynamicAny.DynFixedHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.DynamicAny.DynFixedHelper

No usage of org.omg.DynamicAny.DynFixedHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.DynamicAny.DynFixedOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.DynamicAny.DynFixedOperations

Packages that use DynFixedOperations
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.

Uses of DynFixedOperations in org.omg.DynamicAny

Subinterfaces of DynFixedOperations in org.omg.DynamicAny
 interface DynFixed
DynFixed objects support the manipulation of IDL fixed values.

Classes in org.omg.DynamicAny that implement DynFixedOperations
 class _DynFixedStub
DynFixed objects support the manipulation of IDL fixed values.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.DynamicAny.DynSequence (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.DynamicAny.DynSequence

Packages that use DynSequence
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.

Uses of DynSequence in org.omg.DynamicAny

Classes in org.omg.DynamicAny that implement DynSequence
 class _DynSequenceStub
DynSequence objects support the manipulation of IDL sequences.

Methods in org.omg.DynamicAny that return DynSequence
static DynSequence | DynSequenceHelper.extract(Any a)
static DynSequence | DynSequenceHelper.read(InputStream istream)
static DynSequence | DynSequenceHelper.narrow(Object obj)

Methods in org.omg.DynamicAny with parameters of type DynSequence
static void | DynSequenceHelper.insert(Any a, DynSequence that)
static void | DynSequenceHelper.write(OutputStream ostream, DynSequence value)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.DynamicAny.DynSequenceHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.DynamicAny.DynSequenceHelper

No usage of org.omg.DynamicAny.DynSequenceHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.DynamicAny.DynSequenceOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.DynamicAny.DynSequenceOperations

Packages that use DynSequenceOperations
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.

Uses of DynSequenceOperations in org.omg.DynamicAny

Subinterfaces of DynSequenceOperations in org.omg.DynamicAny
 interface DynSequence
DynSequence objects support the manipulation of IDL sequences.

Classes in org.omg.DynamicAny that implement DynSequenceOperations
 class _DynSequenceStub
DynSequence objects support the manipulation of IDL sequences.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.DynamicAny.DynStruct (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.DynamicAny.DynStruct

Packages that use DynStruct
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.

Uses of DynStruct in org.omg.DynamicAny

Classes in org.omg.DynamicAny that implement DynStruct
 class _DynStructStub
DynStruct objects support the manipulation of IDL struct and exception values.

Methods in org.omg.DynamicAny that return DynStruct
static DynStruct | DynStructHelper.extract(Any a)
static DynStruct | DynStructHelper.read(InputStream istream)
static DynStruct | DynStructHelper.narrow(Object obj)

Methods in org.omg.DynamicAny with parameters of type DynStruct
static void | DynStructHelper.insert(Any a, DynStruct that)
static void | DynStructHelper.write(OutputStream ostream, DynStruct value)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.DynamicAny.DynStructHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.DynamicAny.DynStructHelper

No usage of org.omg.DynamicAny.DynStructHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.DynamicAny.DynStructOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.DynamicAny.DynStructOperations

Packages that use DynStructOperations
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.

Uses of DynStructOperations in org.omg.DynamicAny

Subinterfaces of DynStructOperations in org.omg.DynamicAny
 interface DynStruct
DynStruct objects support the manipulation of IDL struct and exception values.

Classes in org.omg.DynamicAny that implement DynStructOperations
 class _DynStructStub
DynStruct objects support the manipulation of IDL struct and exception values.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.DynamicAny.DynUnion (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.DynamicAny.DynUnion

Packages that use DynUnion
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.

Uses of DynUnion in org.omg.DynamicAny

Classes in org.omg.DynamicAny that implement DynUnion
 class _DynUnionStub
DynUnion objects support the manipulation of IDL unions.

Methods in org.omg.DynamicAny that return DynUnion
static DynUnion | DynUnionHelper.extract(Any a)
static DynUnion | DynUnionHelper.read(InputStream istream)
static DynUnion | DynUnionHelper.narrow(Object obj)

Methods in org.omg.DynamicAny with parameters of type DynUnion
static void | DynUnionHelper.insert(Any a, DynUnion that)
static void | DynUnionHelper.write(OutputStream ostream, DynUnion value)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.DynamicAny.DynUnionHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.DynamicAny.DynUnionHelper

No usage of org.omg.DynamicAny.DynUnionHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.DynamicAny.DynUnionOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.DynamicAny.DynUnionOperations

Packages that use DynUnionOperations
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.

Uses of DynUnionOperations in org.omg.DynamicAny

Subinterfaces of DynUnionOperations in org.omg.DynamicAny
 interface DynUnion
DynUnion objects support the manipulation of IDL unions.

Classes in org.omg.DynamicAny that implement DynUnionOperations
 class _DynUnionStub
DynUnion objects support the manipulation of IDL unions.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.DynamicAny.DynValue (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.DynamicAny.DynValue

Packages that use DynValue
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.

Uses of DynValue in org.omg.DynamicAny

Classes in org.omg.DynamicAny that implement DynValue
 class _DynValueStub
DynValue objects support the manipulation of IDL non-boxed value types.

Methods in org.omg.DynamicAny that return DynValue
static DynValue | DynValueHelper.extract(Any a)
static DynValue | DynValueHelper.read(InputStream istream)
static DynValue | DynValueHelper.narrow(Object obj)

Methods in org.omg.DynamicAny with parameters of type DynValue
static void | DynValueHelper.insert(Any a, DynValue that)
static void | DynValueHelper.write(OutputStream ostream, DynValue value)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.DynamicAny.DynValueBox (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.DynamicAny.DynValueBox

No usage of org.omg.DynamicAny.DynValueBox

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.DynamicAny.DynValueBoxOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.DynamicAny.DynValueBoxOperations

Packages that use DynValueBoxOperations
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.

Uses of DynValueBoxOperations in org.omg.DynamicAny

Subinterfaces of DynValueBoxOperations in org.omg.DynamicAny
 interface DynValueBox
DynValueBox objects support the manipulation of IDL boxed value types.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.DynamicAny.DynValueCommon (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.DynamicAny.DynValueCommon

Packages that use DynValueCommon
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.

Uses of DynValueCommon in org.omg.DynamicAny

Subinterfaces of DynValueCommon in org.omg.DynamicAny
interface | DynValue DynValue objects support the manipulation of IDL non-boxed value types.
interface | DynValueBox DynValueBox objects support the manipulation of IDL boxed value types.

Classes in org.omg.DynamicAny that implement DynValueCommon
 class _DynValueStub
DynValue objects support the manipulation of IDL non-boxed value types.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.DynamicAny.DynValueCommonOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.DynamicAny.DynValueCommonOperations

Packages that use DynValueCommonOperations
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.

Uses of DynValueCommonOperations in org.omg.DynamicAny

Subinterfaces of DynValueCommonOperations in org.omg.DynamicAny
interface | DynValue DynValue objects support the manipulation of IDL non-boxed value types.
interface | DynValueBox DynValueBox objects support the manipulation of IDL boxed value types.
interface | DynValueBoxOperations DynValueBox objects support the manipulation of IDL boxed value types.
interface | DynValueCommon DynValueCommon provides operations supported by both the DynValue and DynValueBox interfaces.
interface | DynValueOperations DynValue objects support the manipulation of IDL non-boxed value types.

Classes in org.omg.DynamicAny that implement DynValueCommonOperations
 class _DynValueStub
DynValue objects support the manipulation of IDL non-boxed value types.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.DynamicAny.DynValueHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.DynamicAny.DynValueHelper

No usage of org.omg.DynamicAny.DynValueHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.DynamicAny.DynValueOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.DynamicAny.DynValueOperations

Packages that use DynValueOperations
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.

Uses of DynValueOperations in org.omg.DynamicAny

Subinterfaces of DynValueOperations in org.omg.DynamicAny
 interface DynValue
DynValue objects support the manipulation of IDL non-boxed value types.

Classes in org.omg.DynamicAny that implement DynValueOperations
 class _DynValueStub
DynValue objects support the manipulation of IDL non-boxed value types.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.DynamicAny.FieldNameHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.DynamicAny.FieldNameHelper

No usage of org.omg.DynamicAny.FieldNameHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.DynamicAny.NameDynAnyPair (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.DynamicAny.NameDynAnyPair

Packages that use NameDynAnyPair
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.

Uses of NameDynAnyPair in org.omg.DynamicAny

Methods in org.omg.DynamicAny that return NameDynAnyPair
NameDynAnyPair[] | _DynValueStub.get_members_as_dyn_any() Returns a sequence of NameDynAnyPairs describing the name and the value of each member in the value type.
NameDynAnyPair[] | _DynStructStub.get_members_as_dyn_any() Returns a sequence of NameDynAnyPairs describing the name and the value of each member in the struct associated with a DynStruct object.
static NameDynAnyPair[] | NameDynAnyPairSeqHelper.extract(Any a)
static NameDynAnyPair[] | NameDynAnyPairSeqHelper.read(InputStream istream)
static NameDynAnyPair | NameDynAnyPairHelper.extract(Any a)
static NameDynAnyPair | NameDynAnyPairHelper.read(InputStream istream)
NameDynAnyPair[] | DynValueOperations.get_members_as_dyn_any() Returns a sequence of NameDynAnyPairs describing the name and the value of each member in the value type.
NameDynAnyPair[] | DynStructOperations.get_members_as_dyn_any() Returns a sequence of NameDynAnyPairs describing the name and the value of each member in the struct associated with a DynStruct object.

Methods in org.omg.DynamicAny with parameters of type NameDynAnyPair
void | _DynValueStub.set_members_as_dyn_any(NameDynAnyPair[] value) Initializes the value type's members from a sequence of NameDynAnyPairs.
void | _DynStructStub.set_members_as_dyn_any(NameDynAnyPair[] value) Initializes the struct data value associated with a DynStruct object from a sequence of NameDynAnyPairs.
static void | NameDynAnyPairSeqHelper.insert(Any a, NameDynAnyPair[] that)
static void | NameDynAnyPairSeqHelper.write(OutputStream ostream, NameDynAnyPair[] value)
static void | NameDynAnyPairHelper.insert(Any a, NameDynAnyPair that)
static void | NameDynAnyPairHelper.write(OutputStream ostream, NameDynAnyPair value)
void | DynValueOperations.set_members_as_dyn_any(NameDynAnyPair[] value) Initializes the value type's members from a sequence of NameDynAnyPairs.
void | DynStructOperations.set_members_as_dyn_any(NameDynAnyPair[] value) Initializes the struct data value associated with a DynStruct object from a sequence of NameDynAnyPairs.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.DynamicAny.NameDynAnyPairHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.DynamicAny.NameDynAnyPairHelper

No usage of org.omg.DynamicAny.NameDynAnyPairHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.DynamicAny.NameDynAnyPairSeqHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.DynamicAny.NameDynAnyPairSeqHelper

No usage of org.omg.DynamicAny.NameDynAnyPairSeqHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.DynamicAny.NameValuePair (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.DynamicAny.NameValuePair

Packages that use NameValuePair
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.

Uses of NameValuePair in org.omg.DynamicAny

Methods in org.omg.DynamicAny that return NameValuePair
NameValuePair[] | _DynValueStub.get_members() Returns a sequence of NameValuePairs describing the name and the value of each member in the value type.
NameValuePair[] | _DynStructStub.get_members() Returns a sequence of NameValuePairs describing the name and the value of each member in the struct associated with a DynStruct object.
static NameValuePair[] | NameValuePairSeqHelper.extract(Any a)
static NameValuePair[] | NameValuePairSeqHelper.read(InputStream istream)
static NameValuePair | NameValuePairHelper.extract(Any a)
static NameValuePair | NameValuePairHelper.read(InputStream istream)
NameValuePair[] | DynValueOperations.get_members() Returns a sequence of NameValuePairs describing the name and the value of each member in the value type.
NameValuePair[] | DynStructOperations.get_members() Returns a sequence of NameValuePairs describing the name and the value of each member in the struct associated with a DynStruct object.

Methods in org.omg.DynamicAny with parameters of type NameValuePair
void | _DynValueStub.set_members(NameValuePair[] value) Initializes the value type's members from a sequence of NameValuePairs.
void | _DynStructStub.set_members(NameValuePair[] value) Initializes the struct data value associated with a DynStruct object from a sequence of NameValuePairs.
static void | NameValuePairSeqHelper.insert(Any a, NameValuePair[] that)
static void | NameValuePairSeqHelper.write(OutputStream ostream, NameValuePair[] value)
static void | NameValuePairHelper.insert(Any a, NameValuePair that)
static void | NameValuePairHelper.write(OutputStream ostream, NameValuePair value)
void | DynValueOperations.set_members(NameValuePair[] value) Initializes the value type's members from a sequence of NameValuePairs.
void | DynStructOperations.set_members(NameValuePair[] value) Initializes the struct data value associated with a DynStruct object from a sequence of NameValuePairs.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.DynamicAny.NameValuePairHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.DynamicAny.NameValuePairHelper

No usage of org.omg.DynamicAny.NameValuePairHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.DynamicAny.NameValuePairSeqHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.DynamicAny.NameValuePairSeqHelper

No usage of org.omg.DynamicAny.NameValuePairSeqHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


InconsistentTypeCode (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny.DynAnyFactoryPackage
Class InconsistentTypeCode

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.DynamicAny.DynAnyFactoryPackage.InconsistentTypeCode
All Implemented Interfaces:
IDLEntity, Serializable
public final class InconsistentTypeCode
extends UserException

org/omg/DynamicAny/DynAnyFactoryPackage/InconsistentTypeCode.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/DynamicAny/DynamicAny.idl Thursday, June 12, 2003 9:59:26 PM GMT-08:00

Constructor Summary
InconsistentTypeCode()
InconsistentTypeCode(String $reason)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

InconsistentTypeCode

public InconsistentTypeCode()

InconsistentTypeCode

public InconsistentTypeCode(String $reason)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


InconsistentTypeCodeHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny.DynAnyFactoryPackage
Class InconsistentTypeCodeHelper

java.lang.Object
    extended by org.omg.DynamicAny.DynAnyFactoryPackage.InconsistentTypeCodeHelper
public abstract class InconsistentTypeCodeHelper
extends Object

org/omg/DynamicAny/DynAnyFactoryPackage/InconsistentTypeCodeHelper.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/DynamicAny/DynamicAny.idl Thursday, June 12, 2003 9:59:26 PM GMT-08:00

Constructor Summary
InconsistentTypeCodeHelper()
Method Summary
static InconsistentTypeCode | extract(Any a)
static String | id()
static void | insert(Any a, InconsistentTypeCode that)
static InconsistentTypeCode | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, InconsistentTypeCode value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

InconsistentTypeCodeHelper

public InconsistentTypeCodeHelper()
Method Detail

insert

public static void insert(Any a,
                          InconsistentTypeCode that)

extract

public static InconsistentTypeCode extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static InconsistentTypeCode read(InputStream istream)

write

public static void write(OutputStream ostream,
                         InconsistentTypeCode value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


org.omg.DynamicAny.DynAnyFactoryPackage (Java 2 Platform SE v1.4.2)

 org.omg.DynamicAny.DynAnyFactoryPackage
Classes
InconsistentTypeCodeHelper
Exceptions
InconsistentTypeCode


org.omg.DynamicAny.DynAnyFactoryPackage (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

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.

See:
Description

Class Summary
InconsistentTypeCodeHelper org/omg/DynamicAny/DynAnyFactoryPackage/InconsistentTypeCodeHelper.java .

Exception Summary
InconsistentTypeCode org/omg/DynamicAny/DynAnyFactoryPackage/InconsistentTypeCode.java .

Package org.omg.DynamicAny.DynAnyFactoryPackage Description

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. Please refer to that OMG specification for further details.

Package Specification

For a precise list of supported sections of official specifications with which the Java 2 Platform, Standard Edition, v.1.4 ORB complies, see Official Specifications for CORBA support in J2SE 1.4.

Since:
1.4
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


org.omg.DynamicAny.DynAnyFactoryPackage Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package org.omg.DynamicAny.DynAnyFactoryPackage

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class org.omg.DynamicAny.DynAnyFactoryPackage.InconsistentTypeCodeHelper
    • class java.lang.Throwable (implements java.io.Serializable)
      • class java.lang.Exception
        • class org.omg.CORBA.UserException (implements org.omg.CORBA.portable.IDLEntity)
          • class org.omg.DynamicAny.DynAnyFactoryPackage.InconsistentTypeCode
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package org.omg.DynamicAny.DynAnyFactoryPackage (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
org.omg.DynamicAny.DynAnyFactoryPackage

Packages that use org.omg.DynamicAny.DynAnyFactoryPackage
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 | 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.

Classes in org.omg.DynamicAny.DynAnyFactoryPackage used by org.omg.DynamicAny
InconsistentTypeCode
org/omg/DynamicAny/DynAnyFactoryPackage/InconsistentTypeCode.java .

Classes in org.omg.DynamicAny.DynAnyFactoryPackage used by org.omg.DynamicAny.DynAnyFactoryPackage
InconsistentTypeCode
org/omg/DynamicAny/DynAnyFactoryPackage/InconsistentTypeCode.java .

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.DynamicAny.DynAnyFactoryPackage.InconsistentTypeCode (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.DynamicAny.DynAnyFactoryPackage.InconsistentTypeCode

Packages that use InconsistentTypeCode
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 | 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.

Uses of InconsistentTypeCode in org.omg.DynamicAny

Methods in org.omg.DynamicAny that throw InconsistentTypeCode
DynAny | _DynAnyFactoryStub.create_dyn_any(Any value) Creates a new DynAny object from an any value.
DynAny | _DynAnyFactoryStub.create_dyn_any_from_type_code(TypeCode type) Creates a DynAny from a TypeCode.
DynAny | DynAnyFactoryOperations.create_dyn_any(Any value) Creates a new DynAny object from an any value.
DynAny | DynAnyFactoryOperations.create_dyn_any_from_type_code(TypeCode type) Creates a DynAny from a TypeCode.

Uses of InconsistentTypeCode in org.omg.DynamicAny.DynAnyFactoryPackage

Methods in org.omg.DynamicAny.DynAnyFactoryPackage that return InconsistentTypeCode
static InconsistentTypeCode | InconsistentTypeCodeHelper.extract(Any a)
static InconsistentTypeCode | InconsistentTypeCodeHelper.read(InputStream istream)

Methods in org.omg.DynamicAny.DynAnyFactoryPackage with parameters of type InconsistentTypeCode
static void | InconsistentTypeCodeHelper.insert(Any a, InconsistentTypeCode that)
static void | InconsistentTypeCodeHelper.write(OutputStream ostream, InconsistentTypeCode value)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.DynamicAny.DynAnyFactoryPackage.InconsistentTypeCodeHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.DynamicAny.DynAnyFactoryPackage.InconsistentTypeCodeHelper

No usage of org.omg.DynamicAny.DynAnyFactoryPackage.InconsistentTypeCodeHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


InvalidValue (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny.DynAnyPackage
Class InvalidValue

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.DynamicAny.DynAnyPackage.InvalidValue
All Implemented Interfaces:
IDLEntity, Serializable
public final class InvalidValue
extends UserException

org/omg/DynamicAny/DynAnyPackage/InvalidValue.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/DynamicAny/DynamicAny.idl Thursday, June 12, 2003 9:59:25 PM GMT-08:00

Constructor Summary
InvalidValue()
InvalidValue(String $reason)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

InvalidValue

public InvalidValue()

InvalidValue

public InvalidValue(String $reason)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


InvalidValueHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny.DynAnyPackage
Class InvalidValueHelper

java.lang.Object
    extended by org.omg.DynamicAny.DynAnyPackage.InvalidValueHelper
public abstract class InvalidValueHelper
extends Object

org/omg/DynamicAny/DynAnyPackage/InvalidValueHelper.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/DynamicAny/DynamicAny.idl Thursday, June 12, 2003 9:59:25 PM GMT-08:00

Constructor Summary
InvalidValueHelper()
Method Summary
static InvalidValue | extract(Any a)
static String | id()
static void | insert(Any a, InvalidValue that)
static InvalidValue | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, InvalidValue value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

InvalidValueHelper

public InvalidValueHelper()
Method Detail

insert

public static void insert(Any a,
                          InvalidValue that)

extract

public static InvalidValue extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static InvalidValue read(InputStream istream)

write

public static void write(OutputStream ostream,
                         InvalidValue value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


org.omg.DynamicAny.DynAnyPackage (Java 2 Platform SE v1.4.2)

 org.omg.DynamicAny.DynAnyPackage
Classes
InvalidValueHelper
TypeMismatchHelper
Exceptions
InvalidValue
TypeMismatch


org.omg.DynamicAny.DynAnyPackage (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

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.

See:
Description

Class Summary
InvalidValueHelper | org/omg/DynamicAny/DynAnyPackage/InvalidValueHelper.java .
TypeMismatchHelper | org/omg/DynamicAny/DynAnyPackage/TypeMismatchHelper.java .

Exception Summary
InvalidValue | org/omg/DynamicAny/DynAnyPackage/InvalidValue.java .
TypeMismatch | org/omg/DynamicAny/DynAnyPackage/TypeMismatch.java .

Package org.omg.DynamicAny.DynAnyPackage Description

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. Please refer to that OMG specification for further details.

Package Specification

For a precise list of supported sections of official specifications with which the Java 2 Platform, Standard Edition, v.1.4 ORB complies, see Official Specifications for CORBA support in J2SE 1.4.

Since:
1.4
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


org.omg.DynamicAny.DynAnyPackage Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package org.omg.DynamicAny.DynAnyPackage

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class org.omg.DynamicAny.DynAnyPackage.InvalidValueHelper
    • class java.lang.Throwable (implements java.io.Serializable)
      • class java.lang.Exception
        • class org.omg.CORBA.UserException (implements org.omg.CORBA.portable.IDLEntity)
          • class org.omg.DynamicAny.DynAnyPackage.InvalidValue
          • class org.omg.DynamicAny.DynAnyPackage.TypeMismatch
    • class org.omg.DynamicAny.DynAnyPackage.TypeMismatchHelper
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package org.omg.DynamicAny.DynAnyPackage (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
org.omg.DynamicAny.DynAnyPackage

Packages that use org.omg.DynamicAny.DynAnyPackage
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.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.

Classes in org.omg.DynamicAny.DynAnyPackage used by org.omg.DynamicAny
InvalidValue
org/omg/DynamicAny/DynAnyPackage/InvalidValue.java .
TypeMismatch
org/omg/DynamicAny/DynAnyPackage/TypeMismatch.java .

Classes in org.omg.DynamicAny.DynAnyPackage used by org.omg.DynamicAny.DynAnyPackage
InvalidValue
org/omg/DynamicAny/DynAnyPackage/InvalidValue.java .
TypeMismatch
org/omg/DynamicAny/DynAnyPackage/TypeMismatch.java .

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


TypeMismatch (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny.DynAnyPackage
Class TypeMismatch

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.DynamicAny.DynAnyPackage.TypeMismatch
All Implemented Interfaces:
IDLEntity, Serializable
public final class TypeMismatch
extends UserException

org/omg/DynamicAny/DynAnyPackage/TypeMismatch.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/DynamicAny/DynamicAny.idl Thursday, June 12, 2003 9:59:25 PM GMT-08:00

Constructor Summary
TypeMismatch()
TypeMismatch(String $reason)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

TypeMismatch

public TypeMismatch()

TypeMismatch

public TypeMismatch(String $reason)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


TypeMismatchHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.DynamicAny.DynAnyPackage
Class TypeMismatchHelper

java.lang.Object
    extended by org.omg.DynamicAny.DynAnyPackage.TypeMismatchHelper
public abstract class TypeMismatchHelper
extends Object

org/omg/DynamicAny/DynAnyPackage/TypeMismatchHelper.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/DynamicAny/DynamicAny.idl Thursday, June 12, 2003 9:59:25 PM GMT-08:00

Constructor Summary
TypeMismatchHelper()
Method Summary
static TypeMismatch | extract(Any a)
static String | id()
static void | insert(Any a, TypeMismatch that)
static TypeMismatch | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, TypeMismatch value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

TypeMismatchHelper

public TypeMismatchHelper()
Method Detail

insert

public static void insert(Any a,
                          TypeMismatch that)

extract

public static TypeMismatch extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static TypeMismatch read(InputStream istream)

write

public static void write(OutputStream ostream,
                         TypeMismatch value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Uses of Class org.omg.DynamicAny.DynAnyPackage.InvalidValue (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.DynamicAny.DynAnyPackage.InvalidValue

Packages that use InvalidValue
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.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.

Uses of InvalidValue in org.omg.DynamicAny

Methods in org.omg.DynamicAny that throw InvalidValue
Any | DynValueBoxOperations.get_boxed_value() Returns the boxed value as an Any.
DynAny | DynValueBoxOperations.get_boxed_value_as_dyn_any() Returns the boxed value as a DynAny.
void | _DynSequenceStub.set_length(int len) Sets the length of the sequence.
void | _DynSequenceStub.set_elements(Any[] value) Sets the elements of a sequence.
void | _DynSequenceStub.set_elements_as_dyn_any(DynAny[] value) Sets the elements of a sequence using DynAnys.
void | _DynSequenceStub.from_any(Any value) Initializes the value associated with a DynAny object with the value contained in an any.
void | _DynSequenceStub.insert_boolean(boolean value) Inserts a boolean value into the DynAny.
void | _DynSequenceStub.insert_octet(byte value) Inserts a byte value into the DynAny.
void | _DynSequenceStub.insert_char(char value) Inserts a char value into the DynAny.
void | _DynSequenceStub.insert_short(short value) Inserts a short value into the DynAny.
void | _DynSequenceStub.insert_ushort(short value) Inserts a short value into the DynAny.
void | _DynSequenceStub.insert_long(int value) Inserts an integer value into the DynAny.
void | _DynSequenceStub.insert_ulong(int value) Inserts an integer value into the DynAny.
void | _DynSequenceStub.insert_float(float value) Inserts a float value into the DynAny.
void | _DynSequenceStub.insert_double(double value) Inserts a double value into the DynAny.
void | _DynSequenceStub.insert_string(String value) Inserts a string value into the DynAny.
void | _DynSequenceStub.insert_reference(Object value) Inserts a reference to a CORBA object into the DynAny.
void | _DynSequenceStub.insert_typecode(TypeCode value) Inserts a TypeCode object into the DynAny.
void | _DynSequenceStub.insert_longlong(long value) Inserts a long value into the DynAny.
void | _DynSequenceStub.insert_ulonglong(long value) Inserts a long value into the DynAny.
void | _DynSequenceStub.insert_wchar(char value) Inserts a char value into the DynAny.
void | _DynSequenceStub.insert_wstring(String value) Inserts a string value into the DynAny.
void | _DynSequenceStub.insert_any(Any value) Inserts an Any value into the Any represented by this DynAny.
void | _DynSequenceStub.insert_dyn_any(DynAny value) Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.
void | _DynSequenceStub.insert_val(Serializable value) Inserts a reference to a Serializable object into this DynAny.
boolean | _DynSequenceStub.get_boolean() Extracts the boolean value from this DynAny.
byte | _DynSequenceStub.get_octet() Extracts the byte value from this DynAny.
char | _DynSequenceStub.get_char() Extracts the char value from this DynAny.
short | _DynSequenceStub.get_short() Extracts the short value from this DynAny.
short | _DynSequenceStub.get_ushort() Extracts the short value from this DynAny.
int | _DynSequenceStub.get_long() Extracts the integer value from this DynAny.
int | _DynSequenceStub.get_ulong() Extracts the integer value from this DynAny.
float | _DynSequenceStub.get_float() Extracts the float value from this DynAny.
double | _DynSequenceStub.get_double() Extracts the double value from this DynAny.
String | _DynSequenceStub.get_string() Extracts the string value from this DynAny.
Object | _DynSequenceStub.get_reference() Extracts the reference to a CORBA Object from this DynAny.
TypeCode | _DynSequenceStub.get_typecode() Extracts the TypeCode object from this DynAny.
long | _DynSequenceStub.get_longlong() Extracts the long value from this DynAny.
long | _DynSequenceStub.get_ulonglong() Extracts the long value from this DynAny.
char | _DynSequenceStub.get_wchar() Extracts the long value from this DynAny.
String | _DynSequenceStub.get_wstring() Extracts the string value from this DynAny.
Any | _DynSequenceStub.get_any() Extracts an Any value contained in the Any represented by this DynAny.
DynAny | _DynSequenceStub.get_dyn_any() Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.
Serializable | _DynSequenceStub.get_val() Extracts a Serializable object from this DynAny.
boolean | _DynFixedStub.set_value(String val) Sets the value of the DynFixed.
void | _DynFixedStub.from_any(Any value) Initializes the value associated with a DynAny object with the value contained in an any.
void | _DynFixedStub.insert_boolean(boolean value) Inserts a boolean value into the DynAny.
void | _DynFixedStub.insert_octet(byte value) Inserts a byte value into the DynAny.
void | _DynFixedStub.insert_char(char value) Inserts a char value into the DynAny.
void | _DynFixedStub.insert_short(short value) Inserts a short value into the DynAny.
void | _DynFixedStub.insert_ushort(short value) Inserts a short value into the DynAny.
void | _DynFixedStub.insert_long(int value) Inserts an integer value into the DynAny.
void | _DynFixedStub.insert_ulong(int value) Inserts an integer value into the DynAny.
void | _DynFixedStub.insert_float(float value) Inserts a float value into the DynAny.
void | _DynFixedStub.insert_double(double value) Inserts a double value into the DynAny.
void | _DynFixedStub.insert_string(String value) Inserts a string value into the DynAny.
void | _DynFixedStub.insert_reference(Object value) Inserts a reference to a CORBA object into the DynAny.
void | _DynFixedStub.insert_typecode(TypeCode value) Inserts a TypeCode object into the DynAny.
void | _DynFixedStub.insert_longlong(long value) Inserts a long value into the DynAny.
void | _DynFixedStub.insert_ulonglong(long value) Inserts a long value into the DynAny.
void | _DynFixedStub.insert_wchar(char value) Inserts a char value into the DynAny.
void | _DynFixedStub.insert_wstring(String value) Inserts a string value into the DynAny.
void | _DynFixedStub.insert_any(Any value) Inserts an Any value into the Any represented by this DynAny.
void | _DynFixedStub.insert_dyn_any(DynAny value) Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.
void | _DynFixedStub.insert_val(Serializable value) Inserts a reference to a Serializable object into this DynAny.
boolean | _DynFixedStub.get_boolean() Extracts the boolean value from this DynAny.
byte | _DynFixedStub.get_octet() Extracts the byte value from this DynAny.
char | _DynFixedStub.get_char() Extracts the char value from this DynAny.
short | _DynFixedStub.get_short() Extracts the short value from this DynAny.
short | _DynFixedStub.get_ushort() Extracts the short value from this DynAny.
int | _DynFixedStub.get_long() Extracts the integer value from this DynAny.
int | _DynFixedStub.get_ulong() Extracts the integer value from this DynAny.
float | _DynFixedStub.get_float() Extracts the float value from this DynAny.
double | _DynFixedStub.get_double() Extracts the double value from this DynAny.
String | _DynFixedStub.get_string() Extracts the string value from this DynAny.
Object | _DynFixedStub.get_reference() Extracts the reference to a CORBA Object from this DynAny.
TypeCode | _DynFixedStub.get_typecode() Extracts the TypeCode object from this DynAny.
long | _DynFixedStub.get_longlong() Extracts the long value from this DynAny.
long | _DynFixedStub.get_ulonglong() Extracts the long value from this DynAny.
char | _DynFixedStub.get_wchar() Extracts the long value from this DynAny.
String | _DynFixedStub.get_wstring() Extracts the string value from this DynAny.
Any | _DynFixedStub.get_any() Extracts an Any value contained in the Any represented by this DynAny.
DynAny | _DynFixedStub.get_dyn_any() Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.
Serializable | _DynFixedStub.get_val() Extracts a Serializable object from this DynAny.
void | _DynEnumStub.set_as_string(String value) Sets the value of the DynEnum to the enumerated value whose IDL identifier is passed in the value parameter.
void | _DynEnumStub.set_as_ulong(int value) Sets the value of the DynEnum as the enumerated value's ordinal value.
void | _DynEnumStub.from_any(Any value) Initializes the value associated with a DynAny object with the value contained in an any.
void | _DynEnumStub.insert_boolean(boolean value) Inserts a boolean value into the DynAny.
void | _DynEnumStub.insert_octet(byte value) Inserts a byte value into the DynAny.
void | _DynEnumStub.insert_char(char value) Inserts a char value into the DynAny.
void | _DynEnumStub.insert_short(short value) Inserts a short value into the DynAny.
void | _DynEnumStub.insert_ushort(short value) Inserts a short value into the DynAny.
void | _DynEnumStub.insert_long(int value) Inserts an integer value into the DynAny.
void | _DynEnumStub.insert_ulong(int value) Inserts an integer value into the DynAny.
void | _DynEnumStub.insert_float(float value) Inserts a float value into the DynAny.
void | _DynEnumStub.insert_double(double value) Inserts a double value into the DynAny.
void | _DynEnumStub.insert_string(String value) Inserts a string value into the DynAny.
void | _DynEnumStub.insert_reference(Object value) Inserts a reference to a CORBA object into the DynAny.
void | _DynEnumStub.insert_typecode(TypeCode value) Inserts a TypeCode object into the DynAny.
void | _DynEnumStub.insert_longlong(long value) Inserts a long value into the DynAny.
void | _DynEnumStub.insert_ulonglong(long value) Inserts a long value into the DynAny.
void | _DynEnumStub.insert_wchar(char value) Inserts a char value into the DynAny.
void | _DynEnumStub.insert_wstring(String value) Inserts a string value into the DynAny.
void | _DynEnumStub.insert_any(Any value) Inserts an Any value into the Any represented by this DynAny.
void | _DynEnumStub.insert_dyn_any(DynAny value) Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.
void | _DynEnumStub.insert_val(Serializable value) Inserts a reference to a Serializable object into this DynAny.
boolean | _DynEnumStub.get_boolean() Extracts the boolean value from this DynAny.
byte | _DynEnumStub.get_octet() Extracts the byte value from this DynAny.
char | _DynEnumStub.get_char() Extracts the char value from this DynAny.
short | _DynEnumStub.get_short() Extracts the short value from this DynAny.
short | _DynEnumStub.get_ushort() Extracts the short value from this DynAny.
int | _DynEnumStub.get_long() Extracts the integer value from this DynAny.
int | _DynEnumStub.get_ulong() Extracts the integer value from this DynAny.
float | _DynEnumStub.get_float() Extracts the float value from this DynAny.
double | _DynEnumStub.get_double() Extracts the double value from this DynAny.
String | _DynEnumStub.get_string() Extracts the string value from this DynAny.
Object | _DynEnumStub.get_reference() Extracts the reference to a CORBA Object from this DynAny.
TypeCode | _DynEnumStub.get_typecode() Extracts the TypeCode object from this DynAny.
long | _DynEnumStub.get_longlong() Extracts the long value from this DynAny.
long | _DynEnumStub.get_ulonglong() Extracts the long value from this DynAny.
char | _DynEnumStub.get_wchar() Extracts the long value from this DynAny.
String | _DynEnumStub.get_wstring() Extracts the string value from this DynAny.
Any | _DynEnumStub.get_any() Extracts an Any value contained in the Any represented by this DynAny.
DynAny | _DynEnumStub.get_dyn_any() Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.
Serializable | _DynEnumStub.get_val() Extracts a Serializable object from this DynAny.
void | _DynArrayStub.set_elements(Any[] value) Sets the DynArray to contain the passed elements.
void | _DynArrayStub.set_elements_as_dyn_any(DynAny[] value) Sets the DynArray to contain the passed elements.
void | _DynArrayStub.from_any(Any value) Initializes the value associated with a DynAny object with the value contained in an any.
void | _DynArrayStub.insert_boolean(boolean value) Inserts a boolean value into the DynAny.
void | _DynArrayStub.insert_octet(byte value) Inserts a byte value into the DynAny.
void | _DynArrayStub.insert_char(char value) Inserts a char value into the DynAny.
void | _DynArrayStub.insert_short(short value) Inserts a short value into the DynAny.
void | _DynArrayStub.insert_ushort(short value) Inserts a short value into the DynAny.
void | _DynArrayStub.insert_long(int value) Inserts an integer value into the DynAny.
void | _DynArrayStub.insert_ulong(int value) Inserts an integer value into the DynAny.
void | _DynArrayStub.insert_float(float value) Inserts a float value into the DynAny.
void | _DynArrayStub.insert_double(double value) Inserts a double value into the DynAny.
void | _DynArrayStub.insert_string(String value) Inserts a string value into the DynAny.
void | _DynArrayStub.insert_reference(Object value) Inserts a reference to a CORBA object into the DynAny.
void | _DynArrayStub.insert_typecode(TypeCode value) Inserts a TypeCode object into the DynAny.
void | _DynArrayStub.insert_longlong(long value) Inserts a long value into the DynAny.
void | _DynArrayStub.insert_ulonglong(long value) Inserts a long value into the DynAny.
void | _DynArrayStub.insert_wchar(char value) Inserts a char value into the DynAny.
void | _DynArrayStub.insert_wstring(String value) Inserts a string value into the DynAny.
void | _DynArrayStub.insert_any(Any value) Inserts an Any value into the Any represented by this DynAny.
void | _DynArrayStub.insert_dyn_any(DynAny value) Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.
void | _DynArrayStub.insert_val(Serializable value) Inserts a reference to a Serializable object into this DynAny.
boolean | _DynArrayStub.get_boolean() Extracts the boolean value from this DynAny.
byte | _DynArrayStub.get_octet() Extracts the byte value from this DynAny.
char | _DynArrayStub.get_char() Extracts the char value from this DynAny.
short | _DynArrayStub.get_short() Extracts the short value from this DynAny.
short | _DynArrayStub.get_ushort() Extracts the short value from this DynAny.
int | _DynArrayStub.get_long() Extracts the integer value from this DynAny.
int | _DynArrayStub.get_ulong() Extracts the integer value from this DynAny.
float | _DynArrayStub.get_float() Extracts the float value from this DynAny.
double | _DynArrayStub.get_double() Extracts the double value from this DynAny.
String | _DynArrayStub.get_string() Extracts the string value from this DynAny.
Object | _DynArrayStub.get_reference() Extracts the reference to a CORBA Object from this DynAny.
TypeCode | _DynArrayStub.get_typecode() Extracts the TypeCode object from this DynAny.
long | _DynArrayStub.get_longlong() Extracts the long value from this DynAny.
long | _DynArrayStub.get_ulonglong() Extracts the long value from this DynAny.
char | _DynArrayStub.get_wchar() Extracts the long value from this DynAny.
String | _DynArrayStub.get_wstring() Extracts the string value from this DynAny.
Any | _DynArrayStub.get_any() Extracts an Any value contained in the Any represented by this DynAny.
DynAny | _DynArrayStub.get_dyn_any() Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.
Serializable | _DynArrayStub.get_val() Extracts a Serializable object from this DynAny.
String | _DynValueStub.current_member_name() Returns the name of the member at the current position.
TCKind | _DynValueStub.current_member_kind() Returns the TCKind associated with the member at the current position.
NameValuePair[] | _DynValueStub.get_members() Returns a sequence of NameValuePairs describing the name and the value of each member in the value type.
void | _DynValueStub.set_members(NameValuePair[] value) Initializes the value type's members from a sequence of NameValuePairs.
NameDynAnyPair[] | _DynValueStub.get_members_as_dyn_any() Returns a sequence of NameDynAnyPairs describing the name and the value of each member in the value type.
void | _DynValueStub.set_members_as_dyn_any(NameDynAnyPair[] value) Initializes the value type's members from a sequence of NameDynAnyPairs.
void | _DynValueStub.from_any(Any value) Initializes the value associated with a DynAny object with the value contained in an any.
void | _DynValueStub.insert_boolean(boolean value) Inserts a boolean value into the DynAny.
void | _DynValueStub.insert_octet(byte value) Inserts a byte value into the DynAny.
void | _DynValueStub.insert_char(char value) Inserts a char value into the DynAny.
void | _DynValueStub.insert_short(short value) Inserts a short value into the DynAny.
void | _DynValueStub.insert_ushort(short value) Inserts a short value into the DynAny.
void | _DynValueStub.insert_long(int value) Inserts an integer value into the DynAny.
void | _DynValueStub.insert_ulong(int value) Inserts an integer value into the DynAny.
void | _DynValueStub.insert_float(float value) Inserts a float value into the DynAny.
void | _DynValueStub.insert_double(double value) Inserts a double value into the DynAny.
void | _DynValueStub.insert_string(String value) Inserts a string value into the DynAny.
void | _DynValueStub.insert_reference(Object value) Inserts a reference to a CORBA object into the DynAny.
void | _DynValueStub.insert_typecode(TypeCode value) Inserts a TypeCode object into the DynAny.
void | _DynValueStub.insert_longlong(long value) Inserts a long value into the DynAny.
void | _DynValueStub.insert_ulonglong(long value) Inserts a long value into the DynAny.
void | _DynValueStub.insert_wchar(char value) Inserts a char value into the DynAny.
void | _DynValueStub.insert_wstring(String value) Inserts a string value into the DynAny.
void | _DynValueStub.insert_any(Any value) Inserts an Any value into the Any represented by this DynAny.
void | _DynValueStub.insert_dyn_any(DynAny value) Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.
void | _DynValueStub.insert_val(Serializable value) Inserts a reference to a Serializable object into this DynAny.
boolean | _DynValueStub.get_boolean() Extracts the boolean value from this DynAny.
byte | _DynValueStub.get_octet() Extracts the byte value from this DynAny.
char | _DynValueStub.get_char() Extracts the char value from this DynAny.
short | _DynValueStub.get_short() Extracts the short value from this DynAny.
short | _DynValueStub.get_ushort() Extracts the short value from this DynAny.
int | _DynValueStub.get_long() Extracts the integer value from this DynAny.
int | _DynValueStub.get_ulong() Extracts the integer value from this DynAny.
float | _DynValueStub.get_float() Extracts the float value from this DynAny.
double | _DynValueStub.get_double() Extracts the double value from this DynAny.
String | _DynValueStub.get_string() Extracts the string value from this DynAny.
Object | _DynValueStub.get_reference() Extracts the reference to a CORBA Object from this DynAny.
TypeCode | _DynValueStub.get_typecode() Extracts the TypeCode object from this DynAny.
long | _DynValueStub.get_longlong() Extracts the long value from this DynAny.
long | _DynValueStub.get_ulonglong() Extracts the long value from this DynAny.
char | _DynValueStub.get_wchar() Extracts the long value from this DynAny.
String | _DynValueStub.get_wstring() Extracts the string value from this DynAny.
Any | _DynValueStub.get_any() Extracts an Any value contained in the Any represented by this DynAny.
DynAny | _DynValueStub.get_dyn_any() Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.
Serializable | _DynValueStub.get_val() Extracts a Serializable object from this DynAny.
void | _DynAnyStub.from_any(Any value) Initializes the value associated with a DynAny object with the value contained in an any.
void | _DynAnyStub.insert_boolean(boolean value) Inserts a boolean value into the DynAny.
void | _DynAnyStub.insert_octet(byte value) Inserts a byte value into the DynAny.
void | _DynAnyStub.insert_char(char value) Inserts a char value into the DynAny.
void | _DynAnyStub.insert_short(short value) Inserts a short value into the DynAny.
void | _DynAnyStub.insert_ushort(short value) Inserts a short value into the DynAny.
void | _DynAnyStub.insert_long(int value) Inserts an integer value into the DynAny.
void | _DynAnyStub.insert_ulong(int value) Inserts an integer value into the DynAny.
void | _DynAnyStub.insert_float(float value) Inserts a float value into the DynAny.
void | _DynAnyStub.insert_double(double value) Inserts a double value into the DynAny.
void | _DynAnyStub.insert_string(String value) Inserts a string value into the DynAny.
void | _DynAnyStub.insert_reference(Object value) Inserts a reference to a CORBA object into the DynAny.
void | _DynAnyStub.insert_typecode(TypeCode value) Inserts a TypeCode object into the DynAny.
void | _DynAnyStub.insert_longlong(long value) Inserts a long value into the DynAny.
void | _DynAnyStub.insert_ulonglong(long value) Inserts a long value into the DynAny.
void | _DynAnyStub.insert_wchar(char value) Inserts a char value into the DynAny.
void | _DynAnyStub.insert_wstring(String value) Inserts a string value into the DynAny.
void | _DynAnyStub.insert_any(Any value) Inserts an Any value into the Any represented by this DynAny.
void | _DynAnyStub.insert_dyn_any(DynAny value) Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.
void | _DynAnyStub.insert_val(Serializable value) Inserts a reference to a Serializable object into this DynAny.
boolean | _DynAnyStub.get_boolean() Extracts the boolean value from this DynAny.
byte | _DynAnyStub.get_octet() Extracts the byte value from this DynAny.
char | _DynAnyStub.get_char() Extracts the char value from this DynAny.
short | _DynAnyStub.get_short() Extracts the short value from this DynAny.
short | _DynAnyStub.get_ushort() Extracts the short value from this DynAny.
int | _DynAnyStub.get_long() Extracts the integer value from this DynAny.
int | _DynAnyStub.get_ulong() Extracts the integer value from this DynAny.
float | _DynAnyStub.get_float() Extracts the float value from this DynAny.
double | _DynAnyStub.get_double() Extracts the double value from this DynAny.
String | _DynAnyStub.get_string() Extracts the string value from this DynAny.
Object | _DynAnyStub.get_reference() Extracts the reference to a CORBA Object from this DynAny.
TypeCode | _DynAnyStub.get_typecode() Extracts the TypeCode object from this DynAny.
long | _DynAnyStub.get_longlong() Extracts the long value from this DynAny.
long | _DynAnyStub.get_ulonglong() Extracts the long value from this DynAny.
char | _DynAnyStub.get_wchar() Extracts the long value from this DynAny.
String | _DynAnyStub.get_wstring() Extracts the string value from this DynAny.
Any | _DynAnyStub.get_any() Extracts an Any value contained in the Any represented by this DynAny.
DynAny | _DynAnyStub.get_dyn_any() Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.
Serializable | _DynAnyStub.get_val() Extracts a Serializable object from this DynAny.
TCKind | _DynUnionStub.member_kind() Returns the TCKind value of the currently active members TypeCode.
DynAny | _DynUnionStub.member() Returns the currently active member.
String | _DynUnionStub.member_name() Returns the name of the currently active member.
void | _DynUnionStub.from_any(Any value) Initializes the value associated with a DynAny object with the value contained in an any.
void | _DynUnionStub.insert_boolean(boolean value) Inserts a boolean value into the DynAny.
void | _DynUnionStub.insert_octet(byte value) Inserts a byte value into the DynAny.
void | _DynUnionStub.insert_char(char value) Inserts a char value into the DynAny.
void | _DynUnionStub.insert_short(short value) Inserts a short value into the DynAny.
void | _DynUnionStub.insert_ushort(short value) Inserts a short value into the DynAny.
void | _DynUnionStub.insert_long(int value) Inserts an integer value into the DynAny.
void | _DynUnionStub.insert_ulong(int value) Inserts an integer value into the DynAny.
void | _DynUnionStub.insert_float(float value) Inserts a float value into the DynAny.
void | _DynUnionStub.insert_double(double value) Inserts a double value into the DynAny.
void | _DynUnionStub.insert_string(String value) Inserts a string value into the DynAny.
void | _DynUnionStub.insert_reference(Object value) Inserts a reference to a CORBA object into the DynAny.
void | _DynUnionStub.insert_typecode(TypeCode value) Inserts a TypeCode object into the DynAny.
void | _DynUnionStub.insert_longlong(long value) Inserts a long value into the DynAny.
void | _DynUnionStub.insert_ulonglong(long value) Inserts a long value into the DynAny.
void | _DynUnionStub.insert_wchar(char value) Inserts a char value into the DynAny.
void | _DynUnionStub.insert_wstring(String value) Inserts a string value into the DynAny.
void | _DynUnionStub.insert_any(Any value) Inserts an Any value into the Any represented by this DynAny.
void | _DynUnionStub.insert_dyn_any(DynAny value) Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.
void | _DynUnionStub.insert_val(Serializable value) Inserts a reference to a Serializable object into this DynAny.
boolean | _DynUnionStub.get_boolean() Extracts the boolean value from this DynAny.
byte | _DynUnionStub.get_octet() Extracts the byte value from this DynAny.
char | _DynUnionStub.get_char() Extracts the char value from this DynAny.
short | _DynUnionStub.get_short() Extracts the short value from this DynAny.
short | _DynUnionStub.get_ushort() Extracts the short value from this DynAny.
int | _DynUnionStub.get_long() Extracts the integer value from this DynAny.
int | _DynUnionStub.get_ulong() Extracts the integer value from this DynAny.
float | _DynUnionStub.get_float() Extracts the float value from this DynAny.
double | _DynUnionStub.get_double() Extracts the double value from this DynAny.
String | _DynUnionStub.get_string() Extracts the string value from this DynAny.
Object | _DynUnionStub.get_reference() Extracts the reference to a CORBA Object from this DynAny.
TypeCode | _DynUnionStub.get_typecode() Extracts the TypeCode object from this DynAny.
long | _DynUnionStub.get_longlong() Extracts the long value from this DynAny.
long | _DynUnionStub.get_ulonglong() Extracts the long value from this DynAny.
char | _DynUnionStub.get_wchar() Extracts the long value from this DynAny.
String | _DynUnionStub.get_wstring() Extracts the string value from this DynAny.
Any | _DynUnionStub.get_any() Extracts an Any value contained in the Any represented by this DynAny.
DynAny | _DynUnionStub.get_dyn_any() Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.
Serializable | _DynUnionStub.get_val() Extracts a Serializable object from this DynAny.
String | _DynStructStub.current_member_name() Returns the name of the member at the current position.
TCKind | _DynStructStub.current_member_kind() Returns the TCKind associated with the member at the current position.
void | _DynStructStub.set_members(NameValuePair[] value) Initializes the struct data value associated with a DynStruct object from a sequence of NameValuePairs.
void | _DynStructStub.set_members_as_dyn_any(NameDynAnyPair[] value) Initializes the struct data value associated with a DynStruct object from a sequence of NameDynAnyPairs.
void | _DynStructStub.from_any(Any value) Initializes the value associated with a DynAny object with the value contained in an any.
void | _DynStructStub.insert_boolean(boolean value) Inserts a boolean value into the DynAny.
void | _DynStructStub.insert_octet(byte value) Inserts a byte value into the DynAny.
void | _DynStructStub.insert_char(char value) Inserts a char value into the DynAny.
void | _DynStructStub.insert_short(short value) Inserts a short value into the DynAny.
void | _DynStructStub.insert_ushort(short value) Inserts a short value into the DynAny.
void | _DynStructStub.insert_long(int value) Inserts an integer value into the DynAny.
void | _DynStructStub.insert_ulong(int value) Inserts an integer value into the DynAny.
void | _DynStructStub.insert_float(float value) Inserts a float value into the DynAny.
void | _DynStructStub.insert_double(double value) Inserts a double value into the DynAny.
void | _DynStructStub.insert_string(String value) Inserts a string value into the DynAny.
void | _DynStructStub.insert_reference(Object value) Inserts a reference to a CORBA object into the DynAny.
void | _DynStructStub.insert_typecode(TypeCode value) Inserts a TypeCode object into the DynAny.
void | _DynStructStub.insert_longlong(long value) Inserts a long value into the DynAny.
void | _DynStructStub.insert_ulonglong(long value) Inserts a long value into the DynAny.
void | _DynStructStub.insert_wchar(char value) Inserts a char value into the DynAny.
void | _DynStructStub.insert_wstring(String value) Inserts a string value into the DynAny.
void | _DynStructStub.insert_any(Any value) Inserts an Any value into the Any represented by this DynAny.
void | _DynStructStub.insert_dyn_any(DynAny value) Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.
void | _DynStructStub.insert_val(Serializable value) Inserts a reference to a Serializable object into this DynAny.
boolean | _DynStructStub.get_boolean() Extracts the boolean value from this DynAny.
byte | _DynStructStub.get_octet() Extracts the byte value from this DynAny.
char | _DynStructStub.get_char() Extracts the char value from this DynAny.
short | _DynStructStub.get_short() Extracts the short value from this DynAny.
short | _DynStructStub.get_ushort() Extracts the short value from this DynAny.
int | _DynStructStub.get_long() Extracts the integer value from this DynAny.
int | _DynStructStub.get_ulong() Extracts the integer value from this DynAny.
float | _DynStructStub.get_float() Extracts the float value from this DynAny.
double | _DynStructStub.get_double() Extracts the double value from this DynAny.
String | _DynStructStub.get_string() Extracts the string value from this DynAny.
Object | _DynStructStub.get_reference() Extracts the reference to a CORBA Object from this DynAny.
TypeCode | _DynStructStub.get_typecode() Extracts the TypeCode object from this DynAny.
long | _DynStructStub.get_longlong() Extracts the long value from this DynAny.
long | _DynStructStub.get_ulonglong() Extracts the long value from this DynAny.
char | _DynStructStub.get_wchar() Extracts the long value from this DynAny.
String | _DynStructStub.get_wstring() Extracts the string value from this DynAny.
Any | _DynStructStub.get_any() Extracts an Any value contained in the Any represented by this DynAny.
DynAny | _DynStructStub.get_dyn_any() Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.
Serializable | _DynStructStub.get_val() Extracts a Serializable object from this DynAny.
String | DynValueOperations.current_member_name() Returns the name of the member at the current position.
TCKind | DynValueOperations.current_member_kind() Returns the TCKind associated with the member at the current position.
NameValuePair[] | DynValueOperations.get_members() Returns a sequence of NameValuePairs describing the name and the value of each member in the value type.
void | DynValueOperations.set_members(NameValuePair[] value) Initializes the value type's members from a sequence of NameValuePairs.
NameDynAnyPair[] | DynValueOperations.get_members_as_dyn_any() Returns a sequence of NameDynAnyPairs describing the name and the value of each member in the value type.
void | DynValueOperations.set_members_as_dyn_any(NameDynAnyPair[] value) Initializes the value type's members from a sequence of NameDynAnyPairs.
TCKind | DynUnionOperations.member_kind() Returns the TCKind value of the currently active members TypeCode.
DynAny | DynUnionOperations.member() Returns the currently active member.
String | DynUnionOperations.member_name() Returns the name of the currently active member.
String | DynStructOperations.current_member_name() Returns the name of the member at the current position.
TCKind | DynStructOperations.current_member_kind() Returns the TCKind associated with the member at the current position.
void | DynStructOperations.set_members(NameValuePair[] value) Initializes the struct data value associated with a DynStruct object from a sequence of NameValuePairs.
void | DynStructOperations.set_members_as_dyn_any(NameDynAnyPair[] value) Initializes the struct data value associated with a DynStruct object from a sequence of NameDynAnyPairs.
void | DynSequenceOperations.set_length(int len) Sets the length of the sequence.
void | DynSequenceOperations.set_elements(Any[] value) Sets the elements of a sequence.
void | DynSequenceOperations.set_elements_as_dyn_any(DynAny[] value) Sets the elements of a sequence using DynAnys.
boolean | DynFixedOperations.set_value(String val) Sets the value of the DynFixed.
void | DynEnumOperations.set_as_string(String value) Sets the value of the DynEnum to the enumerated value whose IDL identifier is passed in the value parameter.
void | DynEnumOperations.set_as_ulong(int value) Sets the value of the DynEnum as the enumerated value's ordinal value.
void | DynArrayOperations.set_elements(Any[] value) Sets the DynArray to contain the passed elements.
void | DynArrayOperations.set_elements_as_dyn_any(DynAny[] value) Sets the DynArray to contain the passed elements.
void | DynAnyOperations.from_any(Any value) Initializes the value associated with a DynAny object with the value contained in an any.
void | DynAnyOperations.insert_boolean(boolean value) Inserts a boolean value into the DynAny.
void | DynAnyOperations.insert_octet(byte value) Inserts a byte value into the DynAny.
void | DynAnyOperations.insert_char(char value) Inserts a char value into the DynAny.
void | DynAnyOperations.insert_short(short value) Inserts a short value into the DynAny.
void | DynAnyOperations.insert_ushort(short value) Inserts a short value into the DynAny.
void | DynAnyOperations.insert_long(int value) Inserts an integer value into the DynAny.
void | DynAnyOperations.insert_ulong(int value) Inserts an integer value into the DynAny.
void | DynAnyOperations.insert_float(float value) Inserts a float value into the DynAny.
void | DynAnyOperations.insert_double(double value) Inserts a double value into the DynAny.
void | DynAnyOperations.insert_string(String value) Inserts a string value into the DynAny.
void | DynAnyOperations.insert_reference(Object value) Inserts a reference to a CORBA object into the DynAny.
void | DynAnyOperations.insert_typecode(TypeCode value) Inserts a TypeCode object into the DynAny.
void | DynAnyOperations.insert_longlong(long value) Inserts a long value into the DynAny.
void | DynAnyOperations.insert_ulonglong(long value) Inserts a long value into the DynAny.
void | DynAnyOperations.insert_wchar(char value) Inserts a char value into the DynAny.
void | DynAnyOperations.insert_wstring(String value) Inserts a string value into the DynAny.
void | DynAnyOperations.insert_any(Any value) Inserts an Any value into the Any represented by this DynAny.
void | DynAnyOperations.insert_dyn_any(DynAny value) Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.
void | DynAnyOperations.insert_val(Serializable value) Inserts a reference to a Serializable object into this DynAny.
boolean | DynAnyOperations.get_boolean() Extracts the boolean value from this DynAny.
byte | DynAnyOperations.get_octet() Extracts the byte value from this DynAny.
char | DynAnyOperations.get_char() Extracts the char value from this DynAny.
short | DynAnyOperations.get_short() Extracts the short value from this DynAny.
short | DynAnyOperations.get_ushort() Extracts the short value from this DynAny.
int | DynAnyOperations.get_long() Extracts the integer value from this DynAny.
int | DynAnyOperations.get_ulong() Extracts the integer value from this DynAny.
float | DynAnyOperations.get_float() Extracts the float value from this DynAny.
double | DynAnyOperations.get_double() Extracts the double value from this DynAny.
String | DynAnyOperations.get_string() Extracts the string value from this DynAny.
Object | DynAnyOperations.get_reference() Extracts the reference to a CORBA Object from this DynAny.
TypeCode | DynAnyOperations.get_typecode() Extracts the TypeCode object from this DynAny.
long | DynAnyOperations.get_longlong() Extracts the long value from this DynAny.
long | DynAnyOperations.get_ulonglong() Extracts the long value from this DynAny.
char | DynAnyOperations.get_wchar() Extracts the long value from this DynAny.
String | DynAnyOperations.get_wstring() Extracts the string value from this DynAny.
Any | DynAnyOperations.get_any() Extracts an Any value contained in the Any represented by this DynAny.
DynAny | DynAnyOperations.get_dyn_any() Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.
Serializable | DynAnyOperations.get_val() Extracts a Serializable object from this DynAny.

Uses of InvalidValue in org.omg.DynamicAny.DynAnyPackage

Methods in org.omg.DynamicAny.DynAnyPackage that return InvalidValue
static InvalidValue | InvalidValueHelper.extract(Any a)
static InvalidValue | InvalidValueHelper.read(InputStream istream)

Methods in org.omg.DynamicAny.DynAnyPackage with parameters of type InvalidValue
static void | InvalidValueHelper.insert(Any a, InvalidValue that)
static void | InvalidValueHelper.write(OutputStream ostream, InvalidValue value)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.DynamicAny.DynAnyPackage.InvalidValueHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.DynamicAny.DynAnyPackage.InvalidValueHelper

No usage of org.omg.DynamicAny.DynAnyPackage.InvalidValueHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.DynamicAny.DynAnyPackage.TypeMismatch (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.DynamicAny.DynAnyPackage.TypeMismatch

Packages that use TypeMismatch
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.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.

Uses of TypeMismatch in org.omg.DynamicAny

Methods in org.omg.DynamicAny that throw TypeMismatch
void | DynValueBoxOperations.set_boxed_value(Any boxed) Replaces the boxed value with the specified value.
void | DynValueBoxOperations.set_boxed_value_as_dyn_any(DynAny boxed) Replaces the boxed value with the value contained in the parameter.
void | _DynSequenceStub.set_elements(Any[] value) Sets the elements of a sequence.
void | _DynSequenceStub.set_elements_as_dyn_any(DynAny[] value) Sets the elements of a sequence using DynAnys.
void | _DynSequenceStub.assign(DynAny dyn_any) Initializes the value associated with a DynAny object with the value associated with another DynAny object.
void | _DynSequenceStub.from_any(Any value) Initializes the value associated with a DynAny object with the value contained in an any.
void | _DynSequenceStub.insert_boolean(boolean value) Inserts a boolean value into the DynAny.
void | _DynSequenceStub.insert_octet(byte value) Inserts a byte value into the DynAny.
void | _DynSequenceStub.insert_char(char value) Inserts a char value into the DynAny.
void | _DynSequenceStub.insert_short(short value) Inserts a short value into the DynAny.
void | _DynSequenceStub.insert_ushort(short value) Inserts a short value into the DynAny.
void | _DynSequenceStub.insert_long(int value) Inserts an integer value into the DynAny.
void | _DynSequenceStub.insert_ulong(int value) Inserts an integer value into the DynAny.
void | _DynSequenceStub.insert_float(float value) Inserts a float value into the DynAny.
void | _DynSequenceStub.insert_double(double value) Inserts a double value into the DynAny.
void | _DynSequenceStub.insert_string(String value) Inserts a string value into the DynAny.
void | _DynSequenceStub.insert_reference(Object value) Inserts a reference to a CORBA object into the DynAny.
void | _DynSequenceStub.insert_typecode(TypeCode value) Inserts a TypeCode object into the DynAny.
void | _DynSequenceStub.insert_longlong(long value) Inserts a long value into the DynAny.
void | _DynSequenceStub.insert_ulonglong(long value) Inserts a long value into the DynAny.
void | _DynSequenceStub.insert_wchar(char value) Inserts a char value into the DynAny.
void | _DynSequenceStub.insert_wstring(String value) Inserts a string value into the DynAny.
void | _DynSequenceStub.insert_any(Any value) Inserts an Any value into the Any represented by this DynAny.
void | _DynSequenceStub.insert_dyn_any(DynAny value) Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.
void | _DynSequenceStub.insert_val(Serializable value) Inserts a reference to a Serializable object into this DynAny.
boolean | _DynSequenceStub.get_boolean() Extracts the boolean value from this DynAny.
byte | _DynSequenceStub.get_octet() Extracts the byte value from this DynAny.
char | _DynSequenceStub.get_char() Extracts the char value from this DynAny.
short | _DynSequenceStub.get_short() Extracts the short value from this DynAny.
short | _DynSequenceStub.get_ushort() Extracts the short value from this DynAny.
int | _DynSequenceStub.get_long() Extracts the integer value from this DynAny.
int | _DynSequenceStub.get_ulong() Extracts the integer value from this DynAny.
float | _DynSequenceStub.get_float() Extracts the float value from this DynAny.
double | _DynSequenceStub.get_double() Extracts the double value from this DynAny.
String | _DynSequenceStub.get_string() Extracts the string value from this DynAny.
Object | _DynSequenceStub.get_reference() Extracts the reference to a CORBA Object from this DynAny.
TypeCode | _DynSequenceStub.get_typecode() Extracts the TypeCode object from this DynAny.
long | _DynSequenceStub.get_longlong() Extracts the long value from this DynAny.
long | _DynSequenceStub.get_ulonglong() Extracts the long value from this DynAny.
char | _DynSequenceStub.get_wchar() Extracts the long value from this DynAny.
String | _DynSequenceStub.get_wstring() Extracts the string value from this DynAny.
Any | _DynSequenceStub.get_any() Extracts an Any value contained in the Any represented by this DynAny.
DynAny | _DynSequenceStub.get_dyn_any() Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.
Serializable | _DynSequenceStub.get_val() Extracts a Serializable object from this DynAny.
DynAny | _DynSequenceStub.current_component() Returns the DynAny for the component at the current position.
boolean | _DynFixedStub.set_value(String val) Sets the value of the DynFixed.
void | _DynFixedStub.assign(DynAny dyn_any) Initializes the value associated with a DynAny object with the value associated with another DynAny object.
void | _DynFixedStub.from_any(Any value) Initializes the value associated with a DynAny object with the value contained in an any.
void | _DynFixedStub.insert_boolean(boolean value) Inserts a boolean value into the DynAny.
void | _DynFixedStub.insert_octet(byte value) Inserts a byte value into the DynAny.
void | _DynFixedStub.insert_char(char value) Inserts a char value into the DynAny.
void | _DynFixedStub.insert_short(short value) Inserts a short value into the DynAny.
void | _DynFixedStub.insert_ushort(short value) Inserts a short value into the DynAny.
void | _DynFixedStub.insert_long(int value) Inserts an integer value into the DynAny.
void | _DynFixedStub.insert_ulong(int value) Inserts an integer value into the DynAny.
void | _DynFixedStub.insert_float(float value) Inserts a float value into the DynAny.
void | _DynFixedStub.insert_double(double value) Inserts a double value into the DynAny.
void | _DynFixedStub.insert_string(String value) Inserts a string value into the DynAny.
void | _DynFixedStub.insert_reference(Object value) Inserts a reference to a CORBA object into the DynAny.
void | _DynFixedStub.insert_typecode(TypeCode value) Inserts a TypeCode object into the DynAny.
void | _DynFixedStub.insert_longlong(long value) Inserts a long value into the DynAny.
void | _DynFixedStub.insert_ulonglong(long value) Inserts a long value into the DynAny.
void | _DynFixedStub.insert_wchar(char value) Inserts a char value into the DynAny.
void | _DynFixedStub.insert_wstring(String value) Inserts a string value into the DynAny.
void | _DynFixedStub.insert_any(Any value) Inserts an Any value into the Any represented by this DynAny.
void | _DynFixedStub.insert_dyn_any(DynAny value) Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.
void | _DynFixedStub.insert_val(Serializable value) Inserts a reference to a Serializable object into this DynAny.
boolean | _DynFixedStub.get_boolean() Extracts the boolean value from this DynAny.
byte | _DynFixedStub.get_octet() Extracts the byte value from this DynAny.
char | _DynFixedStub.get_char() Extracts the char value from this DynAny.
short | _DynFixedStub.get_short() Extracts the short value from this DynAny.
short | _DynFixedStub.get_ushort() Extracts the short value from this DynAny.
int | _DynFixedStub.get_long() Extracts the integer value from this DynAny.
int | _DynFixedStub.get_ulong() Extracts the integer value from this DynAny.
float | _DynFixedStub.get_float() Extracts the float value from this DynAny.
double | _DynFixedStub.get_double() Extracts the double value from this DynAny.
String | _DynFixedStub.get_string() Extracts the string value from this DynAny.
Object | _DynFixedStub.get_reference() Extracts the reference to a CORBA Object from this DynAny.
TypeCode | _DynFixedStub.get_typecode() Extracts the TypeCode object from this DynAny.
long | _DynFixedStub.get_longlong() Extracts the long value from this DynAny.
long | _DynFixedStub.get_ulonglong() Extracts the long value from this DynAny.
char | _DynFixedStub.get_wchar() Extracts the long value from this DynAny.
String | _DynFixedStub.get_wstring() Extracts the string value from this DynAny.
Any | _DynFixedStub.get_any() Extracts an Any value contained in the Any represented by this DynAny.
DynAny | _DynFixedStub.get_dyn_any() Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.
Serializable | _DynFixedStub.get_val() Extracts a Serializable object from this DynAny.
DynAny | _DynFixedStub.current_component() Returns the DynAny for the component at the current position.
void | _DynEnumStub.assign(DynAny dyn_any) Initializes the value associated with a DynAny object with the value associated with another DynAny object.
void | _DynEnumStub.from_any(Any value) Initializes the value associated with a DynAny object with the value contained in an any.
void | _DynEnumStub.insert_boolean(boolean value) Inserts a boolean value into the DynAny.
void | _DynEnumStub.insert_octet(byte value) Inserts a byte value into the DynAny.
void | _DynEnumStub.insert_char(char value) Inserts a char value into the DynAny.
void | _DynEnumStub.insert_short(short value) Inserts a short value into the DynAny.
void | _DynEnumStub.insert_ushort(short value) Inserts a short value into the DynAny.
void | _DynEnumStub.insert_long(int value) Inserts an integer value into the DynAny.
void | _DynEnumStub.insert_ulong(int value) Inserts an integer value into the DynAny.
void | _DynEnumStub.insert_float(float value) Inserts a float value into the DynAny.
void | _DynEnumStub.insert_double(double value) Inserts a double value into the DynAny.
void | _DynEnumStub.insert_string(String value) Inserts a string value into the DynAny.
void | _DynEnumStub.insert_reference(Object value) Inserts a reference to a CORBA object into the DynAny.
void | _DynEnumStub.insert_typecode(TypeCode value) Inserts a TypeCode object into the DynAny.
void | _DynEnumStub.insert_longlong(long value) Inserts a long value into the DynAny.
void | _DynEnumStub.insert_ulonglong(long value) Inserts a long value into the DynAny.
void | _DynEnumStub.insert_wchar(char value) Inserts a char value into the DynAny.
void | _DynEnumStub.insert_wstring(String value) Inserts a string value into the DynAny.
void | _DynEnumStub.insert_any(Any value) Inserts an Any value into the Any represented by this DynAny.
void | _DynEnumStub.insert_dyn_any(DynAny value) Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.
void | _DynEnumStub.insert_val(Serializable value) Inserts a reference to a Serializable object into this DynAny.
boolean | _DynEnumStub.get_boolean() Extracts the boolean value from this DynAny.
byte | _DynEnumStub.get_octet() Extracts the byte value from this DynAny.
char | _DynEnumStub.get_char() Extracts the char value from this DynAny.
short | _DynEnumStub.get_short() Extracts the short value from this DynAny.
short | _DynEnumStub.get_ushort() Extracts the short value from this DynAny.
int | _DynEnumStub.get_long() Extracts the integer value from this DynAny.
int | _DynEnumStub.get_ulong() Extracts the integer value from this DynAny.
float | _DynEnumStub.get_float() Extracts the float value from this DynAny.
double | _DynEnumStub.get_double() Extracts the double value from this DynAny.
String | _DynEnumStub.get_string() Extracts the string value from this DynAny.
Object | _DynEnumStub.get_reference() Extracts the reference to a CORBA Object from this DynAny.
TypeCode | _DynEnumStub.get_typecode() Extracts the TypeCode object from this DynAny.
long | _DynEnumStub.get_longlong() Extracts the long value from this DynAny.
long | _DynEnumStub.get_ulonglong() Extracts the long value from this DynAny.
char | _DynEnumStub.get_wchar() Extracts the long value from this DynAny.
String | _DynEnumStub.get_wstring() Extracts the string value from this DynAny.
Any | _DynEnumStub.get_any() Extracts an Any value contained in the Any represented by this DynAny.
DynAny | _DynEnumStub.get_dyn_any() Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.
Serializable | _DynEnumStub.get_val() Extracts a Serializable object from this DynAny.
DynAny | _DynEnumStub.current_component() Returns the DynAny for the component at the current position.
void | _DynArrayStub.set_elements(Any[] value) Sets the DynArray to contain the passed elements.
void | _DynArrayStub.set_elements_as_dyn_any(DynAny[] value) Sets the DynArray to contain the passed elements.
void | _DynArrayStub.assign(DynAny dyn_any) Initializes the value associated with a DynAny object with the value associated with another DynAny object.
void | _DynArrayStub.from_any(Any value) Initializes the value associated with a DynAny object with the value contained in an any.
void | _DynArrayStub.insert_boolean(boolean value) Inserts a boolean value into the DynAny.
void | _DynArrayStub.insert_octet(byte value) Inserts a byte value into the DynAny.
void | _DynArrayStub.insert_char(char value) Inserts a char value into the DynAny.
void | _DynArrayStub.insert_short(short value) Inserts a short value into the DynAny.
void | _DynArrayStub.insert_ushort(short value) Inserts a short value into the DynAny.
void | _DynArrayStub.insert_long(int value) Inserts an integer value into the DynAny.
void | _DynArrayStub.insert_ulong(int value) Inserts an integer value into the DynAny.
void | _DynArrayStub.insert_float(float value) Inserts a float value into the DynAny.
void | _DynArrayStub.insert_double(double value) Inserts a double value into the DynAny.
void | _DynArrayStub.insert_string(String value) Inserts a string value into the DynAny.
void | _DynArrayStub.insert_reference(Object value) Inserts a reference to a CORBA object into the DynAny.
void | _DynArrayStub.insert_typecode(TypeCode value) Inserts a TypeCode object into the DynAny.
void | _DynArrayStub.insert_longlong(long value) Inserts a long value into the DynAny.
void | _DynArrayStub.insert_ulonglong(long value) Inserts a long value into the DynAny.
void | _DynArrayStub.insert_wchar(char value) Inserts a char value into the DynAny.
void | _DynArrayStub.insert_wstring(String value) Inserts a string value into the DynAny.
void | _DynArrayStub.insert_any(Any value) Inserts an Any value into the Any represented by this DynAny.
void | _DynArrayStub.insert_dyn_any(DynAny value) Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.
void | _DynArrayStub.insert_val(Serializable value) Inserts a reference to a Serializable object into this DynAny.
boolean | _DynArrayStub.get_boolean() Extracts the boolean value from this DynAny.
byte | _DynArrayStub.get_octet() Extracts the byte value from this DynAny.
char | _DynArrayStub.get_char() Extracts the char value from this DynAny.
short | _DynArrayStub.get_short() Extracts the short value from this DynAny.
short | _DynArrayStub.get_ushort() Extracts the short value from this DynAny.
int | _DynArrayStub.get_long() Extracts the integer value from this DynAny.
int | _DynArrayStub.get_ulong() Extracts the integer value from this DynAny.
float | _DynArrayStub.get_float() Extracts the float value from this DynAny.
double | _DynArrayStub.get_double() Extracts the double value from this DynAny.
String | _DynArrayStub.get_string() Extracts the string value from this DynAny.
Object | _DynArrayStub.get_reference() Extracts the reference to a CORBA Object from this DynAny.
TypeCode | _DynArrayStub.get_typecode() Extracts the TypeCode object from this DynAny.
long | _DynArrayStub.get_longlong() Extracts the long value from this DynAny.
long | _DynArrayStub.get_ulonglong() Extracts the long value from this DynAny.
char | _DynArrayStub.get_wchar() Extracts the long value from this DynAny.
String | _DynArrayStub.get_wstring() Extracts the string value from this DynAny.
Any | _DynArrayStub.get_any() Extracts an Any value contained in the Any represented by this DynAny.
DynAny | _DynArrayStub.get_dyn_any() Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.
Serializable | _DynArrayStub.get_val() Extracts a Serializable object from this DynAny.
DynAny | _DynArrayStub.current_component() Returns the DynAny for the component at the current position.
String | _DynValueStub.current_member_name() Returns the name of the member at the current position.
TCKind | _DynValueStub.current_member_kind() Returns the TCKind associated with the member at the current position.
void | _DynValueStub.set_members(NameValuePair[] value) Initializes the value type's members from a sequence of NameValuePairs.
void | _DynValueStub.set_members_as_dyn_any(NameDynAnyPair[] value) Initializes the value type's members from a sequence of NameDynAnyPairs.
void | _DynValueStub.assign(DynAny dyn_any) Initializes the value associated with a DynAny object with the value associated with another DynAny object.
void | _DynValueStub.from_any(Any value) Initializes the value associated with a DynAny object with the value contained in an any.
void | _DynValueStub.insert_boolean(boolean value) Inserts a boolean value into the DynAny.
void | _DynValueStub.insert_octet(byte value) Inserts a byte value into the DynAny.
void | _DynValueStub.insert_char(char value) Inserts a char value into the DynAny.
void | _DynValueStub.insert_short(short value) Inserts a short value into the DynAny.
void | _DynValueStub.insert_ushort(short value) Inserts a short value into the DynAny.
void | _DynValueStub.insert_long(int value) Inserts an integer value into the DynAny.
void | _DynValueStub.insert_ulong(int value) Inserts an integer value into the DynAny.
void | _DynValueStub.insert_float(float value) Inserts a float value into the DynAny.
void | _DynValueStub.insert_double(double value) Inserts a double value into the DynAny.
void | _DynValueStub.insert_string(String value) Inserts a string value into the DynAny.
void | _DynValueStub.insert_reference(Object value) Inserts a reference to a CORBA object into the DynAny.
void | _DynValueStub.insert_typecode(TypeCode value) Inserts a TypeCode object into the DynAny.
void | _DynValueStub.insert_longlong(long value) Inserts a long value into the DynAny.
void | _DynValueStub.insert_ulonglong(long value) Inserts a long value into the DynAny.
void | _DynValueStub.insert_wchar(char value) Inserts a char value into the DynAny.
void | _DynValueStub.insert_wstring(String value) Inserts a string value into the DynAny.
void | _DynValueStub.insert_any(Any value) Inserts an Any value into the Any represented by this DynAny.
void | _DynValueStub.insert_dyn_any(DynAny value) Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.
void | _DynValueStub.insert_val(Serializable value) Inserts a reference to a Serializable object into this DynAny.
boolean | _DynValueStub.get_boolean() Extracts the boolean value from this DynAny.
byte | _DynValueStub.get_octet() Extracts the byte value from this DynAny.
char | _DynValueStub.get_char() Extracts the char value from this DynAny.
short | _DynValueStub.get_short() Extracts the short value from this DynAny.
short | _DynValueStub.get_ushort() Extracts the short value from this DynAny.
int | _DynValueStub.get_long() Extracts the integer value from this DynAny.
int | _DynValueStub.get_ulong() Extracts the integer value from this DynAny.
float | _DynValueStub.get_float() Extracts the float value from this DynAny.
double | _DynValueStub.get_double() Extracts the double value from this DynAny.
String | _DynValueStub.get_string() Extracts the string value from this DynAny.
Object | _DynValueStub.get_reference() Extracts the reference to a CORBA Object from this DynAny.
TypeCode | _DynValueStub.get_typecode() Extracts the TypeCode object from this DynAny.
long | _DynValueStub.get_longlong() Extracts the long value from this DynAny.
long | _DynValueStub.get_ulonglong() Extracts the long value from this DynAny.
char | _DynValueStub.get_wchar() Extracts the long value from this DynAny.
String | _DynValueStub.get_wstring() Extracts the string value from this DynAny.
Any | _DynValueStub.get_any() Extracts an Any value contained in the Any represented by this DynAny.
DynAny | _DynValueStub.get_dyn_any() Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.
Serializable | _DynValueStub.get_val() Extracts a Serializable object from this DynAny.
DynAny | _DynValueStub.current_component() Returns the DynAny for the component at the current position.
void | _DynAnyStub.assign(DynAny dyn_any) Initializes the value associated with a DynAny object with the value associated with another DynAny object.
void | _DynAnyStub.from_any(Any value) Initializes the value associated with a DynAny object with the value contained in an any.
void | _DynAnyStub.insert_boolean(boolean value) Inserts a boolean value into the DynAny.
void | _DynAnyStub.insert_octet(byte value) Inserts a byte value into the DynAny.
void | _DynAnyStub.insert_char(char value) Inserts a char value into the DynAny.
void | _DynAnyStub.insert_short(short value) Inserts a short value into the DynAny.
void | _DynAnyStub.insert_ushort(short value) Inserts a short value into the DynAny.
void | _DynAnyStub.insert_long(int value) Inserts an integer value into the DynAny.
void | _DynAnyStub.insert_ulong(int value) Inserts an integer value into the DynAny.
void | _DynAnyStub.insert_float(float value) Inserts a float value into the DynAny.
void | _DynAnyStub.insert_double(double value) Inserts a double value into the DynAny.
void | _DynAnyStub.insert_string(String value) Inserts a string value into the DynAny.
void | _DynAnyStub.insert_reference(Object value) Inserts a reference to a CORBA object into the DynAny.
void | _DynAnyStub.insert_typecode(TypeCode value) Inserts a TypeCode object into the DynAny.
void | _DynAnyStub.insert_longlong(long value) Inserts a long value into the DynAny.
void | _DynAnyStub.insert_ulonglong(long value) Inserts a long value into the DynAny.
void | _DynAnyStub.insert_wchar(char value) Inserts a char value into the DynAny.
void | _DynAnyStub.insert_wstring(String value) Inserts a string value into the DynAny.
void | _DynAnyStub.insert_any(Any value) Inserts an Any value into the Any represented by this DynAny.
void | _DynAnyStub.insert_dyn_any(DynAny value) Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.
void | _DynAnyStub.insert_val(Serializable value) Inserts a reference to a Serializable object into this DynAny.
boolean | _DynAnyStub.get_boolean() Extracts the boolean value from this DynAny.
byte | _DynAnyStub.get_octet() Extracts the byte value from this DynAny.
char | _DynAnyStub.get_char() Extracts the char value from this DynAny.
short | _DynAnyStub.get_short() Extracts the short value from this DynAny.
short | _DynAnyStub.get_ushort() Extracts the short value from this DynAny.
int | _DynAnyStub.get_long() Extracts the integer value from this DynAny.
int | _DynAnyStub.get_ulong() Extracts the integer value from this DynAny.
float | _DynAnyStub.get_float() Extracts the float value from this DynAny.
double | _DynAnyStub.get_double() Extracts the double value from this DynAny.
String | _DynAnyStub.get_string() Extracts the string value from this DynAny.
Object | _DynAnyStub.get_reference() Extracts the reference to a CORBA Object from this DynAny.
TypeCode | _DynAnyStub.get_typecode() Extracts the TypeCode object from this DynAny.
long | _DynAnyStub.get_longlong() Extracts the long value from this DynAny.
long | _DynAnyStub.get_ulonglong() Extracts the long value from this DynAny.
char | _DynAnyStub.get_wchar() Extracts the long value from this DynAny.
String | _DynAnyStub.get_wstring() Extracts the string value from this DynAny.
Any | _DynAnyStub.get_any() Extracts an Any value contained in the Any represented by this DynAny.
DynAny | _DynAnyStub.get_dyn_any() Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.
Serializable | _DynAnyStub.get_val() Extracts a Serializable object from this DynAny.
DynAny | _DynAnyStub.current_component() Returns the DynAny for the component at the current position.
void | _DynUnionStub.set_discriminator(DynAny d) Sets the discriminator of the DynUnion to the specified value.
void | _DynUnionStub.set_to_default_member() Sets the discriminator to a value that is consistent with the value of the default case of a union.
void | _DynUnionStub.set_to_no_active_member() Sets the discriminator to a value that does not correspond to any of the unions case labels.
void | _DynUnionStub.assign(DynAny dyn_any) Initializes the value associated with a DynAny object with the value associated with another DynAny object.
void | _DynUnionStub.from_any(Any value) Initializes the value associated with a DynAny object with the value contained in an any.
void | _DynUnionStub.insert_boolean(boolean value) Inserts a boolean value into the DynAny.
void | _DynUnionStub.insert_octet(byte value) Inserts a byte value into the DynAny.
void | _DynUnionStub.insert_char(char value) Inserts a char value into the DynAny.
void | _DynUnionStub.insert_short(short value) Inserts a short value into the DynAny.
void | _DynUnionStub.insert_ushort(short value) Inserts a short value into the DynAny.
void | _DynUnionStub.insert_long(int value) Inserts an integer value into the DynAny.
void | _DynUnionStub.insert_ulong(int value) Inserts an integer value into the DynAny.
void | _DynUnionStub.insert_float(float value) Inserts a float value into the DynAny.
void | _DynUnionStub.insert_double(double value) Inserts a double value into the DynAny.
void | _DynUnionStub.insert_string(String value) Inserts a string value into the DynAny.
void | _DynUnionStub.insert_reference(Object value) Inserts a reference to a CORBA object into the DynAny.
void | _DynUnionStub.insert_typecode(TypeCode value) Inserts a TypeCode object into the DynAny.
void | _DynUnionStub.insert_longlong(long value) Inserts a long value into the DynAny.
void | _DynUnionStub.insert_ulonglong(long value) Inserts a long value into the DynAny.
void | _DynUnionStub.insert_wchar(char value) Inserts a char value into the DynAny.
void | _DynUnionStub.insert_wstring(String value) Inserts a string value into the DynAny.
void | _DynUnionStub.insert_any(Any value) Inserts an Any value into the Any represented by this DynAny.
void | _DynUnionStub.insert_dyn_any(DynAny value) Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.
void | _DynUnionStub.insert_val(Serializable value) Inserts a reference to a Serializable object into this DynAny.
boolean | _DynUnionStub.get_boolean() Extracts the boolean value from this DynAny.
byte | _DynUnionStub.get_octet() Extracts the byte value from this DynAny.
char | _DynUnionStub.get_char() Extracts the char value from this DynAny.
short | _DynUnionStub.get_short() Extracts the short value from this DynAny.
short | _DynUnionStub.get_ushort() Extracts the short value from this DynAny.
int | _DynUnionStub.get_long() Extracts the integer value from this DynAny.
int | _DynUnionStub.get_ulong() Extracts the integer value from this DynAny.
float | _DynUnionStub.get_float() Extracts the float value from this DynAny.
double | _DynUnionStub.get_double() Extracts the double value from this DynAny.
String | _DynUnionStub.get_string() Extracts the string value from this DynAny.
Object | _DynUnionStub.get_reference() Extracts the reference to a CORBA Object from this DynAny.
TypeCode | _DynUnionStub.get_typecode() Extracts the TypeCode object from this DynAny.
long | _DynUnionStub.get_longlong() Extracts the long value from this DynAny.
long | _DynUnionStub.get_ulonglong() Extracts the long value from this DynAny.
char | _DynUnionStub.get_wchar() Extracts the long value from this DynAny.
String | _DynUnionStub.get_wstring() Extracts the string value from this DynAny.
Any | _DynUnionStub.get_any() Extracts an Any value contained in the Any represented by this DynAny.
DynAny | _DynUnionStub.get_dyn_any() Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.
Serializable | _DynUnionStub.get_val() Extracts a Serializable object from this DynAny.
DynAny | _DynUnionStub.current_component() Returns the DynAny for the component at the current position.
String | _DynStructStub.current_member_name() Returns the name of the member at the current position.
TCKind | _DynStructStub.current_member_kind() Returns the TCKind associated with the member at the current position.
void | _DynStructStub.set_members(NameValuePair[] value) Initializes the struct data value associated with a DynStruct object from a sequence of NameValuePairs.
void | _DynStructStub.set_members_as_dyn_any(NameDynAnyPair[] value) Initializes the struct data value associated with a DynStruct object from a sequence of NameDynAnyPairs.
void | _DynStructStub.assign(DynAny dyn_any) Initializes the value associated with a DynAny object with the value associated with another DynAny object.
void | _DynStructStub.from_any(Any value) Initializes the value associated with a DynAny object with the value contained in an any.
void | _DynStructStub.insert_boolean(boolean value) Inserts a boolean value into the DynAny.
void | _DynStructStub.insert_octet(byte value) Inserts a byte value into the DynAny.
void | _DynStructStub.insert_char(char value) Inserts a char value into the DynAny.
void | _DynStructStub.insert_short(short value) Inserts a short value into the DynAny.
void | _DynStructStub.insert_ushort(short value) Inserts a short value into the DynAny.
void | _DynStructStub.insert_long(int value) Inserts an integer value into the DynAny.
void | _DynStructStub.insert_ulong(int value) Inserts an integer value into the DynAny.
void | _DynStructStub.insert_float(float value) Inserts a float value into the DynAny.
void | _DynStructStub.insert_double(double value) Inserts a double value into the DynAny.
void | _DynStructStub.insert_string(String value) Inserts a string value into the DynAny.
void | _DynStructStub.insert_reference(Object value) Inserts a reference to a CORBA object into the DynAny.
void | _DynStructStub.insert_typecode(TypeCode value) Inserts a TypeCode object into the DynAny.
void | _DynStructStub.insert_longlong(long value) Inserts a long value into the DynAny.
void | _DynStructStub.insert_ulonglong(long value) Inserts a long value into the DynAny.
void | _DynStructStub.insert_wchar(char value) Inserts a char value into the DynAny.
void | _DynStructStub.insert_wstring(String value) Inserts a string value into the DynAny.
void | _DynStructStub.insert_any(Any value) Inserts an Any value into the Any represented by this DynAny.
void | _DynStructStub.insert_dyn_any(DynAny value) Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.
void | _DynStructStub.insert_val(Serializable value) Inserts a reference to a Serializable object into this DynAny.
boolean | _DynStructStub.get_boolean() Extracts the boolean value from this DynAny.
byte | _DynStructStub.get_octet() Extracts the byte value from this DynAny.
char | _DynStructStub.get_char() Extracts the char value from this DynAny.
short | _DynStructStub.get_short() Extracts the short value from this DynAny.
short | _DynStructStub.get_ushort() Extracts the short value from this DynAny.
int | _DynStructStub.get_long() Extracts the integer value from this DynAny.
int | _DynStructStub.get_ulong() Extracts the integer value from this DynAny.
float | _DynStructStub.get_float() Extracts the float value from this DynAny.
double | _DynStructStub.get_double() Extracts the double value from this DynAny.
String | _DynStructStub.get_string() Extracts the string value from this DynAny.
Object | _DynStructStub.get_reference() Extracts the reference to a CORBA Object from this DynAny.
TypeCode | _DynStructStub.get_typecode() Extracts the TypeCode object from this DynAny.
long | _DynStructStub.get_longlong() Extracts the long value from this DynAny.
long | _DynStructStub.get_ulonglong() Extracts the long value from this DynAny.
char | _DynStructStub.get_wchar() Extracts the long value from this DynAny.
String | _DynStructStub.get_wstring() Extracts the string value from this DynAny.
Any | _DynStructStub.get_any() Extracts an Any value contained in the Any represented by this DynAny.
DynAny | _DynStructStub.get_dyn_any() Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.
Serializable | _DynStructStub.get_val() Extracts a Serializable object from this DynAny.
DynAny | _DynStructStub.current_component() Returns the DynAny for the component at the current position.
String | DynValueOperations.current_member_name() Returns the name of the member at the current position.
TCKind | DynValueOperations.current_member_kind() Returns the TCKind associated with the member at the current position.
void | DynValueOperations.set_members(NameValuePair[] value) Initializes the value type's members from a sequence of NameValuePairs.
void | DynValueOperations.set_members_as_dyn_any(NameDynAnyPair[] value) Initializes the value type's members from a sequence of NameDynAnyPairs.
void | DynUnionOperations.set_discriminator(DynAny d) Sets the discriminator of the DynUnion to the specified value.
void | DynUnionOperations.set_to_default_member() Sets the discriminator to a value that is consistent with the value of the default case of a union.
void | DynUnionOperations.set_to_no_active_member() Sets the discriminator to a value that does not correspond to any of the unions case labels.
String | DynStructOperations.current_member_name() Returns the name of the member at the current position.
TCKind | DynStructOperations.current_member_kind() Returns the TCKind associated with the member at the current position.
void | DynStructOperations.set_members(NameValuePair[] value) Initializes the struct data value associated with a DynStruct object from a sequence of NameValuePairs.
void | DynStructOperations.set_members_as_dyn_any(NameDynAnyPair[] value) Initializes the struct data value associated with a DynStruct object from a sequence of NameDynAnyPairs.
void | DynSequenceOperations.set_elements(Any[] value) Sets the elements of a sequence.
void | DynSequenceOperations.set_elements_as_dyn_any(DynAny[] value) Sets the elements of a sequence using DynAnys.
boolean | DynFixedOperations.set_value(String val) Sets the value of the DynFixed.
void | DynArrayOperations.set_elements(Any[] value) Sets the DynArray to contain the passed elements.
void | DynArrayOperations.set_elements_as_dyn_any(DynAny[] value) Sets the DynArray to contain the passed elements.
void | DynAnyOperations.assign(DynAny dyn_any) Initializes the value associated with a DynAny object with the value associated with another DynAny object.
void | DynAnyOperations.from_any(Any value) Initializes the value associated with a DynAny object with the value contained in an any.
void | DynAnyOperations.insert_boolean(boolean value) Inserts a boolean value into the DynAny.
void | DynAnyOperations.insert_octet(byte value) Inserts a byte value into the DynAny.
void | DynAnyOperations.insert_char(char value) Inserts a char value into the DynAny.
void | DynAnyOperations.insert_short(short value) Inserts a short value into the DynAny.
void | DynAnyOperations.insert_ushort(short value) Inserts a short value into the DynAny.
void | DynAnyOperations.insert_long(int value) Inserts an integer value into the DynAny.
void | DynAnyOperations.insert_ulong(int value) Inserts an integer value into the DynAny.
void | DynAnyOperations.insert_float(float value) Inserts a float value into the DynAny.
void | DynAnyOperations.insert_double(double value) Inserts a double value into the DynAny.
void | DynAnyOperations.insert_string(String value) Inserts a string value into the DynAny.
void | DynAnyOperations.insert_reference(Object value) Inserts a reference to a CORBA object into the DynAny.
void | DynAnyOperations.insert_typecode(TypeCode value) Inserts a TypeCode object into the DynAny.
void | DynAnyOperations.insert_longlong(long value) Inserts a long value into the DynAny.
void | DynAnyOperations.insert_ulonglong(long value) Inserts a long value into the DynAny.
void | DynAnyOperations.insert_wchar(char value) Inserts a char value into the DynAny.
void | DynAnyOperations.insert_wstring(String value) Inserts a string value into the DynAny.
void | DynAnyOperations.insert_any(Any value) Inserts an Any value into the Any represented by this DynAny.
void | DynAnyOperations.insert_dyn_any(DynAny value) Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.
void | DynAnyOperations.insert_val(Serializable value) Inserts a reference to a Serializable object into this DynAny.
boolean | DynAnyOperations.get_boolean() Extracts the boolean value from this DynAny.
byte | DynAnyOperations.get_octet() Extracts the byte value from this DynAny.
char | DynAnyOperations.get_char() Extracts the char value from this DynAny.
short | DynAnyOperations.get_short() Extracts the short value from this DynAny.
short | DynAnyOperations.get_ushort() Extracts the short value from this DynAny.
int | DynAnyOperations.get_long() Extracts the integer value from this DynAny.
int | DynAnyOperations.get_ulong() Extracts the integer value from this DynAny.
float | DynAnyOperations.get_float() Extracts the float value from this DynAny.
double | DynAnyOperations.get_double() Extracts the double value from this DynAny.
String | DynAnyOperations.get_string() Extracts the string value from this DynAny.
Object | DynAnyOperations.get_reference() Extracts the reference to a CORBA Object from this DynAny.
TypeCode | DynAnyOperations.get_typecode() Extracts the TypeCode object from this DynAny.
long | DynAnyOperations.get_longlong() Extracts the long value from this DynAny.
long | DynAnyOperations.get_ulonglong() Extracts the long value from this DynAny.
char | DynAnyOperations.get_wchar() Extracts the long value from this DynAny.
String | DynAnyOperations.get_wstring() Extracts the string value from this DynAny.
Any | DynAnyOperations.get_any() Extracts an Any value contained in the Any represented by this DynAny.
DynAny | DynAnyOperations.get_dyn_any() Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped into a new DynAny.
Serializable | DynAnyOperations.get_val() Extracts a Serializable object from this DynAny.
DynAny | DynAnyOperations.current_component() Returns the DynAny for the component at the current position.

Uses of TypeMismatch in org.omg.DynamicAny.DynAnyPackage

Methods in org.omg.DynamicAny.DynAnyPackage that return TypeMismatch
static TypeMismatch | TypeMismatchHelper.extract(Any a)
static TypeMismatch | TypeMismatchHelper.read(InputStream istream)

Methods in org.omg.DynamicAny.DynAnyPackage with parameters of type TypeMismatch
static void | TypeMismatchHelper.insert(Any a, TypeMismatch that)
static void | TypeMismatchHelper.write(OutputStream ostream, TypeMismatch value)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.DynamicAny.DynAnyPackage.TypeMismatchHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.DynamicAny.DynAnyPackage.TypeMismatchHelper

No usage of org.omg.DynamicAny.DynAnyPackage.TypeMismatchHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Codec (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP
Interface Codec

All Superinterfaces:
CodecOperations, IDLEntity, Object, Serializable
public interface Codec
extends CodecOperations, Object, IDLEntity

The formats of IOR components and service context data used by ORB services are often defined as CDR encapsulations encoding instances of IDL defined data types. The Codec provides a mechanism to transfer these components between their IDL data types and their CDR encapsulation representations.

A Codec is obtained from the CodecFactory. The CodecFactory is obtained through a call to ORB.resolve_initial_references( "CodecFactory" ).

Methods inherited from interface org.omg.IOP.CodecOperations
decode_value, decode, encode_value, encode
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


CodecFactory (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP
Interface CodecFactory

All Superinterfaces:
CodecFactoryOperations, IDLEntity, Object, Serializable
public interface CodecFactory
extends CodecFactoryOperations, Object, IDLEntity

Codecs are obtained from the CodecFactory. The CodecFactory is obtained through a call to ORB.resolve_initial_references( "CodecFactory" ).

Methods inherited from interface org.omg.IOP.CodecFactoryOperations
create_codec
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


CodecFactoryHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP
Class CodecFactoryHelper

java.lang.Object
    extended by org.omg.IOP.CodecFactoryHelper
public abstract class CodecFactoryHelper
extends Object

Codecs are obtained from the CodecFactory. The CodecFactory is obtained through a call to ORB.resolve_initial_references( "CodecFactory" ).

Constructor Summary
CodecFactoryHelper()
Method Summary
static CodecFactory | extract(Any a)
static String | id()
static void | insert(Any a, CodecFactory that)
static CodecFactory | narrow(Object obj)
static CodecFactory | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, CodecFactory value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

CodecFactoryHelper

public CodecFactoryHelper()
Method Detail

insert

public static void insert(Any a,
                          CodecFactory that)

extract

public static CodecFactory extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static CodecFactory read(InputStream istream)

write

public static void write(OutputStream ostream,
                         CodecFactory value)

narrow

public static CodecFactory narrow(Object obj)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


CodecFactoryOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP
Interface CodecFactoryOperations

All Known Subinterfaces:
CodecFactory
public interface CodecFactoryOperations

Codecs are obtained from the CodecFactory. The CodecFactory is obtained through a call to ORB.resolve_initial_references( "CodecFactory" ).

Method Summary
 Codec create_codec(Encoding enc)
Create a Codec of the given encoding.

Method Detail

create_codec

public Codec create_codec(Encoding enc)
                   throws UnknownEncoding
Create a Codec of the given encoding.

Parameters:
enc - The encoding for which to create a Codec.
Returns:
A Codec obtained with the given encoding.
Throws:
UnknownEncoding - thrown if this factory cannot create a Codec of the given encoding.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


CodecOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP
Interface CodecOperations

All Known Subinterfaces:
Codec
public interface CodecOperations

The formats of IOR components and service context data used by ORB services are often defined as CDR encapsulations encoding instances of IDL defined data types. The Codec provides a mechanism to transfer these components between their IDL data types and their CDR encapsulation representations.

A Codec is obtained from the CodecFactory. The CodecFactory is obtained through a call to ORB.resolve_initial_references( "CodecFactory" ).

Method Summary
Any | decode_value(byte[] data, TypeCode tc) Decodes the given byte array into an Any based on the given TypeCode and the encoding format effective for this Codec.
Any | decode(byte[] data) Decodes the given byte array into an Any based on the encoding format effective for this Codec.
byte[] | encode_value(Any data) Converts the given any into a byte array based on the encoding format effective for this Codec.
byte[] | encode(Any data) Converts the given any into a byte array based on the encoding format effective for this Codec.

Method Detail

encode

public byte[] encode(Any data)
              throws InvalidTypeForEncoding
Converts the given any into a byte array based on the encoding format effective for this Codec.

Parameters:
data - The data, in the form of an any, to be encoded into a byte array.
Returns:
A byte array containing the encoded Any. This byte array contains both the TypeCode and the data of the type.
Throws:
InvalidTypeForEncoding - thrown if the type is not valid for the encoding format effective for this Codec.

decode

public Any decode(byte[] data)
           throws FormatMismatch
Decodes the given byte array into an Any based on the encoding format effective for this Codec.

Parameters:
data - The data, in the form of a byte array, to be decoded into an Any.
Returns:
An Any containing the data from the decoded byte array.
Throws:
FormatMismatch - is thrown if the byte array cannot be decoded into an Any.

encode_value

public byte[] encode_value(Any data)
                    throws InvalidTypeForEncoding
Converts the given any into a byte array based on the encoding format effective for this Codec. Only the data from the Any is encoded, not the TypeCode.

Parameters:
data - The data, in the form of an Any, to be encoded into a byte array.
Returns:
A byte array containing the data from the encoded any.
Throws:
InvalidTypeForEncoding - thrown if the type is not valid for the encoding format effective for this Codec.

decode_value

public Any decode_value(byte[] data,
                        TypeCode tc)
                 throws FormatMismatch,
                        TypeMismatch
Decodes the given byte array into an Any based on the given TypeCode and the encoding format effective for this Codec.

Parameters:
data - The data, in the form of a byte array, to be decoded into an Any.
tc - The TypeCode to be used to decode the data.
Returns:
An Any containing the data from the decoded byte array.
Throws:
FormatMismatch - thrown if the byte array cannot be decoded into an Any.
TypeMismatch
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


CodeSets (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP
Interface CodeSets

public interface CodeSets

org/omg/IOP/CodeSets.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableInterceptor/IOP.idl Thursday, June 12, 2003 9:59:14 PM GMT-08:00

Field Summary
static int value
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.

Field Detail

value

public static final int value
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.

See Also:
Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ComponentIdHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP
Class ComponentIdHelper

java.lang.Object
    extended by org.omg.IOP.ComponentIdHelper
public abstract class ComponentIdHelper
extends Object

Standard way of representing multicomponent profiles. This would be encapsulated in a TaggedProfile.

Constructor Summary
ComponentIdHelper()
Method Summary
static int | extract(Any a)
static String | id()
static void | insert(Any a, int that)
static int | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, int value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ComponentIdHelper

public ComponentIdHelper()
Method Detail

insert

public static void insert(Any a,
                          int that)

extract

public static int extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static int read(InputStream istream)

write

public static void write(OutputStream ostream,
                         int value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Encoding (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP
Class Encoding

java.lang.Object
    extended by org.omg.IOP.Encoding
All Implemented Interfaces:
IDLEntity, Serializable
public final class Encoding
extends Object
implements IDLEntity

Defines the encoding format of a Codec. This class details the encoding format, such as CDR Encapsulation encoding, and the major and minor versions of that format.

The encodings currently supported are:

  • ENCODING_CDR_ENCAPS, version 1.0;
  • ENCODING_CDR_ENCAPS, version 1.1;
  • ENCODING_CDR_ENCAPS, version 1.2;
  • ENCODING_CDR_ENCAPS for all future versions of GIOP as they arise.
Vendors are free to support additional encodings.

See Also:
ENCODING_CDR_ENCAPS

Field Summary
short | format The encoding format.
byte | major_version The major version of this Encoding format.
byte | minor_version The minor version of this Encoding format.
Constructor Summary
Encoding()
Encoding(short _format, byte _major_version, byte _minor_version)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

format

public short format
The encoding format.

major_version

public byte major_version
The major version of this Encoding format.

minor_version

public byte minor_version
The minor version of this Encoding format.

Constructor Detail

Encoding

public Encoding()

Encoding

public Encoding(short _format,
                byte _major_version,
                byte _minor_version)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ENCODING_CDR_ENCAPS (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP
Interface ENCODING_CDR_ENCAPS

public interface ENCODING_CDR_ENCAPS

org/omg/IOP/ENCODING_CDR_ENCAPS.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableInterceptor/IOP.idl Thursday, June 12, 2003 9:59:14 PM GMT-08:00

Field Summary
static short value
The CDR Encapsulation encoding.

Field Detail

value

public static final short value
The CDR Encapsulation encoding.

See Also:
CodecFactory, Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


IOR (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP
Class IOR

java.lang.Object
    extended by org.omg.IOP.IOR
All Implemented Interfaces:
IDLEntity, Serializable
public final class IOR
extends Object
implements IDLEntity

Captures information about a object references, such as whether the object is null, what type it is, what protocols are supported, and what ORB services are available.

This data structure need not be used internally to any given ORB, and is not intended to be visible to application-level ORB programmers. It should be used only when crossing object reference domain boundaries, within bridges.

This data structure is designed to be efficient in typical single-protocol configurations, while not penalizing multiprotocol ones.

Object references have at least one tagged profile. Each profile supports one or more protocols and encapsulates all the basic information the protocols it supports need to identify an object. Any single profile holds enough information to drive a complete invocation using any of the protocols it supports; the content and structure of those profile entries are wholly specified by these protocols. A bridge between two domains may need to know the detailed content of the profile for those domains' profiles, depending on the technique it uses to bridge the domains.

Each profile has a unique numeric tag, assigned by the OMG. Profile tags in the range 0x80000000 through 0xffffffff are reserved for future use, and are not currently available for assignment.

Null object references are indicated by an empty set of profiles, and by a "Null" type ID (a string which contains only a single terminating character). A Null TypeID is the only mechanism that can be used to represent the type CORBA.Object. Type IDs may only be "Null" in any message, requiring the client to use existing knowledge or to consult the object, to determine interface types supported. The type ID is a Repository ID identifying the interface type, and is provided to allow ORBs to preserve strong typing. This identifier is agreed on within the bridge and, for reasons outside the scope of the interoperability specification, needs to have a much broader scope to address various problems in system evolution and maintenance. Type IDs support detection of type equivalence, and in conjunction with an Interface Repository, allow processes to reason about the relationship of the type of the object referred to and any other type.

The type ID, if provided by the server, indicates the most derived type that the server wishes to publish, at the time the reference is generated. The object's actual most derived type may later change to a more derived type. Therefore, the type ID in the IOR can only be interpreted by the client as a hint that the object supports at least the indicated interface. The client can succeed in narrowing the reference to the indicated interface, or to one of its base interfaces, based solely on the type ID in the IOR, but must not fail to narrow the reference without consulting the object via the "_is_a" or "_get_interface" pseudo-operations.

Field Summary
TaggedProfile[] | profiles An array of tagged profiles associated with this object reference.
String | type_id The type id, represented as a String.
Constructor Summary
IOR()
IOR(String _type_id, TaggedProfile[] _profiles)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

type_id

public String type_id
The type id, represented as a String.

profiles

public TaggedProfile[] profiles
An array of tagged profiles associated with this object reference.

Constructor Detail

IOR

public IOR()

IOR

public IOR(String _type_id,
           TaggedProfile[] _profiles)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


IORHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP
Class IORHelper

java.lang.Object
    extended by org.omg.IOP.IORHelper
public abstract class IORHelper
extends Object

Captures information about a object references, such as whether the object is null, what type it is, what protocols are supported, and what ORB services are available.

This data structure need not be used internally to any given ORB, and is not intended to be visible to application-level ORB programmers. It should be used only when crossing object reference domain boundaries, within bridges.

This data structure is designed to be efficient in typical single-protocol configurations, while not penalizing multiprotocol ones.

Object references have at least one tagged profile. Each profile supports one or more protocols and encapsulates all the basic information the protocols it supports need to identify an object. Any single profile holds enough information to drive a complete invocation using any of the protocols it supports; the content and structure of those profile entries are wholly specified by these protocols. A bridge between two domains may need to know the detailed content of the profile for those domains' profiles, depending on the technique it uses to bridge the domains.

Each profile has a unique numeric tag, assigned by the OMG. Profile tags in the range 0x80000000 through 0xffffffff are reserved for future use, and are not currently available for assignment.

Null object references are indicated by an empty set of profiles, and by a "Null" type ID (a string which contains only a single terminating character). A Null TypeID is the only mechanism that can be used to represent the type CORBA.Object. Type IDs may only be "Null" in any message, requiring the client to use existing knowledge or to consult the object, to determine interface types supported. The type ID is a Repository ID identifying the interface type, and is provided to allow ORBs to preserve strong typing. This identifier is agreed on within the bridge and, for reasons outside the scope of the interoperability specification, needs to have a much broader scope to address various problems in system evolution and maintenance. Type IDs support detection of type equivalence, and in conjunction with an Interface Repository, allow processes to reason about the relationship of the type of the object referred to and any other type.

The type ID, if provided by the server, indicates the most derived type that the server wishes to publish, at the time the reference is generated. The object's actual most derived type may later change to a more derived type. Therefore, the type ID in the IOR can only be interpreted by the client as a hint that the object supports at least the indicated interface. The client can succeed in narrowing the reference to the indicated interface, or to one of its base interfaces, based solely on the type ID in the IOR, but must not fail to narrow the reference without consulting the object via the "_is_a" or "_get_interface" pseudo-operations.

Constructor Summary
IORHelper()
Method Summary
static IOR | extract(Any a)
static String | id()
static void | insert(Any a, IOR that)
static IOR | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, IOR value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

IORHelper

public IORHelper()
Method Detail

insert

public static void insert(Any a,
                          IOR that)

extract

public static IOR extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static IOR read(InputStream istream)

write

public static void write(OutputStream ostream,
                         IOR value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


IORHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP
Class IORHolder

java.lang.Object
    extended by org.omg.IOP.IORHolder
All Implemented Interfaces:
Streamable
public final class IORHolder
extends Object
implements Streamable

Captures information about a object references, such as whether the object is null, what type it is, what protocols are supported, and what ORB services are available.

This data structure need not be used internally to any given ORB, and is not intended to be visible to application-level ORB programmers. It should be used only when crossing object reference domain boundaries, within bridges.

This data structure is designed to be efficient in typical single-protocol configurations, while not penalizing multiprotocol ones.

Object references have at least one tagged profile. Each profile supports one or more protocols and encapsulates all the basic information the protocols it supports need to identify an object. Any single profile holds enough information to drive a complete invocation using any of the protocols it supports; the content and structure of those profile entries are wholly specified by these protocols. A bridge between two domains may need to know the detailed content of the profile for those domains' profiles, depending on the technique it uses to bridge the domains.

Each profile has a unique numeric tag, assigned by the OMG. Profile tags in the range 0x80000000 through 0xffffffff are reserved for future use, and are not currently available for assignment.

Null object references are indicated by an empty set of profiles, and by a "Null" type ID (a string which contains only a single terminating character). A Null TypeID is the only mechanism that can be used to represent the type CORBA.Object. Type IDs may only be "Null" in any message, requiring the client to use existing knowledge or to consult the object, to determine interface types supported. The type ID is a Repository ID identifying the interface type, and is provided to allow ORBs to preserve strong typing. This identifier is agreed on within the bridge and, for reasons outside the scope of the interoperability specification, needs to have a much broader scope to address various problems in system evolution and maintenance. Type IDs support detection of type equivalence, and in conjunction with an Interface Repository, allow processes to reason about the relationship of the type of the object referred to and any other type.

The type ID, if provided by the server, indicates the most derived type that the server wishes to publish, at the time the reference is generated. The object's actual most derived type may later change to a more derived type. Therefore, the type ID in the IOR can only be interpreted by the client as a hint that the object supports at least the indicated interface. The client can succeed in narrowing the reference to the indicated interface, or to one of its base interfaces, based solely on the type ID in the IOR, but must not fail to narrow the reference without consulting the object via the "_is_a" or "_get_interface" pseudo-operations.

Field Summary
 IOR value
Constructor Summary
IORHolder()
IORHolder(IOR initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public IOR value
Constructor Detail

IORHolder

public IORHolder()

IORHolder

public IORHolder(IOR initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MultipleComponentProfileHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP
Class MultipleComponentProfileHelper

java.lang.Object
    extended by org.omg.IOP.MultipleComponentProfileHelper
public abstract class MultipleComponentProfileHelper
extends Object

An array of tagged components, forming a multiple component profile.

Constructor Summary
MultipleComponentProfileHelper()
Method Summary
static TaggedComponent[] | extract(Any a)
static String | id()
static void | insert(Any a, TaggedComponent[] that)
static TaggedComponent[] | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, TaggedComponent[] value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

MultipleComponentProfileHelper

public MultipleComponentProfileHelper()
Method Detail

insert

public static void insert(Any a,
                          TaggedComponent[] that)

extract

public static TaggedComponent[] extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static TaggedComponent[] read(InputStream istream)

write

public static void write(OutputStream ostream,
                         TaggedComponent[] value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MultipleComponentProfileHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP
Class MultipleComponentProfileHolder

java.lang.Object
    extended by org.omg.IOP.MultipleComponentProfileHolder
All Implemented Interfaces:
Streamable
public final class MultipleComponentProfileHolder
extends Object
implements Streamable

An array of tagged components, forming a multiple component profile.

Field Summary
 TaggedComponent[] value
Constructor Summary
MultipleComponentProfileHolder()
MultipleComponentProfileHolder(TaggedComponent[] initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public TaggedComponent[] value
Constructor Detail

MultipleComponentProfileHolder

public MultipleComponentProfileHolder()

MultipleComponentProfileHolder

public MultipleComponentProfileHolder(TaggedComponent[] initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


org.omg.IOP (Java 2 Platform SE v1.4.2)

 org.omg.IOP
Interfaces
Codec
CodecFactory
CodecFactoryOperations
CodecOperations
CodeSets
ENCODING_CDR_ENCAPS
TAG_ALTERNATE_IIOP_ADDRESS
TAG_CODE_SETS
TAG_INTERNET_IOP
TAG_JAVA_CODEBASE
TAG_MULTIPLE_COMPONENTS
TAG_ORB_TYPE
TAG_POLICIES
TransactionService
Classes
CodecFactoryHelper
ComponentIdHelper
Encoding
IOR
IORHelper
IORHolder
MultipleComponentProfileHelper
MultipleComponentProfileHolder
ProfileIdHelper
ServiceContext
ServiceContextHelper
ServiceContextHolder
ServiceContextListHelper
ServiceContextListHolder
ServiceIdHelper
TaggedComponent
TaggedComponentHelper
TaggedComponentHolder
TaggedProfile
TaggedProfileHelper
TaggedProfileHolder


org.omg.IOP (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

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.

See:
Description

Interface Summary
Codec | The formats of IOR components and service context data used by ORB services are often defined as CDR encapsulations encoding instances of IDL defined data types.
CodecFactory | Codecs are obtained from the CodecFactory.
CodecFactoryOperations | Codecs are obtained from the CodecFactory.
CodecOperations | The formats of IOR components and service context data used by ORB services are often defined as CDR encapsulations encoding instances of IDL defined data types.
CodeSets | org/omg/IOP/CodeSets.java .
ENCODING_CDR_ENCAPS | org/omg/IOP/ENCODING_CDR_ENCAPS.java .
TAG_ALTERNATE_IIOP_ADDRESS | org/omg/IOP/TAG_ALTERNATE_IIOP_ADDRESS.java .
TAG_CODE_SETS | org/omg/IOP/TAG_CODE_SETS.java .
TAG_INTERNET_IOP | org/omg/IOP/TAG_INTERNET_IOP.java .
TAG_JAVA_CODEBASE | org/omg/IOP/TAG_JAVA_CODEBASE.java .
TAG_MULTIPLE_COMPONENTS | org/omg/IOP/TAG_MULTIPLE_COMPONENTS.java .
TAG_ORB_TYPE | org/omg/IOP/TAG_ORB_TYPE.java .
TAG_POLICIES | org/omg/IOP/TAG_POLICIES.java .
TransactionService | org/omg/IOP/TransactionService.java .

Class Summary
CodecFactoryHelper | Codecs are obtained from the CodecFactory.
ComponentIdHelper | Standard way of representing multicomponent profiles.
Encoding | Defines the encoding format of a Codec.
IOR | Captures information about a object references, such as whether the object is null, what type it is, what protocols are supported, and what ORB services are available.
IORHelper | Captures information about a object references, such as whether the object is null, what type it is, what protocols are supported, and what ORB services are available.
IORHolder | Captures information about a object references, such as whether the object is null, what type it is, what protocols are supported, and what ORB services are available.
MultipleComponentProfileHelper | An array of tagged components, forming a multiple component profile.
MultipleComponentProfileHolder | An array of tagged components, forming a multiple component profile.
ProfileIdHelper | Profile ID
ServiceContext | Service-specific information to be passed implicitly with requests and replies.
ServiceContextHelper | Service-specific information to be passed implicitly with requests and replies.
ServiceContextHolder | Service-specific information to be passed implicitly with requests and replies.
ServiceContextListHelper | An array of service contexts, forming a service context list.
ServiceContextListHolder | An array of service contexts, forming a service context list.
ServiceIdHelper | A service id, represented as an int
TaggedComponent | TaggedComponents contained in TAG_INTERNET_IOP and TAG_MULTIPLE_COMPONENTS profiles are identified by unique numeric tags using a namespace distinct form that is used for profile tags.
TaggedComponentHelper | TaggedComponents contained in TAG_INTERNET_IOP and TAG_MULTIPLE_COMPONENTS profiles are identified by unique numeric tags using a namespace distinct form that is used for profile tags.
TaggedComponentHolder | TaggedComponents contained in TAG_INTERNET_IOP and TAG_MULTIPLE_COMPONENTS profiles are identified by unique numeric tags using a namespace distinct form that is used for profile tags.
TaggedProfile | Object references have at least one tagged profile.
TaggedProfileHelper | Object references have at least one tagged profile.
TaggedProfileHolder | Object references have at least one tagged profile.

Package org.omg.IOP Description

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. Please refer to that OMG specification for further details.

Please note that we do not provide all parts of the IOP module from the specification. We only provide those parts that are referenced as return values or parameter types in public APIs, most notably, Portable Interceptors.

Package Specification

For a precise list of supported sections of official specifications with which the Java 2 Platform, Standard Edition, v.1.4 ORB complies, see Official Specifications for CORBA support in J2SE 1.4.

Since:
1.4
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


org.omg.IOP Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package org.omg.IOP

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class org.omg.IOP.CodecFactoryHelper
    • class org.omg.IOP.ComponentIdHelper
    • class org.omg.IOP.Encoding (implements org.omg.CORBA.portable.IDLEntity)
    • class org.omg.IOP.IOR (implements org.omg.CORBA.portable.IDLEntity)
    • class org.omg.IOP.IORHelper
    • class org.omg.IOP.IORHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.IOP.MultipleComponentProfileHelper
    • class org.omg.IOP.MultipleComponentProfileHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.IOP.ProfileIdHelper
    • class org.omg.IOP.ServiceContext (implements org.omg.CORBA.portable.IDLEntity)
    • class org.omg.IOP.ServiceContextHelper
    • class org.omg.IOP.ServiceContextHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.IOP.ServiceContextListHelper
    • class org.omg.IOP.ServiceContextListHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.IOP.ServiceIdHelper
    • class org.omg.IOP.TaggedComponent (implements org.omg.CORBA.portable.IDLEntity)
    • class org.omg.IOP.TaggedComponentHelper
    • class org.omg.IOP.TaggedComponentHolder (implements org.omg.CORBA.portable.Streamable)
    • class org.omg.IOP.TaggedProfile (implements org.omg.CORBA.portable.IDLEntity)
    • class org.omg.IOP.TaggedProfileHelper
    • class org.omg.IOP.TaggedProfileHolder (implements org.omg.CORBA.portable.Streamable)

Interface Hierarchy

  • interface org.omg.IOP.CodecFactoryOperations
    • interface org.omg.IOP.CodecFactory (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CORBA.Object)
  • interface org.omg.IOP.CodecOperations
    • interface org.omg.IOP.Codec (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CORBA.Object)
  • interface org.omg.IOP.CodeSets
  • interface org.omg.IOP.ENCODING_CDR_ENCAPS
  • interface org.omg.CORBA.Object
    • interface org.omg.IOP.Codec (also extends org.omg.IOP.CodecOperations, org.omg.CORBA.portable.IDLEntity)
    • interface org.omg.IOP.CodecFactory (also extends org.omg.IOP.CodecFactoryOperations, org.omg.CORBA.portable.IDLEntity)
  • interface java.io.Serializable
    • interface org.omg.CORBA.portable.IDLEntity
      • interface org.omg.IOP.Codec (also extends org.omg.IOP.CodecOperations, org.omg.CORBA.Object)
      • interface org.omg.IOP.CodecFactory (also extends org.omg.IOP.CodecFactoryOperations, org.omg.CORBA.Object)
  • interface org.omg.IOP.TAG_ALTERNATE_IIOP_ADDRESS
  • interface org.omg.IOP.TAG_CODE_SETS
  • interface org.omg.IOP.TAG_INTERNET_IOP
  • interface org.omg.IOP.TAG_JAVA_CODEBASE
  • interface org.omg.IOP.TAG_MULTIPLE_COMPONENTS
  • interface org.omg.IOP.TAG_ORB_TYPE
  • interface org.omg.IOP.TAG_POLICIES
  • interface org.omg.IOP.TransactionService
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package org.omg.IOP (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
org.omg.IOP

Packages that use org.omg.IOP
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.PortableInterceptor | Provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.

Classes in org.omg.IOP used by org.omg.IOP
Codec
The formats of IOR components and service context data used by ORB services are often defined as CDR encapsulations encoding instances of IDL defined data types.
CodecFactory
Codecs are obtained from the CodecFactory.
CodecFactoryOperations
Codecs are obtained from the CodecFactory.
CodecOperations
The formats of IOR components and service context data used by ORB services are often defined as CDR encapsulations encoding instances of IDL defined data types.
Encoding
Defines the encoding format of a Codec.
IOR
Captures information about a object references, such as whether the object is null, what type it is, what protocols are supported, and what ORB services are available.
ServiceContext
Service-specific information to be passed implicitly with requests and replies.
TaggedComponent
TaggedComponents contained in TAG_INTERNET_IOP and TAG_MULTIPLE_COMPONENTS profiles are identified by unique numeric tags using a namespace distinct form that is used for profile tags.
TaggedProfile
Object references have at least one tagged profile.

Classes in org.omg.IOP used by org.omg.PortableInterceptor
CodecFactory
Codecs are obtained from the CodecFactory.
ServiceContext
Service-specific information to be passed implicitly with requests and replies.
TaggedComponent
TaggedComponents contained in TAG_INTERNET_IOP and TAG_MULTIPLE_COMPONENTS profiles are identified by unique numeric tags using a namespace distinct form that is used for profile tags.
TaggedProfile
Object references have at least one tagged profile.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


ProfileIdHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP
Class ProfileIdHelper

java.lang.Object
    extended by org.omg.IOP.ProfileIdHelper
public abstract class ProfileIdHelper
extends Object

Profile ID

Constructor Summary
ProfileIdHelper()
Method Summary
static int | extract(Any a)
static String | id()
static void | insert(Any a, int that)
static int | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, int value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ProfileIdHelper

public ProfileIdHelper()
Method Detail

insert

public static void insert(Any a,
                          int that)

extract

public static int extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static int read(InputStream istream)

write

public static void write(OutputStream ostream,
                         int value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ServiceContext (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP
Class ServiceContext

java.lang.Object
    extended by org.omg.IOP.ServiceContext
All Implemented Interfaces:
IDLEntity, Serializable
public final class ServiceContext
extends Object
implements IDLEntity

Service-specific information to be passed implicitly with requests and replies. Service contexts are composed of service ids and associated data.

Field Summary
byte[] | context_data The data associated with this service context
int | context_id The service context id
Constructor Summary
ServiceContext()
ServiceContext(int _context_id, byte[] _context_data)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

context_id

public int context_id
The service context id

context_data

public byte[] context_data
The data associated with this service context

Constructor Detail

ServiceContext

public ServiceContext()

ServiceContext

public ServiceContext(int _context_id,
                      byte[] _context_data)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ServiceContextHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP
Class ServiceContextHelper

java.lang.Object
    extended by org.omg.IOP.ServiceContextHelper
public abstract class ServiceContextHelper
extends Object

Service-specific information to be passed implicitly with requests and replies. Service contexts are composed of service ids and associated data.

Constructor Summary
ServiceContextHelper()
Method Summary
static ServiceContext | extract(Any a)
static String | id()
static void | insert(Any a, ServiceContext that)
static ServiceContext | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, ServiceContext value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ServiceContextHelper

public ServiceContextHelper()
Method Detail

insert

public static void insert(Any a,
                          ServiceContext that)

extract

public static ServiceContext extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static ServiceContext read(InputStream istream)

write

public static void write(OutputStream ostream,
                         ServiceContext value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ServiceContextHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP
Class ServiceContextHolder

java.lang.Object
    extended by org.omg.IOP.ServiceContextHolder
All Implemented Interfaces:
Streamable
public final class ServiceContextHolder
extends Object
implements Streamable

Service-specific information to be passed implicitly with requests and replies. Service contexts are composed of service ids and associated data.

Field Summary
 ServiceContext value
Constructor Summary
ServiceContextHolder()
ServiceContextHolder(ServiceContext initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public ServiceContext value
Constructor Detail

ServiceContextHolder

public ServiceContextHolder()

ServiceContextHolder

public ServiceContextHolder(ServiceContext initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ServiceContextListHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP
Class ServiceContextListHelper

java.lang.Object
    extended by org.omg.IOP.ServiceContextListHelper
public abstract class ServiceContextListHelper
extends Object

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

Constructor Summary
ServiceContextListHelper()
Method Summary
static ServiceContext[] | extract(Any a)
static String | id()
static void | insert(Any a, ServiceContext[] that)
static ServiceContext[] | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, ServiceContext[] value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ServiceContextListHelper

public ServiceContextListHelper()
Method Detail

insert

public static void insert(Any a,
                          ServiceContext[] that)

extract

public static ServiceContext[] extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static ServiceContext[] read(InputStream istream)

write

public static void write(OutputStream ostream,
                         ServiceContext[] value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ServiceContextListHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP
Class ServiceContextListHolder

java.lang.Object
    extended by org.omg.IOP.ServiceContextListHolder
All Implemented Interfaces:
Streamable
public final class ServiceContextListHolder
extends Object
implements Streamable

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

Field Summary
 ServiceContext[] value
Constructor Summary
ServiceContextListHolder()
ServiceContextListHolder(ServiceContext[] initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public ServiceContext[] value
Constructor Detail

ServiceContextListHolder

public ServiceContextListHolder()

ServiceContextListHolder

public ServiceContextListHolder(ServiceContext[] initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ServiceIdHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP
Class ServiceIdHelper

java.lang.Object
    extended by org.omg.IOP.ServiceIdHelper
public abstract class ServiceIdHelper
extends Object

A service id, represented as an int

Constructor Summary
ServiceIdHelper()
Method Summary
static int | extract(Any a)
static String | id()
static void | insert(Any a, int that)
static int | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, int value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ServiceIdHelper

public ServiceIdHelper()
Method Detail

insert

public static void insert(Any a,
                          int that)

extract

public static int extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static int read(InputStream istream)

write

public static void write(OutputStream ostream,
                         int value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TAG_ALTERNATE_IIOP_ADDRESS (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP
Interface TAG_ALTERNATE_IIOP_ADDRESS

public interface TAG_ALTERNATE_IIOP_ADDRESS

org/omg/IOP/TAG_ALTERNATE_IIOP_ADDRESS.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableInterceptor/IOP.idl Thursday, June 12, 2003 9:59:14 PM GMT-08:00

Field Summary
static int value
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.

Field Detail

value

public static final int value
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.

The TAG_ALTERNATE_IIOP_ADDRESS component has an associated value of type:

     struct {
         string HostID,
         short Port
     };
encoded as a CDR encapsulation.

Zero or more instances of the TAG_ALTERNATE_IIOP_ADDRESS component type may be included in a version 1.2 TAG_INTERNET_IOP Profile. Each of these alternative addresses may be used by the client orb, in addition to the host and port address expressed in the body of the Profile. In cases where one or more TAG_ALTERNATE_IIOP_ADDRESS components are present in a TAG_INTERNET_IOP Profile, no order of use is prescribed by Version 1.2 of IIOP.

See Also:
Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TAG_CODE_SETS (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP
Interface TAG_CODE_SETS

public interface TAG_CODE_SETS

org/omg/IOP/TAG_CODE_SETS.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableInterceptor/IOP.idl Thursday, June 12, 2003 9:59:14 PM GMT-08:00

Field Summary
static int value
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.

Field Detail

value

public static final int value
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.

See Also:
Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TAG_INTERNET_IOP (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP
Interface TAG_INTERNET_IOP

public interface TAG_INTERNET_IOP

org/omg/IOP/TAG_INTERNET_IOP.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableInterceptor/IOP.idl Thursday, June 12, 2003 9:59:13 PM GMT-08:00

Field Summary
static int value
Identifies profiles that support the Internet Inter-ORB Protocol.

Field Detail

value

public static final int value
Identifies profiles that support the Internet Inter-ORB Protocol. The ProfileBody of this profile contains a CDR encapsulation of a structure containing addressing and object identification information used by IIOP. Version 1.1 of the TAG_INTERNET_IOP profile also includes an array of TaggedComponent objects that can contain additional information supporting optional IIOP features, ORB services such as security, and future protocol extensions.

Protocols other than IIOP (such as ESIOPs and other GIOPs) can share profile information (such as object identity or security information) with IIOP by encoding their additional profile information as components in the TAG_INTERNET_IOP profile. All TAG_INTERNET_IOP profiles support IIOP, regardless of whether they also support additional protocols. Interoperable ORBs are not required to create or understand any other profile, nor are they required to create or understand any of the components defined for other protocols that might share the TAG_INTERNET_IOP profile with IIOP.

The profile_data for the TAG_INTERNET_IOP profile is a CDR encapsulation of the IIOP.ProfileBody_1_1 type.

See Also:
Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TAG_JAVA_CODEBASE (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP
Interface TAG_JAVA_CODEBASE

public interface TAG_JAVA_CODEBASE

org/omg/IOP/TAG_JAVA_CODEBASE.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableInterceptor/IOP.idl Thursday, June 12, 2003 9:59:14 PM GMT-08:00

Field Summary
static int value
Class downloading is supported for stubs, ties, values, and value helpers.

Field Detail

value

public static final int value
Class downloading is supported for stubs, ties, values, and value helpers. The specification allows transmission of codebase information on the wire for stubs and ties, and enables usage of pre-existing ClassLoaders when relevant.

For values and value helpers, the codebase is transmitted after the value tag. For stubs and ties, the codebase is transmitted as the TaggedComponent TAG_JAVA_CODEBASE in the IOR profile, where the component_data is a CDR encapsulation of the codebase written as an IDL string. The codebase is a space-separated list of one or more URLs.

See Also:
Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TAG_MULTIPLE_COMPONENTS (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP
Interface TAG_MULTIPLE_COMPONENTS

public interface TAG_MULTIPLE_COMPONENTS

org/omg/IOP/TAG_MULTIPLE_COMPONENTS.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableInterceptor/IOP.idl Thursday, June 12, 2003 9:59:13 PM GMT-08:00

Field Summary
static int value
Indicates that the value encapsulated is of type MultipleComponentProfile.

Field Detail

value

public static final int value
Indicates that the value encapsulated is of type MultipleComponentProfile. In this case, the profile consists of a list of protocol components, the use of which must be specified by the protocol using this profile. This profile may be used to carry IOR components.

The profile_data for the TAG_MULTIPLE_COMPONENTS profile is a CDR encapsulation of the MultipleComponentProfile type shown above.

See Also:
Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TAG_ORB_TYPE (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP
Interface TAG_ORB_TYPE

public interface TAG_ORB_TYPE

org/omg/IOP/TAG_ORB_TYPE.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableInterceptor/IOP.idl Thursday, June 12, 2003 9:59:13 PM GMT-08:00

Field Summary
static int value
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.

Field Detail

value

public static final int value
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.

The TAG_ORB_TYPE component has an associated value of type unsigned long (Java long), encoded as a CDR encapsulation, designating an ORB type ID allocated by the OMG for the ORB type of the originating ORB. Anyone may register any ORB types by submitting a short (one-paragraph) description of the ORB type to the OMG, and will receive a new ORB type ID in return. A list of ORB type descriptions and values will be made available on the OMG web server.

The TAG_ORB_TYPE component can appear at most once in any IOR profile. For profiles supporting IIOP 1.1 or greater, it is optionally present.

See Also:
Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TAG_POLICIES (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP
Interface TAG_POLICIES

public interface TAG_POLICIES

org/omg/IOP/TAG_POLICIES.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableInterceptor/IOP.idl Thursday, June 12, 2003 9:59:14 PM GMT-08:00

Field Summary
static int value
A profile component containing the sequence of QoS policies exported with the object reference by an object adapter.

Field Detail

value

public static final int value
A profile component containing the sequence of QoS policies exported with the object reference by an object adapter.

See Also:
Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TaggedComponent (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP
Class TaggedComponent

java.lang.Object
    extended by org.omg.IOP.TaggedComponent
All Implemented Interfaces:
IDLEntity, Serializable
public final class TaggedComponent
extends Object
implements IDLEntity

TaggedComponents contained in TAG_INTERNET_IOP and TAG_MULTIPLE_COMPONENTS profiles are identified by unique numeric tags using a namespace distinct form that is used for profile tags. Component tags are assigned by the OMG.

Specifications of components must include the following information:

  • Component ID: The compound tag that is obtained from OMG.
  • Structure and encoding: The syntax of the component data and the encoding rules. If the component value is encoded as a CDR encapsulation, the IDL type that is encapsulated and the GIOP version which is used for encoding the value, if different than GIOP 1.0, must be specified as part of the component definition.
  • Semantics: How the component data is intended to be used.
  • Protocols: The protocol for which the component is defined, and whether it is intended that the component be usable by other protocols.
  • At most once: whether more than one instance of this component can be included in a profile.
Specification of protocols must describe how the components affect the protocol. The following should be specified in any protocol definition for each TaggedComponent that the protocol uses:
  • Mandatory presence: Whether inclusion of the component in profiles supporting the protocol is required (MANDATORY PRESENCE) or not required (OPTIONAL PRESENCE).
  • Droppable: For optional presence component, whether component, if present, must be retained or may be dropped.

Field Summary
byte[] | component_data The component data associated with the component id.
int | tag The tag, represented as a component id.
Constructor Summary
TaggedComponent()
TaggedComponent(int _tag, byte[] _component_data)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

tag

public int tag
The tag, represented as a component id.

component_data

public byte[] component_data
The component data associated with the component id.

Constructor Detail

TaggedComponent

public TaggedComponent()

TaggedComponent

public TaggedComponent(int _tag,
                       byte[] _component_data)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TaggedComponentHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP
Class TaggedComponentHelper

java.lang.Object
    extended by org.omg.IOP.TaggedComponentHelper
public abstract class TaggedComponentHelper
extends Object

TaggedComponents contained in TAG_INTERNET_IOP and TAG_MULTIPLE_COMPONENTS profiles are identified by unique numeric tags using a namespace distinct form that is used for profile tags. Component tags are assigned by the OMG.

Specifications of components must include the following information:

  • Component ID: The compound tag that is obtained from OMG.
  • Structure and encoding: The syntax of the component data and the encoding rules. If the component value is encoded as a CDR encapsulation, the IDL type that is encapsulated and the GIOP version which is used for encoding the value, if different than GIOP 1.0, must be specified as part of the component definition.
  • Semantics: How the component data is intended to be used.
  • Protocols: The protocol for which the component is defined, and whether it is intended that the component be usable by other protocols.
  • At most once: whether more than one instance of this component can be included in a profile.
Specification of protocols must describe how the components affect the protocol. The following should be specified in any protocol definition for each TaggedComponent that the protocol uses:
  • Mandatory presence: Whether inclusion of the component in profiles supporting the protocol is required (MANDATORY PRESENCE) or not required (OPTIONAL PRESENCE).
  • Droppable: For optional presence component, whether component, if present, must be retained or may be dropped.

Constructor Summary
TaggedComponentHelper()
Method Summary
static TaggedComponent | extract(Any a)
static String | id()
static void | insert(Any a, TaggedComponent that)
static TaggedComponent | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, TaggedComponent value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

TaggedComponentHelper

public TaggedComponentHelper()
Method Detail

insert

public static void insert(Any a,
                          TaggedComponent that)

extract

public static TaggedComponent extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static TaggedComponent read(InputStream istream)

write

public static void write(OutputStream ostream,
                         TaggedComponent value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TaggedComponentHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP
Class TaggedComponentHolder

java.lang.Object
    extended by org.omg.IOP.TaggedComponentHolder
All Implemented Interfaces:
Streamable
public final class TaggedComponentHolder
extends Object
implements Streamable

TaggedComponents contained in TAG_INTERNET_IOP and TAG_MULTIPLE_COMPONENTS profiles are identified by unique numeric tags using a namespace distinct form that is used for profile tags. Component tags are assigned by the OMG.

Specifications of components must include the following information:

  • Component ID: The compound tag that is obtained from OMG.
  • Structure and encoding: The syntax of the component data and the encoding rules. If the component value is encoded as a CDR encapsulation, the IDL type that is encapsulated and the GIOP version which is used for encoding the value, if different than GIOP 1.0, must be specified as part of the component definition.
  • Semantics: How the component data is intended to be used.
  • Protocols: The protocol for which the component is defined, and whether it is intended that the component be usable by other protocols.
  • At most once: whether more than one instance of this component can be included in a profile.
Specification of protocols must describe how the components affect the protocol. The following should be specified in any protocol definition for each TaggedComponent that the protocol uses:
  • Mandatory presence: Whether inclusion of the component in profiles supporting the protocol is required (MANDATORY PRESENCE) or not required (OPTIONAL PRESENCE).
  • Droppable: For optional presence component, whether component, if present, must be retained or may be dropped.

Field Summary
 TaggedComponent value
Constructor Summary
TaggedComponentHolder()
TaggedComponentHolder(TaggedComponent initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public TaggedComponent value
Constructor Detail

TaggedComponentHolder

public TaggedComponentHolder()

TaggedComponentHolder

public TaggedComponentHolder(TaggedComponent initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TaggedProfile (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP
Class TaggedProfile

java.lang.Object
    extended by org.omg.IOP.TaggedProfile
All Implemented Interfaces:
IDLEntity, Serializable
public final class TaggedProfile
extends Object
implements IDLEntity

Object references have at least one tagged profile. Each profile supports one or more protocols and encapsulates all the basic information the protocols it supports need to identify an object. Any single profile holds enough information to drive a complete invocation using any of the protocols it supports; the content and structure of those profile entries are wholly specified by these protocols.

Field Summary
byte[] | profile_data The associated profile data.
int | tag The tag, represented as a profile id.
Constructor Summary
TaggedProfile()
TaggedProfile(int _tag, byte[] _profile_data)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

tag

public int tag
The tag, represented as a profile id.

profile_data

public byte[] profile_data
The associated profile data.

Constructor Detail

TaggedProfile

public TaggedProfile()

TaggedProfile

public TaggedProfile(int _tag,
                     byte[] _profile_data)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TaggedProfileHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP
Class TaggedProfileHelper

java.lang.Object
    extended by org.omg.IOP.TaggedProfileHelper
public abstract class TaggedProfileHelper
extends Object

Object references have at least one tagged profile. Each profile supports one or more protocols and encapsulates all the basic information the protocols it supports need to identify an object. Any single profile holds enough information to drive a complete invocation using any of the protocols it supports; the content and structure of those profile entries are wholly specified by these protocols.

Constructor Summary
TaggedProfileHelper()
Method Summary
static TaggedProfile | extract(Any a)
static String | id()
static void | insert(Any a, TaggedProfile that)
static TaggedProfile | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, TaggedProfile value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

TaggedProfileHelper

public TaggedProfileHelper()
Method Detail

insert

public static void insert(Any a,
                          TaggedProfile that)

extract

public static TaggedProfile extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static TaggedProfile read(InputStream istream)

write

public static void write(OutputStream ostream,
                         TaggedProfile value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TaggedProfileHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP
Class TaggedProfileHolder

java.lang.Object
    extended by org.omg.IOP.TaggedProfileHolder
All Implemented Interfaces:
Streamable
public final class TaggedProfileHolder
extends Object
implements Streamable

Object references have at least one tagged profile. Each profile supports one or more protocols and encapsulates all the basic information the protocols it supports need to identify an object. Any single profile holds enough information to drive a complete invocation using any of the protocols it supports; the content and structure of those profile entries are wholly specified by these protocols.

Field Summary
 TaggedProfile value
Constructor Summary
TaggedProfileHolder()
TaggedProfileHolder(TaggedProfile initialValue)
Method Summary
void | _read(InputStream i) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream o) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public TaggedProfile value
Constructor Detail

TaggedProfileHolder

public TaggedProfileHolder()

TaggedProfileHolder

public TaggedProfileHolder(TaggedProfile initialValue)
Method Detail

_read

public void _read(InputStream i)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
i - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream o)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
o - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


TransactionService (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP
Interface TransactionService

public interface TransactionService

org/omg/IOP/TransactionService.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableInterceptor/IOP.idl Thursday, June 12, 2003 9:59:14 PM GMT-08:00

Field Summary
static int value
Identifies a CDR encapsulation of the CosTSInteroperation.PropogationContext defined in CORBAservices: Common Object Services Specifications.

Field Detail

value

public static final int value
Identifies a CDR encapsulation of the CosTSInteroperation.PropogationContext defined in CORBAservices: Common Object Services Specifications.

See Also:
Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Uses of Interface org.omg.IOP.Codec (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.IOP.Codec

Packages that use Codec
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.

Uses of Codec in org.omg.IOP

Methods in org.omg.IOP that return Codec
 Codec CodecFactoryOperations.create_codec(Encoding enc)
Create a Codec of the given encoding.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.IOP.CodecFactory (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.IOP.CodecFactory

Packages that use CodecFactory
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.PortableInterceptor | Provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.

Uses of CodecFactory in org.omg.IOP

Methods in org.omg.IOP that return CodecFactory
static CodecFactory | CodecFactoryHelper.extract(Any a)
static CodecFactory | CodecFactoryHelper.read(InputStream istream)
static CodecFactory | CodecFactoryHelper.narrow(Object obj)

Methods in org.omg.IOP with parameters of type CodecFactory
static void | CodecFactoryHelper.insert(Any a, CodecFactory that)
static void | CodecFactoryHelper.write(OutputStream ostream, CodecFactory value)

Uses of CodecFactory in org.omg.PortableInterceptor

Methods in org.omg.PortableInterceptor that return CodecFactory
 CodecFactory ORBInitInfoOperations.codec_factory()
Returns the IOP.CodecFactory.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.IOP.CodecFactoryHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.IOP.CodecFactoryHelper

No usage of org.omg.IOP.CodecFactoryHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.IOP.CodecFactoryOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.IOP.CodecFactoryOperations

Packages that use CodecFactoryOperations
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.

Uses of CodecFactoryOperations in org.omg.IOP

Subinterfaces of CodecFactoryOperations in org.omg.IOP
 interface CodecFactory
Codecs are obtained from the CodecFactory.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.IOP.CodecOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.IOP.CodecOperations

Packages that use CodecOperations
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.

Uses of CodecOperations in org.omg.IOP

Subinterfaces of CodecOperations in org.omg.IOP
 interface Codec
The formats of IOR components and service context data used by ORB services are often defined as CDR encapsulations encoding instances of IDL defined data types.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.IOP.CodeSets (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.IOP.CodeSets

No usage of org.omg.IOP.CodeSets

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.IOP.ComponentIdHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.IOP.ComponentIdHelper

No usage of org.omg.IOP.ComponentIdHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.IOP.Encoding (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.IOP.Encoding

Packages that use Encoding
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.

Uses of Encoding in org.omg.IOP

Methods in org.omg.IOP with parameters of type Encoding
 Codec CodecFactoryOperations.create_codec(Encoding enc)
Create a Codec of the given encoding.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.IOP.ENCODING_CDR_ENCAPS (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.IOP.ENCODING_CDR_ENCAPS

No usage of org.omg.IOP.ENCODING_CDR_ENCAPS

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.IOP.IOR (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.IOP.IOR

Packages that use IOR
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.

Uses of IOR in org.omg.IOP

Fields in org.omg.IOP declared as IOR
 IOR IORHolder.value

Methods in org.omg.IOP that return IOR
static IOR | IORHelper.extract(Any a)
static IOR | IORHelper.read(InputStream istream)

Methods in org.omg.IOP with parameters of type IOR
static void | IORHelper.insert(Any a, IOR that)
static void | IORHelper.write(OutputStream ostream, IOR value)

Constructors in org.omg.IOP with parameters of type IOR
IORHolder(IOR initialValue)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.IOP.IORHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.IOP.IORHelper

No usage of org.omg.IOP.IORHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.IOP.IORHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.IOP.IORHolder

No usage of org.omg.IOP.IORHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.IOP.MultipleComponentProfileHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.IOP.MultipleComponentProfileHelper

No usage of org.omg.IOP.MultipleComponentProfileHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.IOP.MultipleComponentProfileHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.IOP.MultipleComponentProfileHolder

No usage of org.omg.IOP.MultipleComponentProfileHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.IOP.ProfileIdHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.IOP.ProfileIdHelper

No usage of org.omg.IOP.ProfileIdHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.IOP.ServiceContext (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.IOP.ServiceContext

Packages that use ServiceContext
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.PortableInterceptor | Provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.

Uses of ServiceContext in org.omg.IOP

Fields in org.omg.IOP declared as ServiceContext
ServiceContext[] | ServiceContextListHolder.value
ServiceContext | ServiceContextHolder.value

Methods in org.omg.IOP that return ServiceContext
static ServiceContext[] | ServiceContextListHelper.extract(Any a)
static ServiceContext[] | ServiceContextListHelper.read(InputStream istream)
static ServiceContext | ServiceContextHelper.extract(Any a)
static ServiceContext | ServiceContextHelper.read(InputStream istream)

Methods in org.omg.IOP with parameters of type ServiceContext
static void | ServiceContextListHelper.insert(Any a, ServiceContext[] that)
static void | ServiceContextListHelper.write(OutputStream ostream, ServiceContext[] value)
static void | ServiceContextHelper.insert(Any a, ServiceContext that)
static void | ServiceContextHelper.write(OutputStream ostream, ServiceContext value)

Constructors in org.omg.IOP with parameters of type ServiceContext
ServiceContextListHolder(ServiceContext[] initialValue)
ServiceContextHolder(ServiceContext initialValue)

Uses of ServiceContext in org.omg.PortableInterceptor

Methods in org.omg.PortableInterceptor that return ServiceContext
ServiceContext | RequestInfoOperations.get_request_service_context(int id) Returns a copy of the service context with the given ID that is associated with the request.
ServiceContext | RequestInfoOperations.get_reply_service_context(int id) Returns a copy of the service context with the given ID that is associated with the reply.

Methods in org.omg.PortableInterceptor with parameters of type ServiceContext
void | ServerRequestInfoOperations.add_reply_service_context(ServiceContext service_context, boolean replace) Allows Interceptors to add service contexts to the request.
void | ClientRequestInfoOperations.add_request_service_context(ServiceContext service_context, boolean replace) Allows Interceptors to add service contexts to the request.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.IOP.ServiceContextHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.IOP.ServiceContextHelper

No usage of org.omg.IOP.ServiceContextHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.IOP.ServiceContextHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.IOP.ServiceContextHolder

No usage of org.omg.IOP.ServiceContextHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.IOP.ServiceContextListHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.IOP.ServiceContextListHelper

No usage of org.omg.IOP.ServiceContextListHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.IOP.ServiceContextListHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.IOP.ServiceContextListHolder

No usage of org.omg.IOP.ServiceContextListHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.IOP.ServiceIdHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.IOP.ServiceIdHelper

No usage of org.omg.IOP.ServiceIdHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.IOP.TAG_ALTERNATE_IIOP_ADDRESS (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.IOP.TAG_ALTERNATE_IIOP_ADDRESS

No usage of org.omg.IOP.TAG_ALTERNATE_IIOP_ADDRESS

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.IOP.TAG_CODE_SETS (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.IOP.TAG_CODE_SETS

No usage of org.omg.IOP.TAG_CODE_SETS

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.IOP.TAG_INTERNET_IOP (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.IOP.TAG_INTERNET_IOP

No usage of org.omg.IOP.TAG_INTERNET_IOP

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.IOP.TAG_JAVA_CODEBASE (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.IOP.TAG_JAVA_CODEBASE

No usage of org.omg.IOP.TAG_JAVA_CODEBASE

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.IOP.TAG_MULTIPLE_COMPONENTS (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.IOP.TAG_MULTIPLE_COMPONENTS

No usage of org.omg.IOP.TAG_MULTIPLE_COMPONENTS

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.IOP.TAG_ORB_TYPE (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.IOP.TAG_ORB_TYPE

No usage of org.omg.IOP.TAG_ORB_TYPE

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.IOP.TAG_POLICIES (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.IOP.TAG_POLICIES

No usage of org.omg.IOP.TAG_POLICIES

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.IOP.TaggedComponent (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.IOP.TaggedComponent

Packages that use TaggedComponent
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.PortableInterceptor | Provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.

Uses of TaggedComponent in org.omg.IOP

Fields in org.omg.IOP declared as TaggedComponent
TaggedComponent | TaggedComponentHolder.value
TaggedComponent[] | MultipleComponentProfileHolder.value

Methods in org.omg.IOP that return TaggedComponent
static TaggedComponent | TaggedComponentHelper.extract(Any a)
static TaggedComponent | TaggedComponentHelper.read(InputStream istream)
static TaggedComponent[] | MultipleComponentProfileHelper.extract(Any a)
static TaggedComponent[] | MultipleComponentProfileHelper.read(InputStream istream)

Methods in org.omg.IOP with parameters of type TaggedComponent
static void | TaggedComponentHelper.insert(Any a, TaggedComponent that)
static void | TaggedComponentHelper.write(OutputStream ostream, TaggedComponent value)
static void | MultipleComponentProfileHelper.insert(Any a, TaggedComponent[] that)
static void | MultipleComponentProfileHelper.write(OutputStream ostream, TaggedComponent[] value)

Constructors in org.omg.IOP with parameters of type TaggedComponent
TaggedComponentHolder(TaggedComponent initialValue)
MultipleComponentProfileHolder(TaggedComponent[] initialValue)

Uses of TaggedComponent in org.omg.PortableInterceptor

Methods in org.omg.PortableInterceptor that return TaggedComponent
TaggedComponent | ClientRequestInfoOperations.get_effective_component(int id) Returns the IOP.TaggedComponent with the given ID from the profile selected for this request.
TaggedComponent[] | ClientRequestInfoOperations.get_effective_components(int id) Returns an array of all tagged components with the given ID from the profile selected for this request.

Methods in org.omg.PortableInterceptor with parameters of type TaggedComponent
void | IORInfoOperations.add_ior_component(TaggedComponent tagged_component) A portable ORB service implementation calls add_ior_component from its implementation of establish_components to add a tagged component to the set which will be included when constructing IORs.
void | IORInfoOperations.add_ior_component_to_profile(TaggedComponent tagged_component, int profile_id) A portable ORB service implementation calls add_ior_component_to_profile from its implementation of establish_components to add a tagged component to the set which will be included when constructing IORs.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.IOP.TaggedComponentHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.IOP.TaggedComponentHelper

No usage of org.omg.IOP.TaggedComponentHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.IOP.TaggedComponentHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.IOP.TaggedComponentHolder

No usage of org.omg.IOP.TaggedComponentHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.IOP.TaggedProfile (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.IOP.TaggedProfile

Packages that use TaggedProfile
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.PortableInterceptor | Provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.

Uses of TaggedProfile in org.omg.IOP

Fields in org.omg.IOP declared as TaggedProfile
TaggedProfile | TaggedProfileHolder.value
TaggedProfile[] | IOR.profiles An array of tagged profiles associated with this object reference.

Methods in org.omg.IOP that return TaggedProfile
static TaggedProfile | TaggedProfileHelper.extract(Any a)
static TaggedProfile | TaggedProfileHelper.read(InputStream istream)

Methods in org.omg.IOP with parameters of type TaggedProfile
static void | TaggedProfileHelper.insert(Any a, TaggedProfile that)
static void | TaggedProfileHelper.write(OutputStream ostream, TaggedProfile value)

Constructors in org.omg.IOP with parameters of type TaggedProfile
TaggedProfileHolder(TaggedProfile initialValue)
IOR(String _type_id, TaggedProfile[] _profiles)

Uses of TaggedProfile in org.omg.PortableInterceptor

Methods in org.omg.PortableInterceptor that return TaggedProfile
 TaggedProfile ClientRequestInfoOperations.effective_profile()
Returns the profile that will be used to send the request.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.IOP.TaggedProfileHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.IOP.TaggedProfileHelper

No usage of org.omg.IOP.TaggedProfileHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.IOP.TaggedProfileHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.IOP.TaggedProfileHolder

No usage of org.omg.IOP.TaggedProfileHolder

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.IOP.TransactionService (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.IOP.TransactionService

No usage of org.omg.IOP.TransactionService

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


org.omg.IOP.CodecFactoryPackage (Java 2 Platform SE v1.4.2)

 org.omg.IOP.CodecFactoryPackage
Classes
UnknownEncodingHelper
Exceptions
UnknownEncoding


org.omg.IOP.CodecFactoryPackage (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package org.omg.IOP.CodecFactoryPackage

This package contains the exceptions specified in the IOP::CodeFactory interface (as part of the Portable Interceptors spec).

See:
Description

Class Summary
UnknownEncodingHelper org/omg/IOP/CodecFactoryPackage/UnknownEncodingHelper.java .

Exception Summary
UnknownEncoding org/omg/IOP/CodecFactoryPackage/UnknownEncoding.java .

Package org.omg.IOP.CodecFactoryPackage Description

This package contains the exceptions specified in the IOP::CodeFactory interface (as part of the Portable Interceptors spec).

Package Specification

For a precise list of supported sections of official specifications with which the Java 2 Platform, Standard Edition, v.1.4 ORB complies, see Official Specifications for CORBA support in J2SE 1.4.

Since:
1.4
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


org.omg.IOP.CodecFactoryPackage Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package org.omg.IOP.CodecFactoryPackage

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class java.lang.Throwable (implements java.io.Serializable)
      • class java.lang.Exception
        • class org.omg.CORBA.UserException (implements org.omg.CORBA.portable.IDLEntity)
          • class org.omg.IOP.CodecFactoryPackage.UnknownEncoding
    • class org.omg.IOP.CodecFactoryPackage.UnknownEncodingHelper
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package org.omg.IOP.CodecFactoryPackage (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
org.omg.IOP.CodecFactoryPackage

Packages that use org.omg.IOP.CodecFactoryPackage
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 | This package contains the exceptions specified in the IOP::CodeFactory interface (as part of the Portable Interceptors spec).

Classes in org.omg.IOP.CodecFactoryPackage used by org.omg.IOP
UnknownEncoding
org/omg/IOP/CodecFactoryPackage/UnknownEncoding.java .

Classes in org.omg.IOP.CodecFactoryPackage used by org.omg.IOP.CodecFactoryPackage
UnknownEncoding
org/omg/IOP/CodecFactoryPackage/UnknownEncoding.java .

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


UnknownEncoding (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP.CodecFactoryPackage
Class UnknownEncoding

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.IOP.CodecFactoryPackage.UnknownEncoding
All Implemented Interfaces:
IDLEntity, Serializable
public final class UnknownEncoding
extends UserException

org/omg/IOP/CodecFactoryPackage/UnknownEncoding.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableInterceptor/IOP.idl Thursday, June 12, 2003 9:59:14 PM GMT-08:00

Constructor Summary
UnknownEncoding()
UnknownEncoding(String $reason)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

UnknownEncoding

public UnknownEncoding()

UnknownEncoding

public UnknownEncoding(String $reason)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


UnknownEncodingHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP.CodecFactoryPackage
Class UnknownEncodingHelper

java.lang.Object
    extended by org.omg.IOP.CodecFactoryPackage.UnknownEncodingHelper
public abstract class UnknownEncodingHelper
extends Object

org/omg/IOP/CodecFactoryPackage/UnknownEncodingHelper.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableInterceptor/IOP.idl Thursday, June 12, 2003 9:59:14 PM GMT-08:00

Constructor Summary
UnknownEncodingHelper()
Method Summary
static UnknownEncoding | extract(Any a)
static String | id()
static void | insert(Any a, UnknownEncoding that)
static UnknownEncoding | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, UnknownEncoding value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

UnknownEncodingHelper

public UnknownEncodingHelper()
Method Detail

insert

public static void insert(Any a,
                          UnknownEncoding that)

extract

public static UnknownEncoding extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static UnknownEncoding read(InputStream istream)

write

public static void write(OutputStream ostream,
                         UnknownEncoding value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Uses of Class org.omg.IOP.CodecFactoryPackage.UnknownEncoding (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.IOP.CodecFactoryPackage.UnknownEncoding

Packages that use UnknownEncoding
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 | This package contains the exceptions specified in the IOP::CodeFactory interface (as part of the Portable Interceptors spec).

Uses of UnknownEncoding in org.omg.IOP

Methods in org.omg.IOP that throw UnknownEncoding
 Codec CodecFactoryOperations.create_codec(Encoding enc)
Create a Codec of the given encoding.

Uses of UnknownEncoding in org.omg.IOP.CodecFactoryPackage

Methods in org.omg.IOP.CodecFactoryPackage that return UnknownEncoding
static UnknownEncoding | UnknownEncodingHelper.extract(Any a)
static UnknownEncoding | UnknownEncodingHelper.read(InputStream istream)

Methods in org.omg.IOP.CodecFactoryPackage with parameters of type UnknownEncoding
static void | UnknownEncodingHelper.insert(Any a, UnknownEncoding that)
static void | UnknownEncodingHelper.write(OutputStream ostream, UnknownEncoding value)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.IOP.CodecFactoryPackage.UnknownEncodingHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.IOP.CodecFactoryPackage.UnknownEncodingHelper

No usage of org.omg.IOP.CodecFactoryPackage.UnknownEncodingHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


FormatMismatch (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP.CodecPackage
Class FormatMismatch

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.IOP.CodecPackage.FormatMismatch
All Implemented Interfaces:
IDLEntity, Serializable
public final class FormatMismatch
extends UserException

org/omg/IOP/CodecPackage/FormatMismatch.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableInterceptor/IOP.idl Thursday, June 12, 2003 9:59:14 PM GMT-08:00

Constructor Summary
FormatMismatch()
FormatMismatch(String $reason)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

FormatMismatch

public FormatMismatch()

FormatMismatch

public FormatMismatch(String $reason)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


FormatMismatchHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP.CodecPackage
Class FormatMismatchHelper

java.lang.Object
    extended by org.omg.IOP.CodecPackage.FormatMismatchHelper
public abstract class FormatMismatchHelper
extends Object

org/omg/IOP/CodecPackage/FormatMismatchHelper.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableInterceptor/IOP.idl Thursday, June 12, 2003 9:59:14 PM GMT-08:00

Constructor Summary
FormatMismatchHelper()
Method Summary
static FormatMismatch | extract(Any a)
static String | id()
static void | insert(Any a, FormatMismatch that)
static FormatMismatch | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, FormatMismatch value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

FormatMismatchHelper

public FormatMismatchHelper()
Method Detail

insert

public static void insert(Any a,
                          FormatMismatch that)

extract

public static FormatMismatch extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static FormatMismatch read(InputStream istream)

write

public static void write(OutputStream ostream,
                         FormatMismatch value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


InvalidTypeForEncoding (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP.CodecPackage
Class InvalidTypeForEncoding

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.IOP.CodecPackage.InvalidTypeForEncoding
All Implemented Interfaces:
IDLEntity, Serializable
public final class InvalidTypeForEncoding
extends UserException

org/omg/IOP/CodecPackage/InvalidTypeForEncoding.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableInterceptor/IOP.idl Thursday, June 12, 2003 9:59:14 PM GMT-08:00

Constructor Summary
InvalidTypeForEncoding()
InvalidTypeForEncoding(String $reason)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

InvalidTypeForEncoding

public InvalidTypeForEncoding()

InvalidTypeForEncoding

public InvalidTypeForEncoding(String $reason)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


InvalidTypeForEncodingHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP.CodecPackage
Class InvalidTypeForEncodingHelper

java.lang.Object
    extended by org.omg.IOP.CodecPackage.InvalidTypeForEncodingHelper
public abstract class InvalidTypeForEncodingHelper
extends Object

org/omg/IOP/CodecPackage/InvalidTypeForEncodingHelper.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableInterceptor/IOP.idl Thursday, June 12, 2003 9:59:14 PM GMT-08:00

Constructor Summary
InvalidTypeForEncodingHelper()
Method Summary
static InvalidTypeForEncoding | extract(Any a)
static String | id()
static void | insert(Any a, InvalidTypeForEncoding that)
static InvalidTypeForEncoding | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, InvalidTypeForEncoding value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

InvalidTypeForEncodingHelper

public InvalidTypeForEncodingHelper()
Method Detail

insert

public static void insert(Any a,
                          InvalidTypeForEncoding that)

extract

public static InvalidTypeForEncoding extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static InvalidTypeForEncoding read(InputStream istream)

write

public static void write(OutputStream ostream,
                         InvalidTypeForEncoding value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


org.omg.IOP.CodecPackage (Java 2 Platform SE v1.4.2)

 org.omg.IOP.CodecPackage
Classes
FormatMismatchHelper
InvalidTypeForEncodingHelper
TypeMismatchHelper
Exceptions
FormatMismatch
InvalidTypeForEncoding
TypeMismatch


org.omg.IOP.CodecPackage (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package org.omg.IOP.CodecPackage

This package is generated from the IOP::Codec IDL interface definition.

See:
Description

Class Summary
FormatMismatchHelper | org/omg/IOP/CodecPackage/FormatMismatchHelper.java .
InvalidTypeForEncodingHelper | org/omg/IOP/CodecPackage/InvalidTypeForEncodingHelper.java .
TypeMismatchHelper | org/omg/IOP/CodecPackage/TypeMismatchHelper.java .

Exception Summary
FormatMismatch | org/omg/IOP/CodecPackage/FormatMismatch.java .
InvalidTypeForEncoding | org/omg/IOP/CodecPackage/InvalidTypeForEncoding.java .
TypeMismatch | org/omg/IOP/CodecPackage/TypeMismatch.java .

Package org.omg.IOP.CodecPackage Description

This package is generated from the IOP::Codec IDL interface definition. It contains the Java representations of the IDL exceptions specified in IOP::Codec (as part of the Portable Interceptors specification). Please refer to that OMG specification for further details.

Package Specification

For a precise list of supported sections of official specifications with which the Java 2 Platform, Standard Edition, v.1.4 ORB complies, see Official Specifications for CORBA support in J2SE 1.4.

Since:
1.4
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


org.omg.IOP.CodecPackage Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package org.omg.IOP.CodecPackage

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class org.omg.IOP.CodecPackage.FormatMismatchHelper
    • class org.omg.IOP.CodecPackage.InvalidTypeForEncodingHelper
    • class java.lang.Throwable (implements java.io.Serializable)
      • class java.lang.Exception
        • class org.omg.CORBA.UserException (implements org.omg.CORBA.portable.IDLEntity)
          • class org.omg.IOP.CodecPackage.FormatMismatch
          • class org.omg.IOP.CodecPackage.InvalidTypeForEncoding
          • class org.omg.IOP.CodecPackage.TypeMismatch
    • class org.omg.IOP.CodecPackage.TypeMismatchHelper
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package org.omg.IOP.CodecPackage (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
org.omg.IOP.CodecPackage

Packages that use org.omg.IOP.CodecPackage
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.CodecPackage | This package is generated from the IOP::Codec IDL interface definition.

Classes in org.omg.IOP.CodecPackage used by org.omg.IOP
FormatMismatch
org/omg/IOP/CodecPackage/FormatMismatch.java .
InvalidTypeForEncoding
org/omg/IOP/CodecPackage/InvalidTypeForEncoding.java .
TypeMismatch
org/omg/IOP/CodecPackage/TypeMismatch.java .

Classes in org.omg.IOP.CodecPackage used by org.omg.IOP.CodecPackage
FormatMismatch
org/omg/IOP/CodecPackage/FormatMismatch.java .
InvalidTypeForEncoding
org/omg/IOP/CodecPackage/InvalidTypeForEncoding.java .
TypeMismatch
org/omg/IOP/CodecPackage/TypeMismatch.java .

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


TypeMismatch (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP.CodecPackage
Class TypeMismatch

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.IOP.CodecPackage.TypeMismatch
All Implemented Interfaces:
IDLEntity, Serializable
public final class TypeMismatch
extends UserException

org/omg/IOP/CodecPackage/TypeMismatch.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableInterceptor/IOP.idl Thursday, June 12, 2003 9:59:14 PM GMT-08:00

Constructor Summary
TypeMismatch()
TypeMismatch(String $reason)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

TypeMismatch

public TypeMismatch()

TypeMismatch

public TypeMismatch(String $reason)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


TypeMismatchHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.IOP.CodecPackage
Class TypeMismatchHelper

java.lang.Object
    extended by org.omg.IOP.CodecPackage.TypeMismatchHelper
public abstract class TypeMismatchHelper
extends Object

org/omg/IOP/CodecPackage/TypeMismatchHelper.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableInterceptor/IOP.idl Thursday, June 12, 2003 9:59:14 PM GMT-08:00

Constructor Summary
TypeMismatchHelper()
Method Summary
static TypeMismatch | extract(Any a)
static String | id()
static void | insert(Any a, TypeMismatch that)
static TypeMismatch | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, TypeMismatch value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

TypeMismatchHelper

public TypeMismatchHelper()
Method Detail

insert

public static void insert(Any a,
                          TypeMismatch that)

extract

public static TypeMismatch extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static TypeMismatch read(InputStream istream)

write

public static void write(OutputStream ostream,
                         TypeMismatch value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Uses of Class org.omg.IOP.CodecPackage.FormatMismatch (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.IOP.CodecPackage.FormatMismatch

Packages that use FormatMismatch
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.CodecPackage | This package is generated from the IOP::Codec IDL interface definition.

Uses of FormatMismatch in org.omg.IOP

Methods in org.omg.IOP that throw FormatMismatch
Any | CodecOperations.decode(byte[] data) Decodes the given byte array into an Any based on the encoding format effective for this Codec.
Any | CodecOperations.decode_value(byte[] data, TypeCode tc) Decodes the given byte array into an Any based on the given TypeCode and the encoding format effective for this Codec.

Uses of FormatMismatch in org.omg.IOP.CodecPackage

Methods in org.omg.IOP.CodecPackage that return FormatMismatch
static FormatMismatch | FormatMismatchHelper.extract(Any a)
static FormatMismatch | FormatMismatchHelper.read(InputStream istream)

Methods in org.omg.IOP.CodecPackage with parameters of type FormatMismatch
static void | FormatMismatchHelper.insert(Any a, FormatMismatch that)
static void | FormatMismatchHelper.write(OutputStream ostream, FormatMismatch value)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.IOP.CodecPackage.FormatMismatchHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.IOP.CodecPackage.FormatMismatchHelper

No usage of org.omg.IOP.CodecPackage.FormatMismatchHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.IOP.CodecPackage.InvalidTypeForEncoding (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.IOP.CodecPackage.InvalidTypeForEncoding

Packages that use InvalidTypeForEncoding
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.CodecPackage | This package is generated from the IOP::Codec IDL interface definition.

Uses of InvalidTypeForEncoding in org.omg.IOP

Methods in org.omg.IOP that throw InvalidTypeForEncoding
byte[] | CodecOperations.encode(Any data) Converts the given any into a byte array based on the encoding format effective for this Codec.
byte[] | CodecOperations.encode_value(Any data) Converts the given any into a byte array based on the encoding format effective for this Codec.

Uses of InvalidTypeForEncoding in org.omg.IOP.CodecPackage

Methods in org.omg.IOP.CodecPackage that return InvalidTypeForEncoding
static InvalidTypeForEncoding | InvalidTypeForEncodingHelper.extract(Any a)
static InvalidTypeForEncoding | InvalidTypeForEncodingHelper.read(InputStream istream)

Methods in org.omg.IOP.CodecPackage with parameters of type InvalidTypeForEncoding
static void | InvalidTypeForEncodingHelper.insert(Any a, InvalidTypeForEncoding that)
static void | InvalidTypeForEncodingHelper.write(OutputStream ostream, InvalidTypeForEncoding value)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.IOP.CodecPackage.InvalidTypeForEncodingHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.IOP.CodecPackage.InvalidTypeForEncodingHelper

No usage of org.omg.IOP.CodecPackage.InvalidTypeForEncodingHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.IOP.CodecPackage.TypeMismatch (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.IOP.CodecPackage.TypeMismatch

Packages that use TypeMismatch
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.CodecPackage | This package is generated from the IOP::Codec IDL interface definition.

Uses of TypeMismatch in org.omg.IOP

Methods in org.omg.IOP that throw TypeMismatch
 Any CodecOperations.decode_value(byte[] data, TypeCode tc)
Decodes the given byte array into an Any based on the given TypeCode and the encoding format effective for this Codec.

Uses of TypeMismatch in org.omg.IOP.CodecPackage

Methods in org.omg.IOP.CodecPackage that return TypeMismatch
static TypeMismatch | TypeMismatchHelper.extract(Any a)
static TypeMismatch | TypeMismatchHelper.read(InputStream istream)

Methods in org.omg.IOP.CodecPackage with parameters of type TypeMismatch
static void | TypeMismatchHelper.insert(Any a, TypeMismatch that)
static void | TypeMismatchHelper.write(OutputStream ostream, TypeMismatch value)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.IOP.CodecPackage.TypeMismatchHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.IOP.CodecPackage.TypeMismatchHelper

No usage of org.omg.IOP.CodecPackage.TypeMismatchHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


org.omg.Messaging (Java 2 Platform SE v1.4.2)

 org.omg.Messaging
Interfaces
SYNC_WITH_TRANSPORT
Classes
SyncScopeHelper


org.omg.Messaging (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

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.

See:
Description

Interface Summary
SYNC_WITH_TRANSPORT org/omg/Messaging/SYNC_WITH_TRANSPORT.java .

Class Summary
SyncScopeHelper Synchronization scope

Package org.omg.Messaging Description

This package contains the Messaging module specified in the OMG CORBA Messaging specification, http://cgi.omg.org/cgi-bin/doc?formal/99-10-07. Please refer to that OMG specification for further details.

Please note that we do not provide all parts of the Messaging module from the specification. We only provide those parts that are referenced as return values or parameter types in public APIs, most notably, Portable Interceptors.

Package Specification

For a precise list of supported sections of official specifications with which the Java 2 Platform, Standard Edition, v.1.4 ORB complies, see Official Specifications for CORBA support in J2SE 1.4.

Since:
1.4
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


org.omg.Messaging Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package org.omg.Messaging

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class org.omg.Messaging.SyncScopeHelper

Interface Hierarchy

  • interface org.omg.Messaging.SYNC_WITH_TRANSPORT
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package org.omg.Messaging (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
org.omg.Messaging

No usage of org.omg.Messaging

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


SYNC_WITH_TRANSPORT (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.Messaging
Interface SYNC_WITH_TRANSPORT

public interface SYNC_WITH_TRANSPORT

org/omg/Messaging/SYNC_WITH_TRANSPORT.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableInterceptor/Messaging.idl Thursday, June 12, 2003 9:59:17 PM GMT-08:00

Field Summary
static short value
Constant, defined in the Messaging spec, to define how far the request shall progress before control is returned to the client.

Field Detail

value

public static final short value
Constant, defined in the Messaging spec, to define how far the request shall progress before control is returned to the client.

See Also:
Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


SyncScopeHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.Messaging
Class SyncScopeHelper

java.lang.Object
    extended by org.omg.Messaging.SyncScopeHelper
public abstract class SyncScopeHelper
extends Object

Synchronization scope

Constructor Summary
SyncScopeHelper()
Method Summary
static short | extract(Any a)
static String | id()
static void | insert(Any a, short that)
static short | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, short value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

SyncScopeHelper

public SyncScopeHelper()
Method Detail

insert

public static void insert(Any a,
                          short that)

extract

public static short extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static short read(InputStream istream)

write

public static void write(OutputStream ostream,
                         short value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Uses of Interface org.omg.Messaging.SYNC_WITH_TRANSPORT (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.Messaging.SYNC_WITH_TRANSPORT

No usage of org.omg.Messaging.SYNC_WITH_TRANSPORT

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.Messaging.SyncScopeHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.Messaging.SyncScopeHelper

No usage of org.omg.Messaging.SyncScopeHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


ClientRequestInfo (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableInterceptor
Interface ClientRequestInfo

All Superinterfaces:
ClientRequestInfoOperations, IDLEntity, Object, RequestInfo, RequestInfoOperations, Serializable
public interface ClientRequestInfo
extends ClientRequestInfoOperations, RequestInfo, IDLEntity

Request Information, accessible to client-side request interceptors.

Some attributes and operations on ClientRequestInfo are not valid at all interception points. The following table shows the validity of each attribute or operation. If it is not valid, attempting to access it will result in a BAD_INV_ORDER being thrown with a standard minor code of 14.

 | send_request | send_poll | receive_reply | receive_exception | receive_other
Inherited from RequestInfo:
request_id | yes | yes | yes | yes | yes
operation | yes | yes | yes | yes | yes
arguments | yes1 | no | yes | no | no
exceptions | yes | no | yes | yes | yes
contexts | yes | no | yes | yes | yes
operation_context | yes | no | yes | yes | yes
result | no | no | yes | no | no
response_expected | yes | yes | yes | yes | yes
sync_scope | yes | no | yes | yes | yes
reply_status | no | no | yes | yes | yes
forward_reference | no | no | no | no | yes2
get_slot | yes | yes | yes | yes | yes
get_request_service_context | yes | no | yes | yes | yes
get_reply_service_context | no | no | yes | yes | yes
ClientRequestInfo-specific:
target | yes | yes | yes | yes | yes
effective_target | yes | yes | yes | yes | yes
effective_profile | yes | yes | yes | yes | yes
received_exception | no | no | no | yes | no
received_exception_id | no | no | no | yes | no
get_effective_component | yes | no | yes | yes | yes
get_effective_components | yes | no | yes | yes | yes
get_request_policy | yes | no | yes | yes | yes
add_request_service_context | yes | no | no | no | no
  1. When ClientRequestInfo is passed to send_request, there is an entry in the list for every argument, whether in, inout, or out. But only the in and inout arguments will be available.
  2. If the reply_status atribute is not LOCATION_FORWARD, accessing this attribute will throw BAD_INV_ORDER with a standard minor code of 14.

See Also:
ClientRequestInterceptor

Methods inherited from interface org.omg.PortableInterceptor.ClientRequestInfoOperations
add_request_service_context, effective_profile, effective_target, get_effective_component, get_effective_components, get_request_policy, received_exception_id, received_exception, target
Methods inherited from interface org.omg.PortableInterceptor.RequestInfoOperations
arguments, contexts, exceptions, forward_reference, get_reply_service_context, get_request_service_context, get_slot, operation_context, operation, reply_status, request_id, response_expected, result, sync_scope
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


ClientRequestInfoOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableInterceptor
Interface ClientRequestInfoOperations

All Superinterfaces:
RequestInfoOperations
All Known Subinterfaces:
ClientRequestInfo
public interface ClientRequestInfoOperations
extends RequestInfoOperations

Request Information, accessible to client-side request interceptors.

Some attributes and operations on ClientRequestInfo are not valid at all interception points. The following table shows the validity of each attribute or operation. If it is not valid, attempting to access it will result in a BAD_INV_ORDER being thrown with a standard minor code of 14.

 | send_request | send_poll | receive_reply | receive_exception | receive_other
Inherited from RequestInfo:
request_id | yes | yes | yes | yes | yes
operation | yes | yes | yes | yes | yes
arguments | yes1 | no | yes | no | no
exceptions | yes | no | yes | yes | yes
contexts | yes | no | yes | yes | yes
operation_context | yes | no | yes | yes | yes
result | no | no | yes | no | no
response_expected | yes | yes | yes | yes | yes
sync_scope | yes | no | yes | yes | yes
reply_status | no | no | yes | yes | yes
forward_reference | no | no | no | no | yes2
get_slot | yes | yes | yes | yes | yes
get_request_service_context | yes | no | yes | yes | yes
get_reply_service_context | no | no | yes | yes | yes
ClientRequestInfo-specific:
target | yes | yes | yes | yes | yes
effective_target | yes | yes | yes | yes | yes
effective_profile | yes | yes | yes | yes | yes
received_exception | no | no | no | yes | no
received_exception_id | no | no | no | yes | no
get_effective_component | yes | no | yes | yes | yes
get_effective_components | yes | no | yes | yes | yes
get_request_policy | yes | no | yes | yes | yes
add_request_service_context | yes | no | no | no | no
  1. When ClientRequestInfo is passed to send_request, there is an entry in the list for every argument, whether in, inout, or out. But only the in and inout arguments will be available.
  2. If the reply_status atribute is not LOCATION_FORWARD, accessing this attribute will throw BAD_INV_ORDER with a standard minor code of 14.

See Also:
ClientRequestInterceptor

Method Summary
void | add_request_service_context(ServiceContext service_context, boolean replace) Allows Interceptors to add service contexts to the request.
TaggedProfile | effective_profile() Returns the profile that will be used to send the request.
Object | effective_target() Returns the actual object on which the operation will be invoked.
TaggedComponent | get_effective_component(int id) Returns the IOP.TaggedComponent with the given ID from the profile selected for this request.
TaggedComponent[] | get_effective_components(int id) Returns an array of all tagged components with the given ID from the profile selected for this request.
Policy | get_request_policy(int type) Returns the given policy in effect for this operation.
String | received_exception_id() Returns the repository id of the exception to be returned to the client.
Any | received_exception() Returns an any which contains the exception to be returned to the client.
Object | target() Returns the object which the client called to perform the operation.
Methods inherited from interface org.omg.PortableInterceptor.RequestInfoOperations
arguments, contexts, exceptions, forward_reference, get_reply_service_context, get_request_service_context, get_slot, operation_context, operation, reply_status, request_id, response_expected, result, sync_scope

Method Detail

target

public Object target()
Returns the object which the client called to perform the operation.

See Also:
effective_target()

effective_target

public Object effective_target()
Returns the actual object on which the operation will be invoked. If the reply_status is LOCATION_FORWARD, then on subsequent requests, effective_target will contain the forwarded IOR while target will remain unchanged.

See Also:
target()

effective_profile

public TaggedProfile effective_profile()
Returns the profile that will be used to send the request. If a location forward has occurred for this operation's object and that object's profile changed accordingly, then this profile will be that located profile.

received_exception

public Any received_exception()
Returns an any which contains the exception to be returned to the client.

If the exception is a user exception which cannot be inserted into an any (e.g., it is unknown or the bindings don t provide the TypeCode), then this attribute will be an any containing the system exception UNKNOWN with a standard minor code of 1. However, the repository id of the exception is available in the received_exception_id attribute.

See Also:
received_exception_id()

received_exception_id

public String received_exception_id()
Returns the repository id of the exception to be returned to the client.

See Also:
received_exception(), PortableInterceptor package comments for limitations / unimplemented features

get_effective_component

public TaggedComponent get_effective_component(int id)
Returns the IOP.TaggedComponent with the given ID from the profile selected for this request.

If there is more than one component for a given component ID, it is undefined which component this operation returns. If there is more than one component for a given component ID, get_effective_components should be called instead.

Parameters:
id - The component id of the component which is to be returned.
Returns:
The IOP.TaggedComponent obtained with the given identifier.
Throws:
BAD_PARAM - thrown, with a standard minor code of 28, if no component exists for the given component ID.
See Also:
get_effective_components(int)

get_effective_components

public TaggedComponent[] get_effective_components(int id)
Returns an array of all tagged components with the given ID from the profile selected for this request.

Parameters:
id - The component id of the components which are to be returned.
Returns:
An array of TaggedComponent objects, each of which contains the given identifier.
Throws:
BAD_PARAM - thrown, with a standard minor code of 28, if no component exists for the given component ID.
See Also:
get_effective_component(int)

get_request_policy

public Policy get_request_policy(int type)
Returns the given policy in effect for this operation.

Parameters:
type - The policy type which specifies the policy to be returned.
Returns:
The CORBA.Policy obtained with the given type.
Throws:
INV_POLICY - thrown, with a standard minor code of 1, if the policy type is not valid either because the specified type is not supported by this ORB or because a policy object of that type is not associated with this Object
See Also:
PortableInterceptor package comments for limitations / unimplemented features

add_request_service_context

public void add_request_service_context(ServiceContext service_context,
                                        boolean replace)
Allows Interceptors to add service contexts to the request.

There is no declaration of the order of the service contexts. They may or may not appear in the order that they are added.

Parameters:
service_context - The IOP.ServiceContext to be added to the request.
replace - Indicates the behavior of this operation when a service context already exists with the given ID. If false, then BAD_INV_ORDER with a standard minor code of 15 is thrown. If true, then the existing service context is replaced by the new one.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ClientRequestInterceptor (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableInterceptor
Interface ClientRequestInterceptor

All Superinterfaces:
ClientRequestInterceptorOperations, IDLEntity, Interceptor, InterceptorOperations, Object, Serializable
public interface ClientRequestInterceptor
extends ClientRequestInterceptorOperations, Interceptor, IDLEntity

Client-side request interceptor.

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. There are two types of request Interceptors: client-side and server-side.

To write a client-side Interceptor, implement the ClientRequestInterceptor interface.

See Also:
ClientRequestInfo

Methods inherited from interface org.omg.PortableInterceptor.ClientRequestInterceptorOperations
receive_exception, receive_other, receive_reply, send_poll, send_request
Methods inherited from interface org.omg.PortableInterceptor.InterceptorOperations
destroy, name
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ClientRequestInterceptorOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableInterceptor
Interface ClientRequestInterceptorOperations

All Superinterfaces:
InterceptorOperations
All Known Subinterfaces:
ClientRequestInterceptor
public interface ClientRequestInterceptorOperations
extends InterceptorOperations

Client-side request interceptor.

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. There are two types of request Interceptors: client-side and server-side.

To write a client-side Interceptor, implement the ClientRequestInterceptor interface.

See Also:
ClientRequestInfo

Method Summary
void | receive_exception(ClientRequestInfo ri) Indicates to the interceptor that an exception occurred.
void | receive_other(ClientRequestInfo ri) Allows an Interceptor to query the information available when a request results in something other than a normal reply or an exception.
void | receive_reply(ClientRequestInfo ri) 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.
void | send_poll(ClientRequestInfo ri) Allows an Interceptor to query information during a Time-Independent Invocation (TII) polling get reply sequence.
void | send_request(ClientRequestInfo ri) Allows an Interceptor to query request information and modify the service context before the request is sent to the server.
Methods inherited from interface org.omg.PortableInterceptor.InterceptorOperations
destroy, name

Method Detail

send_request

public void send_request(ClientRequestInfo ri)
                  throws ForwardRequest
Allows an Interceptor to query request information and modify the service context before the request is sent to the server.

This interception point may throw a system exception. If it does, no other Interceptors' send_request operations are called. Those Interceptors on the Flow Stack are popped and their receive_exception interception points are called. This interception point may also throw a ForwardRequest exception. If an Interceptor throws this exception, no other Interceptors' send_request operations are called. Those Interceptors on the Flow Stack are popped and their receive_other interception points are called.

Compliant Interceptors shall properly follow completion_status semantics if they throw a system exception from this interception point. The completion_status shall be COMPLETED_NO.

Parameters:
ri - Information about the current request being intercepted.
Throws:
ForwardRequest - If thrown, indicates to the ORB that a retry of the request should occur with the new object given in the exception.

send_poll

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

With TII, an application may poll for a response to a request sent previously by the polling client or some other client. This poll is reported to Interceptors through the send_poll interception point and the response is returned through the receive_reply or receive_exception interception points. If the response is not available before the poll time-out expires, the system exception TIMEOUT is thrown and receive_exception is called with this exception.

This interception point may throw a system exception. If it does, no other Interceptors' send_poll operations are called. Those Interceptors on the Flow Stack are popped and their receive_exception interception points are called.

Compliant Interceptors shall properly follow completion_status semantics if they throw a system exception from this interception point. The completion_status shall be COMPLETED_NO.

Parameters:
ri - Information about the current request being intercepted.
Throws:
TIMEOUT - thrown if the response is not available before the poll time-out expires

receive_reply

public void receive_reply(ClientRequestInfo ri)
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.

This interception point may throw a system exception. If it does, no other Interceptors' receive_reply operations are called. The remaining Interceptors in the Flow Stack shall have their receive_exception interception point called.

Compliant Interceptors shall properly follow completion_status semantics if they throw a system exception from this interception point. The completion_status shall be COMPLETED_YES.

Parameters:
ri - Information about the current request being intercepted.

receive_exception

public void receive_exception(ClientRequestInfo ri)
                       throws ForwardRequest
Indicates to the interceptor that an exception occurred. Allows an Interceptor to query the exception's information before it is thrown to the client.

This interception point may throw a system exception. This has the effect of changing the exception which successive Interceptors popped from the Flow Stack receive on their calls to receive_exception. The exception thrown to the client will be the last exception thrown by an Interceptor, or the original exception if no Interceptor changes the exception.

This interception point may also throw a ForwardRequest exception. If an Interceptor throws this exception, no other Interceptors' receive_exception operations are called. The remaining Interceptors in the Flow Stack are popped and have their receive_other interception point called.

If the completion_status of the exception is not COMPLETED_NO, then it is inappropriate for this interception point to throw a ForwardRequest exception. The request s at-most-once semantics would be lost.

Compliant Interceptors shall properly follow completion_status semantics if they throw a system exception from this interception point. If the original exception is a system exception, the completion_status of the new exception shall be the same as on the original. If the original exception is a user exception, then the completion_status of the new exception shall be COMPLETED_YES.

Under some conditions, depending on what policies are in effect, an exception (such as COMM_FAILURE) may result in a retry of the request. While this retry is a new request with respect to Interceptors, there is one point of correlation between the original request and the retry: because control has not returned to the client, the PortableInterceptor.Current for both the original request and the retrying request is the same.

Parameters:
ri - Information about the current request being intercepted.
Throws:
ForwardRequest - If thrown, indicates to the ORB that a retry of the request should occur with the new object given in the exception.

receive_other

public void receive_other(ClientRequestInfo ri)
                   throws ForwardRequest
Allows an Interceptor to query the information available when a request results in something other than a normal reply or an exception. For example, a request could result in a retry (e.g., a GIOP Reply with a LOCATION_FORWARD status was received); or on asynchronous calls, the reply does not immediately follow the request, but control shall return to the client and an ending interception point shall be called.

For retries, depending on the policies in effect, a new request may or may not follow when a retry has been indicated. If a new request does follow, while this request is a new request, with respect to Interceptors, there is one point of correlation between the original request and the retry: because control has not returned to the client, the request scoped PortableInterceptor.Current for both the original request and the retrying request is the same.

This interception point may throw a system exception. If it does, no other Interceptors' receive_other operations are called. The remaining Interceptors in the Flow Stack are popped and have their receive_exception interception point called.

This interception point may also throw a ForwardRequest exception. If an Interceptor throws this exception, successive Interceptors' receive_other operations are called with the new information provided by the ForwardRequest exception.

Compliant Interceptors shall properly follow completion_status semantics if they throw a system exception from this interception point. The completion_status shall be COMPLETED_NO. If the target invocation had completed, this interception point would not be called.

Parameters:
ri - Information about the current request being intercepted.
Throws:
ForwardRequest - If thrown, indicates to the ORB that a retry of the request should occur with the new object given in the exception.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Current (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableInterceptor
Interface Current

All Superinterfaces:
Current, CurrentOperations, CurrentOperations, IDLEntity, Object, Serializable
public interface Current
extends CurrentOperations, Current, IDLEntity

Portable Interceptors Current (also known as PICurrent) is merely a slot table, the slots of which are used by each service to transfer their context data between their context and the request's or reply's service context. Each service which wishes to use PICurrent reserves a slot or slots at initialization time and uses those slots during the processing of requests and replies.

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.

Methods inherited from interface org.omg.PortableInterceptor.CurrentOperations
get_slot, set_slot
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


CurrentHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableInterceptor
Class CurrentHelper

java.lang.Object
    extended by org.omg.PortableInterceptor.CurrentHelper
public abstract class CurrentHelper
extends Object

Portable Interceptors Current (also known as PICurrent) is merely a slot table, the slots of which are used by each service to transfer their context data between their context and the request's or reply's service context. Each service which wishes to use PICurrent reserves a slot or slots at initialization time and uses those slots during the processing of requests and replies.

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.

Constructor Summary
CurrentHelper()
Method Summary
static Current | extract(Any a)
static String | id()
static void | insert(Any a, Current that)
static Current | narrow(Object obj)
static Current | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, Current value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

CurrentHelper

public CurrentHelper()
Method Detail

insert

public static void insert(Any a,
                          Current that)

extract

public static Current extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static Current read(InputStream istream)

write

public static void write(OutputStream ostream,
                         Current value)

narrow

public static Current narrow(Object obj)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


CurrentOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableInterceptor
Interface CurrentOperations

All Superinterfaces:
CurrentOperations
All Known Subinterfaces:
Current
public interface CurrentOperations
extends CurrentOperations

Portable Interceptors Current (also known as PICurrent) is merely a slot table, the slots of which are used by each service to transfer their context data between their context and the request's or reply's service context. Each service which wishes to use PICurrent reserves a slot or slots at initialization time and uses those slots during the processing of requests and replies.

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.

Method Summary
Any | get_slot(int id) Retrieves the slot data the application set in PICurrent via get_slot.
void | set_slot(int id, Any data) Sets data in a slot.

Method Detail

get_slot

public Any get_slot(int id)
             throws InvalidSlot
Retrieves the slot data the application set in PICurrent via get_slot. The data is in the form of an Any.

If the given slot has not been set, an Any containing a type code with a TCKind value of tk_null and no value is returned.

Parameters:
id - The SlotId of the slot from which the data will be returned.
Returns:
The data, in the form of an Any, of the given slot identifier.
Throws:
InvalidSlot - thrown if get_slot is called on a slot that has not been allocated.
BAD_INV_ORDER - thrown if get_slot is called from within an ORB initializer

set_slot

public void set_slot(int id,
                     Any data)
              throws InvalidSlot
Sets data in a slot. The data is in the form of an Any. If data already exists in that slot, it is overridden.

Parameters:
id - The SlotId of the slot to which the data will be set.
data - The data, in the form of an Any, which will be set to the identified slot.
Throws:
InvalidSlot - thrown if set_slot is called on a slot that has not been allocated.
BAD_INV_ORDER - thrown if set_slot is called from within an ORB initializer.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ForwardRequest (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableInterceptor
Class ForwardRequest

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.PortableInterceptor.ForwardRequest
All Implemented Interfaces:
IDLEntity, Serializable
public final class ForwardRequest
extends UserException

org/omg/PortableInterceptor/ForwardRequest.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableInterceptor/Interceptors.idl Thursday, June 12, 2003 9:59:19 PM GMT-08:00

Field Summary
 Object forward
The new object to forward the request to.
Constructor Summary
ForwardRequest()
ForwardRequest(Object _forward)
ForwardRequest(String $reason, Object _forward)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

forward

public Object forward
The new object to forward the request to.

Constructor Detail

ForwardRequest

public ForwardRequest()

ForwardRequest

public ForwardRequest(Object _forward)

ForwardRequest

public ForwardRequest(String $reason,
                      Object _forward)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


ForwardRequestHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableInterceptor
Class ForwardRequestHelper

java.lang.Object
    extended by org.omg.PortableInterceptor.ForwardRequestHelper
public abstract class ForwardRequestHelper
extends Object

org/omg/PortableInterceptor/ForwardRequestHelper.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableInterceptor/Interceptors.idl Thursday, June 12, 2003 9:59:19 PM GMT-08:00

Constructor Summary
ForwardRequestHelper()
Method Summary
static ForwardRequest | extract(Any a)
static String | id()
static void | insert(Any a, ForwardRequest that)
static ForwardRequest | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, ForwardRequest value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ForwardRequestHelper

public ForwardRequestHelper()
Method Detail

insert

public static void insert(Any a,
                          ForwardRequest that)

extract

public static ForwardRequest extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static ForwardRequest read(InputStream istream)

write

public static void write(OutputStream ostream,
                         ForwardRequest value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Interceptor (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableInterceptor
Interface Interceptor

All Superinterfaces:
IDLEntity, InterceptorOperations, Object, Serializable
All Known Subinterfaces:
ClientRequestInterceptor, IORInterceptor, ServerRequestInterceptor
public interface Interceptor
extends InterceptorOperations, Object, IDLEntity

All Portable Interceptors implement Interceptor.

Methods inherited from interface org.omg.PortableInterceptor.InterceptorOperations
destroy, name
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


InterceptorOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableInterceptor
Interface InterceptorOperations

All Known Subinterfaces:
ClientRequestInterceptor, ClientRequestInterceptorOperations, Interceptor, IORInterceptor, IORInterceptorOperations, ServerRequestInterceptor, ServerRequestInterceptorOperations
public interface InterceptorOperations

All Portable Interceptors implement Interceptor.

Method Summary
void | destroy() Provides an opportunity to destroy this interceptor.
String | name() Returns the name of the interceptor.

Method Detail

name

public String name()
Returns the name of the interceptor.

Each Interceptor may have a name that may be used administratively to order the lists of Interceptors. Only one Interceptor of a given name can be registered with the ORB for each Interceptor type. An Interceptor may be anonymous, i.e., have an empty string as the name attribute. Any number of anonymous Interceptors may be registered with the ORB.

Returns:
the name of the interceptor.

destroy

public void destroy()
Provides an opportunity to destroy this interceptor. The destroy method is called during ORB.destroy. When an application calls ORB.destroy, the ORB:
  1. waits for all requests in progress to complete
  2. calls the Interceptor.destroy operation for each interceptor
  3. completes destruction of the ORB
Method invocations from within Interceptor.destroy on object references for objects implemented on the ORB being destroyed result in undefined behavior. However, method invocations on objects implemented on an ORB other than the one being destroyed are permitted. (This means that the ORB being destroyed is still capable of acting as a client, but not as a server.)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


InvalidSlot (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableInterceptor
Class InvalidSlot

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.PortableInterceptor.InvalidSlot
All Implemented Interfaces:
IDLEntity, Serializable
public final class InvalidSlot
extends UserException

org/omg/PortableInterceptor/InvalidSlot.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableInterceptor/Interceptors.idl Thursday, June 12, 2003 9:59:19 PM GMT-08:00

Constructor Summary
InvalidSlot()
InvalidSlot(String $reason)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

InvalidSlot

public InvalidSlot()

InvalidSlot

public InvalidSlot(String $reason)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


InvalidSlotHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableInterceptor
Class InvalidSlotHelper

java.lang.Object
    extended by org.omg.PortableInterceptor.InvalidSlotHelper
public abstract class InvalidSlotHelper
extends Object

org/omg/PortableInterceptor/InvalidSlotHelper.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableInterceptor/Interceptors.idl Thursday, June 12, 2003 9:59:19 PM GMT-08:00

Constructor Summary
InvalidSlotHelper()
Method Summary
static InvalidSlot | extract(Any a)
static String | id()
static void | insert(Any a, InvalidSlot that)
static InvalidSlot | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, InvalidSlot value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

InvalidSlotHelper

public InvalidSlotHelper()
Method Detail

insert

public static void insert(Any a,
                          InvalidSlot that)

extract

public static InvalidSlot extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static InvalidSlot read(InputStream istream)

write

public static void write(OutputStream ostream,
                         InvalidSlot value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


IORInfo (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableInterceptor
Interface IORInfo

All Superinterfaces:
IDLEntity, IORInfoOperations, Object, Serializable
public interface IORInfo
extends IORInfoOperations, Object, IDLEntity

Provides the server-side ORB service with access to the applicable policies during IOR construction and the ability to add components. The ORB passes an instance of its implementation of this interface as a parameter to IORInterceptor.establish_components.

See Also:
IORInterceptor

Methods inherited from interface org.omg.PortableInterceptor.IORInfoOperations
add_ior_component_to_profile, add_ior_component, get_effective_policy
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


IORInfoOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableInterceptor
Interface IORInfoOperations

All Known Subinterfaces:
IORInfo
public interface IORInfoOperations

Provides the server-side ORB service with access to the applicable policies during IOR construction and the ability to add components. The ORB passes an instance of its implementation of this interface as a parameter to IORInterceptor.establish_components.

See Also:
IORInterceptor

Method Summary
void | add_ior_component_to_profile(TaggedComponent tagged_component, int profile_id) A portable ORB service implementation calls add_ior_component_to_profile from its implementation of establish_components to add a tagged component to the set which will be included when constructing IORs.
void | add_ior_component(TaggedComponent tagged_component) A portable ORB service implementation calls add_ior_component from its implementation of establish_components to add a tagged component to the set which will be included when constructing IORs.
Policy | get_effective_policy(int type) Allows an ORB service implementation to determine what server side policy of a particular type is in effect for an IOR being constructed.

Method Detail

get_effective_policy

public Policy get_effective_policy(int type)
Allows an ORB service implementation to determine what server side policy of a particular type is in effect for an IOR being constructed. When the IOR being constructed is for an object implemented using a POA, all Policy objects passed to the PortableServer.POA.create_POA call that created that POA are accessable via get_effective_policy.

If a policy for the given type is not known to the ORB, then this operation will throw INV_POLICY with a standard minor code of 2.

Parameters:
type - an int specifying the type of policy to return.
Returns:
The effective CORBA.Policy object of the requested type. If the given policy type is known, but no policy of that type is in effect, then this operation will return a nil object reference.

add_ior_component

public void add_ior_component(TaggedComponent tagged_component)
A portable ORB service implementation calls add_ior_component from its implementation of establish_components to add a tagged component to the set which will be included when constructing IORs. The components in this set will be included in all profiles.

Any number of components may exist with the same component ID.

add_ior_component_to_profile

public void add_ior_component_to_profile(TaggedComponent tagged_component,
                                         int profile_id)
A portable ORB service implementation calls add_ior_component_to_profile from its implementation of establish_components to add a tagged component to the set which will be included when constructing IORs. The components in this set will be included in the specified profile.

Any number of components may exist with the same component ID.

Parameters:
profile_id - The profile id of the profile to which this component will be added.
Throws:
BAD_PARAM - thrown, with a standard minor code of 29, if the given profile ID does not define a known profile or it is impossible to add components to that profile.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


IORInterceptor (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableInterceptor
Interface IORInterceptor

All Superinterfaces:
IDLEntity, Interceptor, InterceptorOperations, IORInterceptorOperations, Object, Serializable
public interface IORInterceptor
extends IORInterceptorOperations, Interceptor, IDLEntity

Interceptor used to establish tagged components in the profiles within an IOR.

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.

See Also:
IORInfo

Methods inherited from interface org.omg.PortableInterceptor.IORInterceptorOperations
establish_components
Methods inherited from interface org.omg.PortableInterceptor.InterceptorOperations
destroy, name
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


IORInterceptorOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableInterceptor
Interface IORInterceptorOperations

All Superinterfaces:
InterceptorOperations
All Known Subinterfaces:
IORInterceptor
public interface IORInterceptorOperations
extends InterceptorOperations

Interceptor used to establish tagged components in the profiles within an IOR.

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.

See Also:
IORInfo

Method Summary
 void establish_components(IORInfo info)
A server side ORB calls the establish_components operation on all registered IORInterceptor instances when it is assembling the list of components that will be included in the profile or profiles of an object reference.
Methods inherited from interface org.omg.PortableInterceptor.InterceptorOperations
destroy, name

Method Detail

establish_components

public void establish_components(IORInfo info)
A server side ORB calls the establish_components operation on all registered IORInterceptor instances when it is assembling the list of components that will be included in the profile or profiles of an object reference. This operation is not necessarily called for each individual object reference. For example, the POA specifies policies at POA granularity and therefore, this operation might be called once per POA rather than once per object. In any case, establish_components is guaranteed to be called at least once for each distinct set of server policies.

An implementation of establish_components must not throw exceptions. If it does, the ORB shall ignore the exception and proceed to call the next IOR Interceptor's establish_components operation.

Parameters:
info - The IORInfo instance used by the ORB service to query applicable policies and add components to be included in the generated IORs.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


LOCATION_FORWARD (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableInterceptor
Interface LOCATION_FORWARD

public interface LOCATION_FORWARD

org/omg/PortableInterceptor/LOCATION_FORWARD.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableInterceptor/Interceptors.idl Thursday, June 12, 2003 9:59:19 PM GMT-08:00

Field Summary
static short value
Indicates a LocationForward reply status.

Field Detail

value

public static final short value
Indicates a LocationForward reply status. One possible value for RequestInfo.reply_status.

See Also:
RequestInfoOperations.reply_status(), SUCCESSFUL, SYSTEM_EXCEPTION, USER_EXCEPTION, TRANSPORT_RETRY, Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ORBInitializer (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableInterceptor
Interface ORBInitializer

All Superinterfaces:
IDLEntity, Object, ORBInitializerOperations, Serializable
public interface ORBInitializer
extends ORBInitializerOperations, Object, IDLEntity

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.

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.

Registering ORB Initializers in Java

ORBInitializers are registered via Java ORB properties.

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
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.

Example

A client-side logging service written by company X, for example, may have the following ORBInitializer implementation:

 package com.x.logging;

 import org.omg.PortableInterceptor.Interceptor;
 import org.omg.PortableInterceptor.ORBInitializer;
 import org.omg.PortableInterceptor.ORBInitInfo;

 public class LoggingService implements ORBInitializer {
     void pre_init( ORBInitInfo info ) {
         // Instantiate the Logging Service s Interceptor.
         Interceptor interceptor = new LoggingInterceptor();

         // Register the Logging Service s Interceptor.
         info.add_client_request_interceptor( interceptor );
     }

     void post_init( ORBInitInfo info ) {
         // This service does not need two init points.
     }
 }
To run a program called MyApp using this logging service, the user could type:
java -Dorg.omg.PortableInterceptor.ORBInitializerClass.com.x.Logging.LoggingService MyApp

Notes about Registering Interceptors

Request Interceptors are registered on a per-ORB basis.

To achieve virtual per-object Interceptors, query the policies on the target from within the interception points to determine whether they should do any work.

To achieve virtual per-POA Interceptors, instantiate each POA with a different ORB. 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.

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.

See Also:
ORBInitInfo

Methods inherited from interface org.omg.PortableInterceptor.ORBInitializerOperations
post_init, pre_init
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ORBInitializerOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableInterceptor
Interface ORBInitializerOperations

All Known Subinterfaces:
ORBInitializer
public interface ORBInitializerOperations

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.

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.

Registering ORB Initializers in Java

ORBInitializers are registered via Java ORB properties.

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
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.

Example

A client-side logging service written by company X, for example, may have the following ORBInitializer implementation:

 package com.x.logging;

 import org.omg.PortableInterceptor.Interceptor;
 import org.omg.PortableInterceptor.ORBInitializer;
 import org.omg.PortableInterceptor.ORBInitInfo;

 public class LoggingService implements ORBInitializer {
     void pre_init( ORBInitInfo info ) {
         // Instantiate the Logging Service s Interceptor.
         Interceptor interceptor = new LoggingInterceptor();

         // Register the Logging Service s Interceptor.
         info.add_client_request_interceptor( interceptor );
     }

     void post_init( ORBInitInfo info ) {
         // This service does not need two init points.
     }
 }
To run a program called MyApp using this logging service, the user could type:
java -Dorg.omg.PortableInterceptor.ORBInitializerClass.com.x.Logging.LoggingService MyApp

Notes about Registering Interceptors

Request Interceptors are registered on a per-ORB basis.

To achieve virtual per-object Interceptors, query the policies on the target from within the interception points to determine whether they should do any work.

To achieve virtual per-POA Interceptors, instantiate each POA with a different ORB. 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.

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.

See Also:
ORBInitInfo

Method Summary
void | post_init(ORBInitInfo info) Called during ORB initialization.
void | pre_init(ORBInitInfo info) Called during ORB initialization.

Method Detail

pre_init

public void pre_init(ORBInitInfo info)
Called during ORB initialization. If it is expected that initial services registered by an interceptor will be used by other interceptors, then those initial services shall be registered at this point via calls to ORBInitInfo.register_initial_reference.

Parameters:
info - provides initialization attributes and operations by which Interceptors can be registered.

post_init

public void post_init(ORBInitInfo info)
Called during ORB initialization. If a service must resolve initial references as part of its initialization, it can assume that all initial references will be available at this point.

Calling the post_init operations is not the final task of ORB initialization. The final task, following the post_init calls, is attaching the lists of registered interceptors to the ORB. Therefore, the ORB does not contain the interceptors during calls to post_init. If an ORB-mediated call is made from within post_init, no request interceptors will be invoked on that call. Likewise, if an operation is performed which causes an IOR to be created, no IOR interceptors will be invoked.

Parameters:
info - provides initialization attributes and operations by which Interceptors can be registered.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ORBInitInfo (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableInterceptor
Interface ORBInitInfo

All Superinterfaces:
IDLEntity, Object, ORBInitInfoOperations, Serializable
public interface ORBInitInfo
extends ORBInitInfoOperations, Object, IDLEntity

Passed to each ORBInitializer, allowing it to to register interceptors and perform other duties while the ORB is initializing.

The ORBInitInfo object is only valid during ORB.init. If a service keeps a reference to its ORBInitInfo object and tries to use it after ORB.init returns, the object no longer exists and an OBJECT_NOT_EXIST exception shall be thrown.

See Also:
ORBInitializer

Methods inherited from interface org.omg.PortableInterceptor.ORBInitInfoOperations
add_client_request_interceptor, add_ior_interceptor, add_server_request_interceptor, allocate_slot_id, arguments, codec_factory, orb_id, register_initial_reference, register_policy_factory, resolve_initial_references
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ORBInitInfoOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableInterceptor
Interface ORBInitInfoOperations

All Known Subinterfaces:
ORBInitInfo
public interface ORBInitInfoOperations

Passed to each ORBInitializer, allowing it to to register interceptors and perform other duties while the ORB is initializing.

The ORBInitInfo object is only valid during ORB.init. If a service keeps a reference to its ORBInitInfo object and tries to use it after ORB.init returns, the object no longer exists and an OBJECT_NOT_EXIST exception shall be thrown.

See Also:
ORBInitializer

Method Summary
void | add_client_request_interceptor(ClientRequestInterceptor interceptor) Used to add a client-side request Interceptor to the list of client-side request Interceptors.
void | add_ior_interceptor(IORInterceptor interceptor) Used to add an IOR Interceptor to the list of IOR Interceptors.
void | add_server_request_interceptor(ServerRequestInterceptor interceptor) Used to add a server-side request Interceptor to the list of server-side request Interceptors.
int | allocate_slot_id() Called to allocate a slot on PortableInterceptor.Current.
String[] | arguments() Returns the arguments passed to ORB.init.
CodecFactory | codec_factory() Returns the IOP.CodecFactory.
String | orb_id() Returns the ID of the ORB being initialized.
void | register_initial_reference(String id, Object obj) Identical to ORB.register_initial_reference.
void | register_policy_factory(int type, PolicyFactory policy_factory) Registers a PolicyFactory for the given PolicyType.
Object | resolve_initial_references(String id) Identical to ORB.resolve_initial_references.

Method Detail

arguments

public String[] arguments()
Returns the arguments passed to ORB.init. They may or may not contain the ORB's arguments.

orb_id

public String orb_id()
Returns the ID of the ORB being initialized.

codec_factory

public CodecFactory codec_factory()
Returns the IOP.CodecFactory. The CodecFactory is normally obtained via a call to ORB.resolve_initial_references( "CodecFactory" ), but since the ORB is not yet available and Interceptors, particularly when processing service contexts, will require a Codec, a means of obtaining a Codec is necessary during ORB initialization.

register_initial_reference

public void register_initial_reference(String id,
                                       Object obj)
                                throws InvalidName
Identical to ORB.register_initial_reference. This same functionality exists here because the ORB, not yet fully initialized, is not yet available but initial references may need to be registered as part of Interceptor registration. The only difference is that the version of this operation on the ORB uses PIDL (CORBA.ORB.ObjectId) and (CORBA.ORB.InvalidName) whereas the version in this interface uses IDL defined in this interface; the semantics are identical.

Throws:
InvalidName

resolve_initial_references

public Object resolve_initial_references(String id)
                                  throws InvalidName
Identical to ORB.resolve_initial_references. This same functionality exists here because the ORB, not yet fully initialized, is not yet available but initial references may be required from the ORB as part of Interceptor registration. The only difference is that the version of this operation on the ORB uses PIDL (CORBA::ORB::ObjectId and CORBA::ORB::InvalidName) whereas the version in this interface uses IDL defined in this interface; the semantics are identical.

This operation is only valid during post_init.

Throws:
InvalidName

add_client_request_interceptor

public void add_client_request_interceptor(ClientRequestInterceptor interceptor)
                                    throws DuplicateName
Used to add a client-side request Interceptor to the list of client-side request Interceptors.

Parameters:
interceptor - The ClientRequestInterceptor to be added.
Throws:
DuplicateName - thrown if a client-side request Interceptor has already been registered with this Interceptor's name.

add_server_request_interceptor

public void add_server_request_interceptor(ServerRequestInterceptor interceptor)
                                    throws DuplicateName
Used to add a server-side request Interceptor to the list of server-side request Interceptors.

Parameters:
interceptor - The ServerRequestInterceptor to be added.
Throws:
DuplicateName - thrown if a server-side request Interceptor has already been registered with this Interceptor's name

add_ior_interceptor

public void add_ior_interceptor(IORInterceptor interceptor)
                         throws DuplicateName
Used to add an IOR Interceptor to the list of IOR Interceptors.

Parameters:
interceptor - The IORInterceptor to be added.
Throws:
DuplicateName - thrown if an IOR Interceptor has already been registered with this Interceptor's name.

allocate_slot_id

public int allocate_slot_id()
Called to allocate a slot on PortableInterceptor.Current.

Note that while slot id's can be allocated within an ORB initializer, the slots themselves cannot be initialized.

Returns:
The index to the slot which has been allocated.
Throws:
BAD_INV_ORDER - thrown, with a standard minor code of 14, if set_slot or get_slot is called on the PICurrent within an ORB initializer.
See Also:
Current

register_policy_factory

public void register_policy_factory(int type,
                                    PolicyFactory policy_factory)
Registers a PolicyFactory for the given PolicyType.

Parameters:
type - The policy type that the given PolicyFactory serves.
policy_factory - The factory for the given policy type.
Throws:
BAD_INV_ORDER - thrown, with a standard minor code of 16, if a PolicyFactory already exists for the given PolicyType.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


org.omg.PortableInterceptor (Java 2 Platform SE v1.4.2)

 org.omg.PortableInterceptor
Interfaces
ClientRequestInfo
ClientRequestInfoOperations
ClientRequestInterceptor
ClientRequestInterceptorOperations
Current
CurrentOperations
Interceptor
InterceptorOperations
IORInfo
IORInfoOperations
IORInterceptor
IORInterceptorOperations
LOCATION_FORWARD
ORBInitializer
ORBInitializerOperations
ORBInitInfo
ORBInitInfoOperations
PolicyFactory
PolicyFactoryOperations
RequestInfo
RequestInfoOperations
ServerRequestInfo
ServerRequestInfoOperations
ServerRequestInterceptor
ServerRequestInterceptorOperations
SUCCESSFUL
SYSTEM_EXCEPTION
TRANSPORT_RETRY
USER_EXCEPTION
Classes
CurrentHelper
ForwardRequestHelper
InvalidSlotHelper
Exceptions
ForwardRequest
InvalidSlot


org.omg.PortableInterceptor (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

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.

See:
Description

Interface Summary
ClientRequestInfo | Request Information, accessible to client-side request interceptors.
ClientRequestInfoOperations | Request Information, accessible to client-side request interceptors.
ClientRequestInterceptor | Client-side request interceptor.
ClientRequestInterceptorOperations | Client-side request interceptor.
Current | Portable Interceptors Current (also known as PICurrent) is merely a slot table, the slots of which are used by each service to transfer their context data between their context and the request's or reply's service context.
CurrentOperations | Portable Interceptors Current (also known as PICurrent) is merely a slot table, the slots of which are used by each service to transfer their context data between their context and the request's or reply's service context.
Interceptor | All Portable Interceptors implement Interceptor.
InterceptorOperations | All Portable Interceptors implement Interceptor.
IORInfo | Provides the server-side ORB service with access to the applicable policies during IOR construction and the ability to add components.
IORInfoOperations | Provides the server-side ORB service with access to the applicable policies during IOR construction and the ability to add components.
IORInterceptor | Interceptor used to establish tagged components in the profiles within an IOR.
IORInterceptorOperations | Interceptor used to establish tagged components in the profiles within an IOR.
LOCATION_FORWARD | org/omg/PortableInterceptor/LOCATION_FORWARD.java .
ORBInitializer | Facilitates interceptor registration and ORB initialization.
ORBInitializerOperations | Facilitates interceptor registration and ORB initialization.
ORBInitInfo | Passed to each ORBInitializer, allowing it to to register interceptors and perform other duties while the ORB is initializing.
ORBInitInfoOperations | Passed to each ORBInitializer, allowing it to to register interceptors and perform other duties while the ORB is initializing.
PolicyFactory | Enables policy types to be constructed using CORBA.ORB.create_policy.
PolicyFactoryOperations | Enables policy types to be constructed using CORBA.ORB.create_policy.
RequestInfo | Request Information, accessible to Interceptors.
RequestInfoOperations | Request Information, accessible to Interceptors.
ServerRequestInfo | Request Information, accessible to server-side request interceptors.
ServerRequestInfoOperations | Request Information, accessible to server-side request interceptors.
ServerRequestInterceptor | Server-side request interceptor.
ServerRequestInterceptorOperations | Server-side request interceptor.
SUCCESSFUL | org/omg/PortableInterceptor/SUCCESSFUL.java .
SYSTEM_EXCEPTION | org/omg/PortableInterceptor/SYSTEM_EXCEPTION.java .
TRANSPORT_RETRY | org/omg/PortableInterceptor/TRANSPORT_RETRY.java .
USER_EXCEPTION | org/omg/PortableInterceptor/USER_EXCEPTION.java .

Class Summary
CurrentHelper | Portable Interceptors Current (also known as PICurrent) is merely a slot table, the slots of which are used by each service to transfer their context data between their context and the request's or reply's service context.
ForwardRequestHelper | org/omg/PortableInterceptor/ForwardRequestHelper.java .
InvalidSlotHelper | org/omg/PortableInterceptor/InvalidSlotHelper.java .

Exception Summary
ForwardRequest | org/omg/PortableInterceptor/ForwardRequest.java .
InvalidSlot | org/omg/PortableInterceptor/InvalidSlot.java .

Package org.omg.PortableInterceptor Description

Provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.

Interceptor Types

There are currently three types of interceptors that can be registered:
  • IORInterceptor - Used to establish tagged components in the profiles within an IOR.
  • ClientRequestInterceptor - Intercepts the flow of a request/reply sequence through the ORB on the client side.
  • ServerRequestInterceptor - Intercepts the flow of a request/reply sequence through the ORB on the server side.
See the javadocs for class ORBInitializer for how to go about registering interceptors.

Known limitations / unimplemented methods in package org.omg.PortableInterceptor

  • RequestInfo
    • sync_scope(): Always returns SYNC_WITH_TRANSPORT
    • arguments(): Only supported for DII/DSI calls
    • exceptions(): Only supported for DII calls on client side. Not supported on server-side.
    • contexts(): Only supported for DII calls on client side. Not supported on server-side since our ORB does not send contexts.
    • operation_context(): Only supported for DII calls on client side. Not supported on server-side since ORB does not send contexts.
    • result(): Only supported for DII/DSI calls
  • ClientRequestInfo
    • received_exception_id(): Always returns null in the DII case
    • get_request_policy(int type): Not implemented.
  • ServerRequestInfo
    • sending_exception(): Does not support user exceptions on the server side in non-DSI case.

Package Specification

For a precise list of supported sections of official OMG specifications with which the Java 2 Platform, Standard Edition, v.1.4 complies, see Official Specifications for CORBA support in J2SE 1.4.

Since:
1.4
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


org.omg.PortableInterceptor Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package org.omg.PortableInterceptor

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class org.omg.PortableInterceptor.CurrentHelper
    • class org.omg.PortableInterceptor.ForwardRequestHelper
    • class org.omg.PortableInterceptor.InvalidSlotHelper
    • class java.lang.Throwable (implements java.io.Serializable)
      • class java.lang.Exception
        • class org.omg.CORBA.UserException (implements org.omg.CORBA.portable.IDLEntity)
          • class org.omg.PortableInterceptor.ForwardRequest
          • class org.omg.PortableInterceptor.InvalidSlot

Interface Hierarchy

  • interface org.omg.CORBA.CurrentOperations
    • interface org.omg.CORBA.Current (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CORBA.Object)
      • interface org.omg.PortableInterceptor.Current (also extends org.omg.PortableInterceptor.CurrentOperations, org.omg.CORBA.portable.IDLEntity)
    • interface org.omg.PortableInterceptor.CurrentOperations
      • interface org.omg.PortableInterceptor.Current (also extends org.omg.CORBA.Current, org.omg.CORBA.portable.IDLEntity)
  • interface org.omg.PortableInterceptor.InterceptorOperations
    • interface org.omg.PortableInterceptor.ClientRequestInterceptorOperations
      • interface org.omg.PortableInterceptor.ClientRequestInterceptor (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableInterceptor.Interceptor)
    • interface org.omg.PortableInterceptor.Interceptor (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CORBA.Object)
      • interface org.omg.PortableInterceptor.ClientRequestInterceptor (also extends org.omg.PortableInterceptor.ClientRequestInterceptorOperations, org.omg.CORBA.portable.IDLEntity)
      • interface org.omg.PortableInterceptor.IORInterceptor (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableInterceptor.IORInterceptorOperations)
      • interface org.omg.PortableInterceptor.ServerRequestInterceptor (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableInterceptor.ServerRequestInterceptorOperations)
    • interface org.omg.PortableInterceptor.IORInterceptorOperations
      • interface org.omg.PortableInterceptor.IORInterceptor (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableInterceptor.Interceptor)
    • interface org.omg.PortableInterceptor.ServerRequestInterceptorOperations
      • interface org.omg.PortableInterceptor.ServerRequestInterceptor (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableInterceptor.Interceptor)
  • interface org.omg.PortableInterceptor.IORInfoOperations
    • interface org.omg.PortableInterceptor.IORInfo (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CORBA.Object)
  • interface org.omg.PortableInterceptor.LOCATION_FORWARD
  • interface org.omg.CORBA.Object
    • interface org.omg.CORBA.Current (also extends org.omg.CORBA.CurrentOperations, org.omg.CORBA.portable.IDLEntity)
      • interface org.omg.PortableInterceptor.Current (also extends org.omg.PortableInterceptor.CurrentOperations, org.omg.CORBA.portable.IDLEntity)
    • interface org.omg.PortableInterceptor.Interceptor (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableInterceptor.InterceptorOperations)
      • interface org.omg.PortableInterceptor.ClientRequestInterceptor (also extends org.omg.PortableInterceptor.ClientRequestInterceptorOperations, org.omg.CORBA.portable.IDLEntity)
      • interface org.omg.PortableInterceptor.IORInterceptor (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableInterceptor.IORInterceptorOperations)
      • interface org.omg.PortableInterceptor.ServerRequestInterceptor (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableInterceptor.ServerRequestInterceptorOperations)
    • interface org.omg.PortableInterceptor.IORInfo (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableInterceptor.IORInfoOperations)
    • interface org.omg.PortableInterceptor.ORBInitializer (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableInterceptor.ORBInitializerOperations)
    • interface org.omg.PortableInterceptor.ORBInitInfo (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableInterceptor.ORBInitInfoOperations)
    • interface org.omg.PortableInterceptor.PolicyFactory (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableInterceptor.PolicyFactoryOperations)
    • interface org.omg.PortableInterceptor.RequestInfo (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableInterceptor.RequestInfoOperations)
      • interface org.omg.PortableInterceptor.ClientRequestInfo (also extends org.omg.PortableInterceptor.ClientRequestInfoOperations, org.omg.CORBA.portable.IDLEntity)
      • interface org.omg.PortableInterceptor.ServerRequestInfo (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableInterceptor.ServerRequestInfoOperations)
  • interface org.omg.PortableInterceptor.ORBInitializerOperations
    • interface org.omg.PortableInterceptor.ORBInitializer (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CORBA.Object)
  • interface org.omg.PortableInterceptor.ORBInitInfoOperations
    • interface org.omg.PortableInterceptor.ORBInitInfo (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CORBA.Object)
  • interface org.omg.PortableInterceptor.PolicyFactoryOperations
    • interface org.omg.PortableInterceptor.PolicyFactory (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CORBA.Object)
  • interface org.omg.PortableInterceptor.RequestInfoOperations
    • interface org.omg.PortableInterceptor.ClientRequestInfoOperations
      • interface org.omg.PortableInterceptor.ClientRequestInfo (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableInterceptor.RequestInfo)
    • interface org.omg.PortableInterceptor.RequestInfo (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CORBA.Object)
      • interface org.omg.PortableInterceptor.ClientRequestInfo (also extends org.omg.PortableInterceptor.ClientRequestInfoOperations, org.omg.CORBA.portable.IDLEntity)
      • interface org.omg.PortableInterceptor.ServerRequestInfo (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableInterceptor.ServerRequestInfoOperations)
    • interface org.omg.PortableInterceptor.ServerRequestInfoOperations
      • interface org.omg.PortableInterceptor.ServerRequestInfo (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableInterceptor.RequestInfo)
  • interface java.io.Serializable
    • interface org.omg.CORBA.portable.IDLEntity
      • interface org.omg.PortableInterceptor.ClientRequestInfo (also extends org.omg.PortableInterceptor.ClientRequestInfoOperations, org.omg.PortableInterceptor.RequestInfo)
      • interface org.omg.PortableInterceptor.ClientRequestInterceptor (also extends org.omg.PortableInterceptor.ClientRequestInterceptorOperations, org.omg.PortableInterceptor.Interceptor)
      • interface org.omg.CORBA.Current (also extends org.omg.CORBA.CurrentOperations, org.omg.CORBA.Object)
        • interface org.omg.PortableInterceptor.Current (also extends org.omg.PortableInterceptor.CurrentOperations, org.omg.CORBA.portable.IDLEntity)
      • interface org.omg.PortableInterceptor.Current (also extends org.omg.CORBA.Current, org.omg.PortableInterceptor.CurrentOperations)
      • interface org.omg.PortableInterceptor.Interceptor (also extends org.omg.PortableInterceptor.InterceptorOperations, org.omg.CORBA.Object)
        • interface org.omg.PortableInterceptor.ClientRequestInterceptor (also extends org.omg.PortableInterceptor.ClientRequestInterceptorOperations, org.omg.CORBA.portable.IDLEntity)
        • interface org.omg.PortableInterceptor.IORInterceptor (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableInterceptor.IORInterceptorOperations)
        • interface org.omg.PortableInterceptor.ServerRequestInterceptor (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableInterceptor.ServerRequestInterceptorOperations)
      • interface org.omg.PortableInterceptor.IORInfo (also extends org.omg.PortableInterceptor.IORInfoOperations, org.omg.CORBA.Object)
      • interface org.omg.PortableInterceptor.IORInterceptor (also extends org.omg.PortableInterceptor.Interceptor, org.omg.PortableInterceptor.IORInterceptorOperations)
      • interface org.omg.PortableInterceptor.ORBInitializer (also extends org.omg.CORBA.Object, org.omg.PortableInterceptor.ORBInitializerOperations)
      • interface org.omg.PortableInterceptor.ORBInitInfo (also extends org.omg.CORBA.Object, org.omg.PortableInterceptor.ORBInitInfoOperations)
      • interface org.omg.PortableInterceptor.PolicyFactory (also extends org.omg.CORBA.Object, org.omg.PortableInterceptor.PolicyFactoryOperations)
      • interface org.omg.PortableInterceptor.RequestInfo (also extends org.omg.CORBA.Object, org.omg.PortableInterceptor.RequestInfoOperations)
        • interface org.omg.PortableInterceptor.ClientRequestInfo (also extends org.omg.PortableInterceptor.ClientRequestInfoOperations, org.omg.CORBA.portable.IDLEntity)
        • interface org.omg.PortableInterceptor.ServerRequestInfo (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableInterceptor.ServerRequestInfoOperations)
      • interface org.omg.PortableInterceptor.ServerRequestInfo (also extends org.omg.PortableInterceptor.RequestInfo, org.omg.PortableInterceptor.ServerRequestInfoOperations)
      • interface org.omg.PortableInterceptor.ServerRequestInterceptor (also extends org.omg.PortableInterceptor.Interceptor, org.omg.PortableInterceptor.ServerRequestInterceptorOperations)
  • interface org.omg.PortableInterceptor.SUCCESSFUL
  • interface org.omg.PortableInterceptor.SYSTEM_EXCEPTION
  • interface org.omg.PortableInterceptor.TRANSPORT_RETRY
  • interface org.omg.PortableInterceptor.USER_EXCEPTION
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package org.omg.PortableInterceptor (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
org.omg.PortableInterceptor

Packages that use org.omg.PortableInterceptor
org.omg.PortableInterceptor Provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.

Classes in org.omg.PortableInterceptor used by org.omg.PortableInterceptor
ClientRequestInfo
Request Information, accessible to client-side request interceptors.
ClientRequestInfoOperations
Request Information, accessible to client-side request interceptors.
ClientRequestInterceptor
Client-side request interceptor.
ClientRequestInterceptorOperations
Client-side request interceptor.
Current
Portable Interceptors Current (also known as PICurrent) is merely a slot table, the slots of which are used by each service to transfer their context data between their context and the request's or reply's service context.
CurrentOperations
Portable Interceptors Current (also known as PICurrent) is merely a slot table, the slots of which are used by each service to transfer their context data between their context and the request's or reply's service context.
ForwardRequest
org/omg/PortableInterceptor/ForwardRequest.java .
Interceptor
All Portable Interceptors implement Interceptor.
InterceptorOperations
All Portable Interceptors implement Interceptor.
InvalidSlot
org/omg/PortableInterceptor/InvalidSlot.java .
IORInfo
Provides the server-side ORB service with access to the applicable policies during IOR construction and the ability to add components.
IORInfoOperations
Provides the server-side ORB service with access to the applicable policies during IOR construction and the ability to add components.
IORInterceptor
Interceptor used to establish tagged components in the profiles within an IOR.
IORInterceptorOperations
Interceptor used to establish tagged components in the profiles within an IOR.
ORBInitializerOperations
Facilitates interceptor registration and ORB initialization.
ORBInitInfo
Passed to each ORBInitializer, allowing it to to register interceptors and perform other duties while the ORB is initializing.
ORBInitInfoOperations
Passed to each ORBInitializer, allowing it to to register interceptors and perform other duties while the ORB is initializing.
PolicyFactory
Enables policy types to be constructed using CORBA.ORB.create_policy.
PolicyFactoryOperations
Enables policy types to be constructed using CORBA.ORB.create_policy.
RequestInfo
Request Information, accessible to Interceptors.
RequestInfoOperations
Request Information, accessible to Interceptors.
ServerRequestInfo
Request Information, accessible to server-side request interceptors.
ServerRequestInfoOperations
Request Information, accessible to server-side request interceptors.
ServerRequestInterceptor
Server-side request interceptor.
ServerRequestInterceptorOperations
Server-side request interceptor.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


PolicyFactory (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableInterceptor
Interface PolicyFactory

All Superinterfaces:
IDLEntity, Object, PolicyFactoryOperations, Serializable
public interface PolicyFactory
extends PolicyFactoryOperations, Object, IDLEntity

Enables policy types to be constructed using CORBA.ORB.create_policy.

A portable ORB service implementation registers an instance of the PolicyFactory interface during ORB initialization in order to enable its policy types to be constructed using CORBA.ORB.create_policy. The POA is required to preserve any policy which is registered with ORBInitInfo in this manner.

See Also:
ORBInitInfoOperations.register_policy_factory(int, org.omg.PortableInterceptor.PolicyFactory)

Methods inherited from interface org.omg.PortableInterceptor.PolicyFactoryOperations
create_policy
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


PolicyFactoryOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableInterceptor
Interface PolicyFactoryOperations

All Known Subinterfaces:
PolicyFactory
public interface PolicyFactoryOperations

Enables policy types to be constructed using CORBA.ORB.create_policy.

A portable ORB service implementation registers an instance of the PolicyFactory interface during ORB initialization in order to enable its policy types to be constructed using CORBA.ORB.create_policy. The POA is required to preserve any policy which is registered with ORBInitInfo in this manner.

See Also:
ORBInitInfoOperations.register_policy_factory(int, org.omg.PortableInterceptor.PolicyFactory)

Method Summary
 Policy create_policy(int type, Any value)
Returns an instance of the appropriate interface derived from CORBA.Policy whose value corresponds to the specified any.

Method Detail

create_policy

public Policy create_policy(int type,
                            Any value)
                     throws PolicyError
Returns an instance of the appropriate interface derived from CORBA.Policy whose value corresponds to the specified any.

The ORB calls create_policy on a registered PolicyFactory instance when CORBA.ORB.create_policy is called for the PolicyType under which the PolicyFactory has been registered. The create_policy operation then returns an instance of the appropriate interface derived from CORBA.Policy whose value corresponds to the specified any. If it cannot, it shall throw an exception as described for CORBA.ORB.create_policy.

Parameters:
type - An int specifying the type of policy being created.
value - An any containing data with which to construct the CORBA.Policy.
Returns:
A CORBA.Policy object of the specified type and value.
Throws:
PolicyError
Overview  Package   Class  Use  Tree  Deprecated  Index  Help
JavaTM 2 Platform
Std. Ed. v1.4.2
 PREV CLASS   NEXT CLASS FRAMES    NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


RequestInfo (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableInterceptor
Interface RequestInfo

All Superinterfaces:
IDLEntity, Object, RequestInfoOperations, Serializable
All Known Subinterfaces:
ClientRequestInfo, ServerRequestInfo
public interface RequestInfo
extends RequestInfoOperations, Object, IDLEntity

Request Information, accessible to Interceptors.

Each interception point is given an object through which the Interceptor can access request information. Client-side and server-side interception points are concerned with different information, so there are two information objects: ClientRequestInfo is passed to the client-side interception points and ServerRequestInfo is passed to the server-side interception points. But there is information that is common to both, so they both inherit from a common interface: RequestInfo.

See Also:
ClientRequestInfo, ServerRequestInfo

Methods inherited from interface org.omg.PortableInterceptor.RequestInfoOperations
arguments, contexts, exceptions, forward_reference, get_reply_service_context, get_request_service_context, get_slot, operation_context, operation, reply_status, request_id, response_expected, result, sync_scope
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


RequestInfoOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableInterceptor
Interface RequestInfoOperations

All Known Subinterfaces:
ClientRequestInfo, ClientRequestInfoOperations, RequestInfo, ServerRequestInfo, ServerRequestInfoOperations
public interface RequestInfoOperations

Request Information, accessible to Interceptors.

Each interception point is given an object through which the Interceptor can access request information. Client-side and server-side interception points are concerned with different information, so there are two information objects: ClientRequestInfo is passed to the client-side interception points and ServerRequestInfo is passed to the server-side interception points. But there is information that is common to both, so they both inherit from a common interface: RequestInfo.

See Also:
ClientRequestInfo, ServerRequestInfo

Method Summary
Parameter[] | arguments() Returns an array of Parameter objects, containing the arguments on the operation being invoked.
String[] | contexts() Returns an array of String objects describing the contexts that may be passed on this operation invocation.
TypeCode[] | exceptions() Returns an array of TypeCode objects describing the TypeCodes of the user exceptions that this operation invocation may throw.
Object | forward_reference() Contains the object to which the request will be forwarded, if the reply_status attribute is LOCATION_FORWARD.
ServiceContext | get_reply_service_context(int id) Returns a copy of the service context with the given ID that is associated with the reply.
ServiceContext | get_request_service_context(int id) Returns a copy of the service context with the given ID that is associated with the request.
Any | get_slot(int id) Returns the data from the given slot of the PortableInterceptor.Current that is in the scope of the request.
String[] | operation_context() Returns an array of String objects containing the contexts being sent on the request.
String | operation() Returns the name of the operation being invoked.
short | reply_status() Describes the state of the result of the operation invocation.
int | request_id() Returns an id that uniquely identifies an active request/reply sequence.
boolean | response_expected() Indicates whether a response is expected.
Any | result() Returns an any containing the result of the operation invocation.
short | sync_scope() Defines how far the request shall progress before control is returned to the client.

Method Detail

request_id

public int request_id()
Returns an id that uniquely identifies an active request/reply sequence. Once a request/reply sequence is concluded this ID may be reused. Note that this id is not the same as the GIOP request_id. If GIOP is the transport mechanism used, then these IDs may very well be the same, but this is not guaranteed nor required.

operation

public String operation()
Returns the name of the operation being invoked.

arguments

public Parameter[] arguments()
Returns an array of Parameter objects, containing the arguments on the operation being invoked. If there are no arguments, this attribute will be a zero length array.

Not all environments provide access to the arguments. With the Java portable bindings, for example, the arguments are not available. In these environments, when this attribute is accessed, NO_RESOURCES will be thrown with a standard minor code of 1.

Note: Arguments are available for DSI/DII calls.

Throws:
NO_RESOURCES - thrown if arguments are not available.
See Also:
PortableInterceptor package comments for limitations / unimplemented features

exceptions

public TypeCode[] exceptions()
Returns an array of TypeCode objects describing the TypeCodes of the user exceptions that this operation invocation may throw. If there are no user exceptions, this will return a zero length array.

Not all environments provide access to the exception list. With the Java portable bindings, for example, the exception list is not available. In these environments, when this attribute is accessed, NO_RESOURCES will be thrown with a standard minor code of 1.

Note: Exceptions are available for DSI/DII calls.

Throws:
NO_RESOURCES - thrown if exceptions are not available.
See Also:
PortableInterceptor package comments for limitations / unimplemented features

contexts

public String[] contexts()
Returns an array of String objects describing the contexts that may be passed on this operation invocation. If there are no contexts, this will return a zero length array.

Not all environments provide access to the context list. With the Java portable bindings, for example, the context list is not available. In these environments, when this attribute is accessed, NO_RESOURCES will be thrown with a standard minor code of 1.

Note: Contexts are available for DSI/DII calls.

Throws:
NO_RESOURCES - thrown if contexts are not available.
See Also:
PortableInterceptor package comments for limitations / unimplemented features

operation_context

public String[] operation_context()
Returns an array of String objects containing the contexts being sent on the request.

Not all environments provide access to the context. With the Java portable bindings, for example, the context is not available. In these environments, when this attribute is accessed, NO_RESOURCES will be thrown with standard minor code of 1.

Note: operation_context is available for DSI/DII calls.

Throws:
NO_RESOURCES - thrown if operation context is not available.
See Also:
PortableInterceptor package comments for limitations / unimplemented features

result

public Any result()
Returns an any containing the result of the operation invocation. If the operation return type is void, this attribute will be an any containing a type code with a TCKind value of tk_void and no value.

Not all environments provide access to the result. With the Java portable bindings, for example, the result is not available. In these environments, when this attribute is accessed, NO_RESOURCES will be thrown with a standard minor code of 1.

Note: Result is available for DSI/DII calls.

Throws:
NO_RESOURCES - thrown if result is not available.
See Also:
PortableInterceptor package comments for limitations / unimplemented features

response_expected

public boolean response_expected()
Indicates whether a response is expected.

On the client, a reply is not returned when response_expected is false, so receive_reply cannot be called. receive_other is called unless an exception occurs, in which case receive_exception is called.

On the client, within send_poll, this attribute is true.

sync_scope

public short sync_scope()
Defines how far the request shall progress before control is returned to the client. This is defined in the Messaging specification, and is pertinent only when response_expected is false. If response_expected is true, the value of sync_scope is undefined. This attribute may have one of the following values:
  • Messaging.SYNC_NONE
  • Messaging.SYNC_WITH_TRANSPORT
  • Messaging.SYNC_WITH_SERVER
  • Messaging.SYNC_WITH_TARGET
On the server, for all scopes, a reply will be created from the return of the target operation call, but the reply will not return to the client. Although it does not return to the client, it does occur, so the normal server-side interception points are followed (i.e., receive_request_service_contexts, receive_request, send_reply or send_exception).

For SYNC_WITH_SERVER and SYNC_WITH_TARGET, the server does send an empty reply back to the client before the target is invoked. This reply is not intercepted by server-side Interceptors.

See Also:
PortableInterceptor package comments for limitations / unimplemented features

reply_status

public short reply_status()
Describes the state of the result of the operation invocation. The return value can be one of the following:
  • PortableInterceptor.SUCCESSFUL
  • PortableInterceptor.SYSTEM_EXCEPTION
  • PortableInterceptor.USER_EXCEPTION
  • PortableInterceptor.LOCATION_FORWARD
  • PortableInterceptor.TRANSPORT_RETRY
On the client:
  • Within the receive_reply interception point, this will only return SUCCESSFUL
    • .
  • Within the receive_exception interception point, this will be either SYSTEM_EXCEPTION or USER_EXCEPTION.
  • Within the receive_other interception point, this will be any of: SUCCESSFUL, LOCATION_FORWARD, or TRANSPORT_RETRY. SUCCESSFUL means an asynchronous request returned successfully. LOCATION_FORWARD means that a reply came back with LOCATION_FORWARD as its status. TRANSPORT_RETRY means that the transport mechanism indicated a retry - a GIOP reply with a status of NEEDS_ADDRESSING_MODE, for instance.
On the server:
  • Within the send_reply interception point, this will only be SUCCESSFUL.
  • Within the send_exception interception point, this will be either SYSTEM_EXCEPTION or USER_EXCEPTION.
  • Within the send_other interception point, this attribute will be any of: SUCCESSFUL, or LOCATION_FORWARD. SUCCESSFUL means an asynchronous request returned successfully. LOCATION_FORWARD means that a reply came back with LOCATION_FORWARD as its status.

See Also:
SUCCESSFUL, SYSTEM_EXCEPTION, USER_EXCEPTION, LOCATION_FORWARD, TRANSPORT_RETRY

forward_reference

public Object forward_reference()
Contains the object to which the request will be forwarded, if the reply_status attribute is LOCATION_FORWARD. It is indeterminate whether a forwarded request will actually occur.

get_slot

public Any get_slot(int id)
             throws InvalidSlot
Returns the data from the given slot of the PortableInterceptor.Current that is in the scope of the request.

If the given slot has not been set, then an any containing a type code with a TCKind value of tk_null is returned.

Parameters:
id - The SlotId of the slot which is to be returned.
Returns:
The slot data, in the form of an any, obtained with the given identifier.
Throws:
InvalidSlot - thrown if the ID does not define an allocated slot.
See Also:
Current

get_request_service_context

public ServiceContext get_request_service_context(int id)
Returns a copy of the service context with the given ID that is associated with the request.

Parameters:
id - The IOP.ServiceId of the service context which is to be returned.
Returns:
The IOP.ServiceContext obtained with the given identifier.
Throws:
BAD_PARAM - thrown with a standard minor code of 26, if the request's service context does not contain an entry for that ID.

get_reply_service_context

public ServiceContext get_reply_service_context(int id)
Returns a copy of the service context with the given ID that is associated with the reply.

Parameters:
id - The IOP.ServiceId of the service context which is to be returned.
Returns:
The IOP.ServiceContext obtained with the given identifier.
Throws:
BAD_PARAM - thrown with a standard minor code of 26 if the request's service context does not contain an entry for that ID.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ServerRequestInfo (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableInterceptor
Interface ServerRequestInfo

All Superinterfaces:
IDLEntity, Object, RequestInfo, RequestInfoOperations, Serializable, ServerRequestInfoOperations
public interface ServerRequestInfo
extends ServerRequestInfoOperations, RequestInfo, IDLEntity

Request Information, accessible to server-side request interceptors.

Some attributes and operations on ServerRequestInfo are not valid at all interception points. The following table shows the validity of each attribute or operation. If it is not valid, attempting to access it will result in a BAD_INV_ORDER being thrown with a standard minor code of 14.

 | receive_request_ service_contexts | receive_request | send_reply | send_exception | send_other
Inherited from RequestInfo:
request_id | yes | yes | yes | yes | yes
operation | yes | yes | yes | yes | yes
arguments | no | yes1 | yes | no2 | no2
exceptions | no | yes | yes | yes | yes
contexts | no | yes | yes | yes | yes
operation_context | no | yes | yes | no | no
result | no | no | yes | no | no
response_expected | yes | yes | yes | yes | yes
sync_scope | yes | yes | yes | yes | yes
reply_status | no | no | yes | yes | yes
forward_reference | no | no | no | no | yes2
get_slot | yes | yes | yes | yes | yes
get_request_service_context | yes | no | yes | yes | yes
get_reply_service_context | no | no | yes | yes | yes
ServerRequestInfo-specific:
sending_exception | no | no | no | yes | no
object_id | no | yes | yes | yes3 | yes3
adapter_id | no | yes | yes | yes3 | yes3
target_most_derived_interface | no | yes | no4 | no4 | no4
get_server_policy | yes | yes | yes | yes | yes
set_slot | yes | yes | yes | yes | yes
target_is_a | no | yes | no4 | no4 | no4
add_reply_service_context | yes | yes | yes | yes | yes
  1. When ServerRequestInfo is passed to receive_request, there is an entry in the list for every argument, whether in, inout, or out. But only the in and inout arguments will be available.
  2. If the reply_status attribute is not LOCATION_FORWARD, accessing this attribute will throw BAD_INV_ORDER with a standard minor code of 14.
  3. If the servant locator caused a location forward, or thrown an exception, this attribute/operation may not be available in this interception point. NO_RESOURCES with a standard minor code of 1 will be thrown if it is not available.
  4. The operation is not available in this interception point because the necessary information requires access to the target object's servant, which may no longer be available to the ORB. For example, if the object's adapter is a POA that uses a ServantLocator, then the ORB invokes the interception point after it calls ServantLocator.postinvoke()
    5. .

See Also:
ServerRequestInterceptor

Methods inherited from interface org.omg.PortableInterceptor.ServerRequestInfoOperations
adapter_id, add_reply_service_context, get_server_policy, object_id, sending_exception, set_slot, target_is_a, target_most_derived_interface
Methods inherited from interface org.omg.PortableInterceptor.RequestInfoOperations
arguments, contexts, exceptions, forward_reference, get_reply_service_context, get_request_service_context, get_slot, operation_context, operation, reply_status, request_id, response_expected, result, sync_scope
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ServerRequestInfoOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableInterceptor
Interface ServerRequestInfoOperations

All Superinterfaces:
RequestInfoOperations
All Known Subinterfaces:
ServerRequestInfo
public interface ServerRequestInfoOperations
extends RequestInfoOperations

Request Information, accessible to server-side request interceptors.

Some attributes and operations on ServerRequestInfo are not valid at all interception points. The following table shows the validity of each attribute or operation. If it is not valid, attempting to access it will result in a BAD_INV_ORDER being thrown with a standard minor code of 14.

 | receive_request_ service_contexts | receive_request | send_reply | send_exception | send_other
Inherited from RequestInfo:
request_id | yes | yes | yes | yes | yes
operation | yes | yes | yes | yes | yes
arguments | no | yes1 | yes | no2 | no2
exceptions | no | yes | yes | yes | yes
contexts | no | yes | yes | yes | yes
operation_context | no | yes | yes | no | no
result | no | no | yes | no | no
response_expected | yes | yes | yes | yes | yes
sync_scope | yes | yes | yes | yes | yes
reply_status | no | no | yes | yes | yes
forward_reference | no | no | no | no | yes2
get_slot | yes | yes | yes | yes | yes
get_request_service_context | yes | no | yes | yes | yes
get_reply_service_context | no | no | yes | yes | yes
ServerRequestInfo-specific:
sending_exception | no | no | no | yes | no
object_id | no | yes | yes | yes3 | yes3
adapter_id | no | yes | yes | yes3 | yes3
target_most_derived_interface | no | yes | no4 | no4 | no4
get_server_policy | yes | yes | yes | yes | yes
set_slot | yes | yes | yes | yes | yes
target_is_a | no | yes | no4 | no4 | no4
add_reply_service_context | yes | yes | yes | yes | yes
  1. When ServerRequestInfo is passed to receive_request, there is an entry in the list for every argument, whether in, inout, or out. But only the in and inout arguments will be available.
  2. If the reply_status attribute is not LOCATION_FORWARD, accessing this attribute will throw BAD_INV_ORDER with a standard minor code of 14.
  3. If the servant locator caused a location forward, or thrown an exception, this attribute/operation may not be available in this interception point. NO_RESOURCES with a standard minor code of 1 will be thrown if it is not available.
  4. The operation is not available in this interception point because the necessary information requires access to the target object's servant, which may no longer be available to the ORB. For example, if the object's adapter is a POA that uses a ServantLocator, then the ORB invokes the interception point after it calls ServantLocator.postinvoke()
    5. .

See Also:
ServerRequestInterceptor

Method Summary
byte[] | adapter_id() Returns the opaque identifier for the object adapter.
void | add_reply_service_context(ServiceContext service_context, boolean replace) Allows Interceptors to add service contexts to the request.
Policy | get_server_policy(int type) Returns the policy in effect for this operation for the given policy type.
byte[] | object_id() Returns the opaque object_id describing the target of the operation invocation.
Any | sending_exception() Returns an any which contains the exception to be returned to the client.
void | set_slot(int id, Any data) Allows an Interceptor to set a slot in the PortableInterceptor.Current that is in the scope of the request.
boolean | target_is_a(String id) Returns true if the servant is the given repository id, false if it is not.
String | target_most_derived_interface() Returns the repository id for the most derived interface of the servant.
Methods inherited from interface org.omg.PortableInterceptor.RequestInfoOperations
arguments, contexts, exceptions, forward_reference, get_reply_service_context, get_request_service_context, get_slot, operation_context, operation, reply_status, request_id, response_expected, result, sync_scope

Method Detail

sending_exception

public Any sending_exception()
Returns an any which contains the exception to be returned to the client.

If the exception is a user exception which cannot be inserted into an any (e.g., it is unknown or the bindings don't provide the TypeCode), then this attribute will be an any containing the system exception UNKNOWN with a standard minor code of 1.

See Also:
PortableInterceptor package comments for limitations / unimplemented features

object_id

public byte[] object_id()
Returns the opaque object_id describing the target of the operation invocation.

adapter_id

public byte[] adapter_id()
Returns the opaque identifier for the object adapter.

target_most_derived_interface

public String target_most_derived_interface()
Returns the repository id for the most derived interface of the servant.

get_server_policy

public Policy get_server_policy(int type)
Returns the policy in effect for this operation for the given policy type. The returned CORBA.Policy object shall only be a policy whose type was registered via register_policy_factory.

Parameters:
type - The CORBA.PolicyType which specifies the policy to be returned.
Returns:
The CORBA.Policy obtained with the given policy type.
Throws:
INV_POLICY - thrown, with a standard minor code of 2, if a policy for the given type was not registered via register_policy_factory.
See Also:
ORBInitInfoOperations.register_policy_factory(int, org.omg.PortableInterceptor.PolicyFactory)

set_slot

public void set_slot(int id,
                     Any data)
              throws InvalidSlot
Allows an Interceptor to set a slot in the PortableInterceptor.Current that is in the scope of the request. If data already exists in that slot, it will be overwritten.

Parameters:
id - The id of the slot.
data - The data, in the form of an any, to store in that slot.
Throws:
InvalidSlot - thrown if the ID does not define an allocated slot.
See Also:
Current

target_is_a

public boolean target_is_a(String id)
Returns true if the servant is the given repository id, false if it is not.

Parameters:
id - The caller wants to know if the servant is this repository id.
Returns:
Is the servant the given RepositoryId?

add_reply_service_context

public void add_reply_service_context(ServiceContext service_context,
                                      boolean replace)
Allows Interceptors to add service contexts to the request.

There is no declaration of the order of the service contexts. They may or may not appear in the order that they are added.

Parameters:
service_context - The IOP.ServiceContext to add to the reply.
replace - Indicates the behavior of this operation when a service context already exists with the given ID. If false, then BAD_INV_ORDER with a standard minor code of 15 is thrown. If true, then the existing service context is replaced by the new one.
Throws:
BAD_INV_ORDER - thrown, with a standard minor code of 15, if replace is false and a service context already exists with the given ID.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ServerRequestInterceptor (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableInterceptor
Interface ServerRequestInterceptor

All Superinterfaces:
IDLEntity, Interceptor, InterceptorOperations, Object, Serializable, ServerRequestInterceptorOperations
public interface ServerRequestInterceptor
extends ServerRequestInterceptorOperations, Interceptor, IDLEntity

Server-side request interceptor.

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. There are two types of request Interceptors: client-side and server-side.

To write a server-side Interceptor, implement the ServerRequestInterceptor interface.

See Also:
ServerRequestInfo

Methods inherited from interface org.omg.PortableInterceptor.ServerRequestInterceptorOperations
receive_request_service_contexts, receive_request, send_exception, send_other, send_reply
Methods inherited from interface org.omg.PortableInterceptor.InterceptorOperations
destroy, name
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ServerRequestInterceptorOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableInterceptor
Interface ServerRequestInterceptorOperations

All Superinterfaces:
InterceptorOperations
All Known Subinterfaces:
ServerRequestInterceptor
public interface ServerRequestInterceptorOperations
extends InterceptorOperations

Server-side request interceptor.

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. There are two types of request Interceptors: client-side and server-side.

To write a server-side Interceptor, implement the ServerRequestInterceptor interface.

See Also:
ServerRequestInfo

Method Summary
void | receive_request_service_contexts(ServerRequestInfo ri) Allows the interceptor to process service context information.
void | receive_request(ServerRequestInfo ri) Allows an Interceptor to query request information after all the information, including operation parameters, are available.
void | send_exception(ServerRequestInfo ri) Allows an Interceptor to query the exception information and modify the reply service context before the exception is thrown to the client.
void | send_other(ServerRequestInfo ri) Allows an Interceptor to query the information available when a request results in something other than a normal reply or an exception.
void | send_reply(ServerRequestInfo ri) 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.
Methods inherited from interface org.omg.PortableInterceptor.InterceptorOperations
destroy, name

Method Detail

receive_request_service_contexts

public void receive_request_service_contexts(ServerRequestInfo ri)
                                      throws ForwardRequest
Allows the interceptor to process service context information.

At this interception point, Interceptors must get their service context information from the incoming request transfer it to PortableInterceptor.Current's slots.

This interception point is called before the servant manager is called. Operation parameters are not yet available at this point. This interception point may or may not execute in the same thread as the target invocation.

This interception point may throw a system exception. If it does, no other Interceptors' receive_request_service_contexts operations are called. Those Interceptors on the Flow Stack are popped and their send_exception interception points are called.

This interception point may also throw a ForwardRequest exception. If an Interceptor throws this exception, no other Interceptors' receive_request_service_contexts operations are called. Those Interceptors on the Flow Stack are popped and their send_other interception points are called.

Compliant Interceptors shall properly follow completion_status semantics if they throw a system exception from this interception point. The completion_status shall be COMPLETED_NO.

Parameters:
ri - Information about the current request being intercepted.
Throws:
ForwardRequest - If thrown, indicates to the ORB that a retry of the request should occur with the new object given in the exception.

receive_request

public void receive_request(ServerRequestInfo ri)
                     throws ForwardRequest
Allows an Interceptor to query request information after all the information, including operation parameters, are available. This interception point shall execute in the same thread as the target invocation.

In the DSI model, since the parameters are first available when the user code calls arguments, receive_request is called from within arguments. It is possible that arguments is not called in the DSI model. The target may call set_exception before calling arguments. The ORB shall guarantee that receive_request is called once, either through arguments or through set_exception. If it is called through set_exception, requesting the arguments will result in NO_RESOURCES being thrown with a standard minor code of 1.

This interception point may throw a system exception. If it does, no other Interceptors' receive_request operations are called. Those Interceptors on the Flow Stack are popped and their send_exception interception points are called.

This interception point may also throw a ForwardRequest exception. If an Interceptor throws this exception, no other Interceptors' receive_request operations are called. Those Interceptors on the Flow Stack are popped and their send_other interception points are called.

Compliant Interceptors shall properly follow completion_status semantics if they throw a system exception from this interception point. The completion_status shall be COMPLETED_NO.

Parameters:
ri - Information about the current request being intercepted.
Throws:
ForwardRequest - If thrown, indicates to the ORB that a retry of the request should occur with the new object given in the exception.

send_reply

public void send_reply(ServerRequestInfo ri)
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. This interception point shall execute in the same thread as the target invocation.

This interception point may throw a system exception. If it does, no other Interceptors' send_reply operations are called. The remaining Interceptors in the Flow Stack shall have their send_exception interception point called.

Compliant Interceptors shall properly follow completion_status semantics if they throw a system exception from this interception point. The completion_status shall be COMPLETED_YES.

Parameters:
ri - Information about the current request being intercepted.

send_exception

public void send_exception(ServerRequestInfo ri)
                    throws ForwardRequest
Allows an Interceptor to query the exception information and modify the reply service context before the exception is thrown to the client. When an exception occurs, this interception point is called. This interception point shall execute in the same thread as the target invocation.

This interception point may throw a system exception. This has the effect of changing the exception which successive Interceptors popped from the Flow Stack receive on their calls to send_exception. The exception thrown to the client will be the last exception thrown by an Interceptor, or the original exception if no Interceptor changes the exception.

This interception point may also throw a ForwardRequest exception. If an Interceptor throws this exception, no other Interceptors' send_exception operations are called. The remaining Interceptors in the Flow Stack shall have their send_other interception points called.

If the completion_status of the exception is not COMPLETED_NO, then it is inappropriate for this interception point to throw a ForwardRequest exception. The request's at-most-once semantics would be lost.

Compliant Interceptors shall properly follow completion_status semantics if they throw a system exception from this interception point. If the original exception is a system exception, the completion_status of the new exception shall be the same as on the original. If the original exception is a user exception, then the completion_status of the new exception shall be COMPLETED_YES.

Parameters:
ri - Information about the current request being intercepted.
Throws:
ForwardRequest - If thrown, indicates to the ORB that a retry of the request should occur with the new object given in the exception.

send_other

public void send_other(ServerRequestInfo ri)
                throws ForwardRequest
Allows an Interceptor to query the information available when a request results in something other than a normal reply or an exception. For example, a request could result in a retry (e.g., a GIOP Reply with a LOCATION_FORWARD status was received). This interception point shall execute in the same thread as the target invocation.

This interception point may throw a system exception. If it does, no other Interceptors' send_other operations are called. The remaining Interceptors in the Flow Stack shall have their send_exception interception points called.

This interception point may also throw a ForwardRequest exception. If an Interceptor throws this exception, successive Interceptors' send_other operations are called with the new information provided by the ForwardRequest exception.

Compliant Interceptors shall properly follow completion_status semantics if they throw a system exception from this interception point. The completion_status shall be COMPLETED_NO.

Parameters:
ri - Information about the current request being intercepted.
Throws:
ForwardRequest - If thrown, indicates to the ORB that a retry of the request should occur with the new object given in the exception.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


SUCCESSFUL (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableInterceptor
Interface SUCCESSFUL

public interface SUCCESSFUL

org/omg/PortableInterceptor/SUCCESSFUL.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableInterceptor/Interceptors.idl Thursday, June 12, 2003 9:59:19 PM GMT-08:00

Field Summary
static short value
Indicates a successful Reply Status.

Field Detail

value

public static final short value
Indicates a successful Reply Status. One possible value for RequestInfo.reply_status.

See Also:
RequestInfoOperations.reply_status(), SYSTEM_EXCEPTION, USER_EXCEPTION, LOCATION_FORWARD, TRANSPORT_RETRY, Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


SYSTEM_EXCEPTION (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableInterceptor
Interface SYSTEM_EXCEPTION

public interface SYSTEM_EXCEPTION

org/omg/PortableInterceptor/SYSTEM_EXCEPTION.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableInterceptor/Interceptors.idl Thursday, June 12, 2003 9:59:19 PM GMT-08:00

Field Summary
static short value
Indicates a SystemException reply status.

Field Detail

value

public static final short value
Indicates a SystemException reply status. One possible value for RequestInfo.reply_status.

See Also:
RequestInfoOperations.reply_status(), SUCCESSFUL, USER_EXCEPTION, LOCATION_FORWARD, TRANSPORT_RETRY, Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TRANSPORT_RETRY (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableInterceptor
Interface TRANSPORT_RETRY

public interface TRANSPORT_RETRY

org/omg/PortableInterceptor/TRANSPORT_RETRY.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableInterceptor/Interceptors.idl Thursday, June 12, 2003 9:59:19 PM GMT-08:00

Field Summary
static short value
Indicates a Transport Retry reply status.

Field Detail

value

public static final short value
Indicates a Transport Retry reply status. One possible value for RequestInfo.reply_status.

See Also:
RequestInfoOperations.reply_status(), SUCCESSFUL, SYSTEM_EXCEPTION, USER_EXCEPTION, LOCATION_FORWARD, Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


USER_EXCEPTION (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableInterceptor
Interface USER_EXCEPTION

public interface USER_EXCEPTION

org/omg/PortableInterceptor/USER_EXCEPTION.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableInterceptor/Interceptors.idl Thursday, June 12, 2003 9:59:19 PM GMT-08:00

Field Summary
static short value
Indicates a UserException reply status.

Field Detail

value

public static final short value
Indicates a UserException reply status. One possible value for RequestInfo.reply_status.

See Also:
RequestInfoOperations.reply_status(), SUCCESSFUL, SYSTEM_EXCEPTION, LOCATION_FORWARD, TRANSPORT_RETRY, Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Uses of Interface org.omg.PortableInterceptor.ClientRequestInfo (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableInterceptor.ClientRequestInfo

Packages that use ClientRequestInfo
org.omg.PortableInterceptor Provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.

Uses of ClientRequestInfo in org.omg.PortableInterceptor

Methods in org.omg.PortableInterceptor with parameters of type ClientRequestInfo
void | ClientRequestInterceptorOperations.send_request(ClientRequestInfo ri) Allows an Interceptor to query request information and modify the service context before the request is sent to the server.
void | ClientRequestInterceptorOperations.send_poll(ClientRequestInfo ri) Allows an Interceptor to query information during a Time-Independent Invocation (TII) polling get reply sequence.
void | ClientRequestInterceptorOperations.receive_reply(ClientRequestInfo ri) 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.
void | ClientRequestInterceptorOperations.receive_exception(ClientRequestInfo ri) Indicates to the interceptor that an exception occurred.
void | ClientRequestInterceptorOperations.receive_other(ClientRequestInfo ri) Allows an Interceptor to query the information available when a request results in something other than a normal reply or an exception.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableInterceptor.ClientRequestInfoOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableInterceptor.ClientRequestInfoOperations

Packages that use ClientRequestInfoOperations
org.omg.PortableInterceptor Provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.

Uses of ClientRequestInfoOperations in org.omg.PortableInterceptor

Subinterfaces of ClientRequestInfoOperations in org.omg.PortableInterceptor
 interface ClientRequestInfo
Request Information, accessible to client-side request interceptors.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableInterceptor.ClientRequestInterceptor (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableInterceptor.ClientRequestInterceptor

Packages that use ClientRequestInterceptor
org.omg.PortableInterceptor Provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.

Uses of ClientRequestInterceptor in org.omg.PortableInterceptor

Methods in org.omg.PortableInterceptor with parameters of type ClientRequestInterceptor
 void ORBInitInfoOperations.add_client_request_interceptor(ClientRequestInterceptor interceptor)
Used to add a client-side request Interceptor to the list of client-side request Interceptors.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableInterceptor.ClientRequestInterceptorOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableInterceptor.ClientRequestInterceptorOperations

Packages that use ClientRequestInterceptorOperations
org.omg.PortableInterceptor Provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.

Uses of ClientRequestInterceptorOperations in org.omg.PortableInterceptor

Subinterfaces of ClientRequestInterceptorOperations in org.omg.PortableInterceptor
 interface ClientRequestInterceptor
Client-side request interceptor.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableInterceptor.Current (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableInterceptor.Current

Packages that use Current
org.omg.PortableInterceptor Provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.

Uses of Current in org.omg.PortableInterceptor

Methods in org.omg.PortableInterceptor that return Current
static Current | CurrentHelper.extract(Any a)
static Current | CurrentHelper.read(InputStream istream)
static Current | CurrentHelper.narrow(Object obj)

Methods in org.omg.PortableInterceptor with parameters of type Current
static void | CurrentHelper.insert(Any a, Current that)
static void | CurrentHelper.write(OutputStream ostream, Current value)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableInterceptor.CurrentHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableInterceptor.CurrentHelper

No usage of org.omg.PortableInterceptor.CurrentHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableInterceptor.CurrentOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableInterceptor.CurrentOperations

Packages that use CurrentOperations
org.omg.PortableInterceptor Provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.

Uses of CurrentOperations in org.omg.PortableInterceptor

Subinterfaces of CurrentOperations in org.omg.PortableInterceptor
 interface Current
Portable Interceptors Current (also known as PICurrent) is merely a slot table, the slots of which are used by each service to transfer their context data between their context and the request's or reply's service context.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableInterceptor.ForwardRequest (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableInterceptor.ForwardRequest

Packages that use ForwardRequest
org.omg.PortableInterceptor Provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.

Uses of ForwardRequest in org.omg.PortableInterceptor

Methods in org.omg.PortableInterceptor that return ForwardRequest
static ForwardRequest | ForwardRequestHelper.extract(Any a)
static ForwardRequest | ForwardRequestHelper.read(InputStream istream)

Methods in org.omg.PortableInterceptor with parameters of type ForwardRequest
static void | ForwardRequestHelper.insert(Any a, ForwardRequest that)
static void | ForwardRequestHelper.write(OutputStream ostream, ForwardRequest value)

Methods in org.omg.PortableInterceptor that throw ForwardRequest
void | ServerRequestInterceptorOperations.receive_request_service_contexts(ServerRequestInfo ri) Allows the interceptor to process service context information.
void | ServerRequestInterceptorOperations.receive_request(ServerRequestInfo ri) Allows an Interceptor to query request information after all the information, including operation parameters, are available.
void | ServerRequestInterceptorOperations.send_exception(ServerRequestInfo ri) Allows an Interceptor to query the exception information and modify the reply service context before the exception is thrown to the client.
void | ServerRequestInterceptorOperations.send_other(ServerRequestInfo ri) Allows an Interceptor to query the information available when a request results in something other than a normal reply or an exception.
void | ClientRequestInterceptorOperations.send_request(ClientRequestInfo ri) Allows an Interceptor to query request information and modify the service context before the request is sent to the server.
void | ClientRequestInterceptorOperations.receive_exception(ClientRequestInfo ri) Indicates to the interceptor that an exception occurred.
void | ClientRequestInterceptorOperations.receive_other(ClientRequestInfo ri) Allows an Interceptor to query the information available when a request results in something other than a normal reply or an exception.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableInterceptor.ForwardRequestHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableInterceptor.ForwardRequestHelper

No usage of org.omg.PortableInterceptor.ForwardRequestHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableInterceptor.Interceptor (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableInterceptor.Interceptor

Packages that use Interceptor
org.omg.PortableInterceptor Provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.

Uses of Interceptor in org.omg.PortableInterceptor

Subinterfaces of Interceptor in org.omg.PortableInterceptor
interface | ClientRequestInterceptor Client-side request interceptor.
interface | IORInterceptor Interceptor used to establish tagged components in the profiles within an IOR.
interface | ServerRequestInterceptor Server-side request interceptor.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableInterceptor.InterceptorOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableInterceptor.InterceptorOperations

Packages that use InterceptorOperations
org.omg.PortableInterceptor Provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.

Uses of InterceptorOperations in org.omg.PortableInterceptor

Subinterfaces of InterceptorOperations in org.omg.PortableInterceptor
interface | ClientRequestInterceptor Client-side request interceptor.
interface | ClientRequestInterceptorOperations Client-side request interceptor.
interface | Interceptor All Portable Interceptors implement Interceptor.
interface | IORInterceptor Interceptor used to establish tagged components in the profiles within an IOR.
interface | IORInterceptorOperations Interceptor used to establish tagged components in the profiles within an IOR.
interface | ServerRequestInterceptor Server-side request interceptor.
interface | ServerRequestInterceptorOperations Server-side request interceptor.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableInterceptor.InvalidSlot (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableInterceptor.InvalidSlot

Packages that use InvalidSlot
org.omg.PortableInterceptor Provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.

Uses of InvalidSlot in org.omg.PortableInterceptor

Methods in org.omg.PortableInterceptor that return InvalidSlot
static InvalidSlot | InvalidSlotHelper.extract(Any a)
static InvalidSlot | InvalidSlotHelper.read(InputStream istream)

Methods in org.omg.PortableInterceptor with parameters of type InvalidSlot
static void | InvalidSlotHelper.insert(Any a, InvalidSlot that)
static void | InvalidSlotHelper.write(OutputStream ostream, InvalidSlot value)

Methods in org.omg.PortableInterceptor that throw InvalidSlot
void | ServerRequestInfoOperations.set_slot(int id, Any data) Allows an Interceptor to set a slot in the PortableInterceptor.Current that is in the scope of the request.
Any | CurrentOperations.get_slot(int id) Retrieves the slot data the application set in PICurrent via get_slot.
void | CurrentOperations.set_slot(int id, Any data) Sets data in a slot.
Any | RequestInfoOperations.get_slot(int id) Returns the data from the given slot of the PortableInterceptor.Current that is in the scope of the request.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableInterceptor.InvalidSlotHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableInterceptor.InvalidSlotHelper

No usage of org.omg.PortableInterceptor.InvalidSlotHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableInterceptor.IORInfo (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableInterceptor.IORInfo

Packages that use IORInfo
org.omg.PortableInterceptor Provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.

Uses of IORInfo in org.omg.PortableInterceptor

Methods in org.omg.PortableInterceptor with parameters of type IORInfo
 void IORInterceptorOperations.establish_components(IORInfo info)
A server side ORB calls the establish_components operation on all registered IORInterceptor instances when it is assembling the list of components that will be included in the profile or profiles of an object reference.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableInterceptor.IORInfoOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableInterceptor.IORInfoOperations

Packages that use IORInfoOperations
org.omg.PortableInterceptor Provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.

Uses of IORInfoOperations in org.omg.PortableInterceptor

Subinterfaces of IORInfoOperations in org.omg.PortableInterceptor
 interface IORInfo
Provides the server-side ORB service with access to the applicable policies during IOR construction and the ability to add components.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableInterceptor.IORInterceptor (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableInterceptor.IORInterceptor

Packages that use IORInterceptor
org.omg.PortableInterceptor Provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.

Uses of IORInterceptor in org.omg.PortableInterceptor

Methods in org.omg.PortableInterceptor with parameters of type IORInterceptor
 void ORBInitInfoOperations.add_ior_interceptor(IORInterceptor interceptor)
Used to add an IOR Interceptor to the list of IOR Interceptors.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableInterceptor.IORInterceptorOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableInterceptor.IORInterceptorOperations

Packages that use IORInterceptorOperations
org.omg.PortableInterceptor Provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.

Uses of IORInterceptorOperations in org.omg.PortableInterceptor

Subinterfaces of IORInterceptorOperations in org.omg.PortableInterceptor
 interface IORInterceptor
Interceptor used to establish tagged components in the profiles within an IOR.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableInterceptor.LOCATION_FORWARD (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableInterceptor.LOCATION_FORWARD

No usage of org.omg.PortableInterceptor.LOCATION_FORWARD

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableInterceptor.ORBInitializer (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableInterceptor.ORBInitializer

No usage of org.omg.PortableInterceptor.ORBInitializer

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableInterceptor.ORBInitializerOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableInterceptor.ORBInitializerOperations

Packages that use ORBInitializerOperations
org.omg.PortableInterceptor Provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.

Uses of ORBInitializerOperations in org.omg.PortableInterceptor

Subinterfaces of ORBInitializerOperations in org.omg.PortableInterceptor
 interface ORBInitializer
Facilitates interceptor registration and ORB initialization.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableInterceptor.ORBInitInfo (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableInterceptor.ORBInitInfo

Packages that use ORBInitInfo
org.omg.PortableInterceptor Provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.

Uses of ORBInitInfo in org.omg.PortableInterceptor

Methods in org.omg.PortableInterceptor with parameters of type ORBInitInfo
void | ORBInitializerOperations.pre_init(ORBInitInfo info) Called during ORB initialization.
void | ORBInitializerOperations.post_init(ORBInitInfo info) Called during ORB initialization.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableInterceptor.ORBInitInfoOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableInterceptor.ORBInitInfoOperations

Packages that use ORBInitInfoOperations
org.omg.PortableInterceptor Provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.

Uses of ORBInitInfoOperations in org.omg.PortableInterceptor

Subinterfaces of ORBInitInfoOperations in org.omg.PortableInterceptor
 interface ORBInitInfo
Passed to each ORBInitializer, allowing it to to register interceptors and perform other duties while the ORB is initializing.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableInterceptor.PolicyFactory (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableInterceptor.PolicyFactory

Packages that use PolicyFactory
org.omg.PortableInterceptor Provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.

Uses of PolicyFactory in org.omg.PortableInterceptor

Methods in org.omg.PortableInterceptor with parameters of type PolicyFactory
 void ORBInitInfoOperations.register_policy_factory(int type, PolicyFactory policy_factory)
Registers a PolicyFactory for the given PolicyType.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableInterceptor.PolicyFactoryOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableInterceptor.PolicyFactoryOperations

Packages that use PolicyFactoryOperations
org.omg.PortableInterceptor Provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.

Uses of PolicyFactoryOperations in org.omg.PortableInterceptor

Subinterfaces of PolicyFactoryOperations in org.omg.PortableInterceptor
 interface PolicyFactory
Enables policy types to be constructed using CORBA.ORB.create_policy.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableInterceptor.RequestInfo (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableInterceptor.RequestInfo

Packages that use RequestInfo
org.omg.PortableInterceptor Provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.

Uses of RequestInfo in org.omg.PortableInterceptor

Subinterfaces of RequestInfo in org.omg.PortableInterceptor
interface | ClientRequestInfo Request Information, accessible to client-side request interceptors.
interface | ServerRequestInfo Request Information, accessible to server-side request interceptors.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableInterceptor.RequestInfoOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableInterceptor.RequestInfoOperations

Packages that use RequestInfoOperations
org.omg.PortableInterceptor Provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.

Uses of RequestInfoOperations in org.omg.PortableInterceptor

Subinterfaces of RequestInfoOperations in org.omg.PortableInterceptor
interface | ClientRequestInfo Request Information, accessible to client-side request interceptors.
interface | ClientRequestInfoOperations Request Information, accessible to client-side request interceptors.
interface | RequestInfo Request Information, accessible to Interceptors.
interface | ServerRequestInfo Request Information, accessible to server-side request interceptors.
interface | ServerRequestInfoOperations Request Information, accessible to server-side request interceptors.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableInterceptor.ServerRequestInfo (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableInterceptor.ServerRequestInfo

Packages that use ServerRequestInfo
org.omg.PortableInterceptor Provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.

Uses of ServerRequestInfo in org.omg.PortableInterceptor

Methods in org.omg.PortableInterceptor with parameters of type ServerRequestInfo
void | ServerRequestInterceptorOperations.receive_request_service_contexts(ServerRequestInfo ri) Allows the interceptor to process service context information.
void | ServerRequestInterceptorOperations.receive_request(ServerRequestInfo ri) Allows an Interceptor to query request information after all the information, including operation parameters, are available.
void | ServerRequestInterceptorOperations.send_reply(ServerRequestInfo ri) 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.
void | ServerRequestInterceptorOperations.send_exception(ServerRequestInfo ri) Allows an Interceptor to query the exception information and modify the reply service context before the exception is thrown to the client.
void | ServerRequestInterceptorOperations.send_other(ServerRequestInfo ri) Allows an Interceptor to query the information available when a request results in something other than a normal reply or an exception.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableInterceptor.ServerRequestInfoOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableInterceptor.ServerRequestInfoOperations

Packages that use ServerRequestInfoOperations
org.omg.PortableInterceptor Provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.

Uses of ServerRequestInfoOperations in org.omg.PortableInterceptor

Subinterfaces of ServerRequestInfoOperations in org.omg.PortableInterceptor
 interface ServerRequestInfo
Request Information, accessible to server-side request interceptors.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableInterceptor.ServerRequestInterceptor (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableInterceptor.ServerRequestInterceptor

Packages that use ServerRequestInterceptor
org.omg.PortableInterceptor Provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.

Uses of ServerRequestInterceptor in org.omg.PortableInterceptor

Methods in org.omg.PortableInterceptor with parameters of type ServerRequestInterceptor
 void ORBInitInfoOperations.add_server_request_interceptor(ServerRequestInterceptor interceptor)
Used to add a server-side request Interceptor to the list of server-side request Interceptors.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableInterceptor.ServerRequestInterceptorOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableInterceptor.ServerRequestInterceptorOperations

Packages that use ServerRequestInterceptorOperations
org.omg.PortableInterceptor Provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.

Uses of ServerRequestInterceptorOperations in org.omg.PortableInterceptor

Subinterfaces of ServerRequestInterceptorOperations in org.omg.PortableInterceptor
 interface ServerRequestInterceptor
Server-side request interceptor.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableInterceptor.SUCCESSFUL (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableInterceptor.SUCCESSFUL

No usage of org.omg.PortableInterceptor.SUCCESSFUL

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableInterceptor.SYSTEM_EXCEPTION (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableInterceptor.SYSTEM_EXCEPTION

No usage of org.omg.PortableInterceptor.SYSTEM_EXCEPTION

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableInterceptor.TRANSPORT_RETRY (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableInterceptor.TRANSPORT_RETRY

No usage of org.omg.PortableInterceptor.TRANSPORT_RETRY

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableInterceptor.USER_EXCEPTION (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableInterceptor.USER_EXCEPTION

No usage of org.omg.PortableInterceptor.USER_EXCEPTION

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


DuplicateName (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableInterceptor.ORBInitInfoPackage
Class DuplicateName

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.PortableInterceptor.ORBInitInfoPackage.DuplicateName
All Implemented Interfaces:
IDLEntity, Serializable
public final class DuplicateName
extends UserException

org/omg/PortableInterceptor/ORBInitInfoPackage/DuplicateName.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableInterceptor/Interceptors.idl Thursday, June 12, 2003 9:59:20 PM GMT-08:00

Field Summary
 String name
The name for which there was already an interceptor registered.
Constructor Summary
DuplicateName()
DuplicateName(String _name)
DuplicateName(String $reason, String _name)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

name

public String name
The name for which there was already an interceptor registered.

Constructor Detail

DuplicateName

public DuplicateName()

DuplicateName

public DuplicateName(String _name)

DuplicateName

public DuplicateName(String $reason,
                     String _name)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


DuplicateNameHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableInterceptor.ORBInitInfoPackage
Class DuplicateNameHelper

java.lang.Object
    extended by org.omg.PortableInterceptor.ORBInitInfoPackage.DuplicateNameHelper
public abstract class DuplicateNameHelper
extends Object

org/omg/PortableInterceptor/ORBInitInfoPackage/DuplicateNameHelper.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableInterceptor/Interceptors.idl Thursday, June 12, 2003 9:59:20 PM GMT-08:00

Constructor Summary
DuplicateNameHelper()
Method Summary
static DuplicateName | extract(Any a)
static String | id()
static void | insert(Any a, DuplicateName that)
static DuplicateName | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, DuplicateName value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DuplicateNameHelper

public DuplicateNameHelper()
Method Detail

insert

public static void insert(Any a,
                          DuplicateName that)

extract

public static DuplicateName extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static DuplicateName read(InputStream istream)

write

public static void write(OutputStream ostream,
                         DuplicateName value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


InvalidName (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableInterceptor.ORBInitInfoPackage
Class InvalidName

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.PortableInterceptor.ORBInitInfoPackage.InvalidName
All Implemented Interfaces:
IDLEntity, Serializable
public final class InvalidName
extends UserException

org/omg/PortableInterceptor/ORBInitInfoPackage/InvalidName.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableInterceptor/Interceptors.idl Thursday, June 12, 2003 9:59:20 PM GMT-08:00

Constructor Summary
InvalidName()
InvalidName(String $reason)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

InvalidName

public InvalidName()

InvalidName

public InvalidName(String $reason)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


InvalidNameHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableInterceptor.ORBInitInfoPackage
Class InvalidNameHelper

java.lang.Object
    extended by org.omg.PortableInterceptor.ORBInitInfoPackage.InvalidNameHelper
public abstract class InvalidNameHelper
extends Object

org/omg/PortableInterceptor/ORBInitInfoPackage/InvalidNameHelper.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableInterceptor/Interceptors.idl Thursday, June 12, 2003 9:59:20 PM GMT-08:00

Constructor Summary
InvalidNameHelper()
Method Summary
static InvalidName | extract(Any a)
static String | id()
static void | insert(Any a, InvalidName that)
static InvalidName | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, InvalidName value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

InvalidNameHelper

public InvalidNameHelper()
Method Detail

insert

public static void insert(Any a,
                          InvalidName that)

extract

public static InvalidName extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static InvalidName read(InputStream istream)

write

public static void write(OutputStream ostream,
                         InvalidName value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ObjectIdHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableInterceptor.ORBInitInfoPackage
Class ObjectIdHelper

java.lang.Object
    extended by org.omg.PortableInterceptor.ORBInitInfoPackage.ObjectIdHelper
public abstract class ObjectIdHelper
extends Object

Object id, represented as a String

Constructor Summary
ObjectIdHelper()
Method Summary
static String | extract(Any a)
static String | id()
static void | insert(Any a, String that)
static String | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, String value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ObjectIdHelper

public ObjectIdHelper()
Method Detail

insert

public static void insert(Any a,
                          String that)

extract

public static String extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static String read(InputStream istream)

write

public static void write(OutputStream ostream,
                         String value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


org.omg.PortableInterceptor.ORBInitInfoPackage (Java 2 Platform SE v1.4.2)

 org.omg.PortableInterceptor.ORBInitInfoPackage
Classes
DuplicateNameHelper
InvalidNameHelper
ObjectIdHelper
Exceptions
DuplicateName
InvalidName


org.omg.PortableInterceptor.ORBInitInfoPackage (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

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.

See:
Description

Class Summary
DuplicateNameHelper | org/omg/PortableInterceptor/ORBInitInfoPackage/DuplicateNameHelper.java .
InvalidNameHelper | org/omg/PortableInterceptor/ORBInitInfoPackage/InvalidNameHelper.java .
ObjectIdHelper | Object id, represented as a String

Exception Summary
DuplicateName | org/omg/PortableInterceptor/ORBInitInfoPackage/DuplicateName.java .
InvalidName | org/omg/PortableInterceptor/ORBInitInfoPackage/InvalidName.java .

Package org.omg.PortableInterceptor.ORBInitInfoPackage Description

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. Please refer to that OMG specification for further details.

Package Specification

For a precise list of supported sections of official specifications with which the Java 2 Platform, Standard Edition, v.1.4 ORB complies, see Official Specifications for CORBA support in J2SE 1.4.

Since:
1.4
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


org.omg.PortableInterceptor.ORBInitInfoPackage Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package org.omg.PortableInterceptor.ORBInitInfoPackage

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class org.omg.PortableInterceptor.ORBInitInfoPackage.DuplicateNameHelper
    • class org.omg.PortableInterceptor.ORBInitInfoPackage.InvalidNameHelper
    • class org.omg.PortableInterceptor.ORBInitInfoPackage.ObjectIdHelper
    • class java.lang.Throwable (implements java.io.Serializable)
      • class java.lang.Exception
        • class org.omg.CORBA.UserException (implements org.omg.CORBA.portable.IDLEntity)
          • class org.omg.PortableInterceptor.ORBInitInfoPackage.DuplicateName
          • class org.omg.PortableInterceptor.ORBInitInfoPackage.InvalidName
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package org.omg.PortableInterceptor.ORBInitInfoPackage (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
org.omg.PortableInterceptor.ORBInitInfoPackage

Packages that use org.omg.PortableInterceptor.ORBInitInfoPackage
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 | 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.

Classes in org.omg.PortableInterceptor.ORBInitInfoPackage used by org.omg.PortableInterceptor
DuplicateName
org/omg/PortableInterceptor/ORBInitInfoPackage/DuplicateName.java .
InvalidName
org/omg/PortableInterceptor/ORBInitInfoPackage/InvalidName.java .

Classes in org.omg.PortableInterceptor.ORBInitInfoPackage used by org.omg.PortableInterceptor.ORBInitInfoPackage
DuplicateName
org/omg/PortableInterceptor/ORBInitInfoPackage/DuplicateName.java .
InvalidName
org/omg/PortableInterceptor/ORBInitInfoPackage/InvalidName.java .

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableInterceptor.ORBInitInfoPackage.DuplicateName (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableInterceptor.ORBInitInfoPackage.DuplicateName

Packages that use DuplicateName
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 | 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.

Uses of DuplicateName in org.omg.PortableInterceptor

Methods in org.omg.PortableInterceptor that throw DuplicateName
void | ORBInitInfoOperations.add_client_request_interceptor(ClientRequestInterceptor interceptor) Used to add a client-side request Interceptor to the list of client-side request Interceptors.
void | ORBInitInfoOperations.add_server_request_interceptor(ServerRequestInterceptor interceptor) Used to add a server-side request Interceptor to the list of server-side request Interceptors.
void | ORBInitInfoOperations.add_ior_interceptor(IORInterceptor interceptor) Used to add an IOR Interceptor to the list of IOR Interceptors.

Uses of DuplicateName in org.omg.PortableInterceptor.ORBInitInfoPackage

Methods in org.omg.PortableInterceptor.ORBInitInfoPackage that return DuplicateName
static DuplicateName | DuplicateNameHelper.extract(Any a)
static DuplicateName | DuplicateNameHelper.read(InputStream istream)

Methods in org.omg.PortableInterceptor.ORBInitInfoPackage with parameters of type DuplicateName
static void | DuplicateNameHelper.insert(Any a, DuplicateName that)
static void | DuplicateNameHelper.write(OutputStream ostream, DuplicateName value)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableInterceptor.ORBInitInfoPackage.DuplicateNameHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableInterceptor.ORBInitInfoPackage.DuplicateNameHelper

No usage of org.omg.PortableInterceptor.ORBInitInfoPackage.DuplicateNameHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableInterceptor.ORBInitInfoPackage.InvalidName (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableInterceptor.ORBInitInfoPackage.InvalidName

Packages that use InvalidName
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 | 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.

Uses of InvalidName in org.omg.PortableInterceptor

Methods in org.omg.PortableInterceptor that throw InvalidName
void | ORBInitInfoOperations.register_initial_reference(String id, Object obj) Identical to ORB.register_initial_reference.
Object | ORBInitInfoOperations.resolve_initial_references(String id) Identical to ORB.resolve_initial_references.

Uses of InvalidName in org.omg.PortableInterceptor.ORBInitInfoPackage

Methods in org.omg.PortableInterceptor.ORBInitInfoPackage that return InvalidName
static InvalidName | InvalidNameHelper.extract(Any a)
static InvalidName | InvalidNameHelper.read(InputStream istream)

Methods in org.omg.PortableInterceptor.ORBInitInfoPackage with parameters of type InvalidName
static void | InvalidNameHelper.insert(Any a, InvalidName that)
static void | InvalidNameHelper.write(OutputStream ostream, InvalidName value)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableInterceptor.ORBInitInfoPackage.InvalidNameHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableInterceptor.ORBInitInfoPackage.InvalidNameHelper

No usage of org.omg.PortableInterceptor.ORBInitInfoPackage.InvalidNameHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableInterceptor.ORBInitInfoPackage.ObjectIdHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableInterceptor.ORBInitInfoPackage.ObjectIdHelper

No usage of org.omg.PortableInterceptor.ORBInitInfoPackage.ObjectIdHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


_ServantActivatorStub (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Class _ServantActivatorStub

java.lang.Object
    extended by org.omg.CORBA.portable.ObjectImpl
        extended by org.omg.PortableServer._ServantActivatorStub
All Implemented Interfaces:
IDLEntity, Object, Serializable, ServantActivator, ServantActivatorOperations, ServantManager, ServantManagerOperations
public class _ServantActivatorStub
extends ObjectImpl
implements ServantActivator

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

Field Summary
static Class _opsClass
Constructor Summary
_ServantActivatorStub()
Method Summary
String[] | _ids() Retrieves a string array containing the repository identifiers supported by this ObjectImpl object.
void | etherealize(byte[] oid, POA adapter, Servant serv, boolean cleanup_in_progress, boolean remaining_activations) This operation is invoked whenever a servant for an object is deactivated, assuming the POA has the USE_SERVANT_MANAGER and RETAIN policies.
Servant | incarnate(byte[] oid, POA adapter) This 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 USE_SERVANT_MANAGER and RETAIN policies.
Methods inherited from class org.omg.CORBA.portable.ObjectImpl
_create_request, _create_request, _duplicate, _get_delegate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _invoke, _is_a, _is_equivalent, _is_local, _non_existent, _orb, _release, _releaseReply, _request, _request, _servant_postinvoke, _servant_preinvoke, _set_delegate, _set_policy_override, equals, hashCode, toString
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Field Detail

_opsClass

public static final Class _opsClass
Constructor Detail

_ServantActivatorStub

public _ServantActivatorStub()
Method Detail

incarnate

public Servant incarnate(byte[] oid,
                         POA adapter)
                  throws ForwardRequest
This 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 USE_SERVANT_MANAGER and RETAIN policies.

Specified by:
incarnate in interface ServantActivatorOperations
Parameters:
oid - object Id associated with the object on the request was made.
adapter - object reference for the POA in which the object is being activated.
Returns:
Servant corresponding to oid is created or located by the user supplied servant manager.
Throws:
ForwardRequest - to indicate to the ORB that it is responsible for delivering the current request and subsequent requests to the object denoted in the forward_reference member of the exception.

etherealize

public void etherealize(byte[] oid,
                        POA adapter,
                        Servant serv,
                        boolean cleanup_in_progress,
                        boolean remaining_activations)
This operation is invoked whenever a servant for an object is deactivated, assuming the POA has the USE_SERVANT_MANAGER and RETAIN policies.

Specified by:
etherealize in interface ServantActivatorOperations
Parameters:
oid - object Id associated with the object being deactivated.
adapter - object reference for the POA in which the object was active.
serv - contains reference to the servant associated with the object being deactivated.
cleanup_in_progress - if TRUE indicates that destroy or deactivate is called with etherealize_objects param of TRUE. FALSE indicates that etherealize was called due to other reasons.
remaining_activations - indicates whether the Servant Manager can destroy a servant. If set to TRUE, the Servant Manager should wait until all invocations in progress have completed.

_ids

public String[] _ids()
Description copied from class: ObjectImpl
Retrieves a string array containing the repository identifiers supported by this ObjectImpl object. For example, for a stub, this method returns information about all the interfaces supported by the stub.

Specified by:
_ids in class ObjectImpl
Returns:
the array of all repository identifiers supported by this ObjectImpl instance
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


_ServantLocatorStub (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Class _ServantLocatorStub

java.lang.Object
    extended by org.omg.CORBA.portable.ObjectImpl
        extended by org.omg.PortableServer._ServantLocatorStub
All Implemented Interfaces:
IDLEntity, Object, Serializable, ServantLocator, ServantLocatorOperations, ServantManager, ServantManagerOperations
public class _ServantLocatorStub
extends ObjectImpl
implements 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.

Field Summary
static Class _opsClass
Constructor Summary
_ServantLocatorStub()
Method Summary
String[] | _ids() Retrieves a string array containing the repository identifiers supported by this ObjectImpl object.
void | postinvoke(byte[] oid, POA adapter, String operation, Object the_cookie, Servant the_servant) This operation is invoked whenener a servant completes a request.
Servant | preinvoke(byte[] oid, POA adapter, String operation, CookieHolder the_cookie) This operations is used to get a servant that will be used to process the request that caused preinvoke to be called.
Methods inherited from class org.omg.CORBA.portable.ObjectImpl
_create_request, _create_request, _duplicate, _get_delegate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _invoke, _is_a, _is_equivalent, _is_local, _non_existent, _orb, _release, _releaseReply, _request, _request, _servant_postinvoke, _servant_preinvoke, _set_delegate, _set_policy_override, equals, hashCode, toString
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Field Detail

_opsClass

public static final Class _opsClass
Constructor Detail

_ServantLocatorStub

public _ServantLocatorStub()
Method Detail

preinvoke

public Servant preinvoke(byte[] oid,
                         POA adapter,
                         String operation,
                         CookieHolder the_cookie)
                  throws ForwardRequest
This operations is used to get a servant that will be used to process the request that caused preinvoke to be called.

Specified by:
preinvoke in interface ServantLocatorOperations
Parameters:
oid - the object id associated with object on which the request was made.
adapter - the reference for POA in which the object is being activated.
operation - the operation name.
the_cookie - an opaque value that can be set by the servant manager to be used during postinvoke.
Returns:
Servant used to process incoming request.
Throws:
ForwardRequest - to indicate to the ORB that it is responsible for delivering the current request and subsequent requests to the object denoted in the forward_reference member of the exception.

postinvoke

public void postinvoke(byte[] oid,
                       POA adapter,
                       String operation,
                       Object the_cookie,
                       Servant the_servant)
This operation is invoked whenener a servant completes a request.

Specified by:
postinvoke in interface ServantLocatorOperations
Parameters:
oid - the object id ssociated with object on which the request was made.
adapter - the reference for POA in which the object was active.
the_cookie - an opaque value that contains the data set by preinvoke.
the_servant - reference to the servant that is associated with the object.

_ids

public String[] _ids()
Description copied from class: ObjectImpl
Retrieves a string array containing the repository identifiers supported by this ObjectImpl object. For example, for a stub, this method returns information about all the interfaces supported by the stub.

Specified by:
_ids in class ObjectImpl
Returns:
the array of all repository identifiers supported by this ObjectImpl instance
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


AdapterActivator (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Interface AdapterActivator

All Superinterfaces:
AdapterActivatorOperations, IDLEntity, Object, Serializable
public interface AdapterActivator
extends AdapterActivatorOperations, Object, IDLEntity

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 find_POA is called with an activate parameter value of TRUE.

Methods inherited from interface org.omg.PortableServer.AdapterActivatorOperations
unknown_adapter
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


AdapterActivatorOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Interface AdapterActivatorOperations

All Known Subinterfaces:
AdapterActivator
public interface AdapterActivatorOperations

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 find_POA is called with an activate parameter value of TRUE.

Method Summary
 boolean unknown_adapter(POA parent, String name)
This operation is invoked when the ORB receives a request for an object reference that identifies a target POA that does not exist.

Method Detail

unknown_adapter

public boolean unknown_adapter(POA parent,
                               String name)
This operation is invoked when the ORB receives a request for an object reference that identifies a target POA that does not exist. The ORB invokes this operation once for each POA that must be created in order for the target POA to exist.

Parameters:
parent - indicates the parent POA for the POA that needs to be created.
name - identifies the name of the POA relative to the parent.
Returns:
returns TRUE if the POA was created or FALSE otherwise.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Current (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Interface Current

All Superinterfaces:
Current, CurrentOperations, CurrentOperations, IDLEntity, Object, Serializable
public interface Current
extends CurrentOperations, Current, IDLEntity

The PortableServer::Current interface, derived from CORBA::Current, provides method implementations with access to the identity of the object on which the method was invoked. The Current interface is provided to support servants that implement multiple objects, but can be used within the context of POA-dispatched method invocations on any servant. To provide location transparency, ORBs are required to support use of Current in the context of both locally and remotely invoked operations. An instance of Current can be obtained by the application by issuing the CORBA::ORB::resolve_initial_references("POACurrent") operation. Thereafter, it can be used within the context of a method dispatched by the POA to obtain the POA and ObjectId that identify the object on which that operation was invoked.

Methods inherited from interface org.omg.PortableServer.CurrentOperations
get_object_id, get_POA
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


CurrentHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Class CurrentHelper

java.lang.Object
    extended by org.omg.PortableServer.CurrentHelper
public abstract class CurrentHelper
extends Object

The PortableServer::Current interface, derived from CORBA::Current, provides method implementations with access to the identity of the object on which the method was invoked. The Current interface is provided to support servants that implement multiple objects, but can be used within the context of POA-dispatched method invocations on any servant. To provide location transparency, ORBs are required to support use of Current in the context of both locally and remotely invoked operations. An instance of Current can be obtained by the application by issuing the CORBA::ORB::resolve_initial_references("POACurrent") operation. Thereafter, it can be used within the context of a method dispatched by the POA to obtain the POA and ObjectId that identify the object on which that operation was invoked.

Constructor Summary
CurrentHelper()
Method Summary
static Current | extract(Any a)
static String | id()
static void | insert(Any a, Current that)
static Current | narrow(Object obj)
static Current | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, Current value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

CurrentHelper

public CurrentHelper()
Method Detail

insert

public static void insert(Any a,
                          Current that)

extract

public static Current extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static Current read(InputStream istream)

write

public static void write(OutputStream ostream,
                         Current value)

narrow

public static Current narrow(Object obj)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


CurrentOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Interface CurrentOperations

All Superinterfaces:
CurrentOperations
All Known Subinterfaces:
Current
public interface CurrentOperations
extends CurrentOperations

The PortableServer::Current interface, derived from CORBA::Current, provides method implementations with access to the identity of the object on which the method was invoked. The Current interface is provided to support servants that implement multiple objects, but can be used within the context of POA-dispatched method invocations on any servant. To provide location transparency, ORBs are required to support use of Current in the context of both locally and remotely invoked operations. An instance of Current can be obtained by the application by issuing the CORBA::ORB::resolve_initial_references("POACurrent") operation. Thereafter, it can be used within the context of a method dispatched by the POA to obtain the POA and ObjectId that identify the object on which that operation was invoked.

Method Summary
byte[] | get_object_id() Returns the ObjectId identifying the object in whose context it is called.
POA | get_POA() Returns reference to the POA implementing the object in whose context it is called.

Method Detail

get_POA

public POA get_POA()
            throws NoContext
Returns reference to the POA implementing the object in whose context it is called.

Returns:
The poa implementing the object
Throws:
NoContext - is raised when the operation is outside the context of a POA-dispatched operation

get_object_id

public byte[] get_object_id()
                     throws NoContext
Returns the ObjectId identifying the object in whose context it is called.

Returns:
the ObjectId of the object
Throws:
NoContext - is raised when the operation is called outside the context of a POA-dispatched operation.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DynamicImplementation (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Class DynamicImplementation

java.lang.Object
    extended by org.omg.PortableServer.Servant
        extended by org.omg.PortableServer.DynamicImplementation
public abstract class DynamicImplementation
extends Servant

Allows dynamic handling of object invocations. POA-based DSI servants inherit from the standard DynamicImplementation class, this class inherits from the Servant class. Based on IDL to Java spec. CORBA V 2.3.1 ptc/00-01-08.pdf.

Constructor Summary
DynamicImplementation()
Method Summary
abstract  void invoke(ServerRequest request)
Receives requests issued to any CORBA object incarnated by the DSI servant and performs the processing necessary to execute the request.
Methods inherited from class org.omg.PortableServer.Servant
_all_interfaces, _default_POA, _get_delegate, _get_interface_def, _is_a, _non_existent, _object_id, _orb, _poa, _set_delegate, _this_object, _this_object
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DynamicImplementation

public DynamicImplementation()
Method Detail

invoke

public abstract void invoke(ServerRequest request)
Receives requests issued to any CORBA object incarnated by the DSI servant and performs the processing necessary to execute the request.

Parameters:
request - the request issued to the CORBA object.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ForwardRequest (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Class ForwardRequest

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.PortableServer.ForwardRequest
All Implemented Interfaces:
IDLEntity, Serializable
public final class ForwardRequest
extends UserException

org/omg/PortableServer/ForwardRequest.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableServer/poa.idl Thursday, June 12, 2003 9:59:10 PM GMT-08:00

Field Summary
 Object forward_reference
Constructor Summary
ForwardRequest()
ForwardRequest(Object _forward_reference)
ForwardRequest(String $reason, Object _forward_reference)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

forward_reference

public Object forward_reference
Constructor Detail

ForwardRequest

public ForwardRequest()

ForwardRequest

public ForwardRequest(Object _forward_reference)

ForwardRequest

public ForwardRequest(String $reason,
                      Object _forward_reference)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


ForwardRequestHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Class ForwardRequestHelper

java.lang.Object
    extended by org.omg.PortableServer.ForwardRequestHelper
public abstract class ForwardRequestHelper
extends Object

org/omg/PortableServer/ForwardRequestHelper.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableServer/poa.idl Thursday, June 12, 2003 9:59:10 PM GMT-08:00

Constructor Summary
ForwardRequestHelper()
Method Summary
static ForwardRequest | extract(Any a)
static String | id()
static void | insert(Any a, ForwardRequest that)
static ForwardRequest | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, ForwardRequest value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ForwardRequestHelper

public ForwardRequestHelper()
Method Detail

insert

public static void insert(Any a,
                          ForwardRequest that)

extract

public static ForwardRequest extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static ForwardRequest read(InputStream istream)

write

public static void write(OutputStream ostream,
                         ForwardRequest value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ID_ASSIGNMENT_POLICY_ID (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Interface ID_ASSIGNMENT_POLICY_ID

public interface ID_ASSIGNMENT_POLICY_ID

org/omg/PortableServer/ID_ASSIGNMENT_POLICY_ID.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableServer/poa.idl Thursday, June 12, 2003 9:59:10 PM GMT-08:00

Field Summary
static int value
The value representing ID_ASSIGNMENT_POLICY_ID.

Field Detail

value

public static final int value
The value representing ID_ASSIGNMENT_POLICY_ID.

See Also:
Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ID_UNIQUENESS_POLICY_ID (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Interface ID_UNIQUENESS_POLICY_ID

public interface ID_UNIQUENESS_POLICY_ID

org/omg/PortableServer/ID_UNIQUENESS_POLICY_ID.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableServer/poa.idl Thursday, June 12, 2003 9:59:10 PM GMT-08:00

Field Summary
static int value
The value representing ID_UNIQUENESS_POLICY_ID.

Field Detail

value

public static final int value
The value representing ID_UNIQUENESS_POLICY_ID.

See Also:
Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


IdAssignmentPolicy (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Interface IdAssignmentPolicy

All Superinterfaces:
IdAssignmentPolicyOperations, IDLEntity, Object, Policy, PolicyOperations, Serializable
public interface IdAssignmentPolicy
extends IdAssignmentPolicyOperations, Policy, IDLEntity

IdAssignmentPolicy specifies whether Object Ids in the created POA are generated by the application or by the ORB. The default is SYSTEM_ID.

Methods inherited from interface org.omg.PortableServer.IdAssignmentPolicyOperations
value
Methods inherited from interface org.omg.CORBA.PolicyOperations
copy, destroy, policy_type
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


IdAssignmentPolicyOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Interface IdAssignmentPolicyOperations

All Superinterfaces:
PolicyOperations
All Known Subinterfaces:
IdAssignmentPolicy
public interface IdAssignmentPolicyOperations
extends PolicyOperations

IdAssignmentPolicy specifies whether Object Ids in the created POA are generated by the application or by the ORB. The default is SYSTEM_ID.

Method Summary
 IdAssignmentPolicyValue value()
specifies the policy value
Methods inherited from interface org.omg.CORBA.PolicyOperations
copy, destroy, policy_type

Method Detail

value

public IdAssignmentPolicyValue value()
specifies the policy value

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


IdAssignmentPolicyValue (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Class IdAssignmentPolicyValue

java.lang.Object
    extended by org.omg.PortableServer.IdAssignmentPolicyValue
All Implemented Interfaces:
IDLEntity, Serializable
public class IdAssignmentPolicyValue
extends Object
implements IDLEntity

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 Object Ids only by the POA. If the POA also has the PERSISTENT policy, assigned Object Ids must be unique across all instantiations of the same POA.

Field Summary
static int | _SYSTEM_ID
static int | _USER_ID
static IdAssignmentPolicyValue | SYSTEM_ID
static IdAssignmentPolicyValue | USER_ID
Constructor Summary
protected IdAssignmentPolicyValue(int value)
Method Summary
static IdAssignmentPolicyValue | from_int(int value)
int | value()
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

_USER_ID

public static final int _USER_ID
See Also:
Constant Field Values

USER_ID

public static final IdAssignmentPolicyValue USER_ID

_SYSTEM_ID

public static final int _SYSTEM_ID
See Also:
Constant Field Values

SYSTEM_ID

public static final IdAssignmentPolicyValue SYSTEM_ID
Constructor Detail

IdAssignmentPolicyValue

protected IdAssignmentPolicyValue(int value)
Method Detail

value

public int value()

from_int

public static IdAssignmentPolicyValue from_int(int value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


IdUniquenessPolicy (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Interface IdUniquenessPolicy

All Superinterfaces:
IDLEntity, IdUniquenessPolicyOperations, Object, Policy, PolicyOperations, Serializable
public interface IdUniquenessPolicy
extends IdUniquenessPolicyOperations, Policy, IDLEntity

The IdUniquenessPolicy specifies whether the servants activated in the created POA must have unique object i identities. The default is UNIQUE_ID.

Methods inherited from interface org.omg.PortableServer.IdUniquenessPolicyOperations
value
Methods inherited from interface org.omg.CORBA.PolicyOperations
copy, destroy, policy_type
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


IdUniquenessPolicyOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Interface IdUniquenessPolicyOperations

All Superinterfaces:
PolicyOperations
All Known Subinterfaces:
IdUniquenessPolicy
public interface IdUniquenessPolicyOperations
extends PolicyOperations

The IdUniquenessPolicy specifies whether the servants activated in the created POA must have unique object i identities. The default is UNIQUE_ID.

Method Summary
 IdUniquenessPolicyValue value()
specifies the policy value
Methods inherited from interface org.omg.CORBA.PolicyOperations
copy, destroy, policy_type

Method Detail

value

public IdUniquenessPolicyValue value()
specifies the policy value

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


IdUniquenessPolicyValue (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Class IdUniquenessPolicyValue

java.lang.Object
    extended by org.omg.PortableServer.IdUniquenessPolicyValue
All Implemented Interfaces:
IDLEntity, Serializable
public class IdUniquenessPolicyValue
extends Object
implements IDLEntity

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.

Field Summary
static int | _MULTIPLE_ID
static int | _UNIQUE_ID
static IdUniquenessPolicyValue | MULTIPLE_ID
static IdUniquenessPolicyValue | UNIQUE_ID
Constructor Summary
protected IdUniquenessPolicyValue(int value)
Method Summary
static IdUniquenessPolicyValue | from_int(int value)
int | value()
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

_UNIQUE_ID

public static final int _UNIQUE_ID
See Also:
Constant Field Values

UNIQUE_ID

public static final IdUniquenessPolicyValue UNIQUE_ID

_MULTIPLE_ID

public static final int _MULTIPLE_ID
See Also:
Constant Field Values

MULTIPLE_ID

public static final IdUniquenessPolicyValue MULTIPLE_ID
Constructor Detail

IdUniquenessPolicyValue

protected IdUniquenessPolicyValue(int value)
Method Detail

value

public int value()

from_int

public static IdUniquenessPolicyValue from_int(int value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


IMPLICIT_ACTIVATION_POLICY_ID (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Interface IMPLICIT_ACTIVATION_POLICY_ID

public interface IMPLICIT_ACTIVATION_POLICY_ID

org/omg/PortableServer/IMPLICIT_ACTIVATION_POLICY_ID.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableServer/poa.idl Thursday, June 12, 2003 9:59:10 PM GMT-08:00

Field Summary
static int value
The value representing IMPLICIT_ACTIVATION_POLICY_ID.

Field Detail

value

public static final int value
The value representing IMPLICIT_ACTIVATION_POLICY_ID.

See Also:
Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ImplicitActivationPolicy (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Interface ImplicitActivationPolicy

All Superinterfaces:
IDLEntity, ImplicitActivationPolicyOperations, Object, Policy, PolicyOperations, Serializable
public interface ImplicitActivationPolicy
extends ImplicitActivationPolicyOperations, Policy, IDLEntity

This policy specifies whether implicit activation of servants is supported in the created POA.

Methods inherited from interface org.omg.PortableServer.ImplicitActivationPolicyOperations
value
Methods inherited from interface org.omg.CORBA.PolicyOperations
copy, destroy, policy_type
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ImplicitActivationPolicyOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Interface ImplicitActivationPolicyOperations

All Superinterfaces:
PolicyOperations
All Known Subinterfaces:
ImplicitActivationPolicy
public interface ImplicitActivationPolicyOperations
extends PolicyOperations

This policy specifies whether implicit activation of servants is supported in the created POA.

Method Summary
 ImplicitActivationPolicyValue value()
specifies the policy value
Methods inherited from interface org.omg.CORBA.PolicyOperations
copy, destroy, policy_type

Method Detail

value

public ImplicitActivationPolicyValue value()
specifies the policy value

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ImplicitActivationPolicyValue (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Class ImplicitActivationPolicyValue

java.lang.Object
    extended by org.omg.PortableServer.ImplicitActivationPolicyValue
All Implemented Interfaces:
IDLEntity, Serializable
public class ImplicitActivationPolicyValue
extends Object
implements IDLEntity

ImplicitActivationPolicyValue has the following semantics. IMPLICIT_ACTIVATION to indicate implicit activation of servants. This requires SYSTEM_ID and RETAIN policies to be set. NO_IMPLICIT_ACTIVATION to indicate no implicit servant activation.

Field Summary
static int | _IMPLICIT_ACTIVATION
static int | _NO_IMPLICIT_ACTIVATION
static ImplicitActivationPolicyValue | IMPLICIT_ACTIVATION
static ImplicitActivationPolicyValue | NO_IMPLICIT_ACTIVATION
Constructor Summary
protected ImplicitActivationPolicyValue(int value)
Method Summary
static ImplicitActivationPolicyValue | from_int(int value)
int | value()
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

_IMPLICIT_ACTIVATION

public static final int _IMPLICIT_ACTIVATION
See Also:
Constant Field Values

IMPLICIT_ACTIVATION

public static final ImplicitActivationPolicyValue IMPLICIT_ACTIVATION

_NO_IMPLICIT_ACTIVATION

public static final int _NO_IMPLICIT_ACTIVATION
See Also:
Constant Field Values

NO_IMPLICIT_ACTIVATION

public static final ImplicitActivationPolicyValue NO_IMPLICIT_ACTIVATION
Constructor Detail

ImplicitActivationPolicyValue

protected ImplicitActivationPolicyValue(int value)
Method Detail

value

public int value()

from_int

public static ImplicitActivationPolicyValue from_int(int value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


LIFESPAN_POLICY_ID (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Interface LIFESPAN_POLICY_ID

public interface LIFESPAN_POLICY_ID

org/omg/PortableServer/LIFESPAN_POLICY_ID.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableServer/poa.idl Thursday, June 12, 2003 9:59:10 PM GMT-08:00

Field Summary
static int value
The value representing LIFESPAN_POLICY_ID.

Field Detail

value

public static final int value
The value representing LIFESPAN_POLICY_ID.

See Also:
Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


LifespanPolicy (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Interface LifespanPolicy

All Superinterfaces:
IDLEntity, LifespanPolicyOperations, Object, Policy, PolicyOperations, Serializable
public interface LifespanPolicy
extends LifespanPolicyOperations, Policy, IDLEntity

The LifespanPolicy specifies the lifespan of the objects implemented in the created POA. The default is TRANSIENT.

Methods inherited from interface org.omg.PortableServer.LifespanPolicyOperations
value
Methods inherited from interface org.omg.CORBA.PolicyOperations
copy, destroy, policy_type
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


LifespanPolicyOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Interface LifespanPolicyOperations

All Superinterfaces:
PolicyOperations
All Known Subinterfaces:
LifespanPolicy
public interface LifespanPolicyOperations
extends PolicyOperations

The LifespanPolicy specifies the lifespan of the objects implemented in the created POA. The default is TRANSIENT.

Method Summary
 LifespanPolicyValue value()
specifies the policy value
Methods inherited from interface org.omg.CORBA.PolicyOperations
copy, destroy, policy_type

Method Detail

value

public LifespanPolicyValue value()
specifies the policy value

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


LifespanPolicyValue (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Class LifespanPolicyValue

java.lang.Object
    extended by org.omg.PortableServer.LifespanPolicyValue
All Implemented Interfaces:
IDLEntity, Serializable
public class LifespanPolicyValue
extends Object
implements IDLEntity

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.

Field Summary
static int | _PERSISTENT
static int | _TRANSIENT
static LifespanPolicyValue | PERSISTENT
static LifespanPolicyValue | TRANSIENT
Constructor Summary
protected LifespanPolicyValue(int value)
Method Summary
static LifespanPolicyValue | from_int(int value)
int | value()
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

_TRANSIENT

public static final int _TRANSIENT
See Also:
Constant Field Values

TRANSIENT

public static final LifespanPolicyValue TRANSIENT

_PERSISTENT

public static final int _PERSISTENT
See Also:
Constant Field Values

PERSISTENT

public static final LifespanPolicyValue PERSISTENT
Constructor Detail

LifespanPolicyValue

protected LifespanPolicyValue(int value)
Method Detail

value

public int value()

from_int

public static LifespanPolicyValue from_int(int value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


org.omg.PortableServer (Java 2 Platform SE v1.4.2)

 org.omg.PortableServer
Interfaces
AdapterActivator
AdapterActivatorOperations
Current
CurrentOperations
ID_ASSIGNMENT_POLICY_ID
ID_UNIQUENESS_POLICY_ID
IdAssignmentPolicy
IdAssignmentPolicyOperations
IdUniquenessPolicy
IdUniquenessPolicyOperations
IMPLICIT_ACTIVATION_POLICY_ID
ImplicitActivationPolicy
ImplicitActivationPolicyOperations
LIFESPAN_POLICY_ID
LifespanPolicy
LifespanPolicyOperations
POA
POAManager
POAManagerOperations
POAOperations
REQUEST_PROCESSING_POLICY_ID
RequestProcessingPolicy
RequestProcessingPolicyOperations
SERVANT_RETENTION_POLICY_ID
ServantActivator
ServantActivatorOperations
ServantLocator
ServantLocatorOperations
ServantManager
ServantManagerOperations
ServantRetentionPolicy
ServantRetentionPolicyOperations
THREAD_POLICY_ID
ThreadPolicy
ThreadPolicyOperations
Classes
_ServantActivatorStub
_ServantLocatorStub
CurrentHelper
DynamicImplementation
ForwardRequestHelper
IdAssignmentPolicyValue
IdUniquenessPolicyValue
ImplicitActivationPolicyValue
LifespanPolicyValue
POAHelper
RequestProcessingPolicyValue
Servant
ServantActivatorHelper
ServantActivatorPOA
ServantLocatorHelper
ServantLocatorPOA
ServantRetentionPolicyValue
ThreadPolicyValue
Exceptions
ForwardRequest


org.omg.PortableServer (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package org.omg.PortableServer

Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

See:
Description

Interface Summary
AdapterActivator | 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 find_POA is called with an activate parameter value of TRUE.
AdapterActivatorOperations | 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 find_POA is called with an activate parameter value of TRUE.
Current | The PortableServer::Current interface, derived from CORBA::Current, provides method implementations with access to the identity of the object on which the method was invoked.
CurrentOperations | The PortableServer::Current interface, derived from CORBA::Current, provides method implementations with access to the identity of the object on which the method was invoked.
ID_ASSIGNMENT_POLICY_ID | org/omg/PortableServer/ID_ASSIGNMENT_POLICY_ID.java .
ID_UNIQUENESS_POLICY_ID | org/omg/PortableServer/ID_UNIQUENESS_POLICY_ID.java .
IdAssignmentPolicy | IdAssignmentPolicy specifies whether Object Ids in the created POA are generated by the application or by the ORB.
IdAssignmentPolicyOperations | IdAssignmentPolicy specifies whether Object Ids in the created POA are generated by the application or by the ORB.
IdUniquenessPolicy | The IdUniquenessPolicy specifies whether the servants activated in the created POA must have unique object i identities.
IdUniquenessPolicyOperations | The IdUniquenessPolicy specifies whether the servants activated in the created POA must have unique object i identities.
IMPLICIT_ACTIVATION_POLICY_ID | org/omg/PortableServer/IMPLICIT_ACTIVATION_POLICY_ID.java .
ImplicitActivationPolicy | This policy specifies whether implicit activation of servants is supported in the created POA.
ImplicitActivationPolicyOperations | This policy specifies whether implicit activation of servants is supported in the created POA.
LIFESPAN_POLICY_ID | org/omg/PortableServer/LIFESPAN_POLICY_ID.java .
LifespanPolicy | The LifespanPolicy specifies the lifespan of the objects implemented in the created POA.
LifespanPolicyOperations | The LifespanPolicy specifies the lifespan of the objects implemented in the created POA.
POA | A POA object manages the implementation of a collection of objects.
POAManager | Each POA object has an associated POAManager object.
POAManagerOperations | Each POA object has an associated POAManager object.
POAOperations | A POA object manages the implementation of a collection of objects.
REQUEST_PROCESSING_POLICY_ID | org/omg/PortableServer/REQUEST_PROCESSING_POLICY_ID.java .
RequestProcessingPolicy | This policy specifies how requests are processed by the created POA.
RequestProcessingPolicyOperations | This policy specifies how requests are processed by the created POA.
SERVANT_RETENTION_POLICY_ID | org/omg/PortableServer/SERVANT_RETENTION_POLICY_ID.java .
ServantActivator | When the POA has the RETAIN policy it uses servant managers that are ServantActivators.
ServantActivatorOperations | When the POA has the RETAIN policy it uses servant managers that are ServantActivators.
ServantLocator | When the POA has the NON_RETAIN policy it uses servant managers that are ServantLocators.
ServantLocatorOperations | When the POA has the NON_RETAIN policy it uses servant managers that are ServantLocators.
ServantManager | 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 | 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.
ServantRetentionPolicy | This policy specifies whether the created POA retains active servants in an Active Object Map.
ServantRetentionPolicyOperations | This policy specifies whether the created POA retains active servants in an Active Object Map.
THREAD_POLICY_ID | org/omg/PortableServer/THREAD_POLICY_ID.java .
ThreadPolicy | The ThreadPolicy specifies the threading model used with the created POA.
ThreadPolicyOperations | The ThreadPolicy specifies the threading model used with the created POA.

Class Summary
_ServantActivatorStub | When the POA has the RETAIN policy it uses servant managers that are ServantActivators.
_ServantLocatorStub | When the POA has the NON_RETAIN policy it uses servant managers that are ServantLocators.
CurrentHelper | The PortableServer::Current interface, derived from CORBA::Current, provides method implementations with access to the identity of the object on which the method was invoked.
DynamicImplementation | Allows dynamic handling of object invocations.
ForwardRequestHelper | org/omg/PortableServer/ForwardRequestHelper.java .
IdAssignmentPolicyValue | The IdAssignmentPolicyValue can have the following values.
IdUniquenessPolicyValue | IdUniquenessPolicyValue can have the following values.
ImplicitActivationPolicyValue | ImplicitActivationPolicyValue has the following semantics.
LifespanPolicyValue | The LifespanPolicyValue can have the following values.
POAHelper | A POA object manages the implementation of a collection of objects.
RequestProcessingPolicyValue | The RequestProcessingPolicyValue can have the following values.
Servant | Defines the native Servant type.
ServantActivatorHelper | When the POA has the RETAIN policy it uses servant managers that are ServantActivators.
ServantActivatorPOA | When the POA has the RETAIN policy it uses servant managers that are ServantActivators.
ServantLocatorHelper | When the POA has the NON_RETAIN policy it uses servant managers that are ServantLocators.
ServantLocatorPOA | When the POA has the NON_RETAIN policy it uses servant managers that are ServantLocators.
ServantRetentionPolicyValue | ServantRetentionPolicyValue can have the following values.
ThreadPolicyValue | The ThreadPolicyValue can have the following values.

Exception Summary
ForwardRequest org/omg/PortableServer/ForwardRequest.java .

Package org.omg.PortableServer Description

Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

In Java, Portable Object Adaptor (POA)-based Dynamic Skeleton Interface (DSI) servants inherit from the standard DynamicImplementation class, which inherits from the Servant class. The native Servant type is defined by the PortableServer module for the POA. In Java, 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.

Package Specification

For a precise list of supported sections of official OMG specifications with which the Java 2 Platform, Standard Edition, v.1.4 complies, see Official Specifications for CORBA support in J2SE 1.4.

POA-related Interfaces

The PortableServer module defines the following POA-related interfaces:

  • POA
  • POAManager
  • ServantManager
  • ServantActivator
  • ServantLocator
  • AdapterActivator
  • ThreadPolicy
  • LifespanPolicy
  • IdUniquenessPolicy
  • IdAssignmentPolicy
  • ImplicitActivationPolicy
  • ServantRetentionPolicy
  • RequestProcessingPolicy
  • Current

In addition, the POA defines the Servant native type.

Operations classes

Each of the interfaces listed above has an associated Operations interface. The Operations interface is generated by the idlj compiler and contains the method signatures for methods defined in its associated interface. The Operations interface can be accessed by both the client and the server, while its associated interface can only be called by the client.

Value Classes

Classes ending in the suffix PolicyValue provide the values used for the create_POA call, which sets the policy for the POA. See the sample code below for a demonstration. PolicyValue files include the following:

  • IdAssignmentPolicyValue
  • IdUniquenessPolicyValue
  • ImplicitActivationPolicyValue
  • LifespanPolicyValue
  • RequestProcessingPolicyValue
  • ServantRetentionPolicyValue
  • ThreadPolicyValue

Helper Classes

Helper classes, which are generated for all user-defined types in an OMG IDL interface, supply static methods needed to manipulate those types. There is only one method in a helper class that an application programmer uses: the narrow method. Only Java interfaces mapped from IDL interfaces will have a helper class that includes a narrow method, so in the PortableServer package, only the following classes have a narrow method:

  • ForwardRequestHelper
  • ServantActivatorHelper
  • ServantLocatorHelper

POA Classes

POA classes are used to implement the ServantActivator or ServantLocator.

Exceptions

The ForwardRequest exception indicates to the ORB that it is responsible for delivering the current request and subsequent ForwardRequest requests to the object denoted in the forward_reference member of the exception.

Interfaces Implemented by the Application Programmer

Most of what PortableServer does is transparent to the user. The result is that programmers will use only a few of the interfaces mentioned above. The remaining interfaces will be provided by the ORB implementation. The interfaces of interest to application programmers are the following:

  • AdapterActivator

    Adapter activators are associated with POAs. 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 find_POA is called with an activate parameter value of TRUE. An application server that creates all its needed POAs at the beginning of execution does not need to use or provide an adapter activator; it is necessary only for the case in which POAs need to be created during request processing.

  • ServantLocator

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

  • ServantActivator

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

Package org.omg.PortableServer.ServantLocatorPackage

This package supplies a CookieHolder class for passing the Cookie type as an out parameter. The CookieHolder class follows exactly the same pattern as the other holder classes for basic types.

Related Documentation

For an overview of Java IDL, please see:

  • Java IDL home page.

    Example Code

    Example Server Code

    import javax.naming.InitialContext;
import javax.naming.Context;
import javax.rmi.PortableRemoteObject ;
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();
         //   p.put("org.omg.CORBA.ORBClass", "com.sun.corba.ee.internal.POA.POAORB");
            ORB orb = ORB.init( args, p );

            POA rootPOA = (POA)orb.resolve_initial_references("RootPOA");

            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);

            String  ObjectId = "MyObjectId";
            byte[] oid = ObjectId.getBytes();

            org.omg.CORBA.Object obj = tpoa.create_reference_with_id(oid,
                new _HelloImpl_Tie()._all_interfaces(tpoa, oid)[0]);
            HelloInterface helloRef = (HelloInterface)PortableRemoteObject.narrow(
                obj, HelloInterface.class );

            Context initialNamingContext = new InitialContext();
            initialNamingContext.rebind("HelloService", helloRef);
            System.out.println("Hello Server: Ready...");
            orb.run();
         } catch (Exception e) {
            System.out.println("Trouble: " + e);
            e.printStackTrace();
         }
     }

     public static void main(String args[]) {
         new HelloServer( args );
     }
}

    Since:
    1.4
    Overview Package Class Use Tree Deprecated Index Help
            JavaTM 2 Platform
    Std. Ed. v1.4.2
    PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


org.omg.PortableServer Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package org.omg.PortableServer

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class org.omg.PortableServer.CurrentHelper
    • class org.omg.PortableServer.ForwardRequestHelper
    • class org.omg.PortableServer.IdAssignmentPolicyValue (implements org.omg.CORBA.portable.IDLEntity)
    • class org.omg.PortableServer.IdUniquenessPolicyValue (implements org.omg.CORBA.portable.IDLEntity)
    • class org.omg.PortableServer.ImplicitActivationPolicyValue (implements org.omg.CORBA.portable.IDLEntity)
    • class org.omg.PortableServer.LifespanPolicyValue (implements org.omg.CORBA.portable.IDLEntity)
    • class org.omg.CORBA.portable.ObjectImpl (implements org.omg.CORBA.Object)
      • class org.omg.PortableServer._ServantActivatorStub (implements org.omg.PortableServer.ServantActivator)
      • class org.omg.PortableServer._ServantLocatorStub (implements org.omg.PortableServer.ServantLocator)
    • class org.omg.PortableServer.POAHelper
    • class org.omg.PortableServer.RequestProcessingPolicyValue (implements org.omg.CORBA.portable.IDLEntity)
    • class org.omg.PortableServer.Servant
      • class org.omg.PortableServer.DynamicImplementation
      • class org.omg.PortableServer.ServantActivatorPOA (implements org.omg.CORBA.portable.InvokeHandler, org.omg.PortableServer.ServantActivatorOperations)
      • class org.omg.PortableServer.ServantLocatorPOA (implements org.omg.CORBA.portable.InvokeHandler, org.omg.PortableServer.ServantLocatorOperations)
    • class org.omg.PortableServer.ServantActivatorHelper
    • class org.omg.PortableServer.ServantLocatorHelper
    • class org.omg.PortableServer.ServantRetentionPolicyValue (implements org.omg.CORBA.portable.IDLEntity)
    • class org.omg.PortableServer.ThreadPolicyValue (implements org.omg.CORBA.portable.IDLEntity)
    • class java.lang.Throwable (implements java.io.Serializable)
      • class java.lang.Exception
        • class org.omg.CORBA.UserException (implements org.omg.CORBA.portable.IDLEntity)
          • class org.omg.PortableServer.ForwardRequest

Interface Hierarchy

  • interface org.omg.PortableServer.AdapterActivatorOperations
    • interface org.omg.PortableServer.AdapterActivator (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CORBA.Object)
  • interface org.omg.CORBA.CurrentOperations
    • interface org.omg.CORBA.Current (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CORBA.Object)
      • interface org.omg.PortableServer.Current (also extends org.omg.PortableServer.CurrentOperations, org.omg.CORBA.portable.IDLEntity)
    • interface org.omg.PortableServer.CurrentOperations
      • interface org.omg.PortableServer.Current (also extends org.omg.CORBA.Current, org.omg.CORBA.portable.IDLEntity)
  • interface org.omg.PortableServer.ID_ASSIGNMENT_POLICY_ID
  • interface org.omg.PortableServer.ID_UNIQUENESS_POLICY_ID
  • interface org.omg.PortableServer.IMPLICIT_ACTIVATION_POLICY_ID
  • interface org.omg.PortableServer.LIFESPAN_POLICY_ID
  • interface org.omg.CORBA.Object
    • interface org.omg.PortableServer.AdapterActivator (also extends org.omg.PortableServer.AdapterActivatorOperations, org.omg.CORBA.portable.IDLEntity)
    • interface org.omg.CORBA.Current (also extends org.omg.CORBA.CurrentOperations, org.omg.CORBA.portable.IDLEntity)
      • interface org.omg.PortableServer.Current (also extends org.omg.PortableServer.CurrentOperations, org.omg.CORBA.portable.IDLEntity)
    • interface org.omg.PortableServer.POA (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableServer.POAOperations)
    • interface org.omg.PortableServer.POAManager (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableServer.POAManagerOperations)
    • interface org.omg.CORBA.Policy (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CORBA.PolicyOperations)
      • interface org.omg.PortableServer.IdAssignmentPolicy (also extends org.omg.PortableServer.IdAssignmentPolicyOperations, org.omg.CORBA.portable.IDLEntity)
      • interface org.omg.PortableServer.IdUniquenessPolicy (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableServer.IdUniquenessPolicyOperations)
      • interface org.omg.PortableServer.ImplicitActivationPolicy (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableServer.ImplicitActivationPolicyOperations)
      • interface org.omg.PortableServer.LifespanPolicy (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableServer.LifespanPolicyOperations)
      • interface org.omg.PortableServer.RequestProcessingPolicy (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableServer.RequestProcessingPolicyOperations)
      • interface org.omg.PortableServer.ServantRetentionPolicy (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableServer.ServantRetentionPolicyOperations)
      • interface org.omg.PortableServer.ThreadPolicy (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableServer.ThreadPolicyOperations)
    • interface org.omg.PortableServer.ServantManager (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableServer.ServantManagerOperations)
      • interface org.omg.PortableServer.ServantActivator (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableServer.ServantActivatorOperations)
      • interface org.omg.PortableServer.ServantLocator (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableServer.ServantLocatorOperations)
  • interface org.omg.PortableServer.POAManagerOperations
    • interface org.omg.PortableServer.POAManager (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CORBA.Object)
  • interface org.omg.PortableServer.POAOperations
    • interface org.omg.PortableServer.POA (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CORBA.Object)
  • interface org.omg.CORBA.PolicyOperations
    • interface org.omg.PortableServer.IdAssignmentPolicyOperations
      • interface org.omg.PortableServer.IdAssignmentPolicy (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CORBA.Policy)
    • interface org.omg.PortableServer.IdUniquenessPolicyOperations
      • interface org.omg.PortableServer.IdUniquenessPolicy (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CORBA.Policy)
    • interface org.omg.PortableServer.ImplicitActivationPolicyOperations
      • interface org.omg.PortableServer.ImplicitActivationPolicy (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CORBA.Policy)
    • interface org.omg.PortableServer.LifespanPolicyOperations
      • interface org.omg.PortableServer.LifespanPolicy (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CORBA.Policy)
    • interface org.omg.CORBA.Policy (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CORBA.Object)
      • interface org.omg.PortableServer.IdAssignmentPolicy (also extends org.omg.PortableServer.IdAssignmentPolicyOperations, org.omg.CORBA.portable.IDLEntity)
      • interface org.omg.PortableServer.IdUniquenessPolicy (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableServer.IdUniquenessPolicyOperations)
      • interface org.omg.PortableServer.ImplicitActivationPolicy (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableServer.ImplicitActivationPolicyOperations)
      • interface org.omg.PortableServer.LifespanPolicy (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableServer.LifespanPolicyOperations)
      • interface org.omg.PortableServer.RequestProcessingPolicy (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableServer.RequestProcessingPolicyOperations)
      • interface org.omg.PortableServer.ServantRetentionPolicy (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableServer.ServantRetentionPolicyOperations)
      • interface org.omg.PortableServer.ThreadPolicy (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableServer.ThreadPolicyOperations)
    • interface org.omg.PortableServer.RequestProcessingPolicyOperations
      • interface org.omg.PortableServer.RequestProcessingPolicy (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CORBA.Policy)
    • interface org.omg.PortableServer.ServantRetentionPolicyOperations
      • interface org.omg.PortableServer.ServantRetentionPolicy (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CORBA.Policy)
    • interface org.omg.PortableServer.ThreadPolicyOperations
      • interface org.omg.PortableServer.ThreadPolicy (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CORBA.Policy)
  • interface org.omg.PortableServer.REQUEST_PROCESSING_POLICY_ID
  • interface java.io.Serializable
    • interface org.omg.CORBA.portable.IDLEntity
      • interface org.omg.PortableServer.AdapterActivator (also extends org.omg.PortableServer.AdapterActivatorOperations, org.omg.CORBA.Object)
      • interface org.omg.CORBA.Current (also extends org.omg.CORBA.CurrentOperations, org.omg.CORBA.Object)
        • interface org.omg.PortableServer.Current (also extends org.omg.PortableServer.CurrentOperations, org.omg.CORBA.portable.IDLEntity)
      • interface org.omg.PortableServer.Current (also extends org.omg.CORBA.Current, org.omg.PortableServer.CurrentOperations)
      • interface org.omg.PortableServer.IdAssignmentPolicy (also extends org.omg.PortableServer.IdAssignmentPolicyOperations, org.omg.CORBA.Policy)
      • interface org.omg.PortableServer.IdUniquenessPolicy (also extends org.omg.PortableServer.IdUniquenessPolicyOperations, org.omg.CORBA.Policy)
      • interface org.omg.PortableServer.ImplicitActivationPolicy (also extends org.omg.PortableServer.ImplicitActivationPolicyOperations, org.omg.CORBA.Policy)
      • interface org.omg.PortableServer.LifespanPolicy (also extends org.omg.PortableServer.LifespanPolicyOperations, org.omg.CORBA.Policy)
      • interface org.omg.PortableServer.POA (also extends org.omg.CORBA.Object, org.omg.PortableServer.POAOperations)
      • interface org.omg.PortableServer.POAManager (also extends org.omg.CORBA.Object, org.omg.PortableServer.POAManagerOperations)
      • interface org.omg.CORBA.Policy (also extends org.omg.CORBA.Object, org.omg.CORBA.PolicyOperations)
        • interface org.omg.PortableServer.IdAssignmentPolicy (also extends org.omg.PortableServer.IdAssignmentPolicyOperations, org.omg.CORBA.portable.IDLEntity)
        • interface org.omg.PortableServer.IdUniquenessPolicy (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableServer.IdUniquenessPolicyOperations)
        • interface org.omg.PortableServer.ImplicitActivationPolicy (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableServer.ImplicitActivationPolicyOperations)
        • interface org.omg.PortableServer.LifespanPolicy (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableServer.LifespanPolicyOperations)
        • interface org.omg.PortableServer.RequestProcessingPolicy (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableServer.RequestProcessingPolicyOperations)
        • interface org.omg.PortableServer.ServantRetentionPolicy (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableServer.ServantRetentionPolicyOperations)
        • interface org.omg.PortableServer.ThreadPolicy (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableServer.ThreadPolicyOperations)
      • interface org.omg.PortableServer.RequestProcessingPolicy (also extends org.omg.CORBA.Policy, org.omg.PortableServer.RequestProcessingPolicyOperations)
      • interface org.omg.PortableServer.ServantActivator (also extends org.omg.PortableServer.ServantActivatorOperations, org.omg.PortableServer.ServantManager)
      • interface org.omg.PortableServer.ServantLocator (also extends org.omg.PortableServer.ServantLocatorOperations, org.omg.PortableServer.ServantManager)
      • interface org.omg.PortableServer.ServantManager (also extends org.omg.CORBA.Object, org.omg.PortableServer.ServantManagerOperations)
        • interface org.omg.PortableServer.ServantActivator (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableServer.ServantActivatorOperations)
        • interface org.omg.PortableServer.ServantLocator (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableServer.ServantLocatorOperations)
      • interface org.omg.PortableServer.ServantRetentionPolicy (also extends org.omg.CORBA.Policy, org.omg.PortableServer.ServantRetentionPolicyOperations)
      • interface org.omg.PortableServer.ThreadPolicy (also extends org.omg.CORBA.Policy, org.omg.PortableServer.ThreadPolicyOperations)
  • interface org.omg.PortableServer.SERVANT_RETENTION_POLICY_ID
  • interface org.omg.PortableServer.ServantManagerOperations
    • interface org.omg.PortableServer.ServantActivatorOperations
      • interface org.omg.PortableServer.ServantActivator (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableServer.ServantManager)
    • interface org.omg.PortableServer.ServantLocatorOperations
      • interface org.omg.PortableServer.ServantLocator (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableServer.ServantManager)
    • interface org.omg.PortableServer.ServantManager (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CORBA.Object)
      • interface org.omg.PortableServer.ServantActivator (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableServer.ServantActivatorOperations)
      • interface org.omg.PortableServer.ServantLocator (also extends org.omg.CORBA.portable.IDLEntity, org.omg.PortableServer.ServantLocatorOperations)
  • interface org.omg.PortableServer.THREAD_POLICY_ID
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package org.omg.PortableServer (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
org.omg.PortableServer

Packages that use org.omg.PortableServer
org.omg.CosNaming | Provides a naming service for Java IDL.
org.omg.PortableServer | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.
org.omg.PortableServer.portable | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Classes in org.omg.PortableServer used by org.omg.CosNaming
POA
A POA object manages the implementation of a collection of objects.
Servant
Defines the native Servant type.

Classes in org.omg.PortableServer used by org.omg.PortableServer
AdapterActivator
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 find_POA is called with an activate parameter value of TRUE.
AdapterActivatorOperations
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 find_POA is called with an activate parameter value of TRUE.
Current
The PortableServer::Current interface, derived from CORBA::Current, provides method implementations with access to the identity of the object on which the method was invoked.
CurrentOperations
The PortableServer::Current interface, derived from CORBA::Current, provides method implementations with access to the identity of the object on which the method was invoked.
ForwardRequest
org/omg/PortableServer/ForwardRequest.java .
IdAssignmentPolicy
IdAssignmentPolicy specifies whether Object Ids in the created POA are generated by the application or by the ORB.
IdAssignmentPolicyOperations
IdAssignmentPolicy specifies whether Object Ids in the created POA are generated by the application or by the ORB.
IdAssignmentPolicyValue
The IdAssignmentPolicyValue can have the following values.
IdUniquenessPolicy
The IdUniquenessPolicy specifies whether the servants activated in the created POA must have unique object i identities.
IdUniquenessPolicyOperations
The IdUniquenessPolicy specifies whether the servants activated in the created POA must have unique object i identities.
IdUniquenessPolicyValue
IdUniquenessPolicyValue can have the following values.
ImplicitActivationPolicy
This policy specifies whether implicit activation of servants is supported in the created POA.
ImplicitActivationPolicyOperations
This policy specifies whether implicit activation of servants is supported in the created POA.
ImplicitActivationPolicyValue
ImplicitActivationPolicyValue has the following semantics.
LifespanPolicy
The LifespanPolicy specifies the lifespan of the objects implemented in the created POA.
LifespanPolicyOperations
The LifespanPolicy specifies the lifespan of the objects implemented in the created POA.
LifespanPolicyValue
The LifespanPolicyValue can have the following values.
POA
A POA object manages the implementation of a collection of objects.
POAManager
Each POA object has an associated POAManager object.
POAManagerOperations
Each POA object has an associated POAManager object.
POAOperations
A POA object manages the implementation of a collection of objects.
RequestProcessingPolicy
This policy specifies how requests are processed by the created POA.
RequestProcessingPolicyOperations
This policy specifies how requests are processed by the created POA.
RequestProcessingPolicyValue
The RequestProcessingPolicyValue can have the following values.
Servant
Defines the native Servant type.
ServantActivator
When the POA has the RETAIN policy it uses servant managers that are ServantActivators.
ServantActivatorOperations
When the POA has the RETAIN policy it uses servant managers that are ServantActivators.
ServantLocator
When the POA has the NON_RETAIN policy it uses servant managers that are ServantLocators.
ServantLocatorOperations
When the POA has the NON_RETAIN policy it uses servant managers that are ServantLocators.
ServantManager
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
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.
ServantRetentionPolicy
This policy specifies whether the created POA retains active servants in an Active Object Map.
ServantRetentionPolicyOperations
This policy specifies whether the created POA retains active servants in an Active Object Map.
ServantRetentionPolicyValue
ServantRetentionPolicyValue can have the following values.
ThreadPolicy
The ThreadPolicy specifies the threading model used with the created POA.
ThreadPolicyOperations
The ThreadPolicy specifies the threading model used with the created POA.
ThreadPolicyValue
The ThreadPolicyValue can have the following values.

Classes in org.omg.PortableServer used by org.omg.PortableServer.portable
POA
A POA object manages the implementation of a collection of objects.
Servant
Defines the native Servant type.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


POA (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Interface POA

All Superinterfaces:
IDLEntity, Object, POAOperations, Serializable
public interface POA
extends POAOperations, Object, IDLEntity

A POA object manages the implementation of a collection of objects. The POA supports a name space for the objects, which are identified by Object Ids. A POA also provides a name space for POAs. A POA is created as a child of an existing POA, which forms a hierarchy starting with the root POA. A POA object must not be exported to other processes, or externalized with ORB::object_to_string.

Methods inherited from interface org.omg.PortableServer.POAOperations
activate_object_with_id, activate_object, create_id_assignment_policy, create_id_uniqueness_policy, create_implicit_activation_policy, create_lifespan_policy, create_POA, create_reference_with_id, create_reference, create_request_processing_policy, create_servant_retention_policy, create_thread_policy, deactivate_object, destroy, find_POA, get_servant_manager, get_servant, id_to_reference, id_to_servant, id, reference_to_id, reference_to_servant, servant_to_id, servant_to_reference, set_servant_manager, set_servant, the_activator, the_activator, the_children, the_name, the_parent, the_POAManager
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


POAHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Class POAHelper

java.lang.Object
    extended by org.omg.PortableServer.POAHelper
public abstract class POAHelper
extends Object

A POA object manages the implementation of a collection of objects. The POA supports a name space for the objects, which are identified by Object Ids. A POA also provides a name space for POAs. A POA is created as a child of an existing POA, which forms a hierarchy starting with the root POA. A POA object must not be exported to other processes, or externalized with ORB::object_to_string.

Constructor Summary
POAHelper()
Method Summary
static POA | extract(Any a)
static String | id()
static void | insert(Any a, POA that)
static POA | narrow(Object obj)
static POA | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, POA value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

POAHelper

public POAHelper()
Method Detail

insert

public static void insert(Any a,
                          POA that)

extract

public static POA extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static POA read(InputStream istream)

write

public static void write(OutputStream ostream,
                         POA value)

narrow

public static POA narrow(Object obj)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


POAManager (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Interface POAManager

All Superinterfaces:
IDLEntity, Object, POAManagerOperations, Serializable
public interface POAManager
extends POAManagerOperations, Object, IDLEntity

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.

Methods inherited from interface org.omg.PortableServer.POAManagerOperations
activate, deactivate, discard_requests, get_state, hold_requests
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


POAManagerOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Interface POAManagerOperations

All Known Subinterfaces:
POAManager
public interface POAManagerOperations

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.

Method Summary
void | activate() This operation changes the state of the POA manager to active, causing associated POAs to start processing requests.
void | deactivate(boolean etherealize_objects, boolean wait_for_completion) This operation changes the state of the POA manager to inactive, causing associated POAs to reject the requests that have not begun executing as well as as any new requests.
void | discard_requests(boolean wait_for_completion) This operation changes the state of the POA manager to discarding.
State | get_state() This operation returns the state of the POA manager.
void | hold_requests(boolean wait_for_completion) This operation changes the state of the POA manager to holding, causing associated POAs to queue incoming requests.

Method Detail

activate

public void activate()
              throws AdapterInactive
This operation changes the state of the POA manager to active, causing associated POAs to start processing requests.

Throws:
AdapterInactive - is raised if the operation is invoked on the POAManager in inactive state.

hold_requests

public void hold_requests(boolean wait_for_completion)
                   throws AdapterInactive
This operation changes the state of the POA manager to holding, causing associated POAs to queue incoming requests.

Parameters:
wait_for_completion - if FALSE, the operation returns immediately after changing state. If TRUE, it waits for all active requests to complete.
Throws:
AdapterInactive - is raised if the operation is invoked on the POAManager in inactive state.

discard_requests

public void discard_requests(boolean wait_for_completion)
                      throws AdapterInactive
This operation changes the state of the POA manager to discarding. This causes associated POAs to discard incoming requests.

Parameters:
wait_for_completion - if FALSE, the operation returns immediately after changing state. If TRUE, it waits for all active requests to complete.
Throws:
AdapterInactive - is raised if the operation is invoked on the POAManager in inactive state.

deactivate

public void deactivate(boolean etherealize_objects,
                       boolean wait_for_completion)
                throws AdapterInactive
This operation changes the state of the POA manager to inactive, causing associated POAs to reject the requests that have not begun executing as well as as any new requests.

Parameters:
etherealize_objects - a flag to indicate whether to invoke the etherealize operation of the associated servant manager for all active objects.
wait_for_completion - if FALSE, the operation returns immediately after changing state. If TRUE, it waits for all active requests to complete.
Throws:
AdapterInactive - is raised if the operation is invoked on the POAManager in inactive state.

get_state

public State get_state()
This operation returns the state of the POA manager.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


POAOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Interface POAOperations

All Known Subinterfaces:
POA
public interface POAOperations

A POA object manages the implementation of a collection of objects. The POA supports a name space for the objects, which are identified by Object Ids. A POA also provides a name space for POAs. A POA is created as a child of an existing POA, which forms a hierarchy starting with the root POA. A POA object must not be exported to other processes, or externalized with ORB::object_to_string.

Method Summary
void | activate_object_with_id(byte[] id, Servant p_servant) This operation enters an association between the specified Object Id and the specified servant in the Active Object Map.
byte[] | activate_object(Servant p_servant) This operation generates an Object Id and enters the Object Id and the specified servant in the Active Object Map.
IdAssignmentPolicy | create_id_assignment_policy(IdAssignmentPolicyValue value) These operations each return a reference to a policy object with the specified value.
IdUniquenessPolicy | create_id_uniqueness_policy(IdUniquenessPolicyValue value) These operations each return a reference to a policy object with the specified value.
ImplicitActivationPolicy | create_implicit_activation_policy(ImplicitActivationPolicyValue value) These operations each return a reference to a policy object with the specified value.
LifespanPolicy | create_lifespan_policy(LifespanPolicyValue value) These operations each return a reference to a policy object with the specified value.
POA | create_POA(String adapter_name, POAManager a_POAManager, Policy[] policies) This operation creates a new POA as a child of the target POA.
Object | create_reference_with_id(byte[] oid, String intf) This operation creates an object reference that encapsulates the specified Object Id and interface repository Id values.
Object | create_reference(String intf) This operation creates an object reference that encapsulates a POA-generated Object Id value and the specified interface repository id.
RequestProcessingPolicy | create_request_processing_policy(RequestProcessingPolicyValue value) These operations each return a reference to a policy object with the specified value.
ServantRetentionPolicy | create_servant_retention_policy(ServantRetentionPolicyValue value) These operations each return a reference to a policy object with the specified value.
ThreadPolicy | create_thread_policy(ThreadPolicyValue value) These operations each return a reference to a policy object with the specified value.
void | deactivate_object(byte[] oid) This operation causes the ObjectId specified in the oid parameter to be deactivated.
void | destroy(boolean etherealize_objects, boolean wait_for_completion) This operation destroys the POA and all descendant POAs.
POA | find_POA(String adapter_name, boolean activate_it) If the target POA is the parent of a child POA with the specified name (relative to the target POA), that child POA is returned.
ServantManager | get_servant_manager() If the ServantRetentionPolicy of the POA is RETAIN, then the ServantManager argument (imgr) shall support the ServantActivator interface.
Servant | get_servant() This operation returns the default servant associated with the POA.
Object | id_to_reference(byte[] oid) If an object with the specified Object Id value is currently active, a reference encapsulating the information used to activate the object is returned.
Servant | id_to_servant(byte[] oid) If the POA has the RETAIN policy and the specified ObjectId is in the Active Object Map, this operation returns the servant associated with that object in the Active Object Map.
byte[] | id() This returns the unique id of the POA in the process in which it is created.
byte[] | reference_to_id(Object reference) This operation returns the Object Id value encapsulated by the specified reference.
Servant | reference_to_servant(Object reference) 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.
byte[] | servant_to_id(Servant p_servant) This operation has four possible behaviors.
Object | servant_to_reference(Servant p_servant) 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.
void | set_servant_manager(ServantManager imgr) This operation sets the default servant manager associated with the POA.
void | set_servant(Servant p_servant) This operation registers the specified servant with the POA as the default servant.
AdapterActivator | the_activator() This attribute identifies the adapter activator associated with the POA.
void | the_activator(AdapterActivator newThe_activator) This attribute identifies the adapter activator associated with the POA.
POA[] | the_children() This attribute identifies the current set of all child POAs of the POA.
String | the_name() This attribute identifies the POA relative to its parent.
POA | the_parent() This attribute identifies the parent of the POA.
POAManager | the_POAManager() This attribute identifies the POA manager associated with the POA.

Method Detail

create_POA

public POA create_POA(String adapter_name,
                      POAManager a_POAManager,
                      Policy[] policies)
               throws AdapterAlreadyExists,
                      InvalidPolicy
This operation creates a new POA as a child of the target POA.

Parameters:
adapter_name - identifies the new POA with respect to other POAs with the same parent POA.
a_POAManager - specifies the POA Manager to be associated with the new POA.
policies - specifies policy objects to be associated with the POA to control its behavior.
Throws:
AdapterAlreadyExists - specifies that the target POA already has a child POA with the specified name.
InvalidPolicy - is raised if any of the policy objects are not valid for the ORB, or are in conflict, or require an administrative action that has not been performed.

find_POA

public POA find_POA(String adapter_name,
                    boolean activate_it)
             throws AdapterNonExistent
If the target POA is the parent of a child POA with the specified name (relative to the target POA), that child POA is returned.

Parameters:
adapter_name - POA name to be found.
activate_it - if a POA with the specified name does not exist and the value of the activate_it parameter is TRUE, the target POA's AdapterActivator, if one exists, is invoked.
Returns:
POA if one exists or is activated by the AdapterActivator.
Throws:
AdapterNonExistent

destroy

public void destroy(boolean etherealize_objects,
                    boolean wait_for_completion)
This operation destroys the POA and all descendant POAs. All descendant POAs are destroyed (recursively) before the destruction of the containing POA. The POA so destroyed (that is, the POA with its name) may be re-created later in the same process.

Parameters:
etherealize_objects - flag to indicate whether etherealize operation on servant manager needs to be called.
wait_for_completion - flag to indicate whether POA and its children need to wait for active requests and the etherealization to complete.

create_thread_policy

public ThreadPolicy create_thread_policy(ThreadPolicyValue value)
These operations each return a reference to a policy object with the specified value.

Parameters:
value - policy type
Returns:
ThreadPolcy Object

create_lifespan_policy

public LifespanPolicy create_lifespan_policy(LifespanPolicyValue value)
These operations each return a reference to a policy object with the specified value.

Parameters:
value - policy type
Returns:
LifespanPolicy Object.

create_id_uniqueness_policy

public IdUniquenessPolicy create_id_uniqueness_policy(IdUniquenessPolicyValue value)
These operations each return a reference to a policy object with the specified value.

Parameters:
value - policy type
Returns:
IdUniquenessPolicy Object.

create_id_assignment_policy

public IdAssignmentPolicy create_id_assignment_policy(IdAssignmentPolicyValue value)
These operations each return a reference to a policy object with the specified value.

Parameters:
value - policy type
Returns:
IdAssignmentPolicy Object.

create_implicit_activation_policy

public ImplicitActivationPolicy create_implicit_activation_policy(ImplicitActivationPolicyValue value)
These operations each return a reference to a policy object with the specified value.

Parameters:
value - policy type
Returns:
ImplicitActivationPolicy Object.

create_servant_retention_policy

public ServantRetentionPolicy create_servant_retention_policy(ServantRetentionPolicyValue value)
These operations each return a reference to a policy object with the specified value.

Parameters:
value - policy type
Returns:
ServantRetentionPolicy Object.

create_request_processing_policy

public RequestProcessingPolicy create_request_processing_policy(RequestProcessingPolicyValue value)
These operations each return a reference to a policy object with the specified value.

Parameters:
value - policy type
Returns:
RequestProcessingPolicy Object.

the_name

public String the_name()
This attribute identifies the POA relative to its parent. This name is assigned when the POA is created.

the_parent

public POA the_parent()
This attribute identifies the parent of the POA. The parent of the root POA is null.

the_children

public POA[] the_children()
This attribute identifies the current set of all child POAs of the POA. The set of child POAs includes only the POA's immediate children, and not their descendants.

the_POAManager

public POAManager the_POAManager()
This attribute identifies the POA manager associated with the POA.

the_activator

public AdapterActivator the_activator()
This attribute identifies the adapter activator associated with the POA.

the_activator

public void the_activator(AdapterActivator newThe_activator)
This attribute identifies the adapter activator associated with the POA.

get_servant_manager

public ServantManager get_servant_manager()
                                   throws WrongPolicy
If the ServantRetentionPolicy of the POA is RETAIN, then the ServantManager argument (imgr) shall support the ServantActivator interface. For a NON_RETAIN policy, the ServantManager shall support the ServantLocator interface. If the argument is nil, or does not support the required interface, then the OBJ_ADAPTER exception is raised.

Returns:
ServantManager associated with a POA or null if none exists.
Throws:
WrongPolicy - raised if the USE_SERVANT_MANAGER policy is not specified.

set_servant_manager

public void set_servant_manager(ServantManager imgr)
                         throws WrongPolicy
This operation sets the default servant manager associated with the POA. This operation may only be invoked once after a POA has been created. Attempting to set the servant manager after one has already been set will result in the BAD_INV_ORDER exception being raised.

Parameters:
imgr - servant manager to be used as a default.
Throws:
WrongPolicy - raised if the USE_SERVANT_MANAGER policy is not specified.

get_servant

public Servant get_servant()
                    throws NoServant,
                           WrongPolicy
This operation returns the default servant associated with the POA.

Returns:
p_servant default servant associated with a POA.
Throws:
NoServant - raised if no default servant is associated with the POA.
WrongPolicy - raised if the USE_DEFAULT_SERVANT policy is not specified.

set_servant

public void set_servant(Servant p_servant)
                 throws WrongPolicy
This operation registers the specified servant with the POA as the default servant. This servant will be used for all requests for which no servant is found in the Active Object Map.

Parameters:
p_servant - servant to be used as a default.
Throws:
WrongPolicy - raised if the USE_DEFAULT_SERVANT policy is not specified.

activate_object

public byte[] activate_object(Servant p_servant)
                       throws ServantAlreadyActive,
                              WrongPolicy
This operation generates an Object Id and enters the Object Id and the specified servant in the Active Object Map.

Parameters:
p_servant - servant to be associated with an object to be activated.
Returns:
POA generated object id.
Throws:
ServantAlreadyActive - is raised if the POA has UNIQUE_ID policy and servant is is already in the Active Object Map.
WrongPolicy - raised if the SYSTEM_ID and RETAIN policies are not specified.

activate_object_with_id

public void activate_object_with_id(byte[] id,
                                    Servant p_servant)
                             throws ServantAlreadyActive,
                                    ObjectAlreadyActive,
                                    WrongPolicy
This operation enters an association between the specified Object Id and the specified servant in the Active Object Map.

Parameters:
id - object id for the object to be activated.
p_servant - servant to be associated with the object.
Throws:
ServantAlreadyActive - raised if the POA has the UNIQUE_ID policy and the servant is already in the Active Object Map.
ObjectAlreadyActive - raised if the object is already active in the POA.
WrongPolicy - raised if the RETAIN policy is is not specified.

deactivate_object

public void deactivate_object(byte[] oid)
                       throws ObjectNotActive,
                              WrongPolicy
This operation causes the ObjectId specified in the oid parameter to be deactivated. An ObjectId which has been deactivated continues to process requests until there are no active requests for that ObjectId. A deactivated ObjectId is removed from the Active Object Map when all requests executing for that ObjectId have completed.

Parameters:
oid - Object Id for the object to be deactivated.
Throws:
ObjectNotActive - if the object with the specified oid is not in the Active Object Map.
WrongPolicy - raised if the RETAIN policy is is not specified.

create_reference

public Object create_reference(String intf)
                        throws WrongPolicy
This operation creates an object reference that encapsulates a POA-generated Object Id value and the specified interface repository id.

Parameters:
intf - rep id for creating an object reference.
Returns:
object reference created using intf.
Throws:
WrongPolicy - if SYSTEM_ID policy is not specified.

create_reference_with_id

public Object create_reference_with_id(byte[] oid,
                                       String intf)
This operation creates an object reference that encapsulates the specified Object Id and interface repository Id values. It does not cause an activation to take place. The resulting reference may be passed to clients, so that subsequent requests on those references will cause the object to be activated if necessary, or the default servant used, depending on the applicable policies.

Parameters:
oid - object id for creating an objref
intf - rep id for creating an objref
Returns:
object reference created using oid and intf
Throws:
BAD_PARAM - is raised if the POA has the SYSTEM_ID policy and it detects that the Object Id value was not generated by the system or for this POA.

servant_to_id

public byte[] servant_to_id(Servant p_servant)
                     throws ServantNotActive,
                            WrongPolicy
This operation has four possible behaviors. 1. If the POA has the UNIQUE_ID policy and the specified servant is active, the Object Id associated with that servant is returned. 2. If the POA has the IMPLICIT_ACTIVATION policy and either the POA has the MULTIPLE_ID policy or the specified servant is not active, the servant is activated using a POA-generated Object Id and the Interface Id associated with the servant, and that Object Id is returned. 3. If the POA has the USE_DEFAULT_SERVANT policy, the servant specified is the default servant, and the operation is being invoked in the context of executing a request on the default servant, then the ObjectId associated with the current invocation is returned. 4. Otherwise, the ServantNotActive exception is raised.

Parameters:
p_servant - servant for which the object disi returned.
Returns:
object id associated with the servant.
Throws:
ServantNotActive - if the above rules and policy combination is not met.
WrongPolicy - if the USE_DEFAULT_SERVANT policy or a combination of the RETAIN policy and either the UNIQUE_ID or IMPLICIT_ACTIVATION policies are not present.

servant_to_reference

public Object servant_to_reference(Servant p_servant)
                            throws ServantNotActive,
                                   WrongPolicy
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. It has four possible behaviors. 1. If the POA has both the RETAIN and the UNIQUE_ID policy and the specified servant is active, an object reference encapsulating the information used to activate the servant is returned. 2. If the POA has both the RETAIN and the IMPLICIT_ACTIVATION policy and either the POA has the MULTIPLE_ID policy or the specified servant is not active, the servant is activated using a POA-generated Object Id and the Interface Id associated with the servant, and a corresponding object reference is returned. 3. If the operation was invoked in the context of executing a request on the specified servant, the reference associated with the current invocation is returned. 4. Otherwise, the ServantNotActive exception is raised.

Parameters:
p_servant - servant for which the object reference needs to be obtained.
Returns:
object reference associated with the servant.
Throws:
WrongPolicy - if the operation is not invoked in the context of executing a request on the specified servant and the required policies are not present.
ServantNotActive - if the above specified policies and rules are not met.

reference_to_servant

public Servant reference_to_servant(Object reference)
                             throws ObjectNotActive,
                                    WrongPolicy,
                                    WrongAdapter
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. Otherwise, if the POA has the USE_DEFAULT_SERVANT policy and a default servant has been registered with the POA, this operation returns the default servant. If the object reference was not created by this POA, the WrongAdapter exception is raised. (OMG Issue on inconsistency with the POA.IDL.

Parameters:
reference - object reference for which the servant is returned.
Returns:
servant associated with the reference.
Throws:
WrongPolicy - if neither the RETAIN policy or the USE_DEFAULT_SERVANT policy is present.
ObjectNotActive - if the servant is not present in the Active Object Map (for RETAIN) or no default servant is registered (for USE_DEFAULT_POLICY).
WrongAdapter - if reference was not created by this POA instance.

reference_to_id

public byte[] reference_to_id(Object reference)
                       throws WrongAdapter,
                              WrongPolicy
This operation returns the Object Id value encapsulated by the specified reference. This operation is valid only if the reference was created by the POA on which the operation is being performed. The object denoted by the reference does not have to be active for this operation to succeed.

Parameters:
reference - the object reference from which the object id needs to be returned.
Returns:
object id encapsulated in the reference.
Throws:
WrongAdapter - if the reference was not created by the POA specified in the reference.
WrongPolicy - declared to allow future extensions.

id_to_servant

public Servant id_to_servant(byte[] oid)
                      throws ObjectNotActive,
                             WrongPolicy
If the POA has the RETAIN policy and the specified ObjectId is in the Active Object Map, this operation returns the servant associated with that object in the Active Object Map. Otherwise, if the POA has the USE_DEFAULT_SERVANT policy and a default servant has been registered with the POA, this operation returns the default servant.

Parameters:
oid - object id for the which the servant is returned.
Returns:
servant associated with oid.
Throws:
ObjectNotActive - is raised if ObjectId is is not in the Active Object Map (for RETAIN policy), or no default servant is registered (for USE_DEFAULT_SERVANT policy).
WrongPolicy - is raised if the RETAIN policy or the USE_DEFAULT_SERVANT policy is not present.

id_to_reference

public Object id_to_reference(byte[] oid)
                       throws ObjectNotActive,
                              WrongPolicy
If an object with the specified Object Id value is currently active, a reference encapsulating the information used to activate the object is returned.

Parameters:
oid - id of the object for which the reference is returned.
Returns:
the object reference
Throws:
ObjectNotActive - if the Object Id value is not active in the POA.
WrongPolicy - if the RETAIN policy is not present.

id

public byte[] id()
This returns the unique id of the POA in the process in which it is created. It is for use by portable interceptors.

This id is guaranteed unique for the life span of the POA in the process. For persistent POAs, this means that if a POA is created in the same path with the same name as another POA, these POAs are identical and, therefore, have the same id. For transient POAs, each POA is unique.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


REQUEST_PROCESSING_POLICY_ID (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Interface REQUEST_PROCESSING_POLICY_ID

public interface REQUEST_PROCESSING_POLICY_ID

org/omg/PortableServer/REQUEST_PROCESSING_POLICY_ID.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableServer/poa.idl Thursday, June 12, 2003 9:59:10 PM GMT-08:00

Field Summary
static int value
The value representing REQUEST_PROCESSING_POLICY_ID.

Field Detail

value

public static final int value
The value representing REQUEST_PROCESSING_POLICY_ID.

See Also:
Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


RequestProcessingPolicy (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Interface RequestProcessingPolicy

All Superinterfaces:
IDLEntity, Object, Policy, PolicyOperations, RequestProcessingPolicyOperations, Serializable
public interface RequestProcessingPolicy
extends RequestProcessingPolicyOperations, Policy, IDLEntity

This policy specifies how requests are processed by the created POA. The default is USE_ACTIVE_OBJECT_MAP_ONLY.

Methods inherited from interface org.omg.PortableServer.RequestProcessingPolicyOperations
value
Methods inherited from interface org.omg.CORBA.PolicyOperations
copy, destroy, policy_type
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


RequestProcessingPolicyOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Interface RequestProcessingPolicyOperations

All Superinterfaces:
PolicyOperations
All Known Subinterfaces:
RequestProcessingPolicy
public interface RequestProcessingPolicyOperations
extends PolicyOperations

This policy specifies how requests are processed by the created POA. The default is USE_ACTIVE_OBJECT_MAP_ONLY.

Method Summary
 RequestProcessingPolicyValue value()
specifies the policy value
Methods inherited from interface org.omg.CORBA.PolicyOperations
copy, destroy, policy_type

Method Detail

value

public RequestProcessingPolicyValue value()
specifies the policy value

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


RequestProcessingPolicyValue (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Class RequestProcessingPolicyValue

java.lang.Object
    extended by org.omg.PortableServer.RequestProcessingPolicyValue
All Implemented Interfaces:
IDLEntity, Serializable
public class RequestProcessingPolicyValue
extends Object
implements IDLEntity

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.

Field Summary
static int | _USE_ACTIVE_OBJECT_MAP_ONLY
static int | _USE_DEFAULT_SERVANT
static int | _USE_SERVANT_MANAGER
static RequestProcessingPolicyValue | USE_ACTIVE_OBJECT_MAP_ONLY
static RequestProcessingPolicyValue | USE_DEFAULT_SERVANT
static RequestProcessingPolicyValue | USE_SERVANT_MANAGER
Constructor Summary
protected RequestProcessingPolicyValue(int value)
Method Summary
static RequestProcessingPolicyValue | from_int(int value)
int | value()
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

_USE_ACTIVE_OBJECT_MAP_ONLY

public static final int _USE_ACTIVE_OBJECT_MAP_ONLY
See Also:
Constant Field Values

USE_ACTIVE_OBJECT_MAP_ONLY

public static final RequestProcessingPolicyValue USE_ACTIVE_OBJECT_MAP_ONLY

_USE_DEFAULT_SERVANT

public static final int _USE_DEFAULT_SERVANT
See Also:
Constant Field Values

USE_DEFAULT_SERVANT

public static final RequestProcessingPolicyValue USE_DEFAULT_SERVANT

_USE_SERVANT_MANAGER

public static final int _USE_SERVANT_MANAGER
See Also:
Constant Field Values

USE_SERVANT_MANAGER

public static final RequestProcessingPolicyValue USE_SERVANT_MANAGER
Constructor Detail

RequestProcessingPolicyValue

protected RequestProcessingPolicyValue(int value)
Method Detail

value

public int value()

from_int

public static RequestProcessingPolicyValue from_int(int value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Servant (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Class Servant

java.lang.Object
    extended by org.omg.PortableServer.Servant
Direct Known Subclasses:
BindingIteratorPOA, DynamicImplementation, NamingContextExtPOA, NamingContextPOA, ServantActivatorPOA, ServantLocatorPOA
public abstract class Servant
extends Object

Defines the native Servant type. In Java, 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 IDL to Java spec. (CORBA V2.3.1) ptc/00-01-08.pdf.

Constructor Summary
Servant()
Method Summary
abstract  String[] _all_interfaces(POA poa, byte[] objectId)
Used by the ORB to obtain complete type information from the servant.
 POA _default_POA()
Returns the root POA from the ORB instance associated with the servant.
 Delegate _get_delegate()
Gets the ORB vendor-specific implementation of PortableServer::Servant.
 Object _get_interface_def()
Returns an InterfaceDef object as a CORBA::Object that defines the runtime type of the CORBA::Object implemented by the Servant.
 boolean _is_a(String repository_id)
Checks to see if the specified repository_id is present on the list returned by _all_interfaces() or is the repository_id for the generic CORBA Object.
 boolean _non_existent()
Checks for the existence of an Object.
 byte[] _object_id()
Allows easy execution of common methods, equivalent to calling PortableServer::Current::get_object_id.
 ORB _orb()
Returns the instance of the ORB currently associated with the Servant (convenience method).
 POA _poa()
Allows easy execution of common methods, equivalent to PortableServer::Current:get_POA.
 void _set_delegate(Delegate delegate)
Supports the Java ORB portability interfaces by providing a method for classes that support ORB portability through delegation to set their delegate.
 Object _this_object()
Allows the servant to obtain the object reference for the target CORBA object it is incarnating for that request.
 Object _this_object(ORB orb)
Allows the servant to obtain the object reference for the target CORBA Object it is incarnating for that request.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

Servant

public Servant()
Method Detail

_get_delegate

public final Delegate _get_delegate()
Gets the ORB vendor-specific implementation of PortableServer::Servant.

Returns:
_delegate the ORB vendor-specific implementation o@throwf PortableServer::Servant.

_set_delegate

public final void _set_delegate(Delegate delegate)
Supports the Java ORB portability interfaces by providing a method for classes that support ORB portability through delegation to set their delegate.

Parameters:
delegate - ORB vendor-specific implementation of the PortableServer::Servant.

_this_object

public final Object _this_object()
Allows the servant to obtain the object reference for the target CORBA object it is incarnating for that request.

Returns:
this_object Object reference associated with the request.

_this_object

public final Object _this_object(ORB orb)
Allows the servant to obtain the object reference for the target CORBA Object it is incarnating for that request.

Parameters:
orb - ORB with which the servant is associated.
Returns:
_this_object reference associated with the request.

_orb

public final ORB _orb()
Returns the instance of the ORB currently associated with the Servant (convenience method).

Returns:
orb the instance of the ORB currently associated with the Servant.

_poa

public final POA _poa()
Allows easy execution of common methods, equivalent to PortableServer::Current:get_POA.

Returns:
poa POA associated with the servant.

_object_id

public final byte[] _object_id()
Allows easy execution of common methods, equivalent to calling PortableServer::Current::get_object_id.

Returns:
object_id the Object ID associated with this servant.

_default_POA

public POA _default_POA()
Returns the root POA from the ORB instance associated with the servant. Subclasses may override this method to return a different POA.

Returns:
default_POA the POA associated with the Servant.

_is_a

public boolean _is_a(String repository_id)
Checks to see if the specified repository_id is present on the list returned by _all_interfaces() or is the repository_id for the generic CORBA Object.

Parameters:
repository_id - the repository_id to be checked in the repository list or against the id of generic CORBA objects.
Returns:
is_a boolean indicating whether the specified repository_id is in the repository list or is same as a generic CORBA object.

_non_existent

public boolean _non_existent()
Checks for the existence of an Object. The Servant provides a default implementation of _non_existent() that can be overridden by derived servants.

Returns:
non_existent true if that object does not exist, false otherwise.

_get_interface_def

public Object _get_interface_def()
Returns an InterfaceDef object as a CORBA::Object that defines the runtime type of the CORBA::Object implemented by the Servant. The invoker of _get_interface_def must narrow the result to an InterfaceDef in order to use it.

This default implementation of _get_interface_def() can be overridden by derived servants if the default behavior is not adequate. As defined in the CORBA 2.3.1 specification, section 11.3.1, the default behavior of _get_interface_def() is to use the most derived interface of a static servant or the most derived interface retrieved from a dynamic servant to obtain the InterfaceDef. This behavior must be supported by the Delegate that implements the Servant.

Returns:
get_interface_def an InterfaceDef object as a CORBA::Object that defines the runtime type of the CORBA::Object implemented by the Servant.

_all_interfaces

public abstract String[] _all_interfaces(POA poa,
                                         byte[] objectId)
Used by the ORB to obtain complete type information from the servant.

Parameters:
poa - POA with which the servant is associated.
objectId - is the id corresponding to the object associated with this servant.
Returns:
list of type information for the object.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


SERVANT_RETENTION_POLICY_ID (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Interface SERVANT_RETENTION_POLICY_ID

public interface SERVANT_RETENTION_POLICY_ID

org/omg/PortableServer/SERVANT_RETENTION_POLICY_ID.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableServer/poa.idl Thursday, June 12, 2003 9:59:10 PM GMT-08:00

Field Summary
static int value
The value representing SERVANT_RETENTION_POLICY_ID.

Field Detail

value

public static final int value
The value representing SERVANT_RETENTION_POLICY_ID.

See Also:
Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ServantActivator (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Interface ServantActivator

All Superinterfaces:
IDLEntity, Object, Serializable, ServantActivatorOperations, ServantManager, ServantManagerOperations
All Known Implementing Classes:
_ServantActivatorStub
public interface ServantActivator
extends ServantActivatorOperations, ServantManager, IDLEntity

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

Methods inherited from interface org.omg.PortableServer.ServantActivatorOperations
etherealize, incarnate
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ServantActivatorHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Class ServantActivatorHelper

java.lang.Object
    extended by org.omg.PortableServer.ServantActivatorHelper
public abstract class ServantActivatorHelper
extends Object

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

Constructor Summary
ServantActivatorHelper()
Method Summary
static ServantActivator | extract(Any a)
static String | id()
static void | insert(Any a, ServantActivator that)
static ServantActivator | narrow(Object obj)
static ServantActivator | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, ServantActivator value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ServantActivatorHelper

public ServantActivatorHelper()
Method Detail

insert

public static void insert(Any a,
                          ServantActivator that)

extract

public static ServantActivator extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static ServantActivator read(InputStream istream)

write

public static void write(OutputStream ostream,
                         ServantActivator value)

narrow

public static ServantActivator narrow(Object obj)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ServantActivatorOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Interface ServantActivatorOperations

All Superinterfaces:
ServantManagerOperations
All Known Subinterfaces:
ServantActivator
All Known Implementing Classes:
_ServantActivatorStub, ServantActivatorPOA
public interface ServantActivatorOperations
extends ServantManagerOperations

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

Method Summary
void | etherealize(byte[] oid, POA adapter, Servant serv, boolean cleanup_in_progress, boolean remaining_activations) This operation is invoked whenever a servant for an object is deactivated, assuming the POA has the USE_SERVANT_MANAGER and RETAIN policies.
Servant | incarnate(byte[] oid, POA adapter) This 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 USE_SERVANT_MANAGER and RETAIN policies.

Method Detail

incarnate

public Servant incarnate(byte[] oid,
                         POA adapter)
                  throws ForwardRequest
This 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 USE_SERVANT_MANAGER and RETAIN policies.

Parameters:
oid - object Id associated with the object on the request was made.
adapter - object reference for the POA in which the object is being activated.
Returns:
Servant corresponding to oid is created or located by the user supplied servant manager.
Throws:
ForwardRequest - to indicate to the ORB that it is responsible for delivering the current request and subsequent requests to the object denoted in the forward_reference member of the exception.

etherealize

public void etherealize(byte[] oid,
                        POA adapter,
                        Servant serv,
                        boolean cleanup_in_progress,
                        boolean remaining_activations)
This operation is invoked whenever a servant for an object is deactivated, assuming the POA has the USE_SERVANT_MANAGER and RETAIN policies.

Parameters:
oid - object Id associated with the object being deactivated.
adapter - object reference for the POA in which the object was active.
serv - contains reference to the servant associated with the object being deactivated.
cleanup_in_progress - if TRUE indicates that destroy or deactivate is called with etherealize_objects param of TRUE. FALSE indicates that etherealize was called due to other reasons.
remaining_activations - indicates whether the Servant Manager can destroy a servant. If set to TRUE, the Servant Manager should wait until all invocations in progress have completed.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ServantActivatorPOA (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Class ServantActivatorPOA

java.lang.Object
    extended by org.omg.PortableServer.Servant
        extended by org.omg.PortableServer.ServantActivatorPOA
All Implemented Interfaces:
InvokeHandler, ServantActivatorOperations, ServantManagerOperations
public abstract class ServantActivatorPOA
extends Servant
implements ServantActivatorOperations, InvokeHandler

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

Constructor Summary
ServantActivatorPOA()
Method Summary
String[] | _all_interfaces(POA poa, byte[] objectId) Used by the ORB to obtain complete type information from the servant.
OutputStream | _invoke(String $method, InputStream in, ResponseHandler $rh) Invoked by the ORB to dispatch a request to the servant.
ServantActivator | _this()
ServantActivator | _this(ORB orb)
Methods inherited from class org.omg.PortableServer.Servant
_default_POA, _get_delegate, _get_interface_def, _is_a, _non_existent, _object_id, _orb, _poa, _set_delegate, _this_object, _this_object
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Methods inherited from interface org.omg.PortableServer.ServantActivatorOperations
etherealize, incarnate

Constructor Detail

ServantActivatorPOA

public ServantActivatorPOA()
Method Detail

_invoke

public OutputStream _invoke(String $method,
                            InputStream in,
                            ResponseHandler $rh)
Description copied from interface: InvokeHandler
Invoked by the ORB to dispatch a request to the servant. ORB passes the method name, an InputStream containing the marshalled arguments, and a ResponseHandler which the servant uses to construct a proper reply. Only CORBA SystemException may be thrown by this method. The method must return an OutputStream created by the ResponseHandler which contains the marshalled reply. A servant must not retain a reference to the ResponseHandler beyond the lifetime of a method invocation. Servant behaviour is defined as follows:

1. Determine correct method, and unmarshal parameters from InputStream.

2. Invoke method implementation.

3. If no user exception, create a normal reply using ResponseHandler.

4. If user exception occurred, create exception reply using ResponseHandler.

5. Marshal reply into OutputStream returned by ResponseHandler.

6. Return OutputStream to ORB.

Specified by:
_invoke in interface InvokeHandler
Parameters:
$method - The method name.
in - The InputStream containing the marshalled arguments.
$rh - The ResponseHandler which the servant uses to construct a proper reply
Returns:
The OutputStream created by the ResponseHandler which contains the marshalled reply

_all_interfaces

public String[] _all_interfaces(POA poa,
                                byte[] objectId)
Description copied from class: Servant
Used by the ORB to obtain complete type information from the servant.

Specified by:
_all_interfaces in class Servant
Parameters:
poa - POA with which the servant is associated.
objectId - is the id corresponding to the object associated with this servant.
Returns:
list of type information for the object.

_this

public ServantActivator _this()

_this

public ServantActivator _this(ORB orb)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ServantLocator (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Interface ServantLocator

All Superinterfaces:
IDLEntity, Object, Serializable, ServantLocatorOperations, ServantManager, ServantManagerOperations
All Known Implementing Classes:
_ServantLocatorStub
public interface ServantLocator
extends ServantLocatorOperations, ServantManager, IDLEntity

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.

Methods inherited from interface org.omg.PortableServer.ServantLocatorOperations
postinvoke, preinvoke
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ServantLocatorHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Class ServantLocatorHelper

java.lang.Object
    extended by org.omg.PortableServer.ServantLocatorHelper
public abstract class ServantLocatorHelper
extends Object

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.

Constructor Summary
ServantLocatorHelper()
Method Summary
static ServantLocator | extract(Any a)
static String | id()
static void | insert(Any a, ServantLocator that)
static ServantLocator | narrow(Object obj)
static ServantLocator | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, ServantLocator value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ServantLocatorHelper

public ServantLocatorHelper()
Method Detail

insert

public static void insert(Any a,
                          ServantLocator that)

extract

public static ServantLocator extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static ServantLocator read(InputStream istream)

write

public static void write(OutputStream ostream,
                         ServantLocator value)

narrow

public static ServantLocator narrow(Object obj)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ServantLocatorOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Interface ServantLocatorOperations

All Superinterfaces:
ServantManagerOperations
All Known Subinterfaces:
ServantLocator
All Known Implementing Classes:
_ServantLocatorStub, ServantLocatorPOA
public interface ServantLocatorOperations
extends ServantManagerOperations

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.

Method Summary
void | postinvoke(byte[] oid, POA adapter, String operation, Object the_cookie, Servant the_servant) This operation is invoked whenener a servant completes a request.
Servant | preinvoke(byte[] oid, POA adapter, String operation, CookieHolder the_cookie) This operations is used to get a servant that will be used to process the request that caused preinvoke to be called.

Method Detail

preinvoke

public Servant preinvoke(byte[] oid,
                         POA adapter,
                         String operation,
                         CookieHolder the_cookie)
                  throws ForwardRequest
This operations is used to get a servant that will be used to process the request that caused preinvoke to be called.

Parameters:
oid - the object id associated with object on which the request was made.
adapter - the reference for POA in which the object is being activated.
operation - the operation name.
the_cookie - an opaque value that can be set by the servant manager to be used during postinvoke.
Returns:
Servant used to process incoming request.
Throws:
ForwardRequest - to indicate to the ORB that it is responsible for delivering the current request and subsequent requests to the object denoted in the forward_reference member of the exception.

postinvoke

public void postinvoke(byte[] oid,
                       POA adapter,
                       String operation,
                       Object the_cookie,
                       Servant the_servant)
This operation is invoked whenener a servant completes a request.

Parameters:
oid - the object id ssociated with object on which the request was made.
adapter - the reference for POA in which the object was active.
the_cookie - an opaque value that contains the data set by preinvoke.
the_servant - reference to the servant that is associated with the object.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ServantLocatorPOA (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Class ServantLocatorPOA

java.lang.Object
    extended by org.omg.PortableServer.Servant
        extended by org.omg.PortableServer.ServantLocatorPOA
All Implemented Interfaces:
InvokeHandler, ServantLocatorOperations, ServantManagerOperations
public abstract class ServantLocatorPOA
extends Servant
implements ServantLocatorOperations, InvokeHandler

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.

Constructor Summary
ServantLocatorPOA()
Method Summary
String[] | _all_interfaces(POA poa, byte[] objectId) Used by the ORB to obtain complete type information from the servant.
OutputStream | _invoke(String $method, InputStream in, ResponseHandler $rh) Invoked by the ORB to dispatch a request to the servant.
ServantLocator | _this()
ServantLocator | _this(ORB orb)
Methods inherited from class org.omg.PortableServer.Servant
_default_POA, _get_delegate, _get_interface_def, _is_a, _non_existent, _object_id, _orb, _poa, _set_delegate, _this_object, _this_object
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Methods inherited from interface org.omg.PortableServer.ServantLocatorOperations
postinvoke, preinvoke

Constructor Detail

ServantLocatorPOA

public ServantLocatorPOA()
Method Detail

_invoke

public OutputStream _invoke(String $method,
                            InputStream in,
                            ResponseHandler $rh)
Description copied from interface: InvokeHandler
Invoked by the ORB to dispatch a request to the servant. ORB passes the method name, an InputStream containing the marshalled arguments, and a ResponseHandler which the servant uses to construct a proper reply. Only CORBA SystemException may be thrown by this method. The method must return an OutputStream created by the ResponseHandler which contains the marshalled reply. A servant must not retain a reference to the ResponseHandler beyond the lifetime of a method invocation. Servant behaviour is defined as follows:

1. Determine correct method, and unmarshal parameters from InputStream.

2. Invoke method implementation.

3. If no user exception, create a normal reply using ResponseHandler.

4. If user exception occurred, create exception reply using ResponseHandler.

5. Marshal reply into OutputStream returned by ResponseHandler.

6. Return OutputStream to ORB.

Specified by:
_invoke in interface InvokeHandler
Parameters:
$method - The method name.
in - The InputStream containing the marshalled arguments.
$rh - The ResponseHandler which the servant uses to construct a proper reply
Returns:
The OutputStream created by the ResponseHandler which contains the marshalled reply

_all_interfaces

public String[] _all_interfaces(POA poa,
                                byte[] objectId)
Description copied from class: Servant
Used by the ORB to obtain complete type information from the servant.

Specified by:
_all_interfaces in class Servant
Parameters:
poa - POA with which the servant is associated.
objectId - is the id corresponding to the object associated with this servant.
Returns:
list of type information for the object.

_this

public ServantLocator _this()

_this

public ServantLocator _this(ORB orb)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ServantManager (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Interface ServantManager

All Superinterfaces:
IDLEntity, Object, Serializable, ServantManagerOperations
All Known Subinterfaces:
ServantActivator, ServantLocator
All Known Implementing Classes:
_ServantActivatorStub, _ServantLocatorStub
public interface ServantManager
extends ServantManagerOperations, Object, IDLEntity

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. A servant manager is registered with a POA as a callback object, to be invoked by the POA when necessary. ServantManagers can either be ServantActivators or ServantLocators. A ServantManager object must be local to the process containing the POA objects it is registered with.

Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ServantManagerOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Interface ServantManagerOperations

All Known Subinterfaces:
ServantActivator, ServantActivatorOperations, ServantLocator, ServantLocatorOperations, ServantManager
All Known Implementing Classes:
_ServantActivatorStub, _ServantLocatorStub, ServantActivatorPOA, ServantLocatorPOA
public interface ServantManagerOperations

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. A servant manager is registered with a POA as a callback object, to be invoked by the POA when necessary. ServantManagers can either be ServantActivators or ServantLocators. A ServantManager object must be local to the process containing the POA objects it is registered with.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ServantRetentionPolicy (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Interface ServantRetentionPolicy

All Superinterfaces:
IDLEntity, Object, Policy, PolicyOperations, Serializable, ServantRetentionPolicyOperations
public interface ServantRetentionPolicy
extends ServantRetentionPolicyOperations, Policy, IDLEntity

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

Methods inherited from interface org.omg.PortableServer.ServantRetentionPolicyOperations
value
Methods inherited from interface org.omg.CORBA.PolicyOperations
copy, destroy, policy_type
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ServantRetentionPolicyOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Interface ServantRetentionPolicyOperations

All Superinterfaces:
PolicyOperations
All Known Subinterfaces:
ServantRetentionPolicy
public interface ServantRetentionPolicyOperations
extends PolicyOperations

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

Method Summary
 ServantRetentionPolicyValue value()
specifies the policy value
Methods inherited from interface org.omg.CORBA.PolicyOperations
copy, destroy, policy_type

Method Detail

value

public ServantRetentionPolicyValue value()
specifies the policy value

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ServantRetentionPolicyValue (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Class ServantRetentionPolicyValue

java.lang.Object
    extended by org.omg.PortableServer.ServantRetentionPolicyValue
All Implemented Interfaces:
IDLEntity, Serializable
public class ServantRetentionPolicyValue
extends Object
implements IDLEntity

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. If no ServantRetentionPolicy is specified at POA creation, the default is RETAIN.

Field Summary
static int | _NON_RETAIN
static int | _RETAIN
static ServantRetentionPolicyValue | NON_RETAIN
static ServantRetentionPolicyValue | RETAIN
Constructor Summary
protected ServantRetentionPolicyValue(int value)
Method Summary
static ServantRetentionPolicyValue | from_int(int value)
int | value()
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

_RETAIN

public static final int _RETAIN
See Also:
Constant Field Values

RETAIN

public static final ServantRetentionPolicyValue RETAIN

_NON_RETAIN

public static final int _NON_RETAIN
See Also:
Constant Field Values

NON_RETAIN

public static final ServantRetentionPolicyValue NON_RETAIN
Constructor Detail

ServantRetentionPolicyValue

protected ServantRetentionPolicyValue(int value)
Method Detail

value

public int value()

from_int

public static ServantRetentionPolicyValue from_int(int value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


THREAD_POLICY_ID (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Interface THREAD_POLICY_ID

public interface THREAD_POLICY_ID

org/omg/PortableServer/THREAD_POLICY_ID.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableServer/poa.idl Thursday, June 12, 2003 9:59:10 PM GMT-08:00

Field Summary
static int value
The value representing THREAD_POLICY_ID.

Field Detail

value

public static final int value
The value representing THREAD_POLICY_ID.

See Also:
Constant Field Values
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ThreadPolicy (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Interface ThreadPolicy

All Superinterfaces:
IDLEntity, Object, Policy, PolicyOperations, Serializable, ThreadPolicyOperations
public interface ThreadPolicy
extends ThreadPolicyOperations, Policy, IDLEntity

The ThreadPolicy specifies the threading model used with the created POA. The default is ORB_CTRL_MODEL.

Methods inherited from interface org.omg.PortableServer.ThreadPolicyOperations
value
Methods inherited from interface org.omg.CORBA.PolicyOperations
copy, destroy, policy_type
Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ThreadPolicyOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Interface ThreadPolicyOperations

All Superinterfaces:
PolicyOperations
All Known Subinterfaces:
ThreadPolicy
public interface ThreadPolicyOperations
extends PolicyOperations

The ThreadPolicy specifies the threading model used with the created POA. The default is ORB_CTRL_MODEL.

Method Summary
 ThreadPolicyValue value()
specifies the policy value
Methods inherited from interface org.omg.CORBA.PolicyOperations
copy, destroy, policy_type

Method Detail

value

public ThreadPolicyValue value()
specifies the policy value

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


ThreadPolicyValue (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer
Class ThreadPolicyValue

java.lang.Object
    extended by org.omg.PortableServer.ThreadPolicyValue
All Implemented Interfaces:
IDLEntity, Serializable
public class ThreadPolicyValue
extends Object
implements IDLEntity

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.

Field Summary
static int | _ORB_CTRL_MODEL
static int | _SINGLE_THREAD_MODEL
static ThreadPolicyValue | ORB_CTRL_MODEL
static ThreadPolicyValue | SINGLE_THREAD_MODEL
Constructor Summary
protected ThreadPolicyValue(int value)
Method Summary
static ThreadPolicyValue | from_int(int value)
int | value()
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

_ORB_CTRL_MODEL

public static final int _ORB_CTRL_MODEL
See Also:
Constant Field Values

ORB_CTRL_MODEL

public static final ThreadPolicyValue ORB_CTRL_MODEL

_SINGLE_THREAD_MODEL

public static final int _SINGLE_THREAD_MODEL
See Also:
Constant Field Values

SINGLE_THREAD_MODEL

public static final ThreadPolicyValue SINGLE_THREAD_MODEL
Constructor Detail

ThreadPolicyValue

protected ThreadPolicyValue(int value)
Method Detail

value

public int value()

from_int

public static ThreadPolicyValue from_int(int value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Uses of Class org.omg.PortableServer._ServantActivatorStub (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer._ServantActivatorStub

No usage of org.omg.PortableServer._ServantActivatorStub

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer._ServantLocatorStub (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer._ServantLocatorStub

No usage of org.omg.PortableServer._ServantLocatorStub

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableServer.AdapterActivator (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableServer.AdapterActivator

Packages that use AdapterActivator
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of AdapterActivator in org.omg.PortableServer

Methods in org.omg.PortableServer that return AdapterActivator
 AdapterActivator POAOperations.the_activator()
This attribute identifies the adapter activator associated with the POA.

Methods in org.omg.PortableServer with parameters of type AdapterActivator
 void POAOperations.the_activator(AdapterActivator newThe_activator)
This attribute identifies the adapter activator associated with the POA.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableServer.AdapterActivatorOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableServer.AdapterActivatorOperations

Packages that use AdapterActivatorOperations
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of AdapterActivatorOperations in org.omg.PortableServer

Subinterfaces of AdapterActivatorOperations in org.omg.PortableServer
 interface AdapterActivator
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 find_POA is called with an activate parameter value of TRUE.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableServer.Current (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableServer.Current

Packages that use Current
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of Current in org.omg.PortableServer

Methods in org.omg.PortableServer that return Current
static Current | CurrentHelper.extract(Any a)
static Current | CurrentHelper.read(InputStream istream)
static Current | CurrentHelper.narrow(Object obj)

Methods in org.omg.PortableServer with parameters of type Current
static void | CurrentHelper.insert(Any a, Current that)
static void | CurrentHelper.write(OutputStream ostream, Current value)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.CurrentHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.CurrentHelper

No usage of org.omg.PortableServer.CurrentHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableServer.CurrentOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableServer.CurrentOperations

Packages that use CurrentOperations
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of CurrentOperations in org.omg.PortableServer

Subinterfaces of CurrentOperations in org.omg.PortableServer
 interface Current
The PortableServer::Current interface, derived from CORBA::Current, provides method implementations with access to the identity of the object on which the method was invoked.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.DynamicImplementation (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.DynamicImplementation

No usage of org.omg.PortableServer.DynamicImplementation

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.ForwardRequest (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.ForwardRequest

Packages that use ForwardRequest
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of ForwardRequest in org.omg.PortableServer

Methods in org.omg.PortableServer that return ForwardRequest
static ForwardRequest | ForwardRequestHelper.extract(Any a)
static ForwardRequest | ForwardRequestHelper.read(InputStream istream)

Methods in org.omg.PortableServer with parameters of type ForwardRequest
static void | ForwardRequestHelper.insert(Any a, ForwardRequest that)
static void | ForwardRequestHelper.write(OutputStream ostream, ForwardRequest value)

Methods in org.omg.PortableServer that throw ForwardRequest
Servant | _ServantLocatorStub.preinvoke(byte[] oid, POA adapter, String operation, CookieHolder the_cookie) This operations is used to get a servant that will be used to process the request that caused preinvoke to be called.
Servant | ServantLocatorOperations.preinvoke(byte[] oid, POA adapter, String operation, CookieHolder the_cookie) This operations is used to get a servant that will be used to process the request that caused preinvoke to be called.
Servant | _ServantActivatorStub.incarnate(byte[] oid, POA adapter) This 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 USE_SERVANT_MANAGER and RETAIN policies.
Servant | ServantActivatorOperations.incarnate(byte[] oid, POA adapter) This 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 USE_SERVANT_MANAGER and RETAIN policies.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.ForwardRequestHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.ForwardRequestHelper

No usage of org.omg.PortableServer.ForwardRequestHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableServer.ID_ASSIGNMENT_POLICY_ID (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableServer.ID_ASSIGNMENT_POLICY_ID

No usage of org.omg.PortableServer.ID_ASSIGNMENT_POLICY_ID

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableServer.ID_UNIQUENESS_POLICY_ID (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableServer.ID_UNIQUENESS_POLICY_ID

No usage of org.omg.PortableServer.ID_UNIQUENESS_POLICY_ID

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableServer.IdAssignmentPolicy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableServer.IdAssignmentPolicy

Packages that use IdAssignmentPolicy
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of IdAssignmentPolicy in org.omg.PortableServer

Methods in org.omg.PortableServer that return IdAssignmentPolicy
 IdAssignmentPolicy POAOperations.create_id_assignment_policy(IdAssignmentPolicyValue value)
These operations each return a reference to a policy object with the specified value.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableServer.IdAssignmentPolicyOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableServer.IdAssignmentPolicyOperations

Packages that use IdAssignmentPolicyOperations
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of IdAssignmentPolicyOperations in org.omg.PortableServer

Subinterfaces of IdAssignmentPolicyOperations in org.omg.PortableServer
 interface IdAssignmentPolicy
IdAssignmentPolicy specifies whether Object Ids in the created POA are generated by the application or by the ORB.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.IdAssignmentPolicyValue (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.IdAssignmentPolicyValue

Packages that use IdAssignmentPolicyValue
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of IdAssignmentPolicyValue in org.omg.PortableServer

Fields in org.omg.PortableServer declared as IdAssignmentPolicyValue
static IdAssignmentPolicyValue | IdAssignmentPolicyValue.USER_ID
static IdAssignmentPolicyValue | IdAssignmentPolicyValue.SYSTEM_ID

Methods in org.omg.PortableServer that return IdAssignmentPolicyValue
IdAssignmentPolicyValue | IdAssignmentPolicyOperations.value() specifies the policy value
static IdAssignmentPolicyValue | IdAssignmentPolicyValue.from_int(int value)

Methods in org.omg.PortableServer with parameters of type IdAssignmentPolicyValue
 IdAssignmentPolicy POAOperations.create_id_assignment_policy(IdAssignmentPolicyValue value)
These operations each return a reference to a policy object with the specified value.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableServer.IdUniquenessPolicy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableServer.IdUniquenessPolicy

Packages that use IdUniquenessPolicy
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of IdUniquenessPolicy in org.omg.PortableServer

Methods in org.omg.PortableServer that return IdUniquenessPolicy
 IdUniquenessPolicy POAOperations.create_id_uniqueness_policy(IdUniquenessPolicyValue value)
These operations each return a reference to a policy object with the specified value.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableServer.IdUniquenessPolicyOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableServer.IdUniquenessPolicyOperations

Packages that use IdUniquenessPolicyOperations
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of IdUniquenessPolicyOperations in org.omg.PortableServer

Subinterfaces of IdUniquenessPolicyOperations in org.omg.PortableServer
 interface IdUniquenessPolicy
The IdUniquenessPolicy specifies whether the servants activated in the created POA must have unique object i identities.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.IdUniquenessPolicyValue (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.IdUniquenessPolicyValue

Packages that use IdUniquenessPolicyValue
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of IdUniquenessPolicyValue in org.omg.PortableServer

Fields in org.omg.PortableServer declared as IdUniquenessPolicyValue
static IdUniquenessPolicyValue | IdUniquenessPolicyValue.UNIQUE_ID
static IdUniquenessPolicyValue | IdUniquenessPolicyValue.MULTIPLE_ID

Methods in org.omg.PortableServer that return IdUniquenessPolicyValue
IdUniquenessPolicyValue | IdUniquenessPolicyOperations.value() specifies the policy value
static IdUniquenessPolicyValue | IdUniquenessPolicyValue.from_int(int value)

Methods in org.omg.PortableServer with parameters of type IdUniquenessPolicyValue
 IdUniquenessPolicy POAOperations.create_id_uniqueness_policy(IdUniquenessPolicyValue value)
These operations each return a reference to a policy object with the specified value.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableServer.IMPLICIT_ACTIVATION_POLICY_ID (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableServer.IMPLICIT_ACTIVATION_POLICY_ID

No usage of org.omg.PortableServer.IMPLICIT_ACTIVATION_POLICY_ID

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableServer.ImplicitActivationPolicy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableServer.ImplicitActivationPolicy

Packages that use ImplicitActivationPolicy
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of ImplicitActivationPolicy in org.omg.PortableServer

Methods in org.omg.PortableServer that return ImplicitActivationPolicy
 ImplicitActivationPolicy POAOperations.create_implicit_activation_policy(ImplicitActivationPolicyValue value)
These operations each return a reference to a policy object with the specified value.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableServer.ImplicitActivationPolicyOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableServer.ImplicitActivationPolicyOperations

Packages that use ImplicitActivationPolicyOperations
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of ImplicitActivationPolicyOperations in org.omg.PortableServer

Subinterfaces of ImplicitActivationPolicyOperations in org.omg.PortableServer
 interface ImplicitActivationPolicy
This policy specifies whether implicit activation of servants is supported in the created POA.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.ImplicitActivationPolicyValue (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.ImplicitActivationPolicyValue

Packages that use ImplicitActivationPolicyValue
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of ImplicitActivationPolicyValue in org.omg.PortableServer

Fields in org.omg.PortableServer declared as ImplicitActivationPolicyValue
static ImplicitActivationPolicyValue | ImplicitActivationPolicyValue.IMPLICIT_ACTIVATION
static ImplicitActivationPolicyValue | ImplicitActivationPolicyValue.NO_IMPLICIT_ACTIVATION

Methods in org.omg.PortableServer that return ImplicitActivationPolicyValue
ImplicitActivationPolicyValue | ImplicitActivationPolicyOperations.value() specifies the policy value
static ImplicitActivationPolicyValue | ImplicitActivationPolicyValue.from_int(int value)

Methods in org.omg.PortableServer with parameters of type ImplicitActivationPolicyValue
 ImplicitActivationPolicy POAOperations.create_implicit_activation_policy(ImplicitActivationPolicyValue value)
These operations each return a reference to a policy object with the specified value.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableServer.LIFESPAN_POLICY_ID (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableServer.LIFESPAN_POLICY_ID

No usage of org.omg.PortableServer.LIFESPAN_POLICY_ID

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableServer.LifespanPolicy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableServer.LifespanPolicy

Packages that use LifespanPolicy
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of LifespanPolicy in org.omg.PortableServer

Methods in org.omg.PortableServer that return LifespanPolicy
 LifespanPolicy POAOperations.create_lifespan_policy(LifespanPolicyValue value)
These operations each return a reference to a policy object with the specified value.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableServer.LifespanPolicyOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableServer.LifespanPolicyOperations

Packages that use LifespanPolicyOperations
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of LifespanPolicyOperations in org.omg.PortableServer

Subinterfaces of LifespanPolicyOperations in org.omg.PortableServer
 interface LifespanPolicy
The LifespanPolicy specifies the lifespan of the objects implemented in the created POA.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.LifespanPolicyValue (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.LifespanPolicyValue

Packages that use LifespanPolicyValue
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of LifespanPolicyValue in org.omg.PortableServer

Fields in org.omg.PortableServer declared as LifespanPolicyValue
static LifespanPolicyValue | LifespanPolicyValue.TRANSIENT
static LifespanPolicyValue | LifespanPolicyValue.PERSISTENT

Methods in org.omg.PortableServer that return LifespanPolicyValue
LifespanPolicyValue | LifespanPolicyOperations.value() specifies the policy value
static LifespanPolicyValue | LifespanPolicyValue.from_int(int value)

Methods in org.omg.PortableServer with parameters of type LifespanPolicyValue
 LifespanPolicy POAOperations.create_lifespan_policy(LifespanPolicyValue value)
These operations each return a reference to a policy object with the specified value.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableServer.POA (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableServer.POA

Packages that use POA
org.omg.CosNaming | Provides a naming service for Java IDL.
org.omg.PortableServer | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.
org.omg.PortableServer.portable | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of POA in org.omg.CosNaming

Methods in org.omg.CosNaming with parameters of type POA
String[] | NamingContextExtPOA._all_interfaces(POA poa, byte[] objectId)
String[] | NamingContextPOA._all_interfaces(POA poa, byte[] objectId)
String[] | BindingIteratorPOA._all_interfaces(POA poa, byte[] objectId)

Uses of POA in org.omg.PortableServer

Methods in org.omg.PortableServer that return POA
static POA POAHelper.extract(Any a)
static POA POAHelper.read(InputStream istream)
static POA POAHelper.narrow(Object obj)
 POA CurrentOperations.get_POA()
Returns reference to the POA implementing the object in whose context it is called.
 POA POAOperations.create_POA(String adapter_name, POAManager a_POAManager, Policy[] policies)
This operation creates a new POA as a child of the target POA.
 POA POAOperations.find_POA(String adapter_name, boolean activate_it)
If the target POA is the parent of a child POA with the specified name (relative to the target POA), that child POA is returned.
 POA POAOperations.the_parent()
This attribute identifies the parent of the POA.
 POA[] POAOperations.the_children()
This attribute identifies the current set of all child POAs of the POA.
 POA Servant._poa()
Allows easy execution of common methods, equivalent to PortableServer::Current:get_POA.
 POA Servant._default_POA()
Returns the root POA from the ORB instance associated with the servant.

Methods in org.omg.PortableServer with parameters of type POA
Servant | _ServantLocatorStub.preinvoke(byte[] oid, POA adapter, String operation, CookieHolder the_cookie) This operations is used to get a servant that will be used to process the request that caused preinvoke to be called.
void | _ServantLocatorStub.postinvoke(byte[] oid, POA adapter, String operation, Object the_cookie, Servant the_servant) This operation is invoked whenener a servant completes a request.
String[] | ServantLocatorPOA._all_interfaces(POA poa, byte[] objectId)
Servant | ServantLocatorOperations.preinvoke(byte[] oid, POA adapter, String operation, CookieHolder the_cookie) This operations is used to get a servant that will be used to process the request that caused preinvoke to be called.
void | ServantLocatorOperations.postinvoke(byte[] oid, POA adapter, String operation, Object the_cookie, Servant the_servant) This operation is invoked whenener a servant completes a request.
Servant | _ServantActivatorStub.incarnate(byte[] oid, POA adapter) This 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 USE_SERVANT_MANAGER and RETAIN policies.
void | _ServantActivatorStub.etherealize(byte[] oid, POA adapter, Servant serv, boolean cleanup_in_progress, boolean remaining_activations) This operation is invoked whenever a servant for an object is deactivated, assuming the POA has the USE_SERVANT_MANAGER and RETAIN policies.
String[] | ServantActivatorPOA._all_interfaces(POA poa, byte[] objectId)
Servant | ServantActivatorOperations.incarnate(byte[] oid, POA adapter) This 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 USE_SERVANT_MANAGER and RETAIN policies.
void | ServantActivatorOperations.etherealize(byte[] oid, POA adapter, Servant serv, boolean cleanup_in_progress, boolean remaining_activations) This operation is invoked whenever a servant for an object is deactivated, assuming the POA has the USE_SERVANT_MANAGER and RETAIN policies.
static void | POAHelper.insert(Any a, POA that)
static void | POAHelper.write(OutputStream ostream, POA value)
boolean | AdapterActivatorOperations.unknown_adapter(POA parent, String name) This operation is invoked when the ORB receives a request for an object reference that identifies a target POA that does not exist.
abstract String[] | Servant._all_interfaces(POA poa, byte[] objectId) Used by the ORB to obtain complete type information from the servant.

Uses of POA in org.omg.PortableServer.portable

Methods in org.omg.PortableServer.portable that return POA
 POA Delegate.poa(Servant Self)
The method _poa() is equivalent to calling PortableServer::Current:get_POA.
 POA Delegate.default_POA(Servant Self)
The default behavior of this function is to return the root POA from the ORB instance associated with the servant.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.POAHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.POAHelper

No usage of org.omg.PortableServer.POAHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableServer.POAManager (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableServer.POAManager

Packages that use POAManager
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of POAManager in org.omg.PortableServer

Methods in org.omg.PortableServer that return POAManager
 POAManager POAOperations.the_POAManager()
This attribute identifies the POA manager associated with the POA.

Methods in org.omg.PortableServer with parameters of type POAManager
 POA POAOperations.create_POA(String adapter_name, POAManager a_POAManager, Policy[] policies)
This operation creates a new POA as a child of the target POA.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableServer.POAManagerOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableServer.POAManagerOperations

Packages that use POAManagerOperations
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of POAManagerOperations in org.omg.PortableServer

Subinterfaces of POAManagerOperations in org.omg.PortableServer
 interface POAManager
Each POA object has an associated POAManager object.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableServer.POAOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableServer.POAOperations

Packages that use POAOperations
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of POAOperations in org.omg.PortableServer

Subinterfaces of POAOperations in org.omg.PortableServer
 interface POA
A POA object manages the implementation of a collection of objects.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableServer.REQUEST_PROCESSING_POLICY_ID (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableServer.REQUEST_PROCESSING_POLICY_ID

No usage of org.omg.PortableServer.REQUEST_PROCESSING_POLICY_ID

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableServer.RequestProcessingPolicy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableServer.RequestProcessingPolicy

Packages that use RequestProcessingPolicy
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of RequestProcessingPolicy in org.omg.PortableServer

Methods in org.omg.PortableServer that return RequestProcessingPolicy
 RequestProcessingPolicy POAOperations.create_request_processing_policy(RequestProcessingPolicyValue value)
These operations each return a reference to a policy object with the specified value.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableServer.RequestProcessingPolicyOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableServer.RequestProcessingPolicyOperations

Packages that use RequestProcessingPolicyOperations
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of RequestProcessingPolicyOperations in org.omg.PortableServer

Subinterfaces of RequestProcessingPolicyOperations in org.omg.PortableServer
 interface RequestProcessingPolicy
This policy specifies how requests are processed by the created POA.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.RequestProcessingPolicyValue (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.RequestProcessingPolicyValue

Packages that use RequestProcessingPolicyValue
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of RequestProcessingPolicyValue in org.omg.PortableServer

Fields in org.omg.PortableServer declared as RequestProcessingPolicyValue
static RequestProcessingPolicyValue | RequestProcessingPolicyValue.USE_ACTIVE_OBJECT_MAP_ONLY
static RequestProcessingPolicyValue | RequestProcessingPolicyValue.USE_DEFAULT_SERVANT
static RequestProcessingPolicyValue | RequestProcessingPolicyValue.USE_SERVANT_MANAGER

Methods in org.omg.PortableServer that return RequestProcessingPolicyValue
RequestProcessingPolicyValue | RequestProcessingPolicyOperations.value() specifies the policy value
static RequestProcessingPolicyValue | RequestProcessingPolicyValue.from_int(int value)

Methods in org.omg.PortableServer with parameters of type RequestProcessingPolicyValue
 RequestProcessingPolicy POAOperations.create_request_processing_policy(RequestProcessingPolicyValue value)
These operations each return a reference to a policy object with the specified value.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.Servant (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.Servant

Packages that use Servant
org.omg.CosNaming | Provides a naming service for Java IDL.
org.omg.PortableServer | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.
org.omg.PortableServer.portable | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of Servant in org.omg.CosNaming

Subclasses of Servant in org.omg.CosNaming
class | BindingIteratorPOA The BindingIterator interface allows a client to iterate through the bindings using the next_one or next_n operations.
class | NamingContextExtPOA 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.
class | NamingContextPOA A naming context is an object that contains a set of name bindings in which each name is unique.

Uses of Servant in org.omg.PortableServer

Subclasses of Servant in org.omg.PortableServer
class | DynamicImplementation Allows dynamic handling of object invocations.
class | ServantActivatorPOA When the POA has the RETAIN policy it uses servant managers that are ServantActivators.
class | ServantLocatorPOA When the POA has the NON_RETAIN policy it uses servant managers that are ServantLocators.

Methods in org.omg.PortableServer that return Servant
Servant | _ServantLocatorStub.preinvoke(byte[] oid, POA adapter, String operation, CookieHolder the_cookie) This operations is used to get a servant that will be used to process the request that caused preinvoke to be called.
Servant | ServantLocatorOperations.preinvoke(byte[] oid, POA adapter, String operation, CookieHolder the_cookie) This operations is used to get a servant that will be used to process the request that caused preinvoke to be called.
Servant | _ServantActivatorStub.incarnate(byte[] oid, POA adapter) This 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 USE_SERVANT_MANAGER and RETAIN policies.
Servant | ServantActivatorOperations.incarnate(byte[] oid, POA adapter) This 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 USE_SERVANT_MANAGER and RETAIN policies.
Servant | POAOperations.get_servant() This operation returns the default servant associated with the POA.
Servant | POAOperations.reference_to_servant(Object reference) 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.
Servant | POAOperations.id_to_servant(byte[] oid) If the POA has the RETAIN policy and the specified ObjectId is in the Active Object Map, this operation returns the servant associated with that object in the Active Object Map.

Methods in org.omg.PortableServer with parameters of type Servant
void | _ServantLocatorStub.postinvoke(byte[] oid, POA adapter, String operation, Object the_cookie, Servant the_servant) This operation is invoked whenener a servant completes a request.
void | ServantLocatorOperations.postinvoke(byte[] oid, POA adapter, String operation, Object the_cookie, Servant the_servant) This operation is invoked whenener a servant completes a request.
void | _ServantActivatorStub.etherealize(byte[] oid, POA adapter, Servant serv, boolean cleanup_in_progress, boolean remaining_activations) This operation is invoked whenever a servant for an object is deactivated, assuming the POA has the USE_SERVANT_MANAGER and RETAIN policies.
void | ServantActivatorOperations.etherealize(byte[] oid, POA adapter, Servant serv, boolean cleanup_in_progress, boolean remaining_activations) This operation is invoked whenever a servant for an object is deactivated, assuming the POA has the USE_SERVANT_MANAGER and RETAIN policies.
void | POAOperations.set_servant(Servant p_servant) This operation registers the specified servant with the POA as the default servant.
byte[] | POAOperations.activate_object(Servant p_servant) This operation generates an Object Id and enters the Object Id and the specified servant in the Active Object Map.
void | POAOperations.activate_object_with_id(byte[] id, Servant p_servant) This operation enters an association between the specified Object Id and the specified servant in the Active Object Map.
byte[] | POAOperations.servant_to_id(Servant p_servant) This operation has four possible behaviors.
Object | POAOperations.servant_to_reference(Servant p_servant) 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.

Uses of Servant in org.omg.PortableServer.portable

Methods in org.omg.PortableServer.portable with parameters of type Servant
 ORB Delegate.orb(Servant Self)
Convenience method that returns the instance of the ORB currently associated with the Servant.
 Object Delegate.this_object(Servant Self)
This allows the servant to obtain the object reference for the target CORBA Object it is incarnating for that request.
 POA Delegate.poa(Servant Self)
The method _poa() is equivalent to calling PortableServer::Current:get_POA.
 byte[] Delegate.object_id(Servant Self)
The method _object_id() is equivalent to calling PortableServer::Current::get_object_id.
 POA Delegate.default_POA(Servant Self)
The default behavior of this function is to return the root POA from the ORB instance associated with the servant.
 boolean Delegate.is_a(Servant Self, String Repository_Id)
This method checks to see if the specified repid is present on the list returned by _all_interfaces() or is the repository id for the generic CORBA Object.
 boolean Delegate.non_existent(Servant Self)
This operation is used to check for the existence of the Object.
 Object Delegate.get_interface_def(Servant self)
This operation returns an object in the Interface Repository which provides type information that may be useful to a program.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableServer.SERVANT_RETENTION_POLICY_ID (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableServer.SERVANT_RETENTION_POLICY_ID

No usage of org.omg.PortableServer.SERVANT_RETENTION_POLICY_ID

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableServer.ServantActivator (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableServer.ServantActivator

Packages that use ServantActivator
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of ServantActivator in org.omg.PortableServer

Classes in org.omg.PortableServer that implement ServantActivator
 class _ServantActivatorStub
When the POA has the RETAIN policy it uses servant managers that are ServantActivators.

Methods in org.omg.PortableServer that return ServantActivator
ServantActivator | ServantActivatorPOA._this()
ServantActivator | ServantActivatorPOA._this(ORB orb)
static ServantActivator | ServantActivatorHelper.extract(Any a)
static ServantActivator | ServantActivatorHelper.read(InputStream istream)
static ServantActivator | ServantActivatorHelper.narrow(Object obj)

Methods in org.omg.PortableServer with parameters of type ServantActivator
static void | ServantActivatorHelper.insert(Any a, ServantActivator that)
static void | ServantActivatorHelper.write(OutputStream ostream, ServantActivator value)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.ServantActivatorHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.ServantActivatorHelper

No usage of org.omg.PortableServer.ServantActivatorHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableServer.ServantActivatorOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableServer.ServantActivatorOperations

Packages that use ServantActivatorOperations
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of ServantActivatorOperations in org.omg.PortableServer

Subinterfaces of ServantActivatorOperations in org.omg.PortableServer
 interface ServantActivator
When the POA has the RETAIN policy it uses servant managers that are ServantActivators.

Classes in org.omg.PortableServer that implement ServantActivatorOperations
class | _ServantActivatorStub When the POA has the RETAIN policy it uses servant managers that are ServantActivators.
class | ServantActivatorPOA When the POA has the RETAIN policy it uses servant managers that are ServantActivators.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.ServantActivatorPOA (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.ServantActivatorPOA

No usage of org.omg.PortableServer.ServantActivatorPOA

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableServer.ServantLocator (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableServer.ServantLocator

Packages that use ServantLocator
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of ServantLocator in org.omg.PortableServer

Classes in org.omg.PortableServer that implement ServantLocator
 class _ServantLocatorStub
When the POA has the NON_RETAIN policy it uses servant managers that are ServantLocators.

Methods in org.omg.PortableServer that return ServantLocator
ServantLocator | ServantLocatorPOA._this()
ServantLocator | ServantLocatorPOA._this(ORB orb)
static ServantLocator | ServantLocatorHelper.extract(Any a)
static ServantLocator | ServantLocatorHelper.read(InputStream istream)
static ServantLocator | ServantLocatorHelper.narrow(Object obj)

Methods in org.omg.PortableServer with parameters of type ServantLocator
static void | ServantLocatorHelper.insert(Any a, ServantLocator that)
static void | ServantLocatorHelper.write(OutputStream ostream, ServantLocator value)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.ServantLocatorHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.ServantLocatorHelper

No usage of org.omg.PortableServer.ServantLocatorHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableServer.ServantLocatorOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableServer.ServantLocatorOperations

Packages that use ServantLocatorOperations
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of ServantLocatorOperations in org.omg.PortableServer

Subinterfaces of ServantLocatorOperations in org.omg.PortableServer
 interface ServantLocator
When the POA has the NON_RETAIN policy it uses servant managers that are ServantLocators.

Classes in org.omg.PortableServer that implement ServantLocatorOperations
class | _ServantLocatorStub When the POA has the NON_RETAIN policy it uses servant managers that are ServantLocators.
class | ServantLocatorPOA When the POA has the NON_RETAIN policy it uses servant managers that are ServantLocators.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.ServantLocatorPOA (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.ServantLocatorPOA

No usage of org.omg.PortableServer.ServantLocatorPOA

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableServer.ServantManager (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableServer.ServantManager

Packages that use ServantManager
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of ServantManager in org.omg.PortableServer

Subinterfaces of ServantManager in org.omg.PortableServer
interface | ServantActivator When the POA has the RETAIN policy it uses servant managers that are ServantActivators.
interface | ServantLocator When the POA has the NON_RETAIN policy it uses servant managers that are ServantLocators.

Classes in org.omg.PortableServer that implement ServantManager
class | _ServantActivatorStub When the POA has the RETAIN policy it uses servant managers that are ServantActivators.
class | _ServantLocatorStub When the POA has the NON_RETAIN policy it uses servant managers that are ServantLocators.

Methods in org.omg.PortableServer that return ServantManager
 ServantManager POAOperations.get_servant_manager()
If the ServantRetentionPolicy of the POA is RETAIN, then the ServantManager argument (imgr) shall support the ServantActivator interface.

Methods in org.omg.PortableServer with parameters of type ServantManager
 void POAOperations.set_servant_manager(ServantManager imgr)
This operation sets the default servant manager associated with the POA.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableServer.ServantManagerOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableServer.ServantManagerOperations

Packages that use ServantManagerOperations
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of ServantManagerOperations in org.omg.PortableServer

Subinterfaces of ServantManagerOperations in org.omg.PortableServer
interface | ServantActivator When the POA has the RETAIN policy it uses servant managers that are ServantActivators.
interface | ServantActivatorOperations When the POA has the RETAIN policy it uses servant managers that are ServantActivators.
interface | ServantLocator When the POA has the NON_RETAIN policy it uses servant managers that are ServantLocators.
interface | ServantLocatorOperations When the POA has the NON_RETAIN policy it uses servant managers that are ServantLocators.
interface | ServantManager 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.

Classes in org.omg.PortableServer that implement ServantManagerOperations
class | _ServantActivatorStub When the POA has the RETAIN policy it uses servant managers that are ServantActivators.
class | _ServantLocatorStub When the POA has the NON_RETAIN policy it uses servant managers that are ServantLocators.
class | ServantActivatorPOA When the POA has the RETAIN policy it uses servant managers that are ServantActivators.
class | ServantLocatorPOA When the POA has the NON_RETAIN policy it uses servant managers that are ServantLocators.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableServer.ServantRetentionPolicy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableServer.ServantRetentionPolicy

Packages that use ServantRetentionPolicy
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of ServantRetentionPolicy in org.omg.PortableServer

Methods in org.omg.PortableServer that return ServantRetentionPolicy
 ServantRetentionPolicy POAOperations.create_servant_retention_policy(ServantRetentionPolicyValue value)
These operations each return a reference to a policy object with the specified value.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableServer.ServantRetentionPolicyOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableServer.ServantRetentionPolicyOperations

Packages that use ServantRetentionPolicyOperations
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of ServantRetentionPolicyOperations in org.omg.PortableServer

Subinterfaces of ServantRetentionPolicyOperations in org.omg.PortableServer
 interface ServantRetentionPolicy
This policy specifies whether the created POA retains active servants in an Active Object Map.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.ServantRetentionPolicyValue (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.ServantRetentionPolicyValue

Packages that use ServantRetentionPolicyValue
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of ServantRetentionPolicyValue in org.omg.PortableServer

Fields in org.omg.PortableServer declared as ServantRetentionPolicyValue
static ServantRetentionPolicyValue | ServantRetentionPolicyValue.RETAIN
static ServantRetentionPolicyValue | ServantRetentionPolicyValue.NON_RETAIN

Methods in org.omg.PortableServer that return ServantRetentionPolicyValue
ServantRetentionPolicyValue | ServantRetentionPolicyOperations.value() specifies the policy value
static ServantRetentionPolicyValue | ServantRetentionPolicyValue.from_int(int value)

Methods in org.omg.PortableServer with parameters of type ServantRetentionPolicyValue
 ServantRetentionPolicy POAOperations.create_servant_retention_policy(ServantRetentionPolicyValue value)
These operations each return a reference to a policy object with the specified value.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableServer.THREAD_POLICY_ID (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableServer.THREAD_POLICY_ID

No usage of org.omg.PortableServer.THREAD_POLICY_ID

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableServer.ThreadPolicy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableServer.ThreadPolicy

Packages that use ThreadPolicy
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of ThreadPolicy in org.omg.PortableServer

Methods in org.omg.PortableServer that return ThreadPolicy
 ThreadPolicy POAOperations.create_thread_policy(ThreadPolicyValue value)
These operations each return a reference to a policy object with the specified value.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableServer.ThreadPolicyOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableServer.ThreadPolicyOperations

Packages that use ThreadPolicyOperations
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of ThreadPolicyOperations in org.omg.PortableServer

Subinterfaces of ThreadPolicyOperations in org.omg.PortableServer
 interface ThreadPolicy
The ThreadPolicy specifies the threading model used with the created POA.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.ThreadPolicyValue (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.ThreadPolicyValue

Packages that use ThreadPolicyValue
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of ThreadPolicyValue in org.omg.PortableServer

Fields in org.omg.PortableServer declared as ThreadPolicyValue
static ThreadPolicyValue | ThreadPolicyValue.ORB_CTRL_MODEL
static ThreadPolicyValue | ThreadPolicyValue.SINGLE_THREAD_MODEL

Methods in org.omg.PortableServer that return ThreadPolicyValue
ThreadPolicyValue | ThreadPolicyOperations.value() specifies the policy value
static ThreadPolicyValue | ThreadPolicyValue.from_int(int value)

Methods in org.omg.PortableServer with parameters of type ThreadPolicyValue
 ThreadPolicy POAOperations.create_thread_policy(ThreadPolicyValue value)
These operations each return a reference to a policy object with the specified value.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


NoContext (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer.CurrentPackage
Class NoContext

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.PortableServer.CurrentPackage.NoContext
All Implemented Interfaces:
IDLEntity, Serializable
public final class NoContext
extends UserException

org/omg/PortableServer/CurrentPackage/NoContext.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableServer/poa.idl Thursday, June 12, 2003 9:59:11 PM GMT-08:00

Constructor Summary
NoContext()
NoContext(String $reason)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

NoContext

public NoContext()

NoContext

public NoContext(String $reason)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


NoContextHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer.CurrentPackage
Class NoContextHelper

java.lang.Object
    extended by org.omg.PortableServer.CurrentPackage.NoContextHelper
public abstract class NoContextHelper
extends Object

org/omg/PortableServer/CurrentPackage/NoContextHelper.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableServer/poa.idl Thursday, June 12, 2003 9:59:11 PM GMT-08:00

Constructor Summary
NoContextHelper()
Method Summary
static NoContext | extract(Any a)
static String | id()
static void | insert(Any a, NoContext that)
static NoContext | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, NoContext value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

NoContextHelper

public NoContextHelper()
Method Detail

insert

public static void insert(Any a,
                          NoContext that)

extract

public static NoContext extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static NoContext read(InputStream istream)

write

public static void write(OutputStream ostream,
                         NoContext value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


org.omg.PortableServer.CurrentPackage (Java 2 Platform SE v1.4.2)

 org.omg.PortableServer.CurrentPackage
Classes
NoContextHelper
Exceptions
NoContext


org.omg.PortableServer.CurrentPackage (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package org.omg.PortableServer.CurrentPackage

Provides method implementations with access to the identity of the object on which the method was invoked.

See:
Description

Class Summary
NoContextHelper org/omg/PortableServer/CurrentPackage/NoContextHelper.java .

Exception Summary
NoContext org/omg/PortableServer/CurrentPackage/NoContext.java .

Package org.omg.PortableServer.CurrentPackage Description

Provides method implementations with access to the identity of the object on which the method was invoked. The Current package supports servants that implement multiple objects, but can be used within the context of POA-dispatched method invocations on any servant. To provide location transparency, ORBs are required to support use of Current in the context of both locally and remotely invoked operations. An instance of Current can be obtained by the application by issuing the CORBA::ORB::resolve_initial_references("POACurrent") operation. Thereafter, it can be used within the context of a method dispatched by the POA to obtain the POA and ObjectId that identify the object on which that operation was invoked.

Package Specification

For a precise list of supported sections of official specifications with which the Java 2 Platform, Standard Edition, v.1.4 ORB complies, see Official Specifications for CORBA support in J2SE 1.4.

Since:
1.4
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


org.omg.PortableServer.CurrentPackage Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package org.omg.PortableServer.CurrentPackage

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class org.omg.PortableServer.CurrentPackage.NoContextHelper
    • class java.lang.Throwable (implements java.io.Serializable)
      • class java.lang.Exception
        • class org.omg.CORBA.UserException (implements org.omg.CORBA.portable.IDLEntity)
          • class org.omg.PortableServer.CurrentPackage.NoContext
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package org.omg.PortableServer.CurrentPackage (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
org.omg.PortableServer.CurrentPackage

Packages that use org.omg.PortableServer.CurrentPackage
org.omg.PortableServer | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.
org.omg.PortableServer.CurrentPackage | Provides method implementations with access to the identity of the object on which the method was invoked.

Classes in org.omg.PortableServer.CurrentPackage used by org.omg.PortableServer
NoContext
org/omg/PortableServer/CurrentPackage/NoContext.java .

Classes in org.omg.PortableServer.CurrentPackage used by org.omg.PortableServer.CurrentPackage
NoContext
org/omg/PortableServer/CurrentPackage/NoContext.java .

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.CurrentPackage.NoContext (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.CurrentPackage.NoContext

Packages that use NoContext
org.omg.PortableServer | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.
org.omg.PortableServer.CurrentPackage | Provides method implementations with access to the identity of the object on which the method was invoked.

Uses of NoContext in org.omg.PortableServer

Methods in org.omg.PortableServer that throw NoContext
POA | CurrentOperations.get_POA() Returns reference to the POA implementing the object in whose context it is called.
byte[] | CurrentOperations.get_object_id() Returns the ObjectId identifying the object in whose context it is called.

Uses of NoContext in org.omg.PortableServer.CurrentPackage

Methods in org.omg.PortableServer.CurrentPackage that return NoContext
static NoContext | NoContextHelper.extract(Any a)
static NoContext | NoContextHelper.read(InputStream istream)

Methods in org.omg.PortableServer.CurrentPackage with parameters of type NoContext
static void | NoContextHelper.insert(Any a, NoContext that)
static void | NoContextHelper.write(OutputStream ostream, NoContext value)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.CurrentPackage.NoContextHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.CurrentPackage.NoContextHelper

No usage of org.omg.PortableServer.CurrentPackage.NoContextHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


AdapterInactive (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer.POAManagerPackage
Class AdapterInactive

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.PortableServer.POAManagerPackage.AdapterInactive
All Implemented Interfaces:
IDLEntity, Serializable
public final class AdapterInactive
extends UserException

org/omg/PortableServer/POAManagerPackage/AdapterInactive.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableServer/poa.idl Thursday, June 12, 2003 9:59:11 PM GMT-08:00

Constructor Summary
AdapterInactive()
AdapterInactive(String $reason)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

AdapterInactive

public AdapterInactive()

AdapterInactive

public AdapterInactive(String $reason)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


AdapterInactiveHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer.POAManagerPackage
Class AdapterInactiveHelper

java.lang.Object
    extended by org.omg.PortableServer.POAManagerPackage.AdapterInactiveHelper
public abstract class AdapterInactiveHelper
extends Object

org/omg/PortableServer/POAManagerPackage/AdapterInactiveHelper.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableServer/poa.idl Thursday, June 12, 2003 9:59:11 PM GMT-08:00

Constructor Summary
AdapterInactiveHelper()
Method Summary
static AdapterInactive | extract(Any a)
static String | id()
static void | insert(Any a, AdapterInactive that)
static AdapterInactive | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, AdapterInactive value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

AdapterInactiveHelper

public AdapterInactiveHelper()
Method Detail

insert

public static void insert(Any a,
                          AdapterInactive that)

extract

public static AdapterInactive extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static AdapterInactive read(InputStream istream)

write

public static void write(OutputStream ostream,
                         AdapterInactive value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


org.omg.PortableServer.POAManagerPackage (Java 2 Platform SE v1.4.2)

 org.omg.PortableServer.POAManagerPackage
Classes
AdapterInactiveHelper
State
Exceptions
AdapterInactive


org.omg.PortableServer.POAManagerPackage (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package org.omg.PortableServer.POAManagerPackage

Encapsulates the processing state of the POAs it is associated with.

See:
Description

Class Summary
AdapterInactiveHelper | org/omg/PortableServer/POAManagerPackage/AdapterInactiveHelper.java .
State | Specifies the states for the POAManager

Exception Summary
AdapterInactive org/omg/PortableServer/POAManagerPackage/AdapterInactive.java .

Package org.omg.PortableServer.POAManagerPackage Description

Encapsulates the processing state of the POAs it is associated with. Each POA object has an associated POAManager object. A POA manager may be associated with one or more POA objects.

Package Specification

For a precise list of supported sections of official specifications with which the Java 2 Platform, Standard Edition, v.1.4 ORB complies, see Official Specifications for CORBA support in J2SE 1.4.

Since:
1.4
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


org.omg.PortableServer.POAManagerPackage Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package org.omg.PortableServer.POAManagerPackage

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class org.omg.PortableServer.POAManagerPackage.AdapterInactiveHelper
    • class org.omg.PortableServer.POAManagerPackage.State (implements org.omg.CORBA.portable.IDLEntity)
    • class java.lang.Throwable (implements java.io.Serializable)
      • class java.lang.Exception
        • class org.omg.CORBA.UserException (implements org.omg.CORBA.portable.IDLEntity)
          • class org.omg.PortableServer.POAManagerPackage.AdapterInactive
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package org.omg.PortableServer.POAManagerPackage (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
org.omg.PortableServer.POAManagerPackage

Packages that use org.omg.PortableServer.POAManagerPackage
org.omg.PortableServer | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.
org.omg.PortableServer.POAManagerPackage | Encapsulates the processing state of the POAs it is associated with.

Classes in org.omg.PortableServer.POAManagerPackage used by org.omg.PortableServer
AdapterInactive
org/omg/PortableServer/POAManagerPackage/AdapterInactive.java .
State
Specifies the states for the POAManager

Classes in org.omg.PortableServer.POAManagerPackage used by org.omg.PortableServer.POAManagerPackage
AdapterInactive
org/omg/PortableServer/POAManagerPackage/AdapterInactive.java .
State
Specifies the states for the POAManager

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


State (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer.POAManagerPackage
Class State

java.lang.Object
    extended by org.omg.PortableServer.POAManagerPackage.State
All Implemented Interfaces:
IDLEntity, Serializable
public class State
extends Object
implements IDLEntity

Specifies the states for the POAManager

Field Summary
static int | _ACTIVE
static int | _DISCARDING
static int | _HOLDING
static int | _INACTIVE
static State | ACTIVE
static State | DISCARDING
static State | HOLDING
static State | INACTIVE
Constructor Summary
protected State(int value)
Method Summary
static State | from_int(int value)
int | value()
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

_HOLDING

public static final int _HOLDING
See Also:
Constant Field Values

HOLDING

public static final State HOLDING

_ACTIVE

public static final int _ACTIVE
See Also:
Constant Field Values

ACTIVE

public static final State ACTIVE

_DISCARDING

public static final int _DISCARDING
See Also:
Constant Field Values

DISCARDING

public static final State DISCARDING

_INACTIVE

public static final int _INACTIVE
See Also:
Constant Field Values

INACTIVE

public static final State INACTIVE
Constructor Detail

State

protected State(int value)
Method Detail

value

public int value()

from_int

public static State from_int(int value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Uses of Class org.omg.PortableServer.POAManagerPackage.AdapterInactive (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.POAManagerPackage.AdapterInactive

Packages that use AdapterInactive
org.omg.PortableServer | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.
org.omg.PortableServer.POAManagerPackage | Encapsulates the processing state of the POAs it is associated with.

Uses of AdapterInactive in org.omg.PortableServer

Methods in org.omg.PortableServer that throw AdapterInactive
void | POAManagerOperations.activate() This operation changes the state of the POA manager to active, causing associated POAs to start processing requests.
void | POAManagerOperations.hold_requests(boolean wait_for_completion) This operation changes the state of the POA manager to holding, causing associated POAs to queue incoming requests.
void | POAManagerOperations.discard_requests(boolean wait_for_completion) This operation changes the state of the POA manager to discarding.
void | POAManagerOperations.deactivate(boolean etherealize_objects, boolean wait_for_completion) This operation changes the state of the POA manager to inactive, causing associated POAs to reject the requests that have not begun executing as well as as any new requests.

Uses of AdapterInactive in org.omg.PortableServer.POAManagerPackage

Methods in org.omg.PortableServer.POAManagerPackage that return AdapterInactive
static AdapterInactive | AdapterInactiveHelper.extract(Any a)
static AdapterInactive | AdapterInactiveHelper.read(InputStream istream)

Methods in org.omg.PortableServer.POAManagerPackage with parameters of type AdapterInactive
static void | AdapterInactiveHelper.insert(Any a, AdapterInactive that)
static void | AdapterInactiveHelper.write(OutputStream ostream, AdapterInactive value)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.POAManagerPackage.AdapterInactiveHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.POAManagerPackage.AdapterInactiveHelper

No usage of org.omg.PortableServer.POAManagerPackage.AdapterInactiveHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.POAManagerPackage.State (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.POAManagerPackage.State

Packages that use State
org.omg.PortableServer | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.
org.omg.PortableServer.POAManagerPackage | Encapsulates the processing state of the POAs it is associated with.

Uses of State in org.omg.PortableServer

Methods in org.omg.PortableServer that return State
 State POAManagerOperations.get_state()
This operation returns the state of the POA manager.

Uses of State in org.omg.PortableServer.POAManagerPackage

Fields in org.omg.PortableServer.POAManagerPackage declared as State
static State | State.HOLDING
static State | State.ACTIVE
static State | State.DISCARDING
static State | State.INACTIVE

Methods in org.omg.PortableServer.POAManagerPackage that return State
static State State.from_int(int value)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


AdapterAlreadyExists (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer.POAPackage
Class AdapterAlreadyExists

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.PortableServer.POAPackage.AdapterAlreadyExists
All Implemented Interfaces:
IDLEntity, Serializable
public final class AdapterAlreadyExists
extends UserException

org/omg/PortableServer/POAPackage/AdapterAlreadyExists.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableServer/poa.idl Thursday, June 12, 2003 9:59:11 PM GMT-08:00

Constructor Summary
AdapterAlreadyExists()
AdapterAlreadyExists(String $reason)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

AdapterAlreadyExists

public AdapterAlreadyExists()

AdapterAlreadyExists

public AdapterAlreadyExists(String $reason)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


AdapterAlreadyExistsHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer.POAPackage
Class AdapterAlreadyExistsHelper

java.lang.Object
    extended by org.omg.PortableServer.POAPackage.AdapterAlreadyExistsHelper
public abstract class AdapterAlreadyExistsHelper
extends Object

org/omg/PortableServer/POAPackage/AdapterAlreadyExistsHelper.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableServer/poa.idl Thursday, June 12, 2003 9:59:11 PM GMT-08:00

Constructor Summary
AdapterAlreadyExistsHelper()
Method Summary
static AdapterAlreadyExists | extract(Any a)
static String | id()
static void | insert(Any a, AdapterAlreadyExists that)
static AdapterAlreadyExists | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, AdapterAlreadyExists value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

AdapterAlreadyExistsHelper

public AdapterAlreadyExistsHelper()
Method Detail

insert

public static void insert(Any a,
                          AdapterAlreadyExists that)

extract

public static AdapterAlreadyExists extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static AdapterAlreadyExists read(InputStream istream)

write

public static void write(OutputStream ostream,
                         AdapterAlreadyExists value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


AdapterNonExistent (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer.POAPackage
Class AdapterNonExistent

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.PortableServer.POAPackage.AdapterNonExistent
All Implemented Interfaces:
IDLEntity, Serializable
public final class AdapterNonExistent
extends UserException

org/omg/PortableServer/POAPackage/AdapterNonExistent.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableServer/poa.idl Thursday, June 12, 2003 9:59:11 PM GMT-08:00

Constructor Summary
AdapterNonExistent()
AdapterNonExistent(String $reason)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

AdapterNonExistent

public AdapterNonExistent()

AdapterNonExistent

public AdapterNonExistent(String $reason)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


AdapterNonExistentHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer.POAPackage
Class AdapterNonExistentHelper

java.lang.Object
    extended by org.omg.PortableServer.POAPackage.AdapterNonExistentHelper
public abstract class AdapterNonExistentHelper
extends Object

org/omg/PortableServer/POAPackage/AdapterNonExistentHelper.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableServer/poa.idl Thursday, June 12, 2003 9:59:11 PM GMT-08:00

Constructor Summary
AdapterNonExistentHelper()
Method Summary
static AdapterNonExistent | extract(Any a)
static String | id()
static void | insert(Any a, AdapterNonExistent that)
static AdapterNonExistent | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, AdapterNonExistent value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

AdapterNonExistentHelper

public AdapterNonExistentHelper()
Method Detail

insert

public static void insert(Any a,
                          AdapterNonExistent that)

extract

public static AdapterNonExistent extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static AdapterNonExistent read(InputStream istream)

write

public static void write(OutputStream ostream,
                         AdapterNonExistent value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


InvalidPolicy (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer.POAPackage
Class InvalidPolicy

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.PortableServer.POAPackage.InvalidPolicy
All Implemented Interfaces:
IDLEntity, Serializable
public final class InvalidPolicy
extends UserException

org/omg/PortableServer/POAPackage/InvalidPolicy.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableServer/poa.idl Thursday, June 12, 2003 9:59:11 PM GMT-08:00

Field Summary
 short index
Constructor Summary
InvalidPolicy()
InvalidPolicy(short _index)
InvalidPolicy(String $reason, short _index)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

index

public short index
Constructor Detail

InvalidPolicy

public InvalidPolicy()

InvalidPolicy

public InvalidPolicy(short _index)

InvalidPolicy

public InvalidPolicy(String $reason,
                     short _index)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


InvalidPolicyHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer.POAPackage
Class InvalidPolicyHelper

java.lang.Object
    extended by org.omg.PortableServer.POAPackage.InvalidPolicyHelper
public abstract class InvalidPolicyHelper
extends Object

org/omg/PortableServer/POAPackage/InvalidPolicyHelper.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableServer/poa.idl Thursday, June 12, 2003 9:59:11 PM GMT-08:00

Constructor Summary
InvalidPolicyHelper()
Method Summary
static InvalidPolicy | extract(Any a)
static String | id()
static void | insert(Any a, InvalidPolicy that)
static InvalidPolicy | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, InvalidPolicy value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

InvalidPolicyHelper

public InvalidPolicyHelper()
Method Detail

insert

public static void insert(Any a,
                          InvalidPolicy that)

extract

public static InvalidPolicy extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static InvalidPolicy read(InputStream istream)

write

public static void write(OutputStream ostream,
                         InvalidPolicy value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NoServant (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer.POAPackage
Class NoServant

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.PortableServer.POAPackage.NoServant
All Implemented Interfaces:
IDLEntity, Serializable
public final class NoServant
extends UserException

org/omg/PortableServer/POAPackage/NoServant.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableServer/poa.idl Thursday, June 12, 2003 9:59:11 PM GMT-08:00

Constructor Summary
NoServant()
NoServant(String $reason)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

NoServant

public NoServant()

NoServant

public NoServant(String $reason)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NoServantHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer.POAPackage
Class NoServantHelper

java.lang.Object
    extended by org.omg.PortableServer.POAPackage.NoServantHelper
public abstract class NoServantHelper
extends Object

org/omg/PortableServer/POAPackage/NoServantHelper.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableServer/poa.idl Thursday, June 12, 2003 9:59:11 PM GMT-08:00

Constructor Summary
NoServantHelper()
Method Summary
static NoServant | extract(Any a)
static String | id()
static void | insert(Any a, NoServant that)
static NoServant | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, NoServant value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

NoServantHelper

public NoServantHelper()
Method Detail

insert

public static void insert(Any a,
                          NoServant that)

extract

public static NoServant extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static NoServant read(InputStream istream)

write

public static void write(OutputStream ostream,
                         NoServant value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ObjectAlreadyActive (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer.POAPackage
Class ObjectAlreadyActive

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.PortableServer.POAPackage.ObjectAlreadyActive
All Implemented Interfaces:
IDLEntity, Serializable
public final class ObjectAlreadyActive
extends UserException

org/omg/PortableServer/POAPackage/ObjectAlreadyActive.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableServer/poa.idl Thursday, June 12, 2003 9:59:11 PM GMT-08:00

Constructor Summary
ObjectAlreadyActive()
ObjectAlreadyActive(String $reason)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

ObjectAlreadyActive

public ObjectAlreadyActive()

ObjectAlreadyActive

public ObjectAlreadyActive(String $reason)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ObjectAlreadyActiveHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer.POAPackage
Class ObjectAlreadyActiveHelper

java.lang.Object
    extended by org.omg.PortableServer.POAPackage.ObjectAlreadyActiveHelper
public abstract class ObjectAlreadyActiveHelper
extends Object

org/omg/PortableServer/POAPackage/ObjectAlreadyActiveHelper.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableServer/poa.idl Thursday, June 12, 2003 9:59:11 PM GMT-08:00

Constructor Summary
ObjectAlreadyActiveHelper()
Method Summary
static ObjectAlreadyActive | extract(Any a)
static String | id()
static void | insert(Any a, ObjectAlreadyActive that)
static ObjectAlreadyActive | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, ObjectAlreadyActive value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ObjectAlreadyActiveHelper

public ObjectAlreadyActiveHelper()
Method Detail

insert

public static void insert(Any a,
                          ObjectAlreadyActive that)

extract

public static ObjectAlreadyActive extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static ObjectAlreadyActive read(InputStream istream)

write

public static void write(OutputStream ostream,
                         ObjectAlreadyActive value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ObjectNotActive (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer.POAPackage
Class ObjectNotActive

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.PortableServer.POAPackage.ObjectNotActive
All Implemented Interfaces:
IDLEntity, Serializable
public final class ObjectNotActive
extends UserException

org/omg/PortableServer/POAPackage/ObjectNotActive.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableServer/poa.idl Thursday, June 12, 2003 9:59:11 PM GMT-08:00

Constructor Summary
ObjectNotActive()
ObjectNotActive(String $reason)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

ObjectNotActive

public ObjectNotActive()

ObjectNotActive

public ObjectNotActive(String $reason)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ObjectNotActiveHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer.POAPackage
Class ObjectNotActiveHelper

java.lang.Object
    extended by org.omg.PortableServer.POAPackage.ObjectNotActiveHelper
public abstract class ObjectNotActiveHelper
extends Object

org/omg/PortableServer/POAPackage/ObjectNotActiveHelper.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableServer/poa.idl Thursday, June 12, 2003 9:59:11 PM GMT-08:00

Constructor Summary
ObjectNotActiveHelper()
Method Summary
static ObjectNotActive | extract(Any a)
static String | id()
static void | insert(Any a, ObjectNotActive that)
static ObjectNotActive | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, ObjectNotActive value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ObjectNotActiveHelper

public ObjectNotActiveHelper()
Method Detail

insert

public static void insert(Any a,
                          ObjectNotActive that)

extract

public static ObjectNotActive extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static ObjectNotActive read(InputStream istream)

write

public static void write(OutputStream ostream,
                         ObjectNotActive value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


org.omg.PortableServer.POAPackage (Java 2 Platform SE v1.4.2)

 org.omg.PortableServer.POAPackage
Classes
AdapterAlreadyExistsHelper
AdapterNonExistentHelper
InvalidPolicyHelper
NoServantHelper
ObjectAlreadyActiveHelper
ObjectNotActiveHelper
ServantAlreadyActiveHelper
ServantNotActiveHelper
WrongAdapterHelper
WrongPolicyHelper
Exceptions
AdapterAlreadyExists
AdapterNonExistent
InvalidPolicy
NoServant
ObjectAlreadyActive
ObjectNotActive
ServantAlreadyActive
ServantNotActive
WrongAdapter
WrongPolicy


org.omg.PortableServer.POAPackage (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package org.omg.PortableServer.POAPackage

Allows programmers to construct object implementations that are portable between different ORB products.

See:
Description

Class Summary
AdapterAlreadyExistsHelper | org/omg/PortableServer/POAPackage/AdapterAlreadyExistsHelper.java .
AdapterNonExistentHelper | org/omg/PortableServer/POAPackage/AdapterNonExistentHelper.java .
InvalidPolicyHelper | org/omg/PortableServer/POAPackage/InvalidPolicyHelper.java .
NoServantHelper | org/omg/PortableServer/POAPackage/NoServantHelper.java .
ObjectAlreadyActiveHelper | org/omg/PortableServer/POAPackage/ObjectAlreadyActiveHelper.java .
ObjectNotActiveHelper | org/omg/PortableServer/POAPackage/ObjectNotActiveHelper.java .
ServantAlreadyActiveHelper | org/omg/PortableServer/POAPackage/ServantAlreadyActiveHelper.java .
ServantNotActiveHelper | org/omg/PortableServer/POAPackage/ServantNotActiveHelper.java .
WrongAdapterHelper | org/omg/PortableServer/POAPackage/WrongAdapterHelper.java .
WrongPolicyHelper | org/omg/PortableServer/POAPackage/WrongPolicyHelper.java .

Exception Summary
AdapterAlreadyExists | org/omg/PortableServer/POAPackage/AdapterAlreadyExists.java .
AdapterNonExistent | org/omg/PortableServer/POAPackage/AdapterNonExistent.java .
InvalidPolicy | org/omg/PortableServer/POAPackage/InvalidPolicy.java .
NoServant | org/omg/PortableServer/POAPackage/NoServant.java .
ObjectAlreadyActive | org/omg/PortableServer/POAPackage/ObjectAlreadyActive.java .
ObjectNotActive | org/omg/PortableServer/POAPackage/ObjectNotActive.java .
ServantAlreadyActive | org/omg/PortableServer/POAPackage/ServantAlreadyActive.java .
ServantNotActive | org/omg/PortableServer/POAPackage/ServantNotActive.java .
WrongAdapter | org/omg/PortableServer/POAPackage/WrongAdapter.java .
WrongPolicy | org/omg/PortableServer/POAPackage/WrongPolicy.java .

Package org.omg.PortableServer.POAPackage Description

Allows programmers to construct object implementations that are portable between different ORB products.

The Portable Object Adaptor (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.

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.

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.

All Mapping corresponds to the Chapter 11 of CORBA V2.3.1 specified by OMG document formal/99-10-07.pdf. The exception to this is the id attribute, which is added in ptc/00-08-06, section 11.3.8.26.

Package Specification

For a precise list of supported sections of official specifications with which the Java 2 Platform, Standard Edition, v.1.4 ORB complies, see Official Specifications for CORBA support in J2SE 1.4.

Since:
1.4
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


org.omg.PortableServer.POAPackage Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package org.omg.PortableServer.POAPackage

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class org.omg.PortableServer.POAPackage.AdapterAlreadyExistsHelper
    • class org.omg.PortableServer.POAPackage.AdapterNonExistentHelper
    • class org.omg.PortableServer.POAPackage.InvalidPolicyHelper
    • class org.omg.PortableServer.POAPackage.NoServantHelper
    • class org.omg.PortableServer.POAPackage.ObjectAlreadyActiveHelper
    • class org.omg.PortableServer.POAPackage.ObjectNotActiveHelper
    • class org.omg.PortableServer.POAPackage.ServantAlreadyActiveHelper
    • class org.omg.PortableServer.POAPackage.ServantNotActiveHelper
    • class java.lang.Throwable (implements java.io.Serializable)
      • class java.lang.Exception
        • class org.omg.CORBA.UserException (implements org.omg.CORBA.portable.IDLEntity)
          • class org.omg.PortableServer.POAPackage.AdapterAlreadyExists
          • class org.omg.PortableServer.POAPackage.AdapterNonExistent
          • class org.omg.PortableServer.POAPackage.InvalidPolicy
          • class org.omg.PortableServer.POAPackage.NoServant
          • class org.omg.PortableServer.POAPackage.ObjectAlreadyActive
          • class org.omg.PortableServer.POAPackage.ObjectNotActive
          • class org.omg.PortableServer.POAPackage.ServantAlreadyActive
          • class org.omg.PortableServer.POAPackage.ServantNotActive
          • class org.omg.PortableServer.POAPackage.WrongAdapter
          • class org.omg.PortableServer.POAPackage.WrongPolicy
    • class org.omg.PortableServer.POAPackage.WrongAdapterHelper
    • class org.omg.PortableServer.POAPackage.WrongPolicyHelper
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package org.omg.PortableServer.POAPackage (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
org.omg.PortableServer.POAPackage

Packages that use org.omg.PortableServer.POAPackage
org.omg.PortableServer | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.
org.omg.PortableServer.POAPackage | Allows programmers to construct object implementations that are portable between different ORB products.

Classes in org.omg.PortableServer.POAPackage used by org.omg.PortableServer
AdapterAlreadyExists
org/omg/PortableServer/POAPackage/AdapterAlreadyExists.java .
AdapterNonExistent
org/omg/PortableServer/POAPackage/AdapterNonExistent.java .
InvalidPolicy
org/omg/PortableServer/POAPackage/InvalidPolicy.java .
NoServant
org/omg/PortableServer/POAPackage/NoServant.java .
ObjectAlreadyActive
org/omg/PortableServer/POAPackage/ObjectAlreadyActive.java .
ObjectNotActive
org/omg/PortableServer/POAPackage/ObjectNotActive.java .
ServantAlreadyActive
org/omg/PortableServer/POAPackage/ServantAlreadyActive.java .
ServantNotActive
org/omg/PortableServer/POAPackage/ServantNotActive.java .
WrongAdapter
org/omg/PortableServer/POAPackage/WrongAdapter.java .
WrongPolicy
org/omg/PortableServer/POAPackage/WrongPolicy.java .

Classes in org.omg.PortableServer.POAPackage used by org.omg.PortableServer.POAPackage
AdapterAlreadyExists
org/omg/PortableServer/POAPackage/AdapterAlreadyExists.java .
AdapterNonExistent
org/omg/PortableServer/POAPackage/AdapterNonExistent.java .
InvalidPolicy
org/omg/PortableServer/POAPackage/InvalidPolicy.java .
NoServant
org/omg/PortableServer/POAPackage/NoServant.java .
ObjectAlreadyActive
org/omg/PortableServer/POAPackage/ObjectAlreadyActive.java .
ObjectNotActive
org/omg/PortableServer/POAPackage/ObjectNotActive.java .
ServantAlreadyActive
org/omg/PortableServer/POAPackage/ServantAlreadyActive.java .
ServantNotActive
org/omg/PortableServer/POAPackage/ServantNotActive.java .
WrongAdapter
org/omg/PortableServer/POAPackage/WrongAdapter.java .
WrongPolicy
org/omg/PortableServer/POAPackage/WrongPolicy.java .

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


ServantAlreadyActive (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer.POAPackage
Class ServantAlreadyActive

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.PortableServer.POAPackage.ServantAlreadyActive
All Implemented Interfaces:
IDLEntity, Serializable
public final class ServantAlreadyActive
extends UserException

org/omg/PortableServer/POAPackage/ServantAlreadyActive.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableServer/poa.idl Thursday, June 12, 2003 9:59:11 PM GMT-08:00

Constructor Summary
ServantAlreadyActive()
ServantAlreadyActive(String $reason)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

ServantAlreadyActive

public ServantAlreadyActive()

ServantAlreadyActive

public ServantAlreadyActive(String $reason)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ServantAlreadyActiveHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer.POAPackage
Class ServantAlreadyActiveHelper

java.lang.Object
    extended by org.omg.PortableServer.POAPackage.ServantAlreadyActiveHelper
public abstract class ServantAlreadyActiveHelper
extends Object

org/omg/PortableServer/POAPackage/ServantAlreadyActiveHelper.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableServer/poa.idl Thursday, June 12, 2003 9:59:11 PM GMT-08:00

Constructor Summary
ServantAlreadyActiveHelper()
Method Summary
static ServantAlreadyActive | extract(Any a)
static String | id()
static void | insert(Any a, ServantAlreadyActive that)
static ServantAlreadyActive | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, ServantAlreadyActive value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ServantAlreadyActiveHelper

public ServantAlreadyActiveHelper()
Method Detail

insert

public static void insert(Any a,
                          ServantAlreadyActive that)

extract

public static ServantAlreadyActive extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static ServantAlreadyActive read(InputStream istream)

write

public static void write(OutputStream ostream,
                         ServantAlreadyActive value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ServantNotActive (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer.POAPackage
Class ServantNotActive

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.PortableServer.POAPackage.ServantNotActive
All Implemented Interfaces:
IDLEntity, Serializable
public final class ServantNotActive
extends UserException

org/omg/PortableServer/POAPackage/ServantNotActive.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableServer/poa.idl Thursday, June 12, 2003 9:59:11 PM GMT-08:00

Constructor Summary
ServantNotActive()
ServantNotActive(String $reason)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

ServantNotActive

public ServantNotActive()

ServantNotActive

public ServantNotActive(String $reason)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ServantNotActiveHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer.POAPackage
Class ServantNotActiveHelper

java.lang.Object
    extended by org.omg.PortableServer.POAPackage.ServantNotActiveHelper
public abstract class ServantNotActiveHelper
extends Object

org/omg/PortableServer/POAPackage/ServantNotActiveHelper.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableServer/poa.idl Thursday, June 12, 2003 9:59:11 PM GMT-08:00

Constructor Summary
ServantNotActiveHelper()
Method Summary
static ServantNotActive | extract(Any a)
static String | id()
static void | insert(Any a, ServantNotActive that)
static ServantNotActive | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, ServantNotActive value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ServantNotActiveHelper

public ServantNotActiveHelper()
Method Detail

insert

public static void insert(Any a,
                          ServantNotActive that)

extract

public static ServantNotActive extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static ServantNotActive read(InputStream istream)

write

public static void write(OutputStream ostream,
                         ServantNotActive value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


WrongAdapter (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer.POAPackage
Class WrongAdapter

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.PortableServer.POAPackage.WrongAdapter
All Implemented Interfaces:
IDLEntity, Serializable
public final class WrongAdapter
extends UserException

org/omg/PortableServer/POAPackage/WrongAdapter.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableServer/poa.idl Thursday, June 12, 2003 9:59:11 PM GMT-08:00

Constructor Summary
WrongAdapter()
WrongAdapter(String $reason)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

WrongAdapter

public WrongAdapter()

WrongAdapter

public WrongAdapter(String $reason)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


WrongAdapterHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer.POAPackage
Class WrongAdapterHelper

java.lang.Object
    extended by org.omg.PortableServer.POAPackage.WrongAdapterHelper
public abstract class WrongAdapterHelper
extends Object

org/omg/PortableServer/POAPackage/WrongAdapterHelper.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableServer/poa.idl Thursday, June 12, 2003 9:59:11 PM GMT-08:00

Constructor Summary
WrongAdapterHelper()
Method Summary
static WrongAdapter | extract(Any a)
static String | id()
static void | insert(Any a, WrongAdapter that)
static WrongAdapter | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, WrongAdapter value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

WrongAdapterHelper

public WrongAdapterHelper()
Method Detail

insert

public static void insert(Any a,
                          WrongAdapter that)

extract

public static WrongAdapter extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static WrongAdapter read(InputStream istream)

write

public static void write(OutputStream ostream,
                         WrongAdapter value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


WrongPolicy (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer.POAPackage
Class WrongPolicy

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.omg.CORBA.UserException
                extended by org.omg.PortableServer.POAPackage.WrongPolicy
All Implemented Interfaces:
IDLEntity, Serializable
public final class WrongPolicy
extends UserException

org/omg/PortableServer/POAPackage/WrongPolicy.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableServer/poa.idl Thursday, June 12, 2003 9:59:11 PM GMT-08:00

Constructor Summary
WrongPolicy()
WrongPolicy(String $reason)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

WrongPolicy

public WrongPolicy()

WrongPolicy

public WrongPolicy(String $reason)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


WrongPolicyHelper (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer.POAPackage
Class WrongPolicyHelper

java.lang.Object
    extended by org.omg.PortableServer.POAPackage.WrongPolicyHelper
public abstract class WrongPolicyHelper
extends Object

org/omg/PortableServer/POAPackage/WrongPolicyHelper.java . Generated by the IDL-to-Java compiler (portable), version "3.1" from ../../../../src/share/classes/org/omg/PortableServer/poa.idl Thursday, June 12, 2003 9:59:11 PM GMT-08:00

Constructor Summary
WrongPolicyHelper()
Method Summary
static WrongPolicy | extract(Any a)
static String | id()
static void | insert(Any a, WrongPolicy that)
static WrongPolicy | read(InputStream istream)
static TypeCode | type()
static void | write(OutputStream ostream, WrongPolicy value)
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

WrongPolicyHelper

public WrongPolicyHelper()
Method Detail

insert

public static void insert(Any a,
                          WrongPolicy that)

extract

public static WrongPolicy extract(Any a)

type

public static TypeCode type()

id

public static String id()

read

public static WrongPolicy read(InputStream istream)

write

public static void write(OutputStream ostream,
                         WrongPolicy value)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Uses of Class org.omg.PortableServer.POAPackage.AdapterAlreadyExists (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.POAPackage.AdapterAlreadyExists

Packages that use AdapterAlreadyExists
org.omg.PortableServer | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.
org.omg.PortableServer.POAPackage | Allows programmers to construct object implementations that are portable between different ORB products.

Uses of AdapterAlreadyExists in org.omg.PortableServer

Methods in org.omg.PortableServer that throw AdapterAlreadyExists
 POA POAOperations.create_POA(String adapter_name, POAManager a_POAManager, Policy[] policies)
This operation creates a new POA as a child of the target POA.

Uses of AdapterAlreadyExists in org.omg.PortableServer.POAPackage

Methods in org.omg.PortableServer.POAPackage that return AdapterAlreadyExists
static AdapterAlreadyExists | AdapterAlreadyExistsHelper.extract(Any a)
static AdapterAlreadyExists | AdapterAlreadyExistsHelper.read(InputStream istream)

Methods in org.omg.PortableServer.POAPackage with parameters of type AdapterAlreadyExists
static void | AdapterAlreadyExistsHelper.insert(Any a, AdapterAlreadyExists that)
static void | AdapterAlreadyExistsHelper.write(OutputStream ostream, AdapterAlreadyExists value)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.POAPackage.AdapterAlreadyExistsHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.POAPackage.AdapterAlreadyExistsHelper

No usage of org.omg.PortableServer.POAPackage.AdapterAlreadyExistsHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.POAPackage.AdapterNonExistent (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.POAPackage.AdapterNonExistent

Packages that use AdapterNonExistent
org.omg.PortableServer | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.
org.omg.PortableServer.POAPackage | Allows programmers to construct object implementations that are portable between different ORB products.

Uses of AdapterNonExistent in org.omg.PortableServer

Methods in org.omg.PortableServer that throw AdapterNonExistent
 POA POAOperations.find_POA(String adapter_name, boolean activate_it)
If the target POA is the parent of a child POA with the specified name (relative to the target POA), that child POA is returned.

Uses of AdapterNonExistent in org.omg.PortableServer.POAPackage

Methods in org.omg.PortableServer.POAPackage that return AdapterNonExistent
static AdapterNonExistent | AdapterNonExistentHelper.extract(Any a)
static AdapterNonExistent | AdapterNonExistentHelper.read(InputStream istream)

Methods in org.omg.PortableServer.POAPackage with parameters of type AdapterNonExistent
static void | AdapterNonExistentHelper.insert(Any a, AdapterNonExistent that)
static void | AdapterNonExistentHelper.write(OutputStream ostream, AdapterNonExistent value)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.POAPackage.AdapterNonExistentHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.POAPackage.AdapterNonExistentHelper

No usage of org.omg.PortableServer.POAPackage.AdapterNonExistentHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.POAPackage.InvalidPolicy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.POAPackage.InvalidPolicy

Packages that use InvalidPolicy
org.omg.PortableServer | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.
org.omg.PortableServer.POAPackage | Allows programmers to construct object implementations that are portable between different ORB products.

Uses of InvalidPolicy in org.omg.PortableServer

Methods in org.omg.PortableServer that throw InvalidPolicy
 POA POAOperations.create_POA(String adapter_name, POAManager a_POAManager, Policy[] policies)
This operation creates a new POA as a child of the target POA.

Uses of InvalidPolicy in org.omg.PortableServer.POAPackage

Methods in org.omg.PortableServer.POAPackage that return InvalidPolicy
static InvalidPolicy | InvalidPolicyHelper.extract(Any a)
static InvalidPolicy | InvalidPolicyHelper.read(InputStream istream)

Methods in org.omg.PortableServer.POAPackage with parameters of type InvalidPolicy
static void | InvalidPolicyHelper.insert(Any a, InvalidPolicy that)
static void | InvalidPolicyHelper.write(OutputStream ostream, InvalidPolicy value)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.POAPackage.InvalidPolicyHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.POAPackage.InvalidPolicyHelper

No usage of org.omg.PortableServer.POAPackage.InvalidPolicyHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.POAPackage.NoServant (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.POAPackage.NoServant

Packages that use NoServant
org.omg.PortableServer | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.
org.omg.PortableServer.POAPackage | Allows programmers to construct object implementations that are portable between different ORB products.

Uses of NoServant in org.omg.PortableServer

Methods in org.omg.PortableServer that throw NoServant
 Servant POAOperations.get_servant()
This operation returns the default servant associated with the POA.

Uses of NoServant in org.omg.PortableServer.POAPackage

Methods in org.omg.PortableServer.POAPackage that return NoServant
static NoServant | NoServantHelper.extract(Any a)
static NoServant | NoServantHelper.read(InputStream istream)

Methods in org.omg.PortableServer.POAPackage with parameters of type NoServant
static void | NoServantHelper.insert(Any a, NoServant that)
static void | NoServantHelper.write(OutputStream ostream, NoServant value)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.POAPackage.NoServantHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.POAPackage.NoServantHelper

No usage of org.omg.PortableServer.POAPackage.NoServantHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.POAPackage.ObjectAlreadyActive (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.POAPackage.ObjectAlreadyActive

Packages that use ObjectAlreadyActive
org.omg.PortableServer | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.
org.omg.PortableServer.POAPackage | Allows programmers to construct object implementations that are portable between different ORB products.

Uses of ObjectAlreadyActive in org.omg.PortableServer

Methods in org.omg.PortableServer that throw ObjectAlreadyActive
 void POAOperations.activate_object_with_id(byte[] id, Servant p_servant)
This operation enters an association between the specified Object Id and the specified servant in the Active Object Map.

Uses of ObjectAlreadyActive in org.omg.PortableServer.POAPackage

Methods in org.omg.PortableServer.POAPackage that return ObjectAlreadyActive
static ObjectAlreadyActive | ObjectAlreadyActiveHelper.extract(Any a)
static ObjectAlreadyActive | ObjectAlreadyActiveHelper.read(InputStream istream)

Methods in org.omg.PortableServer.POAPackage with parameters of type ObjectAlreadyActive
static void | ObjectAlreadyActiveHelper.insert(Any a, ObjectAlreadyActive that)
static void | ObjectAlreadyActiveHelper.write(OutputStream ostream, ObjectAlreadyActive value)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.POAPackage.ObjectAlreadyActiveHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.POAPackage.ObjectAlreadyActiveHelper

No usage of org.omg.PortableServer.POAPackage.ObjectAlreadyActiveHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.POAPackage.ObjectNotActive (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.POAPackage.ObjectNotActive

Packages that use ObjectNotActive
org.omg.PortableServer | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.
org.omg.PortableServer.POAPackage | Allows programmers to construct object implementations that are portable between different ORB products.

Uses of ObjectNotActive in org.omg.PortableServer

Methods in org.omg.PortableServer that throw ObjectNotActive
void | POAOperations.deactivate_object(byte[] oid) This operation causes the ObjectId specified in the oid parameter to be deactivated.
Servant | POAOperations.reference_to_servant(Object reference) 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.
Servant | POAOperations.id_to_servant(byte[] oid) If the POA has the RETAIN policy and the specified ObjectId is in the Active Object Map, this operation returns the servant associated with that object in the Active Object Map.
Object | POAOperations.id_to_reference(byte[] oid) If an object with the specified Object Id value is currently active, a reference encapsulating the information used to activate the object is returned.

Uses of ObjectNotActive in org.omg.PortableServer.POAPackage

Methods in org.omg.PortableServer.POAPackage that return ObjectNotActive
static ObjectNotActive | ObjectNotActiveHelper.extract(Any a)
static ObjectNotActive | ObjectNotActiveHelper.read(InputStream istream)

Methods in org.omg.PortableServer.POAPackage with parameters of type ObjectNotActive
static void | ObjectNotActiveHelper.insert(Any a, ObjectNotActive that)
static void | ObjectNotActiveHelper.write(OutputStream ostream, ObjectNotActive value)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.POAPackage.ObjectNotActiveHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.POAPackage.ObjectNotActiveHelper

No usage of org.omg.PortableServer.POAPackage.ObjectNotActiveHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.POAPackage.ServantAlreadyActive (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.POAPackage.ServantAlreadyActive

Packages that use ServantAlreadyActive
org.omg.PortableServer | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.
org.omg.PortableServer.POAPackage | Allows programmers to construct object implementations that are portable between different ORB products.

Uses of ServantAlreadyActive in org.omg.PortableServer

Methods in org.omg.PortableServer that throw ServantAlreadyActive
byte[] | POAOperations.activate_object(Servant p_servant) This operation generates an Object Id and enters the Object Id and the specified servant in the Active Object Map.
void | POAOperations.activate_object_with_id(byte[] id, Servant p_servant) This operation enters an association between the specified Object Id and the specified servant in the Active Object Map.

Uses of ServantAlreadyActive in org.omg.PortableServer.POAPackage

Methods in org.omg.PortableServer.POAPackage that return ServantAlreadyActive
static ServantAlreadyActive | ServantAlreadyActiveHelper.extract(Any a)
static ServantAlreadyActive | ServantAlreadyActiveHelper.read(InputStream istream)

Methods in org.omg.PortableServer.POAPackage with parameters of type ServantAlreadyActive
static void | ServantAlreadyActiveHelper.insert(Any a, ServantAlreadyActive that)
static void | ServantAlreadyActiveHelper.write(OutputStream ostream, ServantAlreadyActive value)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.POAPackage.ServantAlreadyActiveHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.POAPackage.ServantAlreadyActiveHelper

No usage of org.omg.PortableServer.POAPackage.ServantAlreadyActiveHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.POAPackage.ServantNotActive (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.POAPackage.ServantNotActive

Packages that use ServantNotActive
org.omg.PortableServer | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.
org.omg.PortableServer.POAPackage | Allows programmers to construct object implementations that are portable between different ORB products.

Uses of ServantNotActive in org.omg.PortableServer

Methods in org.omg.PortableServer that throw ServantNotActive
byte[] | POAOperations.servant_to_id(Servant p_servant) This operation has four possible behaviors.
Object | POAOperations.servant_to_reference(Servant p_servant) 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.

Uses of ServantNotActive in org.omg.PortableServer.POAPackage

Methods in org.omg.PortableServer.POAPackage that return ServantNotActive
static ServantNotActive | ServantNotActiveHelper.extract(Any a)
static ServantNotActive | ServantNotActiveHelper.read(InputStream istream)

Methods in org.omg.PortableServer.POAPackage with parameters of type ServantNotActive
static void | ServantNotActiveHelper.insert(Any a, ServantNotActive that)
static void | ServantNotActiveHelper.write(OutputStream ostream, ServantNotActive value)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.POAPackage.ServantNotActiveHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.POAPackage.ServantNotActiveHelper

No usage of org.omg.PortableServer.POAPackage.ServantNotActiveHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.POAPackage.WrongAdapter (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.POAPackage.WrongAdapter

Packages that use WrongAdapter
org.omg.PortableServer | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.
org.omg.PortableServer.POAPackage | Allows programmers to construct object implementations that are portable between different ORB products.

Uses of WrongAdapter in org.omg.PortableServer

Methods in org.omg.PortableServer that throw WrongAdapter
Servant | POAOperations.reference_to_servant(Object reference) 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.
byte[] | POAOperations.reference_to_id(Object reference) This operation returns the Object Id value encapsulated by the specified reference.

Uses of WrongAdapter in org.omg.PortableServer.POAPackage

Methods in org.omg.PortableServer.POAPackage that return WrongAdapter
static WrongAdapter | WrongAdapterHelper.extract(Any a)
static WrongAdapter | WrongAdapterHelper.read(InputStream istream)

Methods in org.omg.PortableServer.POAPackage with parameters of type WrongAdapter
static void | WrongAdapterHelper.insert(Any a, WrongAdapter that)
static void | WrongAdapterHelper.write(OutputStream ostream, WrongAdapter value)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.POAPackage.WrongAdapterHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.POAPackage.WrongAdapterHelper

No usage of org.omg.PortableServer.POAPackage.WrongAdapterHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.POAPackage.WrongPolicy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.POAPackage.WrongPolicy

Packages that use WrongPolicy
org.omg.PortableServer | Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.
org.omg.PortableServer.POAPackage | Allows programmers to construct object implementations that are portable between different ORB products.

Uses of WrongPolicy in org.omg.PortableServer

Methods in org.omg.PortableServer that throw WrongPolicy
ServantManager | POAOperations.get_servant_manager() If the ServantRetentionPolicy of the POA is RETAIN, then the ServantManager argument (imgr) shall support the ServantActivator interface.
void | POAOperations.set_servant_manager(ServantManager imgr) This operation sets the default servant manager associated with the POA.
Servant | POAOperations.get_servant() This operation returns the default servant associated with the POA.
void | POAOperations.set_servant(Servant p_servant) This operation registers the specified servant with the POA as the default servant.
byte[] | POAOperations.activate_object(Servant p_servant) This operation generates an Object Id and enters the Object Id and the specified servant in the Active Object Map.
void | POAOperations.activate_object_with_id(byte[] id, Servant p_servant) This operation enters an association between the specified Object Id and the specified servant in the Active Object Map.
void | POAOperations.deactivate_object(byte[] oid) This operation causes the ObjectId specified in the oid parameter to be deactivated.
Object | POAOperations.create_reference(String intf) This operation creates an object reference that encapsulates a POA-generated Object Id value and the specified interface repository id.
byte[] | POAOperations.servant_to_id(Servant p_servant) This operation has four possible behaviors.
Object | POAOperations.servant_to_reference(Servant p_servant) 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.
Servant | POAOperations.reference_to_servant(Object reference) 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.
byte[] | POAOperations.reference_to_id(Object reference) This operation returns the Object Id value encapsulated by the specified reference.
Servant | POAOperations.id_to_servant(byte[] oid) If the POA has the RETAIN policy and the specified ObjectId is in the Active Object Map, this operation returns the servant associated with that object in the Active Object Map.
Object | POAOperations.id_to_reference(byte[] oid) If an object with the specified Object Id value is currently active, a reference encapsulating the information used to activate the object is returned.

Uses of WrongPolicy in org.omg.PortableServer.POAPackage

Methods in org.omg.PortableServer.POAPackage that return WrongPolicy
static WrongPolicy | WrongPolicyHelper.extract(Any a)
static WrongPolicy | WrongPolicyHelper.read(InputStream istream)

Methods in org.omg.PortableServer.POAPackage with parameters of type WrongPolicy
static void | WrongPolicyHelper.insert(Any a, WrongPolicy that)
static void | WrongPolicyHelper.write(OutputStream ostream, WrongPolicy value)

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.POAPackage.WrongPolicyHelper (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.POAPackage.WrongPolicyHelper

No usage of org.omg.PortableServer.POAPackage.WrongPolicyHelper

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Delegate (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer.portable
Interface Delegate

public interface Delegate

The portability package contains interfaces and classes that are designed for and intended to be used by ORB implementor. It exposes the publicly defined APIs that are used to connect stubs and skeletons to the ORB. The Delegate interface provides the ORB vendor specific implementation of PortableServer::Servant. Conformant to spec CORBA V2.3.1, ptc/00-01-08.pdf

Method Summary
 POA default_POA(Servant Self)
The default behavior of this function is to return the root POA from the ORB instance associated with the servant.
 Object get_interface_def(Servant self)
This operation returns an object in the Interface Repository which provides type information that may be useful to a program.
 boolean is_a(Servant Self, String Repository_Id)
This method checks to see if the specified repid is present on the list returned by _all_interfaces() or is the repository id for the generic CORBA Object.
 boolean non_existent(Servant Self)
This operation is used to check for the existence of the Object.
 byte[] object_id(Servant Self)
The method _object_id() is equivalent to calling PortableServer::Current::get_object_id.
 ORB orb(Servant Self)
Convenience method that returns the instance of the ORB currently associated with the Servant.
 POA poa(Servant Self)
The method _poa() is equivalent to calling PortableServer::Current:get_POA.
 Object this_object(Servant Self)
This allows the servant to obtain the object reference for the target CORBA Object it is incarnating for that request.

Method Detail

orb

public ORB orb(Servant Self)
Convenience method that returns the instance of the ORB currently associated with the Servant.

Parameters:
Self - the servant.
Returns:
ORB associated with the Servant.

this_object

public Object this_object(Servant Self)
This allows the servant to obtain the object reference for the target CORBA Object it is incarnating for that request.

Parameters:
Self - the servant.
Returns:
Object reference associated with the request.

poa

public POA poa(Servant Self)
The method _poa() is equivalent to calling PortableServer::Current:get_POA.

Parameters:
Self - the servant.
Returns:
POA associated with the servant.

object_id

public byte[] object_id(Servant Self)
The method _object_id() is equivalent to calling PortableServer::Current::get_object_id.

Parameters:
Self - the servant.
Returns:
ObjectId associated with this servant.

default_POA

public POA default_POA(Servant Self)
The default behavior of this function is to return the root POA from the ORB instance associated with the servant.

Parameters:
Self - the servant.
Returns:
POA associated with the servant class.

is_a

public boolean is_a(Servant Self,
                    String Repository_Id)
This method checks to see if the specified repid is present on the list returned by _all_interfaces() or is the repository id for the generic CORBA Object.

Parameters:
Self - the servant.
Repository_Id - the repository_id to be checked in the repository list or against the id of generic CORBA object.
Returns:
boolean indicating whether the specified repid is in the list or is same as that got generic CORBA object.

non_existent

public boolean non_existent(Servant Self)
This operation is used to check for the existence of the Object.

Parameters:
Self - the servant.
Returns:
boolean true to indicate that object does not exist, and false otherwise.

get_interface_def

public Object get_interface_def(Servant self)
This operation returns an object in the Interface Repository which provides type information that may be useful to a program.

Parameters:
self - the servant.
Returns:
type information corresponding to the object.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


org.omg.PortableServer.portable (Java 2 Platform SE v1.4.2)

 org.omg.PortableServer.portable
Interfaces
Delegate


org.omg.PortableServer.portable (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package org.omg.PortableServer.portable

Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

See:
Description

Interface Summary
Delegate The portability package contains interfaces and classes that are designed for and intended to be used by ORB implementor.

Package org.omg.PortableServer.portable Description

Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

The portable package contains interfaces and classes that are designed for and intended to be used by an ORB implementor. It exposes the publicly defined APIs that are used to connect stubs and skeletons to the ORB. The Delegate interface provides the ORB-vendor-specific implementation of PortableServer::Servant. This package conforms CORBA Specification V2.3.1, ptc/00-01-08.

Since:
1.4
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


org.omg.PortableServer.portable Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package org.omg.PortableServer.portable

Package Hierarchies:
All Packages

Interface Hierarchy

  • interface org.omg.PortableServer.portable.Delegate
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package org.omg.PortableServer.portable (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
org.omg.PortableServer.portable

Packages that use org.omg.PortableServer.portable
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Classes in org.omg.PortableServer.portable used by org.omg.PortableServer
Delegate
The portability package contains interfaces and classes that are designed for and intended to be used by ORB implementor.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.PortableServer.portable.Delegate (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.PortableServer.portable.Delegate

Packages that use Delegate
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of Delegate in org.omg.PortableServer

Methods in org.omg.PortableServer that return Delegate
 Delegate Servant._get_delegate()
Gets the ORB vendor-specific implementation of PortableServer::Servant.

Methods in org.omg.PortableServer with parameters of type Delegate
 void Servant._set_delegate(Delegate delegate)
Supports the Java ORB portability interfaces by providing a method for classes that support ORB portability through delegation to set their delegate.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


CookieHolder (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.PortableServer.ServantLocatorPackage
Class CookieHolder

java.lang.Object
    extended by org.omg.PortableServer.ServantLocatorPackage.CookieHolder
All Implemented Interfaces:
Streamable
public final class CookieHolder
extends Object
implements Streamable

The native type PortableServer::ServantLocator::Cookie is mapped to java.lang.Object. A CookieHolder class is provided for passing the Cookie type as an out parameter. The CookieHolder class follows exactly the same pattern as the other holder classes for basic types.

Field Summary
 Object value
Constructor Summary
CookieHolder()
CookieHolder(Object initial)
Method Summary
void | _read(InputStream is) Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.
TypeCode | _type() Retrieves the TypeCode object corresponding to the value in the value field of the Holder.
void | _write(OutputStream os) Marshals to ostream the value in the value field of the Holder.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

public Object value
Constructor Detail

CookieHolder

public CookieHolder()

CookieHolder

public CookieHolder(Object initial)
Method Detail

_read

public void _read(InputStream is)
Description copied from interface: Streamable
Reads data from istream and initalizes the value field of the Holder with the unmarshalled data.

Specified by:
_read in interface Streamable
Parameters:
is - the InputStream that represents the CDR data from the wire.

_write

public void _write(OutputStream os)
Description copied from interface: Streamable
Marshals to ostream the value in the value field of the Holder.

Specified by:
_write in interface Streamable
Parameters:
os - the CDR OutputStream

_type

public TypeCode _type()
Description copied from interface: Streamable
Retrieves the TypeCode object corresponding to the value in the value field of the Holder.

Specified by:
_type in interface Streamable
Returns:
the TypeCode object for the value held in the holder
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


org.omg.PortableServer.ServantLocatorPackage (Java 2 Platform SE v1.4.2)

 org.omg.PortableServer.ServantLocatorPackage
Classes
CookieHolder


org.omg.PortableServer.ServantLocatorPackage (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package org.omg.PortableServer.ServantLocatorPackage

Provides classes and interfaces for locating the servant.

See:
Description

Class Summary
CookieHolder The native type PortableServer::ServantLocator::Cookie is mapped to java.lang.Object.

Package org.omg.PortableServer.ServantLocatorPackage Description

Provides classes and interfaces for locating the servant.

This package supplies a CookieHolder class for passing the Cookie type as an out parameter. The CookieHolder class follows exactly the same pattern as the other holder classes for basic types.

Package Specification

For a precise list of supported sections of official OMG specifications with which the Java 2 Platform, Standard Edition, v.1.4 complies, see Official Specifications for CORBA support in J2SE 1.4.

Since:
1.4
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


org.omg.PortableServer.ServantLocatorPackage Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package org.omg.PortableServer.ServantLocatorPackage

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class org.omg.PortableServer.ServantLocatorPackage.CookieHolder (implements org.omg.CORBA.portable.Streamable)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package org.omg.PortableServer.ServantLocatorPackage (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
org.omg.PortableServer.ServantLocatorPackage

Packages that use org.omg.PortableServer.ServantLocatorPackage
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Classes in org.omg.PortableServer.ServantLocatorPackage used by org.omg.PortableServer
CookieHolder
The native type PortableServer::ServantLocator::Cookie is mapped to java.lang.Object.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.PortableServer.ServantLocatorPackage.CookieHolder (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.PortableServer.ServantLocatorPackage.CookieHolder

Packages that use CookieHolder
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.

Uses of CookieHolder in org.omg.PortableServer

Methods in org.omg.PortableServer with parameters of type CookieHolder
Servant | _ServantLocatorStub.preinvoke(byte[] oid, POA adapter, String operation, CookieHolder the_cookie) This operations is used to get a servant that will be used to process the request that caused preinvoke to be called.
Servant | ServantLocatorOperations.preinvoke(byte[] oid, POA adapter, String operation, CookieHolder the_cookie) This operations is used to get a servant that will be used to process the request that caused preinvoke to be called.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


org.omg.SendingContext (Java 2 Platform SE v1.4.2)

 org.omg.SendingContext
Interfaces
RunTime
RunTimeOperations


org.omg.SendingContext (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package org.omg.SendingContext

Provides support for the marshalling of value types.

See:
Description

Interface Summary
RunTime | Defines the base class that represents the Sending Context of a request.
RunTimeOperations | Defines operations on the base class that represents the Sending Context of a request.

Package org.omg.SendingContext Description

Provides support for the marshalling of value types. Value type marshalling may require access to an implementation of the value type or to meta information about the value type. This information is passed between the sending context and the receiving context using a particular service context containing an instance of the SendingContext.RunTime interface.

A sending context may be either the client side or the server side of an invocation, depending on which contains a value type. The sending context is the client side of an invocation if the request contains a value type. It is the server side if the reply contains a value type. The other party in the communication is the receiving context.

The service context marshalled for SendingContext consists of an encapsulated IOR for the SendingContext.RunTime interface. RunTime is just a marker interface defined to allow extensibility in the future. There is currently only one subinterface of RunTime defined: the SendingContext.CodeBase interface. The interface CodeBase defines operations to obtain code URLs and meta-information about a value type received from the sending context.

Note that these classes are currently defined in the com.sun.org.omg.SendingContext package rather than in the package org.omg.SendingContext. This has been done to avoid including large parts of the interface repository in the JDK core, since the interface repository is still evolving in response to the needs of the CORBA Components work.

Package Specification

For a precise list of supported sections of official specifications with which the Java 2 Platform, Standard Edition, v.1.4 ORB complies, see Official Specifications for CORBA support in J2SE 1.4.

Since:
1.3
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


org.omg.SendingContext Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package org.omg.SendingContext

Package Hierarchies:
All Packages

Interface Hierarchy

  • interface org.omg.CORBA.Object
    • interface org.omg.SendingContext.RunTime (also extends org.omg.CORBA.portable.IDLEntity, org.omg.SendingContext.RunTimeOperations)
  • interface org.omg.SendingContext.RunTimeOperations
    • interface org.omg.SendingContext.RunTime (also extends org.omg.CORBA.portable.IDLEntity, org.omg.CORBA.Object)
  • interface java.io.Serializable
    • interface org.omg.CORBA.portable.IDLEntity
      • interface org.omg.SendingContext.RunTime (also extends org.omg.CORBA.Object, org.omg.SendingContext.RunTimeOperations)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package org.omg.SendingContext (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
org.omg.SendingContext

Packages that use org.omg.SendingContext
javax.rmi.CORBA | Contains portability APIs for RMI-IIOP.
org.omg.SendingContext | Provides support for the marshalling of value types.

Classes in org.omg.SendingContext used by javax.rmi.CORBA
RunTime
Defines the base class that represents the Sending Context of a request.

Classes in org.omg.SendingContext used by org.omg.SendingContext
RunTimeOperations
Defines operations on the base class that represents the Sending Context of a request.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


RunTime (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.SendingContext
Interface RunTime

All Superinterfaces:
IDLEntity, Object, RunTimeOperations, Serializable
public interface RunTime
extends RunTimeOperations, Object, IDLEntity

Defines the base class that represents the Sending Context of a request. The sending context provides access to information about the runtime environment of the originator of a GIOP message. For example, when a value type is marshalled on a GIOP Request message, the receiver of the value type may need to ask the sender about the CodeBase for the implementation of the value type.

Methods inherited from interface org.omg.CORBA.Object
_create_request, _create_request, _duplicate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _is_a, _is_equivalent, _non_existent, _release, _request, _set_policy_override

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


RunTimeOperations (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.SendingContext
Interface RunTimeOperations

All Known Subinterfaces:
RunTime
public interface RunTimeOperations

Defines operations on the base class that represents the Sending Context of a request. The sending context provides access to information about the runtime environment of the originator of a GIOP message. For example, when a value type is marshalled on a GIOP Request message, the receiver of the value type may need to ask the sender about the CodeBase for the implementation of the value type.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Uses of Interface org.omg.SendingContext.RunTime (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.SendingContext.RunTime

Packages that use RunTime
javax.rmi.CORBA Contains portability APIs for RMI-IIOP.

Uses of RunTime in javax.rmi.CORBA

Methods in javax.rmi.CORBA that return RunTime
 RunTime ValueHandler.getRunTimeCodeBase()
Returns the CodeBase for this ValueHandler.

Methods in javax.rmi.CORBA with parameters of type RunTime
 Serializable ValueHandler.readValue(InputStream in, int offset, Class clz, String repositoryID, RunTime sender)
Reads a value from the stream using Java semantics.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.omg.SendingContext.RunTimeOperations (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.omg.SendingContext.RunTimeOperations

Packages that use RunTimeOperations
org.omg.SendingContext Provides support for the marshalling of value types.

Uses of RunTimeOperations in org.omg.SendingContext

Subinterfaces of RunTimeOperations in org.omg.SendingContext
 interface RunTime
Defines the base class that represents the Sending Context of a request.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


_Remote_Stub (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.omg.stub.java.rmi
Class _Remote_Stub

java.lang.Object
    extended by org.omg.CORBA.portable.ObjectImpl
        extended by org.omg.CORBA_2_3.portable.ObjectImpl
            extended by javax.rmi.CORBA.Stub
                extended by org.omg.stub.java.rmi._Remote_Stub
All Implemented Interfaces:
Object, Remote, Serializable
public final class _Remote_Stub
extends Stub
implements Remote

This class provides the Stub for the Remote Type. The class is generated by the rmic compiler, and is still under works at OMG. It's contents are subject to change without notice as the specification evolves.

Constructor Summary
_Remote_Stub()
Method Summary
 String[] _ids()
Returns an array of repository ids that an object implements.
Methods inherited from class javax.rmi.CORBA.Stub
connect, equals, hashCode, toString
Methods inherited from class org.omg.CORBA_2_3.portable.ObjectImpl
_get_codebase
Methods inherited from class org.omg.CORBA.portable.ObjectImpl
_create_request, _create_request, _duplicate, _get_delegate, _get_domain_managers, _get_interface_def, _get_policy, _hash, _invoke, _is_a, _is_equivalent, _is_local, _non_existent, _orb, _release, _releaseReply, _request, _request, _servant_postinvoke, _servant_preinvoke, _set_delegate, _set_policy_override
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait

Constructor Detail

_Remote_Stub

public _Remote_Stub()
Method Detail

_ids

public String[] _ids()
Returns an array of repository ids that an object implements. The string at index zero represents the most derived interface. The last id, for the generic CORBA object is (i.e., IDL:omg.org/CORBA/Object:1.0") is implied and not present.

Specified by:
_ids in class ObjectImpl
Returns:
an array of repository ids that an object implements.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


org.omg.stub.java.rmi (Java 2 Platform SE v1.4.2)

 org.omg.stub.java.rmi
Classes
_Remote_Stub


org.omg.stub.java.rmi (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package org.omg.stub.java.rmi

Contains RMI-IIOP Stubs for the Remote types that occur in the java.rmi package.

See:
Description

Class Summary
_Remote_Stub This class provides the Stub for the Remote Type.

Package org.omg.stub.java.rmi Description

Contains RMI-IIOP Stubs for the Remote types that occur in the java.rmi package.

Since:
1.3
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


org.omg.stub.java.rmi Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package org.omg.stub.java.rmi

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class org.omg.CORBA.portable.ObjectImpl (implements org.omg.CORBA.Object)
      • class org.omg.CORBA_2_3.portable.ObjectImpl
        • class javax.rmi.CORBA.Stub (implements java.io.Serializable)
          • class org.omg.stub.java.rmi._Remote_Stub (implements java.rmi.Remote)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package org.omg.stub.java.rmi (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
org.omg.stub.java.rmi

No usage of org.omg.stub.java.rmi

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.omg.stub.java.rmi._Remote_Stub (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.omg.stub.java.rmi._Remote_Stub

No usage of org.omg.stub.java.rmi._Remote_Stub

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Attr (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom
Interface Attr

All Superinterfaces:
Node
public interface Attr
extends Node

The Attr interface represents an attribute in an Element object. Typically the allowable values for the attribute are defined in a document type definition.

Attr objects inherit the Node interface, but since they are not actually child nodes of the element they describe, the DOM does not consider them part of the document tree. Thus, the Node attributes parentNode, previousSibling, and nextSibling have a null value for Attr objects. The DOM takes the view that attributes are properties of elements rather than having a separate identity from the elements they are associated with; this should make it more efficient to implement such features as default attributes associated with all elements of a given type. Furthermore, Attr nodes may not be immediate children of a DocumentFragment. However, they can be associated with Element nodes contained within a DocumentFragment. In short, users and implementors of the DOM need to be aware that Attr nodes have some things in common with other objects inheriting the Node interface, but they also are quite distinct.

The attribute's effective value is determined as follows: if this attribute has been explicitly assigned any value, that value is the attribute's effective value; otherwise, if there is a declaration for this attribute, and that declaration includes a default value, then that default value is the attribute's effective value; otherwise, the attribute does not exist on this element in the structure model until it has been explicitly added. Note that the nodeValue attribute on the Attr instance can also be used to retrieve the string version of the attribute's value(s).

In XML, where the value of an attribute can contain entity references, the child nodes of the Attr node may be either Text or EntityReference nodes (when these are in use; see the description of EntityReference for discussion). Because the DOM Core is not aware of attribute types, it treats all attribute values as simple strings, even if the DTD or schema declares them as having tokenized types.

See also the Document Object Model (DOM) Level 2 Core Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getName() Returns the name of this attribute.
Element | getOwnerElement() The Element node this attribute is attached to or null if this attribute is not in use.
boolean | getSpecified() If this attribute was explicitly given a value in the original document, this is true; otherwise, it is false.
String | getValue() On retrieval, the value of the attribute is returned as a string.
void | setValue(String value) On retrieval, the value of the attribute is returned as a string.
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getName

public String getName()
Returns the name of this attribute.

getSpecified

public boolean getSpecified()
If this attribute was explicitly given a value in the original document, this is true; otherwise, it is false. Note that the implementation is in charge of this attribute, not the user. If the user changes the value of the attribute (even if it ends up having the same value as the default value) then the specified flag is automatically flipped to true. To re-specify the attribute as the default value from the DTD, the user must delete the attribute. The implementation will then make a new attribute available with specified set to false and the default value (if one exists).
In summary: If the attribute has an assigned value in the document then specified is true, and the value is the assigned value.If the attribute has no assigned value in the document and has a default value in the DTD, then specified is false, and the value is the default value in the DTD.If the attribute has no assigned value in the document and has a value of #IMPLIED in the DTD, then the attribute does not appear in the structure model of the document.If the ownerElement attribute is null (i.e. because it was just created or was set to null by the various removal and cloning operations) specified is true.

getValue

public String getValue()
On retrieval, the value of the attribute is returned as a string. Character and general entity references are replaced with their values. See also the method getAttribute on the Element interface.
On setting, this creates a Text node with the unparsed contents of the string. I.e. any characters that an XML processor would recognize as markup are instead treated as literal text. See also the method setAttribute on the Element interface.

Throws:
DOMException - NO_MODIFICATION_ALLOWED_ERR: Raised when the node is readonly.

setValue

public void setValue(String value)
              throws DOMException
On retrieval, the value of the attribute is returned as a string. Character and general entity references are replaced with their values. See also the method getAttribute on the Element interface.
On setting, this creates a Text node with the unparsed contents of the string. I.e. any characters that an XML processor would recognize as markup are instead treated as literal text. See also the method setAttribute on the Element interface.

Throws:
DOMException - NO_MODIFICATION_ALLOWED_ERR: Raised when the node is readonly.

getOwnerElement

public Element getOwnerElement()
The Element node this attribute is attached to or null if this attribute is not in use.

Since:
DOM Level 2
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


CDATASection (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom
Interface CDATASection

All Superinterfaces:
CharacterData, Node, Text
public interface CDATASection
extends Text

CDATA sections are used to escape blocks of text containing characters that would otherwise be regarded as markup. The only delimiter that is recognized in a CDATA section is the "]]>" string that ends the CDATA section. CDATA sections cannot be nested. Their primary purpose is for including material such as XML fragments, without needing to escape all the delimiters.

The DOMString attribute of the Text node holds the text that is contained by the CDATA section. Note that this may contain characters that need to be escaped outside of CDATA sections and that, depending on the character encoding ("charset") chosen for serialization, it may be impossible to write out some characters as part of a CDATA section.

The CDATASection interface inherits from the CharacterData interface through the Text interface. Adjacent CDATASection nodes are not merged by use of the normalize method of the Node interface. Because no markup is recognized within a CDATASection, character numeric references cannot be used as an escape mechanism when serializing. Therefore, action needs to be taken when serializing a CDATASection with a character encoding where some of the contained characters cannot be represented. Failure to do so would not produce well-formed XML.One potential solution in the serialization process is to end the CDATA section before the character, output the character using a character reference or entity reference, and open a new CDATA section for any further characters in the text node. Note, however, that some code conversion libraries at the time of writing do not return an error or exception when a character is missing from the encoding, making the task of ensuring that data is not corrupted on serialization more difficult.

See also the Document Object Model (DOM) Level 2 Core Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Methods inherited from interface org.w3c.dom.Text
splitText
Methods inherited from interface org.w3c.dom.CharacterData
appendData, deleteData, getData, getLength, insertData, replaceData, setData, substringData
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


CharacterData (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom
Interface CharacterData

All Superinterfaces:
Node
All Known Subinterfaces:
CDATASection, Comment, Text
public interface CharacterData
extends Node

The CharacterData interface extends Node with a set of attributes and methods for accessing character data in the DOM. For clarity this set is defined here rather than on each object that uses these attributes and methods. No DOM objects correspond directly to CharacterData, though Text and others do inherit the interface from it. All offsets in this interface start from 0.

As explained in the DOMString interface, text strings in the DOM are represented in UTF-16, i.e. as a sequence of 16-bit units. In the following, the term 16-bit units is used whenever necessary to indicate that indexing on CharacterData is done in 16-bit units.

See also the Document Object Model (DOM) Level 2 Core Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
void | appendData(String arg) Append the string to the end of the character data of the node.
void | deleteData(int offset, int count) Remove a range of 16-bit units from the node.
String | getData() The character data of the node that implements this interface.
int | getLength() The number of 16-bit units that are available through data and the substringData method below.
void | insertData(int offset, String arg) Insert a string at the specified 16-bit unit offset.
void | replaceData(int offset, int count, String arg) Replace the characters starting at the specified 16-bit unit offset with the specified string.
void | setData(String data) The character data of the node that implements this interface.
String | substringData(int offset, int count) Extracts a range of data from the node.
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getData

public String getData()
               throws DOMException
The character data of the node that implements this interface. The DOM implementation may not put arbitrary limits on the amount of data that may be stored in a CharacterData node. However, implementation limits may mean that the entirety of a node's data may not fit into a single DOMString. In such cases, the user may call substringData to retrieve the data in appropriately sized pieces.

Throws:
DOMException - NO_MODIFICATION_ALLOWED_ERR: Raised when the node is readonly.
DOMException - DOMSTRING_SIZE_ERR: Raised when it would return more characters than fit in a DOMString variable on the implementation platform.

setData

public void setData(String data)
             throws DOMException
The character data of the node that implements this interface. The DOM implementation may not put arbitrary limits on the amount of data that may be stored in a CharacterData node. However, implementation limits may mean that the entirety of a node's data may not fit into a single DOMString. In such cases, the user may call substringData to retrieve the data in appropriately sized pieces.

Throws:
DOMException - NO_MODIFICATION_ALLOWED_ERR: Raised when the node is readonly.
DOMException - DOMSTRING_SIZE_ERR: Raised when it would return more characters than fit in a DOMString variable on the implementation platform.

getLength

public int getLength()
The number of 16-bit units that are available through data and the substringData method below. This may have the value zero, i.e., CharacterData nodes may be empty.

substringData

public String substringData(int offset,
                            int count)
                     throws DOMException
Extracts a range of data from the node.

Parameters:
offset - Start offset of substring to extract.
count - The number of 16-bit units to extract.
Returns:
The specified substring. If the sum of offset and count exceeds the length, then all 16-bit units to the end of the data are returned.
Throws:
DOMException - INDEX_SIZE_ERR: Raised if the specified offset is negative or greater than the number of 16-bit units in data, or if the specified count is negative.
DOMSTRING_SIZE_ERR: Raised if the specified range of text does not fit into a DOMString.

appendData

public void appendData(String arg)
                throws DOMException
Append the string to the end of the character data of the node. Upon success, data provides access to the concatenation of data and the DOMString specified.

Parameters:
arg - The DOMString to append.
Throws:
DOMException - NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.

insertData

public void insertData(int offset,
                       String arg)
                throws DOMException
Insert a string at the specified 16-bit unit offset.

Parameters:
offset - The character offset at which to insert.
arg - The DOMString to insert.
Throws:
DOMException - INDEX_SIZE_ERR: Raised if the specified offset is negative or greater than the number of 16-bit units in data.
NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.

deleteData

public void deleteData(int offset,
                       int count)
                throws DOMException
Remove a range of 16-bit units from the node. Upon success, data and length reflect the change.

Parameters:
offset - The offset from which to start removing.
count - The number of 16-bit units to delete. If the sum of offset and count exceeds length then all 16-bit units from offset to the end of the data are deleted.
Throws:
DOMException - INDEX_SIZE_ERR: Raised if the specified offset is negative or greater than the number of 16-bit units in data, or if the specified count is negative.
NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.

replaceData

public void replaceData(int offset,
                        int count,
                        String arg)
                 throws DOMException
Replace the characters starting at the specified 16-bit unit offset with the specified string.

Parameters:
offset - The offset from which to start replacing.
count - The number of 16-bit units to replace. If the sum of offset and count exceeds length, then all 16-bit units to the end of the data are replaced; (i.e., the effect is the same as a remove method call with the same range, followed by an append method invocation).
arg - The DOMString with which the range must be replaced.
Throws:
DOMException - INDEX_SIZE_ERR: Raised if the specified offset is negative or greater than the number of 16-bit units in data, or if the specified count is negative.
NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Comment (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom
Interface Comment

All Superinterfaces:
CharacterData, Node
public interface Comment
extends CharacterData

This interface inherits from CharacterData and represents the content of a comment, i.e., all the characters between the starting ' <!--' and ending '-->'. Note that this is the definition of a comment in XML, and, in practice, HTML, although some HTML tools may implement the full SGML comment structure.

See also the Document Object Model (DOM) Level 2 Core Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Methods inherited from interface org.w3c.dom.CharacterData
appendData, deleteData, getData, getLength, insertData, replaceData, setData, substringData
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Document (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom
Interface Document

All Superinterfaces:
Node
public interface Document
extends Node

The Document interface represents the entire HTML or XML document. Conceptually, it is the root of the document tree, and provides the primary access to the document's data.

Since elements, text nodes, comments, processing instructions, etc. cannot exist outside the context of a Document, the Document interface also contains the factory methods needed to create these objects. The Node objects created have a ownerDocument attribute which associates them with the Document within whose context they were created.

See also the Document Object Model (DOM) Level 2 Core Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
Attr | createAttribute(String name) Creates an Attr of the given name.
Attr | createAttributeNS(String namespaceURI, String qualifiedName) Creates an attribute of the given qualified name and namespace URI.
CDATASection | createCDATASection(String data) Creates a CDATASection node whose value is the specified string.
Comment | createComment(String data) Creates a Comment node given the specified string.
DocumentFragment | createDocumentFragment() Creates an empty DocumentFragment object.
Element | createElement(String tagName) Creates an element of the type specified.
Element | createElementNS(String namespaceURI, String qualifiedName) Creates an element of the given qualified name and namespace URI.
EntityReference | createEntityReference(String name) Creates an EntityReference object.
ProcessingInstruction | createProcessingInstruction(String target, String data) Creates a ProcessingInstruction node given the specified name and data strings.
Text | createTextNode(String data) Creates a Text node given the specified string.
DocumentType | getDoctype() The Document Type Declaration (see DocumentType) associated with this document.
Element | getDocumentElement() This is a convenience attribute that allows direct access to the child node that is the root element of the document.
Element | getElementById(String elementId) Returns the Element whose ID is given by elementId.
NodeList | getElementsByTagName(String tagname) Returns a NodeList of all the Elements with a given tag name in the order in which they are encountered in a preorder traversal of the Document tree.
NodeList | getElementsByTagNameNS(String namespaceURI, String localName) Returns a NodeList of all the Elements with a given local name and namespace URI in the order in which they are encountered in a preorder traversal of the Document tree.
DOMImplementation | getImplementation() The DOMImplementation object that handles this document.
Node | importNode(Node importedNode, boolean deep) Imports a node from another document to this document.
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getDoctype

public DocumentType getDoctype()
The Document Type Declaration (see DocumentType) associated with this document. For HTML documents as well as XML documents without a document type declaration this returns null. The DOM Level 2 does not support editing the Document Type Declaration. docType cannot be altered in any way, including through the use of methods inherited from the Node interface, such as insertNode or removeNode.

getImplementation

public DOMImplementation getImplementation()
The DOMImplementation object that handles this document. A DOM application may use objects from multiple implementations.

getDocumentElement

public Element getDocumentElement()
This is a convenience attribute that allows direct access to the child node that is the root element of the document. For HTML documents, this is the element with the tagName "HTML".

createElement

public Element createElement(String tagName)
                      throws DOMException
Creates an element of the type specified. Note that the instance returned implements the Element interface, so attributes can be specified directly on the returned object.
In addition, if there are known attributes with default values, Attr nodes representing them are automatically created and attached to the element.
To create an element with a qualified name and namespace URI, use the createElementNS method.

Parameters:
tagName - The name of the element type to instantiate. For XML, this is case-sensitive. For HTML, the tagName parameter may be provided in any case, but it must be mapped to the canonical uppercase form by the DOM implementation.
Returns:
A new Element object with the nodeName attribute set to tagName, and localName, prefix, and namespaceURI set to null.
Throws:
DOMException - INVALID_CHARACTER_ERR: Raised if the specified name contains an illegal character.

createDocumentFragment

public DocumentFragment createDocumentFragment()
Creates an empty DocumentFragment object.

Returns:
A new DocumentFragment.

createTextNode

public Text createTextNode(String data)
Creates a Text node given the specified string.

Parameters:
data - The data for the node.
Returns:
The new Text object.

createComment

public Comment createComment(String data)
Creates a Comment node given the specified string.

Parameters:
data - The data for the node.
Returns:
The new Comment object.

createCDATASection

public CDATASection createCDATASection(String data)
                                throws DOMException
Creates a CDATASection node whose value is the specified string.

Parameters:
data - The data for the CDATASection contents.
Returns:
The new CDATASection object.
Throws:
DOMException - NOT_SUPPORTED_ERR: Raised if this document is an HTML document.

createProcessingInstruction

public ProcessingInstruction createProcessingInstruction(String target,
                                                         String data)
                                                  throws DOMException
Creates a ProcessingInstruction node given the specified name and data strings.

Parameters:
target - The target part of the processing instruction.
data - The data for the node.
Returns:
The new ProcessingInstruction object.
Throws:
DOMException - INVALID_CHARACTER_ERR: Raised if the specified target contains an illegal character.
NOT_SUPPORTED_ERR: Raised if this document is an HTML document.

createAttribute

public Attr createAttribute(String name)
                     throws DOMException
Creates an Attr of the given name. Note that the Attr instance can then be set on an Element using the setAttributeNode method.
To create an attribute with a qualified name and namespace URI, use the createAttributeNS method.

Parameters:
name - The name of the attribute.
Returns:
A new Attr object with the nodeName attribute set to name, and localName, prefix, and namespaceURI set to null. The value of the attribute is the empty string.
Throws:
DOMException - INVALID_CHARACTER_ERR: Raised if the specified name contains an illegal character.

createEntityReference

public EntityReference createEntityReference(String name)
                                      throws DOMException
Creates an EntityReference object. In addition, if the referenced entity is known, the child list of the EntityReference node is made the same as that of the corresponding Entity node.If any descendant of the Entity node has an unbound namespace prefix, the corresponding descendant of the created EntityReference node is also unbound; (its namespaceURI is null). The DOM Level 2 does not support any mechanism to resolve namespace prefixes.

Parameters:
name - The name of the entity to reference.
Returns:
The new EntityReference object.
Throws:
DOMException - INVALID_CHARACTER_ERR: Raised if the specified name contains an illegal character.
NOT_SUPPORTED_ERR: Raised if this document is an HTML document.

getElementsByTagName

public NodeList getElementsByTagName(String tagname)
Returns a NodeList of all the Elements with a given tag name in the order in which they are encountered in a preorder traversal of the Document tree.

Parameters:
tagname - The name of the tag to match on. The special value "*" matches all tags.
Returns:
A new NodeList object containing all the matched Elements.

importNode

public Node importNode(Node importedNode,
                       boolean deep)
                throws DOMException
Imports a node from another document to this document. The returned node has no parent; (parentNode is null). The source node is not altered or removed from the original document; this method creates a new copy of the source node.
For all nodes, importing a node creates a node object owned by the importing document, with attribute values identical to the source node's nodeName and nodeType, plus the attributes related to namespaces (prefix, localName, and namespaceURI). As in the cloneNode operation on a Node, the source node is not altered.
Additional information is copied as appropriate to the nodeType, attempting to mirror the behavior expected if a fragment of XML or HTML source was copied from one document to another, recognizing that the two documents may have different DTDs in the XML case. The following list describes the specifics for each type of node.
ATTRIBUTE_NODE
The ownerElement attribute is set to null and the specified flag is set to true on the generated Attr. The descendants of the source Attr are recursively imported and the resulting nodes reassembled to form the corresponding subtree. Note that the deep parameter has no effect on Attr nodes; they always carry their children with them when imported.
DOCUMENT_FRAGMENT_NODE
If the deep option was set to true, the descendants of the source element are recursively imported and the resulting nodes reassembled to form the corresponding subtree. Otherwise, this simply generates an empty DocumentFragment.
DOCUMENT_NODE
Document nodes cannot be imported.
DOCUMENT_TYPE_NODE
DocumentType nodes cannot be imported.
ELEMENT_NODE
Specified attribute nodes of the source element are imported, and the generated Attr nodes are attached to the generated Element. Default attributes are not copied, though if the document being imported into defines default attributes for this element name, those are assigned. If the importNode deep parameter was set to true, the descendants of the source element are recursively imported and the resulting nodes reassembled to form the corresponding subtree.
ENTITY_NODE
Entity nodes can be imported, however in the current release of the DOM the DocumentType is readonly. Ability to add these imported nodes to a DocumentType will be considered for addition to a future release of the DOM.On import, the publicId, systemId, and notationName attributes are copied. If a deep import is requested, the descendants of the the source Entity are recursively imported and the resulting nodes reassembled to form the corresponding subtree.
ENTITY_REFERENCE_NODE
Only the EntityReference itself is copied, even if a deep import is requested, since the source and destination documents might have defined the entity differently. If the document being imported into provides a definition for this entity name, its value is assigned.
NOTATION_NODE
Notation nodes can be imported, however in the current release of the DOM the DocumentType is readonly. Ability to add these imported nodes to a DocumentType will be considered for addition to a future release of the DOM.On import, the publicId and systemId attributes are copied. Note that the deep parameter has no effect on Notation nodes since they never have any children.
PROCESSING_INSTRUCTION_NODE
The imported node copies its target and data values from those of the source node.
TEXT_NODE, CDATA_SECTION_NODE, COMMENT_NODE
These three types of nodes inheriting from CharacterData copy their data and length attributes from those of the source node.

Parameters:
importedNode - The node to import.
deep - If true, recursively import the subtree under the specified node; if false, import only the node itself, as explained above. This has no effect on Attr , EntityReference, and Notation nodes.
Returns:
The imported node that belongs to this Document.
Throws:
DOMException - NOT_SUPPORTED_ERR: Raised if the type of node being imported is not supported.
Since:
DOM Level 2

createElementNS

public Element createElementNS(String namespaceURI,
                               String qualifiedName)
                        throws DOMException
Creates an element of the given qualified name and namespace URI.

Parameters:
namespaceURI - The namespace URI of the element to create.
qualifiedName - The qualified name of the element type to instantiate.
Returns:
A new Element object with the following attributes:
Attribute | Value
Node.nodeName | qualifiedName
Node.namespaceURI | namespaceURI
Node.prefix | prefix, extracted from qualifiedName, or null if there is no prefix
Node.localName | local name, extracted from qualifiedName
Element.tagName | qualifiedName
Throws:
DOMException - INVALID_CHARACTER_ERR: Raised if the specified qualified name contains an illegal character, per the XML 1.0 specification .
NAMESPACE_ERR: Raised if the qualifiedName is malformed per the Namespaces in XML specification, if the qualifiedName has a prefix and the namespaceURI is null, or if the qualifiedName has a prefix that is "xml" and the namespaceURI is different from " http://www.w3.org/XML/1998/namespace" .
NOT_SUPPORTED_ERR: Always thrown if the current document does not support the "XML" feature, since namespaces were defined by XML.
Since:
DOM Level 2

createAttributeNS

public Attr createAttributeNS(String namespaceURI,
                              String qualifiedName)
                       throws DOMException
Creates an attribute of the given qualified name and namespace URI.

Parameters:
namespaceURI - The namespace URI of the attribute to create.
qualifiedName - The qualified name of the attribute to instantiate.
Returns:
A new Attr object with the following attributes:
Attribute | Value
Node.nodeName | qualifiedName
Node.namespaceURI | namespaceURI
Node.prefix | prefix, extracted from qualifiedName, or null if there is no prefix
Node.localName | local name, extracted from qualifiedName
Attr.name | qualifiedName
Node.nodeValue | the empty string
Throws:
DOMException - INVALID_CHARACTER_ERR: Raised if the specified qualified name contains an illegal character, per the XML 1.0 specification .
NAMESPACE_ERR: Raised if the qualifiedName is malformed per the Namespaces in XML specification, if the qualifiedName has a prefix and the namespaceURI is null, if the qualifiedName has a prefix that is "xml" and the namespaceURI is different from " http://www.w3.org/XML/1998/namespace", or if the qualifiedName, or its prefix, is "xmlns" and the namespaceURI is different from " http://www.w3.org/2000/xmlns/".
NOT_SUPPORTED_ERR: Always thrown if the current document does not support the "XML" feature, since namespaces were defined by XML.
Since:
DOM Level 2

getElementsByTagNameNS

public NodeList getElementsByTagNameNS(String namespaceURI,
                                       String localName)
Returns a NodeList of all the Elements with a given local name and namespace URI in the order in which they are encountered in a preorder traversal of the Document tree.

Parameters:
namespaceURI - The namespace URI of the elements to match on. The special value "*" matches all namespaces.
localName - The local name of the elements to match on. The special value "*" matches all local names.
Returns:
A new NodeList object containing all the matched Elements.
Since:
DOM Level 2

getElementById

public Element getElementById(String elementId)
Returns the Element whose ID is given by elementId. If no such element exists, returns null. Behavior is not defined if more than one element has this ID. The DOM implementation must have information that says which attributes are of type ID. Attributes with the name "ID" are not of type ID unless so defined. Implementations that do not know whether attributes are of type ID or not are expected to return null.

Parameters:
elementId - The unique id value for an element.
Returns:
The matching element.
Since:
DOM Level 2
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DocumentFragment (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom
Interface DocumentFragment

All Superinterfaces:
Node
public interface DocumentFragment
extends Node

DocumentFragment is a "lightweight" or "minimal" Document object. It is very common to want to be able to extract a portion of a document's tree or to create a new fragment of a document. Imagine implementing a user command like cut or rearranging a document by moving fragments around. It is desirable to have an object which can hold such fragments and it is quite natural to use a Node for this purpose. While it is true that a Document object could fulfill this role, a Document object can potentially be a heavyweight object, depending on the underlying implementation. What is really needed for this is a very lightweight object. DocumentFragment is such an object.

Furthermore, various operations -- such as inserting nodes as children of another Node -- may take DocumentFragment objects as arguments; this results in all the child nodes of the DocumentFragment being moved to the child list of this node.

The children of a DocumentFragment node are zero or more nodes representing the tops of any sub-trees defining the structure of the document. DocumentFragment nodes do not need to be well-formed XML documents (although they do need to follow the rules imposed upon well-formed XML parsed entities, which can have multiple top nodes). For example, a DocumentFragment might have only one child and that child node could be a Text node. Such a structure model represents neither an HTML document nor a well-formed XML document.

When a DocumentFragment is inserted into a Document (or indeed any other Node that may take children) the children of the DocumentFragment and not the DocumentFragment itself are inserted into the Node. This makes the DocumentFragment very useful when the user wishes to create nodes that are siblings; the DocumentFragment acts as the parent of these nodes so that the user can use the standard methods from the Node interface, such as insertBefore and appendChild.

See also the Document Object Model (DOM) Level 2 Core Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DocumentType (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom
Interface DocumentType

All Superinterfaces:
Node
public interface DocumentType
extends Node

Each Document has a doctype attribute whose value is either null or a DocumentType object. The DocumentType interface in the DOM Core provides an interface to the list of entities that are defined for the document, and little else because the effect of namespaces and the various XML schema efforts on DTD representation are not clearly understood as of this writing.

The DOM Level 2 doesn't support editing DocumentType nodes.

See also the Document Object Model (DOM) Level 2 Core Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
NamedNodeMap | getEntities() A NamedNodeMap containing the general entities, both external and internal, declared in the DTD.
String | getInternalSubset() The internal subset as a string, or null if there is none.
String | getName() The name of DTD; i.e., the name immediately following the DOCTYPE keyword.
NamedNodeMap | getNotations() A NamedNodeMap containing the notations declared in the DTD.
String | getPublicId() The public identifier of the external subset.
String | getSystemId() The system identifier of the external subset.
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getName

public String getName()
The name of DTD; i.e., the name immediately following the DOCTYPE keyword.

getEntities

public NamedNodeMap getEntities()
A NamedNodeMap containing the general entities, both external and internal, declared in the DTD. Parameter entities are not contained. Duplicates are discarded. For example in:
<!DOCTYPE
 ex SYSTEM "ex.dtd" [ <!ENTITY foo "foo"> <!ENTITY bar
 "bar"> <!ENTITY bar "bar2"> <!ENTITY % baz "baz">
 ]> <ex/>
the interface provides access to foo and the first declaration of bar but not the second declaration of bar or baz. Every node in this map also implements the Entity interface.
The DOM Level 2 does not support editing entities, therefore entities cannot be altered in any way.

getNotations

public NamedNodeMap getNotations()
A NamedNodeMap containing the notations declared in the DTD. Duplicates are discarded. Every node in this map also implements the Notation interface.
The DOM Level 2 does not support editing notations, therefore notations cannot be altered in any way.

getPublicId

public String getPublicId()
The public identifier of the external subset.

Since:
DOM Level 2

getSystemId

public String getSystemId()
The system identifier of the external subset.

Since:
DOM Level 2

getInternalSubset

public String getInternalSubset()
The internal subset as a string, or null if there is none. This is does not contain the delimiting square brackets.The actual content returned depends on how much information is available to the implementation. This may vary depending on various parameters, including the XML processor used to build the document.

Since:
DOM Level 2
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DOMException (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom
Class DOMException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by org.w3c.dom.DOMException
All Implemented Interfaces:
Serializable
public class DOMException
extends RuntimeException

DOM operations only raise exceptions in "exceptional" circumstances, i.e., when an operation is impossible to perform (either for logical reasons, because data is lost, or because the implementation has become unstable). In general, DOM methods return specific error values in ordinary processing situations, such as out-of-bound errors when using NodeList.

Implementations should raise other exceptions under other circumstances. For example, implementations should raise an implementation-dependent exception if a null argument is passed.

Some languages and object systems do not support the concept of exceptions. For such systems, error conditions may be indicated using native error reporting mechanisms. For some bindings, for example, methods may return error codes similar to those listed in the corresponding method descriptions.

See also the Document Object Model (DOM) Level 2 Core Specification.

See Also:
Serialized Form

Field Summary
short | code
static short | DOMSTRING_SIZE_ERR If the specified range of text does not fit into a DOMString
static short | HIERARCHY_REQUEST_ERR If any node is inserted somewhere it doesn't belong
static short | INDEX_SIZE_ERR If index or size is negative, or greater than the allowed value
static short | INUSE_ATTRIBUTE_ERR If an attempt is made to add an attribute that is already in use elsewhere
static short | INVALID_ACCESS_ERR If a parameter or an operation is not supported by the underlying object.
static short | INVALID_CHARACTER_ERR If an invalid or illegal character is specified, such as in a name.
static short | INVALID_MODIFICATION_ERR If an attempt is made to modify the type of the underlying object.
static short | INVALID_STATE_ERR If an attempt is made to use an object that is not, or is no longer, usable.
static short | NAMESPACE_ERR If an attempt is made to create or change an object in a way which is incorrect with regard to namespaces.
static short | NO_DATA_ALLOWED_ERR If data is specified for a node which does not support data
static short | NO_MODIFICATION_ALLOWED_ERR If an attempt is made to modify an object where modifications are not allowed
static short | NOT_FOUND_ERR If an attempt is made to reference a node in a context where it does not exist
static short | NOT_SUPPORTED_ERR If the implementation does not support the requested type of object or operation.
static short | SYNTAX_ERR If an invalid or illegal string is specified.
static short | WRONG_DOCUMENT_ERR If a node is used in a different document than the one that created it (that doesn't support it)
Constructor Summary
DOMException(short code, String message)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

code

public short code

INDEX_SIZE_ERR

public static final short INDEX_SIZE_ERR
If index or size is negative, or greater than the allowed value

See Also:
Constant Field Values

DOMSTRING_SIZE_ERR

public static final short DOMSTRING_SIZE_ERR
If the specified range of text does not fit into a DOMString

See Also:
Constant Field Values

HIERARCHY_REQUEST_ERR

public static final short HIERARCHY_REQUEST_ERR
If any node is inserted somewhere it doesn't belong

See Also:
Constant Field Values

WRONG_DOCUMENT_ERR

public static final short WRONG_DOCUMENT_ERR
If a node is used in a different document than the one that created it (that doesn't support it)

See Also:
Constant Field Values

INVALID_CHARACTER_ERR

public static final short INVALID_CHARACTER_ERR
If an invalid or illegal character is specified, such as in a name. See production 2 in the XML specification for the definition of a legal character, and production 5 for the definition of a legal name character.

See Also:
Constant Field Values

NO_DATA_ALLOWED_ERR

public static final short NO_DATA_ALLOWED_ERR
If data is specified for a node which does not support data

See Also:
Constant Field Values

NO_MODIFICATION_ALLOWED_ERR

public static final short NO_MODIFICATION_ALLOWED_ERR
If an attempt is made to modify an object where modifications are not allowed

See Also:
Constant Field Values

NOT_FOUND_ERR

public static final short NOT_FOUND_ERR
If an attempt is made to reference a node in a context where it does not exist

See Also:
Constant Field Values

NOT_SUPPORTED_ERR

public static final short NOT_SUPPORTED_ERR
If the implementation does not support the requested type of object or operation.

See Also:
Constant Field Values

INUSE_ATTRIBUTE_ERR

public static final short INUSE_ATTRIBUTE_ERR
If an attempt is made to add an attribute that is already in use elsewhere

See Also:
Constant Field Values

INVALID_STATE_ERR

public static final short INVALID_STATE_ERR
If an attempt is made to use an object that is not, or is no longer, usable.

Since:
DOM Level 2
See Also:
Constant Field Values

SYNTAX_ERR

public static final short SYNTAX_ERR
If an invalid or illegal string is specified.

Since:
DOM Level 2
See Also:
Constant Field Values

INVALID_MODIFICATION_ERR

public static final short INVALID_MODIFICATION_ERR
If an attempt is made to modify the type of the underlying object.

Since:
DOM Level 2
See Also:
Constant Field Values

NAMESPACE_ERR

public static final short NAMESPACE_ERR
If an attempt is made to create or change an object in a way which is incorrect with regard to namespaces.

Since:
DOM Level 2
See Also:
Constant Field Values

INVALID_ACCESS_ERR

public static final short INVALID_ACCESS_ERR
If a parameter or an operation is not supported by the underlying object.

Since:
DOM Level 2
See Also:
Constant Field Values
Constructor Detail

DOMException

public DOMException(short code,
                    String message)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


DOMImplementation (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom
Interface DOMImplementation

public interface DOMImplementation

The DOMImplementation interface provides a number of methods for performing operations that are independent of any particular instance of the document object model.

See also the Document Object Model (DOM) Level 2 Core Specification.

Method Summary
Document | createDocument(String namespaceURI, String qualifiedName, DocumentType doctype) Creates a DOM Document object of the specified type with its document element.
DocumentType | createDocumentType(String qualifiedName, String publicId, String systemId) Creates an empty DocumentType node.
boolean | hasFeature(String feature, String version) Test if the DOM implementation implements a specific feature.

Method Detail

hasFeature

public boolean hasFeature(String feature,
                          String version)
Test if the DOM implementation implements a specific feature.

Parameters:
feature - The name of the feature to test (case-insensitive). The values used by DOM features are defined throughout the DOM Level 2 specifications and listed in the section. The name must be an XML name. To avoid possible conflicts, as a convention, names referring to features defined outside the DOM specification should be made unique.
version - This is the version number of the feature to test. In Level 2, the string can be either "2.0" or "1.0". If the version is not specified, supporting any version of the feature causes the method to return true.
Returns:
true if the feature is implemented in the specified version, false otherwise.

createDocumentType

public DocumentType createDocumentType(String qualifiedName,
                                       String publicId,
                                       String systemId)
                                throws DOMException
Creates an empty DocumentType node. Entity declarations and notations are not made available. Entity reference expansions and default attribute additions do not occur. It is expected that a future version of the DOM will provide a way for populating a DocumentType.

Parameters:
qualifiedName - The qualified name of the document type to be created.
publicId - The external subset public identifier.
systemId - The external subset system identifier.
Returns:
A new DocumentType node with Node.ownerDocument set to null.
Throws:
DOMException - INVALID_CHARACTER_ERR: Raised if the specified qualified name contains an illegal character.
NAMESPACE_ERR: Raised if the qualifiedName is malformed.
NOT_SUPPORTED_ERR: May be raised by DOM implementations which do not support the "XML" feature, if they choose not to support this method. Other features introduced in the future, by the DOM WG or in extensions defined by other groups, may also demand support for this method; please consult the definition of the feature to see if it requires this method.
Since:
DOM Level 2

createDocument

public Document createDocument(String namespaceURI,
                               String qualifiedName,
                               DocumentType doctype)
                        throws DOMException
Creates a DOM Document object of the specified type with its document element.

Parameters:
namespaceURI - The namespace URI of the document element to create.
qualifiedName - The qualified name of the document element to be created.
doctype - The type of document to be created or null. When doctype is not null, its Node.ownerDocument attribute is set to the document being created.
Returns:
A new Document object.
Throws:
DOMException - INVALID_CHARACTER_ERR: Raised if the specified qualified name contains an illegal character.
NAMESPACE_ERR: Raised if the qualifiedName is malformed, if the qualifiedName has a prefix and the namespaceURI is null, or if the qualifiedName has a prefix that is "xml" and the namespaceURI is different from " http://www.w3.org/XML/1998/namespace" , or if the DOM implementation does not support the "XML" feature but a non-null namespace URI was provided, since namespaces were defined by XML.
WRONG_DOCUMENT_ERR: Raised if doctype has already been used with a different document or was created from a different implementation.
NOT_SUPPORTED_ERR: May be raised by DOM implementations which do not support the "XML" feature, if they choose not to support this method. Other features introduced in the future, by the DOM WG or in extensions defined by other groups, may also demand support for this method; please consult the definition of the feature to see if it requires this method.
Since:
DOM Level 2
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Element (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom
Interface Element

All Superinterfaces:
Node
All Known Implementing Classes:
IIOMetadataNode
public interface Element
extends Node

The Element interface represents an element in an HTML or XML document. Elements may have attributes associated with them; since the Element interface inherits from Node, the generic Node interface attribute attributes may be used to retrieve the set of all attributes for an element. There are methods on the Element interface to retrieve either an Attr object by name or an attribute value by name. In XML, where an attribute value may contain entity references, an Attr object should be retrieved to examine the possibly fairly complex sub-tree representing the attribute value. On the other hand, in HTML, where all attributes have simple string values, methods to directly access an attribute value can safely be used as a convenience.In DOM Level 2, the method normalize is inherited from the Node interface where it was moved.

See also the Document Object Model (DOM) Level 2 Core Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getAttribute(String name) Retrieves an attribute value by name.
Attr | getAttributeNode(String name) Retrieves an attribute node by name.
Attr | getAttributeNodeNS(String namespaceURI, String localName) Retrieves an Attr node by local name and namespace URI.
String | getAttributeNS(String namespaceURI, String localName) Retrieves an attribute value by local name and namespace URI.
NodeList | getElementsByTagName(String name) Returns a NodeList of all descendant Elements with a given tag name, in the order in which they are encountered in a preorder traversal of this Element tree.
NodeList | getElementsByTagNameNS(String namespaceURI, String localName) Returns a NodeList of all the descendant Elements with a given local name and namespace URI in the order in which they are encountered in a preorder traversal of this Element tree.
String | getTagName() The name of the element.
boolean | hasAttribute(String name) Returns true when an attribute with a given name is specified on this element or has a default value, false otherwise.
boolean | 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.
void | removeAttribute(String name) Removes an attribute by name.
Attr | removeAttributeNode(Attr oldAttr) Removes the specified attribute node.
void | removeAttributeNS(String namespaceURI, String localName) Removes an attribute by local name and namespace URI.
void | setAttribute(String name, String value) Adds a new attribute.
Attr | setAttributeNode(Attr newAttr) Adds a new attribute node.
Attr | setAttributeNodeNS(Attr newAttr) Adds a new attribute.
void | setAttributeNS(String namespaceURI, String qualifiedName, String value) Adds a new attribute.
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getTagName

public String getTagName()
The name of the element. For example, in:
 <elementExample
 id="demo"> ... </elementExample> ,
tagName has the value "elementExample". Note that this is case-preserving in XML, as are all of the operations of the DOM. The HTML DOM returns the tagName of an HTML element in the canonical uppercase form, regardless of the case in the source HTML document.

getAttribute

public String getAttribute(String name)
Retrieves an attribute value by name.

Parameters:
name - The name of the attribute to retrieve.
Returns:
The Attr value as a string, or the empty string if that attribute does not have a specified or default value.

setAttribute

public void setAttribute(String name,
                         String value)
                  throws DOMException
Adds a new attribute. If an attribute with that name is already present in the element, its value is changed to be that of the value parameter. This value is a simple string; it is not parsed as it is being set. So any markup (such as syntax to be recognized as an entity reference) is treated as literal text, and needs to be appropriately escaped by the implementation when it is written out. In order to assign an attribute value that contains entity references, the user must create an Attr node plus any Text and EntityReference nodes, build the appropriate subtree, and use setAttributeNode to assign it as the value of an attribute.
To set an attribute with a qualified name and namespace URI, use the setAttributeNS method.

Parameters:
name - The name of the attribute to create or alter.
value - Value to set in string form.
Throws:
DOMException - INVALID_CHARACTER_ERR: Raised if the specified name contains an illegal character.
NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.

removeAttribute

public void removeAttribute(String name)
                     throws DOMException
Removes an attribute by name. If the removed attribute is known to have a default value, an attribute immediately appears containing the default value as well as the corresponding namespace URI, local name, and prefix when applicable.
To remove an attribute by local name and namespace URI, use the removeAttributeNS method.

Parameters:
name - The name of the attribute to remove.
Throws:
DOMException - NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.

getAttributeNode

public Attr getAttributeNode(String name)
Retrieves an attribute node by name.
To retrieve an attribute node by qualified name and namespace URI, use the getAttributeNodeNS method.

Parameters:
name - The name (nodeName) of the attribute to retrieve.
Returns:
The Attr node with the specified name ( nodeName) or null if there is no such attribute.

setAttributeNode

public Attr setAttributeNode(Attr newAttr)
                      throws DOMException
Adds a new attribute node. If an attribute with that name ( nodeName) is already present in the element, it is replaced by the new one.
To add a new attribute node with a qualified name and namespace URI, use the setAttributeNodeNS method.

Parameters:
newAttr - The Attr node to add to the attribute list.
Returns:
If the newAttr attribute replaces an existing attribute, the replaced Attr node is returned, otherwise null is returned.
Throws:
DOMException - WRONG_DOCUMENT_ERR: Raised if newAttr was created from a different document than the one that created the element.
NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.
INUSE_ATTRIBUTE_ERR: Raised if newAttr is already an attribute of another Element object. The DOM user must explicitly clone Attr nodes to re-use them in other elements.

removeAttributeNode

public Attr removeAttributeNode(Attr oldAttr)
                         throws DOMException
Removes the specified attribute node. If the removed Attr has a default value it is immediately replaced. The replacing attribute has the same namespace URI and local name, as well as the original prefix, when applicable.

Parameters:
oldAttr - The Attr node to remove from the attribute list.
Returns:
The Attr node that was removed.
Throws:
DOMException - NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.
NOT_FOUND_ERR: Raised if oldAttr is not an attribute of the element.

getElementsByTagName

public NodeList getElementsByTagName(String name)
Returns a NodeList of all descendant Elements with a given tag name, in the order in which they are encountered in a preorder traversal of this Element tree.

Parameters:
name - The name of the tag to match on. The special value "*" matches all tags.
Returns:
A list of matching Element nodes.

getAttributeNS

public String getAttributeNS(String namespaceURI,
                             String localName)
Retrieves an attribute value by local name and namespace URI.
Documents which do not support the "XML" feature will permit only the DOM Level 1 calls for creating/setting elements and attributes. Hence, if you specify a non-null namespace URI, these DOMs will never find a matching node.

Parameters:
namespaceURI - The namespace URI of the attribute to retrieve.
localName - The local name of the attribute to retrieve.
Returns:
The Attr value as a string, or the empty string if that attribute does not have a specified or default value.
Since:
DOM Level 2

setAttributeNS

public void setAttributeNS(String namespaceURI,
                           String qualifiedName,
                           String value)
                    throws DOMException
Adds a new attribute. If an attribute with the same local name and namespace URI is already present on the element, its prefix is changed to be the prefix part of the qualifiedName, and its value is changed to be the value parameter. This value is a simple string; it is not parsed as it is being set. So any markup (such as syntax to be recognized as an entity reference) is treated as literal text, and needs to be appropriately escaped by the implementation when it is written out. In order to assign an attribute value that contains entity references, the user must create an Attr node plus any Text and EntityReference nodes, build the appropriate subtree, and use setAttributeNodeNS or setAttributeNode to assign it as the value of an attribute.

Parameters:
namespaceURI - The namespace URI of the attribute to create or alter.
qualifiedName - The qualified name of the attribute to create or alter.
value - The value to set in string form.
Throws:
DOMException - INVALID_CHARACTER_ERR: Raised if the specified qualified name contains an illegal character, per the XML 1.0 specification .
NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.
NAMESPACE_ERR: Raised if the qualifiedName is malformed per the Namespaces in XML specification, if the qualifiedName has a prefix and the namespaceURI is null, if the qualifiedName has a prefix that is "xml" and the namespaceURI is different from " http://www.w3.org/XML/1998/namespace", or if the qualifiedName, or its prefix, is "xmlns" and the namespaceURI is different from " http://www.w3.org/2000/xmlns/".
NOT_SUPPORTED_ERR: Always thrown if the current document does not support the "XML" feature, since namespaces were defined by XML.
Since:
DOM Level 2

removeAttributeNS

public void removeAttributeNS(String namespaceURI,
                              String localName)
                       throws DOMException
Removes an attribute by local name and namespace URI. If the removed attribute has a default value it is immediately replaced. The replacing attribute has the same namespace URI and local name, as well as the original prefix.
Documents which do not support the "XML" feature will permit only the DOM Level 1 calls for creating/setting elements and attributes. Hence, if you specify a non-null namespace URI, these DOMs will never find a matching node.

Parameters:
namespaceURI - The namespace URI of the attribute to remove.
localName - The local name of the attribute to remove.
Throws:
DOMException - NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.
Since:
DOM Level 2

getAttributeNodeNS

public Attr getAttributeNodeNS(String namespaceURI,
                               String localName)
Retrieves an Attr node by local name and namespace URI.
Documents which do not support the "XML" feature will permit only the DOM Level 1 calls for creating/setting elements and attributes. Hence, if you specify a non-null namespace URI, these DOMs will never find a matching node.

Parameters:
namespaceURI - The namespace URI of the attribute to retrieve.
localName - The local name of the attribute to retrieve.
Returns:
The Attr node with the specified attribute local name and namespace URI or null if there is no such attribute.
Since:
DOM Level 2

setAttributeNodeNS

public Attr setAttributeNodeNS(Attr newAttr)
                        throws DOMException
Adds a new attribute. If an attribute with that local name and that namespace URI is already present in the element, it is replaced by the new one.

Parameters:
newAttr - The Attr node to add to the attribute list.
Returns:
If the newAttr attribute replaces an existing attribute with the same local name and namespace URI, the replaced Attr node is returned, otherwise null is returned.
Throws:
DOMException - WRONG_DOCUMENT_ERR: Raised if newAttr was created from a different document than the one that created the element.
NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.
INUSE_ATTRIBUTE_ERR: Raised if newAttr is already an attribute of another Element object. The DOM user must explicitly clone Attr nodes to re-use them in other elements.
NOT_SUPPORTED_ERR: Always thrown if the current document does not support the "XML" feature, since namespaces were defined by XML.
Since:
DOM Level 2

getElementsByTagNameNS

public NodeList getElementsByTagNameNS(String namespaceURI,
                                       String localName)
Returns a NodeList of all the descendant Elements with a given local name and namespace URI in the order in which they are encountered in a preorder traversal of this Element tree.
Documents which do not support the "XML" feature will permit only the DOM Level 1 calls for creating/setting elements and attributes. Hence, if you specify a non-null namespace URI, these DOMs will never find a matching node.

Parameters:
namespaceURI - The namespace URI of the elements to match on. The special value "*" matches all namespaces.
localName - The local name of the elements to match on. The special value "*" matches all local names.
Returns:
A new NodeList object containing all the matched Elements.
Since:
DOM Level 2

hasAttribute

public boolean hasAttribute(String name)
Returns true when an attribute with a given name is specified on this element or has a default value, false otherwise.

Parameters:
name - The name of the attribute to look for.
Returns:
true if an attribute with the given name is specified on this element or has a default value, false otherwise.
Since:
DOM Level 2

hasAttributeNS

public boolean 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.
Documents which do not support the "XML" feature will permit only the DOM Level 1 calls for creating/setting elements and attributes. Hence, if you specify a non-null namespace URI, these DOMs will never find a matching node.

Parameters:
namespaceURI - The namespace URI of the attribute to look for.
localName - The local name of the attribute to look for.
Returns:
true if an attribute with the given local name and namespace URI is specified or has a default value on this element, false otherwise.
Since:
DOM Level 2
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Entity (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom
Interface Entity

All Superinterfaces:
Node
public interface Entity
extends Node

This interface represents an entity, either parsed or unparsed, in an XML document. Note that this models the entity itself not the entity declaration. Entity declaration modeling has been left for a later Level of the DOM specification.

The nodeName attribute that is inherited from Node contains the name of the entity.

An XML processor may choose to completely expand entities before the structure model is passed to the DOM; in this case there will be no EntityReference nodes in the document tree.

XML does not mandate that a non-validating XML processor read and process entity declarations made in the external subset or declared in external parameter entities. This means that parsed entities declared in the external subset need not be expanded by some classes of applications, and that the replacement value of the entity may not be available. When the replacement value is available, the corresponding Entity node's child list represents the structure of that replacement text. Otherwise, the child list is empty.

The DOM Level 2 does not support editing Entity nodes; if a user wants to make changes to the contents of an Entity, every related EntityReference node has to be replaced in the structure model by a clone of the Entity's contents, and then the desired changes must be made to each of those clones instead. Entity nodes and all their descendants are readonly.

An Entity node does not have any parent.If the entity contains an unbound namespace prefix, the namespaceURI of the corresponding node in the Entity node subtree is null. The same is true for EntityReference nodes that refer to this entity, when they are created using the createEntityReference method of the Document interface. The DOM Level 2 does not support any mechanism to resolve namespace prefixes.

See also the Document Object Model (DOM) Level 2 Core Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getNotationName() For unparsed entities, the name of the notation for the entity.
String | getPublicId() The public identifier associated with the entity, if specified.
String | getSystemId() The system identifier associated with the entity, if specified.
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getPublicId

public String getPublicId()
The public identifier associated with the entity, if specified. If the public identifier was not specified, this is null.

getSystemId

public String getSystemId()
The system identifier associated with the entity, if specified. If the system identifier was not specified, this is null.

getNotationName

public String getNotationName()
For unparsed entities, the name of the notation for the entity. For parsed entities, this is null.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


EntityReference (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom
Interface EntityReference

All Superinterfaces:
Node
public interface EntityReference
extends Node

EntityReference objects may be inserted into the structure model when an entity reference is in the source document, or when the user wishes to insert an entity reference. Note that character references and references to predefined entities are considered to be expanded by the HTML or XML processor so that characters are represented by their Unicode equivalent rather than by an entity reference. Moreover, the XML processor may completely expand references to entities while building the structure model, instead of providing EntityReference objects. If it does provide such objects, then for a given EntityReference node, it may be that there is no Entity node representing the referenced entity. If such an Entity exists, then the subtree of the EntityReference node is in general a copy of the Entity node subtree. However, this may not be true when an entity contains an unbound namespace prefix. In such a case, because the namespace prefix resolution depends on where the entity reference is, the descendants of the EntityReference node may be bound to different namespace URIs.

As for Entity nodes, EntityReference nodes and all their descendants are readonly.

See also the Document Object Model (DOM) Level 2 Core Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NamedNodeMap (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom
Interface NamedNodeMap

public interface NamedNodeMap

Objects implementing the NamedNodeMap interface are used to represent collections of nodes that can be accessed by name. Note that NamedNodeMap does not inherit from NodeList; NamedNodeMaps are not maintained in any particular order. Objects contained in an object implementing NamedNodeMap may also be accessed by an ordinal index, but this is simply to allow convenient enumeration of the contents of a NamedNodeMap, and does not imply that the DOM specifies an order to these Nodes.

NamedNodeMap objects in the DOM are live.

See also the Document Object Model (DOM) Level 2 Core Specification.

Method Summary
int | getLength() The number of nodes in this map.
Node | getNamedItem(String name) Retrieves a node specified by name.
Node | getNamedItemNS(String namespaceURI, String localName) Retrieves a node specified by local name and namespace URI.
Node | item(int index) Returns the indexth item in the map.
Node | removeNamedItem(String name) Removes a node specified by name.
Node | removeNamedItemNS(String namespaceURI, String localName) Removes a node specified by local name and namespace URI.
Node | setNamedItem(Node arg) Adds a node using its nodeName attribute.
Node | setNamedItemNS(Node arg) Adds a node using its namespaceURI and localName.

Method Detail

getNamedItem

public Node getNamedItem(String name)
Retrieves a node specified by name.

Parameters:
name - The nodeName of a node to retrieve.
Returns:
A Node (of any type) with the specified nodeName, or null if it does not identify any node in this map.

setNamedItem

public Node setNamedItem(Node arg)
                  throws DOMException
Adds a node using its nodeName attribute. If a node with that name is already present in this map, it is replaced by the new one.
As the nodeName attribute is used to derive the name which the node must be stored under, multiple nodes of certain types (those that have a "special" string value) cannot be stored as the names would clash. This is seen as preferable to allowing nodes to be aliased.

Parameters:
arg - A node to store in this map. The node will later be accessible using the value of its nodeName attribute.
Returns:
If the new Node replaces an existing node the replaced Node is returned, otherwise null is returned.
Throws:
DOMException - WRONG_DOCUMENT_ERR: Raised if arg was created from a different document than the one that created this map.
NO_MODIFICATION_ALLOWED_ERR: Raised if this map is readonly.
INUSE_ATTRIBUTE_ERR: Raised if arg is an Attr that is already an attribute of another Element object. The DOM user must explicitly clone Attr nodes to re-use them in other elements.
HIERARCHY_REQUEST_ERR: Raised if an attempt is made to add a node doesn't belong in this NamedNodeMap. Examples would include trying to insert something other than an Attr node into an Element's map of attributes, or a non-Entity node into the DocumentType's map of Entities.

removeNamedItem

public Node removeNamedItem(String name)
                     throws DOMException
Removes a node specified by name. When this map contains the attributes attached to an element, if the removed attribute is known to have a default value, an attribute immediately appears containing the default value as well as the corresponding namespace URI, local name, and prefix when applicable.

Parameters:
name - The nodeName of the node to remove.
Returns:
The node removed from this map if a node with such a name exists.
Throws:
DOMException - NOT_FOUND_ERR: Raised if there is no node named name in this map.
NO_MODIFICATION_ALLOWED_ERR: Raised if this map is readonly.

item

public Node item(int index)
Returns the indexth item in the map. If index is greater than or equal to the number of nodes in this map, this returns null.

Parameters:
index - Index into this map.
Returns:
The node at the indexth position in the map, or null if that is not a valid index.

getLength

public int getLength()
The number of nodes in this map. The range of valid child node indices is 0 to length-1 inclusive.

getNamedItemNS

public Node getNamedItemNS(String namespaceURI,
                           String localName)
Retrieves a node specified by local name and namespace URI.
Documents which do not support the "XML" feature will permit only the DOM Level 1 calls for creating/setting elements and attributes. Hence, if you specify a non-null namespace URI, these DOMs will never find a matching node.

Parameters:
namespaceURI - The namespace URI of the node to retrieve.
localName - The local name of the node to retrieve.
Returns:
A Node (of any type) with the specified local name and namespace URI, or null if they do not identify any node in this map.
Since:
DOM Level 2

setNamedItemNS

public Node setNamedItemNS(Node arg)
                    throws DOMException
Adds a node using its namespaceURI and localName. If a node with that namespace URI and that local name is already present in this map, it is replaced by the new one.

Parameters:
arg - A node to store in this map. The node will later be accessible using the value of its namespaceURI and localName attributes.
Returns:
If the new Node replaces an existing node the replaced Node is returned, otherwise null is returned.
Throws:
DOMException - WRONG_DOCUMENT_ERR: Raised if arg was created from a different document than the one that created this map.
NO_MODIFICATION_ALLOWED_ERR: Raised if this map is readonly.
INUSE_ATTRIBUTE_ERR: Raised if arg is an Attr that is already an attribute of another Element object. The DOM user must explicitly clone Attr nodes to re-use them in other elements.
HIERARCHY_REQUEST_ERR: Raised if an attempt is made to add a node doesn't belong in this NamedNodeMap. Examples would include trying to insert something other than an Attr node into an Element's map of attributes, or a non-Entity node into the DocumentType's map of Entities.
NOT_SUPPORTED_ERR: Always thrown if the current document does not support the "XML" feature, since namespaces were defined by XML.
Since:
DOM Level 2

removeNamedItemNS

public Node removeNamedItemNS(String namespaceURI,
                              String localName)
                       throws DOMException
Removes a node specified by local name and namespace URI. A removed attribute may be known to have a default value when this map contains the attributes attached to an element, as returned by the attributes attribute of the Node interface. If so, an attribute immediately appears containing the default value as well as the corresponding namespace URI, local name, and prefix when applicable.
Documents which do not support the "XML" feature will permit only the DOM Level 1 calls for creating/setting elements and attributes. Hence, if you specify a non-null namespace URI, these DOMs will never find a matching node.

Parameters:
namespaceURI - The namespace URI of the node to remove.
localName - The local name of the node to remove.
Returns:
The node removed from this map if a node with such a local name and namespace URI exists.
Throws:
DOMException - NOT_FOUND_ERR: Raised if there is no node with the specified namespaceURI and localName in this map.
NO_MODIFICATION_ALLOWED_ERR: Raised if this map is readonly.
Since:
DOM Level 2
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Node (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom
Interface Node

All Known Subinterfaces:
Attr, CDATASection, CharacterData, Comment, Document, DocumentFragment, DocumentType, Element, Entity, EntityReference, Notation, ProcessingInstruction, Text
All Known Implementing Classes:
IIOMetadataNode
public interface Node

The Node interface is the primary datatype for the entire Document Object Model. It represents a single node in the document tree. While all objects implementing the Node interface expose methods for dealing with children, not all objects implementing the Node interface may have children. For example, Text nodes may not have children, and adding children to such nodes results in a DOMException being raised.

The attributes nodeName, nodeValue and attributes are included as a mechanism to get at node information without casting down to the specific derived interface. In cases where there is no obvious mapping of these attributes for a specific nodeType (e.g., nodeValue for an Element or attributes for a Comment ), this returns null. Note that the specialized interfaces may contain additional and more convenient mechanisms to get and set the relevant information.

The values of nodeName, nodeValue, and attributes vary according to the node type as follows:

Interface | nodeName | nodeValue | attributes
Attr | name of attribute | value of attribute | null
CDATASection | "#cdata-section" | content of the CDATA Section | null
Comment | "#comment" | content of the comment | null
Document | "#document" | null | null
DocumentFragment | "#document-fragment" | null | null
DocumentType | document type name | null | null
Element | tag name | null | NamedNodeMap
Entity | entity name | null | null
EntityReference | name of entity referenced | null | null
Notation | notation name | null | null
ProcessingInstruction | target | entire content excluding the target | null
Text | "#text" | content of the text node | null

See also the Document Object Model (DOM) Level 2 Core Specification.

Field Summary
static short | ATTRIBUTE_NODE The node is an Attr.
static short | CDATA_SECTION_NODE The node is a CDATASection.
static short | COMMENT_NODE The node is a Comment.
static short | DOCUMENT_FRAGMENT_NODE The node is a DocumentFragment.
static short | DOCUMENT_NODE The node is a Document.
static short | DOCUMENT_TYPE_NODE The node is a DocumentType.
static short | ELEMENT_NODE The node is an Element.
static short | ENTITY_NODE The node is an Entity.
static short | ENTITY_REFERENCE_NODE The node is an EntityReference.
static short | NOTATION_NODE The node is a Notation.
static short | PROCESSING_INSTRUCTION_NODE The node is a ProcessingInstruction.
static short | TEXT_NODE The node is a Text node.
Method Summary
Node | appendChild(Node newChild) Adds the node newChild to the end of the list of children of this node.
Node | cloneNode(boolean deep) Returns a duplicate of this node, i.e., serves as a generic copy constructor for nodes.
NamedNodeMap | getAttributes() A NamedNodeMap containing the attributes of this node (if it is an Element) or null otherwise.
NodeList | getChildNodes() A NodeList that contains all children of this node.
Node | getFirstChild() The first child of this node.
Node | getLastChild() The last child of this node.
String | getLocalName() Returns the local part of the qualified name of this node.
String | getNamespaceURI() The namespace URI of this node, or null if it is unspecified.
Node | getNextSibling() The node immediately following this node.
String | getNodeName() The name of this node, depending on its type; see the table above.
short | getNodeType() A code representing the type of the underlying object, as defined above.
String | getNodeValue() The value of this node, depending on its type; see the table above.
Document | getOwnerDocument() The Document object associated with this node.
Node | getParentNode() The parent of this node.
String | getPrefix() The namespace prefix of this node, or null if it is unspecified.
Node | getPreviousSibling() The node immediately preceding this node.
boolean | hasAttributes() Returns whether this node (if it is an element) has any attributes.
boolean | hasChildNodes() Returns whether this node has any children.
Node | insertBefore(Node newChild, Node refChild) Inserts the node newChild before the existing child node refChild.
boolean | isSupported(String feature, String version) Tests whether the DOM implementation implements a specific feature and that feature is supported by this node.
void | normalize() 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.
Node | removeChild(Node oldChild) Removes the child node indicated by oldChild from the list of children, and returns it.
Node | replaceChild(Node newChild, Node oldChild) Replaces the child node oldChild with newChild in the list of children, and returns the oldChild node.
void | setNodeValue(String nodeValue) The value of this node, depending on its type; see the table above.
void | setPrefix(String prefix) The namespace prefix of this node, or null if it is unspecified.

Field Detail

ELEMENT_NODE

public static final short ELEMENT_NODE
The node is an Element.

See Also:
Constant Field Values

ATTRIBUTE_NODE

public static final short ATTRIBUTE_NODE
The node is an Attr.

See Also:
Constant Field Values

TEXT_NODE

public static final short TEXT_NODE
The node is a Text node.

See Also:
Constant Field Values

CDATA_SECTION_NODE

public static final short CDATA_SECTION_NODE
The node is a CDATASection.

See Also:
Constant Field Values

ENTITY_REFERENCE_NODE

public static final short ENTITY_REFERENCE_NODE
The node is an EntityReference.

See Also:
Constant Field Values

ENTITY_NODE

public static final short ENTITY_NODE
The node is an Entity.

See Also:
Constant Field Values

PROCESSING_INSTRUCTION_NODE

public static final short PROCESSING_INSTRUCTION_NODE
The node is a ProcessingInstruction.

See Also:
Constant Field Values

COMMENT_NODE

public static final short COMMENT_NODE
The node is a Comment.

See Also:
Constant Field Values

DOCUMENT_NODE

public static final short DOCUMENT_NODE
The node is a Document.

See Also:
Constant Field Values

DOCUMENT_TYPE_NODE

public static final short DOCUMENT_TYPE_NODE
The node is a DocumentType.

See Also:
Constant Field Values

DOCUMENT_FRAGMENT_NODE

public static final short DOCUMENT_FRAGMENT_NODE
The node is a DocumentFragment.

See Also:
Constant Field Values

NOTATION_NODE

public static final short NOTATION_NODE
The node is a Notation.

See Also:
Constant Field Values
Method Detail

getNodeName

public String getNodeName()
The name of this node, depending on its type; see the table above.

getNodeValue

public String getNodeValue()
                    throws DOMException
The value of this node, depending on its type; see the table above. When it is defined to be null, setting it has no effect.

Throws:
DOMException - NO_MODIFICATION_ALLOWED_ERR: Raised when the node is readonly.
DOMException - DOMSTRING_SIZE_ERR: Raised when it would return more characters than fit in a DOMString variable on the implementation platform.

setNodeValue

public void setNodeValue(String nodeValue)
                  throws DOMException
The value of this node, depending on its type; see the table above. When it is defined to be null, setting it has no effect.

Throws:
DOMException - NO_MODIFICATION_ALLOWED_ERR: Raised when the node is readonly.
DOMException - DOMSTRING_SIZE_ERR: Raised when it would return more characters than fit in a DOMString variable on the implementation platform.

getNodeType

public short getNodeType()
A code representing the type of the underlying object, as defined above.

getParentNode

public Node getParentNode()
The parent of this node. All nodes, except Attr, Document, DocumentFragment, Entity, and Notation may have a parent. However, if a node has just been created and not yet added to the tree, or if it has been removed from the tree, this is null.

getChildNodes

public NodeList getChildNodes()
A NodeList that contains all children of this node. If there are no children, this is a NodeList containing no nodes.

getFirstChild

public Node getFirstChild()
The first child of this node. If there is no such node, this returns null.

getLastChild

public Node getLastChild()
The last child of this node. If there is no such node, this returns null.

getPreviousSibling

public Node getPreviousSibling()
The node immediately preceding this node. If there is no such node, this returns null.

getNextSibling

public Node getNextSibling()
The node immediately following this node. If there is no such node, this returns null.

getAttributes

public NamedNodeMap getAttributes()
A NamedNodeMap containing the attributes of this node (if it is an Element) or null otherwise.

getOwnerDocument

public Document getOwnerDocument()
The Document object associated with this node. This is also the Document object used to create new nodes. When this node is a Document or a DocumentType which is not used with any Document yet, this is null.

insertBefore

public Node insertBefore(Node newChild,
                         Node refChild)
                  throws DOMException
Inserts the node newChild before the existing child node refChild. If refChild is null, insert newChild at the end of the list of children.
If newChild is a DocumentFragment object, all of its children are inserted, in the same order, before refChild. If the newChild is already in the tree, it is first removed.

Parameters:
newChild - The node to insert.
refChild - The reference node, i.e., the node before which the new node must be inserted.
Returns:
The node being inserted.
Throws:
DOMException - HIERARCHY_REQUEST_ERR: Raised if this node is of a type that does not allow children of the type of the newChild node, or if the node to insert is one of this node's ancestors or this node itself.
WRONG_DOCUMENT_ERR: Raised if newChild was created from a different document than the one that created this node.
NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly or if the parent of the node being inserted is readonly.
NOT_FOUND_ERR: Raised if refChild is not a child of this node.

replaceChild

public Node replaceChild(Node newChild,
                         Node oldChild)
                  throws DOMException
Replaces the child node oldChild with newChild in the list of children, and returns the oldChild node.
If newChild is a DocumentFragment object, oldChild is replaced by all of the DocumentFragment children, which are inserted in the same order. If the newChild is already in the tree, it is first removed.

Parameters:
newChild - The new node to put in the child list.
oldChild - The node being replaced in the list.
Returns:
The node replaced.
Throws:
DOMException - HIERARCHY_REQUEST_ERR: Raised if this node is of a type that does not allow children of the type of the newChild node, or if the node to put in is one of this node's ancestors or this node itself.
WRONG_DOCUMENT_ERR: Raised if newChild was created from a different document than the one that created this node.
NO_MODIFICATION_ALLOWED_ERR: Raised if this node or the parent of the new node is readonly.
NOT_FOUND_ERR: Raised if oldChild is not a child of this node.

removeChild

public Node removeChild(Node oldChild)
                 throws DOMException
Removes the child node indicated by oldChild from the list of children, and returns it.

Parameters:
oldChild - The node being removed.
Returns:
The node removed.
Throws:
DOMException - NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.
NOT_FOUND_ERR: Raised if oldChild is not a child of this node.

appendChild

public Node appendChild(Node newChild)
                 throws DOMException
Adds the node newChild to the end of the list of children of this node. If the newChild is already in the tree, it is first removed.

Parameters:
newChild - The node to add.If it is a DocumentFragment object, the entire contents of the document fragment are moved into the child list of this node
Returns:
The node added.
Throws:
DOMException - HIERARCHY_REQUEST_ERR: Raised if this node is of a type that does not allow children of the type of the newChild node, or if the node to append is one of this node's ancestors or this node itself.
WRONG_DOCUMENT_ERR: Raised if newChild was created from a different document than the one that created this node.
NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly or if the previous parent of the node being inserted is readonly.

hasChildNodes

public boolean hasChildNodes()
Returns whether this node has any children.

Returns:
true if this node has any children, false otherwise.

cloneNode

public Node cloneNode(boolean deep)
Returns a duplicate of this node, i.e., serves as a generic copy constructor for nodes. The duplicate node has no parent; ( parentNode is null.).
Cloning an Element copies all attributes and their values, including those generated by the XML processor to represent defaulted attributes, but this method does not copy any text it contains unless it is a deep clone, since the text is contained in a child Text node. Cloning an Attribute directly, as opposed to be cloned as part of an Element cloning operation, returns a specified attribute ( specified is true). Cloning any other type of node simply returns a copy of this node.
Note that cloning an immutable subtree results in a mutable copy, but the children of an EntityReference clone are readonly . In addition, clones of unspecified Attr nodes are specified. And, cloning Document, DocumentType, Entity, and Notation nodes is implementation dependent.

Parameters:
deep - If true, recursively clone the subtree under the specified node; if false, clone only the node itself (and its attributes, if it is an Element).
Returns:
The duplicate node.

normalize

public void normalize()
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. This can be used to ensure that the DOM view of a document is the same as if it were saved and re-loaded, and is useful when operations (such as XPointer lookups) that depend on a particular document tree structure are to be used.In cases where the document contains CDATASections, the normalize operation alone may not be sufficient, since XPointers do not differentiate between Text nodes and CDATASection nodes.

isSupported

public boolean isSupported(String feature,
                           String version)
Tests whether the DOM implementation implements a specific feature and that feature is supported by this node.

Parameters:
feature - The name of the feature to test. This is the same name which can be passed to the method hasFeature on DOMImplementation.
version - This is the version number of the feature to test. In Level 2, version 1, this is the string "2.0". If the version is not specified, supporting any version of the feature will cause the method to return true.
Returns:
Returns true if the specified feature is supported on this node, false otherwise.
Since:
DOM Level 2

getNamespaceURI

public String getNamespaceURI()
The namespace URI of this node, or null if it is unspecified.
This is not a computed value that is the result of a namespace lookup based on an examination of the namespace declarations in scope. It is merely the namespace URI given at creation time.
For nodes of any type other than ELEMENT_NODE and ATTRIBUTE_NODE and nodes created with a DOM Level 1 method, such as createElement from the Document interface, this is always null.Per the Namespaces in XML Specification an attribute does not inherit its namespace from the element it is attached to. If an attribute is not explicitly given a namespace, it simply has no namespace.

Since:
DOM Level 2

getPrefix

public String getPrefix()
The namespace prefix of this node, or null if it is unspecified.
Note that setting this attribute, when permitted, changes the nodeName attribute, which holds the qualified name, as well as the tagName and name attributes of the Element and Attr interfaces, when applicable.
Note also that changing the prefix of an attribute that is known to have a default value, does not make a new attribute with the default value and the original prefix appear, since the namespaceURI and localName do not change.
For nodes of any type other than ELEMENT_NODE and ATTRIBUTE_NODE and nodes created with a DOM Level 1 method, such as createElement from the Document interface, this is always null.

Throws:
DOMException - INVALID_CHARACTER_ERR: Raised if the specified prefix contains an illegal character, per the XML 1.0 specification .
NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.
NAMESPACE_ERR: Raised if the specified prefix is malformed per the Namespaces in XML specification, if the namespaceURI of this node is null, if the specified prefix is "xml" and the namespaceURI of this node is different from "http://www.w3.org/XML/1998/namespace", if this node is an attribute and the specified prefix is "xmlns" and the namespaceURI of this node is different from " http://www.w3.org/2000/xmlns/", or if this node is an attribute and the qualifiedName of this node is "xmlns" .
Since:
DOM Level 2

setPrefix

public void setPrefix(String prefix)
               throws DOMException
The namespace prefix of this node, or null if it is unspecified.
Note that setting this attribute, when permitted, changes the nodeName attribute, which holds the qualified name, as well as the tagName and name attributes of the Element and Attr interfaces, when applicable.
Note also that changing the prefix of an attribute that is known to have a default value, does not make a new attribute with the default value and the original prefix appear, since the namespaceURI and localName do not change.
For nodes of any type other than ELEMENT_NODE and ATTRIBUTE_NODE and nodes created with a DOM Level 1 method, such as createElement from the Document interface, this is always null.

Throws:
DOMException - INVALID_CHARACTER_ERR: Raised if the specified prefix contains an illegal character, per the XML 1.0 specification .
NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.
NAMESPACE_ERR: Raised if the specified prefix is malformed per the Namespaces in XML specification, if the namespaceURI of this node is null, if the specified prefix is "xml" and the namespaceURI of this node is different from "http://www.w3.org/XML/1998/namespace", if this node is an attribute and the specified prefix is "xmlns" and the namespaceURI of this node is different from " http://www.w3.org/2000/xmlns/", or if this node is an attribute and the qualifiedName of this node is "xmlns" .
Since:
DOM Level 2

getLocalName

public String getLocalName()
Returns the local part of the qualified name of this node.
For nodes of any type other than ELEMENT_NODE and ATTRIBUTE_NODE and nodes created with a DOM Level 1 method, such as createElement from the Document interface, this is always null.

Since:
DOM Level 2

hasAttributes

public boolean hasAttributes()
Returns whether this node (if it is an element) has any attributes.

Returns:
true if this node has any attributes, false otherwise.
Since:
DOM Level 2
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NodeList (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom
Interface NodeList

All Known Implementing Classes:
IIOMetadataNode
public interface NodeList

The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. NodeList objects in the DOM are live.

The items in the NodeList are accessible via an integral index, starting from 0.

See also the Document Object Model (DOM) Level 2 Core Specification.

Method Summary
int | getLength() The number of nodes in the list.
Node | item(int index) Returns the indexth item in the collection.

Method Detail

item

public Node item(int index)
Returns the indexth item in the collection. If index is greater than or equal to the number of nodes in the list, this returns null.

Parameters:
index - Index into the collection.
Returns:
The node at the indexth position in the NodeList, or null if that is not a valid index.

getLength

public int getLength()
The number of nodes in the list. The range of valid child node indices is 0 to length-1 inclusive.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Notation (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom
Interface Notation

All Superinterfaces:
Node
public interface Notation
extends Node

This interface represents a notation declared in the DTD. A notation either declares, by name, the format of an unparsed entity (see section 4.7 of the XML 1.0 specification ), or is used for formal declaration of processing instruction targets (see section 2.6 of the XML 1.0 specification ). The nodeName attribute inherited from Node is set to the declared name of the notation.

The DOM Level 1 does not support editing Notation nodes; they are therefore readonly.

A Notation node does not have any parent.

See also the Document Object Model (DOM) Level 2 Core Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getPublicId() The public identifier of this notation.
String | getSystemId() The system identifier of this notation.
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getPublicId

public String getPublicId()
The public identifier of this notation. If the public identifier was not specified, this is null.

getSystemId

public String getSystemId()
The system identifier of this notation. If the system identifier was not specified, this is null.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


org.w3c.dom (Java 2 Platform SE v1.4.2)

 org.w3c.dom
Interfaces
Attr
CDATASection
CharacterData
Comment
Document
DocumentFragment
DocumentType
DOMImplementation
Element
Entity
EntityReference
NamedNodeMap
Node
NodeList
Notation
ProcessingInstruction
Text
Exceptions
DOMException


org.w3c.dom (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

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.

See:
Description

Interface Summary
Attr | The Attr interface represents an attribute in an Element object.
CDATASection | CDATA sections are used to escape blocks of text containing characters that would otherwise be regarded as markup.
CharacterData | The CharacterData interface extends Node with a set of attributes and methods for accessing character data in the DOM.
Comment | This interface inherits from CharacterData and represents the content of a comment, i.e., all the characters between the starting ' <!--' and ending '-->'.
Document | The Document interface represents the entire HTML or XML document.
DocumentFragment | DocumentFragment is a "lightweight" or "minimal" Document object.
DocumentType | Each Document has a doctype attribute whose value is either null or a DocumentType object.
DOMImplementation | The DOMImplementation interface provides a number of methods for performing operations that are independent of any particular instance of the document object model.
Element | The Element interface represents an element in an HTML or XML document.
Entity | This interface represents an entity, either parsed or unparsed, in an XML document.
EntityReference | EntityReference objects may be inserted into the structure model when an entity reference is in the source document, or when the user wishes to insert an entity reference.
NamedNodeMap | Objects implementing the NamedNodeMap interface are used to represent collections of nodes that can be accessed by name.
Node | The Node interface is the primary datatype for the entire Document Object Model.
NodeList | The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented.
Notation | This interface represents a notation declared in the DTD.
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.
Text | The Text interface inherits from CharacterData and represents the textual content (termed character data in XML) of an Element or Attr.

Exception Summary
DOMException DOM operations only raise exceptions in "exceptional" circumstances, i.e., when an operation is impossible to perform (either for logical reasons, because data is lost, or because the implementation has become unstable).

Package org.w3c.dom Description

Provides the interfaces for the Document Object Model (DOM) which is a component API of the Java API for XML Processing. The Document Object Model Level 2 Core API allows programs to dynamically access and update the content and structure of documents. See the specification for more information.

Since:
JDK1.4
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


org.w3c.dom Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package org.w3c.dom

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class java.lang.Throwable (implements java.io.Serializable)
      • class java.lang.Exception
        • class java.lang.RuntimeException
          • class org.w3c.dom.DOMException

Interface Hierarchy

  • interface org.w3c.dom.DOMImplementation
  • interface org.w3c.dom.NamedNodeMap
  • interface org.w3c.dom.Node
    • interface org.w3c.dom.Attr
    • interface org.w3c.dom.CharacterData
      • interface org.w3c.dom.Comment
      • interface org.w3c.dom.Text
        • interface org.w3c.dom.CDATASection
    • interface org.w3c.dom.Document
    • interface org.w3c.dom.DocumentFragment
    • interface org.w3c.dom.DocumentType
    • interface org.w3c.dom.Element
    • interface org.w3c.dom.Entity
    • interface org.w3c.dom.EntityReference
    • interface org.w3c.dom.Notation
    • interface org.w3c.dom.ProcessingInstruction
  • interface org.w3c.dom.NodeList
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package org.w3c.dom (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
org.w3c.dom

Packages that use org.w3c.dom
javax.imageio.metadata | A package of the Java Image I/O API dealing with reading and writing metadata.
javax.xml.parsers | Provides classes allowing the processing of XML documents.
javax.xml.transform.dom | This package implements DOM-specific transformation APIs.
org.w3c.dom | Provides the interfaces for the Document Object Model (DOM) which is a component API of the Java API for XML Processing.

Classes in org.w3c.dom used by javax.imageio.metadata
Attr
The Attr interface represents an attribute in an Element object.
Document
The Document interface represents the entire HTML or XML document.
DOMException
DOM operations only raise exceptions in "exceptional" circumstances, i.e., when an operation is impossible to perform (either for logical reasons, because data is lost, or because the implementation has become unstable).
Element
The Element interface represents an element in an HTML or XML document.
NamedNodeMap
Objects implementing the NamedNodeMap interface are used to represent collections of nodes that can be accessed by name.
Node
The Node interface is the primary datatype for the entire Document Object Model.
NodeList
The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented.

Classes in org.w3c.dom used by javax.xml.parsers
Document
The Document interface represents the entire HTML or XML document.
DOMImplementation
The DOMImplementation interface provides a number of methods for performing operations that are independent of any particular instance of the document object model.

Classes in org.w3c.dom used by javax.xml.transform.dom
Node
The Node interface is the primary datatype for the entire Document Object Model.

Classes in org.w3c.dom used by org.w3c.dom
Attr
The Attr interface represents an attribute in an Element object.
CDATASection
CDATA sections are used to escape blocks of text containing characters that would otherwise be regarded as markup.
CharacterData
The CharacterData interface extends Node with a set of attributes and methods for accessing character data in the DOM.
Comment
This interface inherits from CharacterData and represents the content of a comment, i.e., all the characters between the starting ' <!--' and ending '-->'.
Document
The Document interface represents the entire HTML or XML document.
DocumentFragment
DocumentFragment is a "lightweight" or "minimal" Document object.
DocumentType
Each Document has a doctype attribute whose value is either null or a DocumentType object.
DOMException
DOM operations only raise exceptions in "exceptional" circumstances, i.e., when an operation is impossible to perform (either for logical reasons, because data is lost, or because the implementation has become unstable).
DOMImplementation
The DOMImplementation interface provides a number of methods for performing operations that are independent of any particular instance of the document object model.
Element
The Element interface represents an element in an HTML or XML document.
EntityReference
EntityReference objects may be inserted into the structure model when an entity reference is in the source document, or when the user wishes to insert an entity reference.
NamedNodeMap
Objects implementing the NamedNodeMap interface are used to represent collections of nodes that can be accessed by name.
Node
The Node interface is the primary datatype for the entire Document Object Model.
NodeList
The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented.
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.
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
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


ProcessingInstruction (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom
Interface ProcessingInstruction

All Superinterfaces:
Node
public interface ProcessingInstruction
extends Node

The ProcessingInstruction interface represents a "processing instruction", used in XML as a way to keep processor-specific information in the text of the document.

See also the Document Object Model (DOM) Level 2 Core Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getData() The content of this processing instruction.
String | getTarget() The target of this processing instruction.
void | setData(String data) The content of this processing instruction.
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getTarget

public String getTarget()
The target of this processing instruction. XML defines this as being the first token following the markup that begins the processing instruction.

getData

public String getData()
The content of this processing instruction. This is from the first non white space character after the target to the character immediately preceding the ?>.

Throws:
DOMException - NO_MODIFICATION_ALLOWED_ERR: Raised when the node is readonly.

setData

public void setData(String data)
             throws DOMException
The content of this processing instruction. This is from the first non white space character after the target to the character immediately preceding the ?>.

Throws:
DOMException - NO_MODIFICATION_ALLOWED_ERR: Raised when the node is readonly.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Text (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom
Interface Text

All Superinterfaces:
CharacterData, Node
All Known Subinterfaces:
CDATASection
public interface Text
extends CharacterData

The Text interface inherits from CharacterData and represents the textual content (termed character data in XML) of an Element or Attr. If there is no markup inside an element's content, the text is contained in a single object implementing the Text interface that is the only child of the element. If there is markup, it is parsed into the information items (elements, comments, etc.) and Text nodes that form the list of children of the element.

When a document is first made available via the DOM, there is only one Text node for each block of text. Users may create adjacent Text nodes that represent the contents of a given element without any intervening markup, but should be aware that there is no way to represent the separations between these nodes in XML or HTML, so they will not (in general) persist between DOM editing sessions. The normalize() method on Node merges any such adjacent Text objects into a single node for each block of text.

See also the Document Object Model (DOM) Level 2 Core Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
 Text splitText(int offset)
Breaks this node into two nodes at the specified offset, keeping both in the tree as siblings.
Methods inherited from interface org.w3c.dom.CharacterData
appendData, deleteData, getData, getLength, insertData, replaceData, setData, substringData
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

splitText

public Text splitText(int offset)
               throws DOMException
Breaks this node into two nodes at the specified offset, keeping both in the tree as siblings. After being split, this node will contain all the content up to the offset point. A new node of the same type, which contains all the content at and after the offset point, is returned. If the original node had a parent node, the new node is inserted as the next sibling of the original node. When the offset is equal to the length of this node, the new node has no data.

Parameters:
offset - The 16-bit unit offset at which to split, starting from 0.
Returns:
The new node, of the same type as this node.
Throws:
DOMException - INDEX_SIZE_ERR: Raised if the specified offset is negative or greater than the number of 16-bit units in data.
NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Uses of Interface org.w3c.dom.Attr (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.Attr

Packages that use Attr
javax.imageio.metadata | A package of the Java Image I/O API dealing with reading and writing metadata.
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 javax.imageio.metadata

Methods in javax.imageio.metadata that return Attr
Attr | IIOMetadataNode.getAttributeNode(String name)
Attr | IIOMetadataNode.getAttributeNodeNS(String namespaceURI, String localName) Equivalent to getAttributeNode(localName).
Attr | IIOMetadataNode.setAttributeNode(Attr newAttr)
Attr | IIOMetadataNode.setAttributeNodeNS(Attr newAttr) Equivalent to setAttributeNode(newAttr).
Attr | IIOMetadataNode.removeAttributeNode(Attr oldAttr)

Methods in javax.imageio.metadata with parameters of type Attr
Attr | IIOMetadataNode.setAttributeNode(Attr newAttr)
Attr | IIOMetadataNode.setAttributeNodeNS(Attr newAttr) Equivalent to setAttributeNode(newAttr).
Attr | IIOMetadataNode.removeAttributeNode(Attr oldAttr)

Uses of Attr in org.w3c.dom

Methods in org.w3c.dom that return Attr
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.setAttributeNode(Attr newAttr) Adds a new attribute node.
Attr | Element.removeAttributeNode(Attr oldAttr) Removes the specified attribute node.
Attr | Element.getAttributeNodeNS(String namespaceURI, String localName) Retrieves an Attr node by local name and namespace URI.
Attr | Element.setAttributeNodeNS(Attr newAttr) Adds a new attribute.

Methods in org.w3c.dom with parameters of type Attr
Attr | Element.setAttributeNode(Attr newAttr) Adds a new attribute node.
Attr | Element.removeAttributeNode(Attr oldAttr) Removes the specified attribute node.
Attr | Element.setAttributeNodeNS(Attr newAttr) Adds a new attribute.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.w3c.dom.CDATASection (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.CDATASection

Packages that use CDATASection
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
 CDATASection Document.createCDATASection(String data)
Creates a CDATASection node whose value is the specified string.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.w3c.dom.CharacterData (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.CharacterData

Packages that use CharacterData
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
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
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.w3c.dom.Comment (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.Comment

Packages that use Comment
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
 Comment Document.createComment(String data)
Creates a Comment node given the specified string.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.w3c.dom.Document (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.Document

Packages that use Document
javax.imageio.metadata | A package of the Java Image I/O API dealing with reading and writing metadata.
javax.xml.parsers | Provides classes allowing the processing of XML documents.
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 Document in javax.imageio.metadata

Methods in javax.imageio.metadata that return Document
 Document IIOMetadataNode.getOwnerDocument()
Returns null, since IIOMetadataNodes do not belong to any Document.

Uses of Document in javax.xml.parsers

Methods in javax.xml.parsers that return Document
Document | DocumentBuilder.parse(InputStream is) Parse the content of the given InputStream as an XML document and return a new DOM Document object.
Document | DocumentBuilder.parse(InputStream is, String systemId) Parse the content of the given InputStream as an XML document and return a new DOM Document object.
Document | DocumentBuilder.parse(String uri) Parse the content of the given URI as an XML document and return a new DOM Document object.
Document | DocumentBuilder.parse(File f) Parse the content of the given file as an XML document and return a new DOM Document object.
abstract Document | DocumentBuilder.parse(InputSource is) Parse the content of the given input source as an XML document and return a new DOM Document object.
abstract Document | DocumentBuilder.newDocument() Obtain a new instance of a DOM Document object to build a DOM tree with.

Uses of Document in org.w3c.dom

Methods in org.w3c.dom that return Document
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.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.w3c.dom.DocumentFragment (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.DocumentFragment

Packages that use DocumentFragment
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 DocumentFragment in org.w3c.dom

Methods in org.w3c.dom that return DocumentFragment
 DocumentFragment Document.createDocumentFragment()
Creates an empty DocumentFragment object.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.w3c.dom.DocumentType (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.DocumentType

Packages that use DocumentType
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
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
 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
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.w3c.dom.DOMException (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.w3c.dom.DOMException

Packages that use DOMException
javax.imageio.metadata | A package of the Java Image I/O API dealing with reading and writing metadata.
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 DOMException in javax.imageio.metadata

Methods in javax.imageio.metadata that throw DOMException
String | IIOMetadataNode.getNodeValue()
void | IIOMetadataNode.setNodeValue(String nodeValue)
String | IIOMetadataNode.getNamespaceURI() Returns null, since namespaces are not supported.
Attr | IIOMetadataNode.setAttributeNode(Attr newAttr)

Uses of DOMException in org.w3c.dom

Methods in org.w3c.dom that throw DOMException
void | ProcessingInstruction.setData(String data) The content of this processing instruction.
String | CharacterData.getData() The character data of the node that implements this interface.
void | CharacterData.setData(String data) The character data of the node that implements this interface.
String | CharacterData.substringData(int offset, int count) Extracts a range of data from the node.
void | CharacterData.appendData(String arg) Append the string to the end of the character data of the node.
void | CharacterData.insertData(int offset, String arg) Insert a string at the specified 16-bit unit offset.
void | CharacterData.deleteData(int offset, int count) Remove a range of 16-bit units from the 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.splitText(int offset) Breaks this node into two nodes at the specified offset, keeping both in the tree as siblings.
DocumentType | DOMImplementation.createDocumentType(String qualifiedName, String publicId, String systemId) Creates an empty DocumentType node.
Document | DOMImplementation.createDocument(String namespaceURI, String qualifiedName, DocumentType doctype) Creates a DOM Document object of the specified type with its document element.
Element | Document.createElement(String tagName) Creates an element of the type specified.
CDATASection | Document.createCDATASection(String data) Creates a CDATASection node whose value is the specified string.
ProcessingInstruction | Document.createProcessingInstruction(String target, String data) Creates a ProcessingInstruction node given the specified name and data strings.
Attr | Document.createAttribute(String name) Creates an Attr of the given name.
EntityReference | Document.createEntityReference(String name) Creates an EntityReference object.
Node | Document.importNode(Node importedNode, boolean deep) Imports a node from another document to this document.
Element | Document.createElementNS(String namespaceURI, String qualifiedName) Creates an element of the given qualified name and namespace URI.
Attr | Document.createAttributeNS(String namespaceURI, String qualifiedName) Creates an attribute of the given qualified name and namespace URI.
Node | NamedNodeMap.setNamedItem(Node arg) Adds a node using its nodeName attribute.
Node | NamedNodeMap.removeNamedItem(String name) Removes a node specified by name.
Node | NamedNodeMap.setNamedItemNS(Node arg) Adds a node using its namespaceURI and localName.
Node | NamedNodeMap.removeNamedItemNS(String namespaceURI, String localName) Removes a node specified by local name and namespace URI.
void | Attr.setValue(String value) On retrieval, the value of the attribute is returned as a string.
String | Node.getNodeValue() The value of this node, depending on its type; see the table above.
void | Node.setNodeValue(String nodeValue) The value of this node, depending on its type; see the table above.
Node | Node.insertBefore(Node newChild, Node refChild) Inserts the node newChild before the existing child node refChild.
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 | Node.removeChild(Node oldChild) Removes the child node indicated by oldChild from the list of children, and returns it.
Node | Node.appendChild(Node newChild) Adds the node newChild to the end of the list of children of this node.
void | Node.setPrefix(String prefix) The namespace prefix of this node, or null if it is unspecified.
void | Element.setAttribute(String name, String value) Adds a new attribute.
void | Element.removeAttribute(String name) Removes an attribute by name.
Attr | Element.setAttributeNode(Attr newAttr) Adds a new attribute node.
Attr | Element.removeAttributeNode(Attr oldAttr) Removes the specified attribute node.
void | Element.setAttributeNS(String namespaceURI, String qualifiedName, String value) Adds a new attribute.
void | Element.removeAttributeNS(String namespaceURI, String localName) Removes an attribute by local name and namespace URI.
Attr | Element.setAttributeNodeNS(Attr newAttr) Adds a new attribute.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.w3c.dom.DOMImplementation (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.DOMImplementation

Packages that use DOMImplementation
javax.xml.parsers | Provides classes allowing the processing of XML documents.
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 DOMImplementation in javax.xml.parsers

Methods in javax.xml.parsers that return DOMImplementation
abstract  DOMImplementation DocumentBuilder.getDOMImplementation()
Obtain an instance of a DOMImplementation object.

Uses of DOMImplementation in org.w3c.dom

Methods in org.w3c.dom that return DOMImplementation
 DOMImplementation Document.getImplementation()
The DOMImplementation object that handles this document.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.w3c.dom.Element (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.Element

Packages that use Element
javax.imageio.metadata | A package of the Java Image I/O API dealing with reading and writing metadata.
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 Element in javax.imageio.metadata

Classes in javax.imageio.metadata that implement Element
 class IIOMetadataNode
A class representing a node in a meta-data tree, which implements the org.w3c.dom.Element interface and additionally allows for the storage of non-textual objects via the getUserObject and setUserObject methods.

Uses of Element in org.w3c.dom

Methods in org.w3c.dom that return Element
Element | Document.getDocumentElement() This is a convenience attribute that allows direct access to the child node that is the root element of the document.
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.getElementById(String elementId) Returns the Element whose ID is given by elementId.
Element | Attr.getOwnerElement() The Element node this attribute is attached to or null if this attribute is not in use.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.w3c.dom.Entity (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.Entity

No usage of org.w3c.dom.Entity

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.w3c.dom.EntityReference (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.EntityReference

Packages that use EntityReference
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
 EntityReference Document.createEntityReference(String name)
Creates an EntityReference object.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.w3c.dom.NamedNodeMap (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.NamedNodeMap

Packages that use NamedNodeMap
javax.imageio.metadata | A package of the Java Image I/O API dealing with reading and writing metadata.
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 javax.imageio.metadata

Methods in javax.imageio.metadata that return NamedNodeMap
 NamedNodeMap IIOMetadataNode.getAttributes()

Uses of NamedNodeMap in org.w3c.dom

Methods in org.w3c.dom that return NamedNodeMap
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.
NamedNodeMap | Node.getAttributes() A NamedNodeMap containing the attributes of this node (if it is an Element) or null otherwise.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.w3c.dom.Node (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.Node

Packages that use Node
javax.imageio.metadata | A package of the Java Image I/O API dealing with reading and writing metadata.
javax.xml.transform.dom | This package implements DOM-specific transformation APIs.
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 Node in javax.imageio.metadata

Classes in javax.imageio.metadata that implement Node
 class IIOMetadataNode
A class representing a node in a meta-data tree, which implements the org.w3c.dom.Element interface and additionally allows for the storage of non-textual objects via the getUserObject and setUserObject methods.

Fields in javax.imageio.metadata declared as Node
protected  Node IIOInvalidTreeException.offendingNode
The Node that led to the parsing error, or null.

Methods in javax.imageio.metadata that return Node
Node | IIOMetadataNode.getParentNode() Returns the parent of this node.
Node | IIOMetadataNode.getFirstChild() Returns the first child of this node, or null if the node has no children.
Node | IIOMetadataNode.getLastChild() Returns the last child of this node, or null if the node has no children.
Node | IIOMetadataNode.getPreviousSibling() Returns the previous sibling of this node, or null if this node has no previous sibling.
Node | IIOMetadataNode.getNextSibling() Returns the next sibling of this node, or null if the node has no next sibling.
Node | IIOMetadataNode.insertBefore(Node newChild, Node refChild) Inserts the node newChild before the existing child node refChild.
Node | IIOMetadataNode.replaceChild(Node newChild, Node oldChild) Replaces the child node oldChild with newChild in the list of children, and returns the oldChild node.
Node | IIOMetadataNode.removeChild(Node oldChild) Removes the child node indicated by oldChild from the list of children, and returns it.
Node | IIOMetadataNode.appendChild(Node newChild) Adds the node newChild to the end of the list of children of this node.
Node | IIOMetadataNode.cloneNode(boolean deep) Returns a duplicate of this node.
Node | IIOMetadataNode.item(int index)
Node | IIOInvalidTreeException.getOffendingNode() Returns the Node that caused the error in parsing.
abstract Node | IIOMetadata.getAsTree(String formatName) Returns an XML DOM Node object that represents the root of a tree of metadata contained within this object according to the conventions defined by a given metadata format.

Methods in javax.imageio.metadata with parameters of type Node
Node | IIOMetadataNode.insertBefore(Node newChild, Node refChild) Inserts the node newChild before the existing child node refChild.
Node | IIOMetadataNode.replaceChild(Node newChild, Node oldChild) Replaces the child node oldChild with newChild in the list of children, and returns the oldChild node.
Node | IIOMetadataNode.removeChild(Node oldChild) Removes the child node indicated by oldChild from the list of children, and returns it.
Node | IIOMetadataNode.appendChild(Node newChild) Adds the node newChild to the end of the list of children of this node.
abstract void | IIOMetadata.mergeTree(String formatName, Node root) Alters the internal state of this IIOMetadata object from a tree of XML DOM Nodes whose syntax is defined by the given metadata format.
void | IIOMetadata.setFromTree(String formatName, Node root) Sets the internal state of this IIOMetadata object from a tree of XML DOM Nodes whose syntax is defined by the given metadata format.

Constructors in javax.imageio.metadata with parameters of type Node
IIOInvalidTreeException(String message, Node offendingNode)
Constructs an IIOInvalidTreeException with a message string and a reference to the Node that caused the parsing error.
IIOInvalidTreeException(String message, Throwable cause, Node offendingNode)
Constructs an IIOInvalidTreeException with a message string, a reference to an exception that caused this exception, and a reference to the Node that caused the parsing error.

Uses of Node in javax.xml.transform.dom

Methods in javax.xml.transform.dom that return Node
Node | DOMSource.getNode() Get the node that represents a Source DOM tree.
Node | DOMResult.getNode() Get the node that will contain the result DOM tree.
Node | DOMLocator.getOriginatingNode() Return the node where the event occurred.

Methods in javax.xml.transform.dom with parameters of type Node
void | DOMSource.setNode(Node node) Set the node that will represents a Source DOM tree.
void | DOMResult.setNode(Node node) Set the node that will contain the result DOM tree.

Constructors in javax.xml.transform.dom with parameters of type Node
DOMSource(Node n)
Create a new input source with a DOM node.
DOMSource(Node node, String systemID)
Create a new input source with a DOM node, and with the system ID also passed in as the base URI.
DOMResult(Node node)
Use a DOM node to create a new output target.
DOMResult(Node node, String systemID)
Create a new output target with a DOM node.

Uses of Node in org.w3c.dom

Subinterfaces of Node in org.w3c.dom
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 an entity, either parsed or unparsed, in an XML document.
interface | EntityReference EntityReference objects may be inserted into the structure model when an entity reference is in the source document, or when the user wishes to insert an entity reference.
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
Node | Document.importNode(Node importedNode, boolean deep) Imports a node from another document to this document.
Node | NamedNodeMap.getNamedItem(String name) Retrieves a node specified by name.
Node | NamedNodeMap.setNamedItem(Node arg) Adds a node using its nodeName attribute.
Node | NamedNodeMap.removeNamedItem(String name) Removes a node specified by name.
Node | NamedNodeMap.item(int index) Returns the indexth item in the map.
Node | NamedNodeMap.getNamedItemNS(String namespaceURI, String localName) Retrieves a node specified by local name and namespace URI.
Node | NamedNodeMap.setNamedItemNS(Node arg) Adds a node using its namespaceURI and localName.
Node | NamedNodeMap.removeNamedItemNS(String namespaceURI, String localName) Removes a node specified by local name and namespace URI.
Node | NodeList.item(int index) Returns the indexth item in the collection.
Node | Node.getParentNode() The parent of this node.
Node | Node.getFirstChild() The first child of this node.
Node | Node.getLastChild() The last child of this node.
Node | Node.getPreviousSibling() The node immediately preceding this node.
Node | Node.getNextSibling() The node immediately following this node.
Node | Node.insertBefore(Node newChild, Node refChild) Inserts the node newChild before the existing child node refChild.
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 | Node.removeChild(Node oldChild) Removes the child node indicated by oldChild from the list of children, and returns it.
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.

Methods in org.w3c.dom with parameters of type Node
Node | Document.importNode(Node importedNode, boolean deep) Imports a node from another document to this document.
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.
Node | Node.insertBefore(Node newChild, Node refChild) Inserts the node newChild before the existing child node refChild.
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 | Node.removeChild(Node oldChild) Removes the child node indicated by oldChild from the list of children, and returns it.
Node | Node.appendChild(Node newChild) Adds the node newChild to the end of the list of children of this node.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.w3c.dom.NodeList (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.NodeList

Packages that use NodeList
javax.imageio.metadata | A package of the Java Image I/O API dealing with reading and writing metadata.
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 NodeList in javax.imageio.metadata

Classes in javax.imageio.metadata that implement NodeList
 class IIOMetadataNode
A class representing a node in a meta-data tree, which implements the org.w3c.dom.Element interface and additionally allows for the storage of non-textual objects via the getUserObject and setUserObject methods.

Methods in javax.imageio.metadata that return NodeList
NodeList | IIOMetadataNode.getChildNodes()
NodeList | IIOMetadataNode.getElementsByTagName(String name)
NodeList | IIOMetadataNode.getElementsByTagNameNS(String namespaceURI, String localName) Equivalent to getElementsByTagName(localName).

Uses of NodeList in org.w3c.dom

Methods in org.w3c.dom that return NodeList
NodeList | Document.getElementsByTagName(String tagname) Returns a NodeList of all the Elements with a given tag name in the order in which they are encountered in a preorder traversal of the Document tree.
NodeList | Document.getElementsByTagNameNS(String namespaceURI, String localName) Returns a NodeList of all the Elements with a given local name and namespace URI in the order in which they are encountered in a preorder traversal of the Document tree.
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 the order in which they are encountered in a preorder traversal of this Element tree.
NodeList | Element.getElementsByTagNameNS(String namespaceURI, String localName) Returns a NodeList of all the descendant Elements with a given local name and namespace URI in the order in which they are encountered in a preorder traversal of this Element tree.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.w3c.dom.Notation (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.Notation

No usage of org.w3c.dom.Notation

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.w3c.dom.ProcessingInstruction (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.ProcessingInstruction

Packages that use ProcessingInstruction
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
 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
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.w3c.dom.Text (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.Text

Packages that use Text
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
 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
Text | Text.splitText(int offset) Breaks this node into two nodes at the specified offset, keeping both in the tree as siblings.
Text | Document.createTextNode(String data) Creates a Text node given the specified string.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


AttributeList (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.xml.sax
Interface AttributeList

All Known Implementing Classes:
AttributeListImpl
Deprecated. This interface has been replaced by the SAX2 Attributes interface, which includes Namespace support.

public interface AttributeList

Interface for an element's attribute specifications.

This module, both source code and documentation, is in the Public Domain, and comes with NO WARRANTY.

This is the original SAX1 interface for reporting an element's attributes. Unlike the new Attributes interface, it does not support Namespace-related information.

When an attribute list is supplied as part of a startElement event, the list will return valid results only during the scope of the event; once the event handler returns control to the parser, the attribute list is invalid. To save a persistent copy of the attribute list, use the SAX1 AttributeListImpl helper class.

An attribute list includes only attributes that have been specified or defaulted: #IMPLIED attributes will not be included.

There are two ways for the SAX application to obtain information from the AttributeList. First, it can iterate through the entire list:

 public void startElement (String name, AttributeList atts) {
   for (int i = 0; i < atts.getLength(); i++) {
     String name = atts.getName(i);
     String type = atts.getType(i);
     String value = atts.getValue(i);
     [...]
   }
 }

(Note that the result of getLength() will be zero if there are no attributes.)

As an alternative, the application can request the value or type of specific attributes:

 public void startElement (String name, AttributeList atts) {
   String identifier = atts.getValue("id");
   String label = atts.getValue("label");
   [...]
 }

Since:
SAX 1.0
See Also:
startElement, AttributeListImpl

Method Summary
int | getLength() Deprecated. Return the number of attributes in this list.
String | getName(int i) Deprecated. Return the name of an attribute in this list (by position).
String | getType(int i) Deprecated. Return the type of an attribute in the list (by position).
String | getType(String name) Deprecated. Return the type of an attribute in the list (by name).
String | getValue(int i) Deprecated. Return the value of an attribute in the list (by position).
String | getValue(String name) Deprecated. Return the value of an attribute in the list (by name).

Method Detail

getLength

public int getLength()
Deprecated.
Return the number of attributes in this list.

The SAX parser may provide attributes in any arbitrary order, regardless of the order in which they were declared or specified. The number of attributes may be zero.

Returns:
The number of attributes in the list.

getName

public String getName(int i)
Deprecated.
Return the name of an attribute in this list (by position).

The names must be unique: the SAX parser shall not include the same attribute twice. Attributes without values (those declared #IMPLIED without a value specified in the start tag) will be omitted from the list.

If the attribute name has a namespace prefix, the prefix will still be attached.

Parameters:
i - The index of the attribute in the list (starting at 0).
Returns:
The name of the indexed attribute, or null if the index is out of range.
See Also:
getLength()

getType

public String getType(int i)
Deprecated.
Return the type of an attribute in the list (by position).

The attribute type is one of the strings "CDATA", "ID", "IDREF", "IDREFS", "NMTOKEN", "NMTOKENS", "ENTITY", "ENTITIES", or "NOTATION" (always in upper case).

If the parser has not read a declaration for the attribute, or if the parser does not report attribute types, then it must return the value "CDATA" as stated in the XML 1.0 Recommentation (clause 3.3.3, "Attribute-Value Normalization").

For an enumerated attribute that is not a notation, the parser will report the type as "NMTOKEN".

Parameters:
i - The index of the attribute in the list (starting at 0).
Returns:
The attribute type as a string, or null if the index is out of range.
See Also:
getLength(), getType(java.lang.String)

getValue

public String getValue(int i)
Deprecated.
Return the value of an attribute in the list (by position).

If the attribute value is a list of tokens (IDREFS, ENTITIES, or NMTOKENS), the tokens will be concatenated into a single string separated by whitespace.

Parameters:
i - The index of the attribute in the list (starting at 0).
Returns:
The attribute value as a string, or null if the index is out of range.
See Also:
getLength(), getValue(java.lang.String)

getType

public String getType(String name)
Deprecated.
Return the type of an attribute in the list (by name).

The return value is the same as the return value for getType(int).

If the attribute name has a namespace prefix in the document, the application must include the prefix here.

Parameters:
name - The name of the attribute.
Returns:
The attribute type as a string, or null if no such attribute exists.
See Also:
getType(int)

getValue

public String getValue(String name)
Deprecated.
Return the value of an attribute in the list (by name).

The return value is the same as the return value for getValue(int).

If the attribute name has a namespace prefix in the document, the application must include the prefix here.

Returns:
The attribute value as a string, or null if no such attribute exists.
See Also:
getValue(int)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Attributes (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.xml.sax
Interface Attributes

All Known Implementing Classes:
AttributesImpl
public interface Attributes

Interface for a list of XML attributes.

This module, both source code and documentation, is in the Public Domain, and comes with NO WARRANTY.

This interface allows access to a list of attributes in three different ways:

  1. by attribute index;
  2. by Namespace-qualified name; or
  3. by qualified (prefixed) name.

The list will not contain attributes that were declared #IMPLIED but not specified in the start tag. It will also not contain attributes used as Namespace declarations (xmlns*) unless the http://xml.org/sax/features/namespace-prefixes feature is set to true (it is false by default).

If the namespace-prefixes feature (see above) is false, access by qualified name may not be available; if the http://xml.org/sax/features/namespaces feature is false, access by Namespace-qualified names may not be available.

This interface replaces the now-deprecated SAX1 AttributeList interface, which does not contain Namespace support. In addition to Namespace support, it adds the getIndex methods (below).

The order of attributes in the list is unspecified, and will vary from implementation to implementation.

Since:
SAX 2.0
See Also:
AttributeListImpl

Method Summary
int | getIndex(String qName) Look up the index of an attribute by XML 1.0 qualified name.
int | getIndex(String uri, String localName) Look up the index of an attribute by Namespace name.
int | getLength() Return the number of attributes in the list.
String | getLocalName(int index) Look up an attribute's local name by index.
String | getQName(int index) Look up an attribute's XML 1.0 qualified name by index.
String | getType(int index) Look up an attribute's type by index.
String | getType(String qName) Look up an attribute's type by XML 1.0 qualified name.
String | getType(String uri, String localName) Look up an attribute's type by Namespace name.
String | getURI(int index) Look up an attribute's Namespace URI by index.
String | getValue(int index) Look up an attribute's value by index.
String | getValue(String qName) Look up an attribute's value by XML 1.0 qualified name.
String | getValue(String uri, String localName) Look up an attribute's value by Namespace name.

Method Detail

getLength

public int getLength()
Return the number of attributes in the list.

Once you know the number of attributes, you can iterate through the list.

Returns:
The number of attributes in the list.
See Also:
getURI(int), getLocalName(int), getQName(int), getType(int), getValue(int)

getURI

public String getURI(int index)
Look up an attribute's Namespace URI by index.

Parameters:
index - The attribute index (zero-based).
Returns:
The Namespace URI, or the empty string if none is available, or null if the index is out of range.
See Also:
getLength()

getLocalName

public String getLocalName(int index)
Look up an attribute's local name by index.

Parameters:
index - The attribute index (zero-based).
Returns:
The local name, or the empty string if Namespace processing is not being performed, or null if the index is out of range.
See Also:
getLength()

getQName

public String getQName(int index)
Look up an attribute's XML 1.0 qualified name by index.

Parameters:
index - The attribute index (zero-based).
Returns:
The XML 1.0 qualified name, or the empty string if none is available, or null if the index is out of range.
See Also:
getLength()

getType

public String getType(int index)
Look up an attribute's type by index.

The attribute type is one of the strings "CDATA", "ID", "IDREF", "IDREFS", "NMTOKEN", "NMTOKENS", "ENTITY", "ENTITIES", or "NOTATION" (always in upper case).

If the parser has not read a declaration for the attribute, or if the parser does not report attribute types, then it must return the value "CDATA" as stated in the XML 1.0 Recommentation (clause 3.3.3, "Attribute-Value Normalization").

For an enumerated attribute that is not a notation, the parser will report the type as "NMTOKEN".

Parameters:
index - The attribute index (zero-based).
Returns:
The attribute's type as a string, or null if the index is out of range.
See Also:
getLength()

getValue

public String getValue(int index)
Look up an attribute's value by index.

If the attribute value is a list of tokens (IDREFS, ENTITIES, or NMTOKENS), the tokens will be concatenated into a single string with each token separated by a single space.

Parameters:
index - The attribute index (zero-based).
Returns:
The attribute's value as a string, or null if the index is out of range.
See Also:
getLength()

getIndex

public int getIndex(String uri,
                    String localName)
Look up the index of an attribute by Namespace name.

Parameters:
uri - The Namespace URI, or the empty string if the name has no Namespace URI.
localName - The attribute's local name.
Returns:
The index of the attribute, or -1 if it does not appear in the list.

getIndex

public int getIndex(String qName)
Look up the index of an attribute by XML 1.0 qualified name.

Parameters:
qName - The qualified (prefixed) name.
Returns:
The index of the attribute, or -1 if it does not appear in the list.

getType

public String getType(String uri,
                      String localName)
Look up an attribute's type by Namespace name.

See getType(int) for a description of the possible types.

Parameters:
uri - The Namespace URI, or the empty String if the name has no Namespace URI.
localName - The local name of the attribute.
Returns:
The attribute type as a string, or null if the attribute is not in the list or if Namespace processing is not being performed.

getType

public String getType(String qName)
Look up an attribute's type by XML 1.0 qualified name.

See getType(int) for a description of the possible types.

Parameters:
qName - The XML 1.0 qualified name.
Returns:
The attribute type as a string, or null if the attribute is not in the list or if qualified names are not available.

getValue

public String getValue(String uri,
                       String localName)
Look up an attribute's value by Namespace name.

See getValue(int) for a description of the possible values.

Parameters:
uri - The Namespace URI, or the empty String if the name has no Namespace URI.
localName - The local name of the attribute.
Returns:
The attribute value as a string, or null if the attribute is not in the list.

getValue

public String getValue(String qName)
Look up an attribute's value by XML 1.0 qualified name.

See getValue(int) for a description of the possible values.

Parameters:
qName - The XML 1.0 qualified name.
Returns:
The attribute value as a string, or null if the attribute is not in the list or if qualified names are not available.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ContentHandler (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.xml.sax
Interface ContentHandler

All Known Subinterfaces:
TemplatesHandler, TransformerHandler
All Known Implementing Classes:
DefaultHandler, XMLFilterImpl, XMLReaderAdapter
public interface ContentHandler

Receive notification of the logical content of a document.

This module, both source code and documentation, is in the Public Domain, and comes with NO WARRANTY.

This is the main interface that most SAX applications implement: if the application needs to be informed of basic parsing events, it implements this interface and registers an instance with the SAX parser using the setContentHandler method. The parser uses the instance to report basic document-related events like the start and end of elements and character data.

The order of events in this interface is very important, and mirrors the order of information in the document itself. For example, all of an element's content (character data, processing instructions, and/or subelements) will appear, in order, between the startElement event and the corresponding endElement event.

This interface is similar to the now-deprecated SAX 1.0 DocumentHandler interface, but it adds support for Namespaces and for reporting skipped entities (in non-validating XML processors).

Implementors should note that there is also a Java class ContentHandler in the java.net package; that means that it's probably a bad idea to do

import java.net.*; import org.xml.sax.*;

In fact, "import ...*" is usually a sign of sloppy programming anyway, so the user should consider this a feature rather than a bug.

Since:
SAX 2.0
See Also:
XMLReader, DTDHandler, ErrorHandler

Method Summary
void | characters(char[] ch, int start, int length) Receive notification of character data.
void | endDocument() Receive notification of the end of a document.
void | endElement(String namespaceURI, String localName, String qName) Receive notification of the end of an element.
void | endPrefixMapping(String prefix) End the scope of a prefix-URI mapping.
void | ignorableWhitespace(char[] ch, int start, int length) Receive notification of ignorable whitespace in element content.
void | processingInstruction(String target, String data) Receive notification of a processing instruction.
void | setDocumentLocator(Locator locator) Receive an object for locating the origin of SAX document events.
void | skippedEntity(String name) Receive notification of a skipped entity.
void | startDocument() Receive notification of the beginning of a document.
void | startElement(String namespaceURI, String localName, String qName, Attributes atts) Receive notification of the beginning of an element.
void | startPrefixMapping(String prefix, String uri) Begin the scope of a prefix-URI Namespace mapping.

Method Detail

setDocumentLocator

public void setDocumentLocator(Locator locator)
Receive an object for locating the origin of SAX document events.

SAX parsers are strongly encouraged (though not absolutely required) to supply a locator: if it does so, it must supply the locator to the application by invoking this method before invoking any of the other methods in the ContentHandler interface.

The locator allows the application to determine the end position of any document-related event, even if the parser is not reporting an error. Typically, the application will use this information for reporting its own errors (such as character content that does not match an application's business rules). The information returned by the locator is probably not sufficient for use with a search engine.

Note that the locator will return correct information only during the invocation of the events in this interface. The application should not attempt to use it at any other time.

Parameters:
locator - An object that can return the location of any SAX document event.
See Also:
Locator

startDocument

public void startDocument()
                   throws SAXException
Receive notification of the beginning of a document.

The SAX parser will invoke this method only once, before any other methods in this interface or in DTDHandler (except for setDocumentLocator).

Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
endDocument()

endDocument

public void endDocument()
                 throws SAXException
Receive notification of the end of a document.

The SAX parser will invoke this method only once, and it will be the last method invoked during the parse. The parser shall not invoke this method until it has either abandoned parsing (because of an unrecoverable error) or reached the end of input.

Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
startDocument()

startPrefixMapping

public void startPrefixMapping(String prefix,
                               String uri)
                        throws SAXException
Begin the scope of a prefix-URI Namespace mapping.

The information from this event is not necessary for normal Namespace processing: the SAX XML reader will automatically replace prefixes for element and attribute names when the http://xml.org/sax/features/namespaces feature is true (the default).

There are cases, however, when applications need to use prefixes in character data or in attribute values, where they cannot safely be expanded automatically; the start/endPrefixMapping event supplies the information to the application to expand prefixes in those contexts itself, if necessary.

Note that start/endPrefixMapping events are not guaranteed to be properly nested relative to each-other: all startPrefixMapping events will occur before the corresponding startElement event, and all endPrefixMapping events will occur after the corresponding endElement event, but their order is not otherwise guaranteed.

There should never be start/endPrefixMapping events for the "xml" prefix, since it is predeclared and immutable.

Parameters:
prefix - The Namespace prefix being declared.
uri - The Namespace URI the prefix is mapped to.
Throws:
SAXException - The client may throw an exception during processing.
See Also:
endPrefixMapping(java.lang.String), startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)

endPrefixMapping

public void endPrefixMapping(String prefix)
                      throws SAXException
End the scope of a prefix-URI mapping.

See startPrefixMapping for details. This event will always occur after the corresponding endElement event, but the order of endPrefixMapping events is not otherwise guaranteed.

Parameters:
prefix - The prefix that was being mapping.
Throws:
SAXException - The client may throw an exception during processing.
See Also:
startPrefixMapping(java.lang.String, java.lang.String), endElement(java.lang.String, java.lang.String, java.lang.String)

startElement

public void startElement(String namespaceURI,
                         String localName,
                         String qName,
                         Attributes atts)
                  throws SAXException
Receive notification of the beginning of an element.

The Parser will invoke this method at the beginning of every element in the XML document; there will be a corresponding endElement event for every startElement event (even when the element is empty). All of the element's content will be reported, in order, before the corresponding endElement event.

This event allows up to three name components for each element:

  1. the Namespace URI;
  2. the local name; and
  3. the qualified (prefixed) name.

Any or all of these may be provided, depending on the values of the http://xml.org/sax/features/namespaces and the http://xml.org/sax/features/namespace-prefixes properties:

  • the Namespace URI and local name are required when the namespaces property is true (the default), and are optional when the namespaces property is false (if one is specified, both must be);
  • the qualified name is required when the namespace-prefixes property is true, and is optional when the namespace-prefixes property is false (the default).

Note that the attribute list provided will contain only attributes with explicit values (specified or defaulted): #IMPLIED attributes will be omitted. The attribute list will contain attributes used for Namespace declarations (xmlns* attributes) only if the http://xml.org/sax/features/namespace-prefixes property is true (it is false by default, and support for a true value is optional).

Parameters:
localName - The local name (without prefix), or the empty string if Namespace processing is not being performed.
qName - The qualified name (with prefix), or the empty string if qualified names are not available.
atts - The attributes attached to the element. If there are no attributes, it shall be an empty Attributes object.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
endElement(java.lang.String, java.lang.String, java.lang.String), Attributes

endElement

public void endElement(String namespaceURI,
                       String localName,
                       String qName)
                throws SAXException
Receive notification of the end of an element.

The SAX parser will invoke this method at the end of every element in the XML document; there will be a corresponding startElement event for every endElement event (even when the element is empty).

For information on the names, see startElement.

Parameters:
localName - The local name (without prefix), or the empty string if Namespace processing is not being performed.
qName - The qualified XML 1.0 name (with prefix), or the empty string if qualified names are not available.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.

characters

public void characters(char[] ch,
                       int start,
                       int length)
                throws SAXException
Receive notification of character data.

The Parser will call this method to report each chunk of character data. SAX parsers may return all contiguous character data in a single chunk, or they may split it into several chunks; however, all of the characters in any single event must come from the same external entity so that the Locator provides useful information.

The application must not attempt to read from the array outside of the specified range.

Note that some parsers will report whitespace in element content using the ignorableWhitespace method rather than this one (validating parsers must do so).

Parameters:
ch - The characters from the XML document.
start - The start position in the array.
length - The number of characters to read from the array.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
ignorableWhitespace(char[], int, int), Locator

ignorableWhitespace

public void ignorableWhitespace(char[] ch,
                                int start,
                                int length)
                         throws SAXException
Receive notification of ignorable whitespace in element content.

Validating Parsers must use this method to report each chunk of whitespace in element content (see the W3C XML 1.0 recommendation, section 2.10): non-validating parsers may also use this method if they are capable of parsing and using content models.

SAX parsers may return all contiguous whitespace in a single chunk, or they may split it into several chunks; however, all of the characters in any single event must come from the same external entity, so that the Locator provides useful information.

The application must not attempt to read from the array outside of the specified range.

Parameters:
ch - The characters from the XML document.
start - The start position in the array.
length - The number of characters to read from the array.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
characters(char[], int, int)

processingInstruction

public void processingInstruction(String target,
                                  String data)
                           throws SAXException
Receive notification of a processing instruction.

The Parser will invoke this method once for each processing instruction found: note that processing instructions may occur before or after the main document element.

A SAX parser must never report an XML declaration (XML 1.0, section 2.8) or a text declaration (XML 1.0, section 4.3.1) using this method.

Parameters:
target - The processing instruction target.
data - The processing instruction data, or null if none was supplied. The data does not include any whitespace separating it from the target.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.

skippedEntity

public void skippedEntity(String name)
                   throws SAXException
Receive notification of a skipped entity.

The Parser will invoke this method once for each entity skipped. Non-validating processors may skip entities if they have not seen the declarations (because, for example, the entity was declared in an external DTD subset). All processors may skip external entities, depending on the values of the http://xml.org/sax/features/external-general-entities and the http://xml.org/sax/features/external-parameter-entities properties.

Parameters:
name - The name of the skipped entity. If it is a parameter entity, the name will begin with '%', and if it is the external DTD subset, it will be the string "[dtd]".
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DocumentHandler (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.xml.sax
Interface DocumentHandler

All Known Implementing Classes:
HandlerBase, ParserAdapter
Deprecated. This interface has been replaced by the SAX2 ContentHandler interface, which includes Namespace support.

public interface DocumentHandler

Receive notification of general document events.

This module, both source code and documentation, is in the Public Domain, and comes with NO WARRANTY.

This was the main event-handling interface for SAX1; in SAX2, it has been replaced by ContentHandler, which provides Namespace support and reporting of skipped entities. This interface is included in SAX2 only to support legacy SAX1 applications.

The order of events in this interface is very important, and mirrors the order of information in the document itself. For example, all of an element's content (character data, processing instructions, and/or subelements) will appear, in order, between the startElement event and the corresponding endElement event.

Application writers who do not want to implement the entire interface can derive a class from HandlerBase, which implements the default functionality; parser writers can instantiate HandlerBase to obtain a default handler. The application can find the location of any document event using the Locator interface supplied by the Parser through the setDocumentLocator method.

Since:
SAX 1.0
See Also:
Parser.setDocumentHandler(org.xml.sax.DocumentHandler), Locator, HandlerBase

Method Summary
void | characters(char[] ch, int start, int length) Deprecated. Receive notification of character data.
void | endDocument() Deprecated. Receive notification of the end of a document.
void | endElement(String name) Deprecated. Receive notification of the end of an element.
void | ignorableWhitespace(char[] ch, int start, int length) Deprecated. Receive notification of ignorable whitespace in element content.
void | processingInstruction(String target, String data) Deprecated. Receive notification of a processing instruction.
void | setDocumentLocator(Locator locator) Deprecated. Receive an object for locating the origin of SAX document events.
void | startDocument() Deprecated. Receive notification of the beginning of a document.
void | startElement(String name, AttributeList atts) Deprecated. Receive notification of the beginning of an element.

Method Detail

setDocumentLocator

public void setDocumentLocator(Locator locator)
Deprecated.
Receive an object for locating the origin of SAX document events.

SAX parsers are strongly encouraged (though not absolutely required) to supply a locator: if it does so, it must supply the locator to the application by invoking this method before invoking any of the other methods in the DocumentHandler interface.

The locator allows the application to determine the end position of any document-related event, even if the parser is not reporting an error. Typically, the application will use this information for reporting its own errors (such as character content that does not match an application's business rules). The information returned by the locator is probably not sufficient for use with a search engine.

Note that the locator will return correct information only during the invocation of the events in this interface. The application should not attempt to use it at any other time.

Parameters:
locator - An object that can return the location of any SAX document event.
See Also:
Locator

startDocument

public void startDocument()
                   throws SAXException
Deprecated.
Receive notification of the beginning of a document.

The SAX parser will invoke this method only once, before any other methods in this interface or in DTDHandler (except for setDocumentLocator).

Throws:
SAXException - Any SAX exception, possibly wrapping another exception.

endDocument

public void endDocument()
                 throws SAXException
Deprecated.
Receive notification of the end of a document.

The SAX parser will invoke this method only once, and it will be the last method invoked during the parse. The parser shall not invoke this method until it has either abandoned parsing (because of an unrecoverable error) or reached the end of input.

Throws:
SAXException - Any SAX exception, possibly wrapping another exception.

startElement

public void startElement(String name,
                         AttributeList atts)
                  throws SAXException
Deprecated.
Receive notification of the beginning of an element.

The Parser will invoke this method at the beginning of every element in the XML document; there will be a corresponding endElement() event for every startElement() event (even when the element is empty). All of the element's content will be reported, in order, before the corresponding endElement() event.

If the element name has a namespace prefix, the prefix will still be attached. Note that the attribute list provided will contain only attributes with explicit values (specified or defaulted): #IMPLIED attributes will be omitted.

Parameters:
name - The element type name.
atts - The attributes attached to the element, if any.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
endElement(java.lang.String), AttributeList

endElement

public void endElement(String name)
                throws SAXException
Deprecated.
Receive notification of the end of an element.

The SAX parser will invoke this method at the end of every element in the XML document; there will be a corresponding startElement() event for every endElement() event (even when the element is empty).

If the element name has a namespace prefix, the prefix will still be attached to the name.

Parameters:
name - The element type name
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.

characters

public void characters(char[] ch,
                       int start,
                       int length)
                throws SAXException
Deprecated.
Receive notification of character data.

The Parser will call this method to report each chunk of character data. SAX parsers may return all contiguous character data in a single chunk, or they may split it into several chunks; however, all of the characters in any single event must come from the same external entity, so that the Locator provides useful information.

The application must not attempt to read from the array outside of the specified range.

Note that some parsers will report whitespace using the ignorableWhitespace() method rather than this one (validating parsers must do so).

Parameters:
ch - The characters from the XML document.
start - The start position in the array.
length - The number of characters to read from the array.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
ignorableWhitespace(char[], int, int), Locator

ignorableWhitespace

public void ignorableWhitespace(char[] ch,
                                int start,
                                int length)
                         throws SAXException
Deprecated.
Receive notification of ignorable whitespace in element content.

Validating Parsers must use this method to report each chunk of ignorable whitespace (see the W3C XML 1.0 recommendation, section 2.10): non-validating parsers may also use this method if they are capable of parsing and using content models.

SAX parsers may return all contiguous whitespace in a single chunk, or they may split it into several chunks; however, all of the characters in any single event must come from the same external entity, so that the Locator provides useful information.

The application must not attempt to read from the array outside of the specified range.

Parameters:
ch - The characters from the XML document.
start - The start position in the array.
length - The number of characters to read from the array.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
characters(char[], int, int)

processingInstruction

public void processingInstruction(String target,
                                  String data)
                           throws SAXException
Deprecated.
Receive notification of a processing instruction.

The Parser will invoke this method once for each processing instruction found: note that processing instructions may occur before or after the main document element.

A SAX parser should never report an XML declaration (XML 1.0, section 2.8) or a text declaration (XML 1.0, section 4.3.1) using this method.

Parameters:
target - The processing instruction target.
data - The processing instruction data, or null if none was supplied.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DTDHandler (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.xml.sax
Interface DTDHandler

All Known Subinterfaces:
TransformerHandler
All Known Implementing Classes:
DefaultHandler, HandlerBase, XMLFilterImpl
public interface DTDHandler

Receive notification of basic DTD-related events.

This module, both source code and documentation, is in the Public Domain, and comes with NO WARRANTY.

If a SAX application needs information about notations and unparsed entities, then the application implements this interface and registers an instance with the SAX parser using the parser's setDTDHandler method. The parser uses the instance to report notation and unparsed entity declarations to the application.

Note that this interface includes only those DTD events that the XML recommendation requires processors to report: notation and unparsed entity declarations.

The SAX parser may report these events in any order, regardless of the order in which the notations and unparsed entities were declared; however, all DTD events must be reported after the document handler's startDocument event, and before the first startElement event.

It is up to the application to store the information for future use (perhaps in a hash table or object tree). If the application encounters attributes of type "NOTATION", "ENTITY", or "ENTITIES", it can use the information that it obtained through this interface to find the entity and/or notation corresponding with the attribute value.

Since:
SAX 1.0
See Also:
Parser.setDTDHandler(org.xml.sax.DTDHandler), HandlerBase

Method Summary
void | notationDecl(String name, String publicId, String systemId) Receive notification of a notation declaration event.
void | unparsedEntityDecl(String name, String publicId, String systemId, String notationName) Receive notification of an unparsed entity declaration event.

Method Detail

notationDecl

public void notationDecl(String name,
                         String publicId,
                         String systemId)
                  throws SAXException
Receive notification of a notation declaration event.

It is up to the application to record the notation for later reference, if necessary.

At least one of publicId and systemId must be non-null. If a system identifier is present, and it is a URL, the SAX parser must resolve it fully before passing it to the application through this event.

There is no guarantee that the notation declaration will be reported before any unparsed entities that use it.

Parameters:
name - The notation name.
publicId - The notation's public identifier, or null if none was given.
systemId - The notation's system identifier, or null if none was given.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
unparsedEntityDecl(java.lang.String, java.lang.String, java.lang.String, java.lang.String), AttributeList

unparsedEntityDecl

public void unparsedEntityDecl(String name,
                               String publicId,
                               String systemId,
                               String notationName)
                        throws SAXException
Receive notification of an unparsed entity declaration event.

Note that the notation name corresponds to a notation reported by the notationDecl event. It is up to the application to record the entity for later reference, if necessary.

If the system identifier is a URL, the parser must resolve it fully before passing it to the application.

Parameters:
name - The unparsed entity's name.
publicId - The entity's public identifier, or null if none was given.
systemId - The entity's system identifier.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
notationDecl(java.lang.String, java.lang.String, java.lang.String), AttributeList
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


EntityResolver (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.xml.sax
Interface EntityResolver

All Known Implementing Classes:
DefaultHandler, HandlerBase, XMLFilterImpl
public interface EntityResolver

Basic interface for resolving entities.

This module, both source code and documentation, is in the Public Domain, and comes with NO WARRANTY.

If a SAX application needs to implement customized handling for external entities, it must implement this interface and register an instance with the SAX driver using the setEntityResolver method.

The XML reader will then allow the application to intercept any external entities (including the external DTD subset and external parameter entities, if any) before including them.

Many SAX applications will not need to implement this interface, but it will be especially useful for applications that build XML documents from databases or other specialised input sources, or for applications that use URI types other than URLs.

The following resolver would provide the application with a special character stream for the entity with the system identifier "http://www.myhost.com/today":

 import org.xml.sax.EntityResolver;
 import org.xml.sax.InputSource;

 public class MyResolver implements EntityResolver {
   public InputSource resolveEntity (String publicId, String systemId)
   {
     if (systemId.equals("http://www.myhost.com/today")) {
              // return a special input source
       MyReader reader = new MyReader();
       return new InputSource(reader);
     } else {
              // use the default behaviour
       return null;
     }
   }
 }

The application can also use this interface to redirect system identifiers to local URIs or to look up replacements in a catalog (possibly by using the public identifier).

Since:
SAX 1.0
See Also:
Parser.setEntityResolver(org.xml.sax.EntityResolver), InputSource

Method Summary
 InputSource resolveEntity(String publicId, String systemId)
Allow the application to resolve external entities.

Method Detail

resolveEntity

public InputSource resolveEntity(String publicId,
                                 String systemId)
                          throws SAXException,
                                 IOException
Allow the application to resolve external entities.

The Parser will call this method before opening any external entity except the top-level document entity (including the external DTD subset, external entities referenced within the DTD, and external entities referenced within the document element): the application may request that the parser resolve the entity itself, that it use an alternative URI, or that it use an entirely different input source.

Application writers can use this method to redirect external system identifiers to secure and/or local URIs, to look up public identifiers in a catalogue, or to read an entity from a database or other input source (including, for example, a dialog box).

If the system identifier is a URL, the SAX parser must resolve it fully before reporting it to the application.

Parameters:
publicId - The public identifier of the external entity being referenced, or null if none was supplied.
systemId - The system identifier of the external entity being referenced.
Returns:
An InputSource object describing the new input source, or null to request that the parser open a regular URI connection to the system identifier.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
IOException - A Java-specific IO exception, possibly the result of creating a new InputStream or Reader for the InputSource.
See Also:
InputSource
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ErrorHandler (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.xml.sax
Interface ErrorHandler

All Known Implementing Classes:
DefaultHandler, HandlerBase, XMLFilterImpl
public interface ErrorHandler

Basic interface for SAX error handlers.

This module, both source code and documentation, is in the Public Domain, and comes with NO WARRANTY.

If a SAX application needs to implement customized error handling, it must implement this interface and then register an instance with the XML reader using the setErrorHandler method. The parser will then report all errors and warnings through this interface.

WARNING: If an application does not register an ErrorHandler, XML parsing errors will go unreported and bizarre behaviour may result.

For XML processing errors, a SAX driver must use this interface instead of throwing an exception: it is up to the application to decide whether to throw an exception for different types of errors and warnings. Note, however, that there is no requirement that the parser continue to provide useful information after a call to fatalError (in other words, a SAX driver class could catch an exception and report a fatalError).

Since:
SAX 1.0
See Also:
Parser.setErrorHandler(org.xml.sax.ErrorHandler), SAXParseException

Method Summary
void | error(SAXParseException exception) Receive notification of a recoverable error.
void | fatalError(SAXParseException exception) Receive notification of a non-recoverable error.
void | warning(SAXParseException exception) Receive notification of a warning.

Method Detail

warning

public void warning(SAXParseException exception)
             throws SAXException
Receive notification of a warning.

SAX parsers will use this method to report conditions that are not errors or fatal errors as defined by the XML 1.0 recommendation. The default behaviour is to take no action.

The SAX parser must continue to provide normal parsing events after invoking this method: it should still be possible for the application to process the document through to the end.

Filters may use this method to report other, non-XML warnings as well.

Parameters:
exception - The warning information encapsulated in a SAX parse exception.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
SAXParseException

error

public void error(SAXParseException exception)
           throws SAXException
Receive notification of a recoverable error.

This corresponds to the definition of "error" in section 1.2 of the W3C XML 1.0 Recommendation. For example, a validating parser would use this callback to report the violation of a validity constraint. The default behaviour is to take no action.

The SAX parser must continue to provide normal parsing events after invoking this method: it should still be possible for the application to process the document through to the end. If the application cannot do so, then the parser should report a fatal error even if the XML 1.0 recommendation does not require it to do so.

Filters may use this method to report other, non-XML errors as well.

Parameters:
exception - The error information encapsulated in a SAX parse exception.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
SAXParseException

fatalError

public void fatalError(SAXParseException exception)
                throws SAXException
Receive notification of a non-recoverable error.

This corresponds to the definition of "fatal error" in section 1.2 of the W3C XML 1.0 Recommendation. For example, a parser would use this callback to report the violation of a well-formedness constraint.

The application must assume that the document is unusable after the parser has invoked this method, and should continue (if at all) only for the sake of collecting addition error messages: in fact, SAX parsers are free to stop reporting any other events once this method has been invoked.

Parameters:
exception - The error information encapsulated in a SAX parse exception.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
SAXParseException
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


HandlerBase (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.xml.sax
Class HandlerBase

java.lang.Object
    extended by org.xml.sax.HandlerBase
All Implemented Interfaces:
DocumentHandler, DTDHandler, EntityResolver, ErrorHandler
Deprecated. This class works with the deprecated DocumentHandler interface. It has been replaced by the SAX2 DefaultHandler class.

public class HandlerBase
extends Object
implements EntityResolver, DTDHandler, DocumentHandler, ErrorHandler

Default base class for handlers.

This module, both source code and documentation, is in the Public Domain, and comes with NO WARRANTY.

This class implements the default behaviour for four SAX1 interfaces: EntityResolver, DTDHandler, DocumentHandler, and ErrorHandler. It is now obsolete, but is included in SAX2 to support legacy SAX1 applications. SAX2 applications should use the DefaultHandler class instead.

Application writers can extend this class when they need to implement only part of an interface; parser writers can instantiate this class to provide default handlers when the application has not supplied its own.

Note that the use of this class is optional.

Since:
SAX 1.0
See Also:
EntityResolver, DTDHandler, DocumentHandler, ErrorHandler

Constructor Summary
HandlerBase()
Deprecated.
Method Summary
void | characters(char[] ch, int start, int length) Deprecated. Receive notification of character data inside an element.
void | endDocument() Deprecated. Receive notification of the end of the document.
void | endElement(String name) Deprecated. Receive notification of the end of an element.
void | error(SAXParseException e) Deprecated. Receive notification of a recoverable parser error.
void | fatalError(SAXParseException e) Deprecated. Report a fatal XML parsing error.
void | ignorableWhitespace(char[] ch, int start, int length) Deprecated. Receive notification of ignorable whitespace in element content.
void | notationDecl(String name, String publicId, String systemId) Deprecated. Receive notification of a notation declaration.
void | processingInstruction(String target, String data) Deprecated. Receive notification of a processing instruction.
InputSource | resolveEntity(String publicId, String systemId) Deprecated. Resolve an external entity.
void | setDocumentLocator(Locator locator) Deprecated. Receive a Locator object for document events.
void | startDocument() Deprecated. Receive notification of the beginning of the document.
void | startElement(String name, AttributeList attributes) Deprecated. Receive notification of the start of an element.
void | unparsedEntityDecl(String name, String publicId, String systemId, String notationName) Deprecated. Receive notification of an unparsed entity declaration.
void | warning(SAXParseException e) Deprecated. Receive notification of a parser warning.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

HandlerBase

public HandlerBase()
Deprecated.
Method Detail

resolveEntity

public InputSource resolveEntity(String publicId,
                                 String systemId)
                          throws SAXException
Deprecated.
Resolve an external entity.

Always return null, so that the parser will use the system identifier provided in the XML document. This method implements the SAX default behaviour: application writers can override it in a subclass to do special translations such as catalog lookups or URI redirection.

Specified by:
resolveEntity in interface EntityResolver
Parameters:
publicId - The public identifer, or null if none is available.
systemId - The system identifier provided in the XML document.
Returns:
The new input source, or null to require the default behaviour.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
EntityResolver.resolveEntity(java.lang.String, java.lang.String)

notationDecl

public void notationDecl(String name,
                         String publicId,
                         String systemId)
Deprecated.
Receive notification of a notation declaration.

By default, do nothing. Application writers may override this method in a subclass if they wish to keep track of the notations declared in a document.

Specified by:
notationDecl in interface DTDHandler
Parameters:
name - The notation name.
publicId - The notation public identifier, or null if not available.
systemId - The notation system identifier.
See Also:
DTDHandler.notationDecl(java.lang.String, java.lang.String, java.lang.String)

unparsedEntityDecl

public void unparsedEntityDecl(String name,
                               String publicId,
                               String systemId,
                               String notationName)
Deprecated.
Receive notification of an unparsed entity declaration.

By default, do nothing. Application writers may override this method in a subclass to keep track of the unparsed entities declared in a document.

Specified by:
unparsedEntityDecl in interface DTDHandler
Parameters:
name - The entity name.
publicId - The entity public identifier, or null if not available.
systemId - The entity system identifier.
notationName - The name of the associated notation.
See Also:
DTDHandler.unparsedEntityDecl(java.lang.String, java.lang.String, java.lang.String, java.lang.String)

setDocumentLocator

public void setDocumentLocator(Locator locator)
Deprecated.
Receive a Locator object for document events.

By default, do nothing. Application writers may override this method in a subclass if they wish to store the locator for use with other document events.

Specified by:
setDocumentLocator in interface DocumentHandler
Parameters:
locator - A locator for all SAX document events.
See Also:
DocumentHandler.setDocumentLocator(org.xml.sax.Locator), Locator

startDocument

public void startDocument()
                   throws SAXException
Deprecated.
Receive notification of the beginning of the document.

By default, do nothing. Application writers may override this method in a subclass to take specific actions at the beginning of a document (such as allocating the root node of a tree or creating an output file).

Specified by:
startDocument in interface DocumentHandler
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
DocumentHandler.startDocument()

endDocument

public void endDocument()
                 throws SAXException
Deprecated.
Receive notification of the end of the document.

By default, do nothing. Application writers may override this method in a subclass to take specific actions at the beginning of a document (such as finalising a tree or closing an output file).

Specified by:
endDocument in interface DocumentHandler
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
DocumentHandler.endDocument()

startElement

public void startElement(String name,
                         AttributeList attributes)
                  throws SAXException
Deprecated.
Receive notification of the start of an element.

By default, do nothing. Application writers may override this method in a subclass to take specific actions at the start of each element (such as allocating a new tree node or writing output to a file).

Specified by:
startElement in interface DocumentHandler
Parameters:
name - The element type name.
attributes - The specified or defaulted attributes.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
DocumentHandler.startElement(java.lang.String, org.xml.sax.AttributeList)

endElement

public void endElement(String name)
                throws SAXException
Deprecated.
Receive notification of the end of an element.

By default, do nothing. Application writers may override this method in a subclass to take specific actions at the end of each element (such as finalising a tree node or writing output to a file).

Specified by:
endElement in interface DocumentHandler
Parameters:
name - The element type name.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
DocumentHandler.endElement(java.lang.String)

characters

public void characters(char[] ch,
                       int start,
                       int length)
                throws SAXException
Deprecated.
Receive notification of character data inside an element.

By default, do nothing. Application writers may override this method to take specific actions for each chunk of character data (such as adding the data to a node or buffer, or printing it to a file).

Specified by:
characters in interface DocumentHandler
Parameters:
ch - The characters.
start - The start position in the character array.
length - The number of characters to use from the character array.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
DocumentHandler.characters(char[], int, int)

ignorableWhitespace

public void ignorableWhitespace(char[] ch,
                                int start,
                                int length)
                         throws SAXException
Deprecated.
Receive notification of ignorable whitespace in element content.

By default, do nothing. Application writers may override this method to take specific actions for each chunk of ignorable whitespace (such as adding data to a node or buffer, or printing it to a file).

Specified by:
ignorableWhitespace in interface DocumentHandler
Parameters:
ch - The whitespace characters.
start - The start position in the character array.
length - The number of characters to use from the character array.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
DocumentHandler.ignorableWhitespace(char[], int, int)

processingInstruction

public void processingInstruction(String target,
                                  String data)
                           throws SAXException
Deprecated.
Receive notification of a processing instruction.

By default, do nothing. Application writers may override this method in a subclass to take specific actions for each processing instruction, such as setting status variables or invoking other methods.

Specified by:
processingInstruction in interface DocumentHandler
Parameters:
target - The processing instruction target.
data - The processing instruction data, or null if none is supplied.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
DocumentHandler.processingInstruction(java.lang.String, java.lang.String)

warning

public void warning(SAXParseException e)
             throws SAXException
Deprecated.
Receive notification of a parser warning.

The default implementation does nothing. Application writers may override this method in a subclass to take specific actions for each warning, such as inserting the message in a log file or printing it to the console.

Specified by:
warning in interface ErrorHandler
Parameters:
e - The warning information encoded as an exception.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
ErrorHandler.warning(org.xml.sax.SAXParseException), SAXParseException

error

public void error(SAXParseException e)
           throws SAXException
Deprecated.
Receive notification of a recoverable parser error.

The default implementation does nothing. Application writers may override this method in a subclass to take specific actions for each error, such as inserting the message in a log file or printing it to the console.

Specified by:
error in interface ErrorHandler
Parameters:
e - The warning information encoded as an exception.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
ErrorHandler.warning(org.xml.sax.SAXParseException), SAXParseException

fatalError

public void fatalError(SAXParseException e)
                throws SAXException
Deprecated.
Report a fatal XML parsing error.

The default implementation throws a SAXParseException. Application writers may override this method in a subclass if they need to take specific actions for each fatal error (such as collecting all of the errors into a single report): in any case, the application must stop all regular processing when this method is invoked, since the document is no longer reliable, and the parser may no longer report parsing events.

Specified by:
fatalError in interface ErrorHandler
Parameters:
e - The error information encoded as an exception.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
ErrorHandler.fatalError(org.xml.sax.SAXParseException), SAXParseException
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


InputSource (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.xml.sax
Class InputSource

java.lang.Object
    extended by org.xml.sax.InputSource
public class InputSource
extends Object

A single input source for an XML entity.

This module, both source code and documentation, is in the Public Domain, and comes with NO WARRANTY.

This class allows a SAX application to encapsulate information about an input source in a single object, which may include a public identifier, a system identifier, a byte stream (possibly with a specified encoding), and/or a character stream.

There are two places that the application will deliver this input source to the parser: as the argument to the Parser.parse method, or as the return value of the EntityResolver.resolveEntity method.

The SAX parser will use the InputSource object to determine how to read XML input. If there is a character stream available, the parser will read that stream directly; if not, the parser will use a byte stream, if available; if neither a character stream nor a byte stream is available, the parser will attempt to open a URI connection to the resource identified by the system identifier.

An InputSource object belongs to the application: the SAX parser shall never modify it in any way (it may modify a copy if necessary).

Since:
SAX 1.0
See Also:
Parser.parse(org.xml.sax.InputSource), EntityResolver.resolveEntity(java.lang.String, java.lang.String), InputStream, Reader

Constructor Summary
InputSource()
Zero-argument default constructor.
InputSource(InputStream byteStream)
Create a new input source with a byte stream.
InputSource(Reader characterStream)
Create a new input source with a character stream.
InputSource(String systemId)
Create a new input source with a system identifier.
Method Summary
InputStream | getByteStream() Get the byte stream for this input source.
Reader | getCharacterStream() Get the character stream for this input source.
String | getEncoding() Get the character encoding for a byte stream or URI.
String | getPublicId() Get the public identifier for this input source.
String | getSystemId() Get the system identifier for this input source.
void | setByteStream(InputStream byteStream) Set the byte stream for this input source.
void | setCharacterStream(Reader characterStream) Set the character stream for this input source.
void | setEncoding(String encoding) Set the character encoding, if known.
void | setPublicId(String publicId) Set the public identifier for this input source.
void | setSystemId(String systemId) Set the system identifier for this input source.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

InputSource

public InputSource()
Zero-argument default constructor.

See Also:
setPublicId(java.lang.String),
setSystemId(java.lang.String),
setByteStream(java.io.InputStream),
setCharacterStream(java.io.Reader),
setEncoding(java.lang.String)

InputSource

public InputSource(String systemId)
Create a new input source with a system identifier.

Applications may use setPublicId to include a public identifier as well, or setEncoding to specify the character encoding, if known.

If the system identifier is a URL, it must be full resolved.

Parameters:
systemId - The system identifier (URI).
See Also:
setPublicId(java.lang.String),
setSystemId(java.lang.String),
setByteStream(java.io.InputStream),
setEncoding(java.lang.String),
setCharacterStream(java.io.Reader)

InputSource

public InputSource(InputStream byteStream)
Create a new input source with a byte stream.

Application writers may use setSystemId to provide a base for resolving relative URIs, setPublicId to include a public identifier, and/or setEncoding to specify the object's character encoding.

Parameters:
byteStream - The raw byte stream containing the document.
See Also:
setPublicId(java.lang.String),
setSystemId(java.lang.String),
setEncoding(java.lang.String),
setByteStream(java.io.InputStream),
setCharacterStream(java.io.Reader)

InputSource

public InputSource(Reader characterStream)
Create a new input source with a character stream.

Application writers may use setSystemId() to provide a base for resolving relative URIs, and setPublicId to include a public identifier.

The character stream shall not include a byte order mark.

See Also:
setPublicId(java.lang.String),
setSystemId(java.lang.String),
setByteStream(java.io.InputStream),
setCharacterStream(java.io.Reader)
Method Detail

setPublicId

public void setPublicId(String publicId)
Set the public identifier for this input source.

The public identifier is always optional: if the application writer includes one, it will be provided as part of the location information.

Parameters:
publicId - The public identifier as a string.
See Also:
getPublicId(),
Locator.getPublicId(),
SAXParseException.getPublicId()

getPublicId

public String getPublicId()
Get the public identifier for this input source.

Returns:
The public identifier, or null if none was supplied.
See Also:
setPublicId(java.lang.String)

setSystemId

public void setSystemId(String systemId)
Set the system identifier for this input source.

The system identifier is optional if there is a byte stream or a character stream, but it is still useful to provide one, since the application can use it to resolve relative URIs and can include it in error messages and warnings (the parser will attempt to open a connection to the URI only if there is no byte stream or character stream specified).

If the application knows the character encoding of the object pointed to by the system identifier, it can register the encoding using the setEncoding method.

If the system ID is a URL, it must be fully resolved.

Parameters:
systemId - The system identifier as a string.
See Also:
setEncoding(java.lang.String),
getSystemId(),
Locator.getSystemId(),
SAXParseException.getSystemId()

getSystemId

public String getSystemId()
Get the system identifier for this input source.

The getEncoding method will return the character encoding of the object pointed to, or null if unknown.

If the system ID is a URL, it will be fully resolved.

Returns:
The system identifier, or null if none was supplied.
See Also:
setSystemId(java.lang.String), getEncoding()

setByteStream

public void setByteStream(InputStream byteStream)
Set the byte stream for this input source.

The SAX parser will ignore this if there is also a character stream specified, but it will use a byte stream in preference to opening a URI connection itself.

If the application knows the character encoding of the byte stream, it should set it with the setEncoding method.

Parameters:
byteStream - A byte stream containing an XML document or other entity.
See Also:
setEncoding(java.lang.String),
getByteStream(),
getEncoding(),
InputStream

getByteStream

public InputStream getByteStream()
Get the byte stream for this input source.

The getEncoding method will return the character encoding for this byte stream, or null if unknown.

Returns:
The byte stream, or null if none was supplied.
See Also:
getEncoding(), setByteStream(java.io.InputStream)

setEncoding

public void setEncoding(String encoding)
Set the character encoding, if known.

The encoding must be a string acceptable for an XML encoding declaration (see section 4.3.3 of the XML 1.0 recommendation).

This method has no effect when the application provides a character stream.

Parameters:
encoding - A string describing the character encoding.
See Also:
setSystemId(java.lang.String),
setByteStream(java.io.InputStream),
getEncoding()

getEncoding

public String getEncoding()
Get the character encoding for a byte stream or URI.

Returns:
The encoding, or null if none was supplied.
See Also:
setByteStream(java.io.InputStream),
getSystemId(),
getByteStream()

setCharacterStream

public void setCharacterStream(Reader characterStream)
Set the character stream for this input source.

If there is a character stream specified, the SAX parser will ignore any byte stream and will not attempt to open a URI connection to the system identifier.

Parameters:
characterStream - The character stream containing the XML document or other entity.
See Also:
getCharacterStream(), Reader

getCharacterStream

public Reader getCharacterStream()
Get the character stream for this input source.

Returns:
The character stream, or null if none was supplied.
See Also:
setCharacterStream(java.io.Reader)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Locator (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.xml.sax
Interface Locator

All Known Implementing Classes:
LocatorImpl
public interface Locator

Interface for associating a SAX event with a document location.

This module, both source code and documentation, is in the Public Domain, and comes with NO WARRANTY.

If a SAX parser provides location information to the SAX application, it does so by implementing this interface and then passing an instance to the application using the content handler's setDocumentLocator method. The application can use the object to obtain the location of any other content handler event in the XML source document.

Note that the results returned by the object will be valid only during the scope of each content handler method: the application will receive unpredictable results if it attempts to use the locator at any other time.

SAX parsers are not required to supply a locator, but they are very strongly encouraged to do so. If the parser supplies a locator, it must do so before reporting any other document events. If no locator has been set by the time the application receives the startDocument event, the application should assume that a locator is not available.

Since:
SAX 1.0
See Also:
ContentHandler.setDocumentLocator(org.xml.sax.Locator)

Method Summary
int | getColumnNumber() Return the column number where the current document event ends.
int | getLineNumber() Return the line number where the current document event ends.
String | getPublicId() Return the public identifier for the current document event.
String | getSystemId() Return the system identifier for the current document event.

Method Detail

getPublicId

public String getPublicId()
Return the public identifier for the current document event.

The return value is the public identifier of the document entity or of the external parsed entity in which the markup triggering the event appears.

Returns:
A string containing the public identifier, or null if none is available.
See Also:
getSystemId()

getSystemId

public String getSystemId()
Return the system identifier for the current document event.

The return value is the system identifier of the document entity or of the external parsed entity in which the markup triggering the event appears.

If the system identifier is a URL, the parser must resolve it fully before passing it to the application.

Returns:
A string containing the system identifier, or null if none is available.
See Also:
getPublicId()

getLineNumber

public int getLineNumber()
Return the line number where the current document event ends.

Warning: The return value from the method is intended only as an approximation for the sake of error reporting; it is not intended to provide sufficient information to edit the character content of the original XML document.

The return value is an approximation of the line number in the document entity or external parsed entity where the markup triggering the event appears.

If possible, the SAX driver should provide the line position of the first character after the text associated with the document event. The first line in the document is line 1.

Returns:
The line number, or -1 if none is available.
See Also:
getColumnNumber()

getColumnNumber

public int getColumnNumber()
Return the column number where the current document event ends.

Warning: The return value from the method is intended only as an approximation for the sake of error reporting; it is not intended to provide sufficient information to edit the character content of the original XML document.

The return value is an approximation of the column number in the document entity or external parsed entity where the markup triggering the event appears.

If possible, the SAX driver should provide the line position of the first character after the text associated with the document event.

If possible, the SAX driver should provide the line position of the first character after the text associated with the document event. The first column in each line is column 1.

Returns:
The column number, or -1 if none is available.
See Also:
getLineNumber()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


org.xml.sax (Java 2 Platform SE v1.4.2)

 org.xml.sax
Interfaces
AttributeList
Attributes
ContentHandler
DocumentHandler
DTDHandler
EntityResolver
ErrorHandler
Locator
Parser
XMLFilter
XMLReader
Classes
HandlerBase
InputSource
Exceptions
SAXException
SAXNotRecognizedException
SAXNotSupportedException
SAXParseException


org.xml.sax (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package org.xml.sax

Provides the classes and interfaces for the Simple API for XML (SAX) which is a component of the Java API for XML Processing.

See:
Description

Interface Summary
AttributeList | Deprecated. This interface has been replaced by the SAX2 Attributes interface, which includes Namespace support.
Attributes | Interface for a list of XML attributes.
ContentHandler | Receive notification of the logical content of a document.
DocumentHandler | Deprecated. This interface has been replaced by the SAX2 ContentHandler interface, which includes Namespace support.
DTDHandler | Receive notification of basic DTD-related events.
EntityResolver | Basic interface for resolving entities.
ErrorHandler | Basic interface for SAX error handlers.
Locator | Interface for associating a SAX event with a document location.
Parser | Deprecated. This interface has been replaced by the SAX2 XMLReader interface, which includes Namespace support.
XMLFilter | Interface for an XML filter.
XMLReader | Interface for reading an XML document using callbacks.

Class Summary
HandlerBase | Deprecated. This class works with the deprecated DocumentHandler interface.
InputSource | A single input source for an XML entity.

Exception Summary
SAXException | Encapsulate a general SAX error or warning.
SAXNotRecognizedException | Exception class for an unrecognized identifier.
SAXNotSupportedException | Exception class for an unsupported operation.
SAXParseException | Encapsulate an XML parse error or warning.

Package org.xml.sax Description

Provides the classes and interfaces for the Simple API for XML (SAX) which is a component of the Java API for XML Processing. SAX, the Simple API for XML, is a standard interface for event-based XML parsing, developed collaboratively by the members of the XML-DEV mailing list, currently hosted by OASIS. See the following link for more information on SAX.

Since:
JDK1.4
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


org.xml.sax Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package org.xml.sax

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class org.xml.sax.HandlerBase (implements org.xml.sax.DocumentHandler, org.xml.sax.DTDHandler, org.xml.sax.EntityResolver, org.xml.sax.ErrorHandler)
    • class org.xml.sax.InputSource
    • class java.lang.Throwable (implements java.io.Serializable)
      • class java.lang.Exception
        • class org.xml.sax.SAXException
          • class org.xml.sax.SAXNotRecognizedException
          • class org.xml.sax.SAXNotSupportedException
          • class org.xml.sax.SAXParseException

Interface Hierarchy

  • interface org.xml.sax.AttributeList
  • interface org.xml.sax.Attributes
  • interface org.xml.sax.ContentHandler
  • interface org.xml.sax.DocumentHandler
  • interface org.xml.sax.DTDHandler
  • interface org.xml.sax.EntityResolver
  • interface org.xml.sax.ErrorHandler
  • interface org.xml.sax.Locator
  • interface org.xml.sax.Parser
  • interface org.xml.sax.XMLReader
    • interface org.xml.sax.XMLFilter
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package org.xml.sax (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
org.xml.sax

Packages that use org.xml.sax
javax.xml.parsers | Provides classes allowing the processing of XML documents.
javax.xml.transform.sax | This package implements SAX2-specific transformation APIs.
org.xml.sax | Provides the classes and interfaces for the Simple API for XML (SAX) which is a component of the Java API for XML Processing.
org.xml.sax.ext | Provides extension classes and interfaces for the Simple API for XML (SAX) which is a component of the Java API for XML Processing.
org.xml.sax.helpers | Provides helper classes for the Simple API for XML (SAX) which is a component of the Java API for XML Processing.

Classes in org.xml.sax used by javax.xml.parsers
EntityResolver
Basic interface for resolving entities.
ErrorHandler
Basic interface for SAX error handlers.
HandlerBase
Deprecated. This class works with the deprecated DocumentHandler interface. It has been replaced by the SAX2 DefaultHandler class.
InputSource
A single input source for an XML entity.
Parser
Deprecated. This interface has been replaced by the SAX2 XMLReader interface, which includes Namespace support.
SAXException
Encapsulate a general SAX error or warning.
SAXNotRecognizedException
Exception class for an unrecognized identifier.
SAXNotSupportedException
Exception class for an unsupported operation.
XMLReader
Interface for reading an XML document using callbacks.

Classes in org.xml.sax used by javax.xml.transform.sax
ContentHandler
Receive notification of the logical content of a document.
DTDHandler
Receive notification of basic DTD-related events.
InputSource
A single input source for an XML entity.
XMLFilter
Interface for an XML filter.
XMLReader
Interface for reading an XML document using callbacks.

Classes in org.xml.sax used by org.xml.sax
AttributeList
Deprecated. This interface has been replaced by the SAX2 Attributes interface, which includes Namespace support.
Attributes
Interface for a list of XML attributes.
ContentHandler
Receive notification of the logical content of a document.
DocumentHandler
Deprecated. This interface has been replaced by the SAX2 ContentHandler interface, which includes Namespace support.
DTDHandler
Receive notification of basic DTD-related events.
EntityResolver
Basic interface for resolving entities.
ErrorHandler
Basic interface for SAX error handlers.
InputSource
A single input source for an XML entity.
Locator
Interface for associating a SAX event with a document location.
SAXException
Encapsulate a general SAX error or warning.
SAXNotRecognizedException
Exception class for an unrecognized identifier.
SAXNotSupportedException
Exception class for an unsupported operation.
SAXParseException
Encapsulate an XML parse error or warning.
XMLReader
Interface for reading an XML document using callbacks.

Classes in org.xml.sax used by org.xml.sax.ext
SAXException
Encapsulate a general SAX error or warning.

Classes in org.xml.sax used by org.xml.sax.helpers
AttributeList
Deprecated. This interface has been replaced by the SAX2 Attributes interface, which includes Namespace support.
Attributes
Interface for a list of XML attributes.
ContentHandler
Receive notification of the logical content of a document.
DocumentHandler
Deprecated. This interface has been replaced by the SAX2 ContentHandler interface, which includes Namespace support.
DTDHandler
Receive notification of basic DTD-related events.
EntityResolver
Basic interface for resolving entities.
ErrorHandler
Basic interface for SAX error handlers.
InputSource
A single input source for an XML entity.
Locator
Interface for associating a SAX event with a document location.
Parser
Deprecated. This interface has been replaced by the SAX2 XMLReader interface, which includes Namespace support.
SAXException
Encapsulate a general SAX error or warning.
SAXNotRecognizedException
Exception class for an unrecognized identifier.
SAXNotSupportedException
Exception class for an unsupported operation.
SAXParseException
Encapsulate an XML parse error or warning.
XMLFilter
Interface for an XML filter.
XMLReader
Interface for reading an XML document using callbacks.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Parser (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.xml.sax
Interface Parser

All Known Implementing Classes:
XMLReaderAdapter
Deprecated. This interface has been replaced by the SAX2 XMLReader interface, which includes Namespace support.

public interface Parser

Basic interface for SAX (Simple API for XML) parsers.

This module, both source code and documentation, is in the Public Domain, and comes with NO WARRANTY.

This was the main event supplier interface for SAX1; it has been replaced in SAX2 by XMLReader, which includes Namespace support and sophisticated configurability and extensibility.

All SAX1 parsers must implement this basic interface: it allows applications to register handlers for different types of events and to initiate a parse from a URI, or a character stream.

All SAX1 parsers must also implement a zero-argument constructor (though other constructors are also allowed).

SAX1 parsers are reusable but not re-entrant: the application may reuse a parser object (possibly with a different input source) once the first parse has completed successfully, but it may not invoke the parse() methods recursively within a parse.

Since:
SAX 1.0
See Also:
EntityResolver, DTDHandler, DocumentHandler, ErrorHandler, HandlerBase, InputSource

Method Summary
void | parse(InputSource source) Deprecated. Parse an XML document.
void | parse(String systemId) Deprecated. Parse an XML document from a system identifier (URI).
void | setDocumentHandler(DocumentHandler handler) Deprecated. Allow an application to register a document event handler.
void | setDTDHandler(DTDHandler handler) Deprecated. Allow an application to register a DTD event handler.
void | setEntityResolver(EntityResolver resolver) Deprecated. Allow an application to register a custom entity resolver.
void | setErrorHandler(ErrorHandler handler) Deprecated. Allow an application to register an error event handler.
void | setLocale(Locale locale) Deprecated. Allow an application to request a locale for errors and warnings.

Method Detail

setLocale

public void setLocale(Locale locale)
               throws SAXException
Deprecated.
Allow an application to request a locale for errors and warnings.

SAX parsers are not required to provide localisation for errors and warnings; if they cannot support the requested locale, however, they must throw a SAX exception. Applications may not request a locale change in the middle of a parse.

Parameters:
locale - A Java Locale object.
Throws:
SAXException - Throws an exception (using the previous or default locale) if the requested locale is not supported.
See Also:
SAXException, SAXParseException

setEntityResolver

public void setEntityResolver(EntityResolver resolver)
Deprecated.
Allow an application to register a custom entity resolver.

If the application does not register an entity resolver, the SAX parser will resolve system identifiers and open connections to entities itself (this is the default behaviour implemented in HandlerBase).

Applications may register a new or different entity resolver in the middle of a parse, and the SAX parser must begin using the new resolver immediately.

Parameters:
resolver - The object for resolving entities.
See Also:
EntityResolver, HandlerBase

setDTDHandler

public void setDTDHandler(DTDHandler handler)
Deprecated.
Allow an application to register a DTD event handler.

If the application does not register a DTD handler, all DTD events reported by the SAX parser will be silently ignored (this is the default behaviour implemented by HandlerBase).

Applications may register a new or different handler in the middle of a parse, and the SAX parser must begin using the new handler immediately.

Parameters:
handler - The DTD handler.
See Also:
DTDHandler, HandlerBase

setDocumentHandler

public void setDocumentHandler(DocumentHandler handler)
Deprecated.
Allow an application to register a document event handler.

If the application does not register a document handler, all document events reported by the SAX parser will be silently ignored (this is the default behaviour implemented by HandlerBase).

Applications may register a new or different handler in the middle of a parse, and the SAX parser must begin using the new handler immediately.

Parameters:
handler - The document handler.
See Also:
DocumentHandler, HandlerBase

setErrorHandler

public void setErrorHandler(ErrorHandler handler)
Deprecated.
Allow an application to register an error event handler.

If the application does not register an error event handler, all error events reported by the SAX parser will be silently ignored, except for fatalError, which will throw a SAXException (this is the default behaviour implemented by HandlerBase).

Applications may register a new or different handler in the middle of a parse, and the SAX parser must begin using the new handler immediately.

Parameters:
handler - The error handler.
See Also:
ErrorHandler, SAXException, HandlerBase

parse

public void parse(InputSource source)
           throws SAXException,
                  IOException
Deprecated.
Parse an XML document.

The application can use this method to instruct the SAX parser to begin parsing an XML document from any valid input source (a character stream, a byte stream, or a URI).

Applications may not invoke this method while a parse is in progress (they should create a new Parser instead for each additional XML document). Once a parse is complete, an application may reuse the same Parser object, possibly with a different input source.

Parameters:
source - The input source for the top-level of the XML document.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
IOException - An IO exception from the parser, possibly from a byte stream or character stream supplied by the application.
See Also:
InputSource,
parse(java.lang.String),
setEntityResolver(org.xml.sax.EntityResolver),
setDTDHandler(org.xml.sax.DTDHandler),
setDocumentHandler(org.xml.sax.DocumentHandler),
setErrorHandler(org.xml.sax.ErrorHandler)

parse

public void parse(String systemId)
           throws SAXException,
                  IOException
Deprecated.
Parse an XML document from a system identifier (URI).

This method is a shortcut for the common case of reading a document from a system identifier. It is the exact equivalent of the following:

 parse(new InputSource(systemId));

If the system identifier is a URL, it must be fully resolved by the application before it is passed to the parser.

Parameters:
systemId - The system identifier (URI).
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
IOException - An IO exception from the parser, possibly from a byte stream or character stream supplied by the application.
See Also:
parse(org.xml.sax.InputSource)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


SAXException (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.xml.sax
Class SAXException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.xml.sax.SAXException
All Implemented Interfaces:
Serializable
Direct Known Subclasses:
SAXNotRecognizedException, SAXNotSupportedException, SAXParseException
public class SAXException
extends Exception

Encapsulate a general SAX error or warning.

This module, both source code and documentation, is in the Public Domain, and comes with NO WARRANTY.

This class can contain basic error or warning information from either the XML parser or the application: a parser writer or application writer can subclass it to provide additional functionality. SAX handlers may throw this exception or any exception subclassed from it.

If the application needs to pass through other types of exceptions, it must wrap those exceptions in a SAXException or an exception derived from a SAXException.

If the parser or application needs to include information about a specific location in an XML document, it should use the SAXParseException subclass.

Since:
SAX 1.0
See Also:
SAXParseException, Serialized Form

Constructor Summary
SAXException(Exception e)
Create a new SAXException wrapping an existing exception.
SAXException(String message)
Create a new SAXException.
SAXException(String message, Exception e)
Create a new SAXException from an existing exception.
Method Summary
Exception | getException() Return the embedded exception, if any.
String | getMessage() Return a detail message for this exception.
String | toString() Override toString to pick up any embedded exception.
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

SAXException

public SAXException(String message)
Create a new SAXException.

Parameters:
message - The error or warning message.
See Also:
Parser.setLocale(java.util.Locale)

SAXException

public SAXException(Exception e)
Create a new SAXException wrapping an existing exception.

The existing exception will be embedded in the new one, and its message will become the default message for the SAXException.

Parameters:
e - The exception to be wrapped in a SAXException.

SAXException

public SAXException(String message,
                    Exception e)
Create a new SAXException from an existing exception.

The existing exception will be embedded in the new one, but the new exception will have its own message.

Parameters:
message - The detail message.
e - The exception to be wrapped in a SAXException.
See Also:
Parser.setLocale(java.util.Locale)
Method Detail

getMessage

public String getMessage()
Return a detail message for this exception.

If there is an embedded exception, and if the SAXException has no detail message of its own, this method will return the detail message from the embedded exception.

Overrides:
getMessage in class Throwable
Returns:
The error or warning message.
See Also:
Parser.setLocale(java.util.Locale)

getException

public Exception getException()
Return the embedded exception, if any.

Returns:
The embedded exception, or null if there is none.

toString

public String toString()
Override toString to pick up any embedded exception.

Overrides:
toString in class Throwable
Returns:
A string representation of this exception.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


SAXNotRecognizedException (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.xml.sax
Class SAXNotRecognizedException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.xml.sax.SAXException
                extended by org.xml.sax.SAXNotRecognizedException
All Implemented Interfaces:
Serializable
public class SAXNotRecognizedException
extends SAXException

Exception class for an unrecognized identifier.

This module, both source code and documentation, is in the Public Domain, and comes with NO WARRANTY.

An XMLReader will throw this exception when it finds an unrecognized feature or property identifier; SAX applications and extensions may use this class for other, similar purposes.

Since:
SAX 2.0
See Also:
SAXNotSupportedException, Serialized Form

Constructor Summary
SAXNotRecognizedException(String message)
Construct a new exception with the given message.
Methods inherited from class org.xml.sax.SAXException
getException, getMessage, toString
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

SAXNotRecognizedException

public SAXNotRecognizedException(String message)
Construct a new exception with the given message.

Parameters:
message - The text message of the exception.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


SAXNotSupportedException (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.xml.sax
Class SAXNotSupportedException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.xml.sax.SAXException
                extended by org.xml.sax.SAXNotSupportedException
All Implemented Interfaces:
Serializable
public class SAXNotSupportedException
extends SAXException

Exception class for an unsupported operation.

This module, both source code and documentation, is in the Public Domain, and comes with NO WARRANTY.

An XMLReader will throw this exception when it recognizes a feature or property identifier, but cannot perform the requested operation (setting a state or value). Other SAX2 applications and extensions may use this class for similar purposes.

Since:
SAX 2.0
See Also:
SAXNotRecognizedException, Serialized Form

Constructor Summary
SAXNotSupportedException(String message)
Construct a new exception with the given message.
Methods inherited from class org.xml.sax.SAXException
getException, getMessage, toString
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

SAXNotSupportedException

public SAXNotSupportedException(String message)
Construct a new exception with the given message.

Parameters:
message - The text message of the exception.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


SAXParseException (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.xml.sax
Class SAXParseException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by org.xml.sax.SAXException
                extended by org.xml.sax.SAXParseException
All Implemented Interfaces:
Serializable
public class SAXParseException
extends SAXException

Encapsulate an XML parse error or warning.

This module, both source code and documentation, is in the Public Domain, and comes with NO WARRANTY.

This exception will include information for locating the error in the original XML document. Note that although the application will receive a SAXParseException as the argument to the handlers in the ErrorHandler interface, the application is not actually required to throw the exception; instead, it can simply read the information in it and take a different action.

Since this exception is a subclass of SAXException, it inherits the ability to wrap another exception.

Since:
SAX 1.0
See Also:
SAXException, Locator, ErrorHandler, Serialized Form

Constructor Summary
SAXParseException(String message, Locator locator)
Create a new SAXParseException from a message and a Locator.
SAXParseException(String message, Locator locator, Exception e)
Wrap an existing exception in a SAXParseException.
SAXParseException(String message, String publicId, String systemId, int lineNumber, int columnNumber)
Create a new SAXParseException.
SAXParseException(String message, String publicId, String systemId, int lineNumber, int columnNumber, Exception e)
Create a new SAXParseException with an embedded exception.
Method Summary
int | getColumnNumber() The column number of the end of the text where the exception occurred.
int | getLineNumber() The line number of the end of the text where the exception occurred.
String | getPublicId() Get the public identifier of the entity where the exception occurred.
String | getSystemId() Get the system identifier of the entity where the exception occurred.
Methods inherited from class org.xml.sax.SAXException
getException, getMessage, toString
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

SAXParseException

public SAXParseException(String message,
                         Locator locator)
Create a new SAXParseException from a message and a Locator.

This constructor is especially useful when an application is creating its own exception from within a ContentHandler callback.

Parameters:
message - The error or warning message.
locator - The locator object for the error or warning (may be null).
See Also:
Locator, Parser.setLocale(java.util.Locale)

SAXParseException

public SAXParseException(String message,
                         Locator locator,
                         Exception e)
Wrap an existing exception in a SAXParseException.

This constructor is especially useful when an application is creating its own exception from within a ContentHandler callback, and needs to wrap an existing exception that is not a subclass of SAXException.

Parameters:
message - The error or warning message, or null to use the message from the embedded exception.
locator - The locator object for the error or warning (may be null).
e - Any exception.
See Also:
Locator, Parser.setLocale(java.util.Locale)

SAXParseException

public SAXParseException(String message,
                         String publicId,
                         String systemId,
                         int lineNumber,
                         int columnNumber)
Create a new SAXParseException.

This constructor is most useful for parser writers.

If the system identifier is a URL, the parser must resolve it fully before creating the exception.

Parameters:
message - The error or warning message.
publicId - The public identifer of the entity that generated the error or warning.
systemId - The system identifer of the entity that generated the error or warning.
lineNumber - The line number of the end of the text that caused the error or warning.
columnNumber - The column number of the end of the text that cause the error or warning.
See Also:
Parser.setLocale(java.util.Locale)

SAXParseException

public SAXParseException(String message,
                         String publicId,
                         String systemId,
                         int lineNumber,
                         int columnNumber,
                         Exception e)
Create a new SAXParseException with an embedded exception.

This constructor is most useful for parser writers who need to wrap an exception that is not a subclass of SAXException.

If the system identifier is a URL, the parser must resolve it fully before creating the exception.

Parameters:
message - The error or warning message, or null to use the message from the embedded exception.
publicId - The public identifer of the entity that generated the error or warning.
systemId - The system identifer of the entity that generated the error or warning.
lineNumber - The line number of the end of the text that caused the error or warning.
columnNumber - The column number of the end of the text that cause the error or warning.
e - Another exception to embed in this one.
See Also:
Parser.setLocale(java.util.Locale)
Method Detail

getPublicId

public String getPublicId()
Get the public identifier of the entity where the exception occurred.

Returns:
A string containing the public identifier, or null if none is available.
See Also:
Locator.getPublicId()

getSystemId

public String getSystemId()
Get the system identifier of the entity where the exception occurred.

If the system identifier is a URL, it will be resolved fully.

Returns:
A string containing the system identifier, or null if none is available.
See Also:
Locator.getSystemId()

getLineNumber

public int getLineNumber()
The line number of the end of the text where the exception occurred.

Returns:
An integer representing the line number, or -1 if none is available.
See Also:
Locator.getLineNumber()

getColumnNumber

public int getColumnNumber()
The column number of the end of the text where the exception occurred.

The first column in a line is position 1.

Returns:
An integer representing the column number, or -1 if none is available.
See Also:
Locator.getColumnNumber()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


XMLFilter (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.xml.sax
Interface XMLFilter

All Superinterfaces:
XMLReader
All Known Implementing Classes:
XMLFilterImpl
public interface XMLFilter
extends XMLReader

Interface for an XML filter.

This module, both source code and documentation, is in the Public Domain, and comes with NO WARRANTY.

An XML filter is like an XML reader, except that it obtains its events from another XML reader rather than a primary source like an XML document or database. Filters can modify a stream of events as they pass on to the final application.

The XMLFilterImpl helper class provides a convenient base for creating SAX2 filters, by passing on all EntityResolver, DTDHandler, ContentHandler and ErrorHandler events automatically.

Since:
SAX 2.0
See Also:
XMLFilterImpl

Method Summary
XMLReader | getParent() Get the parent reader.
void | setParent(XMLReader parent) Set the parent reader.
Methods inherited from interface org.xml.sax.XMLReader
getContentHandler, getDTDHandler, getEntityResolver, getErrorHandler, getFeature, getProperty, parse, parse, setContentHandler, setDTDHandler, setEntityResolver, setErrorHandler, setFeature, setProperty

Method Detail

setParent

public void setParent(XMLReader parent)
Set the parent reader.

This method allows the application to link the filter to a parent reader (which may be another filter). The argument may not be null.

Parameters:
parent - The parent reader.

getParent

public XMLReader getParent()
Get the parent reader.

This method allows the application to query the parent reader (which may be another filter). It is generally a bad idea to perform any operations on the parent reader directly: they should all pass through this filter.

Returns:
The parent filter, or null if none has been set.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


XMLReader (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.xml.sax
Interface XMLReader

All Known Subinterfaces:
XMLFilter
All Known Implementing Classes:
ParserAdapter, XMLFilterImpl
public interface XMLReader

Interface for reading an XML document using callbacks.

This module, both source code and documentation, is in the Public Domain, and comes with NO WARRANTY.

Note: despite its name, this interface does not extend the standard Java Reader interface, because reading XML is a fundamentally different activity than reading character data.

XMLReader is the interface that an XML parser's SAX2 driver must implement. This interface allows an application to set and query features and properties in the parser, to register event handlers for document processing, and to initiate a document parse.

All SAX interfaces are assumed to be synchronous: the parse methods must not return until parsing is complete, and readers must wait for an event-handler callback to return before reporting the next event.

This interface replaces the (now deprecated) SAX 1.0 Parser interface. The XMLReader interface contains two important enhancements over the old Parser interface:

  1. it adds a standard way to query and set features and properties; and
  2. it adds Namespace support, which is required for many higher-level XML standards.

There are adapters available to convert a SAX1 Parser to a SAX2 XMLReader and vice-versa.

Since:
SAX 2.0
See Also:
XMLFilter, ParserAdapter, XMLReaderAdapter

Method Summary
ContentHandler | getContentHandler() Return the current content handler.
DTDHandler | getDTDHandler() Return the current DTD handler.
EntityResolver | getEntityResolver() Return the current entity resolver.
ErrorHandler | getErrorHandler() Return the current error handler.
boolean | getFeature(String name) Look up the value of a feature.
Object | getProperty(String name) Look up the value of a property.
void | parse(InputSource input) Parse an XML document.
void | parse(String systemId) Parse an XML document from a system identifier (URI).
void | setContentHandler(ContentHandler handler) Allow an application to register a content event handler.
void | setDTDHandler(DTDHandler handler) Allow an application to register a DTD event handler.
void | setEntityResolver(EntityResolver resolver) Allow an application to register an entity resolver.
void | setErrorHandler(ErrorHandler handler) Allow an application to register an error event handler.
void | setFeature(String name, boolean value) Set the state of a feature.
void | setProperty(String name, Object value) Set the value of a property.

Method Detail

getFeature

public boolean getFeature(String name)
                   throws SAXNotRecognizedException,
                          SAXNotSupportedException
Look up the value of a feature.

The feature name is any fully-qualified URI. It is possible for an XMLReader to recognize a feature name but to be unable to return its value; this is especially true in the case of an adapter for a SAX1 Parser, which has no way of knowing whether the underlying parser is performing validation or expanding external entities.

All XMLReaders are required to recognize the http://xml.org/sax/features/namespaces and the http://xml.org/sax/features/namespace-prefixes feature names.

Some feature values may be available only in specific contexts, such as before, during, or after a parse.

Typical usage is something like this:

 XMLReader r = new MySAXDriver();

                         // try to activate validation
 try {
   r.setFeature("http://xml.org/sax/features/validation", true);
 } catch (SAXException e) {
   System.err.println("Cannot activate validation.");
 }

                         // register event handlers
 r.setContentHandler(new MyContentHandler());
 r.setErrorHandler(new MyErrorHandler());

                         // parse the first document
 try {
   r.parse("http://www.foo.com/mydoc.xml");
 } catch (IOException e) {
   System.err.println("I/O exception reading XML document");
 } catch (SAXException e) {
   System.err.println("XML exception reading document.");
 }

Implementors are free (and encouraged) to invent their own features, using names built on their own URIs.

Parameters:
name - The feature name, which is a fully-qualified URI.
Returns:
The current state of the feature (true or false).
Throws:
SAXNotRecognizedException - When the XMLReader does not recognize the feature name.
SAXNotSupportedException - When the XMLReader recognizes the feature name but cannot determine its value at this time.
See Also:
setFeature(java.lang.String, boolean)

setFeature

public void setFeature(String name,
                       boolean value)
                throws SAXNotRecognizedException,
                       SAXNotSupportedException
Set the state of a feature.

The feature name is any fully-qualified URI. It is possible for an XMLReader to recognize a feature name but to be unable to set its value; this is especially true in the case of an adapter for a SAX1 Parser, which has no way of affecting whether the underlying parser is validating, for example.

All XMLReaders are required to support setting http://xml.org/sax/features/namespaces to true and http://xml.org/sax/features/namespace-prefixes to false.

Some feature values may be immutable or mutable only in specific contexts, such as before, during, or after a parse.

Parameters:
name - The feature name, which is a fully-qualified URI.
Throws:
SAXNotRecognizedException - When the XMLReader does not recognize the feature name.
SAXNotSupportedException - When the XMLReader recognizes the feature name but cannot set the requested value.
See Also:
getFeature(java.lang.String)

getProperty

public Object getProperty(String name)
                   throws SAXNotRecognizedException,
                          SAXNotSupportedException
Look up the value of a property.

The property name is any fully-qualified URI. It is possible for an XMLReader to recognize a property name but to be unable to return its state; this is especially true in the case of an adapter for a SAX1 Parser.

XMLReaders are not required to recognize any specific property names, though an initial core set is documented for SAX2.

Some property values may be available only in specific contexts, such as before, during, or after a parse.

Implementors are free (and encouraged) to invent their own properties, using names built on their own URIs.

Parameters:
name - The property name, which is a fully-qualified URI.
Returns:
The current value of the property.
Throws:
SAXNotRecognizedException - When the XMLReader does not recognize the property name.
SAXNotSupportedException - When the XMLReader recognizes the property name but cannot determine its value at this time.
See Also:
setProperty(java.lang.String, java.lang.Object)

setProperty

public void setProperty(String name,
                        Object value)
                 throws SAXNotRecognizedException,
                        SAXNotSupportedException
Set the value of a property.

The property name is any fully-qualified URI. It is possible for an XMLReader to recognize a property name but to be unable to set its value; this is especially true in the case of an adapter for a SAX1 Parser.

XMLReaders are not required to recognize setting any specific property names, though a core set is provided with SAX2.

Some property values may be immutable or mutable only in specific contexts, such as before, during, or after a parse.

This method is also the standard mechanism for setting extended handlers.

Parameters:
name - The property name, which is a fully-qualified URI.
Throws:
SAXNotRecognizedException - When the XMLReader does not recognize the property name.
SAXNotSupportedException - When the XMLReader recognizes the property name but cannot set the requested value.

setEntityResolver

public void setEntityResolver(EntityResolver resolver)
Allow an application to register an entity resolver.

If the application does not register an entity resolver, the XMLReader will perform its own default resolution.

Applications may register a new or different resolver in the middle of a parse, and the SAX parser must begin using the new resolver immediately.

Parameters:
resolver - The entity resolver.
Throws:
NullPointerException - If the resolver argument is null.
See Also:
getEntityResolver()

getEntityResolver

public EntityResolver getEntityResolver()
Return the current entity resolver.

Returns:
The current entity resolver, or null if none has been registered.
See Also:
setEntityResolver(org.xml.sax.EntityResolver)

setDTDHandler

public void setDTDHandler(DTDHandler handler)
Allow an application to register a DTD event handler.

If the application does not register a DTD handler, all DTD events reported by the SAX parser will be silently ignored.

Applications may register a new or different handler in the middle of a parse, and the SAX parser must begin using the new handler immediately.

Parameters:
handler - The DTD handler.
Throws:
NullPointerException - If the handler argument is null.
See Also:
getDTDHandler()

getDTDHandler

public DTDHandler getDTDHandler()
Return the current DTD handler.

Returns:
The current DTD handler, or null if none has been registered.
See Also:
setDTDHandler(org.xml.sax.DTDHandler)

setContentHandler

public void setContentHandler(ContentHandler handler)
Allow an application to register a content event handler.

If the application does not register a content handler, all content events reported by the SAX parser will be silently ignored.

Applications may register a new or different handler in the middle of a parse, and the SAX parser must begin using the new handler immediately.

Parameters:
handler - The content handler.
Throws:
NullPointerException - If the handler argument is null.
See Also:
getContentHandler()

getContentHandler

public ContentHandler getContentHandler()
Return the current content handler.

Returns:
The current content handler, or null if none has been registered.
See Also:
setContentHandler(org.xml.sax.ContentHandler)

setErrorHandler

public void setErrorHandler(ErrorHandler handler)
Allow an application to register an error event handler.

If the application does not register an error handler, all error events reported by the SAX parser will be silently ignored; however, normal processing may not continue. It is highly recommended that all SAX applications implement an error handler to avoid unexpected bugs.

Applications may register a new or different handler in the middle of a parse, and the SAX parser must begin using the new handler immediately.

Parameters:
handler - The error handler.
Throws:
NullPointerException - If the handler argument is null.
See Also:
getErrorHandler()

getErrorHandler

public ErrorHandler getErrorHandler()
Return the current error handler.

Returns:
The current error handler, or null if none has been registered.
See Also:
setErrorHandler(org.xml.sax.ErrorHandler)

parse

public void parse(InputSource input)
           throws IOException,
                  SAXException
Parse an XML document.

The application can use this method to instruct the XML reader to begin parsing an XML document from any valid input source (a character stream, a byte stream, or a URI).

Applications may not invoke this method while a parse is in progress (they should create a new XMLReader instead for each nested XML document). Once a parse is complete, an application may reuse the same XMLReader object, possibly with a different input source.

During the parse, the XMLReader will provide information about the XML document through the registered event handlers.

This method is synchronous: it will not return until parsing has ended. If a client application wants to terminate parsing early, it should throw an exception.

Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
IOException - An IO exception from the parser, possibly from a byte stream or character stream supplied by the application.
See Also:
InputSource,
parse(java.lang.String),
setEntityResolver(org.xml.sax.EntityResolver),
setDTDHandler(org.xml.sax.DTDHandler),
setContentHandler(org.xml.sax.ContentHandler),
setErrorHandler(org.xml.sax.ErrorHandler)

parse

public void parse(String systemId)
           throws IOException,
                  SAXException
Parse an XML document from a system identifier (URI).

This method is a shortcut for the common case of reading a document from a system identifier. It is the exact equivalent of the following:

 parse(new InputSource(systemId));

If the system identifier is a URL, it must be fully resolved by the application before it is passed to the parser.

Parameters:
systemId - The system identifier (URI).
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
IOException - An IO exception from the parser, possibly from a byte stream or character stream supplied by the application.
See Also:
parse(org.xml.sax.InputSource)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Uses of Interface org.xml.sax.AttributeList (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.xml.sax.AttributeList

Packages that use AttributeList
org.xml.sax | Provides the classes and interfaces for the Simple API for XML (SAX) which is a component of the Java API for XML Processing.
org.xml.sax.helpers | Provides helper classes for the Simple API for XML (SAX) which is a component of the Java API for XML Processing.

Uses of AttributeList in org.xml.sax

Methods in org.xml.sax with parameters of type AttributeList
void | HandlerBase.startElement(String name, AttributeList attributes) Deprecated. Receive notification of the start of an element.
void | DocumentHandler.startElement(String name, AttributeList atts) Deprecated. Receive notification of the beginning of an element.

Uses of AttributeList in org.xml.sax.helpers

Classes in org.xml.sax.helpers that implement AttributeList
 class AttributeListImpl
Deprecated. This class implements a deprecated interface, AttributeList; that interface has been replaced by Attributes, which is implemented in the AttributesImpl helper class.

Methods in org.xml.sax.helpers with parameters of type AttributeList
void | AttributeListImpl.setAttributeList(AttributeList atts) Deprecated. Set the attribute list, discarding previous contents.
void | ParserAdapter.startElement(String qName, AttributeList qAtts) Adapt a SAX1 startElement event.

Constructors in org.xml.sax.helpers with parameters of type AttributeList
AttributeListImpl(AttributeList atts)
Deprecated. Construct a persistent copy of an existing attribute list.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.xml.sax.Attributes (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.xml.sax.Attributes

Packages that use Attributes
org.xml.sax | Provides the classes and interfaces for the Simple API for XML (SAX) which is a component of the Java API for XML Processing.
org.xml.sax.helpers | Provides helper classes for the Simple API for XML (SAX) which is a component of the Java API for XML Processing.

Uses of Attributes in org.xml.sax

Methods in org.xml.sax with parameters of type Attributes
 void ContentHandler.startElement(String namespaceURI, String localName, String qName, Attributes atts)
Receive notification of the beginning of an element.

Uses of Attributes in org.xml.sax.helpers

Classes in org.xml.sax.helpers that implement Attributes
 class AttributesImpl
Default implementation of the Attributes interface.

Methods in org.xml.sax.helpers with parameters of type Attributes
void | XMLReaderAdapter.startElement(String uri, String localName, String qName, Attributes atts) Adapt a SAX2 start element event.
void | XMLFilterImpl.startElement(String uri, String localName, String qName, Attributes atts) Filter a start element event.
void | AttributesImpl.setAttributes(Attributes atts) Copy an entire Attributes object.
void | DefaultHandler.startElement(String uri, String localName, String qName, Attributes attributes) Receive notification of the start of an element.

Constructors in org.xml.sax.helpers with parameters of type Attributes
AttributesImpl(Attributes atts)
Copy an existing Attributes object.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.xml.sax.ContentHandler (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.xml.sax.ContentHandler

Packages that use ContentHandler
javax.xml.transform.sax | This package implements SAX2-specific transformation APIs.
org.xml.sax | Provides the classes and interfaces for the Simple API for XML (SAX) which is a component of the Java API for XML Processing.
org.xml.sax.helpers | Provides helper classes for the Simple API for XML (SAX) which is a component of the Java API for XML Processing.

Uses of ContentHandler in javax.xml.transform.sax

Subinterfaces of ContentHandler in javax.xml.transform.sax
interface | TemplatesHandler A SAX ContentHandler that may be used to process SAX parse events (parsing transformation instructions) into a Templates object.
interface | TransformerHandler A TransformerHandler listens for SAX ContentHandler parse events and transforms them to a Result.

Methods in javax.xml.transform.sax that return ContentHandler
 ContentHandler SAXResult.getHandler()
Get the ContentHandler that is the Result.

Methods in javax.xml.transform.sax with parameters of type ContentHandler
 void SAXResult.setHandler(ContentHandler handler)
Set the target to be a SAX2 ContentHandler.

Constructors in javax.xml.transform.sax with parameters of type ContentHandler
SAXResult(ContentHandler handler)
Create a SAXResult that targets a SAX2 ContentHandler.

Uses of ContentHandler in org.xml.sax

Methods in org.xml.sax that return ContentHandler
 ContentHandler XMLReader.getContentHandler()
Return the current content handler.

Methods in org.xml.sax with parameters of type ContentHandler
 void XMLReader.setContentHandler(ContentHandler handler)
Allow an application to register a content event handler.

Uses of ContentHandler in org.xml.sax.helpers

Classes in org.xml.sax.helpers that implement ContentHandler
class | DefaultHandler Default base class for SAX2 event handlers.
class | XMLFilterImpl Base class for deriving an XML filter.
class | XMLReaderAdapter Adapt a SAX2 XMLReader as a SAX1 Parser.

Methods in org.xml.sax.helpers that return ContentHandler
ContentHandler | XMLFilterImpl.getContentHandler() Get the content event handler.
ContentHandler | ParserAdapter.getContentHandler() Return the current content handler.

Methods in org.xml.sax.helpers with parameters of type ContentHandler
void | XMLFilterImpl.setContentHandler(ContentHandler handler) Set the content event handler.
void | ParserAdapter.setContentHandler(ContentHandler handler) Set the content handler.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.xml.sax.DocumentHandler (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.xml.sax.DocumentHandler

Packages that use DocumentHandler
org.xml.sax | Provides the classes and interfaces for the Simple API for XML (SAX) which is a component of the Java API for XML Processing.
org.xml.sax.helpers | Provides helper classes for the Simple API for XML (SAX) which is a component of the Java API for XML Processing.

Uses of DocumentHandler in org.xml.sax

Classes in org.xml.sax that implement DocumentHandler
 class HandlerBase
Deprecated. This class works with the deprecated DocumentHandler interface. It has been replaced by the SAX2 DefaultHandler class.

Methods in org.xml.sax with parameters of type DocumentHandler
 void Parser.setDocumentHandler(DocumentHandler handler)
Deprecated. Allow an application to register a document event handler.

Uses of DocumentHandler in org.xml.sax.helpers

Classes in org.xml.sax.helpers that implement DocumentHandler
 class ParserAdapter
Adapt a SAX1 Parser as a SAX2 XMLReader.

Methods in org.xml.sax.helpers with parameters of type DocumentHandler
 void XMLReaderAdapter.setDocumentHandler(DocumentHandler handler)
Register the SAX1 document event handler.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.xml.sax.DTDHandler (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.xml.sax.DTDHandler

Packages that use DTDHandler
javax.xml.transform.sax | This package implements SAX2-specific transformation APIs.
org.xml.sax | Provides the classes and interfaces for the Simple API for XML (SAX) which is a component of the Java API for XML Processing.
org.xml.sax.helpers | Provides helper classes for the Simple API for XML (SAX) which is a component of the Java API for XML Processing.

Uses of DTDHandler in javax.xml.transform.sax

Subinterfaces of DTDHandler in javax.xml.transform.sax
 interface TransformerHandler
A TransformerHandler listens for SAX ContentHandler parse events and transforms them to a Result.

Uses of DTDHandler in org.xml.sax

Classes in org.xml.sax that implement DTDHandler
 class HandlerBase
Deprecated. This class works with the deprecated DocumentHandler interface. It has been replaced by the SAX2 DefaultHandler class.

Methods in org.xml.sax that return DTDHandler
 DTDHandler XMLReader.getDTDHandler()
Return the current DTD handler.

Methods in org.xml.sax with parameters of type DTDHandler
void | Parser.setDTDHandler(DTDHandler handler) Deprecated. Allow an application to register a DTD event handler.
void | XMLReader.setDTDHandler(DTDHandler handler) Allow an application to register a DTD event handler.

Uses of DTDHandler in org.xml.sax.helpers

Classes in org.xml.sax.helpers that implement DTDHandler
class | DefaultHandler Default base class for SAX2 event handlers.
class | XMLFilterImpl Base class for deriving an XML filter.

Methods in org.xml.sax.helpers that return DTDHandler
DTDHandler | XMLFilterImpl.getDTDHandler() Get the current DTD event handler.
DTDHandler | ParserAdapter.getDTDHandler() Return the current DTD handler.

Methods in org.xml.sax.helpers with parameters of type DTDHandler
void | XMLReaderAdapter.setDTDHandler(DTDHandler handler) Register the DTD event handler.
void | XMLFilterImpl.setDTDHandler(DTDHandler handler) Set the DTD event handler.
void | ParserAdapter.setDTDHandler(DTDHandler handler) Set the DTD handler.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.xml.sax.EntityResolver (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.xml.sax.EntityResolver

Packages that use EntityResolver
javax.xml.parsers | Provides classes allowing the processing of XML documents.
org.xml.sax | Provides the classes and interfaces for the Simple API for XML (SAX) which is a component of the Java API for XML Processing.
org.xml.sax.helpers | Provides helper classes for the Simple API for XML (SAX) which is a component of the Java API for XML Processing.

Uses of EntityResolver in javax.xml.parsers

Methods in javax.xml.parsers with parameters of type EntityResolver
abstract  void DocumentBuilder.setEntityResolver(EntityResolver er)
Specify the EntityResolver to be used to resolve entities present in the XML document to be parsed.

Uses of EntityResolver in org.xml.sax

Classes in org.xml.sax that implement EntityResolver
 class HandlerBase
Deprecated. This class works with the deprecated DocumentHandler interface. It has been replaced by the SAX2 DefaultHandler class.

Methods in org.xml.sax that return EntityResolver
 EntityResolver XMLReader.getEntityResolver()
Return the current entity resolver.

Methods in org.xml.sax with parameters of type EntityResolver
void | Parser.setEntityResolver(EntityResolver resolver) Deprecated. Allow an application to register a custom entity resolver.
void | XMLReader.setEntityResolver(EntityResolver resolver) Allow an application to register an entity resolver.

Uses of EntityResolver in org.xml.sax.helpers

Classes in org.xml.sax.helpers that implement EntityResolver
class | DefaultHandler Default base class for SAX2 event handlers.
class | XMLFilterImpl Base class for deriving an XML filter.

Methods in org.xml.sax.helpers that return EntityResolver
EntityResolver | XMLFilterImpl.getEntityResolver() Get the current entity resolver.
EntityResolver | ParserAdapter.getEntityResolver() Return the current entity resolver.

Methods in org.xml.sax.helpers with parameters of type EntityResolver
void | XMLReaderAdapter.setEntityResolver(EntityResolver resolver) Register the entity resolver.
void | XMLFilterImpl.setEntityResolver(EntityResolver resolver) Set the entity resolver.
void | ParserAdapter.setEntityResolver(EntityResolver resolver) Set the entity resolver.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.xml.sax.ErrorHandler (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.xml.sax.ErrorHandler

Packages that use ErrorHandler
javax.xml.parsers | Provides classes allowing the processing of XML documents.
org.xml.sax | Provides the classes and interfaces for the Simple API for XML (SAX) which is a component of the Java API for XML Processing.
org.xml.sax.helpers | Provides helper classes for the Simple API for XML (SAX) which is a component of the Java API for XML Processing.

Uses of ErrorHandler in javax.xml.parsers

Methods in javax.xml.parsers with parameters of type ErrorHandler
abstract  void DocumentBuilder.setErrorHandler(ErrorHandler eh)
Specify the ErrorHandler to be used to report errors present in the XML document to be parsed.

Uses of ErrorHandler in org.xml.sax

Classes in org.xml.sax that implement ErrorHandler
 class HandlerBase
Deprecated. This class works with the deprecated DocumentHandler interface. It has been replaced by the SAX2 DefaultHandler class.

Methods in org.xml.sax that return ErrorHandler
 ErrorHandler XMLReader.getErrorHandler()
Return the current error handler.

Methods in org.xml.sax with parameters of type ErrorHandler
void | Parser.setErrorHandler(ErrorHandler handler) Deprecated. Allow an application to register an error event handler.
void | XMLReader.setErrorHandler(ErrorHandler handler) Allow an application to register an error event handler.

Uses of ErrorHandler in org.xml.sax.helpers

Classes in org.xml.sax.helpers that implement ErrorHandler
class | DefaultHandler Default base class for SAX2 event handlers.
class | XMLFilterImpl Base class for deriving an XML filter.

Methods in org.xml.sax.helpers that return ErrorHandler
ErrorHandler | XMLFilterImpl.getErrorHandler() Get the current error event handler.
ErrorHandler | ParserAdapter.getErrorHandler() Return the current error handler.

Methods in org.xml.sax.helpers with parameters of type ErrorHandler
void | XMLReaderAdapter.setErrorHandler(ErrorHandler handler) Register the error event handler.
void | XMLFilterImpl.setErrorHandler(ErrorHandler handler) Set the error event handler.
void | ParserAdapter.setErrorHandler(ErrorHandler handler) Set the error handler.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.xml.sax.HandlerBase (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.xml.sax.HandlerBase

Packages that use HandlerBase
javax.xml.parsers Provides classes allowing the processing of XML documents.

Uses of HandlerBase in javax.xml.parsers

Methods in javax.xml.parsers with parameters of type HandlerBase
void | SAXParser.parse(InputStream is, HandlerBase hb) Parse the content of the given InputStream instance as XML using the specified HandlerBase.
void | SAXParser.parse(InputStream is, HandlerBase hb, String systemId) Parse the content of the given InputStream instance as XML using the specified HandlerBase.
void | SAXParser.parse(String uri, HandlerBase hb) Parse the content described by the giving Uniform Resource Identifier (URI) as XML using the specified HandlerBase.
void | SAXParser.parse(File f, HandlerBase hb) Parse the content of the file specified as XML using the specified HandlerBase.
void | SAXParser.parse(InputSource is, HandlerBase hb) Parse the content given InputSource as XML using the specified HandlerBase.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.xml.sax.InputSource (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.xml.sax.InputSource

Packages that use InputSource
javax.xml.parsers | Provides classes allowing the processing of XML documents.
javax.xml.transform.sax | This package implements SAX2-specific transformation APIs.
org.xml.sax | Provides the classes and interfaces for the Simple API for XML (SAX) which is a component of the Java API for XML Processing.
org.xml.sax.helpers | Provides helper classes for the Simple API for XML (SAX) which is a component of the Java API for XML Processing.

Uses of InputSource in javax.xml.parsers

Methods in javax.xml.parsers with parameters of type InputSource
void | SAXParser.parse(InputSource is, HandlerBase hb) Parse the content given InputSource as XML using the specified HandlerBase.
void | SAXParser.parse(InputSource is, DefaultHandler dh) Parse the content given InputSource as XML using the specified DefaultHandler.
abstract Document | DocumentBuilder.parse(InputSource is) Parse the content of the given input source as an XML document and return a new DOM Document object.

Uses of InputSource in javax.xml.transform.sax

Methods in javax.xml.transform.sax that return InputSource
InputSource | SAXSource.getInputSource() Get the SAX InputSource to be used for the Source.
static InputSource | SAXSource.sourceToInputSource(Source source) Attempt to obtain a SAX InputSource object from a TrAX Source object.

Methods in javax.xml.transform.sax with parameters of type InputSource
 void SAXSource.setInputSource(InputSource inputSource)
Set the SAX InputSource to be used for the Source.

Constructors in javax.xml.transform.sax with parameters of type InputSource
SAXSource(XMLReader reader, InputSource inputSource)
Create a SAXSource, using an XMLReader and a SAX InputSource.
SAXSource(InputSource inputSource)
Create a SAXSource, using a SAX InputSource.

Uses of InputSource in org.xml.sax

Methods in org.xml.sax that return InputSource
InputSource | HandlerBase.resolveEntity(String publicId, String systemId) Deprecated. Resolve an external entity.
InputSource | EntityResolver.resolveEntity(String publicId, String systemId) Allow the application to resolve external entities.

Methods in org.xml.sax with parameters of type InputSource
void | Parser.parse(InputSource source) Deprecated. Parse an XML document.
void | XMLReader.parse(InputSource input) Parse an XML document.

Uses of InputSource in org.xml.sax.helpers

Methods in org.xml.sax.helpers that return InputSource
InputSource | XMLFilterImpl.resolveEntity(String publicId, String systemId) Filter an external entity resolution.
InputSource | DefaultHandler.resolveEntity(String publicId, String systemId) Resolve an external entity.

Methods in org.xml.sax.helpers with parameters of type InputSource
void | XMLReaderAdapter.parse(InputSource input) Parse the document.
void | XMLFilterImpl.parse(InputSource input) Parse a document.
void | ParserAdapter.parse(InputSource input) Parse an XML document.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.xml.sax.Locator (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.xml.sax.Locator

Packages that use Locator
org.xml.sax | Provides the classes and interfaces for the Simple API for XML (SAX) which is a component of the Java API for XML Processing.
org.xml.sax.helpers | Provides helper classes for the Simple API for XML (SAX) which is a component of the Java API for XML Processing.

Uses of Locator in org.xml.sax

Methods in org.xml.sax with parameters of type Locator
void | HandlerBase.setDocumentLocator(Locator locator) Deprecated. Receive a Locator object for document events.
void | DocumentHandler.setDocumentLocator(Locator locator) Deprecated. Receive an object for locating the origin of SAX document events.
void | ContentHandler.setDocumentLocator(Locator locator) Receive an object for locating the origin of SAX document events.

Constructors in org.xml.sax with parameters of type Locator
SAXParseException(String message, Locator locator)
Create a new SAXParseException from a message and a Locator.
SAXParseException(String message, Locator locator, Exception e)
Wrap an existing exception in a SAXParseException.

Uses of Locator in org.xml.sax.helpers

Classes in org.xml.sax.helpers that implement Locator
 class LocatorImpl
Provide an optional convenience implementation of Locator.

Methods in org.xml.sax.helpers with parameters of type Locator
void | XMLReaderAdapter.setDocumentLocator(Locator locator) Set a document locator.
void | XMLFilterImpl.setDocumentLocator(Locator locator) Filter a new document locator event.
void | ParserAdapter.setDocumentLocator(Locator locator) Adapt a SAX1 document locator event.
void | DefaultHandler.setDocumentLocator(Locator locator) Receive a Locator object for document events.

Constructors in org.xml.sax.helpers with parameters of type Locator
LocatorImpl(Locator locator)
Copy constructor.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.xml.sax.Parser (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.xml.sax.Parser

Packages that use Parser
javax.xml.parsers | Provides classes allowing the processing of XML documents.
org.xml.sax.helpers | Provides helper classes for the Simple API for XML (SAX) which is a component of the Java API for XML Processing.

Uses of Parser in javax.xml.parsers

Methods in javax.xml.parsers that return Parser
abstract  Parser SAXParser.getParser()
Returns the SAX parser that is encapsultated by the implementation of this class.

Uses of Parser in org.xml.sax.helpers

Classes in org.xml.sax.helpers that implement Parser
 class XMLReaderAdapter
Adapt a SAX2 XMLReader as a SAX1 Parser.

Methods in org.xml.sax.helpers that return Parser
static Parser | ParserFactory.makeParser() Deprecated. Create a new SAX parser using the `org.xml.sax.parser' system property.
static Parser | ParserFactory.makeParser(String className) Deprecated. Create a new SAX parser object using the class name provided.

Constructors in org.xml.sax.helpers with parameters of type Parser
ParserAdapter(Parser parser)
Construct a new parser adapter.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.xml.sax.SAXException (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.xml.sax.SAXException

Packages that use SAXException
javax.xml.parsers | Provides classes allowing the processing of XML documents.
org.xml.sax | Provides the classes and interfaces for the Simple API for XML (SAX) which is a component of the Java API for XML Processing.
org.xml.sax.ext | Provides extension classes and interfaces for the Simple API for XML (SAX) which is a component of the Java API for XML Processing.
org.xml.sax.helpers | Provides helper classes for the Simple API for XML (SAX) which is a component of the Java API for XML Processing.

Uses of SAXException in javax.xml.parsers

Methods in javax.xml.parsers that throw SAXException
void | SAXParser.parse(InputStream is, HandlerBase hb) Parse the content of the given InputStream instance as XML using the specified HandlerBase.
void | SAXParser.parse(InputStream is, HandlerBase hb, String systemId) Parse the content of the given InputStream instance as XML using the specified HandlerBase.
void | SAXParser.parse(InputStream is, DefaultHandler dh) Parse the content of the given InputStream instance as XML using the specified DefaultHandler.
void | SAXParser.parse(InputStream is, DefaultHandler dh, String systemId) Parse the content of the given InputStream instance as XML using the specified DefaultHandler.
void | SAXParser.parse(String uri, HandlerBase hb) Parse the content described by the giving Uniform Resource Identifier (URI) as XML using the specified HandlerBase.
void | SAXParser.parse(String uri, DefaultHandler dh) Parse the content described by the giving Uniform Resource Identifier (URI) as XML using the specified DefaultHandler.
void | SAXParser.parse(File f, HandlerBase hb) Parse the content of the file specified as XML using the specified HandlerBase.
void | SAXParser.parse(File f, DefaultHandler dh) Parse the content of the file specified as XML using the specified DefaultHandler.
void | SAXParser.parse(InputSource is, HandlerBase hb) Parse the content given InputSource as XML using the specified HandlerBase.
void | SAXParser.parse(InputSource is, DefaultHandler dh) Parse the content given InputSource as XML using the specified DefaultHandler.
abstract Parser | SAXParser.getParser() Returns the SAX parser that is encapsultated by the implementation of this class.
abstract XMLReader | SAXParser.getXMLReader() Returns the XMLReader that is encapsulated by the implementation of this class.
abstract SAXParser | SAXParserFactory.newSAXParser() Creates a new instance of a SAXParser using the currently configured factory parameters.
Document | DocumentBuilder.parse(InputStream is) Parse the content of the given InputStream as an XML document and return a new DOM Document object.
Document | DocumentBuilder.parse(InputStream is, String systemId) Parse the content of the given InputStream as an XML document and return a new DOM Document object.
Document | DocumentBuilder.parse(String uri) Parse the content of the given URI as an XML document and return a new DOM Document object.
Document | DocumentBuilder.parse(File f) Parse the content of the given file as an XML document and return a new DOM Document object.
abstract Document | DocumentBuilder.parse(InputSource is) Parse the content of the given input source as an XML document and return a new DOM Document object.

Uses of SAXException in org.xml.sax

Subclasses of SAXException in org.xml.sax
class | SAXNotRecognizedException Exception class for an unrecognized identifier.
class | SAXNotSupportedException Exception class for an unsupported operation.
class | SAXParseException Encapsulate an XML parse error or warning.

Methods in org.xml.sax that throw SAXException
InputSource | HandlerBase.resolveEntity(String publicId, String systemId) Deprecated. Resolve an external entity.
void | HandlerBase.startDocument() Deprecated. Receive notification of the beginning of the document.
void | HandlerBase.endDocument() Deprecated. Receive notification of the end of the document.
void | HandlerBase.startElement(String name, AttributeList attributes) Deprecated. Receive notification of the start of an element.
void | HandlerBase.endElement(String name) Deprecated. Receive notification of the end of an element.
void | HandlerBase.characters(char[] ch, int start, int length) Deprecated. Receive notification of character data inside an element.
void | HandlerBase.ignorableWhitespace(char[] ch, int start, int length) Deprecated. Receive notification of ignorable whitespace in element content.
void | HandlerBase.processingInstruction(String target, String data) Deprecated. Receive notification of a processing instruction.
void | HandlerBase.warning(SAXParseException e) Deprecated. Receive notification of a parser warning.
void | HandlerBase.error(SAXParseException e) Deprecated. Receive notification of a recoverable parser error.
void | HandlerBase.fatalError(SAXParseException e) Deprecated. Report a fatal XML parsing error.
void | DocumentHandler.startDocument() Deprecated. Receive notification of the beginning of a document.
void | DocumentHandler.endDocument() Deprecated. Receive notification of the end of a document.
void | DocumentHandler.startElement(String name, AttributeList atts) Deprecated. Receive notification of the beginning of an element.
void | DocumentHandler.endElement(String name) Deprecated. Receive notification of the end of an element.
void | DocumentHandler.characters(char[] ch, int start, int length) Deprecated. Receive notification of character data.
void | DocumentHandler.ignorableWhitespace(char[] ch, int start, int length) Deprecated. Receive notification of ignorable whitespace in element content.
void | DocumentHandler.processingInstruction(String target, String data) Deprecated. Receive notification of a processing instruction.
void | Parser.setLocale(Locale locale) Deprecated. Allow an application to request a locale for errors and warnings.
void | Parser.parse(InputSource source) Deprecated. Parse an XML document.
void | Parser.parse(String systemId) Deprecated. Parse an XML document from a system identifier (URI).
void | XMLReader.parse(InputSource input) Parse an XML document.
void | XMLReader.parse(String systemId) Parse an XML document from a system identifier (URI).
void | ContentHandler.startDocument() Receive notification of the beginning of a document.
void | ContentHandler.endDocument() Receive notification of the end of a document.
void | ContentHandler.startPrefixMapping(String prefix, String uri) Begin the scope of a prefix-URI Namespace mapping.
void | ContentHandler.endPrefixMapping(String prefix) End the scope of a prefix-URI mapping.
void | ContentHandler.startElement(String namespaceURI, String localName, String qName, Attributes atts) Receive notification of the beginning of an element.
void | ContentHandler.endElement(String namespaceURI, String localName, String qName) Receive notification of the end of an element.
void | ContentHandler.characters(char[] ch, int start, int length) Receive notification of character data.
void | ContentHandler.ignorableWhitespace(char[] ch, int start, int length) Receive notification of ignorable whitespace in element content.
void | ContentHandler.processingInstruction(String target, String data) Receive notification of a processing instruction.
void | ContentHandler.skippedEntity(String name) Receive notification of a skipped entity.
void | DTDHandler.notationDecl(String name, String publicId, String systemId) Receive notification of a notation declaration event.
void | DTDHandler.unparsedEntityDecl(String name, String publicId, String systemId, String notationName) Receive notification of an unparsed entity declaration event.
void | ErrorHandler.warning(SAXParseException exception) Receive notification of a warning.
void | ErrorHandler.error(SAXParseException exception) Receive notification of a recoverable error.
void | ErrorHandler.fatalError(SAXParseException exception) Receive notification of a non-recoverable error.
InputSource | EntityResolver.resolveEntity(String publicId, String systemId) Allow the application to resolve external entities.

Uses of SAXException in org.xml.sax.ext

Methods in org.xml.sax.ext that throw SAXException
void | LexicalHandler.startDTD(String name, String publicId, String systemId) Report the start of DTD declarations, if any.
void | LexicalHandler.endDTD() Report the end of DTD declarations.
void | LexicalHandler.startEntity(String name) Report the beginning of some internal and external XML entities.
void | LexicalHandler.endEntity(String name) Report the end of an entity.
void | LexicalHandler.startCDATA() Report the start of a CDATA section.
void | LexicalHandler.endCDATA() Report the end of a CDATA section.
void | LexicalHandler.comment(char[] ch, int start, int length) Report an XML comment anywhere in the document.
void | DeclHandler.elementDecl(String name, String model) Report an element type declaration.
void | DeclHandler.attributeDecl(String eName, String aName, String type, String valueDefault, String value) Report an attribute type declaration.
void | DeclHandler.internalEntityDecl(String name, String value) Report an internal entity declaration.
void | DeclHandler.externalEntityDecl(String name, String publicId, String systemId) Report a parsed external entity declaration.

Uses of SAXException in org.xml.sax.helpers

Methods in org.xml.sax.helpers that throw SAXException
void | XMLReaderAdapter.setLocale(Locale locale) Set the locale for error reporting.
void | XMLReaderAdapter.parse(String systemId) Parse the document.
void | XMLReaderAdapter.parse(InputSource input) Parse the document.
void | XMLReaderAdapter.startDocument() Start document event.
void | XMLReaderAdapter.endDocument() End document event.
void | XMLReaderAdapter.startElement(String uri, String localName, String qName, Attributes atts) Adapt a SAX2 start element event.
void | XMLReaderAdapter.endElement(String uri, String localName, String qName) Adapt a SAX2 end element event.
void | XMLReaderAdapter.characters(char[] ch, int start, int length) Adapt a SAX2 characters event.
void | XMLReaderAdapter.ignorableWhitespace(char[] ch, int start, int length) Adapt a SAX2 ignorable whitespace event.
void | XMLReaderAdapter.processingInstruction(String target, String data) Adapt a SAX2 processing instruction event.
void | XMLReaderAdapter.skippedEntity(String name) Adapt a SAX2 skipped entity event.
void | XMLFilterImpl.parse(InputSource input) Parse a document.
void | XMLFilterImpl.parse(String systemId) Parse a document.
InputSource | XMLFilterImpl.resolveEntity(String publicId, String systemId) Filter an external entity resolution.
void | XMLFilterImpl.notationDecl(String name, String publicId, String systemId) Filter a notation declaration event.
void | XMLFilterImpl.unparsedEntityDecl(String name, String publicId, String systemId, String notationName) Filter an unparsed entity declaration event.
void | XMLFilterImpl.startDocument() Filter a start document event.
void | XMLFilterImpl.endDocument() Filter an end document event.
void | XMLFilterImpl.startPrefixMapping(String prefix, String uri) Filter a start Namespace prefix mapping event.
void | XMLFilterImpl.endPrefixMapping(String prefix) Filter an end Namespace prefix mapping event.
void | XMLFilterImpl.startElement(String uri, String localName, String qName, Attributes atts) Filter a start element event.
void | XMLFilterImpl.endElement(String uri, String localName, String qName) Filter an end element event.
void | XMLFilterImpl.characters(char[] ch, int start, int length) Filter a character data event.
void | XMLFilterImpl.ignorableWhitespace(char[] ch, int start, int length) Filter an ignorable whitespace event.
void | XMLFilterImpl.processingInstruction(String target, String data) Filter a processing instruction event.
void | XMLFilterImpl.skippedEntity(String name) Filter a skipped entity event.
void | XMLFilterImpl.warning(SAXParseException e) Filter a warning event.
void | XMLFilterImpl.error(SAXParseException e) Filter an error event.
void | XMLFilterImpl.fatalError(SAXParseException e) Filter a fatal error event.
void | ParserAdapter.parse(String systemId) Parse an XML document.
void | ParserAdapter.parse(InputSource input) Parse an XML document.
void | ParserAdapter.startDocument() Adapt a SAX1 start document event.
void | ParserAdapter.endDocument() Adapt a SAX1 end document event.
void | ParserAdapter.startElement(String qName, AttributeList qAtts) Adapt a SAX1 startElement event.
void | ParserAdapter.endElement(String qName) Adapt a SAX1 end element event.
void | ParserAdapter.characters(char[] ch, int start, int length) Adapt a SAX1 characters event.
void | ParserAdapter.ignorableWhitespace(char[] ch, int start, int length) Adapt a SAX1 ignorable whitespace event.
void | ParserAdapter.processingInstruction(String target, String data) Adapt a SAX1 processing instruction event.
static XMLReader | XMLReaderFactory.createXMLReader() Attempt to create an XML reader from a system property.
static XMLReader | XMLReaderFactory.createXMLReader(String className) Attempt to create an XML reader from a class name.
InputSource | DefaultHandler.resolveEntity(String publicId, String systemId) Resolve an external entity.
void | DefaultHandler.notationDecl(String name, String publicId, String systemId) Receive notification of a notation declaration.
void | DefaultHandler.unparsedEntityDecl(String name, String publicId, String systemId, String notationName) Receive notification of an unparsed entity declaration.
void | DefaultHandler.startDocument() Receive notification of the beginning of the document.
void | DefaultHandler.endDocument() Receive notification of the end of the document.
void | DefaultHandler.startPrefixMapping(String prefix, String uri) Receive notification of the start of a Namespace mapping.
void | DefaultHandler.endPrefixMapping(String prefix) Receive notification of the end of a Namespace mapping.
void | DefaultHandler.startElement(String uri, String localName, String qName, Attributes attributes) Receive notification of the start of an element.
void | DefaultHandler.endElement(String uri, String localName, String qName) Receive notification of the end of an element.
void | DefaultHandler.characters(char[] ch, int start, int length) Receive notification of character data inside an element.
void | DefaultHandler.ignorableWhitespace(char[] ch, int start, int length) Receive notification of ignorable whitespace in element content.
void | DefaultHandler.processingInstruction(String target, String data) Receive notification of a processing instruction.
void | DefaultHandler.skippedEntity(String name) Receive notification of a skipped entity.
void | DefaultHandler.warning(SAXParseException e) Receive notification of a parser warning.
void | DefaultHandler.error(SAXParseException e) Receive notification of a recoverable parser error.
void | DefaultHandler.fatalError(SAXParseException e) Report a fatal XML parsing error.

Constructors in org.xml.sax.helpers that throw SAXException
XMLReaderAdapter()
Create a new adapter.
ParserAdapter()
Construct a new parser adapter.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.xml.sax.SAXNotRecognizedException (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.xml.sax.SAXNotRecognizedException

Packages that use SAXNotRecognizedException
javax.xml.parsers | Provides classes allowing the processing of XML documents.
org.xml.sax | Provides the classes and interfaces for the Simple API for XML (SAX) which is a component of the Java API for XML Processing.
org.xml.sax.helpers | Provides helper classes for the Simple API for XML (SAX) which is a component of the Java API for XML Processing.

Uses of SAXNotRecognizedException in javax.xml.parsers

Methods in javax.xml.parsers that throw SAXNotRecognizedException
abstract void | SAXParser.setProperty(String name, Object value) Sets the particular property in the underlying implementation of XMLReader.
abstract Object | SAXParser.getProperty(String name) Returns the particular property requested for in the underlying implementation of XMLReader.
abstract void | SAXParserFactory.setFeature(String name, boolean value) Sets the particular feature in the underlying implementation of org.xml.sax.XMLReader.
abstract boolean | SAXParserFactory.getFeature(String name) Returns the particular property requested for in the underlying implementation of org.xml.sax.XMLReader.

Uses of SAXNotRecognizedException in org.xml.sax

Methods in org.xml.sax that throw SAXNotRecognizedException
boolean | XMLReader.getFeature(String name) Look up the value of a feature.
void | XMLReader.setFeature(String name, boolean value) Set the state of a feature.
Object | XMLReader.getProperty(String name) Look up the value of a property.
void | XMLReader.setProperty(String name, Object value) Set the value of a property.

Uses of SAXNotRecognizedException in org.xml.sax.helpers

Methods in org.xml.sax.helpers that throw SAXNotRecognizedException
void | XMLFilterImpl.setFeature(String name, boolean state) Set the state of a feature.
boolean | XMLFilterImpl.getFeature(String name) Look up the state of a feature.
void | XMLFilterImpl.setProperty(String name, Object value) Set the value of a property.
Object | XMLFilterImpl.getProperty(String name) Look up the value of a property.
void | ParserAdapter.setFeature(String name, boolean state) Set a feature for the parser.
boolean | ParserAdapter.getFeature(String name) Check a parser feature.
void | ParserAdapter.setProperty(String name, Object value) Set a parser property.
Object | ParserAdapter.getProperty(String name) Get a parser property.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.xml.sax.SAXNotSupportedException (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.xml.sax.SAXNotSupportedException

Packages that use SAXNotSupportedException
javax.xml.parsers | Provides classes allowing the processing of XML documents.
org.xml.sax | Provides the classes and interfaces for the Simple API for XML (SAX) which is a component of the Java API for XML Processing.
org.xml.sax.helpers | Provides helper classes for the Simple API for XML (SAX) which is a component of the Java API for XML Processing.

Uses of SAXNotSupportedException in javax.xml.parsers

Methods in javax.xml.parsers that throw SAXNotSupportedException
abstract void | SAXParser.setProperty(String name, Object value) Sets the particular property in the underlying implementation of XMLReader.
abstract Object | SAXParser.getProperty(String name) Returns the particular property requested for in the underlying implementation of XMLReader.
abstract void | SAXParserFactory.setFeature(String name, boolean value) Sets the particular feature in the underlying implementation of org.xml.sax.XMLReader.
abstract boolean | SAXParserFactory.getFeature(String name) Returns the particular property requested for in the underlying implementation of org.xml.sax.XMLReader.

Uses of SAXNotSupportedException in org.xml.sax

Methods in org.xml.sax that throw SAXNotSupportedException
boolean | XMLReader.getFeature(String name) Look up the value of a feature.
void | XMLReader.setFeature(String name, boolean value) Set the state of a feature.
Object | XMLReader.getProperty(String name) Look up the value of a property.
void | XMLReader.setProperty(String name, Object value) Set the value of a property.

Uses of SAXNotSupportedException in org.xml.sax.helpers

Methods in org.xml.sax.helpers that throw SAXNotSupportedException
void | XMLFilterImpl.setFeature(String name, boolean state) Set the state of a feature.
boolean | XMLFilterImpl.getFeature(String name) Look up the state of a feature.
void | XMLFilterImpl.setProperty(String name, Object value) Set the value of a property.
Object | XMLFilterImpl.getProperty(String name) Look up the value of a property.
void | ParserAdapter.setFeature(String name, boolean state) Set a feature for the parser.
boolean | ParserAdapter.getFeature(String name) Check a parser feature.
void | ParserAdapter.setProperty(String name, Object value) Set a parser property.
Object | ParserAdapter.getProperty(String name) Get a parser property.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.xml.sax.SAXParseException (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.xml.sax.SAXParseException

Packages that use SAXParseException
org.xml.sax | Provides the classes and interfaces for the Simple API for XML (SAX) which is a component of the Java API for XML Processing.
org.xml.sax.helpers | Provides helper classes for the Simple API for XML (SAX) which is a component of the Java API for XML Processing.

Uses of SAXParseException in org.xml.sax

Methods in org.xml.sax with parameters of type SAXParseException
void | HandlerBase.warning(SAXParseException e) Deprecated. Receive notification of a parser warning.
void | HandlerBase.error(SAXParseException e) Deprecated. Receive notification of a recoverable parser error.
void | HandlerBase.fatalError(SAXParseException e) Deprecated. Report a fatal XML parsing error.
void | ErrorHandler.warning(SAXParseException exception) Receive notification of a warning.
void | ErrorHandler.error(SAXParseException exception) Receive notification of a recoverable error.
void | ErrorHandler.fatalError(SAXParseException exception) Receive notification of a non-recoverable error.

Uses of SAXParseException in org.xml.sax.helpers

Methods in org.xml.sax.helpers with parameters of type SAXParseException
void | XMLFilterImpl.warning(SAXParseException e) Filter a warning event.
void | XMLFilterImpl.error(SAXParseException e) Filter an error event.
void | XMLFilterImpl.fatalError(SAXParseException e) Filter a fatal error event.
void | DefaultHandler.warning(SAXParseException e) Receive notification of a parser warning.
void | DefaultHandler.error(SAXParseException e) Receive notification of a recoverable parser error.
void | DefaultHandler.fatalError(SAXParseException e) Report a fatal XML parsing error.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.xml.sax.XMLFilter (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.xml.sax.XMLFilter

Packages that use XMLFilter
javax.xml.transform.sax | This package implements SAX2-specific transformation APIs.
org.xml.sax.helpers | Provides helper classes for the Simple API for XML (SAX) which is a component of the Java API for XML Processing.

Uses of XMLFilter in javax.xml.transform.sax

Methods in javax.xml.transform.sax that return XMLFilter
abstract XMLFilter | SAXTransformerFactory.newXMLFilter(Source src) Create an XMLFilter that uses the given Source as the transformation instructions.
abstract XMLFilter | SAXTransformerFactory.newXMLFilter(Templates templates) Create an XMLFilter, based on the Templates argument..

Uses of XMLFilter in org.xml.sax.helpers

Classes in org.xml.sax.helpers that implement XMLFilter
 class XMLFilterImpl
Base class for deriving an XML filter.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.xml.sax.XMLReader (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.xml.sax.XMLReader

Packages that use XMLReader
javax.xml.parsers | Provides classes allowing the processing of XML documents.
javax.xml.transform.sax | This package implements SAX2-specific transformation APIs.
org.xml.sax | Provides the classes and interfaces for the Simple API for XML (SAX) which is a component of the Java API for XML Processing.
org.xml.sax.helpers | Provides helper classes for the Simple API for XML (SAX) which is a component of the Java API for XML Processing.

Uses of XMLReader in javax.xml.parsers

Methods in javax.xml.parsers that return XMLReader
abstract  XMLReader SAXParser.getXMLReader()
Returns the XMLReader that is encapsulated by the implementation of this class.

Uses of XMLReader in javax.xml.transform.sax

Methods in javax.xml.transform.sax that return XMLReader
 XMLReader SAXSource.getXMLReader()
Get the XMLReader to be used for the Source.

Methods in javax.xml.transform.sax with parameters of type XMLReader
 void SAXSource.setXMLReader(XMLReader reader)
Set the XMLReader to be used for the Source.

Constructors in javax.xml.transform.sax with parameters of type XMLReader
SAXSource(XMLReader reader, InputSource inputSource)
Create a SAXSource, using an XMLReader and a SAX InputSource.

Uses of XMLReader in org.xml.sax

Subinterfaces of XMLReader in org.xml.sax
 interface XMLFilter
Interface for an XML filter.

Methods in org.xml.sax that return XMLReader
 XMLReader XMLFilter.getParent()
Get the parent reader.

Methods in org.xml.sax with parameters of type XMLReader
 void XMLFilter.setParent(XMLReader parent)
Set the parent reader.

Uses of XMLReader in org.xml.sax.helpers

Classes in org.xml.sax.helpers that implement XMLReader
class | ParserAdapter Adapt a SAX1 Parser as a SAX2 XMLReader.
class | XMLFilterImpl Base class for deriving an XML filter.

Methods in org.xml.sax.helpers that return XMLReader
XMLReader | XMLFilterImpl.getParent() Get the parent reader.
static XMLReader | XMLReaderFactory.createXMLReader() Attempt to create an XML reader from a system property.
static XMLReader | XMLReaderFactory.createXMLReader(String className) Attempt to create an XML reader from a class name.

Methods in org.xml.sax.helpers with parameters of type XMLReader
 void XMLFilterImpl.setParent(XMLReader parent)
Set the parent reader.

Constructors in org.xml.sax.helpers with parameters of type XMLReader
XMLReaderAdapter(XMLReader xmlReader)
Create a new adapter.
XMLFilterImpl(XMLReader parent)
Construct an XML filter with the specified parent.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


DeclHandler (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.xml.sax.ext
Interface DeclHandler

public interface DeclHandler

SAX2 extension handler for DTD declaration events.

This module, both source code and documentation, is in the Public Domain, and comes with NO WARRANTY.

This is an optional extension handler for SAX2 to provide information about DTD declarations in an XML document. XML readers are not required to support this handler, and this handler is not included in the core SAX2 distribution.

Note that data-related DTD declarations (unparsed entities and notations) are already reported through the DTDHandler interface.

If you are using the declaration handler together with a lexical handler, all of the events will occur between the startDTD and the endDTD events.

To set the DeclHandler for an XML reader, use the setProperty method with the propertyId "http://xml.org/sax/properties/declaration-handler". If the reader does not support declaration events, it will throw a SAXNotRecognizedException or a SAXNotSupportedException when you attempt to register the handler.

Since:
1.0
See Also:
XMLReader

Method Summary
void | attributeDecl(String eName, String aName, String type, String valueDefault, String value) Report an attribute type declaration.
void | elementDecl(String name, String model) Report an element type declaration.
void | externalEntityDecl(String name, String publicId, String systemId) Report a parsed external entity declaration.
void | internalEntityDecl(String name, String value) Report an internal entity declaration.

Method Detail

elementDecl

public void elementDecl(String name,
                        String model)
                 throws SAXException
Report an element type declaration.

The content model will consist of the string "EMPTY", the string "ANY", or a parenthesised group, optionally followed by an occurrence indicator. The model will be normalized so that all parameter entities are fully resolved and all whitespace is removed,and will include the enclosing parentheses. Other normalization (such as removing redundant parentheses or simplifying occurrence indicators) is at the discretion of the parser.

Parameters:
name - The element type name.
model - The content model as a normalized string.
Throws:
SAXException - The application may raise an exception.

attributeDecl

public void attributeDecl(String eName,
                          String aName,
                          String type,
                          String valueDefault,
                          String value)
                   throws SAXException
Report an attribute type declaration.

Only the effective (first) declaration for an attribute will be reported. The type will be one of the strings "CDATA", "ID", "IDREF", "IDREFS", "NMTOKEN", "NMTOKENS", "ENTITY", "ENTITIES", a parenthesized token group with the separator "|" and all whitespace removed, or the word "NOTATION" followed by a space followed by a parenthesized token group with all whitespace removed.

Any parameter entities in the attribute value will be expanded, but general entities will not.

Parameters:
eName - The name of the associated element.
aName - The name of the attribute.
type - A string representing the attribute type.
valueDefault - A string representing the attribute default ("#IMPLIED", "#REQUIRED", or "#FIXED") or null if none of these applies.
value - A string representing the attribute's default value, or null if there is none.
Throws:
SAXException - The application may raise an exception.

internalEntityDecl

public void internalEntityDecl(String name,
                               String value)
                        throws SAXException
Report an internal entity declaration.

Only the effective (first) declaration for each entity will be reported. All parameter entities in the value will be expanded, but general entities will not.

Parameters:
name - The name of the entity. If it is a parameter entity, the name will begin with '%'.
value - The replacement text of the entity.
Throws:
SAXException - The application may raise an exception.
See Also:
externalEntityDecl(java.lang.String, java.lang.String, java.lang.String), DTDHandler.unparsedEntityDecl(java.lang.String, java.lang.String, java.lang.String, java.lang.String)

externalEntityDecl

public void externalEntityDecl(String name,
                               String publicId,
                               String systemId)
                        throws SAXException
Report a parsed external entity declaration.

Only the effective (first) declaration for each entity will be reported.

Parameters:
name - The name of the entity. If it is a parameter entity, the name will begin with '%'.
publicId - The declared public identifier of the entity, or null if none was declared.
systemId - The declared system identifier of the entity.
Throws:
SAXException - The application may raise an exception.
See Also:
internalEntityDecl(java.lang.String, java.lang.String), DTDHandler.unparsedEntityDecl(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


LexicalHandler (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.xml.sax.ext
Interface LexicalHandler

All Known Subinterfaces:
TransformerHandler
public interface LexicalHandler

SAX2 extension handler for lexical events.

This module, both source code and documentation, is in the Public Domain, and comes with NO WARRANTY.

This is an optional extension handler for SAX2 to provide lexical information about an XML document, such as comments and CDATA section boundaries; XML readers are not required to support this handler, and it is not part of the core SAX2 distribution.

The events in the lexical handler apply to the entire document, not just to the document element, and all lexical handler events must appear between the content handler's startDocument and endDocument events.

To set the LexicalHandler for an XML reader, use the setProperty method with the propertyId "http://xml.org/sax/properties/lexical-handler". If the reader does not support lexical events, it will throw a SAXNotRecognizedException or a SAXNotSupportedException when you attempt to register the handler.

Since:
1.0
See Also:
XMLReader.setProperty(java.lang.String, java.lang.Object), SAXNotRecognizedException, SAXNotSupportedException

Method Summary
void | comment(char[] ch, int start, int length) Report an XML comment anywhere in the document.
void | endCDATA() Report the end of a CDATA section.
void | endDTD() Report the end of DTD declarations.
void | endEntity(String name) Report the end of an entity.
void | startCDATA() Report the start of a CDATA section.
void | startDTD(String name, String publicId, String systemId) Report the start of DTD declarations, if any.
void | startEntity(String name) Report the beginning of some internal and external XML entities.

Method Detail

startDTD

public void startDTD(String name,
                     String publicId,
                     String systemId)
              throws SAXException
Report the start of DTD declarations, if any.

This method is intended to report the beginning of the DOCTYPE declaration; if the document has no DOCTYPE declaration, this method will not be invoked.

All declarations reported through DTDHandler or DeclHandler events must appear between the startDTD and endDTD events. Declarations are assumed to belong to the internal DTD subset unless they appear between startEntity and endEntity events. Comments and processing instructions from the DTD should also be reported between the startDTD and endDTD events, in their original order of (logical) occurrence; they are not required to appear in their correct locations relative to DTDHandler or DeclHandler events, however.

Note that the start/endDTD events will appear within the start/endDocument events from ContentHandler and before the first startElement event.

Parameters:
name - The document type name.
publicId - The declared public identifier for the external DTD subset, or null if none was declared.
systemId - The declared system identifier for the external DTD subset, or null if none was declared.
Throws:
SAXException - The application may raise an exception.
See Also:
endDTD(), startEntity(java.lang.String)

endDTD

public void endDTD()
            throws SAXException
Report the end of DTD declarations.

This method is intended to report the end of the DOCTYPE declaration; if the document has no DOCTYPE declaration, this method will not be invoked.

Throws:
SAXException - The application may raise an exception.
See Also:
startDTD(java.lang.String, java.lang.String, java.lang.String)

startEntity

public void startEntity(String name)
                 throws SAXException
Report the beginning of some internal and external XML entities.

The reporting of parameter entities (including the external DTD subset) is optional, and SAX2 drivers that support LexicalHandler may not support it; you can use the http://xml.org/sax/features/lexical-handler/parameter-entities feature to query or control the reporting of parameter entities.

General entities are reported with their regular names, parameter entities have '%' prepended to their names, and the external DTD subset has the pseudo-entity name "[dtd]".

When a SAX2 driver is providing these events, all other events must be properly nested within start/end entity events. There is no additional requirement that events from DeclHandler or DTDHandler be properly ordered.

Note that skipped entities will be reported through the skippedEntity event, which is part of the ContentHandler interface.

Because of the streaming event model that SAX uses, some entity boundaries cannot be reported under any circumstances:

  • general entities within attribute values
  • parameter entities within declarations

These will be silently expanded, with no indication of where the original entity boundaries were.

Note also that the boundaries of character references (which are not really entities anyway) are not reported.

All start/endEntity events must be properly nested.

Parameters:
name - The name of the entity. If it is a parameter entity, the name will begin with '%', and if it is the external DTD subset, it will be "[dtd]".
Throws:
SAXException - The application may raise an exception.
See Also:
endEntity(java.lang.String),
DeclHandler.internalEntityDecl(java.lang.String, java.lang.String),
DeclHandler.externalEntityDecl(java.lang.String, java.lang.String, java.lang.String)

endEntity

public void endEntity(String name)
               throws SAXException
Report the end of an entity.

Parameters:
name - The name of the entity that is ending.
Throws:
SAXException - The application may raise an exception.
See Also:
startEntity(java.lang.String)

startCDATA

public void startCDATA()
                throws SAXException
Report the start of a CDATA section.

The contents of the CDATA section will be reported through the regular characters event; this event is intended only to report the boundary.

Throws:
SAXException - The application may raise an exception.
See Also:
endCDATA()

endCDATA

public void endCDATA()
              throws SAXException
Report the end of a CDATA section.

Throws:
SAXException - The application may raise an exception.
See Also:
startCDATA()

comment

public void comment(char[] ch,
                    int start,
                    int length)
             throws SAXException
Report an XML comment anywhere in the document.

This callback will be used for comments inside or outside the document element, including comments in the external DTD subset (if read). Comments in the DTD must be properly nested inside start/endDTD and start/endEntity events (if used).

Parameters:
ch - An array holding the characters in the comment.
start - The starting position in the array.
length - The number of characters to use from the array.
Throws:
SAXException - The application may raise an exception.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


org.xml.sax.ext (Java 2 Platform SE v1.4.2)

 org.xml.sax.ext
Interfaces
DeclHandler
LexicalHandler


org.xml.sax.ext (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package org.xml.sax.ext

Provides extension classes and interfaces for the Simple API for XML (SAX) which is a component of the Java API for XML Processing.

See:
Description

Interface Summary
DeclHandler | SAX2 extension handler for DTD declaration events.
LexicalHandler | SAX2 extension handler for lexical events.

Package org.xml.sax.ext Description

Provides extension classes and interfaces for the Simple API for XML (SAX) which is a component of the Java API for XML Processing. SAX, the Simple API for XML, is a standard interface for event-based XML parsing, developed collaboratively by the members of the XML-DEV mailing list, currently hosted by OASIS. See the following link for more information on SAX.

Since:
JDK1.4
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


org.xml.sax.ext Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package org.xml.sax.ext

Package Hierarchies:
All Packages

Interface Hierarchy

  • interface org.xml.sax.ext.DeclHandler
  • interface org.xml.sax.ext.LexicalHandler
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package org.xml.sax.ext (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
org.xml.sax.ext

Packages that use org.xml.sax.ext
javax.xml.transform.sax This package implements SAX2-specific transformation APIs.

Classes in org.xml.sax.ext used by javax.xml.transform.sax
LexicalHandler
SAX2 extension handler for lexical events.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.xml.sax.ext.DeclHandler (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.xml.sax.ext.DeclHandler

No usage of org.xml.sax.ext.DeclHandler

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Interface org.xml.sax.ext.LexicalHandler (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.xml.sax.ext.LexicalHandler

Packages that use LexicalHandler
javax.xml.transform.sax This package implements SAX2-specific transformation APIs.

Uses of LexicalHandler in javax.xml.transform.sax

Subinterfaces of LexicalHandler in javax.xml.transform.sax
 interface TransformerHandler
A TransformerHandler listens for SAX ContentHandler parse events and transforms them to a Result.

Methods in javax.xml.transform.sax that return LexicalHandler
 LexicalHandler SAXResult.getLexicalHandler()
Get a SAX2 LexicalHandler for the output.

Methods in javax.xml.transform.sax with parameters of type LexicalHandler
 void SAXResult.setLexicalHandler(LexicalHandler handler)
Set the SAX2 LexicalHandler for the output.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


AttributeListImpl (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.xml.sax.helpers
Class AttributeListImpl

java.lang.Object
    extended by org.xml.sax.helpers.AttributeListImpl
All Implemented Interfaces:
AttributeList
Deprecated. This class implements a deprecated interface, AttributeList; that interface has been replaced by Attributes, which is implemented in the AttributesImpl helper class.

public class AttributeListImpl
extends Object
implements AttributeList

Default implementation for AttributeList.

This module, both source code and documentation, is in the Public Domain, and comes with NO WARRANTY.

AttributeList implements the deprecated SAX1 AttributeList interface, and has been replaced by the new SAX2 AttributesImpl interface.

This class provides a convenience implementation of the SAX AttributeList interface. This implementation is useful both for SAX parser writers, who can use it to provide attributes to the application, and for SAX application writers, who can use it to create a persistent copy of an element's attribute specifications:

 private AttributeList myatts;

 public void startElement (String name, AttributeList atts)
 {
              // create a persistent copy of the attribute list
              // for use outside this method
   myatts = new AttributeListImpl(atts);
   [...]
 }

Please note that SAX parsers are not required to use this class to provide an implementation of AttributeList; it is supplied only as an optional convenience. In particular, parser writers are encouraged to invent more efficient implementations.

Since:
SAX 1.0
See Also:
AttributeList, DocumentHandler.startElement(java.lang.String, org.xml.sax.AttributeList)

Constructor Summary
AttributeListImpl()
Deprecated. Create an empty attribute list.
AttributeListImpl(AttributeList atts)
Deprecated. Construct a persistent copy of an existing attribute list.
Method Summary
void | addAttribute(String name, String type, String value) Deprecated. Add an attribute to an attribute list.
void | clear() Deprecated. Clear the attribute list.
int | getLength() Deprecated. Return the number of attributes in the list.
String | getName(int i) Deprecated. Get the name of an attribute (by position).
String | getType(int i) Deprecated. Get the type of an attribute (by position).
String | getType(String name) Deprecated. Get the type of an attribute (by name).
String | getValue(int i) Deprecated. Get the value of an attribute (by position).
String | getValue(String name) Deprecated. Get the value of an attribute (by name).
void | removeAttribute(String name) Deprecated. Remove an attribute from the list.
void | setAttributeList(AttributeList atts) Deprecated. Set the attribute list, discarding previous contents.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

AttributeListImpl

public AttributeListImpl()
Deprecated.
Create an empty attribute list.

This constructor is most useful for parser writers, who will use it to create a single, reusable attribute list that can be reset with the clear method between elements.

See Also:
addAttribute(java.lang.String, java.lang.String, java.lang.String), clear()

AttributeListImpl

public AttributeListImpl(AttributeList atts)
Deprecated.
Construct a persistent copy of an existing attribute list.

This constructor is most useful for application writers, who will use it to create a persistent copy of an existing attribute list.

Parameters:
atts - The attribute list to copy
See Also:
DocumentHandler.startElement(java.lang.String, org.xml.sax.AttributeList)
Method Detail

setAttributeList

public void setAttributeList(AttributeList atts)
Deprecated.
Set the attribute list, discarding previous contents.

This method allows an application writer to reuse an attribute list easily.

Parameters:
atts - The attribute list to copy.

addAttribute

public void addAttribute(String name,
                         String type,
                         String value)
Deprecated.
Add an attribute to an attribute list.

This method is provided for SAX parser writers, to allow them to build up an attribute list incrementally before delivering it to the application.

Parameters:
name - The attribute name.
type - The attribute type ("NMTOKEN" for an enumeration).
value - The attribute value (must not be null).
See Also:
removeAttribute(java.lang.String), DocumentHandler.startElement(java.lang.String, org.xml.sax.AttributeList)

removeAttribute

public void removeAttribute(String name)
Deprecated.
Remove an attribute from the list.

SAX application writers can use this method to filter an attribute out of an AttributeList. Note that invoking this method will change the length of the attribute list and some of the attribute's indices.

If the requested attribute is not in the list, this is a no-op.

Parameters:
name - The attribute name.
See Also:
addAttribute(java.lang.String, java.lang.String, java.lang.String)

clear

public void clear()
Deprecated.
Clear the attribute list.

SAX parser writers can use this method to reset the attribute list between DocumentHandler.startElement events. Normally, it will make sense to reuse the same AttributeListImpl object rather than allocating a new one each time.

See Also:
DocumentHandler.startElement(java.lang.String, org.xml.sax.AttributeList)

getLength

public int getLength()
Deprecated.
Return the number of attributes in the list.

Specified by:
getLength in interface AttributeList
Returns:
The number of attributes in the list.
See Also:
AttributeList.getLength()

getName

public String getName(int i)
Deprecated.
Get the name of an attribute (by position).

Specified by:
getName in interface AttributeList
Parameters:
i - The position of the attribute in the list.
Returns:
The attribute name as a string, or null if there is no attribute at that position.
See Also:
AttributeList.getName(int)

getType

public String getType(int i)
Deprecated.
Get the type of an attribute (by position).

Specified by:
getType in interface AttributeList
Parameters:
i - The position of the attribute in the list.
Returns:
The attribute type as a string ("NMTOKEN" for an enumeration, and "CDATA" if no declaration was read), or null if there is no attribute at that position.
See Also:
AttributeList.getType(int)

getValue

public String getValue(int i)
Deprecated.
Get the value of an attribute (by position).

Specified by:
getValue in interface AttributeList
Parameters:
i - The position of the attribute in the list.
Returns:
The attribute value as a string, or null if there is no attribute at that position.
See Also:
AttributeList.getValue(int)

getType

public String getType(String name)
Deprecated.
Get the type of an attribute (by name).

Specified by:
getType in interface AttributeList
Parameters:
name - The attribute name.
Returns:
The attribute type as a string ("NMTOKEN" for an enumeration, and "CDATA" if no declaration was read).
See Also:
AttributeList.getType(java.lang.String)

getValue

public String getValue(String name)
Deprecated.
Get the value of an attribute (by name).

Specified by:
getValue in interface AttributeList
Parameters:
name - The attribute name.
Returns:
The attribute value as a string, or null if no such attribute exists.
See Also:
AttributeList.getValue(java.lang.String)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


AttributesImpl (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.xml.sax.helpers
Class AttributesImpl

java.lang.Object
    extended by org.xml.sax.helpers.AttributesImpl
All Implemented Interfaces:
Attributes
public class AttributesImpl
extends Object
implements Attributes

Default implementation of the Attributes interface.

This module, both source code and documentation, is in the Public Domain, and comes with NO WARRANTY.

This class provides a default implementation of the SAX2 Attributes interface, with the addition of manipulators so that the list can be modified or reused.

There are two typical uses of this class:

  1. to take a persistent snapshot of an Attributes object in a startElement event; or
  2. to construct or modify an Attributes object in a SAX2 driver or filter.

This class replaces the now-deprecated SAX1 AttributeListImpl class; in addition to supporting the updated Attributes interface rather than the deprecated AttributeList interface, it also includes a much more efficient implementation using a single array rather than a set of Vectors.

Since:
SAX 2.0

Constructor Summary
AttributesImpl()
Construct a new, empty AttributesImpl object.
AttributesImpl(Attributes atts)
Copy an existing Attributes object.
Method Summary
void | addAttribute(String uri, String localName, String qName, String type, String value) Add an attribute to the end of the list.
void | clear() Clear the attribute list for reuse.
int | getIndex(String qName) Look up an attribute's index by qualified (prefixed) name.
int | getIndex(String uri, String localName) Look up an attribute's index by Namespace name.
int | getLength() Return the number of attributes in the list.
String | getLocalName(int index) Return an attribute's local name.
String | getQName(int index) Return an attribute's qualified (prefixed) name.
String | getType(int index) Return an attribute's type by index.
String | getType(String qName) Look up an attribute's type by qualified (prefixed) name.
String | getType(String uri, String localName) Look up an attribute's type by Namespace-qualified name.
String | getURI(int index) Return an attribute's Namespace URI.
String | getValue(int index) Return an attribute's value by index.
String | getValue(String qName) Look up an attribute's value by qualified (prefixed) name.
String | getValue(String uri, String localName) Look up an attribute's value by Namespace-qualified name.
void | removeAttribute(int index) Remove an attribute from the list.
void | setAttribute(int index, String uri, String localName, String qName, String type, String value) Set an attribute in the list.
void | setAttributes(Attributes atts) Copy an entire Attributes object.
void | setLocalName(int index, String localName) Set the local name of a specific attribute.
void | setQName(int index, String qName) Set the qualified name of a specific attribute.
void | setType(int index, String type) Set the type of a specific attribute.
void | setURI(int index, String uri) Set the Namespace URI of a specific attribute.
void | setValue(int index, String value) Set the value of a specific attribute.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

AttributesImpl

public AttributesImpl()
Construct a new, empty AttributesImpl object.

AttributesImpl

public AttributesImpl(Attributes atts)
Copy an existing Attributes object.

This constructor is especially useful inside a startElement event.

Parameters:
atts - The existing Attributes object.
Method Detail

getLength

public int getLength()
Return the number of attributes in the list.

Specified by:
getLength in interface Attributes
Returns:
The number of attributes in the list.
See Also:
Attributes.getLength()

getURI

public String getURI(int index)
Return an attribute's Namespace URI.

Specified by:
getURI in interface Attributes
Parameters:
index - The attribute's index (zero-based).
Returns:
The Namespace URI, the empty string if none is available, or null if the index is out of range.
See Also:
Attributes.getURI(int)

getLocalName

public String getLocalName(int index)
Return an attribute's local name.

Specified by:
getLocalName in interface Attributes
Parameters:
index - The attribute's index (zero-based).
Returns:
The attribute's local name, the empty string if none is available, or null if the index if out of range.
See Also:
Attributes.getLocalName(int)

getQName

public String getQName(int index)
Return an attribute's qualified (prefixed) name.

Specified by:
getQName in interface Attributes
Parameters:
index - The attribute's index (zero-based).
Returns:
The attribute's qualified name, the empty string if none is available, or null if the index is out of bounds.
See Also:
Attributes.getQName(int)

getType

public String getType(int index)
Return an attribute's type by index.

Specified by:
getType in interface Attributes
Parameters:
index - The attribute's index (zero-based).
Returns:
The attribute's type, "CDATA" if the type is unknown, or null if the index is out of bounds.
See Also:
Attributes.getType(int)

getValue

public String getValue(int index)
Return an attribute's value by index.

Specified by:
getValue in interface Attributes
Parameters:
index - The attribute's index (zero-based).
Returns:
The attribute's value or null if the index is out of bounds.
See Also:
Attributes.getValue(int)

getIndex

public int getIndex(String uri,
                    String localName)
Look up an attribute's index by Namespace name.

In many cases, it will be more efficient to look up the name once and use the index query methods rather than using the name query methods repeatedly.

Specified by:
getIndex in interface Attributes
Parameters:
uri - The attribute's Namespace URI, or the empty string if none is available.
localName - The attribute's local name.
Returns:
The attribute's index, or -1 if none matches.
See Also:
Attributes.getIndex(java.lang.String,java.lang.String)

getIndex

public int getIndex(String qName)
Look up an attribute's index by qualified (prefixed) name.

Specified by:
getIndex in interface Attributes
Parameters:
qName - The qualified name.
Returns:
The attribute's index, or -1 if none matches.
See Also:
Attributes.getIndex(java.lang.String)

getType

public String getType(String uri,
                      String localName)
Look up an attribute's type by Namespace-qualified name.

Specified by:
getType in interface Attributes
Parameters:
uri - The Namespace URI, or the empty string for a name with no explicit Namespace URI.
localName - The local name.
Returns:
The attribute's type, or null if there is no matching attribute.
See Also:
Attributes.getType(java.lang.String,java.lang.String)

getType

public String getType(String qName)
Look up an attribute's type by qualified (prefixed) name.

Specified by:
getType in interface Attributes
Parameters:
qName - The qualified name.
Returns:
The attribute's type, or null if there is no matching attribute.
See Also:
Attributes.getType(java.lang.String)

getValue

public String getValue(String uri,
                       String localName)
Look up an attribute's value by Namespace-qualified name.

Specified by:
getValue in interface Attributes
Parameters:
uri - The Namespace URI, or the empty string for a name with no explicit Namespace URI.
localName - The local name.
Returns:
The attribute's value, or null if there is no matching attribute.
See Also:
Attributes.getValue(java.lang.String,java.lang.String)

getValue

public String getValue(String qName)
Look up an attribute's value by qualified (prefixed) name.

Specified by:
getValue in interface Attributes
Parameters:
qName - The qualified name.
Returns:
The attribute's value, or null if there is no matching attribute.
See Also:
Attributes.getValue(java.lang.String)

clear

public void clear()
Clear the attribute list for reuse.

Note that no memory is actually freed by this call: the current arrays are kept so that they can be reused.

setAttributes

public void setAttributes(Attributes atts)
Copy an entire Attributes object.

It may be more efficient to reuse an existing object rather than constantly allocating new ones.

Parameters:
atts - The attributes to copy.

addAttribute

public void addAttribute(String uri,
                         String localName,
                         String qName,
                         String type,
                         String value)
Add an attribute to the end of the list.

For the sake of speed, this method does no checking to see if the attribute is already in the list: that is the responsibility of the application.

Parameters:
uri - The Namespace URI, or the empty string if none is available or Namespace processing is not being performed.
localName - The local name, or the empty string if Namespace processing is not being performed.
qName - The qualified (prefixed) name, or the empty string if qualified names are not available.
type - The attribute type as a string.
value - The attribute value.

setAttribute

public void setAttribute(int index,
                         String uri,
                         String localName,
                         String qName,
                         String type,
                         String value)
Set an attribute in the list.

For the sake of speed, this method does no checking for name conflicts or well-formedness: such checks are the responsibility of the application.

Parameters:
index - The index of the attribute (zero-based).
uri - The Namespace URI, or the empty string if none is available or Namespace processing is not being performed.
localName - The local name, or the empty string if Namespace processing is not being performed.
qName - The qualified name, or the empty string if qualified names are not available.
type - The attribute type as a string.
value - The attribute value.
Throws:
ArrayIndexOutOfBoundsException - When the supplied index does not point to an attribute in the list.

removeAttribute

public void removeAttribute(int index)
Remove an attribute from the list.

Parameters:
index - The index of the attribute (zero-based).
Throws:
ArrayIndexOutOfBoundsException - When the supplied index does not point to an attribute in the list.

setURI

public void setURI(int index,
                   String uri)
Set the Namespace URI of a specific attribute.

Parameters:
index - The index of the attribute (zero-based).
uri - The attribute's Namespace URI, or the empty string for none.
Throws:
ArrayIndexOutOfBoundsException - When the supplied index does not point to an attribute in the list.

setLocalName

public void setLocalName(int index,
                         String localName)
Set the local name of a specific attribute.

Parameters:
index - The index of the attribute (zero-based).
localName - The attribute's local name, or the empty string for none.
Throws:
ArrayIndexOutOfBoundsException - When the supplied index does not point to an attribute in the list.

setQName

public void setQName(int index,
                     String qName)
Set the qualified name of a specific attribute.

Parameters:
index - The index of the attribute (zero-based).
qName - The attribute's qualified name, or the empty string for none.
Throws:
ArrayIndexOutOfBoundsException - When the supplied index does not point to an attribute in the list.

setType

public void setType(int index,
                    String type)
Set the type of a specific attribute.

Parameters:
index - The index of the attribute (zero-based).
type - The attribute's type.
Throws:
ArrayIndexOutOfBoundsException - When the supplied index does not point to an attribute in the list.

setValue

public void setValue(int index,
                     String value)
Set the value of a specific attribute.

Parameters:
index - The index of the attribute (zero-based).
value - The attribute's value.
Throws:
ArrayIndexOutOfBoundsException - When the supplied index does not point to an attribute in the list.
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DefaultHandler (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.xml.sax.helpers
Class DefaultHandler

java.lang.Object
    extended by org.xml.sax.helpers.DefaultHandler
All Implemented Interfaces:
ContentHandler, DTDHandler, EntityResolver, ErrorHandler
public class DefaultHandler
extends Object
implements EntityResolver, DTDHandler, ContentHandler, ErrorHandler

Default base class for SAX2 event handlers.

This module, both source code and documentation, is in the Public Domain, and comes with NO WARRANTY.

This class is available as a convenience base class for SAX2 applications: it provides default implementations for all of the callbacks in the four core SAX2 handler classes:

  • EntityResolver
  • DTDHandler
  • ContentHandler
  • ErrorHandler

Application writers can extend this class when they need to implement only part of an interface; parser writers can instantiate this class to provide default handlers when the application has not supplied its own.

This class replaces the deprecated SAX1 HandlerBase class.

Since:
SAX 2.0
See Also:
EntityResolver, DTDHandler, ContentHandler, ErrorHandler

Constructor Summary
DefaultHandler()
Method Summary
void | characters(char[] ch, int start, int length) Receive notification of character data inside an element.
void | endDocument() Receive notification of the end of the document.
void | endElement(String uri, String localName, String qName) Receive notification of the end of an element.
void | endPrefixMapping(String prefix) Receive notification of the end of a Namespace mapping.
void | error(SAXParseException e) Receive notification of a recoverable parser error.
void | fatalError(SAXParseException e) Report a fatal XML parsing error.
void | ignorableWhitespace(char[] ch, int start, int length) Receive notification of ignorable whitespace in element content.
void | notationDecl(String name, String publicId, String systemId) Receive notification of a notation declaration.
void | processingInstruction(String target, String data) Receive notification of a processing instruction.
InputSource | resolveEntity(String publicId, String systemId) Resolve an external entity.
void | setDocumentLocator(Locator locator) Receive a Locator object for document events.
void | skippedEntity(String name) Receive notification of a skipped entity.
void | startDocument() Receive notification of the beginning of the document.
void | startElement(String uri, String localName, String qName, Attributes attributes) Receive notification of the start of an element.
void | startPrefixMapping(String prefix, String uri) Receive notification of the start of a Namespace mapping.
void | unparsedEntityDecl(String name, String publicId, String systemId, String notationName) Receive notification of an unparsed entity declaration.
void | warning(SAXParseException e) Receive notification of a parser warning.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DefaultHandler

public DefaultHandler()
Method Detail

resolveEntity

public InputSource resolveEntity(String publicId,
                                 String systemId)
                          throws SAXException
Resolve an external entity.

Always return null, so that the parser will use the system identifier provided in the XML document. This method implements the SAX default behaviour: application writers can override it in a subclass to do special translations such as catalog lookups or URI redirection.

Specified by:
resolveEntity in interface EntityResolver
Parameters:
publicId - The public identifer, or null if none is available.
systemId - The system identifier provided in the XML document.
Returns:
The new input source, or null to require the default behaviour.
Throws:
IOException - If there is an error setting up the new input source.
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
EntityResolver.resolveEntity(java.lang.String, java.lang.String)

notationDecl

public void notationDecl(String name,
                         String publicId,
                         String systemId)
                  throws SAXException
Receive notification of a notation declaration.

By default, do nothing. Application writers may override this method in a subclass if they wish to keep track of the notations declared in a document.

Specified by:
notationDecl in interface DTDHandler
Parameters:
name - The notation name.
publicId - The notation public identifier, or null if not available.
systemId - The notation system identifier.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
DTDHandler.notationDecl(java.lang.String, java.lang.String, java.lang.String)

unparsedEntityDecl

public void unparsedEntityDecl(String name,
                               String publicId,
                               String systemId,
                               String notationName)
                        throws SAXException
Receive notification of an unparsed entity declaration.

By default, do nothing. Application writers may override this method in a subclass to keep track of the unparsed entities declared in a document.

Specified by:
unparsedEntityDecl in interface DTDHandler
Parameters:
name - The entity name.
publicId - The entity public identifier, or null if not available.
systemId - The entity system identifier.
notationName - The name of the associated notation.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
DTDHandler.unparsedEntityDecl(java.lang.String, java.lang.String, java.lang.String, java.lang.String)

setDocumentLocator

public void setDocumentLocator(Locator locator)
Receive a Locator object for document events.

By default, do nothing. Application writers may override this method in a subclass if they wish to store the locator for use with other document events.

Specified by:
setDocumentLocator in interface ContentHandler
Parameters:
locator - A locator for all SAX document events.
See Also:
ContentHandler.setDocumentLocator(org.xml.sax.Locator), Locator

startDocument

public void startDocument()
                   throws SAXException
Receive notification of the beginning of the document.

By default, do nothing. Application writers may override this method in a subclass to take specific actions at the beginning of a document (such as allocating the root node of a tree or creating an output file).

Specified by:
startDocument in interface ContentHandler
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
ContentHandler.startDocument()

endDocument

public void endDocument()
                 throws SAXException
Receive notification of the end of the document.

By default, do nothing. Application writers may override this method in a subclass to take specific actions at the end of a document (such as finalising a tree or closing an output file).

Specified by:
endDocument in interface ContentHandler
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
ContentHandler.endDocument()

startPrefixMapping

public void startPrefixMapping(String prefix,
                               String uri)
                        throws SAXException
Receive notification of the start of a Namespace mapping.

By default, do nothing. Application writers may override this method in a subclass to take specific actions at the start of each Namespace prefix scope (such as storing the prefix mapping).

Specified by:
startPrefixMapping in interface ContentHandler
Parameters:
prefix - The Namespace prefix being declared.
uri - The Namespace URI mapped to the prefix.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
ContentHandler.startPrefixMapping(java.lang.String, java.lang.String)

endPrefixMapping

public void endPrefixMapping(String prefix)
                      throws SAXException
Receive notification of the end of a Namespace mapping.

By default, do nothing. Application writers may override this method in a subclass to take specific actions at the end of each prefix mapping.

Specified by:
endPrefixMapping in interface ContentHandler
Parameters:
prefix - The Namespace prefix being declared.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
ContentHandler.endPrefixMapping(java.lang.String)

startElement

public void startElement(String uri,
                         String localName,
                         String qName,
                         Attributes attributes)
                  throws SAXException
Receive notification of the start of an element.

By default, do nothing. Application writers may override this method in a subclass to take specific actions at the start of each element (such as allocating a new tree node or writing output to a file).

Specified by:
startElement in interface ContentHandler
Parameters:
attributes - The specified or defaulted attributes.
localName - The local name (without prefix), or the empty string if Namespace processing is not being performed.
qName - The qualified name (with prefix), or the empty string if qualified names are not available.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
ContentHandler.startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)

endElement

public void endElement(String uri,
                       String localName,
                       String qName)
                throws SAXException
Receive notification of the end of an element.

By default, do nothing. Application writers may override this method in a subclass to take specific actions at the end of each element (such as finalising a tree node or writing output to a file).

Specified by:
endElement in interface ContentHandler
Parameters:
localName - The local name (without prefix), or the empty string if Namespace processing is not being performed.
qName - The qualified XML 1.0 name (with prefix), or the empty string if qualified names are not available.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
ContentHandler.endElement(java.lang.String, java.lang.String, java.lang.String)

characters

public void characters(char[] ch,
                       int start,
                       int length)
                throws SAXException
Receive notification of character data inside an element.

By default, do nothing. Application writers may override this method to take specific actions for each chunk of character data (such as adding the data to a node or buffer, or printing it to a file).

Specified by:
characters in interface ContentHandler
Parameters:
ch - The characters.
start - The start position in the character array.
length - The number of characters to use from the character array.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
ContentHandler.characters(char[], int, int)

ignorableWhitespace

public void ignorableWhitespace(char[] ch,
                                int start,
                                int length)
                         throws SAXException
Receive notification of ignorable whitespace in element content.

By default, do nothing. Application writers may override this method to take specific actions for each chunk of ignorable whitespace (such as adding data to a node or buffer, or printing it to a file).

Specified by:
ignorableWhitespace in interface ContentHandler
Parameters:
ch - The whitespace characters.
start - The start position in the character array.
length - The number of characters to use from the character array.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
ContentHandler.ignorableWhitespace(char[], int, int)

processingInstruction

public void processingInstruction(String target,
                                  String data)
                           throws SAXException
Receive notification of a processing instruction.

By default, do nothing. Application writers may override this method in a subclass to take specific actions for each processing instruction, such as setting status variables or invoking other methods.

Specified by:
processingInstruction in interface ContentHandler
Parameters:
target - The processing instruction target.
data - The processing instruction data, or null if none is supplied.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
ContentHandler.processingInstruction(java.lang.String, java.lang.String)

skippedEntity

public void skippedEntity(String name)
                   throws SAXException
Receive notification of a skipped entity.

By default, do nothing. Application writers may override this method in a subclass to take specific actions for each processing instruction, such as setting status variables or invoking other methods.

Specified by:
skippedEntity in interface ContentHandler
Parameters:
name - The name of the skipped entity.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
ContentHandler.processingInstruction(java.lang.String, java.lang.String)

warning

public void warning(SAXParseException e)
             throws SAXException
Receive notification of a parser warning.

The default implementation does nothing. Application writers may override this method in a subclass to take specific actions for each warning, such as inserting the message in a log file or printing it to the console.

Specified by:
warning in interface ErrorHandler
Parameters:
e - The warning information encoded as an exception.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
ErrorHandler.warning(org.xml.sax.SAXParseException), SAXParseException

error

public void error(SAXParseException e)
           throws SAXException
Receive notification of a recoverable parser error.

The default implementation does nothing. Application writers may override this method in a subclass to take specific actions for each error, such as inserting the message in a log file or printing it to the console.

Specified by:
error in interface ErrorHandler
Parameters:
e - The warning information encoded as an exception.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
ErrorHandler.warning(org.xml.sax.SAXParseException), SAXParseException

fatalError

public void fatalError(SAXParseException e)
                throws SAXException
Report a fatal XML parsing error.

The default implementation throws a SAXParseException. Application writers may override this method in a subclass if they need to take specific actions for each fatal error (such as collecting all of the errors into a single report): in any case, the application must stop all regular processing when this method is invoked, since the document is no longer reliable, and the parser may no longer report parsing events.

Specified by:
fatalError in interface ErrorHandler
Parameters:
e - The error information encoded as an exception.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
ErrorHandler.fatalError(org.xml.sax.SAXParseException), SAXParseException
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


LocatorImpl (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.xml.sax.helpers
Class LocatorImpl

java.lang.Object
    extended by org.xml.sax.helpers.LocatorImpl
All Implemented Interfaces:
Locator
public class LocatorImpl
extends Object
implements Locator

Provide an optional convenience implementation of Locator.

This module, both source code and documentation, is in the Public Domain, and comes with NO WARRANTY.

This class is available mainly for application writers, who can use it to make a persistent snapshot of a locator at any point during a document parse:

 Locator locator;
 Locator startloc;

 public void setLocator (Locator locator)
 {
         // note the locator
   this.locator = locator;
 }

 public void startDocument ()
 {
         // save the location of the start of the document
         // for future use.
   Locator startloc = new LocatorImpl(locator);
 }

Normally, parser writers will not use this class, since it is more efficient to provide location information only when requested, rather than constantly updating a Locator object.

Since:
SAX 1.0
See Also:
Locator

Constructor Summary
LocatorImpl()
Zero-argument constructor.
LocatorImpl(Locator locator)
Copy constructor.
Method Summary
int | getColumnNumber() Return the saved column number (1-based).
int | getLineNumber() Return the saved line number (1-based).
String | getPublicId() Return the saved public identifier.
String | getSystemId() Return the saved system identifier.
void | setColumnNumber(int columnNumber) Set the column number for this locator (1-based).
void | setLineNumber(int lineNumber) Set the line number for this locator (1-based).
void | setPublicId(String publicId) Set the public identifier for this locator.
void | setSystemId(String systemId) Set the system identifier for this locator.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

LocatorImpl

public LocatorImpl()
Zero-argument constructor.

This will not normally be useful, since the main purpose of this class is to make a snapshot of an existing Locator.

LocatorImpl

public LocatorImpl(Locator locator)
Copy constructor.

Create a persistent copy of the current state of a locator. When the original locator changes, this copy will still keep the original values (and it can be used outside the scope of DocumentHandler methods).

Parameters:
locator - The locator to copy.
Method Detail

getPublicId

public String getPublicId()
Return the saved public identifier.

Specified by:
getPublicId in interface Locator
Returns:
The public identifier as a string, or null if none is available.
See Also:
Locator.getPublicId(), setPublicId(java.lang.String)

getSystemId

public String getSystemId()
Return the saved system identifier.

Specified by:
getSystemId in interface Locator
Returns:
The system identifier as a string, or null if none is available.
See Also:
Locator.getSystemId(), setSystemId(java.lang.String)

getLineNumber

public int getLineNumber()
Return the saved line number (1-based).

Specified by:
getLineNumber in interface Locator
Returns:
The line number as an integer, or -1 if none is available.
See Also:
Locator.getLineNumber(), setLineNumber(int)

getColumnNumber

public int getColumnNumber()
Return the saved column number (1-based).

Specified by:
getColumnNumber in interface Locator
Returns:
The column number as an integer, or -1 if none is available.
See Also:
Locator.getColumnNumber(), setColumnNumber(int)

setPublicId

public void setPublicId(String publicId)
Set the public identifier for this locator.

Parameters:
publicId - The new public identifier, or null if none is available.
See Also:
getPublicId()

setSystemId

public void setSystemId(String systemId)
Set the system identifier for this locator.

Parameters:
systemId - The new system identifier, or null if none is available.
See Also:
getSystemId()

setLineNumber

public void setLineNumber(int lineNumber)
Set the line number for this locator (1-based).

Parameters:
lineNumber - The line number, or -1 if none is available.
See Also:
getLineNumber()

setColumnNumber

public void setColumnNumber(int columnNumber)
Set the column number for this locator (1-based).

Parameters:
columnNumber - The column number, or -1 if none is available.
See Also:
getColumnNumber()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NamespaceSupport (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.xml.sax.helpers
Class NamespaceSupport

java.lang.Object
    extended by org.xml.sax.helpers.NamespaceSupport
public class NamespaceSupport
extends Object

Encapsulate Namespace logic for use by SAX drivers.

This module, both source code and documentation, is in the Public Domain, and comes with NO WARRANTY.

This class encapsulates the logic of Namespace processing: it tracks the declarations currently in force for each context and automatically processes qualified XML 1.0 names into their Namespace parts; it can also be used in reverse for generating XML 1.0 from Namespaces.

Namespace support objects are reusable, but the reset method must be invoked between each session.

Here is a simple session:

 String parts[] = new String[3];
 NamespaceSupport support = new NamespaceSupport();

 support.pushContext();
 support.declarePrefix("", "http://www.w3.org/1999/xhtml");
 support.declarePrefix("dc", "http://www.purl.org/dc#");

 String parts[] = support.processName("p", parts, false);
 System.out.println("Namespace URI: " + parts[0]);
 System.out.println("Local name: " + parts[1]);
 System.out.println("Raw name: " + parts[2]);

 String parts[] = support.processName("dc:title", parts, false);
 System.out.println("Namespace URI: " + parts[0]);
 System.out.println("Local name: " + parts[1]);
 System.out.println("Raw name: " + parts[2]);

 support.popContext();

Note that this class is optimized for the use case where most elements do not contain Namespace declarations: if the same prefix/URI mapping is repeated for each context (for example), this class will be somewhat less efficient.

Since:
SAX 2.0

Field Summary
static String XMLNS
The XML Namespace as a constant.
Constructor Summary
NamespaceSupport()
Create a new Namespace support object.
Method Summary
boolean | declarePrefix(String prefix, String uri) Declare a Namespace prefix.
Enumeration | getDeclaredPrefixes() Return an enumeration of all prefixes declared in this context.
String | getPrefix(String uri) Return one of the prefixes mapped to a Namespace URI.
Enumeration | getPrefixes() Return an enumeration of all prefixes currently declared.
Enumeration | getPrefixes(String uri) Return an enumeration of all prefixes currently declared for a URI.
String | getURI(String prefix) Look up a prefix and get the currently-mapped Namespace URI.
void | popContext() Revert to the previous Namespace context.
String[] | processName(String qName, String[] parts, boolean isAttribute) Process a raw XML 1.0 name.
void | pushContext() Start a new Namespace context.
void | reset() Reset this Namespace support object for reuse.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

XMLNS

public static final String XMLNS
The XML Namespace as a constant.

This is the Namespace URI that is automatically mapped to the "xml" prefix.

See Also:
Constant Field Values
Constructor Detail

NamespaceSupport

public NamespaceSupport()
Create a new Namespace support object.

Method Detail

reset

public void reset()
Reset this Namespace support object for reuse.

It is necessary to invoke this method before reusing the Namespace support object for a new session.

pushContext

public void pushContext()
Start a new Namespace context.

Normally, you should push a new context at the beginning of each XML element: the new context will automatically inherit the declarations of its parent context, but it will also keep track of which declarations were made within this context.

The Namespace support object always starts with a base context already in force: in this context, only the "xml" prefix is declared.

See Also:
popContext()

popContext

public void popContext()
Revert to the previous Namespace context.

Normally, you should pop the context at the end of each XML element. After popping the context, all Namespace prefix mappings that were previously in force are restored.

You must not attempt to declare additional Namespace prefixes after popping a context, unless you push another context first.

See Also:
pushContext()

declarePrefix

public boolean declarePrefix(String prefix,
                             String uri)
Declare a Namespace prefix.

This method declares a prefix in the current Namespace context; the prefix will remain in force until this context is popped, unless it is shadowed in a descendant context.

To declare a default Namespace, use the empty string. The prefix must not be "xml" or "xmlns".

Note that you must not declare a prefix after you've pushed and popped another Namespace.

Note that there is an asymmetry in this library: while getPrefix will not return the default "" prefix, even if you have declared one; to check for a default prefix, you have to look it up explicitly using getURI. This asymmetry exists to make it easier to look up prefixes for attribute names, where the default prefix is not allowed.

Parameters:
prefix - The prefix to declare, or null for the empty string.
uri - The Namespace URI to associate with the prefix.
Returns:
true if the prefix was legal, false otherwise
See Also:
processName(java.lang.String, java.lang.String[], boolean),
getURI(java.lang.String),
getPrefix(java.lang.String)

processName

public String[] processName(String qName,
                            String[] parts,
                            boolean isAttribute)
Process a raw XML 1.0 name.

This method processes a raw XML 1.0 name in the current context by removing the prefix and looking it up among the prefixes currently declared. The return value will be the array supplied by the caller, filled in as follows:

parts[0]
The Namespace URI, or an empty string if none is in use.
parts[1]
The local name (without prefix).
parts[2]
The original raw name.

All of the strings in the array will be internalized. If the raw name has a prefix that has not been declared, then the return value will be null.

Note that attribute names are processed differently than element names: an unprefixed element name will received the default Namespace (if any), while an unprefixed element name will not.

Parameters:
qName - The raw XML 1.0 name to be processed.
parts - An array supplied by the caller, capable of holding at least three members.
isAttribute - A flag indicating whether this is an attribute name (true) or an element name (false).
Returns:
The supplied array holding three internalized strings representing the Namespace URI (or empty string), the local name, and the raw XML 1.0 name; or null if there is an undeclared prefix.
See Also:
declarePrefix(java.lang.String, java.lang.String), String.intern()

getURI

public String getURI(String prefix)
Look up a prefix and get the currently-mapped Namespace URI.

This method looks up the prefix in the current context. Use the empty string ("") for the default Namespace.

Parameters:
prefix - The prefix to look up.
Returns:
The associated Namespace URI, or null if the prefix is undeclared in this context.
See Also:
getPrefix(java.lang.String), getPrefixes()

getPrefixes

public Enumeration getPrefixes()
Return an enumeration of all prefixes currently declared.

Note: if there is a default prefix, it will not be returned in this enumeration; check for the default prefix using the getURI with an argument of "".

Returns:
An enumeration of all prefixes declared in the current context except for the empty (default) prefix.
See Also:
getDeclaredPrefixes(), getURI(java.lang.String)

getPrefix

public String getPrefix(String uri)
Return one of the prefixes mapped to a Namespace URI.

If more than one prefix is currently mapped to the same URI, this method will make an arbitrary selection; if you want all of the prefixes, use the getPrefixes() method instead.

Note: this will never return the empty (default) prefix; to check for a default prefix, use the getURI method with an argument of "".

Parameters:
uri - The Namespace URI.
Returns:
One of the prefixes currently mapped to the URI supplied, or null if none is mapped or if the URI is assigned to the default Namespace.
See Also:
getPrefixes(java.lang.String), getURI(java.lang.String)

getPrefixes

public Enumeration getPrefixes(String uri)
Return an enumeration of all prefixes currently declared for a URI.

This method returns prefixes mapped to a specific Namespace URI. The xml: prefix will be included. If you want only one prefix that's mapped to the Namespace URI, and you don't care which one you get, use the getPrefix method instead.

Note: the empty (default) prefix is never included in this enumeration; to check for the presence of a default Namespace, use the getURI method with an argument of "".

Parameters:
uri - The Namespace URI.
Returns:
An enumeration of all prefixes declared in the current context.
See Also:
getPrefix(java.lang.String),
getDeclaredPrefixes(),
getURI(java.lang.String)

getDeclaredPrefixes

public Enumeration getDeclaredPrefixes()
Return an enumeration of all prefixes declared in this context.

The empty (default) prefix will be included in this enumeration; note that this behaviour differs from that of getPrefix(java.lang.String) and getPrefixes().

Returns:
An enumeration of all prefixes declared in this context.
See Also:
getPrefixes(), getURI(java.lang.String)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


org.xml.sax.helpers (Java 2 Platform SE v1.4.2)

 org.xml.sax.helpers
Classes
AttributeListImpl
AttributesImpl
DefaultHandler
LocatorImpl
NamespaceSupport
ParserAdapter
ParserFactory
XMLFilterImpl
XMLReaderAdapter
XMLReaderFactory


org.xml.sax.helpers (Java 2 Platform SE v1.4.2)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package org.xml.sax.helpers

Provides helper classes for the Simple API for XML (SAX) which is a component of the Java API for XML Processing.

See:
Description

Class Summary
AttributeListImpl | Deprecated. This class implements a deprecated interface, AttributeList; that interface has been replaced by Attributes, which is implemented in the AttributesImpl helper class.
AttributesImpl | Default implementation of the Attributes interface.
DefaultHandler | Default base class for SAX2 event handlers.
LocatorImpl | Provide an optional convenience implementation of Locator.
NamespaceSupport | Encapsulate Namespace logic for use by SAX drivers.
ParserAdapter | Adapt a SAX1 Parser as a SAX2 XMLReader.
ParserFactory | Deprecated. This class works with the deprecated Parser interface.
XMLFilterImpl | Base class for deriving an XML filter.
XMLReaderAdapter | Adapt a SAX2 XMLReader as a SAX1 Parser.
XMLReaderFactory | Factory for creating an XML reader.

Package org.xml.sax.helpers Description

Provides helper classes for the Simple API for XML (SAX) which is a component of the Java API for XML Processing. SAX, the Simple API for XML, is a standard interface for event-based XML parsing, developed collaboratively by the members of the XML-DEV mailing list, currently hosted by OASIS. See the following link for more information on SAX.

Since:
JDK1.4
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


org.xml.sax.helpers Class Hierarchy (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package org.xml.sax.helpers

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class org.xml.sax.helpers.AttributeListImpl (implements org.xml.sax.AttributeList)
    • class org.xml.sax.helpers.AttributesImpl (implements org.xml.sax.Attributes)
    • class org.xml.sax.helpers.DefaultHandler (implements org.xml.sax.ContentHandler, org.xml.sax.DTDHandler, org.xml.sax.EntityResolver, org.xml.sax.ErrorHandler)
    • class org.xml.sax.helpers.LocatorImpl (implements org.xml.sax.Locator)
    • class org.xml.sax.helpers.NamespaceSupport
    • class org.xml.sax.helpers.ParserAdapter (implements org.xml.sax.DocumentHandler, org.xml.sax.XMLReader)
    • class org.xml.sax.helpers.ParserFactory
    • class org.xml.sax.helpers.XMLFilterImpl (implements org.xml.sax.ContentHandler, org.xml.sax.DTDHandler, org.xml.sax.EntityResolver, org.xml.sax.ErrorHandler, org.xml.sax.XMLFilter)
    • class org.xml.sax.helpers.XMLReaderAdapter (implements org.xml.sax.ContentHandler, org.xml.sax.Parser)
    • class org.xml.sax.helpers.XMLReaderFactory
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Package org.xml.sax.helpers (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Package
org.xml.sax.helpers

Packages that use org.xml.sax.helpers
javax.xml.parsers Provides classes allowing the processing of XML documents.

Classes in org.xml.sax.helpers used by javax.xml.parsers
DefaultHandler
Default base class for SAX2 event handlers.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


ParserAdapter (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.xml.sax.helpers
Class ParserAdapter

java.lang.Object
    extended by org.xml.sax.helpers.ParserAdapter
All Implemented Interfaces:
DocumentHandler, XMLReader
public class ParserAdapter
extends Object
implements XMLReader, DocumentHandler

Adapt a SAX1 Parser as a SAX2 XMLReader.

This module, both source code and documentation, is in the Public Domain, and comes with NO WARRANTY.

This class wraps a SAX1 Parser and makes it act as a SAX2 XMLReader, with feature, property, and Namespace support. Note that it is not possible to report skippedEntity events, since SAX1 does not make that information available.

This adapter does not test for duplicate Namespace-qualified attribute names.

Since:
SAX 2.0
See Also:
XMLReaderAdapter, XMLReader, Parser

Constructor Summary
ParserAdapter()
Construct a new parser adapter.
ParserAdapter(Parser parser)
Construct a new parser adapter.
Method Summary
void | characters(char[] ch, int start, int length) Adapt a SAX1 characters event.
void | endDocument() Adapt a SAX1 end document event.
void | endElement(String qName) Adapt a SAX1 end element event.
ContentHandler | getContentHandler() Return the current content handler.
DTDHandler | getDTDHandler() Return the current DTD handler.
EntityResolver | getEntityResolver() Return the current entity resolver.
ErrorHandler | getErrorHandler() Return the current error handler.
boolean | getFeature(String name) Check a parser feature.
Object | getProperty(String name) Get a parser property.
void | ignorableWhitespace(char[] ch, int start, int length) Adapt a SAX1 ignorable whitespace event.
void | parse(InputSource input) Parse an XML document.
void | parse(String systemId) Parse an XML document.
void | processingInstruction(String target, String data) Adapt a SAX1 processing instruction event.
void | setContentHandler(ContentHandler handler) Set the content handler.
void | setDocumentLocator(Locator locator) Adapt a SAX1 document locator event.
void | setDTDHandler(DTDHandler handler) Set the DTD handler.
void | setEntityResolver(EntityResolver resolver) Set the entity resolver.
void | setErrorHandler(ErrorHandler handler) Set the error handler.
void | setFeature(String name, boolean state) Set a feature for the parser.
void | setProperty(String name, Object value) Set a parser property.
void | startDocument() Adapt a SAX1 start document event.
void | startElement(String qName, AttributeList qAtts) Adapt a SAX1 startElement event.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ParserAdapter

public ParserAdapter()
              throws SAXException
Construct a new parser adapter.

Use the "org.xml.sax.parser" property to locate the embedded SAX1 driver.

Throws:
SAXException - If the embedded driver cannot be instantiated or if the org.xml.sax.parser property is not specified.

ParserAdapter

public ParserAdapter(Parser parser)
Construct a new parser adapter.

Note that the embedded parser cannot be changed once the adapter is created; to embed a different parser, allocate a new ParserAdapter.

Parameters:
parser - The SAX1 parser to embed.
Throws:
NullPointerException - If the parser parameter is null.
Method Detail

setFeature

public void setFeature(String name,
                       boolean state)
                throws SAXNotRecognizedException,
                       SAXNotSupportedException
Set a feature for the parser.

The only features supported are namespaces and namespace-prefixes.

Specified by:
setFeature in interface XMLReader
Parameters:
name - The feature name, as a complete URI.
state - The requested feature state.
Throws:
SAXNotRecognizedException - If the feature name is not known.
SAXNotSupportedException - If the feature state is not supported.
See Also:
XMLReader.setFeature(java.lang.String, boolean)

getFeature

public boolean getFeature(String name)
                   throws SAXNotRecognizedException,
                          SAXNotSupportedException
Check a parser feature.

The only features supported are namespaces and namespace-prefixes.

Specified by:
getFeature in interface XMLReader
Parameters:
name - The feature name, as a complete URI.
Returns:
The current feature state.
Throws:
SAXNotRecognizedException - If the feature name is not known.
SAXNotSupportedException - If querying the feature state is not supported.
See Also:
XMLReader.setFeature(java.lang.String, boolean)

setProperty

public void setProperty(String name,
                        Object value)
                 throws SAXNotRecognizedException,
                        SAXNotSupportedException
Set a parser property.

No special properties are currently supported.

Specified by:
setProperty in interface XMLReader
Parameters:
name - The property name.
value - The property value.
Throws:
SAXNotRecognizedException - If the feature name is not known.
SAXNotSupportedException - If the feature state is not supported.
See Also:
XMLReader.setProperty(java.lang.String, java.lang.Object)

getProperty

public Object getProperty(String name)
                   throws SAXNotRecognizedException,
                          SAXNotSupportedException
Get a parser property.

No special properties are currently supported.

Specified by:
getProperty in interface XMLReader
Parameters:
name - The property name.
Returns:
The property value.
Throws:
SAXNotRecognizedException - If the feature name is not known.
SAXNotSupportedException - If the feature state is not supported.
See Also:
XMLReader.getProperty(java.lang.String)

setEntityResolver

public void setEntityResolver(EntityResolver resolver)
Set the entity resolver.

Specified by:
setEntityResolver in interface XMLReader
Parameters:
resolver - The new entity resolver.
Throws:
NullPointerException - If the entity resolver parameter is null.
See Also:
XMLReader.setEntityResolver(org.xml.sax.EntityResolver)

getEntityResolver

public EntityResolver getEntityResolver()
Return the current entity resolver.

Specified by:
getEntityResolver in interface XMLReader
Returns:
The current entity resolver, or null if none was supplied.
See Also:
XMLReader.getEntityResolver()

setDTDHandler

public void setDTDHandler(DTDHandler handler)
Set the DTD handler.

Specified by:
setDTDHandler in interface XMLReader
Parameters:
handler - The DTD handler.
Throws:
NullPointerException - If the DTD handler parameter is null.
See Also:
XMLReader.setEntityResolver(org.xml.sax.EntityResolver)

getDTDHandler

public DTDHandler getDTDHandler()
Return the current DTD handler.

Specified by:
getDTDHandler in interface XMLReader
Returns:
The current DTD handler, or null if none was supplied.
See Also:
XMLReader.getEntityResolver()

setContentHandler

public void setContentHandler(ContentHandler handler)
Set the content handler.

Specified by:
setContentHandler in interface XMLReader
Parameters:
handler - The content handler.
Throws:
NullPointerException - If the content handler parameter is null.
See Also:
XMLReader.setEntityResolver(org.xml.sax.EntityResolver)

getContentHandler

public ContentHandler getContentHandler()
Return the current content handler.

Specified by:
getContentHandler in interface XMLReader
Returns:
The current content handler, or null if none was supplied.
See Also:
XMLReader.getEntityResolver()

setErrorHandler

public void setErrorHandler(ErrorHandler handler)
Set the error handler.

Specified by:
setErrorHandler in interface XMLReader
Parameters:
handler - The error handler.
Throws:
NullPointerException - If the error handler parameter is null.
See Also:
XMLReader.setEntityResolver(org.xml.sax.EntityResolver)

getErrorHandler

public ErrorHandler getErrorHandler()
Return the current error handler.

Specified by:
getErrorHandler in interface XMLReader
Returns:
The current error handler, or null if none was supplied.
See Also:
XMLReader.getEntityResolver()

parse

public void parse(String systemId)
           throws IOException,
                  SAXException
Parse an XML document.

Specified by:
parse in interface XMLReader
Parameters:
systemId - The absolute URL of the document.
Throws:
IOException - If there is a problem reading the raw content of the document.
SAXException - If there is a problem processing the document.
See Also:
parse(org.xml.sax.InputSource), Parser.parse(java.lang.String)

parse

public void parse(InputSource input)
           throws IOException,
                  SAXException
Parse an XML document.

Specified by:
parse in interface XMLReader
Parameters:
input - An input source for the document.
Throws:
IOException - If there is a problem reading the raw content of the document.
SAXException - If there is a problem processing the document.
See Also:
parse(java.lang.String), Parser.parse(org.xml.sax.InputSource)

setDocumentLocator

public void setDocumentLocator(Locator locator)
Adapt a SAX1 document locator event.

Specified by:
setDocumentLocator in interface DocumentHandler
Parameters:
locator - A document locator.
See Also:
ContentHandler.setDocumentLocator(org.xml.sax.Locator)

startDocument

public void startDocument()
                   throws SAXException
Adapt a SAX1 start document event.

Specified by:
startDocument in interface DocumentHandler
Throws:
SAXException - The client may raise a processing exception.
See Also:
DocumentHandler.startDocument()

endDocument

public void endDocument()
                 throws SAXException
Adapt a SAX1 end document event.

Specified by:
endDocument in interface DocumentHandler
Throws:
SAXException - The client may raise a processing exception.
See Also:
DocumentHandler.endDocument()

startElement

public void startElement(String qName,
                         AttributeList qAtts)
                  throws SAXException
Adapt a SAX1 startElement event.

If necessary, perform Namespace processing.

Specified by:
startElement in interface DocumentHandler
Parameters:
qName - The qualified (prefixed) name.
qAtts - The XML 1.0 attribute list (with qnames).
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
DocumentHandler.endElement(java.lang.String), AttributeList

endElement

public void endElement(String qName)
                throws SAXException
Adapt a SAX1 end element event.

Specified by:
endElement in interface DocumentHandler
Parameters:
qName - The qualified (prefixed) name.
Throws:
SAXException - The client may raise a processing exception.
See Also:
DocumentHandler.endElement(java.lang.String)

characters

public void characters(char[] ch,
                       int start,
                       int length)
                throws SAXException
Adapt a SAX1 characters event.

Specified by:
characters in interface DocumentHandler
Parameters:
ch - An array of characters.
start - The starting position in the array.
length - The number of characters to use.
Throws:
SAXException - The client may raise a processing exception.
See Also:
DocumentHandler.characters(char[], int, int)

ignorableWhitespace

public void ignorableWhitespace(char[] ch,
                                int start,
                                int length)
                         throws SAXException
Adapt a SAX1 ignorable whitespace event.

Specified by:
ignorableWhitespace in interface DocumentHandler
Parameters:
ch - An array of characters.
start - The starting position in the array.
length - The number of characters to use.
Throws:
SAXException - The client may raise a processing exception.
See Also:
DocumentHandler.ignorableWhitespace(char[], int, int)

processingInstruction

public void processingInstruction(String target,
                                  String data)
                           throws SAXException
Adapt a SAX1 processing instruction event.

Specified by:
processingInstruction in interface DocumentHandler
Parameters:
target - The processing instruction target.
data - The remainder of the processing instruction
Throws:
SAXException - The client may raise a processing exception.
See Also:
DocumentHandler.processingInstruction(java.lang.String, java.lang.String)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ParserFactory (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.xml.sax.helpers
Class ParserFactory

java.lang.Object
    extended by org.xml.sax.helpers.ParserFactory
Deprecated. This class works with the deprecated Parser interface.

public class ParserFactory
extends Object

Java-specific class for dynamically loading SAX parsers.

This module, both source code and documentation, is in the Public Domain, and comes with NO WARRANTY.

Note: This class is designed to work with the now-deprecated SAX1 Parser class. SAX2 applications should use XMLReaderFactory instead.

ParserFactory is not part of the platform-independent definition of SAX; it is an additional convenience class designed specifically for Java XML application writers. SAX applications can use the static methods in this class to allocate a SAX parser dynamically at run-time based either on the value of the `org.xml.sax.parser' system property or on a string containing the class name.

Note that the application still requires an XML parser that implements SAX1.

Since:
SAX 1.0
See Also:
Parser, Class

Method Summary
static Parser | makeParser() Deprecated. Create a new SAX parser using the `org.xml.sax.parser' system property.
static Parser | makeParser(String className) Deprecated. Create a new SAX parser object using the class name provided.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Method Detail

makeParser

public static Parser makeParser()
                         throws ClassNotFoundException,
                                IllegalAccessException,
                                InstantiationException,
                                NullPointerException,
                                ClassCastException
Deprecated.
Create a new SAX parser using the `org.xml.sax.parser' system property.

The named class must exist and must implement the Parser interface.

Throws:
NullPointerException - There is no value for the `org.xml.sax.parser' system property.
ClassNotFoundException - The SAX parser class was not found (check your CLASSPATH).
IllegalAccessException - The SAX parser class was found, but you do not have permission to load it.
InstantiationException - The SAX parser class was found but could not be instantiated.
ClassCastException - The SAX parser class was found and instantiated, but does not implement org.xml.sax.Parser.
See Also:
makeParser(java.lang.String), Parser

makeParser

public static Parser makeParser(String className)
                         throws ClassNotFoundException,
                                IllegalAccessException,
                                InstantiationException,
                                ClassCastException
Deprecated.
Create a new SAX parser object using the class name provided.

The named class must exist and must implement the Parser interface.

Parameters:
className - A string containing the name of the SAX parser class.
Throws:
ClassNotFoundException - The SAX parser class was not found (check your CLASSPATH).
IllegalAccessException - The SAX parser class was found, but you do not have permission to load it.
InstantiationException - The SAX parser class was found but could not be instantiated.
ClassCastException - The SAX parser class was found and instantiated, but does not implement org.xml.sax.Parser.
See Also:
makeParser(), Parser
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


XMLFilterImpl (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.xml.sax.helpers
Class XMLFilterImpl

java.lang.Object
    extended by org.xml.sax.helpers.XMLFilterImpl
All Implemented Interfaces:
ContentHandler, DTDHandler, EntityResolver, ErrorHandler, XMLFilter, XMLReader
public class XMLFilterImpl
extends Object
implements XMLFilter, EntityResolver, DTDHandler, ContentHandler, ErrorHandler

Base class for deriving an XML filter.

This module, both source code and documentation, is in the Public Domain, and comes with NO WARRANTY.

This class is designed to sit between an XMLReader and the client application's event handlers. By default, it does nothing but pass requests up to the reader and events on to the handlers unmodified, but subclasses can override specific methods to modify the event stream or the configuration requests as they pass through.

Since:
SAX 2.0
See Also:
XMLFilter, XMLReader, EntityResolver, DTDHandler, ContentHandler, ErrorHandler

Constructor Summary
XMLFilterImpl()
Construct an empty XML filter, with no parent.
XMLFilterImpl(XMLReader parent)
Construct an XML filter with the specified parent.
Method Summary
void | characters(char[] ch, int start, int length) Filter a character data event.
void | endDocument() Filter an end document event.
void | endElement(String uri, String localName, String qName) Filter an end element event.
void | endPrefixMapping(String prefix) Filter an end Namespace prefix mapping event.
void | error(SAXParseException e) Filter an error event.
void | fatalError(SAXParseException e) Filter a fatal error event.
ContentHandler | getContentHandler() Get the content event handler.
DTDHandler | getDTDHandler() Get the current DTD event handler.
EntityResolver | getEntityResolver() Get the current entity resolver.
ErrorHandler | getErrorHandler() Get the current error event handler.
boolean | getFeature(String name) Look up the state of a feature.
XMLReader | getParent() Get the parent reader.
Object | getProperty(String name) Look up the value of a property.
void | ignorableWhitespace(char[] ch, int start, int length) Filter an ignorable whitespace event.
void | notationDecl(String name, String publicId, String systemId) Filter a notation declaration event.
void | parse(InputSource input) Parse a document.
void | parse(String systemId) Parse a document.
void | processingInstruction(String target, String data) Filter a processing instruction event.
InputSource | resolveEntity(String publicId, String systemId) Filter an external entity resolution.
void | setContentHandler(ContentHandler handler) Set the content event handler.
void | setDocumentLocator(Locator locator) Filter a new document locator event.
void | setDTDHandler(DTDHandler handler) Set the DTD event handler.
void | setEntityResolver(EntityResolver resolver) Set the entity resolver.
void | setErrorHandler(ErrorHandler handler) Set the error event handler.
void | setFeature(String name, boolean state) Set the state of a feature.
void | setParent(XMLReader parent) Set the parent reader.
void | setProperty(String name, Object value) Set the value of a property.
void | skippedEntity(String name) Filter a skipped entity event.
void | startDocument() Filter a start document event.
void | startElement(String uri, String localName, String qName, Attributes atts) Filter a start element event.
void | startPrefixMapping(String prefix, String uri) Filter a start Namespace prefix mapping event.
void | unparsedEntityDecl(String name, String publicId, String systemId, String notationName) Filter an unparsed entity declaration event.
void | warning(SAXParseException e) Filter a warning event.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

XMLFilterImpl

public XMLFilterImpl()
Construct an empty XML filter, with no parent.

This filter will have no parent: you must assign a parent before you start a parse or do any configuration with setFeature or setProperty.

See Also:
XMLReader.setFeature(java.lang.String, boolean), XMLReader.setProperty(java.lang.String, java.lang.Object)

XMLFilterImpl

public XMLFilterImpl(XMLReader parent)
Construct an XML filter with the specified parent.

See Also:
setParent(org.xml.sax.XMLReader), getParent()
Method Detail

setParent

public void setParent(XMLReader parent)
Set the parent reader.

This is the XMLReader from which this filter will obtain its events and to which it will pass its configuration requests. The parent may itself be another filter.

If there is no parent reader set, any attempt to parse or to set or get a feature or property will fail.

Specified by:
setParent in interface XMLFilter
Parameters:
parent - The parent XML reader.
Throws:
NullPointerException - If the parent is null.
See Also:
getParent()

getParent

public XMLReader getParent()
Get the parent reader.

Specified by:
getParent in interface XMLFilter
Returns:
The parent XML reader, or null if none is set.
See Also:
setParent(org.xml.sax.XMLReader)

setFeature

public void setFeature(String name,
                       boolean state)
                throws SAXNotRecognizedException,
                       SAXNotSupportedException
Set the state of a feature.

This will always fail if the parent is null.

Specified by:
setFeature in interface XMLReader
Parameters:
name - The feature name.
state - The requested feature state.
Throws:
SAXNotRecognizedException - When the XMLReader does not recognize the feature name.
SAXNotSupportedException - When the XMLReader recognizes the feature name but cannot set the requested value.
See Also:
XMLReader.setFeature(java.lang.String, boolean)

getFeature

public boolean getFeature(String name)
                   throws SAXNotRecognizedException,
                          SAXNotSupportedException
Look up the state of a feature.

This will always fail if the parent is null.

Specified by:
getFeature in interface XMLReader
Parameters:
name - The feature name.
Returns:
The current state of the feature.
Throws:
SAXNotRecognizedException - When the XMLReader does not recognize the feature name.
SAXNotSupportedException - When the XMLReader recognizes the feature name but cannot determine its state at this time.
See Also:
XMLReader.getFeature(java.lang.String)

setProperty

public void setProperty(String name,
                        Object value)
                 throws SAXNotRecognizedException,
                        SAXNotSupportedException
Set the value of a property.

This will always fail if the parent is null.

Specified by:
setProperty in interface XMLReader
Parameters:
name - The property name.
Throws:
SAXNotRecognizedException - When the XMLReader does not recognize the property name.
SAXNotSupportedException - When the XMLReader recognizes the property name but cannot set the requested value.
See Also:
XMLReader.setProperty(java.lang.String, java.lang.Object)

getProperty

public Object getProperty(String name)
                   throws SAXNotRecognizedException,
                          SAXNotSupportedException
Look up the value of a property.

Specified by:
getProperty in interface XMLReader
Parameters:
name - The property name.
Returns:
The current value of the property.
Throws:
SAXNotRecognizedException - When the XMLReader does not recognize the feature name.
SAXNotSupportedException - When the XMLReader recognizes the property name but cannot determine its value at this time.
See Also:
XMLReader.setFeature(java.lang.String, boolean)

setEntityResolver

public void setEntityResolver(EntityResolver resolver)
Set the entity resolver.

Specified by:
setEntityResolver in interface XMLReader
Parameters:
resolver - The new entity resolver.
Throws:
NullPointerException - If the resolver is null.
See Also:
XMLReader.setEntityResolver(org.xml.sax.EntityResolver)

getEntityResolver

public EntityResolver getEntityResolver()
Get the current entity resolver.

Specified by:
getEntityResolver in interface XMLReader
Returns:
The current entity resolver, or null if none was set.
See Also:
XMLReader.getEntityResolver()

setDTDHandler

public void setDTDHandler(DTDHandler handler)
Set the DTD event handler.

Specified by:
setDTDHandler in interface XMLReader
Parameters:
handler - The DTD handler.
Throws:
NullPointerException - If the handler is null.
See Also:
XMLReader.setDTDHandler(org.xml.sax.DTDHandler)

getDTDHandler

public DTDHandler getDTDHandler()
Get the current DTD event handler.

Specified by:
getDTDHandler in interface XMLReader
Returns:
The current DTD handler, or null if none was set.
See Also:
XMLReader.getDTDHandler()

setContentHandler

public void setContentHandler(ContentHandler handler)
Set the content event handler.

Specified by:
setContentHandler in interface XMLReader
Parameters:
handler - The content handler.
Throws:
NullPointerException - If the handler is null.
See Also:
XMLReader.setContentHandler(org.xml.sax.ContentHandler)

getContentHandler

public ContentHandler getContentHandler()
Get the content event handler.

Specified by:
getContentHandler in interface XMLReader
Returns:
The current content handler, or null if none was set.
See Also:
XMLReader.getContentHandler()

setErrorHandler

public void setErrorHandler(ErrorHandler handler)
Set the error event handler.

Specified by:
setErrorHandler in interface XMLReader
Parameters:
handler - The error handler.
Throws:
NullPointerException - If the handler is null.
See Also:
XMLReader.setErrorHandler(org.xml.sax.ErrorHandler)

getErrorHandler

public ErrorHandler getErrorHandler()
Get the current error event handler.

Specified by:
getErrorHandler in interface XMLReader
Returns:
The current error handler, or null if none was set.
See Also:
XMLReader.getErrorHandler()

parse

public void parse(InputSource input)
           throws SAXException,
                  IOException
Parse a document.

Specified by:
parse in interface XMLReader
Parameters:
input - The input source for the document entity.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
IOException - An IO exception from the parser, possibly from a byte stream or character stream supplied by the application.
See Also:
XMLReader.parse(org.xml.sax.InputSource)

parse

public void parse(String systemId)
           throws SAXException,
                  IOException
Parse a document.

Specified by:
parse in interface XMLReader
Parameters:
systemId - The system identifier as a fully-qualified URI.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
IOException - An IO exception from the parser, possibly from a byte stream or character stream supplied by the application.
See Also:
XMLReader.parse(java.lang.String)

resolveEntity

public InputSource resolveEntity(String publicId,
                                 String systemId)
                          throws SAXException,
                                 IOException
Filter an external entity resolution.

Specified by:
resolveEntity in interface EntityResolver
Parameters:
publicId - The entity's public identifier, or null.
systemId - The entity's system identifier.
Returns:
A new InputSource or null for the default.
Throws:
SAXException - The client may throw an exception during processing.
IOException - The client may throw an I/O-related exception while obtaining the new InputSource.
See Also:
EntityResolver.resolveEntity(java.lang.String, java.lang.String)

notationDecl

public void notationDecl(String name,
                         String publicId,
                         String systemId)
                  throws SAXException
Filter a notation declaration event.

Specified by:
notationDecl in interface DTDHandler
Parameters:
name - The notation name.
publicId - The notation's public identifier, or null.
systemId - The notation's system identifier, or null.
Throws:
SAXException - The client may throw an exception during processing.
See Also:
DTDHandler.notationDecl(java.lang.String, java.lang.String, java.lang.String)

unparsedEntityDecl

public void unparsedEntityDecl(String name,
                               String publicId,
                               String systemId,
                               String notationName)
                        throws SAXException
Filter an unparsed entity declaration event.

Specified by:
unparsedEntityDecl in interface DTDHandler
Parameters:
name - The entity name.
publicId - The entity's public identifier, or null.
systemId - The entity's system identifier, or null.
notationName - The name of the associated notation.
Throws:
SAXException - The client may throw an exception during processing.
See Also:
DTDHandler.unparsedEntityDecl(java.lang.String, java.lang.String, java.lang.String, java.lang.String)

setDocumentLocator

public void setDocumentLocator(Locator locator)
Filter a new document locator event.

Specified by:
setDocumentLocator in interface ContentHandler
Parameters:
locator - The document locator.
See Also:
ContentHandler.setDocumentLocator(org.xml.sax.Locator)

startDocument

public void startDocument()
                   throws SAXException
Filter a start document event.

Specified by:
startDocument in interface ContentHandler
Throws:
SAXException - The client may throw an exception during processing.
See Also:
ContentHandler.startDocument()

endDocument

public void endDocument()
                 throws SAXException
Filter an end document event.

Specified by:
endDocument in interface ContentHandler
Throws:
SAXException - The client may throw an exception during processing.
See Also:
ContentHandler.endDocument()

startPrefixMapping

public void startPrefixMapping(String prefix,
                               String uri)
                        throws SAXException
Filter a start Namespace prefix mapping event.

Specified by:
startPrefixMapping in interface ContentHandler
Parameters:
prefix - The Namespace prefix.
uri - The Namespace URI.
Throws:
SAXException - The client may throw an exception during processing.
See Also:
ContentHandler.startPrefixMapping(java.lang.String, java.lang.String)

endPrefixMapping

public void endPrefixMapping(String prefix)
                      throws SAXException
Filter an end Namespace prefix mapping event.

Specified by:
endPrefixMapping in interface ContentHandler
Parameters:
prefix - The Namespace prefix.
Throws:
SAXException - The client may throw an exception during processing.
See Also:
ContentHandler.endPrefixMapping(java.lang.String)

startElement

public void startElement(String uri,
                         String localName,
                         String qName,
                         Attributes atts)
                  throws SAXException
Filter a start element event.

Specified by:
startElement in interface ContentHandler
Parameters:
uri - The element's Namespace URI, or the empty string.
localName - The element's local name, or the empty string.
qName - The element's qualified (prefixed) name, or the empty string.
atts - The element's attributes.
Throws:
SAXException - The client may throw an exception during processing.
See Also:
ContentHandler.startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)

endElement

public void endElement(String uri,
                       String localName,
                       String qName)
                throws SAXException
Filter an end element event.

Specified by:
endElement in interface ContentHandler
Parameters:
uri - The element's Namespace URI, or the empty string.
localName - The element's local name, or the empty string.
qName - The element's qualified (prefixed) name, or the empty string.
Throws:
SAXException - The client may throw an exception during processing.
See Also:
ContentHandler.endElement(java.lang.String, java.lang.String, java.lang.String)

characters

public void characters(char[] ch,
                       int start,
                       int length)
                throws SAXException
Filter a character data event.

Specified by:
characters in interface ContentHandler
Parameters:
ch - An array of characters.
start - The starting position in the array.
length - The number of characters to use from the array.
Throws:
SAXException - The client may throw an exception during processing.
See Also:
ContentHandler.characters(char[], int, int)

ignorableWhitespace

public void ignorableWhitespace(char[] ch,
                                int start,
                                int length)
                         throws SAXException
Filter an ignorable whitespace event.

Specified by:
ignorableWhitespace in interface ContentHandler
Parameters:
ch - An array of characters.
start - The starting position in the array.
length - The number of characters to use from the array.
Throws:
SAXException - The client may throw an exception during processing.
See Also:
ContentHandler.ignorableWhitespace(char[], int, int)

processingInstruction

public void processingInstruction(String target,
                                  String data)
                           throws SAXException
Filter a processing instruction event.

Specified by:
processingInstruction in interface ContentHandler
Parameters:
target - The processing instruction target.
data - The text following the target.
Throws:
SAXException - The client may throw an exception during processing.
See Also:
ContentHandler.processingInstruction(java.lang.String, java.lang.String)

skippedEntity

public void skippedEntity(String name)
                   throws SAXException
Filter a skipped entity event.

Specified by:
skippedEntity in interface ContentHandler
Parameters:
name - The name of the skipped entity.
Throws:
SAXException - The client may throw an exception during processing.
See Also:
ContentHandler.skippedEntity(java.lang.String)

warning

public void warning(SAXParseException e)
             throws SAXException
Filter a warning event.

Specified by:
warning in interface ErrorHandler
Parameters:
e - The nwarning as an exception.
Throws:
SAXException - The client may throw an exception during processing.
See Also:
ErrorHandler.warning(org.xml.sax.SAXParseException)

error

public void error(SAXParseException e)
           throws SAXException
Filter an error event.

Specified by:
error in interface ErrorHandler
Parameters:
e - The error as an exception.
Throws:
SAXException - The client may throw an exception during processing.
See Also:
ErrorHandler.error(org.xml.sax.SAXParseException)

fatalError

public void fatalError(SAXParseException e)
                throws SAXException
Filter a fatal error event.

Specified by:
fatalError in interface ErrorHandler
Parameters:
e - The error as an exception.
Throws:
SAXException - The client may throw an exception during processing.
See Also:
ErrorHandler.fatalError(org.xml.sax.SAXParseException)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


XMLReaderAdapter (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.xml.sax.helpers
Class XMLReaderAdapter

java.lang.Object
    extended by org.xml.sax.helpers.XMLReaderAdapter
All Implemented Interfaces:
ContentHandler, Parser
public class XMLReaderAdapter
extends Object
implements Parser, ContentHandler

Adapt a SAX2 XMLReader as a SAX1 Parser.

This module, both source code and documentation, is in the Public Domain, and comes with NO WARRANTY.

This class wraps a SAX2 XMLReader and makes it act as a SAX1 Parser. The XMLReader must support a true value for the http://xml.org/sax/features/namespace-prefixes property or parsing will fail with a SAXException; if the XMLReader supports a false value for the http://xml.org/sax/features/namespaces property, that will also be used to improve efficiency.

Since:
SAX 2.0
See Also:
Parser, XMLReader

Constructor Summary
XMLReaderAdapter()
Create a new adapter.
XMLReaderAdapter(XMLReader xmlReader)
Create a new adapter.
Method Summary
void | characters(char[] ch, int start, int length) Adapt a SAX2 characters event.
void | endDocument() End document event.
void | endElement(String uri, String localName, String qName) Adapt a SAX2 end element event.
void | endPrefixMapping(String prefix) Adapt a SAX2 end prefix mapping event.
void | ignorableWhitespace(char[] ch, int start, int length) Adapt a SAX2 ignorable whitespace event.
void | parse(InputSource input) Parse the document.
void | parse(String systemId) Parse the document.
void | processingInstruction(String target, String data) Adapt a SAX2 processing instruction event.
void | setDocumentHandler(DocumentHandler handler) Register the SAX1 document event handler.
void | setDocumentLocator(Locator locator) Set a document locator.
void | setDTDHandler(DTDHandler handler) Register the DTD event handler.
void | setEntityResolver(EntityResolver resolver) Register the entity resolver.
void | setErrorHandler(ErrorHandler handler) Register the error event handler.
void | setLocale(Locale locale) Set the locale for error reporting.
void | skippedEntity(String name) Adapt a SAX2 skipped entity event.
void | startDocument() Start document event.
void | startElement(String uri, String localName, String qName, Attributes atts) Adapt a SAX2 start element event.
void | startPrefixMapping(String prefix, String uri) Adapt a SAX2 start prefix mapping event.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

XMLReaderAdapter

public XMLReaderAdapter()
                 throws SAXException
Create a new adapter.

Use the "org.xml.sax.driver" property to locate the SAX2 driver to embed.

Throws:
SAXException - If the embedded driver cannot be instantiated or if the org.xml.sax.driver property is not specified.

XMLReaderAdapter

public XMLReaderAdapter(XMLReader xmlReader)
Create a new adapter.

Create a new adapter, wrapped around a SAX2 XMLReader. The adapter will make the XMLReader act like a SAX1 Parser.

Parameters:
xmlReader - The SAX2 XMLReader to wrap.
Throws:
NullPointerException - If the argument is null.
Method Detail

setLocale

public void setLocale(Locale locale)
               throws SAXException
Set the locale for error reporting.

This is not supported in SAX2, and will always throw an exception.

Specified by:
setLocale in interface Parser
Parameters:
locale - A Java Locale object.
Throws:
SAXException - Throws an exception (using the previous or default locale) if the requested locale is not supported.
See Also:
Parser.setLocale(java.util.Locale)

setEntityResolver

public void setEntityResolver(EntityResolver resolver)
Register the entity resolver.

Specified by:
setEntityResolver in interface Parser
Parameters:
resolver - The new resolver.
See Also:
Parser.setEntityResolver(org.xml.sax.EntityResolver)

setDTDHandler

public void setDTDHandler(DTDHandler handler)
Register the DTD event handler.

Specified by:
setDTDHandler in interface Parser
Parameters:
handler - The new DTD event handler.
See Also:
Parser.setDTDHandler(org.xml.sax.DTDHandler)

setDocumentHandler

public void setDocumentHandler(DocumentHandler handler)
Register the SAX1 document event handler.

Note that the SAX1 document handler has no Namespace support.

Specified by:
setDocumentHandler in interface Parser
Parameters:
handler - The new SAX1 document event handler.
See Also:
Parser.setDocumentHandler(org.xml.sax.DocumentHandler)

setErrorHandler

public void setErrorHandler(ErrorHandler handler)
Register the error event handler.

Specified by:
setErrorHandler in interface Parser
Parameters:
handler - The new error event handler.
See Also:
Parser.setErrorHandler(org.xml.sax.ErrorHandler)

parse

public void parse(String systemId)
           throws IOException,
                  SAXException
Parse the document.

This method will throw an exception if the embedded XMLReader does not support the http://xml.org/sax/features/namespace-prefixes property.

Specified by:
parse in interface Parser
Parameters:
systemId - The absolute URL of the document.
Throws:
IOException - If there is a problem reading the raw content of the document.
SAXException - If there is a problem processing the document.
See Also:
parse(org.xml.sax.InputSource), Parser.parse(java.lang.String)

parse

public void parse(InputSource input)
           throws IOException,
                  SAXException
Parse the document.

This method will throw an exception if the embedded XMLReader does not support the http://xml.org/sax/features/namespace-prefixes property.

Specified by:
parse in interface Parser
Parameters:
input - An input source for the document.
Throws:
IOException - If there is a problem reading the raw content of the document.
SAXException - If there is a problem processing the document.
See Also:
parse(java.lang.String), Parser.parse(org.xml.sax.InputSource)

setDocumentLocator

public void setDocumentLocator(Locator locator)
Set a document locator.

Specified by:
setDocumentLocator in interface ContentHandler
Parameters:
locator - The document locator.
See Also:
ContentHandler.setDocumentLocator(org.xml.sax.Locator)

startDocument

public void startDocument()
                   throws SAXException
Start document event.

Specified by:
startDocument in interface ContentHandler
Throws:
SAXException - The client may raise a processing exception.
See Also:
ContentHandler.startDocument()

endDocument

public void endDocument()
                 throws SAXException
End document event.

Specified by:
endDocument in interface ContentHandler
Throws:
SAXException - The client may raise a processing exception.
See Also:
ContentHandler.endDocument()

startPrefixMapping

public void startPrefixMapping(String prefix,
                               String uri)
Adapt a SAX2 start prefix mapping event.

Specified by:
startPrefixMapping in interface ContentHandler
Parameters:
prefix - The prefix being mapped.
uri - The Namespace URI being mapped to.
See Also:
ContentHandler.startPrefixMapping(java.lang.String, java.lang.String)

endPrefixMapping

public void endPrefixMapping(String prefix)
Adapt a SAX2 end prefix mapping event.

Specified by:
endPrefixMapping in interface ContentHandler
Parameters:
prefix - The prefix being mapped.
See Also:
ContentHandler.endPrefixMapping(java.lang.String)

startElement

public void startElement(String uri,
                         String localName,
                         String qName,
                         Attributes atts)
                  throws SAXException
Adapt a SAX2 start element event.

Specified by:
startElement in interface ContentHandler
Parameters:
uri - The Namespace URI.
localName - The Namespace local name.
qName - The qualified (prefixed) name.
atts - The SAX2 attributes.
Throws:
SAXException - The client may raise a processing exception.
See Also:
ContentHandler.endDocument()

endElement

public void endElement(String uri,
                       String localName,
                       String qName)
                throws SAXException
Adapt a SAX2 end element event.

Specified by:
endElement in interface ContentHandler
Parameters:
uri - The Namespace URI.
localName - The Namespace local name.
qName - The qualified (prefixed) name.
Throws:
SAXException - The client may raise a processing exception.
See Also:
ContentHandler.endElement(java.lang.String, java.lang.String, java.lang.String)

characters

public void characters(char[] ch,
                       int start,
                       int length)
                throws SAXException
Adapt a SAX2 characters event.

Specified by:
characters in interface ContentHandler
Parameters:
ch - An array of characters.
start - The starting position in the array.
length - The number of characters to use.
Throws:
SAXException - The client may raise a processing exception.
See Also:
ContentHandler.characters(char[], int, int)

ignorableWhitespace

public void ignorableWhitespace(char[] ch,
                                int start,
                                int length)
                         throws SAXException
Adapt a SAX2 ignorable whitespace event.

Specified by:
ignorableWhitespace in interface ContentHandler
Parameters:
ch - An array of characters.
start - The starting position in the array.
length - The number of characters to use.
Throws:
SAXException - The client may raise a processing exception.
See Also:
ContentHandler.ignorableWhitespace(char[], int, int)

processingInstruction

public void processingInstruction(String target,
                                  String data)
                           throws SAXException
Adapt a SAX2 processing instruction event.

Specified by:
processingInstruction in interface ContentHandler
Parameters:
target - The processing instruction target.
data - The remainder of the processing instruction
Throws:
SAXException - The client may raise a processing exception.
See Also:
ContentHandler.processingInstruction(java.lang.String, java.lang.String)

skippedEntity

public void skippedEntity(String name)
                   throws SAXException
Adapt a SAX2 skipped entity event.

Specified by:
skippedEntity in interface ContentHandler
Parameters:
name - The name of the skipped entity.
Throws:
SAXException - Any SAX exception, possibly wrapping another exception.
See Also:
ContentHandler.skippedEntity(java.lang.String)
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


XMLReaderFactory (Java 2 Platform SE v1.4.2)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.xml.sax.helpers
Class XMLReaderFactory

java.lang.Object
    extended by org.xml.sax.helpers.XMLReaderFactory
public final class XMLReaderFactory
extends Object

Factory for creating an XML reader.

This module, both source code and documentation, is in the Public Domain, and comes with NO WARRANTY.

This class contains static methods for creating an XML reader from an explicit class name, or for creating an XML reader based on the value of the org.xml.sax.driver system property:

 try {
   XMLReader myReader = XMLReaderFactory.createXMLReader();
 } catch (SAXException e) {
   System.err.println(e.getMessage());
 }

Note that these methods will not be usable in environments where system properties are not accessible or where the application or applet is not permitted to load classes dynamically.

Note to implementors: SAX implementations in specialized environments may replace this class with a different one optimized for the environment, as long as its method signatures remain the same.

Since:
SAX 2.0
See Also:
XMLReader

Method Summary
static XMLReader | createXMLReader() Attempt to create an XML reader from a system property.
static XMLReader | createXMLReader(String className) Attempt to create an XML reader from a class name.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Method Detail

createXMLReader

public static XMLReader createXMLReader()
                                 throws SAXException
Attempt to create an XML reader from a system property.

This method uses the value of the system property "org.xml.sax.driver" as the full name of a Java class and tries to instantiate that class as a SAX2 XMLReader.

Note that many Java interpreters allow system properties to be specified on the command line.

Returns:
A new XMLReader.
Throws:
SAXException - If the value of the "org.xml.sax.driver" system property is null, or if the class cannot be loaded and instantiated.
See Also:
createXMLReader(java.lang.String)

createXMLReader

public static XMLReader createXMLReader(String className)
                                 throws SAXException
Attempt to create an XML reader from a class name.

Given a class name, this method attempts to load and instantiate the class as an XML reader.

Returns:
A new XML reader.
Throws:
SAXException - If the class cannot be loaded, instantiated, and cast to XMLReader.
See Also:
createXMLReader()
Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Uses of Class org.xml.sax.helpers.AttributeListImpl (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.xml.sax.helpers.AttributeListImpl

No usage of org.xml.sax.helpers.AttributeListImpl

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.xml.sax.helpers.AttributesImpl (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.xml.sax.helpers.AttributesImpl

No usage of org.xml.sax.helpers.AttributesImpl

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.xml.sax.helpers.DefaultHandler (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.xml.sax.helpers.DefaultHandler

Packages that use DefaultHandler
javax.xml.parsers Provides classes allowing the processing of XML documents.

Uses of DefaultHandler in javax.xml.parsers

Methods in javax.xml.parsers with parameters of type DefaultHandler
void | SAXParser.parse(InputStream is, DefaultHandler dh) Parse the content of the given InputStream instance as XML using the specified DefaultHandler.
void | SAXParser.parse(InputStream is, DefaultHandler dh, String systemId) Parse the content of the given InputStream instance as XML using the specified DefaultHandler.
void | SAXParser.parse(String uri, DefaultHandler dh) Parse the content described by the giving Uniform Resource Identifier (URI) as XML using the specified DefaultHandler.
void | SAXParser.parse(File f, DefaultHandler dh) Parse the content of the file specified as XML using the specified DefaultHandler.
void | SAXParser.parse(InputSource is, DefaultHandler dh) Parse the content given InputSource as XML using the specified DefaultHandler.

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.xml.sax.helpers.LocatorImpl (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.xml.sax.helpers.LocatorImpl

No usage of org.xml.sax.helpers.LocatorImpl

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.xml.sax.helpers.NamespaceSupport (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.xml.sax.helpers.NamespaceSupport

No usage of org.xml.sax.helpers.NamespaceSupport

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.xml.sax.helpers.ParserAdapter (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.xml.sax.helpers.ParserAdapter

No usage of org.xml.sax.helpers.ParserAdapter

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.xml.sax.helpers.ParserFactory (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.xml.sax.helpers.ParserFactory

No usage of org.xml.sax.helpers.ParserFactory

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.xml.sax.helpers.XMLFilterImpl (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.xml.sax.helpers.XMLFilterImpl

No usage of org.xml.sax.helpers.XMLFilterImpl

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.xml.sax.helpers.XMLReaderAdapter (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.xml.sax.helpers.XMLReaderAdapter

No usage of org.xml.sax.helpers.XMLReaderAdapter

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


Uses of Class org.xml.sax.helpers.XMLReaderFactory (Java 2 Platform SE v1.4.2)

PREV NEXT FRAMES NO FRAMES

Uses of Class
org.xml.sax.helpers.XMLReaderFactory

No usage of org.xml.sax.helpers.XMLReaderFactory

Overview Package Class Use Tree Deprecated Index Help
JavaTM 2 Platform
Std. Ed. v1.4.2
PREV NEXT FRAMES NO FRAMES


1.4.2 2D Enhancements

Java

Enhancements to JavaTM 2D Technology in v1.4.2

 Documentation Contents
This page lists some of the most noteworthy 2D bugs that were fixed in J2SE v 1.4.2.

The following bugs were fixed to make full-screen exclusive mode more robust on Microsoft Windows:

4713003: Windows XP freezes on Java application exit/draw
4738111: Crash or hang when display mode changes on Matrox g400
4737785: Some fullscreen tests render no graphics without alt-tabbing out and back in
4690085: Color problems in fullscreen mode
4641396: Loss of video memory causes screen to turn white, and then freeze
4754180: Radeon blue-screen system crash on FullScreenTest when alt-tabbing

The following bugs were fixed to make the font rasterizer more robust when handling bad font data:

4514102: Installing certain fonts with bad data, will crash VM
4599491: Assertion failed: pos <= t->maxPos
4755210: JRE win32 install time support for identifying bad fonts
4755211: Java2D font scaler has memory alignment bug in TrueType hinting code
4755212: Java2D rasteriser has problems with some TT fonts
4772892: Bad TrueType font data can crash Java font scaler

The following bug affected many people running SunOneStudio or NetBeans:

4789067: Debugging test JUnit classes locks up IDE

The following noteworthy bugs were also fixed:

4517321: Java fails on 3-byte RGB screens used by some Linux implementations
4665237: REGRESSION: JInternalFrame outline dragging is very slow to respond
4707777: UNIX print jobs go only to the default printer

Copyright © 2003 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java2d-comments@sun.com 		Sun


Java 2D(tm) Technology

Java

Java 2DTM Technology

 Documentation Contents
The Java 2DTM API is a set of classes for advanced 2D graphics and imaging. It encompasses line art, text, and images in a single comprehensive model. The API provides extensive support for image compositing and alpha channel images, a set of classes to provide accurate color space definition and conversion, and a rich set of display-oriented imaging operators. These classes are provided as additions to the java.awt and java.awt.image packages.

Java 2D Enhancements
  • New Java 2D features - A list of new features added to the Java 2D API for JavaTM 2 SDK, v 1.4.0, and carried forward to subsequent releases in the Java 2 SDK v 1.4 family.
  • 1.4.2 Enhancements - A list of noteworthy 2D bug fixes made in 1.4.2.

Java 2D API Guide

Java 2D API Guide: Enhanced Graphics and Imaging for Java. Also available in PDF and PostScript format.

Read the README for instructions on how to run the code samples used in the Imaging chapter of the Java2D API Guide.

2D Graphics Tutorial

The 2D Graphics trail in The JavaTM Tutorial demonstrates how to display and print 2D graphics.

Java 2D API Specification

Java 2D API Specification - a list of the packages and classes included in the Java 2D API.

For More Information

See the Java Software website:
  • The Java 2D Home Page
  • The JFC Home Page
  • High Performance Graphics White Paper

Copyright © 2003 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java2d-comments@sun.com 		Sun Microsystems, Inc
Java Software


New Features in Java 2D(TM) Technology

Java

New Java 2DTM Features in the
JavaTM 2 SDK, v1.4

Documentation Contents

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. The VolatileImage.flush method can be used to release the memory used by an offscreen image.

For more information on using the VolatileImage API, see The VolatileImage API User Guide ( PDF)

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 © 1995-2001 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java2d-comments@sun.com 		Sun Microsystems, Inc
Java Software


Java 2D API Specification

Java

Java 2DTM API Specification

 Documentation Contents
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 respective 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.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.
  • com.sun.image.codec.jpeg
      Provides classes for encoding and decoding JPEG images.
  • java.awt.image.renderable
      Provides classes and interfaces for producing rendering-independent images.
The java.awt and java.awt.image packages also include classes that are part of the Java 2D API:
  • java.awt - Contains classes for generating user interfaces and painting graphics and images. The following 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.GradientPaint
    • java.awt.Graphics2D
    • java.awt.GraphicsConfiguration
    • java.awt.GraphicsDevice
    • java.awt.GraphicsEnvironment
    • java.awt.Paint
    • java.awt.PaintContext
    • java.awt.Rectangle
    • java.awt.Shape
    • java.awt.Stroke
    • java.awt.TexturePaint
    • java.awt.Toolkit
    • java.awt.Transparency

  • java.awt.image - Provides classes for creating and modifying images, as well as image producers, consumers and filters for configuring image processing. The following image classes are part of the Java 2D API.
    • java.awt.image.AffineTransformOp
    • java.awt.image.BandCombineOp
    • java.awt.image.BandedSampleModel
    • java.awt.image.BufferedImage
    • java.awt.image.BufferedImageFilter
    • java.awt.image.BufferedImageOp
    • java.awt.image.ByteLookupTable
    • java.awt.image.ColorConvertOp
    • java.awt.image.ColorModel
    • java.awt.image.ComponentColorModel
    • java.awt.image.ComponentSampleModel
    • java.awt.image.ConvolveOp
    • java.awt.image.DataBuffer
    • java.awt.image.DataBufferByte
    • java.awt.image.DataBufferInt
    • java.awt.image.DataBufferShort
    • java.awt.image.DirectColorModel
    • java.awt.image.IndexColorModel
    • java.awt.image.Kernel
    • java.awt.image.LookupOp
    • java.awt.image.LookupTable
    • java.awt.image.MultiPixelPackedSampleModel
    • java.awt.image.PackedColorModel
    • java.awt.image.Raster
    • java.awt.image.RasterformatException
    • java.awt.image.RasterOp
    • java.awt.image.RenderedImage
    • java.awt.image.RescaleOp
    • java.awt.image.SampleModel
    • java.awt.image.ShortLookupTable
    • java.awt.image.SinglePixelPackedSampleModel
    • java.awt.image.VolatileImage
    • java.awt.image.WritableRaster

Copyright © 1995-2001 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java2d-comments@sun.com 		Sun Microsystems, Inc
Java Software


All Classes (Other API Bundled with the Java 2 SDK)

 All Classes
ImageFormatException
JPEGCodec
JPEGDecodeParam
JPEGEncodeParam
JPEGHuffmanTable
JPEGImageDecoder
JPEGImageEncoder
JPEGQTable
TruncatedFileException


Constant Field Values (Other API Bundled with the Java 2 SDK)

PREV NEXT FRAMES NO FRAMES

Constant Field Values

Contents
  • com.sun.*
com.sun.*

com.sun.image.codec.jpeg.JPEGDecodeParam
public static final int | APP0_MARKER | 224
public static final int | APP1_MARKER | 225
public static final int | APP2_MARKER | 226
public static final int | APP3_MARKER | 227
public static final int | APP4_MARKER | 228
public static final int | APP5_MARKER | 229
public static final int | APP6_MARKER | 230
public static final int | APP7_MARKER | 231
public static final int | APP8_MARKER | 232
public static final int | APP9_MARKER | 233
public static final int | APPA_MARKER | 234
public static final int | APPB_MARKER | 235
public static final int | APPC_MARKER | 236
public static final int | APPD_MARKER | 237
public static final int | APPE_MARKER | 238
public static final int | APPF_MARKER | 239
public static final int | COLOR_ID_CMYK | 4
public static final int | COLOR_ID_GRAY | 1
public static final int | COLOR_ID_PYCC | 5
public static final int | COLOR_ID_PYCCA | 10
public static final int | COLOR_ID_RGB | 2
public static final int | COLOR_ID_RGBA | 6
public static final int | COLOR_ID_RGBA_INVERTED | 8
public static final int | COLOR_ID_UNKNOWN | 0
public static final int | COLOR_ID_YCbCr | 3
public static final int | COLOR_ID_YCbCrA | 7
public static final int | COLOR_ID_YCbCrA_INVERTED | 9
public static final int | COLOR_ID_YCCK | 11
public static final int | COMMENT_MARKER | 254
public static final int | DENSITY_UNIT_ASPECT_RATIO | 0
public static final int | DENSITY_UNIT_DOTS_CM | 2
public static final int | DENSITY_UNIT_DOTS_INCH | 1
public static final int | NUM_COLOR_ID | 12
public static final int | NUM_DENSITY_UNIT | 3
public static final int | NUM_TABLES | 4

Overview Package Class Use Tree Deprecated Index Help
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Deprecated List (Other API Bundled with the Java 2 SDK)

PREV NEXT FRAMES NO FRAMES

Deprecated API

Overview Package Class Use Tree Deprecated Index Help
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


API Help (Other API Bundled with the Java 2 SDK)

PREV NEXT FRAMES NO FRAMES

How This API Document Is Organized

This API (Application Programming Interface) document has pages corresponding to the items in the navigation bar, described as follows.

Overview

The Overview page is the front page of this API document and provides a list of all packages with a summary for each. This page can also contain an overall description of the set of packages.

Package

Each package has a page that contains a list of its classes and interfaces, with a summary for each. This page can contain four categories:

  • Interfaces (italic)
  • Classes
  • Exceptions
  • Errors

Class/Interface

Each class, interface, nested class and nested interface has its own separate page. Each of these pages has three sections consisting of a class/interface description, summary tables, and detailed member descriptions:

  • Class inheritance diagram
  • Direct Subclasses
  • All Known Subinterfaces
  • All Known Implementing Classes
  • Class/interface declaration
  • Class/interface description

  • Nested Class Summary
  • Field Summary
  • Constructor Summary
  • Method Summary

  • Field Detail
  • Constructor Detail
  • Method Detail
Each summary entry contains the first sentence from the detailed description for that item. The summary entries are alphabetical, while the detailed descriptions are in the order they appear in the source code. This preserves the logical groupings established by the programmer.

Use

Each documented package, class and interface has its own Use page. This page describes what packages, classes, methods, constructors and fields use any part of the given class 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.

Tree (Class Hierarchy)

There is a Class Hierarchy page for all packages, plus a hierarchy for each package. Each hierarchy page contains a list of classes and a list of interfaces. The classes are organized by inheritance structure starting with java.lang.Object. The interfaces do not inherit from java.lang.Object.
  • When viewing the Overview page, clicking on "Tree" displays the hierarchy for all packages.
  • When viewing a particular package, class or interface page, clicking "Tree" displays the hierarchy for only that package.

Deprecated API

The Deprecated API page lists all of the API that have been deprecated. A deprecated API is not recommended for use, generally due to improvements, and a replacement API is usually given. Deprecated APIs may be removed in future implementations.

Index

The Index contains an alphabetic list of all classes, interfaces, constructors, methods, and fields.

Prev/Next

These links take you to the next or previous class, interface, package, or related page.

Frames/No Frames

These links show and hide the HTML frames. All pages are available with or without frames.

Serialized Form

Each serializable or externalizable 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 description.

This help file applies to API documentation generated using the standard doclet.

Overview Package Class Use Tree Deprecated Index Help
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Other API Bundled with the Java 2 SDK

Frame Alert

This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client.
Link toNon-frame version.


Overview (Other API Bundled with the Java 2 SDK)

PREV NEXT FRAMES NO FRAMES

Other API Bundled with the Java 2 SDK

This document contains API that are not part of the Java 2 Platform.

See:
Description

Packages
com.sun.image.codec.jpeg Provides classes for encoding and decoding JPEG images.

This document contains API that are not part of the Java 2 Platform. While they may be a part of Sun's Java 2 SDK and Java 2 Runtime Environment distributions, developers cannot depend on their availability in non-Sun implementations.

Overview Package Class Use Tree Deprecated Index Help
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Class Hierarchy (Other API Bundled with the Java 2 SDK)

PREV NEXT FRAMES NO FRAMES

Hierarchy For All Packages

Package Hierarchies:
com.sun.image.codec.jpeg

Class Hierarchy

  • class java.lang.Object
    • class com.sun.image.codec.jpeg.JPEGCodec
    • class com.sun.image.codec.jpeg.JPEGHuffmanTable
    • class com.sun.image.codec.jpeg.JPEGQTable
    • class java.lang.Throwable (implements java.io.Serializable)
      • class java.lang.Exception
        • class java.lang.RuntimeException
          • class com.sun.image.codec.jpeg.ImageFormatException
          • class com.sun.image.codec.jpeg.TruncatedFileException

Interface Hierarchy

  • interface java.lang.Cloneable
    • interface com.sun.image.codec.jpeg.JPEGDecodeParam
      • interface com.sun.image.codec.jpeg.JPEGEncodeParam (also extends java.lang.Cloneable)
    • interface com.sun.image.codec.jpeg.JPEGEncodeParam (also extends com.sun.image.codec.jpeg.JPEGDecodeParam)
  • interface com.sun.image.codec.jpeg.JPEGImageDecoder
  • interface com.sun.image.codec.jpeg.JPEGImageEncoder
Overview Package Class Use Tree Deprecated Index Help
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Serialized Form (Other API Bundled with the Java 2 SDK)

PREV NEXT FRAMES NO FRAMES

Serialized Form

Package com.sun.image.codec.jpeg

Class com.sun.image.codec.jpeg.ImageFormatException extends RuntimeException implements Serializable

Class com.sun.image.codec.jpeg.TruncatedFileException extends RuntimeException implements Serializable

Serialized Fields

ras

Raster ras

bi

BufferedImage bi

Overview Package Class Use Tree Deprecated Index Help
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


ImageFormatException (Other API Bundled with the Java 2 SDK)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

com.sun.image.codec.jpeg
Class ImageFormatException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by com.sun.image.codec.jpeg.ImageFormatException
All Implemented Interfaces:
Serializable
public class ImageFormatException
extends RuntimeException

Signals that an Image Format exception of some sort has occurred.

Note that the classes in the com.sun.image.codec.jpeg package are not part of the core Java APIs. They are a part of Sun's JDK and JRE distributions. Although other licensees may choose to distribute these classes, developers cannot depend on their availability in non-Sun implementations. We expect that equivalent functionality will eventually be available in a core API or standard extension.

Since:
JDK1.2
See Also:
JPEGImageEncoder, JPEGImageDecoder, Serialized Form

Constructor Summary
ImageFormatException()
Constructs an ImageFormatException with no detail message.
ImageFormatException(String s)
Constructs an ImageFormatException with the specified detailed message.
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

ImageFormatException

public ImageFormatException()
Constructs an ImageFormatException with no detail message.

ImageFormatException

public ImageFormatException(String s)
Constructs an ImageFormatException with the specified detailed message.

Parameters:
s - the message.
Overview Package Class Use Tree Deprecated Index Help
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


JPEGCodec (Other API Bundled with the Java 2 SDK)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

com.sun.image.codec.jpeg
Class JPEGCodec

java.lang.Object
    extended by com.sun.image.codec.jpeg.JPEGCodec
public class JPEGCodec
extends Object

This class is a factory for implementations of the JPEG Image Decoder/Encoder.

Note that the classes in the com.sun.image.codec.jpeg package are not part of the core Java APIs. They are a part of Sun's JDK and JRE distributions. Although other licensees may choose to distribute these classes, developers cannot depend on their availability in non-Sun implementations. We expect that equivalent functionality will eventually be available in a core API or standard extension.

See Also:
JPEGImageDecoder, JPEGImageEncoder

Method Summary
static JPEGImageDecoder | createJPEGDecoder(InputStream src) This creates an instance of a JPEGImageDecoder that can be used to decode JPEG Data streams.
static JPEGImageDecoder | createJPEGDecoder(InputStream src, JPEGDecodeParam jdp) This creates an instance of a JPEGImageDecoder that can be used to decode JPEG Data streams.
static JPEGImageEncoder | createJPEGEncoder(OutputStream dest) This creates an instance of a JPEGImageEncoder that can be used to encode image data as JPEG Data streams.
static JPEGImageEncoder | createJPEGEncoder(OutputStream dest, JPEGEncodeParam jep) This creates an instance of a JPEGImageEncoder that can be used to encode image data as JPEG Data streams.
static JPEGEncodeParam | getDefaultJPEGEncodeParam(BufferedImage bi) This is a factory method for creating JPEGEncodeParam objects.
static JPEGEncodeParam | getDefaultJPEGEncodeParam(int numBands, int colorID) This is a factory method for creating JPEGEncodeParam objects.
static JPEGEncodeParam | getDefaultJPEGEncodeParam(JPEGDecodeParam jdp) This is a factory method for creating a JPEGEncodeParam from a JPEGDecodeParam.
static JPEGEncodeParam | getDefaultJPEGEncodeParam(Raster ras, int colorID) This is a factory method for creating JPEGEncodeParam objects.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Method Detail

createJPEGDecoder

public static JPEGImageDecoder createJPEGDecoder(InputStream src)
This creates an instance of a JPEGImageDecoder that can be used to decode JPEG Data streams.

createJPEGDecoder

public static JPEGImageDecoder createJPEGDecoder(InputStream src,
                                                 JPEGDecodeParam jdp)
This creates an instance of a JPEGImageDecoder that can be used to decode JPEG Data streams.

createJPEGEncoder

public static JPEGImageEncoder createJPEGEncoder(OutputStream dest)
This creates an instance of a JPEGImageEncoder that can be used to encode image data as JPEG Data streams.

createJPEGEncoder

public static JPEGImageEncoder createJPEGEncoder(OutputStream dest,
                                                 JPEGEncodeParam jep)
This creates an instance of a JPEGImageEncoder that can be used to encode image data as JPEG Data streams.

getDefaultJPEGEncodeParam

public static JPEGEncodeParam getDefaultJPEGEncodeParam(BufferedImage bi)
This is a factory method for creating JPEGEncodeParam objects. The returned object should do a credible job of encoding the given BufferedImage.

Parameters:
bi - A BufferedImage that is similar to the BufferedImage(s) that will encoded using the returned JPEGEncodeParam object.

getDefaultJPEGEncodeParam

public static JPEGEncodeParam getDefaultJPEGEncodeParam(Raster ras,
                                                        int colorID)
This is a factory method for creating JPEGEncodeParam objects. It is the users responsiblity to match the colorID with the data contained in the Raster. Failure to do so may lead to either poor compression or poor image quality. If you don't understand much about JPEG it is strongly recommended that you stick to the BufferedImage interface.

Parameters:
ras - Raster that is similar to those to be encoded later.
colorID - the COLOR_ID for the encoded data. This should match the data in the raster.

getDefaultJPEGEncodeParam

public static JPEGEncodeParam getDefaultJPEGEncodeParam(int numBands,
                                                        int colorID)
                                                 throws ImageFormatException
This is a factory method for creating JPEGEncodeParam objects. It is the users responsiblity to match the colorID with the given number of bands, which should match the data being encoded. Failure to do so may lead to poor compression and/or poor image quality. If you don't understand much about JPEG it is strongly recommended that you stick to the BufferedImage interface. This can also be used as a factory for a JPEGDecodeParam object. However this usage is extremely rare, as one needs to be decoding abbreviated JPEG streams where the JPEG tables are coming from some source other than a JPEG tables only stream.

Parameters:
numBands - the number of bands that will be encoded (max of four).
colorID - the COLOR_ID for the encoded data. This is used to set reasonable defaults in the parameter object. This must match the number of bands given.
Throws:
ImageFormatException

getDefaultJPEGEncodeParam

public static JPEGEncodeParam getDefaultJPEGEncodeParam(JPEGDecodeParam jdp)
                                                 throws ImageFormatException
This is a factory method for creating a JPEGEncodeParam from a JPEGDecodeParam. This will return a new JPEGEncodeParam object that is initialized from the JPEGDecodeParam object. All major pieces of information will be initialized from the DecodeParam (Markers, Tables, mappings).

Parameters:
jdp - The JPEGDecodeParam object to copy.
Throws:
ImageFormatException
Overview Package Class Use Tree Deprecated Index Help
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


JPEGDecodeParam (Other API Bundled with the Java 2 SDK)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

com.sun.image.codec.jpeg
Interface JPEGDecodeParam

All Superinterfaces:
Cloneable
All Known Subinterfaces:
JPEGEncodeParam
public interface JPEGDecodeParam
extends Cloneable

JPEGDecodeParam encapsulates tables and options necessary to control decoding JPEG datastreams. Parameters are either set explicitly by the application for encoding, or read from the JPEG header for decoding. In the case of decoding abbreviated data streams the application may need to set some/all of the values it's self.

When working with BufferedImages (@see JPEGImageDecoder.decodeBufferedImage), the codec will attempt to generate an appropriate ColorModel for the JPEG COLOR_ID. This is not always possible (example mappings are listed below) . In cases where unsupported conversions are required, or unknown encoded COLOR_ID's are in use, the user must request the data as a Raster and perform the transformations themselves. When decoding into a raster (@see JPEGImageDecoder.decodeRaster) no ColorSpace adjustments are made. Note: The color ids described herein are simply enumerated values that influence data processing by the JPEG codec. JPEG compression is by definition color blind. These values are used as hints when decompressing JPEG data. Of particular interest is the default conversion from YCbCr to sRGB when decoding buffered Images.

Note: because JPEG is mostly color-blind color fidelity can not be garunteed. This will hopefully be rectified in the near future by the wide spread inclusion of ICC-profiles in the JPEG data stream (as a special marker). The following is an example of the conversions that take place. This is only a guide to the types of conversions that are allowed. This list is likely to change in the future so it is strongly recommended that you check for thrown ImageFormatExceptions and check the actual ColorModel associated with the BufferedImage returned rather than make assumtions.

    DECODING:

    JPEG (Encoded) Color ID         BufferedImage ColorSpace
    =======================         ========================
    COLOR_ID_UNKNOWN                ** Invalid **
    COLOR_ID_GRAY                   CS_GRAY
    COLOR_ID_RGB                    CS_sRGB
    COLOR_ID_YCbCr                  CS_sRGB
    COLOR_ID_CMYK                   ** Invalid **
    COLOR_ID_PYCC                   CS_PYCC
    COLOR_ID_RGBA                   CS_sRGB (w/ alpha)
    COLOR_ID_YCbCrA                 CS_sRGB (w/ alpha)
    COLOR_ID_RGBA_INVERTED          ** Invalid **
    COLOR_ID_YCbCrA_INVERTED        ** Invalid **
    COLOR_ID_PYCCA                  CS_PYCC (w/ alpha)
    COLOR_ID_YCCK                   ** Invalid **
If the user needs better control over conversion, the user must request the data as a Raster and handle the conversion of the image data themselves.

When decoding JFIF files the encoded COLOR_ID will always be one of: COLOR_ID_UNKNOWN, COLOR_ID_GRAY, COLOR_ID_RGB, COLOR_ID_YCbCr, COLOR_ID_CMYK, or COLOR_ID_YCCK

Note that the classes in the com.sun.image.codec.jpeg package are not part of the core Java APIs. They are a part of Sun's JDK and JRE distributions. Although other licensees may choose to distribute these classes, developers cannot depend on their availability in non-Sun implementations. We expect that equivalent functionality will eventually be available in a core API or standard extension.

Field Summary
static int | APP0_MARKER APP0 marker - JFIF info
static int | APP1_MARKER APP1 marker
static int | APP2_MARKER APP2 marker
static int | APP3_MARKER APP3 marker
static int | APP4_MARKER APP4 marker
static int | APP5_MARKER APP5 marker
static int | APP6_MARKER APP6 marker
static int | APP7_MARKER APP7 marker
static int | APP8_MARKER APP8 marker
static int | APP9_MARKER APP9 marker
static int | APPA_MARKER APPA marker
static int | APPB_MARKER APPB marker
static int | APPC_MARKER APPC marker
static int | APPD_MARKER APPD marker
static int | APPE_MARKER APPE marker - Adobe info
static int | APPF_MARKER APPF marker
static int | COLOR_ID_CMYK CMYK
static int | COLOR_ID_GRAY Monochrome
static int | COLOR_ID_PYCC PhotoYCC
static int | COLOR_ID_PYCCA PhotoYCC-Alpha
static int | COLOR_ID_RGB Red, Green, and Blue
static int | COLOR_ID_RGBA RGB-Alpha
static int | COLOR_ID_RGBA_INVERTED RGB-Alpha with R, G, and B inverted.
static int | COLOR_ID_UNKNOWN Unknown or Undefined Color ID
static int | COLOR_ID_YCbCr YCbCr
static int | COLOR_ID_YCbCrA YCbCr-Alpha
static int | COLOR_ID_YCbCrA_INVERTED YCbCr-Alpha with Y, Cb, and Cr inverted.
static int | COLOR_ID_YCCK YCbCrK
static int | COMMENT_MARKER Adobe marker indicates presence/need for Adobe marker.
static int | DENSITY_UNIT_ASPECT_RATIO The X and Y units simply indicate the aspect ratio of the pixels.
static int | DENSITY_UNIT_DOTS_CM Pixel density is in pixels per centemeter.
static int | DENSITY_UNIT_DOTS_INCH Pixel density is in pixels per inch.
static int | NUM_COLOR_ID Number of color ids defined.
static int | NUM_DENSITY_UNIT The max known value for DENSITY_UNIT
static int | NUM_TABLES Number of allowed Huffman and Quantization Tables
Method Summary
Object | clone()
int | getACHuffmanComponentMapping(int component) Get the number of the AC Huffman table that will be used for a particular component.
JPEGHuffmanTable | getACHuffmanTable(int tableNum) Returns the AC Huffman coding table requested or null if not defined
JPEGHuffmanTable | getACHuffmanTableForComponent(int component) Returns the AC Huffman coding table for the requested component.
int | getDCHuffmanComponentMapping(int component) Get the number of the DC Huffman table that will be used for a particular component.
JPEGHuffmanTable | getDCHuffmanTable(int tableNum) Returns the DC Huffman coding table requested or null if not defined
JPEGHuffmanTable | getDCHuffmanTableForComponent(int component) Returns the DC Huffman coding table for the requested component.
int | getDensityUnit() Get the code for pixel size units This value is copied from the APP0 marker.
int | getEncodedColorID() Returns the JPEG Encoded color id.
int | getHeight() Get the image height
int | getHorizontalSubsampling(int component) Return the Horizontal subsampling factor for requested Component.
boolean | getMarker(int marker) Returns true if at least one instance of the marker is present in the Parameter object.
byte[][] | getMarkerData(int marker) Returns a 'byte[][]' associated with the requested marker in the parameter object.
int | getNumComponents() Returns the number of components for the current encoding COLOR_ID.
JPEGQTable | getQTable(int tableNum) Returns the coefficient quantization tables or NULL if not defined.
int | getQTableComponentMapping(int component) Get the number of the quantization table that will be used for a particular component.
JPEGQTable | getQTableForComponent(int component) Returns the Quantization table for the requested component.
int | getRestartInterval() Get the MCUs per restart marker.
int | getVerticalSubsampling(int component) Return the Vertical subsampling factor for requested Component.
int | getWidth() Get the image width
int | getXDensity() Get the horizontal pixel density This value is copied from the APP0 marker.
int | getYDensity() Get the vertical pixel density This value is copied into the APP0 marker.
boolean | isImageInfoValid() Returns true if the image information in the ParamBlock is currently valid.
boolean | isTableInfoValid() Returns true if the tables in the ParamBlock are currently valid.

Field Detail

COLOR_ID_UNKNOWN

public static final int COLOR_ID_UNKNOWN
Unknown or Undefined Color ID

See Also:
Constant Field Values

COLOR_ID_GRAY

public static final int COLOR_ID_GRAY
Monochrome

See Also:
Constant Field Values

COLOR_ID_RGB

public static final int COLOR_ID_RGB
Red, Green, and Blue

See Also:
Constant Field Values

COLOR_ID_YCbCr

public static final int COLOR_ID_YCbCr
YCbCr

See Also:
Constant Field Values

COLOR_ID_CMYK

public static final int COLOR_ID_CMYK
CMYK

See Also:
Constant Field Values

COLOR_ID_PYCC

public static final int COLOR_ID_PYCC
PhotoYCC

See Also:
Constant Field Values

COLOR_ID_RGBA

public static final int COLOR_ID_RGBA
RGB-Alpha

See Also:
Constant Field Values

COLOR_ID_YCbCrA

public static final int COLOR_ID_YCbCrA
YCbCr-Alpha

See Also:
Constant Field Values

COLOR_ID_RGBA_INVERTED

public static final int COLOR_ID_RGBA_INVERTED
RGB-Alpha with R, G, and B inverted.

See Also:
Constant Field Values

COLOR_ID_YCbCrA_INVERTED

public static final int COLOR_ID_YCbCrA_INVERTED
YCbCr-Alpha with Y, Cb, and Cr inverted.

See Also:
Constant Field Values

COLOR_ID_PYCCA

public static final int COLOR_ID_PYCCA
PhotoYCC-Alpha

See Also:
Constant Field Values

COLOR_ID_YCCK

public static final int COLOR_ID_YCCK
YCbCrK

See Also:
Constant Field Values

NUM_COLOR_ID

public static final int NUM_COLOR_ID
Number of color ids defined.

See Also:
Constant Field Values

NUM_TABLES

public static final int NUM_TABLES
Number of allowed Huffman and Quantization Tables

See Also:
Constant Field Values

DENSITY_UNIT_ASPECT_RATIO

public static final int DENSITY_UNIT_ASPECT_RATIO
The X and Y units simply indicate the aspect ratio of the pixels.

See Also:
Constant Field Values

DENSITY_UNIT_DOTS_INCH

public static final int DENSITY_UNIT_DOTS_INCH
Pixel density is in pixels per inch.

See Also:
Constant Field Values

DENSITY_UNIT_DOTS_CM

public static final int DENSITY_UNIT_DOTS_CM
Pixel density is in pixels per centemeter.

See Also:
Constant Field Values

NUM_DENSITY_UNIT

public static final int NUM_DENSITY_UNIT
The max known value for DENSITY_UNIT

See Also:
Constant Field Values

APP0_MARKER

public static final int APP0_MARKER
APP0 marker - JFIF info

See Also:
Constant Field Values

APP1_MARKER

public static final int APP1_MARKER
APP1 marker

See Also:
Constant Field Values

APP2_MARKER

public static final int APP2_MARKER
APP2 marker

See Also:
Constant Field Values

APP3_MARKER

public static final int APP3_MARKER
APP3 marker

See Also:
Constant Field Values

APP4_MARKER

public static final int APP4_MARKER
APP4 marker

See Also:
Constant Field Values

APP5_MARKER

public static final int APP5_MARKER
APP5 marker

See Also:
Constant Field Values

APP6_MARKER

public static final int APP6_MARKER
APP6 marker

See Also:
Constant Field Values

APP7_MARKER

public static final int APP7_MARKER
APP7 marker

See Also:
Constant Field Values

APP8_MARKER

public static final int APP8_MARKER
APP8 marker

See Also:
Constant Field Values

APP9_MARKER

public static final int APP9_MARKER
APP9 marker

See Also:
Constant Field Values

APPA_MARKER

public static final int APPA_MARKER
APPA marker

See Also:
Constant Field Values

APPB_MARKER

public static final int APPB_MARKER
APPB marker

See Also:
Constant Field Values

APPC_MARKER

public static final int APPC_MARKER
APPC marker

See Also:
Constant Field Values

APPD_MARKER

public static final int APPD_MARKER
APPD marker

See Also:
Constant Field Values

APPE_MARKER

public static final int APPE_MARKER
APPE marker - Adobe info

See Also:
Constant Field Values

APPF_MARKER

public static final int APPF_MARKER
APPF marker

See Also:
Constant Field Values

COMMENT_MARKER

public static final int COMMENT_MARKER
Adobe marker indicates presence/need for Adobe marker.

See Also:
Constant Field Values
Method Detail

clone

public Object clone()

getWidth

public int getWidth()
Get the image width

Returns:
int the width of the image data in pixels.

getHeight

public int getHeight()
Get the image height

Returns:
The height of the image data in pixels.

getHorizontalSubsampling

public int getHorizontalSubsampling(int component)
Return the Horizontal subsampling factor for requested Component. The Subsample factor is the number of input pixels that contribute to each output pixel. This is distinct from the way the JPEG to each output pixel. This is distinct from the way the JPEG standard defines this quantity, because fractional subsampling factors are not allowed, and it was felt

Parameters:
component - The component of the encoded image to return the subsampling factor for.
Returns:
The subsample factor.

getVerticalSubsampling

public int getVerticalSubsampling(int component)
Return the Vertical subsampling factor for requested Component. The Subsample factor is the number of input pixels that contribute to each output pixel. This is distinct from the way the JPEG to each output pixel. This is distinct from the way the JPEG standard defines this quantity, because fractional subsampling factors are not allowed, and it was felt

Parameters:
component - The component of the encoded image to return the subsampling factor for.
Returns:
The subsample factor.

getQTable

public JPEGQTable getQTable(int tableNum)
Returns the coefficient quantization tables or NULL if not defined. tableNum must range in value from 0 - 3.

Parameters:
tableNum - the index of the table to be returned.
Returns:
Quantization table stored at index tableNum.

getQTableForComponent

public JPEGQTable getQTableForComponent(int component)
Returns the Quantization table for the requested component.

Parameters:
component - the image component of interest.
Returns:
Quantization table associated with component

getDCHuffmanTable

public JPEGHuffmanTable getDCHuffmanTable(int tableNum)
Returns the DC Huffman coding table requested or null if not defined

Parameters:
tableNum - the index of the table to be returned.
Returns:
Huffman table stored at index tableNum.

getDCHuffmanTableForComponent

public JPEGHuffmanTable getDCHuffmanTableForComponent(int component)
Returns the DC Huffman coding table for the requested component.

Parameters:
component - the image component of interest.
Returns:
Huffman table associated with component

getACHuffmanTable

public JPEGHuffmanTable getACHuffmanTable(int tableNum)
Returns the AC Huffman coding table requested or null if not defined

Parameters:
tableNum - the index of the table to be returned.
Returns:
Huffman table stored at index tableNum.

getACHuffmanTableForComponent

public JPEGHuffmanTable getACHuffmanTableForComponent(int component)
Returns the AC Huffman coding table for the requested component.

Parameters:
component - the image component of interest.
Returns:
Huffman table associated with component

getDCHuffmanComponentMapping

public int getDCHuffmanComponentMapping(int component)
Get the number of the DC Huffman table that will be used for a particular component.

Parameters:
component - The Component of interest.
Returns:
The table number of the DC Huffman table for component.

getACHuffmanComponentMapping

public int getACHuffmanComponentMapping(int component)
Get the number of the AC Huffman table that will be used for a particular component.

Parameters:
component - The Component of interest.
Returns:
The table number of the AC Huffman table for component.

getQTableComponentMapping

public int getQTableComponentMapping(int component)
Get the number of the quantization table that will be used for a particular component.

Parameters:
component - The Component of interest.
Returns:
The table number of the Quantization table for component.

isImageInfoValid

public boolean isImageInfoValid()
Returns true if the image information in the ParamBlock is currently valid. This indicates if image data was read from the stream for decoding and weather image data should be written when encoding.

isTableInfoValid

public boolean isTableInfoValid()
Returns true if the tables in the ParamBlock are currently valid. This indicates that tables were read from the stream for decoding. When encoding this indicates wether tables should be written to the stream.

getMarker

public boolean getMarker(int marker)
Returns true if at least one instance of the marker is present in the Parameter object. For encoding returns true if there is at least one instance of the marker to be written.

Parameters:
marker - The marker of interest.

getMarkerData

public byte[][] getMarkerData(int marker)
Returns a 'byte[][]' associated with the requested marker in the parameter object. Each entry in the 'byte[][]' is the data associated with one instance of the marker (each marker can theoretically appear any number of times in a stream).

Parameters:
marker - The marker of interest.
Returns:
The 'byte[][]' for this marker or null if none available.

getEncodedColorID

public int getEncodedColorID()
Returns the JPEG Encoded color id. This is generally speaking only used if you are decoding into Rasters. Note that when decoding into a Raster no color conversion is performed.

Returns:
The value of the JPEG encoded data's color id.

getNumComponents

public int getNumComponents()
Returns the number of components for the current encoding COLOR_ID.

Returns:
the number of Components

getRestartInterval

public int getRestartInterval()
Get the MCUs per restart marker.

Returns:
The number of MCUs between restart markers.

getDensityUnit

public int getDensityUnit()
Get the code for pixel size units This value is copied from the APP0 marker. It isn't used by the JPEG codec. If the APP0 marker wasn't present then you can not rely on this value.

Returns:
Value indicating the density unit one of the DENSITY_UNIT_* constants.

getXDensity

public int getXDensity()
Get the horizontal pixel density This value is copied from the APP0 marker. It isn't used by the JPEG code. If the APP0 marker wasn't present then you can not rely on this value.

Returns:
The horizontal pixel density, in units described by
See Also:
getDensityUnit()

getYDensity

public int getYDensity()
Get the vertical pixel density This value is copied into the APP0 marker. It isn't used by the JPEG code. If the APP0 marker wasn't present then you can not rely on this value.

Returns:
The verticle pixel density, in units described by
See Also:
getDensityUnit()
Overview Package Class Use Tree Deprecated Index Help
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


JPEGEncodeParam (Other API Bundled with the Java 2 SDK)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.image.codec.jpeg
Interface JPEGEncodeParam

All Superinterfaces:
Cloneable, JPEGDecodeParam
public interface JPEGEncodeParam
extends Cloneable, JPEGDecodeParam

JPEGEncodeParam encapsulates tables and options necessary to control encoding of JPEG data streams. Parameters are either set explicitly by the application for encoding, or read from another JPEG header.

When working with BufferedImages, the codec will attempt to match the encoded JPEG COLOR_ID with the ColorModel in the BufferedImage. This is not always possible (the default mappings are listed below). In cases where unsupported conversions are required (or odd image colorspaces are in use) the user must either convert the image data to a known ColorSpace or encode the data from a raster. When encoding rasters no colorspace adjustments are made, so the user must do any conversions required to get to the encoded COLOR_ID. The COLOR_ID for the encoded images is used to control the JPEG codec's inital values for Huffman and Quantization Tables as well as subsampling factors. It is also used to determine what color conversion should be performed to obtain the best encoding.

Note: The color ids described herein are simply enumerated values that influence data processing by the JPEG codec. JPEG compression is, by definition, color blind. These values are used as hints when compressing JPEG data. Through these values the JPEG codec can perform some default rotation of data into spaces that will aid in getting better compression ratios.

Example behaviour is described below. Since these mappings are likely to change in the future it is strongly recommended that you make use of the @see JPEGImageEncoder.getDefaultParamBlock calls and check the encodedColorID for your particular BufferedImage. In extreme cases is may be necessary for the user to convert the image to the desired colorspace, and encode it from a Raster. In this case the API programmer must specify the colorID of the data in the Raster and no color conversion will take place.

 ENCODING:

 BufferedImage Type/Instance        JPEG (Encoded) Color ID
 ========================       =======================
 TYPE_GRAY                      COLOR_ID_GRAYSCALE
 TYPE_RGB                       COLOR_ID_YCbCr
 TYPE_YCbCr                     COLOR_ID_YCbCr
 TYPE_YCbCr/CS_PYCC             COLOR_ID_PYCC
 TYPE_CMYK                      COLOR_ID_CMYK
 TYPE_RGB   (w/ alpha)          COLOR_ID_YCbCrA
 TYPE_YCbCr (w/ alpha)          COLOR_ID_YCbCrA
 TYPE_YCbCr/CS_PYCC (w/ alpha)  COLOR_ID_PYCCA
 Any Other **                COLOR_ID_UNKNOWN
When the user wants more control than the BufferedImage conversions provide, the user must encode the data from a Raster. In this case the data undergoes no color conversion at all. It is the user's responsiblity to perform the desired conversions.

If you intend to write a JFIF image (by including the APP0_MARKER) the encoded COLOR_ID must be one of: COLOR_ID_UNKNOWN, COLOR_ID_GRAYSCALE, COLOR_ID_YCbCr, or COLOR_ID_CMYK. In all other instances an ImageformatException will be thrown.

IMPORTANT: an Alpha RGB BufferedImage will not map to a valid JFIF stream, you must strip off the alpha prior to encoding if you want a JFIF file. If the APP0 marker is set and you do not strip off the Alpha, an ImageFormatException will be thrown.

Note that the classes in the com.sun.image.codec.jpeg package are not part of the core Java APIs. They are a part of Sun's JDK and JRE distributions. Although other licensees may choose to distribute these classes, developers cannot depend on their availability in non-Sun implementations. We expect that equivalent functionality will eventually be available in a core API or standard extension.

Field Summary
Fields inherited from interface com.sun.image.codec.jpeg.JPEGDecodeParam
APP0_MARKER, APP1_MARKER, APP2_MARKER, APP3_MARKER, APP4_MARKER, APP5_MARKER, APP6_MARKER, APP7_MARKER, APP8_MARKER, APP9_MARKER, APPA_MARKER, APPB_MARKER, APPC_MARKER, APPD_MARKER, APPE_MARKER, APPF_MARKER, COLOR_ID_CMYK, COLOR_ID_GRAY, COLOR_ID_PYCC, COLOR_ID_PYCCA, COLOR_ID_RGB, COLOR_ID_RGBA, COLOR_ID_RGBA_INVERTED, COLOR_ID_UNKNOWN, COLOR_ID_YCbCr, COLOR_ID_YCbCrA, COLOR_ID_YCbCrA_INVERTED, COLOR_ID_YCCK, COMMENT_MARKER, DENSITY_UNIT_ASPECT_RATIO, DENSITY_UNIT_DOTS_CM, DENSITY_UNIT_DOTS_INCH, NUM_COLOR_ID, NUM_DENSITY_UNIT, NUM_TABLES
Method Summary
void | addMarkerData(int marker, byte[] data) Appends 'data' to the array of byte[] associated with marker.
Object | clone()
void | setACHuffmanComponentMapping(int component, int table) Sets the mapping between a component and it's AC Huffman Table.
void | setACHuffmanTable(int tableNum, JPEGHuffmanTable huffTable) Sets the AC Huffman coding table at index to the table provided.
void | setDCHuffmanComponentMapping(int component, int table) Sets the mapping between a component and it's DC Huffman Table.
void | setDCHuffmanTable(int tableNum, JPEGHuffmanTable huffTable) Sets the DC Huffman coding table at index to the table provided.
void | setDensityUnit(int unit) Set the pixel size units This value is copied into the APP0 marker (if that marker is written).
void | setHorizontalSubsampling(int component, int subsample) Set the horizontal subsample factor for the given component.
void | setImageInfoValid(boolean flag) Set the flag indicating the validity of the table information in the ParamBlock.
void | setMarkerData(int marker, byte[][] data) Sets the marker data to be written to the output data stream.
void | setQTable(int tableNum, JPEGQTable qTable) Sets the coefficient quantization tables at index passed.
void | setQTableComponentMapping(int component, int table) Sets the mapping between a component and it's Quantization Table.
void | setQuality(float quality, boolean forceBaseline) This creates new Quantization tables that replace the currently installed Quantization tables.
void | setRestartInterval(int restartInterval) Set the MCUs per restart, or 0 for no restart markers.
void | setTableInfoValid(boolean flag) Set the flag indicating the validity of the image information in the ParamBlock.
void | setVerticalSubsampling(int component, int subsample) Set the vertical subsample factor for the given component.
void | setXDensity(int density) Set the horizontal pixel density This value is written into the APP0 marker.
void | setYDensity(int density) Set the vertical pixel density.
Methods inherited from interface com.sun.image.codec.jpeg.JPEGDecodeParam
getACHuffmanComponentMapping, getACHuffmanTable, getACHuffmanTableForComponent, getDCHuffmanComponentMapping, getDCHuffmanTable, getDCHuffmanTableForComponent, getDensityUnit, getEncodedColorID, getHeight, getHorizontalSubsampling, getMarker, getMarkerData, getNumComponents, getQTable, getQTableComponentMapping, getQTableForComponent, getRestartInterval, getVerticalSubsampling, getWidth, getXDensity, getYDensity, isImageInfoValid, isTableInfoValid

Method Detail

clone

public Object clone()
Specified by:
clone in interface JPEGDecodeParam

setHorizontalSubsampling

public void setHorizontalSubsampling(int component,
                                     int subsample)
Set the horizontal subsample factor for the given component. Note that the subsample factor is the number of input pixels that contribute to each output pixel (ussually 2 for YCC).

Parameters:
component - The component being specified.
subsample - The subsampling factor being specified.

setVerticalSubsampling

public void setVerticalSubsampling(int component,
                                   int subsample)
Set the vertical subsample factor for the given component. Note that the subsample factor is the number of input pixels that contribute to each output pixel (ussually 2 for YCC).

Parameters:
component - The component being specified.
subsample - The subsampling factor being specified.

setQTable

public void setQTable(int tableNum,
                      JPEGQTable qTable)
Sets the coefficient quantization tables at index passed. tableNum must range in value from 0 - 3.

Parameters:
tableNum - the index of the table to be set.

setDCHuffmanTable

public void setDCHuffmanTable(int tableNum,
                              JPEGHuffmanTable huffTable)
Sets the DC Huffman coding table at index to the table provided.

Parameters:
huffTable - JPEGHuffmanTable that will be assigned to index tableNum.
tableNum - - the index of the table to be set.
Throws:
IllegalArgumentException - - thrown if the tableNum is out of range. Index must range in value from 0 - 3.

setACHuffmanTable

public void setACHuffmanTable(int tableNum,
                              JPEGHuffmanTable huffTable)
Sets the AC Huffman coding table at index to the table provided.

Parameters:
huffTable - JPEGHuffmanTable that will be assigned to index tableNum.
tableNum - - the index of the table to be set.
Throws:
IllegalArgumentException - - thrown if the tableNum is out of range. Index must range in value from 0 - 3.

setDCHuffmanComponentMapping

public void setDCHuffmanComponentMapping(int component,
                                         int table)
Sets the mapping between a component and it's DC Huffman Table.

Parameters:
component - The component to set the mapping for
table - The DC Huffman table to use for component

setACHuffmanComponentMapping

public void setACHuffmanComponentMapping(int component,
                                         int table)
Sets the mapping between a component and it's AC Huffman Table.

Parameters:
component - The component to set the mapping for
table - The AC Huffman table to use for component

setQTableComponentMapping

public void setQTableComponentMapping(int component,
                                      int table)
Sets the mapping between a component and it's Quantization Table.

Parameters:
component - The component to set the mapping for
table - The Quantization Table to use for component

setImageInfoValid

public void setImageInfoValid(boolean flag)
Set the flag indicating the validity of the table information in the ParamBlock. This is used to indicate if tables should be included when encoding.

setTableInfoValid

public void setTableInfoValid(boolean flag)
Set the flag indicating the validity of the image information in the ParamBlock. This is used to indicates if image data should be written when encoding.

setMarkerData

public void setMarkerData(int marker,
                          byte[][] data)
Sets the marker data to be written to the output data stream. This removes any existing marker data in the JPEParm object. This can be used to remove the default APP0 marker by calling it with data set to null.

Parameters:
marker - The marker to set the data for.
data - the new set of data to be written.

addMarkerData

public void addMarkerData(int marker,
                          byte[] data)
Appends 'data' to the array of byte[] associated with marker. This will result in additional instance of the marker being written (one for each byte[] in the array.).

Parameters:
marker - The marker to add and instance of.
data - the data to be written.

setRestartInterval

public void setRestartInterval(int restartInterval)
Set the MCUs per restart, or 0 for no restart markers.

Parameters:
restartInterval - number MCUs per restart marker.

setDensityUnit

public void setDensityUnit(int unit)
Set the pixel size units This value is copied into the APP0 marker (if that marker is written). This value isn't used by the JPEG code.

Parameters:
unit - One of the DENSITY_UNIT_* values.

setXDensity

public void setXDensity(int density)
Set the horizontal pixel density This value is written into the APP0 marker. It isn't used by the JPEG code.

Parameters:
density - the horizontal pixel density, in units described by @see JPEGParam.getDensityUnit.

setYDensity

public void setYDensity(int density)
Set the vertical pixel density. This value is copied into the JFIF APP0 marker. It isn't used by the JPEG code.

Parameters:
density - The verticle pixel density, in units described by @see JPEGParam.getDensityUnit.

setQuality

public void setQuality(float quality,
                       boolean forceBaseline)
This creates new Quantization tables that replace the currently installed Quantization tables. It also updates the Component QTable mapping to the default for the current encoded COLOR_ID. The Created Quantization table varies from very high compression, very low quality, (0.0) to low compression, very high quality (1.0) based on the quality parameter.

At a quality level of 1.0 the table will be all 1's which will lead to no loss of data due to quantization (however chrominace subsampling, if used, and roundoff error in the DCT will still degrade the image some what).

This is a linear manipulation of the standard Chrominance Q-Table.

Some guidelines: 0.75 high quality
                 0.5  medium quality
                 0.25 low quality

Parameters:
quality - 0.0-1.0 setting of desired quality level.
forceBaseline - force baseline quantization table
Overview Package Class Use Tree Deprecated Index Help
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


JPEGHuffmanTable (Other API Bundled with the Java 2 SDK)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.image.codec.jpeg
Class JPEGHuffmanTable

java.lang.Object
    extended by com.sun.image.codec.jpeg.JPEGHuffmanTable
public class JPEGHuffmanTable
extends Object

A class to encapsulate a JPEG Huffman table.

Note that the classes in the com.sun.image.codec.jpeg package are not part of the core Java APIs. They are a part of Sun's JDK and JRE distributions. Although other licensees may choose to distribute these classes, developers cannot depend on their availability in non-Sun implementations. We expect that equivalent functionality will eventually be available in a core API or standard extension.

Field Summary
static JPEGHuffmanTable | StdACChrominance Standard Huffman table ( JPEG standard section K.3 )
static JPEGHuffmanTable | StdACLuminance Standard Huffman table ( JPEG standard section K.3 )
static JPEGHuffmanTable | StdDCChrominance Standard Huffman table ( JPEG standard section K.3 )
static JPEGHuffmanTable | StdDCLuminance Standard Huffman table ( JPEG standard section K.3 )
Constructor Summary
JPEGHuffmanTable(short[] lengths, short[] symbols)
Creates a Huffman Table and initializes it.
Method Summary
short[] | getLengths() Return a copy of the array containing the number of symbols for each length in the Huffman table.
short[] | getSymbols() Return an array containing the Huffman symbols arranged by increasing length.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

StdDCLuminance

public static final JPEGHuffmanTable StdDCLuminance
Standard Huffman table ( JPEG standard section K.3 )

StdDCChrominance

public static final JPEGHuffmanTable StdDCChrominance
Standard Huffman table ( JPEG standard section K.3 )

StdACLuminance

public static final JPEGHuffmanTable StdACLuminance
Standard Huffman table ( JPEG standard section K.3 )

StdACChrominance

public static final JPEGHuffmanTable StdACChrominance
Standard Huffman table ( JPEG standard section K.3 )

Constructor Detail

JPEGHuffmanTable

public JPEGHuffmanTable(short[] lengths,
                        short[] symbols)
Creates a Huffman Table and initializes it.

Parameters:
lengths - lengths[k] = # of symbols with codes of length k bits; lengths[0] is ignored
symbols - symbols in order of increasing code length
Throws:
IllegalArgumentException - if the length of lengths is greater than 17
IllegalArgumentException - if the length of symbols is greater than 256
IllegalArgumentException - if any of the values in lengths or symbols is less than zero
Method Detail

getLengths

public short[] getLengths()
Return a copy of the array containing the number of symbols for each length in the Huffman table.

Returns:
A short array where array[k] = # of symbols in the table of length k. array[0] is unused

getSymbols

public short[] getSymbols()
Return an array containing the Huffman symbols arranged by increasing length. To make use of this array you must refer the the lengths array.

Returns:
A short array of Huffman symbols
Overview Package Class Use Tree Deprecated Index Help
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


JPEGImageDecoder (Other API Bundled with the Java 2 SDK)

PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.image.codec.jpeg
Interface JPEGImageDecoder

public interface JPEGImageDecoder

This interface describes a JPEG data stream decoder. This decoder takes an InputStream that contains JPEG encoded image data. The JPEGImageDecoder will decode the JPEG image data according to the parameters set in a JPEGDecodeParam object. The resulting image data is returned in either a Raster or a BufferedImage.

Note that the classes in the com.sun.image.codec.jpeg package are not part of the core Java APIs. They are a part of Sun's JDK and JRE distributions. Although other licensees may choose to distribute these classes, developers cannot depend on their availability in non-Sun implementations. We expect that equivalent functionality will eventually be available in a core API or standard extension.

See Also:
JPEGCodec, JPEGDecodeParam, Raster, BufferedImage

Method Summary
BufferedImage | decodeAsBufferedImage() Decodes the current JPEG data stream.
Raster | decodeAsRaster() Decode the JPEG stream that was passed as part of construction.
InputStream | getInputStream() Get the input stream that decoding will occur from.
JPEGDecodeParam | getJPEGDecodeParam() Returns the JPEGDecodeParam object that resulted from the most recent decoding event.
void | setJPEGDecodeParam(JPEGDecodeParam jdp) Sets the JPEGDecodeParam object used to determine the features of the decompression performed on the JPEG encoded data.

Method Detail

getJPEGDecodeParam

public JPEGDecodeParam getJPEGDecodeParam()
Returns the JPEGDecodeParam object that resulted from the most recent decoding event.

setJPEGDecodeParam

public void setJPEGDecodeParam(JPEGDecodeParam jdp)
Sets the JPEGDecodeParam object used to determine the features of the decompression performed on the JPEG encoded data. This is ussually only needed for decoding abbreviated JPEG data streams.

Parameters:
jdp - JPEGDecodeParam object

getInputStream

public InputStream getInputStream()
Get the input stream that decoding will occur from.

Returns:
The stream that the decoder is currently assciated with.

decodeAsRaster

public Raster decodeAsRaster()
                      throws IOException,
                             ImageFormatException
Decode the JPEG stream that was passed as part of construction. The JPEG decompression will be performed according to the current settings of the JPEGDecodeParam object. For a tables only stream this will return null.

Returns:
Raster containg the image data. Colorspace and other pertinent information can be obtained from the JPEGDecodeParam object.
Throws:
ImageFormatException - if irregularities in the JPEG stream or an unknown condition is encountered.
IOException

decodeAsBufferedImage

public BufferedImage decodeAsBufferedImage()
                                    throws IOException,
                                           ImageFormatException
Decodes the current JPEG data stream. The result of decoding this InputStream is a BufferedImage the ColorModel associated with this BufferedImage is determined based on the encoded COLOR_ID of the JPEGDecodeParam object. For a tables only stream this will return null.

Returns:
BufferedImage containing the image data.
Throws:
ImageFormatException - if irregularities in the JPEG stream or an unknown condition is encountered.
IOException
Overview Package Class Use Tree Deprecated Index Help
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


JPEGImageEncoder (Other API Bundled with the Java 2 SDK)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

com.sun.image.codec.jpeg
Interface JPEGImageEncoder

public interface JPEGImageEncoder

JPEGImageEncoder encodes buffers of image data into JPEG data streams. Users of this interface are required to provide image data in a Raster or a BufferedImage, set the necessary parameters in the JPEGEncodeParams object and successfully open the OutputStream that is the destination of the encoded JPEG stream. The JPEGImageEncoder interface can encode image data into interchange, and abbreviated JPEG data streams that are written to the OutputStream provided to the encoder.

Note that the classes in the com.sun.image.codec.jpeg package are not part of the core Java APIs. They are a part of Sun's JDK and JRE distributions. Although other licensees may choose to distribute these classes, developers cannot depend on their availability in non-Sun implementations. We expect that equivalent functionality will eventually be available in a core API or standard extension.

See Also:
JPEGCodec, JPEGEncodeParam, Raster, BufferedImage, OutputStream

Method Summary
void | encode(BufferedImage bi) Encode a BufferedImage as a JPEG data stream.
void | encode(BufferedImage bi, JPEGEncodeParam jep) Encode a BufferedImage as a JPEG data stream.
void | encode(Raster ras) Encode a Raster as a JPEG data stream.
void | encode(Raster ras, JPEGEncodeParam jep) Encode a Raster as a JPEG data stream.
int | getDefaultColorId(ColorModel cm) Returns the 'default' encoded COLOR_ID for a given ColorModel.
JPEGEncodeParam | getDefaultJPEGEncodeParam(BufferedImage bi) This is a factory method for creating JPEGEncodeParam objects.
JPEGEncodeParam | getDefaultJPEGEncodeParam(int numBands, int colorID) This is a factory method for creating JPEGEncodeParam objects.
JPEGEncodeParam | getDefaultJPEGEncodeParam(JPEGDecodeParam jdp) This is a factory method for creating a JPEGEncodeParam from a JPEGDecodeParam.
JPEGEncodeParam | getDefaultJPEGEncodeParam(Raster ras, int colorID) This is a factory method for creating JPEGEncodeParam objects.
JPEGEncodeParam | getJPEGEncodeParam() This returns a copy of the current JPEGEncodeParam object, if you want changes to affect the encoding process you must 'set' it back into the encoder (either through setJPEGEncodeParam or by providing the modified param object in the call to encode.
OutputStream | getOutputStream() Return the stream the Encoder is currenlt associated with.
void | setJPEGEncodeParam(JPEGEncodeParam jep) Set the JPEGEncodeParam object that is to be used for future encoding operations.

Method Detail

getOutputStream

public OutputStream getOutputStream()
Return the stream the Encoder is currenlt associated with.

setJPEGEncodeParam

public void setJPEGEncodeParam(JPEGEncodeParam jep)
Set the JPEGEncodeParam object that is to be used for future encoding operations. 'jep' is copied so changes will not be tracked, unless you call this method again.

Parameters:
jep - The JPEGEncodeParam object to use for future encodings.

getJPEGEncodeParam

public JPEGEncodeParam getJPEGEncodeParam()
This returns a copy of the current JPEGEncodeParam object, if you want changes to affect the encoding process you must 'set' it back into the encoder (either through setJPEGEncodeParam or by providing the modified param object in the call to encode.

Returns:
A copy of the current JPEGEncodeParam object

getDefaultJPEGEncodeParam

public JPEGEncodeParam getDefaultJPEGEncodeParam(BufferedImage bi)
                                          throws ImageFormatException
This is a factory method for creating JPEGEncodeParam objects. The returned object will do a credible job of encoding the given BufferedImage.

Throws:
ImageFormatException

encode

public void encode(BufferedImage bi)
            throws IOException,
                   ImageFormatException
Encode a BufferedImage as a JPEG data stream. Note, some color conversions may takes place. The current JPEGEncodeParam's encoded COLOR_ID should match the value returned by getDefaultColorID when given the BufferedImage's ColorModel.

If no JPEGEncodeParam object has been provided yet a default one will be created by calling getDefaultJPEGEncodeParam with bi.

Parameters:
bi - The BufferedImage to encode.
Throws:
IOException
ImageFormatException

encode

public void encode(BufferedImage bi,
                   JPEGEncodeParam jep)
            throws IOException,
                   ImageFormatException
Encode a BufferedImage as a JPEG data stream. Note, some color conversions may takes place. The jep's encoded COLOR_ID should match the value returned by getDefaultColorID when given the BufferedImage's ColorModel.

This call also sets the current JPEGEncodeParam object. The given JPEGEncodeParam object will be used for this and future encodings. If jep is null then a new JPEGEncodeParam object will be created by calling getDefaultJPEGEncodeParam with bi.

Parameters:
bi - The BufferedImage to encode.
jep - The JPEGEncodeParam object used to control the encoding.
Throws:
IOException
ImageFormatException

getDefaultColorId

public int getDefaultColorId(ColorModel cm)
Returns the 'default' encoded COLOR_ID for a given ColorModel. This method is not needed in the simple case of encoding Buffered Images (the library will figure things out for you). It can be useful for encoding Rasters. To determine what needs to be done to the image prior to encoding.

Parameters:
cm - The ColorModel to map to an jpeg encoded COLOR_ID.
Returns:
The default mapping of cm to a jpeg Color_ID note that in a few cases color conversion is required.

getDefaultJPEGEncodeParam

public JPEGEncodeParam getDefaultJPEGEncodeParam(Raster ras,
                                                 int colorID)
                                          throws ImageFormatException
This is a factory method for creating JPEGEncodeParam objects. It is the users responsiblity to match the colorID with the data contained in the Raster. Failure to do so may lead to either poor compression or poor image quality. If you don't understand much about JPEG it is strongly reccomended that you stick to the BufferedImage interfaces.

Throws:
ImageFormatException

getDefaultJPEGEncodeParam

public JPEGEncodeParam getDefaultJPEGEncodeParam(int numBands,
                                                 int colorID)
                                          throws ImageFormatException
This is a factory method for creating JPEGEncodeParam objects. It is the users responsiblity to match the colorID with the given number of bands, which should match the data being encoded. Failure to do so may lead to poor compression and/or poor image quality. If you don't understand much about JPEG it is strongly recommended that you stick to the BufferedImage interface.

Parameters:
numBands - the number of bands that will be encoded (max of four).
colorID - the COLOR_ID for the encoded data. This is used to set reasonable defaults in the parameter object. This must match the number of bands given.
Throws:
ImageFormatException

getDefaultJPEGEncodeParam

public JPEGEncodeParam getDefaultJPEGEncodeParam(JPEGDecodeParam jdp)
                                          throws ImageFormatException
This is a factory method for creating a JPEGEncodeParam from a JPEGDecodeParam. This will return a new JPEGEncodeParam object that is initialized from the JPEGDecodeParam object. All major pieces of information will be initialized from the DecodeParam (Markers, Tables, mappings).

Parameters:
jdp - The JPEGDecodeParam object to copy.
Throws:
ImageFormatException

encode

public void encode(Raster ras)
            throws IOException,
                   ImageFormatException
Encode a Raster as a JPEG data stream. Note that no color conversion takes place. It is required that you match the Raster to the encoded COLOR_ID contained in the current JPEGEncodeParam object.

If no JPEGEncodeParam object has been provided yet a new JPEGEncodeParam object will be created by calling getDefaultJPEGEncodeParam with ras and COLOR_ID_UNKNOWN.

Parameters:
ras - The Raster to encode.
Throws:
IOException
ImageFormatException

encode

public void encode(Raster ras,
                   JPEGEncodeParam jep)
            throws IOException,
                   ImageFormatException
Encode a Raster as a JPEG data stream. Note that no color conversion takes place. It is required that you match the Raster to the encoded COLOR_ID contained in the JPEGEncodeParam object. If jep is null a new JPEGEncodeParam object will be created by calling getDefaultJPEGEncodeParam with ras and COLOR_ID_UNKNOWN.

Parameters:
ras - The Raster to encode.
jep - The JPEGEncodeParam object used to control the encoding.
Throws:
IOException
ImageFormatException
Overview Package Class Use Tree Deprecated Index Help
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


JPEGQTable (Other API Bundled with the Java 2 SDK)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

com.sun.image.codec.jpeg
Class JPEGQTable

java.lang.Object
    extended by com.sun.image.codec.jpeg.JPEGQTable
public class JPEGQTable
extends Object

Class to encapsulate the JPEG quantization tables.

Note that the classes in the com.sun.image.codec.jpeg package are not part of the core Java APIs. They are a part of Sun's JDK and JRE distributions. Although other licensees may choose to distribute these classes, developers cannot depend on their availability in non-Sun implementations. We expect that equivalent functionality will eventually be available in a core API or standard extension.

Field Summary
static JPEGQTable | StdChrominance This is the sample luminance quantization table given in the JPEG spec section K.1, expressed in zigzag order.
static JPEGQTable | StdLuminance This is the sample luminance quantization table given in the JPEG spec section K.1, expressed in zigzag order.
Constructor Summary
JPEGQTable(int[] table)
Constructs an quantization table from the array that was passed.
Method Summary
JPEGQTable | getScaledInstance(float scaleFactor, boolean forceBaseline) Returns a new Quantization table where the values are multiplied by scaleFactor and then clamped to the range 1..32767 (or to 1..255 if forceBaseline is 'true').
int[] | getTable() Returns the current quantization table as an array of ints in zig zag order.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

StdLuminance

public static final JPEGQTable StdLuminance
This is the sample luminance quantization table given in the JPEG spec section K.1, expressed in zigzag order. The spec says that the values given produce "good" quality, and when divided by 2, "very good" quality.

StdChrominance

public static final JPEGQTable StdChrominance
This is the sample luminance quantization table given in the JPEG spec section K.1, expressed in zigzag order. The spec says that the values given produce "good" quality, and when divided by 2, "very good" quality.

Constructor Detail

JPEGQTable

public JPEGQTable(int[] table)
Constructs an quantization table from the array that was passed. The coefficents must be in zig-zag order. The array must be of length 64.

Parameters:
table - the quantization table (this is copied).
Method Detail

getTable

public int[] getTable()
Returns the current quantization table as an array of ints in zig zag order.

Returns:
A copy of the contained quantization table.

getScaledInstance

public JPEGQTable getScaledInstance(float scaleFactor,
                                    boolean forceBaseline)
Returns a new Quantization table where the values are multiplied by scaleFactor and then clamped to the range 1..32767 (or to 1..255 if forceBaseline is 'true').

Values less than one tend to improve the quality level of the table, and values greater than one degrade the quality level of the table.

Parameters:
scaleFactor - the multiplication factor for the table
forceBaseline - if true the values will be clamped to the range [1 .. 255]
Returns:
A new Q-Table that is a linear multiple of this Q-Table
Overview Package Class Use Tree Deprecated Index Help
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


com.sun.image.codec.jpeg (Other API Bundled with the Java 2 SDK)

PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package com.sun.image.codec.jpeg

Provides classes for encoding and decoding JPEG images.

See:
Description

Interface Summary
JPEGDecodeParam | JPEGDecodeParam encapsulates tables and options necessary to control decoding JPEG datastreams.
JPEGEncodeParam | JPEGEncodeParam encapsulates tables and options necessary to control encoding of JPEG data streams.
JPEGImageDecoder | This interface describes a JPEG data stream decoder.
JPEGImageEncoder | JPEGImageEncoder encodes buffers of image data into JPEG data streams.

Class Summary
JPEGCodec | This class is a factory for implementations of the JPEG Image Decoder/Encoder.
JPEGHuffmanTable | A class to encapsulate a JPEG Huffman table.
JPEGQTable | Class to encapsulate the JPEG quantization tables.

Exception Summary
ImageFormatException | Signals that an Image Format exception of some sort has occurred.
TruncatedFileException | Signals that a truncated file was detected.

Package com.sun.image.codec.jpeg Description

Provides classes for encoding and decoding JPEG images.

Overview Package Class Use Tree Deprecated Index Help
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


com.sun.image.codec.jpeg Class Hierarchy (Other API Bundled with the Java 2 SDK)

PREV NEXT FRAMES NO FRAMES

Hierarchy For Package com.sun.image.codec.jpeg

Class Hierarchy

  • class java.lang.Object
    • class com.sun.image.codec.jpeg.JPEGCodec
    • class com.sun.image.codec.jpeg.JPEGHuffmanTable
    • class com.sun.image.codec.jpeg.JPEGQTable
    • class java.lang.Throwable (implements java.io.Serializable)
      • class java.lang.Exception
        • class java.lang.RuntimeException
          • class com.sun.image.codec.jpeg.ImageFormatException
          • class com.sun.image.codec.jpeg.TruncatedFileException

Interface Hierarchy

  • interface java.lang.Cloneable
    • interface com.sun.image.codec.jpeg.JPEGDecodeParam
      • interface com.sun.image.codec.jpeg.JPEGEncodeParam (also extends java.lang.Cloneable)
    • interface com.sun.image.codec.jpeg.JPEGEncodeParam (also extends com.sun.image.codec.jpeg.JPEGDecodeParam)
  • interface com.sun.image.codec.jpeg.JPEGImageDecoder
  • interface com.sun.image.codec.jpeg.JPEGImageEncoder
Overview Package Class Use Tree Deprecated Index Help
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Package com.sun.image.codec.jpeg (Other API Bundled with the Java 2 SDK)

PREV NEXT FRAMES NO FRAMES

Uses of Package
com.sun.image.codec.jpeg

Classes in com.sun.image.codec.jpeg used by com.sun.image.codec.jpeg
ImageFormatException
Signals that an Image Format exception of some sort has occurred.
JPEGDecodeParam
JPEGDecodeParam encapsulates tables and options necessary to control decoding JPEG datastreams.
JPEGEncodeParam
JPEGEncodeParam encapsulates tables and options necessary to control encoding of JPEG data streams.
JPEGHuffmanTable
A class to encapsulate a JPEG Huffman table.
JPEGImageDecoder
This interface describes a JPEG data stream decoder.
JPEGImageEncoder
JPEGImageEncoder encodes buffers of image data into JPEG data streams.
JPEGQTable
Class to encapsulate the JPEG quantization tables.

Overview Package Class Use Tree Deprecated Index Help
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


TruncatedFileException (Other API Bundled with the Java 2 SDK)

PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

com.sun.image.codec.jpeg
Class TruncatedFileException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by com.sun.image.codec.jpeg.TruncatedFileException
All Implemented Interfaces:
Serializable
public class TruncatedFileException
extends RuntimeException

Signals that a truncated file was detected. This object contains the Raster/BufferedImage that has the partially decoded image data in it. There is no indication of the portion of the Raster that may or may not be good.

Note that the classes in the com.sun.image.codec.jpeg package are not part of the core Java APIs. They are a part of Sun's JDK and JRE distributions. Although other licensees may choose to distribute these classes, developers cannot depend on their availability in non-Sun implementations. We expect that equivalent functionality will eventually be available in a core API or standard extension.

Since:
JDK1.2
See Also:
JPEGImageDecoder, Serialized Form

Constructor Summary
TruncatedFileException(BufferedImage bi)
Constructs a TruncatedFileException/code> with the partially decoded BufferedImage.
TruncatedFileException(Raster ras)
Constructs an TruncatedFileException with the partially decoded Raster
Method Summary
BufferedImage | getBufferedImage() Allows access to the BufferedImage that was in the progress of being decoded, this may be null, it is likely to be only partially filled with image data.
Raster | getRaster() Allows access to the raster that was in the progress of being decoded may be null, it is likely to be only partially filled with image data.
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

TruncatedFileException

public TruncatedFileException(BufferedImage bi)
Constructs a TruncatedFileException/code> with the partially decoded BufferedImage.

Parameters:
bi - the partially decoded BufferedImage (may be null).
Since:
JDK1.2

TruncatedFileException

public TruncatedFileException(Raster ras)
Constructs an TruncatedFileException with the partially decoded Raster

Parameters:
ras - the partially decoded Raster (may be null).
Since:
JDK1.2
Method Detail

getRaster

public Raster getRaster()
Allows access to the raster that was in the progress of being decoded may be null, it is likely to be only partially filled with image data.

Since:
JDK1.2

getBufferedImage

public BufferedImage getBufferedImage()
Allows access to the BufferedImage that was in the progress of being decoded, this may be null, it is likely to be only partially filled with image data.

Since:
JDK1.2
Overview  Package   Class  Use  Tree  Deprecated  Index  Help
 PREV CLASS   NEXT CLASS | FRAMES    NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Class com.sun.image.codec.jpeg.ImageFormatException (Other API Bundled with the Java 2 SDK)

PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.image.codec.jpeg.ImageFormatException

Uses of ImageFormatException in com.sun.image.codec.jpeg

Methods in com.sun.image.codec.jpeg that throw ImageFormatException
static JPEGEncodeParam | JPEGCodec.getDefaultJPEGEncodeParam(int numBands, int colorID) This is a factory method for creating JPEGEncodeParam objects.
static JPEGEncodeParam | JPEGCodec.getDefaultJPEGEncodeParam(JPEGDecodeParam jdp) This is a factory method for creating a JPEGEncodeParam from a JPEGDecodeParam.
JPEGEncodeParam | JPEGImageEncoder.getDefaultJPEGEncodeParam(BufferedImage bi) This is a factory method for creating JPEGEncodeParam objects.
void | JPEGImageEncoder.encode(BufferedImage bi) Encode a BufferedImage as a JPEG data stream.
void | JPEGImageEncoder.encode(BufferedImage bi, JPEGEncodeParam jep) Encode a BufferedImage as a JPEG data stream.
JPEGEncodeParam | JPEGImageEncoder.getDefaultJPEGEncodeParam(Raster ras, int colorID) This is a factory method for creating JPEGEncodeParam objects.
JPEGEncodeParam | JPEGImageEncoder.getDefaultJPEGEncodeParam(int numBands, int colorID) This is a factory method for creating JPEGEncodeParam objects.
JPEGEncodeParam | JPEGImageEncoder.getDefaultJPEGEncodeParam(JPEGDecodeParam jdp) This is a factory method for creating a JPEGEncodeParam from a JPEGDecodeParam.
void | JPEGImageEncoder.encode(Raster ras) Encode a Raster as a JPEG data stream.
void | JPEGImageEncoder.encode(Raster ras, JPEGEncodeParam jep) Encode a Raster as a JPEG data stream.
Raster | JPEGImageDecoder.decodeAsRaster() Decode the JPEG stream that was passed as part of construction.
BufferedImage | JPEGImageDecoder.decodeAsBufferedImage() Decodes the current JPEG data stream.

Overview Package Class Use Tree Deprecated Index Help
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Class com.sun.image.codec.jpeg.JPEGCodec (Other API Bundled with the Java 2 SDK)

PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.image.codec.jpeg.JPEGCodec

No usage of com.sun.image.codec.jpeg.JPEGCodec

Overview Package Class Use Tree Deprecated Index Help
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface com.sun.image.codec.jpeg.JPEGDecodeParam (Other API Bundled with the Java 2 SDK)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.image.codec.jpeg.JPEGDecodeParam

Uses of JPEGDecodeParam in com.sun.image.codec.jpeg

Subinterfaces of JPEGDecodeParam in com.sun.image.codec.jpeg
 interface JPEGEncodeParam
JPEGEncodeParam encapsulates tables and options necessary to control encoding of JPEG data streams.

Methods in com.sun.image.codec.jpeg that return JPEGDecodeParam
 JPEGDecodeParam JPEGImageDecoder.getJPEGDecodeParam()
Returns the JPEGDecodeParam object that resulted from the most recent decoding event.

Methods in com.sun.image.codec.jpeg with parameters of type JPEGDecodeParam
static JPEGImageDecoder | JPEGCodec.createJPEGDecoder(InputStream src, JPEGDecodeParam jdp) This creates an instance of a JPEGImageDecoder that can be used to decode JPEG Data streams.
static JPEGEncodeParam | JPEGCodec.getDefaultJPEGEncodeParam(JPEGDecodeParam jdp) This is a factory method for creating a JPEGEncodeParam from a JPEGDecodeParam.
JPEGEncodeParam | JPEGImageEncoder.getDefaultJPEGEncodeParam(JPEGDecodeParam jdp) This is a factory method for creating a JPEGEncodeParam from a JPEGDecodeParam.
void | JPEGImageDecoder.setJPEGDecodeParam(JPEGDecodeParam jdp) Sets the JPEGDecodeParam object used to determine the features of the decompression performed on the JPEG encoded data.

Overview Package Class Use Tree Deprecated Index Help
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface com.sun.image.codec.jpeg.JPEGEncodeParam (Other API Bundled with the Java 2 SDK)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.image.codec.jpeg.JPEGEncodeParam

Uses of JPEGEncodeParam in com.sun.image.codec.jpeg

Methods in com.sun.image.codec.jpeg that return JPEGEncodeParam
static JPEGEncodeParam | JPEGCodec.getDefaultJPEGEncodeParam(BufferedImage bi) This is a factory method for creating JPEGEncodeParam objects.
static JPEGEncodeParam | JPEGCodec.getDefaultJPEGEncodeParam(Raster ras, int colorID) This is a factory method for creating JPEGEncodeParam objects.
static JPEGEncodeParam | JPEGCodec.getDefaultJPEGEncodeParam(int numBands, int colorID) This is a factory method for creating JPEGEncodeParam objects.
static JPEGEncodeParam | JPEGCodec.getDefaultJPEGEncodeParam(JPEGDecodeParam jdp) This is a factory method for creating a JPEGEncodeParam from a JPEGDecodeParam.
JPEGEncodeParam | JPEGImageEncoder.getJPEGEncodeParam() This returns a copy of the current JPEGEncodeParam object, if you want changes to affect the encoding process you must 'set' it back into the encoder (either through setJPEGEncodeParam or by providing the modified param object in the call to encode.
JPEGEncodeParam | JPEGImageEncoder.getDefaultJPEGEncodeParam(BufferedImage bi) This is a factory method for creating JPEGEncodeParam objects.
JPEGEncodeParam | JPEGImageEncoder.getDefaultJPEGEncodeParam(Raster ras, int colorID) This is a factory method for creating JPEGEncodeParam objects.
JPEGEncodeParam | JPEGImageEncoder.getDefaultJPEGEncodeParam(int numBands, int colorID) This is a factory method for creating JPEGEncodeParam objects.
JPEGEncodeParam | JPEGImageEncoder.getDefaultJPEGEncodeParam(JPEGDecodeParam jdp) This is a factory method for creating a JPEGEncodeParam from a JPEGDecodeParam.

Methods in com.sun.image.codec.jpeg with parameters of type JPEGEncodeParam
static JPEGImageEncoder | JPEGCodec.createJPEGEncoder(OutputStream dest, JPEGEncodeParam jep) This creates an instance of a JPEGImageEncoder that can be used to encode image data as JPEG Data streams.
void | JPEGImageEncoder.setJPEGEncodeParam(JPEGEncodeParam jep) Set the JPEGEncodeParam object that is to be used for future encoding operations.
void | JPEGImageEncoder.encode(BufferedImage bi, JPEGEncodeParam jep) Encode a BufferedImage as a JPEG data stream.
void | JPEGImageEncoder.encode(Raster ras, JPEGEncodeParam jep) Encode a Raster as a JPEG data stream.

Overview Package Class Use Tree Deprecated Index Help
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Class com.sun.image.codec.jpeg.JPEGHuffmanTable (Other API Bundled with the Java 2 SDK)

PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.image.codec.jpeg.JPEGHuffmanTable

Uses of JPEGHuffmanTable in com.sun.image.codec.jpeg

Fields in com.sun.image.codec.jpeg declared as JPEGHuffmanTable
static JPEGHuffmanTable | JPEGHuffmanTable.StdDCLuminance Standard Huffman table ( JPEG standard section K.3 )
static JPEGHuffmanTable | JPEGHuffmanTable.StdDCChrominance Standard Huffman table ( JPEG standard section K.3 )
static JPEGHuffmanTable | JPEGHuffmanTable.StdACLuminance Standard Huffman table ( JPEG standard section K.3 )
static JPEGHuffmanTable | JPEGHuffmanTable.StdACChrominance Standard Huffman table ( JPEG standard section K.3 )

Methods in com.sun.image.codec.jpeg that return JPEGHuffmanTable
JPEGHuffmanTable | JPEGDecodeParam.getDCHuffmanTable(int tableNum) Returns the DC Huffman coding table requested or null if not defined
JPEGHuffmanTable | JPEGDecodeParam.getDCHuffmanTableForComponent(int component) Returns the DC Huffman coding table for the requested component.
JPEGHuffmanTable | JPEGDecodeParam.getACHuffmanTable(int tableNum) Returns the AC Huffman coding table requested or null if not defined
JPEGHuffmanTable | JPEGDecodeParam.getACHuffmanTableForComponent(int component) Returns the AC Huffman coding table for the requested component.

Methods in com.sun.image.codec.jpeg with parameters of type JPEGHuffmanTable
void | JPEGEncodeParam.setDCHuffmanTable(int tableNum, JPEGHuffmanTable huffTable) Sets the DC Huffman coding table at index to the table provided.
void | JPEGEncodeParam.setACHuffmanTable(int tableNum, JPEGHuffmanTable huffTable) Sets the AC Huffman coding table at index to the table provided.

Overview Package Class Use Tree Deprecated Index Help
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface com.sun.image.codec.jpeg.JPEGImageDecoder (Other API Bundled with the Java 2 SDK)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.image.codec.jpeg.JPEGImageDecoder

Uses of JPEGImageDecoder in com.sun.image.codec.jpeg

Methods in com.sun.image.codec.jpeg that return JPEGImageDecoder
static JPEGImageDecoder | JPEGCodec.createJPEGDecoder(InputStream src) This creates an instance of a JPEGImageDecoder that can be used to decode JPEG Data streams.
static JPEGImageDecoder | JPEGCodec.createJPEGDecoder(InputStream src, JPEGDecodeParam jdp) This creates an instance of a JPEGImageDecoder that can be used to decode JPEG Data streams.

Overview Package Class Use Tree Deprecated Index Help
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface com.sun.image.codec.jpeg.JPEGImageEncoder (Other API Bundled with the Java 2 SDK)

PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.image.codec.jpeg.JPEGImageEncoder

Uses of JPEGImageEncoder in com.sun.image.codec.jpeg

Methods in com.sun.image.codec.jpeg that return JPEGImageEncoder
static JPEGImageEncoder | JPEGCodec.createJPEGEncoder(OutputStream dest) This creates an instance of a JPEGImageEncoder that can be used to encode image data as JPEG Data streams.
static JPEGImageEncoder | JPEGCodec.createJPEGEncoder(OutputStream dest, JPEGEncodeParam jep) This creates an instance of a JPEGImageEncoder that can be used to encode image data as JPEG Data streams.

Overview Package Class Use Tree Deprecated Index Help
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Class com.sun.image.codec.jpeg.JPEGQTable (Other API Bundled with the Java 2 SDK)

PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.image.codec.jpeg.JPEGQTable

Uses of JPEGQTable in com.sun.image.codec.jpeg

Fields in com.sun.image.codec.jpeg declared as JPEGQTable
static JPEGQTable | JPEGQTable.StdLuminance This is the sample luminance quantization table given in the JPEG spec section K.1, expressed in zigzag order.
static JPEGQTable | JPEGQTable.StdChrominance This is the sample luminance quantization table given in the JPEG spec section K.1, expressed in zigzag order.

Methods in com.sun.image.codec.jpeg that return JPEGQTable
JPEGQTable | JPEGQTable.getScaledInstance(float scaleFactor, boolean forceBaseline) Returns a new Quantization table where the values are multiplied by scaleFactor and then clamped to the range 1..32767 (or to 1..255 if forceBaseline is 'true').
JPEGQTable | JPEGDecodeParam.getQTable(int tableNum) Returns the coefficient quantization tables or NULL if not defined.
JPEGQTable | JPEGDecodeParam.getQTableForComponent(int component) Returns the Quantization table for the requested component.

Methods in com.sun.image.codec.jpeg with parameters of type JPEGQTable
 void JPEGEncodeParam.setQTable(int tableNum, JPEGQTable qTable)
Sets the coefficient quantization tables at index passed.

Overview Package Class Use Tree Deprecated Index Help
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Class com.sun.image.codec.jpeg.TruncatedFileException (Other API Bundled with the Java 2 SDK)

PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.image.codec.jpeg.TruncatedFileException

No usage of com.sun.image.codec.jpeg.TruncatedFileException

Overview Package Class Use Tree Deprecated Index Help
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


A-Index (Other API Bundled with the Java 2 SDK)

PREV LETTER NEXT LETTER FRAMES NO FRAMES
A C D E G I J N S T

A

APP0_MARKER - Static variable in interface com.sun.image.codec.jpeg.JPEGDecodeParam
APP0 marker - JFIF info
APP1_MARKER - Static variable in interface com.sun.image.codec.jpeg.JPEGDecodeParam
APP1 marker
APP2_MARKER - Static variable in interface com.sun.image.codec.jpeg.JPEGDecodeParam
APP2 marker
APP3_MARKER - Static variable in interface com.sun.image.codec.jpeg.JPEGDecodeParam
APP3 marker
APP4_MARKER - Static variable in interface com.sun.image.codec.jpeg.JPEGDecodeParam
APP4 marker
APP5_MARKER - Static variable in interface com.sun.image.codec.jpeg.JPEGDecodeParam
APP5 marker
APP6_MARKER - Static variable in interface com.sun.image.codec.jpeg.JPEGDecodeParam
APP6 marker
APP7_MARKER - Static variable in interface com.sun.image.codec.jpeg.JPEGDecodeParam
APP7 marker
APP8_MARKER - Static variable in interface com.sun.image.codec.jpeg.JPEGDecodeParam
APP8 marker
APP9_MARKER - Static variable in interface com.sun.image.codec.jpeg.JPEGDecodeParam
APP9 marker
APPA_MARKER - Static variable in interface com.sun.image.codec.jpeg.JPEGDecodeParam
APPA marker
APPB_MARKER - Static variable in interface com.sun.image.codec.jpeg.JPEGDecodeParam
APPB marker
APPC_MARKER - Static variable in interface com.sun.image.codec.jpeg.JPEGDecodeParam
APPC marker
APPD_MARKER - Static variable in interface com.sun.image.codec.jpeg.JPEGDecodeParam
APPD marker
APPE_MARKER - Static variable in interface com.sun.image.codec.jpeg.JPEGDecodeParam
APPE marker - Adobe info
APPF_MARKER - Static variable in interface com.sun.image.codec.jpeg.JPEGDecodeParam
APPF marker
addMarkerData(int, byte[]) - Method in interface com.sun.image.codec.jpeg.JPEGEncodeParam
Appends 'data' to the array of byte[] associated with marker.
Overview Package Class Use Tree Deprecated Index Help
PREV LETTER NEXT LETTER FRAMES NO FRAMES
A C D E G I J N S T
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


C-Index (Other API Bundled with the Java 2 SDK)

PREV LETTER NEXT LETTER FRAMES NO FRAMES
A C D E G I J N S T

C

COLOR_ID_CMYK - Static variable in interface com.sun.image.codec.jpeg.JPEGDecodeParam
CMYK
COLOR_ID_GRAY - Static variable in interface com.sun.image.codec.jpeg.JPEGDecodeParam
Monochrome
COLOR_ID_PYCC - Static variable in interface com.sun.image.codec.jpeg.JPEGDecodeParam
PhotoYCC
COLOR_ID_PYCCA - Static variable in interface com.sun.image.codec.jpeg.JPEGDecodeParam
PhotoYCC-Alpha
COLOR_ID_RGB - Static variable in interface com.sun.image.codec.jpeg.JPEGDecodeParam
Red, Green, and Blue
COLOR_ID_RGBA - Static variable in interface com.sun.image.codec.jpeg.JPEGDecodeParam
RGB-Alpha
COLOR_ID_RGBA_INVERTED - Static variable in interface com.sun.image.codec.jpeg.JPEGDecodeParam
RGB-Alpha with R, G, and B inverted.
COLOR_ID_UNKNOWN - Static variable in interface com.sun.image.codec.jpeg.JPEGDecodeParam
Unknown or Undefined Color ID
COLOR_ID_YCCK - Static variable in interface com.sun.image.codec.jpeg.JPEGDecodeParam
YCbCrK
COLOR_ID_YCbCr - Static variable in interface com.sun.image.codec.jpeg.JPEGDecodeParam
YCbCr
COLOR_ID_YCbCrA - Static variable in interface com.sun.image.codec.jpeg.JPEGDecodeParam
YCbCr-Alpha
COLOR_ID_YCbCrA_INVERTED - Static variable in interface com.sun.image.codec.jpeg.JPEGDecodeParam
YCbCr-Alpha with Y, Cb, and Cr inverted.
COMMENT_MARKER - Static variable in interface com.sun.image.codec.jpeg.JPEGDecodeParam
Adobe marker indicates presence/need for Adobe marker.
clone() - Method in interface com.sun.image.codec.jpeg.JPEGDecodeParam
clone() - Method in interface com.sun.image.codec.jpeg.JPEGEncodeParam
com.sun.image.codec.jpeg - package com.sun.image.codec.jpeg
Provides classes for encoding and decoding JPEG images.
createJPEGDecoder(InputStream) - Static method in class com.sun.image.codec.jpeg.JPEGCodec
This creates an instance of a JPEGImageDecoder that can be used to decode JPEG Data streams.
createJPEGDecoder(InputStream, JPEGDecodeParam) - Static method in class com.sun.image.codec.jpeg.JPEGCodec
This creates an instance of a JPEGImageDecoder that can be used to decode JPEG Data streams.
createJPEGEncoder(OutputStream) - Static method in class com.sun.image.codec.jpeg.JPEGCodec
This creates an instance of a JPEGImageEncoder that can be used to encode image data as JPEG Data streams.
createJPEGEncoder(OutputStream, JPEGEncodeParam) - Static method in class com.sun.image.codec.jpeg.JPEGCodec
This creates an instance of a JPEGImageEncoder that can be used to encode image data as JPEG Data streams.
Overview Package Class Use Tree Deprecated Index Help
A C D E G I J N S T
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


D-Index (Other API Bundled with the Java 2 SDK)

PREV LETTER NEXT LETTER FRAMES NO FRAMES
A C D E G I J N S T

D

DENSITY_UNIT_ASPECT_RATIO - Static variable in interface com.sun.image.codec.jpeg.JPEGDecodeParam
The X and Y units simply indicate the aspect ratio of the pixels.
DENSITY_UNIT_DOTS_CM - Static variable in interface com.sun.image.codec.jpeg.JPEGDecodeParam
Pixel density is in pixels per centemeter.
DENSITY_UNIT_DOTS_INCH - Static variable in interface com.sun.image.codec.jpeg.JPEGDecodeParam
Pixel density is in pixels per inch.
decodeAsBufferedImage() - Method in interface com.sun.image.codec.jpeg.JPEGImageDecoder
Decodes the current JPEG data stream.
decodeAsRaster() - Method in interface com.sun.image.codec.jpeg.JPEGImageDecoder
Decode the JPEG stream that was passed as part of construction.
Overview Package Class Use Tree Deprecated Index Help
A C D E G I J N S T
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


E-Index (Other API Bundled with the Java 2 SDK)

PREV LETTER NEXT LETTER FRAMES NO FRAMES
A C D E G I J N S T

E

encode(BufferedImage) - Method in interface com.sun.image.codec.jpeg.JPEGImageEncoder
Encode a BufferedImage as a JPEG data stream.
encode(BufferedImage, JPEGEncodeParam) - Method in interface com.sun.image.codec.jpeg.JPEGImageEncoder
Encode a BufferedImage as a JPEG data stream.
encode(Raster) - Method in interface com.sun.image.codec.jpeg.JPEGImageEncoder
Encode a Raster as a JPEG data stream.
encode(Raster, JPEGEncodeParam) - Method in interface com.sun.image.codec.jpeg.JPEGImageEncoder
Encode a Raster as a JPEG data stream.
Overview Package Class Use Tree Deprecated Index Help
A C D E G I J N S T
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


G-Index (Other API Bundled with the Java 2 SDK)

PREV LETTER NEXT LETTER FRAMES NO FRAMES
A C D E G I J N S T

G

getACHuffmanComponentMapping(int) - Method in interface com.sun.image.codec.jpeg.JPEGDecodeParam
Get the number of the AC Huffman table that will be used for a particular component.
getACHuffmanTable(int) - Method in interface com.sun.image.codec.jpeg.JPEGDecodeParam
Returns the AC Huffman coding table requested or null if not defined
getACHuffmanTableForComponent(int) - Method in interface com.sun.image.codec.jpeg.JPEGDecodeParam
Returns the AC Huffman coding table for the requested component.
getBufferedImage() - Method in class com.sun.image.codec.jpeg.TruncatedFileException
Allows access to the BufferedImage that was in the progress of being decoded, this may be null, it is likely to be only partially filled with image data.
getDCHuffmanComponentMapping(int) - Method in interface com.sun.image.codec.jpeg.JPEGDecodeParam
Get the number of the DC Huffman table that will be used for a particular component.
getDCHuffmanTable(int) - Method in interface com.sun.image.codec.jpeg.JPEGDecodeParam
Returns the DC Huffman coding table requested or null if not defined
getDCHuffmanTableForComponent(int) - Method in interface com.sun.image.codec.jpeg.JPEGDecodeParam
Returns the DC Huffman coding table for the requested component.
getDefaultColorId(ColorModel) - Method in interface com.sun.image.codec.jpeg.JPEGImageEncoder
Returns the 'default' encoded COLOR_ID for a given ColorModel.
getDefaultJPEGEncodeParam(BufferedImage) - Static method in class com.sun.image.codec.jpeg.JPEGCodec
This is a factory method for creating JPEGEncodeParam objects.
getDefaultJPEGEncodeParam(Raster, int) - Static method in class com.sun.image.codec.jpeg.JPEGCodec
This is a factory method for creating JPEGEncodeParam objects.
getDefaultJPEGEncodeParam(int, int) - Static method in class com.sun.image.codec.jpeg.JPEGCodec
This is a factory method for creating JPEGEncodeParam objects.
getDefaultJPEGEncodeParam(JPEGDecodeParam) - Static method in class com.sun.image.codec.jpeg.JPEGCodec
This is a factory method for creating a JPEGEncodeParam from a JPEGDecodeParam.
getDefaultJPEGEncodeParam(BufferedImage) - Method in interface com.sun.image.codec.jpeg.JPEGImageEncoder
This is a factory method for creating JPEGEncodeParam objects.
getDefaultJPEGEncodeParam(Raster, int) - Method in interface com.sun.image.codec.jpeg.JPEGImageEncoder
This is a factory method for creating JPEGEncodeParam objects.
getDefaultJPEGEncodeParam(int, int) - Method in interface com.sun.image.codec.jpeg.JPEGImageEncoder
This is a factory method for creating JPEGEncodeParam objects.
getDefaultJPEGEncodeParam(JPEGDecodeParam) - Method in interface com.sun.image.codec.jpeg.JPEGImageEncoder
This is a factory method for creating a JPEGEncodeParam from a JPEGDecodeParam.
getDensityUnit() - Method in interface com.sun.image.codec.jpeg.JPEGDecodeParam
Get the code for pixel size units This value is copied from the APP0 marker.
getEncodedColorID() - Method in interface com.sun.image.codec.jpeg.JPEGDecodeParam
Returns the JPEG Encoded color id.
getHeight() - Method in interface com.sun.image.codec.jpeg.JPEGDecodeParam
Get the image height
getHorizontalSubsampling(int) - Method in interface com.sun.image.codec.jpeg.JPEGDecodeParam
Return the Horizontal subsampling factor for requested Component.
getInputStream() - Method in interface com.sun.image.codec.jpeg.JPEGImageDecoder
Get the input stream that decoding will occur from.
getJPEGDecodeParam() - Method in interface com.sun.image.codec.jpeg.JPEGImageDecoder
Returns the JPEGDecodeParam object that resulted from the most recent decoding event.
getJPEGEncodeParam() - Method in interface com.sun.image.codec.jpeg.JPEGImageEncoder
This returns a copy of the current JPEGEncodeParam object, if you want changes to affect the encoding process you must 'set' it back into the encoder (either through setJPEGEncodeParam or by providing the modified param object in the call to encode.
getLengths() - Method in class com.sun.image.codec.jpeg.JPEGHuffmanTable
Return a copy of the array containing the number of symbols for each length in the Huffman table.
getMarker(int) - Method in interface com.sun.image.codec.jpeg.JPEGDecodeParam
Returns true if at least one instance of the marker is present in the Parameter object.
getMarkerData(int) - Method in interface com.sun.image.codec.jpeg.JPEGDecodeParam
Returns a 'byte[][]' associated with the requested marker in the parameter object.
getNumComponents() - Method in interface com.sun.image.codec.jpeg.JPEGDecodeParam
Returns the number of components for the current encoding COLOR_ID.
getOutputStream() - Method in interface com.sun.image.codec.jpeg.JPEGImageEncoder
Return the stream the Encoder is currenlt associated with.
getQTable(int) - Method in interface com.sun.image.codec.jpeg.JPEGDecodeParam
Returns the coefficient quantization tables or NULL if not defined.
getQTableComponentMapping(int) - Method in interface com.sun.image.codec.jpeg.JPEGDecodeParam
Get the number of the quantization table that will be used for a particular component.
getQTableForComponent(int) - Method in interface com.sun.image.codec.jpeg.JPEGDecodeParam
Returns the Quantization table for the requested component.
getRaster() - Method in class com.sun.image.codec.jpeg.TruncatedFileException
Allows access to the raster that was in the progress of being decoded may be null, it is likely to be only partially filled with image data.
getRestartInterval() - Method in interface com.sun.image.codec.jpeg.JPEGDecodeParam
Get the MCUs per restart marker.
getScaledInstance(float, boolean) - Method in class com.sun.image.codec.jpeg.JPEGQTable
Returns a new Quantization table where the values are multiplied by scaleFactor and then clamped to the range 1..32767 (or to 1..255 if forceBaseline is 'true').
getSymbols() - Method in class com.sun.image.codec.jpeg.JPEGHuffmanTable
Return an array containing the Huffman symbols arranged by increasing length.
getTable() - Method in class com.sun.image.codec.jpeg.JPEGQTable
Returns the current quantization table as an array of ints in zig zag order.
getVerticalSubsampling(int) - Method in interface com.sun.image.codec.jpeg.JPEGDecodeParam
Return the Vertical subsampling factor for requested Component.
getWidth() - Method in interface com.sun.image.codec.jpeg.JPEGDecodeParam
Get the image width
getXDensity() - Method in interface com.sun.image.codec.jpeg.JPEGDecodeParam
Get the horizontal pixel density This value is copied from the APP0 marker.
getYDensity() - Method in interface com.sun.image.codec.jpeg.JPEGDecodeParam
Get the vertical pixel density This value is copied into the APP0 marker.
Overview Package Class Use Tree Deprecated Index Help
A C D E G I J N S T
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


I-Index (Other API Bundled with the Java 2 SDK)

PREV LETTER NEXT LETTER FRAMES NO FRAMES
A C D E G I J N S T

I

ImageFormatException - exception com.sun.image.codec.jpeg.ImageFormatException.
Signals that an Image Format exception of some sort has occurred.
ImageFormatException() - Constructor for class com.sun.image.codec.jpeg.ImageFormatException
Constructs an ImageFormatException with no detail message.
ImageFormatException(String) - Constructor for class com.sun.image.codec.jpeg.ImageFormatException
Constructs an ImageFormatException with the specified detailed message.
isImageInfoValid() - Method in interface com.sun.image.codec.jpeg.JPEGDecodeParam
Returns true if the image information in the ParamBlock is currently valid.
isTableInfoValid() - Method in interface com.sun.image.codec.jpeg.JPEGDecodeParam
Returns true if the tables in the ParamBlock are currently valid.
Overview Package Class Use Tree Deprecated Index Help
A C D E G I J N S T
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


J-Index (Other API Bundled with the Java 2 SDK)

PREV LETTER NEXT LETTER FRAMES NO FRAMES
A C D E G I J N S T

J

JPEGCodec - class com.sun.image.codec.jpeg.JPEGCodec.
This class is a factory for implementations of the JPEG Image Decoder/Encoder.
JPEGDecodeParam - interface com.sun.image.codec.jpeg.JPEGDecodeParam.
JPEGDecodeParam encapsulates tables and options necessary to control decoding JPEG datastreams.
JPEGEncodeParam - interface com.sun.image.codec.jpeg.JPEGEncodeParam.
JPEGEncodeParam encapsulates tables and options necessary to control encoding of JPEG data streams.
JPEGHuffmanTable - class com.sun.image.codec.jpeg.JPEGHuffmanTable.
A class to encapsulate a JPEG Huffman table.
JPEGHuffmanTable(short[], short[]) - Constructor for class com.sun.image.codec.jpeg.JPEGHuffmanTable
Creates a Huffman Table and initializes it.
JPEGImageDecoder - interface com.sun.image.codec.jpeg.JPEGImageDecoder.
This interface describes a JPEG data stream decoder.
JPEGImageEncoder - interface com.sun.image.codec.jpeg.JPEGImageEncoder.
JPEGImageEncoder encodes buffers of image data into JPEG data streams.
JPEGQTable - class com.sun.image.codec.jpeg.JPEGQTable.
Class to encapsulate the JPEG quantization tables.
JPEGQTable(int[]) - Constructor for class com.sun.image.codec.jpeg.JPEGQTable
Constructs an quantization table from the array that was passed.
Overview Package Class Use Tree Deprecated Index Help
A C D E G I J N S T
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


N-Index (Other API Bundled with the Java 2 SDK)

PREV LETTER NEXT LETTER FRAMES NO FRAMES
A C D E G I J N S T

N

NUM_COLOR_ID - Static variable in interface com.sun.image.codec.jpeg.JPEGDecodeParam
Number of color ids defined.
NUM_DENSITY_UNIT - Static variable in interface com.sun.image.codec.jpeg.JPEGDecodeParam
The max known value for DENSITY_UNIT
NUM_TABLES - Static variable in interface com.sun.image.codec.jpeg.JPEGDecodeParam
Number of allowed Huffman and Quantization Tables
Overview Package Class Use Tree Deprecated Index Help
A C D E G I J N S T
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


S-Index (Other API Bundled with the Java 2 SDK)

PREV LETTER NEXT LETTER FRAMES NO FRAMES
A C D E G I J N S T

S

StdACChrominance - Static variable in class com.sun.image.codec.jpeg.JPEGHuffmanTable
Standard Huffman table ( JPEG standard section K.3 )
StdACLuminance - Static variable in class com.sun.image.codec.jpeg.JPEGHuffmanTable
Standard Huffman table ( JPEG standard section K.3 )
StdChrominance - Static variable in class com.sun.image.codec.jpeg.JPEGQTable
This is the sample luminance quantization table given in the JPEG spec section K.1, expressed in zigzag order.
StdDCChrominance - Static variable in class com.sun.image.codec.jpeg.JPEGHuffmanTable
Standard Huffman table ( JPEG standard section K.3 )
StdDCLuminance - Static variable in class com.sun.image.codec.jpeg.JPEGHuffmanTable
Standard Huffman table ( JPEG standard section K.3 )
StdLuminance - Static variable in class com.sun.image.codec.jpeg.JPEGQTable
This is the sample luminance quantization table given in the JPEG spec section K.1, expressed in zigzag order.
setACHuffmanComponentMapping(int, int) - Method in interface com.sun.image.codec.jpeg.JPEGEncodeParam
Sets the mapping between a component and it's AC Huffman Table.
setACHuffmanTable(int, JPEGHuffmanTable) - Method in interface com.sun.image.codec.jpeg.JPEGEncodeParam
Sets the AC Huffman coding table at index to the table provided.
setDCHuffmanComponentMapping(int, int) - Method in interface com.sun.image.codec.jpeg.JPEGEncodeParam
Sets the mapping between a component and it's DC Huffman Table.
setDCHuffmanTable(int, JPEGHuffmanTable) - Method in interface com.sun.image.codec.jpeg.JPEGEncodeParam
Sets the DC Huffman coding table at index to the table provided.
setDensityUnit(int) - Method in interface com.sun.image.codec.jpeg.JPEGEncodeParam
Set the pixel size units This value is copied into the APP0 marker (if that marker is written).
setHorizontalSubsampling(int, int) - Method in interface com.sun.image.codec.jpeg.JPEGEncodeParam
Set the horizontal subsample factor for the given component.
setImageInfoValid(boolean) - Method in interface com.sun.image.codec.jpeg.JPEGEncodeParam
Set the flag indicating the validity of the table information in the ParamBlock.
setJPEGDecodeParam(JPEGDecodeParam) - Method in interface com.sun.image.codec.jpeg.JPEGImageDecoder
Sets the JPEGDecodeParam object used to determine the features of the decompression performed on the JPEG encoded data.
setJPEGEncodeParam(JPEGEncodeParam) - Method in interface com.sun.image.codec.jpeg.JPEGImageEncoder
Set the JPEGEncodeParam object that is to be used for future encoding operations.
setMarkerData(int, byte[][]) - Method in interface com.sun.image.codec.jpeg.JPEGEncodeParam
Sets the marker data to be written to the output data stream.
setQTable(int, JPEGQTable) - Method in interface com.sun.image.codec.jpeg.JPEGEncodeParam
Sets the coefficient quantization tables at index passed.
setQTableComponentMapping(int, int) - Method in interface com.sun.image.codec.jpeg.JPEGEncodeParam
Sets the mapping between a component and it's Quantization Table.
setQuality(float, boolean) - Method in interface com.sun.image.codec.jpeg.JPEGEncodeParam
This creates new Quantization tables that replace the currently installed Quantization tables.
setRestartInterval(int) - Method in interface com.sun.image.codec.jpeg.JPEGEncodeParam
Set the MCUs per restart, or 0 for no restart markers.
setTableInfoValid(boolean) - Method in interface com.sun.image.codec.jpeg.JPEGEncodeParam
Set the flag indicating the validity of the image information in the ParamBlock.
setVerticalSubsampling(int, int) - Method in interface com.sun.image.codec.jpeg.JPEGEncodeParam
Set the vertical subsample factor for the given component.
setXDensity(int) - Method in interface com.sun.image.codec.jpeg.JPEGEncodeParam
Set the horizontal pixel density This value is written into the APP0 marker.
setYDensity(int) - Method in interface com.sun.image.codec.jpeg.JPEGEncodeParam
Set the vertical pixel density.
Overview Package Class Use Tree Deprecated Index Help
A C D E G I J N S T
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


T-Index (Other API Bundled with the Java 2 SDK)

PREV LETTER NEXT LETTER FRAMES NO FRAMES
A C D E G I J N S T

T

TruncatedFileException - exception com.sun.image.codec.jpeg.TruncatedFileException.
Signals that a truncated file was detected.
TruncatedFileException(BufferedImage) - Constructor for class com.sun.image.codec.jpeg.TruncatedFileException
Constructs a TruncatedFileException/code> with the partially decoded BufferedImage.
TruncatedFileException(Raster) - Constructor for class com.sun.image.codec.jpeg.TruncatedFileException
Constructs an TruncatedFileException with the partially decoded Raster
Overview  Package  Class  Use  Tree  Deprecated   Index  Help
 PREV LETTER   NEXT LETTER FRAMES    NO FRAMES
A C D E G I J N S T
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Java 2D(TM) 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 Page for Sun Microsystems, Inc.

Sun Microsystems, Inc.

Copyright 1996-1999 Sun Microsystems, Inc.
901 San Antonio Road, Palo Alto, California 94303-4900 U.S.A.

All rights reserved. Copyright in this document is owned by Sun Microsystems, Inc.

Sun Microsystems, Inc. (SUN) hereby grants to you a fully-paid, nonexclusive, nontransferable, perpetual, worldwide limited license (without the right to sublicense) under SUN's intellectual property rights that are essential to practice this specification. This license allows and is limited to the creation and distribution of clean room implementations of this specification that (i) include a complete implementation of the current version of this specification without subsetting or supersetting, (ii) implement all the interfaces and functionality of the standard java.* packages as defined by SUN, without subsetting or supersetting, (iii) do not add any additional packages, classes or methods to the java.* packages (iv) pass all test suites relating to the most recent published version of this specification that are available from SUN six (6) months prior to any beta release of the clean room implementation or upgrade thereto, (v) do not derive from SUN source code or binary materials, and (vi) do not include any SUN binary materials without an appropriate and separate license from SUN.

RESTRICTED RIGHTS LEGEND

Use, duplication, or disclosure by the U.S. Government is subject to restrictions of FAR 52.227-14(g)(2)(6/87) and FAR 52.227-19(6/87), or DFAR 252.227-7015(b)(6/95) and DFAR 227.7202-1(a).

This software and documentation 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.

SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.

TRADEMARKS

Sun, the Sun logo, Sun Microsystems, SunNet Manager, SunCore, SunWeb, Sun Workshop, Sun Workstation, Java, the Java Coffee Cup logo, JavaSoft, JavaBeans, HotJava, HotJava Views, Java WorkShop, Visual Java, JDK and all Java-based trademarks and logos, Solaris, the Solaris sunburst design, SolarNet, Solstice, NEO, Joe, Netra, NFS, PC-NFS, ONC, ONC+, OpenWindows, SNM, The Network Is The Computer, ToolTalk, Ultra, Ultracomputing, Ultraserver, Where The Network Is Going, and XView, are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries.

UNIX is a registered trademark in the United States and other countries, exclusively licensed through X/Open Company, Ltd. OPEN LOOK® is a registered trademark of Novell, Inc.

All SPARC trademarks are used under license and are trademarks or registered trademarks of SPARC International, Inc. in the United States and other countries. Products bearing SPARC trademarks are based upon an architecture developed by Sun Microsystems, Inc.

The OPEN LOOK® and Sun(TM) Graphical User Interfaces were developed by Sun Microsystems, Inc. for its users and licensees. Sun acknowledges the pioneering efforts of Xerox in researching and developing the concept of visual or graphical user interfaces for the computer industry. Sun holds a non-exclusive license from Xerox to the Xerox Graphical User Interface, which license also covers Sun's licensees who implement OPEN LOOK GUIs and otherwise comply with Sun's written license agreements.

X Window System is a trademark of the X Consortium, Inc.

OpenStep is a trademark owned by NeXT and is used under license.

THIS PUBLICATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.

THIS PUBLICATION COULD INCLUDE TECHNICAL INACCURACIES OR TYPOGRAPHICAL ERRORS. CHANGES ARE PERIODICALLY ADDED TO THE INFORMATION HEREIN; THESE CHANGES WILL BE INCORPORATED IN NEW EDITIONS OF THE PUBLICATION. SUN MICROSYSTEMS, INC. MAY MAKE IMPROVEMENTS AND/OR CHANGES IN THE PRODUCT(S) AND/OR THE PROGRAM(S) DESCRIBED IN THIS PUBLICATION AT ANY TIME.

For further information on Intellectual Property matters, see Terms of Use or contact Sun Legal Department:

  • Trademarks, Karrie Malouf at (650) 336-7419
  • Patents at 415-336-0069


Contents | Previous | Next Programmer's Guide to the JavaTM 2D API

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:

  1. 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.
  2. The coordinates of the Shape’s path are transformed from user space into device space according to the transform attribute in the Graphics2D context.
  3. The Shape’s path is clipped using the clip attribute in the Graphics2D context.
  4. 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:

  1. The Stroke is applied to the rectangle’s outline.
  2. The stroked outline is converted to a Shape object.
  3. 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:

  1. Determines what pixels comprise the Shape.
  2. Gets the color of each pixel from the Paint object.
  3. Converts the color to an appropriate pixel value for the output device.
  4. 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:

  1. 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.”)
  2. 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:

  1. Create a GradientPaint object.
  2. Call Graphics2D.setPaint.
  3. Create the Shape.
  4. 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:

  1. Create a TexturePaint object.
  2. Call Graphics2D.setPaint.
  3. Create the Shape.
  4. 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:

  1. Create a Shape that represents the area you want to render.
  2. Call Graphics2D.setClip to use the shape as the clipping path for the Graphics2D context.

To shrink the clipping path:

  1. Create a Shape that intersects the current clipping path.
  2. 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:

  1. 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.
  2. Get a rotation transform by calling AffineTransform. getRotateInstance.
  3. 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.
  4. Create a Rectangle2D.Float object.
  5. Call Graphics2D.draw to render the rectangle.
  6. 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:

  1. Create an AlphaComposite object by calling getInstance and specifying the SRC_OVER rule.
    2. AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER);
  2. 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:

  1. Create a BasicStroke object
  2. Call Graphics2D.setStroke
  3. Create the Shape.
  4. 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:

  1. Set the fill color or pattern on the graphics context using
    Graphics2D.setColor or Graphics2D.setPaint.
  2. Create the Shape.
  3. 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 Programmer's Guide to the JavaTM 2D API
JavaTM 2 SDK, Standard Edition, 1.4 version

Copyright © 2003 Sun Microsystems, Inc. All rights reserved.


Java 2DTM API Overview 1

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 © 2003 Sun Microsystems, Inc. All rights reserved.


Contents | Previous | Next Programmer's Guide to the JavaTM 2D API

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.

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 Programmer's Guide to the JavaTM 2D API
JavaTM 2 SDK, Standard Edition, 1.4 version

Copyright © 2003 Sun Microsystems, Inc. All rights reserved.


Contents | Previous | Next Programmer's Guide to the JavaTM 2D API

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://developer.java.sun.com/developer/onlineTraining/Graphics/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:

  1. Create a Font object.,
  2. Create the AffineTransform you want to apply to the Font.
  3. 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 Programmer's Guide to the JavaTM 2D API
JavaTM 2 SDK, Standard Edition, 1.4 version

Copyright © 2003 Sun Microsystems, Inc. All rights reserved.


Contents | Previous | Next Programmer's Guide to the JavaTM 2D API

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:

  1. Using Shapes, construct the Areas to be combined.
  2. 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 Programmer's Guide to the JavaTM 2D API
JavaTM 2 SDK, Standard Edition, 1.4 version

Copyright © 2003 Sun Microsystems, Inc. All rights reserved.


Contents | Previous | Next Programmer's Guide to the JavaTM 2D API

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 Programmer's Guide to the JavaTM 2D API
JavaTM 2 SDK, Standard Edition, 1.4 version

Copyright © 2003 Sun Microsystems, Inc. All rights reserved.


Contents | Previous | Next Programmer's Guide to the JavaTM 2D API

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 Programmer's Guide to the JavaTM 2D API
JavaTM 2 SDK, Standard Edition, 1.4 version

Copyright © 2003 Sun Microsystems, Inc. All rights reserved.


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:

Contents | Previous | Next Programmer's Guide to the JavaTM 2D API

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://java.sun.com/docs/books/tutorial/2d/index.html
  • The 2D Text Tutorial. Available online from the Java Developer Connection:
    http://developer.java.sun.com/developer/onlineTraining/Graphics/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 Programmer's Guide to the JavaTM 2D API
    JavaTM 2 SDK, Standard Edition, 1.4 version

    Copyright © 2003 Sun Microsystems, Inc. All rights reserved.


Contents | Previous | Next Programmer's Guide to the JavaTM 2D API

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:

  1. Get a new PrinterJob object by calling PrinterJob.getPrinterJob.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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:

  1. Implement the Printable interface to provide a page painter that can render each page to be printed.
  2. Create a PrinterJob.
  3. Call setPrintable to tell the PrinterJob how to print your document.
  4. 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 Programmer's Guide to the JavaTM 2D API
JavaTM 2 SDK, Standard Edition, 1.4 version

Copyright © 2003 Sun Microsystems, Inc. All rights reserved.


Java Accessibility

Java logo

JavaTM Accessibility

 Java 2 SDK Contents

Java Accessibility API

With the Java Accessibility API, developers can easily create Java applications that are accessible to disabled persons. Accessible Java applications are compatible with assistive technologies such as screen readers, speech recognition systems, and refreshable braille displays.

The Java Accessibility API (JAAPI) is one of the core parts of the Java Foundation Classes (JFC). The JFC are a comprehensive set of graphical user interface components and foundation services designed to simplify deployment of Internet, intranet and desktop applications. The JAAPI makes GUI component information available to assistive technologies, giving users alternative presentation and control of Java applications.

Java Accessibility Utilities

The Java Accessibility Utilities help assistive technologies take advantage of the Java Accessibility API. The Utilities monitor events related to UI components. They also help assistive technologies get additional information about a GUI, such as the current position of the mouse, or the window that currently has focus.

The Utilities are released separately from the JFC, but they can be downloaded from the JFC Home Page.

Keyboard Navigation Support

The interactive user interface components provide a full set of keyboard bindings that enable mouseless navigation, edit, and control of the components. No special efforts are required of the developer to enable these capabilities and if the developer so desires they can easily change any keybinding.

Pluggable Look and Feel

The Java Foundation Classes implement a Pluggable Look and Feel architecture. This architecture allows non-visual manifestations of a user interface to replace or enhance the visual presentation of an application. The expression of the user interface is separated from the underlying structure and data of each individual component. This is accomplished by separating the user interface of the component from its model. The model of a component is the structure which encapsulates the state and information that is presented to the user by the user interface. More information on this architecture can be found in The Swing Connection.

Java Accessibility Documentation

  • Accessibility Enhancements in the Java 2 Platform, v1.4
  • Accessibility Properties
  • Java Accessibility API Specification

For More Information

  • Java Accessibility Utilities
    The Utilities help assistive technologies take advantage of the Java Accessibility API.
  • Java Access Bridge for Microsoft Windows
    The Java Access Bridge for Microsoft Windows makes Java applications visible to assistive technologies on Windows.
  • Assistive Technology Defined
  • The JFC Home Page
  • Sun Microsystems' Accessibility Program

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: access@sun.com 		Sun


Accessibility - New Features

Java logo

Accessibility

New Features in the JavaTM 2 Platform, v1.4

 Java Accessibility
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 © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: access@sun.com 		Sun


Accessibility Properties

 Java Accessibility

Available Properties

The javax.accessibility package provides the following properties:
  • assistive_technologies
  • screen_magnifier_present
  • screen_reader_present

Loading Assistive Technologies

The assistive_technologies property specifies the assistive technologies to load into the JVM. It takes a comma-delimited list as input.

Indicating the Presence of a Screen Magnifier

When the screen_magnifier_present property is set to true, it 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. For example, on Microsoft Windows operating systems, the reference implementation of the Java 2DTM API checks this property and if true, turns off Microsoft DirectDraw to avoid problems with the screen magnifier. (Some screen magnifiers may not be able to magnify DirectDraw graphics.)

Indicating the Presence of a Screen Reader

When the screen_reader_present property is set to true, it 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.

Setting Properties

You can set a property at run time or in a properties file. To set a property at run time, enter a command such as the following:

java -Djavax.accessibility.screen_magnifier_present=true foo.class

The reference implementation includes an accessibility.properties file in the jre/lib directory. To set a property in the accessibility.properties file, add a line or lines such as the following:

assistive_technologies=Ferret,Monkey
screen_magnifier_present=true
screen_reader_present=true

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: access@sun.com 		Sun


AWT Enhancements

Java

AWT Enhancements in the JavaTM 2 SDK, v1.4

 Documentation Contents
Version 1.4 of the Java 2 SDK includes the following AWT enhancements:
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.
  • 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, Robot, 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
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 in the 1.3 release notes for AWT.

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-awt@java.sun.com 		Sun


Abstract Window Toolkit (AWT)

 Documentation Contents

The Abstract Window Toolkit (AWT) supports Graphical User Interface (GUI) programming. AWT features include:
  • a rich set of user interface components;
  • a robust event-handling model;
  • graphics and imaging tools, including shape, color, and font classes;
  • layout managers, for flexible window layouts that don't depend on a particular window size or screen resolution;
  • data transfer classes, for cut-and-paste through the native platform clipboard.
The AWT is part of the Java Foundation Classes (JFC). For other JFC features, see below.

Enhancements

  • AWT Enhancements in the Java 2 SDK, v1.4
  • AWT Enhancements in the Java 2 SDK, v1.3

Using the AWT

The Overview and Demos were originally written for programmers making the transition from 1.0 to 1.1, and most of the documents have not been updated recently. The programming techniques they describe are still applicable in the Java 2 platform.
  • Overview of Previous Enhancements
  • Programming Examples

On the Java Software web site:
  • Creating a User Interface (from the Java Tutorial).
  • The AWT Home Page

API References

  • java.awt Package
  • java.awt.event Package
  • java.awt.datatransfer Package

Other JFC APIs

  • Swing Components
  • Drag-and-Drop Data Transfer
  • 2D - Advanced graphics and imaging
  • Accessibility API

On the Java Software web site:
  • The JFC Home Page

Additional Specification

  • Focus Model Specification
Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved. Please send comments to: java-awt@java.sun.com Sun Microsystems, Inc
Java Software


AWT Native Interface

The AWT Native Interface

The Key to Rendering to an AWT Canvas from Native Code

The new JavaTM 2 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 2 Platform, 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're trying to port to Java uses a third-party library for a critical set of operations. If you don't have source rights to this library and you can't 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're 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's usually best to keep it intact until you're 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 doesn't know 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 can't 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 2 upgrade release (``Kestrel'') expected in early 2000. 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. ``myRenderingLib'' is the name we're using for the native shared library; for the Solaris operating environment, the actual name for the library file on disk is libmyRenderingLib.so .

Here's 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 2 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 1999 Sun Microsystems, Inc.,
 * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
 * 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 1999 by Sun Microsystems, Inc.,
 * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
 * 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
 *
 * 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 1999 by Sun Microsystems, Inc.,
 * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
 * 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
#include
#include
#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 1999 by Sun Microsystems, Inc.,
 * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
 * 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
#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 © 1999 Sun Microsystems, Inc. All Rights Reserved.

 Sun


AWT Enhancements

Java

AWT Enhancements in the JavaTM 2 SDK, v1.3

 Documentation Contents
Version 1.3 of the Java 2 SDK includes the following AWT enhancements:
Multiple Monitor Support
New Class java.awt.Robot
New Event Masks for PaintEvents and InvocationEvents
Paint Coalescing
Printing API Enhancements
New Event Type for Tracking Changes to Component Hierarchies
AWT Native Interface
Multiple Monitor Support

You can now render on multiple screens by creating Frame, JFrame, Window, or JWindow objects with the GraphicsConfiguration of the target GraphicsDevice.

The new Frame constructor, Frame(GraphicsConfiguration), enables creation of a Frame object on a different screen device.

The new Window constructor, Window(Window, GraphicsConfiguration), constructs a new invisible window with the specified window as its owner and the GraphicsConfiguration of a screen device.

The new GraphicsConfiguration getBounds method returns the bounds of the GraphicsConfiguration in device coordinates. If you have a virtual device, then the device coordinates returned from getBounds are virtual device coordinates.

Finally, the new Component getGraphicsConfiguration method returns the GraphicsConfiguration with which the Component was created.

In a virtual device configuration consisting of more than one physical screen device, the GraphicsConfiguration objects' coordinates are relative to the virtual coordinate system. For this reason, virtual coordinates must be used when calling the setLocation method of a Frame or Window. Similarly, calling getBounds of a GraphicsConfiguration in a virtual device environment returns virtual device coordinates.

The following code sample creates a JFrame object for each GraphicsConfiguration on each screen device in the GraphicsEnvironment. It offsets the coordinates of the intended location of the JFrame with the bounds of the GraphicsConfiguration to ensure that the JFrame appears on the screen of the specified GraphicsConfiguration.

        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());
                    Canvas c = new Canvas(gc[i]);
                    Rectangle gcBounds = gc[i].getBounds();
                    int xoffs = gcBounds.x;
                    int yoffs = gcBounds.y;
                    f.getContentPane().add(c);
                    f.setSize(300, 150);
                    f.setLocation((i*50)+xoffs, (i*60)+yoffs);
                    f.show();
        }
    }
If the bounds of a GraphicsConfiguration is not taken into account in this sample, a JFrame would appear at location (i*50, i*60) on the primary screen, which might be different than the screen of the specified GraphicsConfiguration.

For more information on how the Java 2D API supports multi-screen environments, see Rendering in a Multi-Screen Environment in the Programmer's Guide to the Java 2D API.

New Class java.awt.Robot
New class java.awt.Robot has been added to the JavaTM 2 Platform. The Robot API is designed to make automated AWT and Swing testing possible. The Robot API allows code written in the Java programming language to generate low-level native mouse and keyboard input events. Because the events are generated at the operating system level (as opposed to the Java event queue or component level), they are indistinguishable from real user input to the rest of the AWT (both the native and Java-language portions).

Though designed to improve testability, the Robot API also provides other benefits:

  • Accessibility enabled applications will be able to give more feedback. For example, if the user acts on a screen object using voice commands, the mouse pointer can be moved to indicated the object being manipulated.
  • Enables the creation of computer-based training (CBT) and other demo type Java applications.

New Event Masks for PaintEvents and InvocationEvents

The new final static fields PAINT_EVENT_MASK and INVOCATION_EVENT_MASK have been added to class AWTEvent. These fields are now available for use by addAWTEventListener() to allow client applications to listen for paint events and invocation events.

Paint Coalescing

Painting performance has been enhanced through the implementation of paint coalescing. Areas that require repainting are now coalesced into a single, non-rectangular repaint area as they are posted to the event queue. This has the effect of batching repaints, executing multiple repaints simultaneously. Previously, paint events were queued up and executed in succession, even when the repaint areas overlapped.

Printing API Enhancements

Two new classes have been added to package java.awt.print:
  • JobAttributes
  • PageAttributes
Class JobAttributes controls properties of a print job such as destination, number of copies, page ranges, etc. Class PageAttributes controls attributes of a printed page such as paper size, orientation, print quality, etc.

These classes are used by a new method in class java.awt.Toolkit:

getPrintJob(Frame, String, JobAttributes, PageAttributes)
See Java AWT: Printing for more information on the printing API.

Support for using attributes will be added to the printing API in a future release of the Java platform.

New Event Type for Tracking Changes to Component Hierarchies

Several new classes have been added to the Java 2 Platform to provide a standardized way for components to track changes to their component hierarchy. The new API is a preferred alternative to that provided by javax.swing.event.AncestorEvent
  • displayability - whether a component has a peer
  • show state - whether a component is showing on the screen
  • ancestors additions to and deletions from the hieracrhy
  • ancestor resizes
  • ancestor moves
The new classes and interfaces implementing the new event types are:
  • java.awt.event.HierarchyEvent
  • java.awt.event.HierarchyListener
  • java.awt.event.HierarchyBoundsListener
  • java.awt.event.HierarchyBoundsAdapter
The following methods have been added to java.awt.Component:
  • addHierarchyListener
  • removeHierarchyListener
  • addHierarchyBoundsListener
  • removeHierarchyBoundsListener
  • processHierarchyEvent
  • processHierarchyBoundsEvent
The following fields have been added to java.awt.AWTEvent:
  • HIERARCHY_EVENT_MASK
  • HIERARCHY_BOUNDS_EVENT_MASK
Class java.awt.AWTEventMulticaster now implements interfaces HierarchyListener and HierarchyBoundsListener. In addition, it has the following new methods:
  • hierarchyChanged
  • ancestorMoved
  • ancestorResized
  • add(HierarchyListener, HierarchyListener)
  • add(HierarchyBoundsListener, HierarchyBoundsListener)
  • remove(HierarchyListener, HierarchyListener)
  • remove(HierarchyBoundsListener, HierarchyBoundsListener)

AWT Native Interface

The AWT Native Interface is a new interface for integrating native rendering engines with the Java 2 platform. The AWT Native Interface lets you design UIs with natively rendered components for best rendering performance.

In the most common usage, four steps are involved:

  1. Define a class that extends a Canvas .
  2. Declare the paint method as native and load its shared library in the static block.
  3. Use javah to generate a C/C++ header file for the native paint method. (See javah documentation for Windows and Solaris platforms.)
  4. Write the native paint method and build it as a shared library.
Header files associated with the AWT Native Interface are in the SDK's include directory. They are
  • include/jawt.h on both Windows and SolarisTM platforms
  • include/windows/jawt_md.h in the Windows SDK only
  • include/solaris/jawt_md.h on Solaris SDK only
These headers are not part of the official specification of the Java 2 Platform. The headers are provided as a convenience to developers who want a standardized way to access native drawing functionality.

For further information and sample code, see The AWT Native Interface.

Copyright © 1999 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-awt@java.sun.com 		Sun


Java AWT: Data Transfer

Juggling Duke logo Java AWT: Data Transfer

Last updated: August 13, 1997

Purpose

 Typical GUI users today expect to be able to transfer data between applications using operations like cut/copy/paste and drag-and-drop. The only mechanism for this in the current Java environment is through whatever facilities the AWT native widgets (TextField, TextArea) provide by default. There are many cases however, where an application needs to enable these operations outside of these native widgets, and therefore the Java platform needs to provide an API to enable basic data transfer capabilities. This document defines a baseline data transfer capability for Java objects on top of which various transfer-protocols can be built. This document also describes APIs for two of those higher-level transfer-protocols, Clipboard and Drag-and-Drop.

Note: The Clipboard API will be included in JDK1.1, however the Drag-and-Drop API will be in the following release (due to time constraints on 1.1). We are including the document on Drag-and-Drop here so that the Java Beans document can refer to it and we can get as much early feedback as possible.

Java Data Transfer

Design Goals for Transfer API

 The design goals for the data transfer API are the following:
  • Keep simple tasks simple (as always with Java APIs).
  • Ensure API is general enough to enable existing and future transfer models.
  • Allow dynamic data types to be created, registered, and transferred.
  • Enable data transfer both within and across process space boundaries.
  • Enable data transfer between Java and non-Java applications.
  • Support the transfer of Java Beans

Transfer API Overview

Transferable Objects

The API centers on an interface which is implemented by objects which are to be transferred.:
    java.awt.datatransfer.Transferable
A transferable object must be able to provide a list of formats (called " data flavors") for which it can provide the data, ordered from the most-richly descriptive flavor to the least. It must also be able to return the data (in the form of an Object reference) when requested in a particular flavor (or throw an exception if that flavor is not supported or the data is no longer available).

Convenience classes which implement the Transferable interface for common data types will be provided to make transfer of these common types easy for the developer. For example:

    java.awt.datatransfer.StringSelection

The purpose of this API is to ensure that once the work goes into making a particular element or type of data transferable, it can be easily be passed around using any of the higher-level transfer protocols (clipboard, drag-and-drop, etc.).

Data Flavors

A typical aspect of common data transfer operations (clipboard, Drag-and-Drop) is a negotiation between the provider and the requestor on which flavor to transfer the data in. For example, when html text is selected in a browser and then copied/pasted into a separate word-processing application, the browser would typically offer the data in multiple flavors (probably html formatted text and plain ASCII) in order to maximize the number of potential target applications for a paste operation.

This negotiation requires the definition of a data typing name-space such that these various flavors and data-types can be uniquely defined and recognized by distinct applications. In order to avoid the confusion of such overloaded terms such as "format", we have chosen the term "flavor" to represent this concept.

A data flavor is represented by an object which encapsulates all necessary information about a particular flavor to enable flavor negotiation and transfer between applications:

    java.awt.datatransfer.DataFlavor

This information includes a logical name for the flavor (to enable programmatic identification), a human-presentable name (which be used to present to the user and would be localizable), and the representation class which is used to define the class of object used to actually transfer the data.

MIME Types as Logical Names

We are currently planning on using MIME type/subtype parameter notation to represent the logical name for data flavors (See RFC 1521 for the MIME type specification). We believe it is preferable to embrace an existing Internet standard rather than creating "yet another data typing namespace" for the Java environment.

MIME type registration is currently handled by a third-party, the Internet Assigned Numbers Authority (IANA), enabling developers to easily locate the standard type/subtype name used for published data formats. Fortunately, formal registration is not required in order to define new MIME type/subtype names for less common formats (we agree that such a formal requirement would not be acceptable for basic Java data transfer). New type names can be created without formal registration by prepending "x-" in front of the name.

Representation Class

Since the method in Transferable which actually returns the data:
    Object getTransferData(DataFlavor flavor)
is loosely defined to return an instance of class "Object" (for maximum flexibility), the DataFlavor's defined representation class becomes important to the receiving end of a transfer operation because it allows the returned object to be decoded unambiguously.

The current DataFlavor class defines two general kinds of data flavors:

  • DataFlavor which represents a specific Java class:
         MIME-type="application/x-java-serialized-object; class=<implemenation class>"

         RepresentationClass=<implemenation class>

        e.g. a DataFlavor representing an AWT GUI component:
         MIME-type="application/x-java-serialized-object; class=java.awt.Component"

         RepresentationClass=java.awt.Component

      If the requesting side of a transfer operation asks for the data in this flavor,
          it will be handed back an instance of the Component class.
  • DataFlavor which represents a particular MIME-type:
         MIME-type="application/<mime-subtype>"

         RepresentationClass=java.io.InputStream

        e.g. a DataFlavor representing RTF text:
         MIME-type="application/rtf"

         RepresentationClass=java.io.InputStream

      If the requesting side of a transfer operation asks for the data in this fla-vor,
          it will be handed back an InputStream instance from which it can read/
          parse the RTF formatted text.

For a given MIME-type (type #2 above), a Java program is free to create multiple flavors with different representation classes. For example, in addition to providing the flavor for the MIME-type "application/rtf" above, a program could specify another flavor:

        e.g. a DataFlavor representing RTF text:
         MIME-type="application/rtf"

         RepresentationClass=foobar.fooRTF

Rationale Behind Encapsulation

At first it may seem that using a class to define a data flavor (rather than simply the MIME-type string) is over-kill. We believe this encapsulation to be an advantage for the following reasons:
  1. Usability - There are attributes that should be associated with data formats, like the human-presentable name for the data format, that could only be associated with a logical string baroquely. With a DataFlavor object, these attributes are directly associated with the encapsulating DataFlavor object
  2. Convenience - Using DataFlavor objects gives us a convenient way of handling data format comparisons. An isMimeTypeEqual() method relieves the programmer or having to remember to convert his MIME types into a canonical form. (This is an issue because MIME type, subtype, and parameter names are case insensitive and parameters can appear in any order.).
  3. Extensibility - The abstraction will allow us to extend a flavor's attributes/methods over time if necessary.
  4. Performance - Motif and Windows use atoms rather than strings to identify data formats. Using an object to identify each data format gives us a handy place to cache the atom corresponding to the MIME type name, reducing the number of atom internments required. Similarly, the results of mapping MIME types like "text/plain" to platform-specific clipboard formats like CF_TEXT on Windows and 'TEXT' on Macintosh can be cached.

The DataFlavor concept may seem complex and confusing, however our intent is to make this as convenient as possible for developers by defining a set of commonly used data flavors.

Multiple Item Transfer

It is not uncommon for a transfer protocol to support the transfer of multiple distinct pieces of data in a single transfer operation (i.e. like a drag-and-drop of multiple file icons from a file manager application). The transfer API needs to support some form of simultaneous transfer of multiple data items and the current proposal is to encapsulate this capability using an implementation of Transferable which can deal with a collection of distinct data objects. This plan is currently under more rigorous investigation and will be discussed in more detail in a future revision of this proposal.

Code Example for Creating a Transferable Object

 The following code shows the StringSelection class source, which is an example of how the API in this proposal would be used to create a class which is capable of transferring plain unicode text.

package java.awt.datatransfer;

import java.io.*;

/**
 * A class which implements the capability required to transfer a
 * simple java String in plain text format.
 */
public class StringSelection implements Transferable, ClipboardOwner {

    final static int STRING = 0;
    final static int PLAIN_TEXT = 1;

    DataFlavor flavors[] = {DataFlavor.stringFlavor, DataFlavor.plainTextFlavor};

    private String data;

    /**
     * Creates a transferable object capable of transferring the
     * specified string in plain text format.
     */
    public StringSelection(String data) {
        this.data = data;
    }

    /**
     * Returns the array of flavors in which it can provide the data.
     */
    public synchronized DataFlavor[] getTransferDataFlavors() {
    return flavors;
    }

    /**
     * Returns whether the requested flavor is supported by this object.
     * @param flavor the requested flavor for the data
     */
    public boolean isDataFlavorSupported(DataFlavor flavor) {
    return (flavor.equals(flavors[STRING]) || flavor.equals(flavors[PLAIN_TEXT]));
    }

    /**
     * If the data was requested in the "java.lang.String" flavor, return the
     * String representing the selection, else throw an UnsupportedFlavorException.
     * @param flavor the requested flavor for the data
     */
    public synchronized Object getTransferData(DataFlavor flavor)
            throws UnsupportedFlavorException, IOException {
    if (flavor.equals(flavors[STRING])) {
        return (Object)data;
    } else if (flavor.equals(flavors[PLAIN_TEXT])) {
        return new StringReader(data);
    } else {
        throw new UnsupportedFlavorException(flavor);
    }
    }

    public void lostOwnership(Clipboard clipboard, Transferable contents) {
    }
}

Clipboard

 Providing Cut/Copy/Paste operations as a means for transferring data both within and between applications is now a common and expected feature in most applications. The AWT API in JDK1.0 does not currently provide any facilities for this basic clipboard operation (except where is exists by default in native text widgets) and this ability is critical for Java programs to be well-integrated into a user's environment.

Design Goals for Clipboard API

 Following are the design goals of this API:
  • Make it *extremely* easy for programs to implement cut/copy/paste of text
  • Enable clipboard operations which interact with the platform's native clipboard
  • Enable the creation/use of private clipboards for inter-app clipboard operations

Clipboard API Overview

 The clipboard API provides a standard mechanism to implement cut/copy/paste operations in Java programs. Different clipboards can be created and named for different purposes (a program might wish to create it's own private clipboard), however there will be a single clipboard instance (named "System") that will be the one which interfaces with the platform's native facilities to allow Java programs to transfer data to/from non-Java applications.

The clipboard architecture relies on the data transfer mechanism defined by the Java Data Transfer API. The Clipboard API includes a single class which implements the data transfer model for a standard clipboard:

    java.awt.datatransfer.Clipboard

and an interface which is implemented by any classes which will be writing data to the clipboard:

    java.awt.datatransfer.ClipboardOwner

The Clipboard class provides two basic methods for reading-from/writing-to the clipboard:

    void setContents(Transferable content, ClipboardOwner owner)

    Transferable getContents(Object requestor)

The ClipboardOwner interface consists of a single method which is called if another object asserts ownership of the clipboard:

    void lostOwnership(Clipboard clipboard)

To make the job of implementing clipboard operations on common data types easy for the developer, there will be convenience classes provided which implement the ClipboardOwner interface in a standard way:

    java.awt.datatransfer.StringSelection

The following method in java.awt.Toolkit will provide access to the clipboard instance which interacts with the native platform facilities:

    Clipboard getSystemClipboard();

Implementing Cut/Copy/Paste using Clipboard API

 The general sequence of operations for a program implementing "cut"/"copy":
  1. Instantiate an object which implements the Transferable interface for the data to be cut/copied.
  2. Instantiate an object which implements the ClipboardOwner interface (may be the same object as that which implements Transferable)
  3. Pass this Transferable and ClipboardOwner objects to the clipboard's setContents() method; this establishes ownership of the clipboard.
  4. Handle the call to your clipboard owner's lostOwnership() method, which will be called if/when another object asserts ownership of the clipboard (this method can be empty if you don't need to do anything when you lose ownership)

The general sequence for implementing "paste":

  1. Request the contents of the clipboard using its getContents() method, which returns a handle to an object which implements the Transferable interface.
  2. Request the list of available flavors for the data from the transferable object using its getTransferDataFlavors() method.
  3. Retrieve the data in the desired available flavor using the transferable object's getTransferData() method.

Lazy Data Model

The clipboard model implies a level of persistence for the clipboard's contents, however to avoid unnecessary performance penalties at cut/copy time, the data may not actually be transferred from the owner until it has been requested by a consumer (this is known as a "lazy" data model). If the clipboard owner is destroyed, then it may be necessary to attempt to retrieve the data and store it within the clipboard to ensure its availability after the provider has exited. The clipboard owner should not, however, make any assumptions about when the transfer will occur and should attempt to keep the data available until its lostOwnership() method is called (if it cannot keep the data available indefinitely, then it should throw an IOException if the data is requested but no longer available).

Security

 There are definite security issues with allowing downloaded applets access to the native system's clipboard, both in terms of being able to read it's contents (which could be sensitive) and in terms of writing to it. Initially, untrusted applets will not be allowed direct access to the *System* clipboard (there will be a SecurityManager method for clipboard access). We are exploring a mechanism which would allow untrusted applets to participate in clipboard operations if the initiation of the operation was from a user-generated event (such as a "cut" or "paste" keyboard event).

Sample Code using Clipboard API

The following is a simple example of a program which is implementing cut/copy/paste of plain text

(note: for simplicity this example uses a TextArea as the source/dest for the copy/paste operation; on most platforms, cut/copy/paste is already implemented for the TextArea and TextField classes within the native peers)

import java.awt.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.datatransfer.*;

public class ClipboardTest extends Frame
                           implements ClipboardOwner, ActionListener {

    TextArea srcText, dstText;
    Button copyButton, pasteButton;

    Clipboard clipboard = getToolkit().getSystemClipboard();

    public ClipboardTest() {
        super("Clipboard Test");
        GridBagLayout gridbag = new GridBagLayout();
        GridBagConstraints c = new GridBagConstraints();
        setLayout(gridbag);

        srcText = new TextArea(8, 32);
        c.gridwidth = 2;
        c.anchor = GridBagConstraints.CENTER;
        gridbag.setConstraints(srcText, c);
        add(srcText);

        copyButton = new Button("Copy Above");
        copyButton.setActionCommand("copy");
        copyButton.addActionListener(this);
        c.gridy = 1;
        c.gridwidth = 1;
        gridbag.setConstraints(copyButton, c);
        add(copyButton);

        pasteButton = new Button("Paste Below");
        pasteButton.setActionCommand("paste");
        pasteButton.addActionListener(this);
        pasteButton.setEnabled(false);
        c.gridx = 1;
        gridbag.setConstraints(pasteButton, c);
        add(pasteButton);

        dstText = new TextArea(8, 32);
        c.gridx = 0;
        c.gridy = 2;
        c.gridwidth = 2;
        gridbag.setConstraints(dstText, c);
        add(dstText);

        pack();
    }

    public void actionPerformed(ActionEvent evt) {
        String cmd = evt.getActionCommand();

        if (cmd.equals("copy")) {
           // Implement Copy operation
           String srcData = srcText.getText();
           if (srcData != null) {
                StringSelection contents = new StringSelection(srcData);
                clipboard.setContents(contents, this);
                pasteButton.setEnabled(true);
            }
        } else if (cmd.equals("paste")) {
            // Implement Paste operation
            Transferable content = clipboard.getContents(this);
            if (content != null) {
                try {
                    String dstData = (String)content.getTransferData(
                                                DataFlavor.stringFlavor);
                    dstText.append(dstData);
                } catch (Exception e) {
                    System.out.println("Couldn't get contents in format: "+
                           DataFlavor.stringFlavor.getHumanPresentableName());
                }
             }
        }
    }
    public void lostOwnership(Clipboard clipboard, Transferable contents) {
       System.out.println("Clipboard contents replaced");
    }
     public static void main(String[] args) {
        ClipboardTest test = new ClipboardTest();
        test.show();
     }
}

Drag and Drop

 The Drag-and-drop specification which was previously contained in this document has been superceded by the Drag-and-Drop documentation in the Java 2 SDK documentation.

Send feedback to:java-awt@java.sun.com
Copyright © 1996, 1999, Sun Microsystems, Inc. All rights reserved.


Java AWT: Desktop Colors

Duke logo holding a pencil Java AWT: Desktop Colors

Last Updated: February 3, 1997

Purpose

 It is common for platform desktops (Windows95, Solaris/CDE, etc.) to provide a color scheme for objects on the desktop, and typically this scheme is configurable by the user. It is usually desirable to have applications running on that desktop use that color scheme in order to maintain visual consistency.

The AWT attempts to set appropriate default colors for its components, but there is currently no convenient way for a Java program to query and use those colors directly. This is particularly a problem when creating custom components where you'd like to ensure that the background, shadow, and font colors all match the rest of the desktop. As of version 1.1 of the JavaTM platform, the AWT provides a simple API for accessing and using these desktop colors.

Desktop Color API

The API involves introducing a new type of "symbolic" color, which is represented by a subclass of java.awt.Color:

        java.awt.SystemColor
A SystemColor object can be used just like any other Color object, the only difference being that the actual value that represents its current color may change dynamically (on systems which support dynamic notification when the user changes the color scheme).

SystemColor objects are defined by the system and cannot be instantiated by Java programs.

Range of Colors

The SystemColor class provides a standard set of these symbolic colors that represent each distinct type of coloration on the desktop. These symbolic color objects are created automatically and stored statically in java.awt.SystemColor:
    public final static SystemColor desktop; // Background color of desktop

    public final static SystemColor activeCaption; // Background color for captions

    public final static SystemColor activeCaptionText; // Text color for captions

    public final static SystemColor activeCaptionBorder; // Border color for caption text

    public final static SystemColor inactiveCaption; // Background color for inactive captions

    public final static SystemColor inactiveCaptionText; // Text color for inactive captions

    public final static SystemColor inactiveCaptionBorder; // Border color for inactive captions

    public final static SystemColor window; // Background for windows

    public final static SystemColor windowBorder; // Color of window border frame

    public final static SystemColor windowText; // Text color inside windows

    public final static SystemColor menu; // Background for menus

    public final static SystemColor menuText; // Text color for menus

    public final static SystemColor text; // background color for text

    public final static SystemColor textText; // text color for text

    public final static SystemColor textHighlight; // background color for highlighted text

    public final static SystemColor textHighlightText; // text color for highlighted text

    public final static SystemColor control; // Background color for controls

    public final static SystemColor controlText; // Text color for controls

    public final static SystemColor controlLtHighlight; // Light highlight color for controls

    public final static SystemColor controlHighlight; // Highlight color for controls

    public final static SystemColor controlShadow; // Shadow color for controls

    public final static SystemColor controlDkShadow; // Dark shadow color for controls

    public final static SystemColor inactiveControlText; // Text color for inactive controls

    public final static SystemColor scrollbar; // Background color for scrollbars

    public final static SystemColor info; // Background color for spot-help text

    public final static SystemColor infoText; // Text color for spot-help text

If a Java program either sets the foreground or background of a component to be one of these symbolic colors, or uses one of these for rendering, the current value for that symbolic color will be used.

Not all platforms support distinct colors for each of these symbolic names. In the cases where a symbolic color is not supported by a platform, it is mapped to the most appropriate default. These colors are guaranteed to be non-null.

The AWT base components will be modified to use these symbolic colors in order to provide more consistent default integration with the desktop. Java programs written for 1.0 which make any assumptions about the default color of components (i.e. assume they will be "gray") may not render correctly under 1.1. It is always important to query the component for its background/foreground colors within paint() methods for this reason.

One-time vs. Dynamic Updates

At a minimum, these colors are initialized dynamically when the toolkit is first loaded. Some desktops provide dynamic update capabilities such that the AWT can detect when the user changes the color scheme and then update all these symbolic colors on the fly. However, this is platform-specific and is not a guaranteed feature of this interface.

Sample Code

 Following is an example of a custom component (a separator) which uses this API:

import java.awt.*;

//
// Oversimplified separator class for creating 3D horizontal
// line separators
//
public class Separator extends Component {

    public Separator(int length, int thickness) {
       super();
       setSize(length, thickness);
       setBackground(SystemColor.control);
    }

    public void paint(Graphics g) {
       int x1, y1, x2, y2;
       Rectangle bbox = getBounds();

       x1 = 0;
       x2 = bbox.width - 1;
       y1 = y2 = bbox.height/2 - 1;

       g.setColor(SystemColor.controlShadow);
       g.drawLine(x1, y2, x2, y2);
       g.setColor(SystemColor.controlHighlight);
       g.drawLine(x1, y2+1, x2, y2+1);
    }

    public static void main(String[] args) {
        Frame f = new Frame("Separator Example");
        f.setSize(200, 100);
        f.setBackground(SystemColor.control);
        Separator sep = new Separator(200, 4);
        f.add("Center", sep);
        f.show();
    }
}

Send feedback to:java-awt@java.sun.com
Copyright © 1996, Sun Microsystems, Inc. All rights reserved.


Java AWT: Delegation Event Model

Duke logo holding a gun Java AWT: Delegation Event Model

Last updated: February 3, 1997

Purpose

 This document explains the rationale behind introducing a new event model into the AWT and describes specifically how the new model maps to the AWT API. This new model has also been adopted by the JavaBeans architecture for general event processing and is described at a high level in the JavaBeans Specification document.

The 1.0 Event Model

 The model for event processing in version 1.0 of the AWT is based on inheritance. In order for a program to catch and process GUI events, it must subclass GUI components and override either action() or handleEvent() methods. Returning "true" from one of these methods consumes the event so it is not processed further; otherwise the event is propagated sequentially up the GUI hierarchy until either it is consumed or the root of the hierarchy is reached. The result of this model is that programs have essentially two choices for structuring their event-handling code:
  1. Each individual component can be subclassed to specifically handle its target events. The result of this is a plethora of classes.
  2. All events for an entire hierarchy (or subset thereof) can be handled by a particular container; the result is that the container's overridden action() or handleEvent() method must contain a complex conditional statement in order to process the events.

Issues with the 1.0 Event Model

While the above model works fine for small applets with simple interfaces, it does not scale well for larger java programs for the following reasons:
  • The requirement to subclass a component in order make any real use of its functionality is cumbersome to developers; subclassing should be reserved for circumstances where components are being extended in some functional or visual way.
  • The inheritance model does not lend itself well to maintaining a clean separation between the application model and the GUI because application code must be integrated directly into the subclassed components at some level.
  • Since ALL event types are filtered through the same methods, the logic to process the different event types (and possibly the event targets in approach #2) is complex and error-prone. It is not uncommon for programs to have perplexing bugs that are the result of returning an incorrect result (true or false) from the handleEvent() method. This becomes an even greater problem as new event types are added to the AWT; if the logic of existing handleEvent() methods isn't set up to deal properly with unknown types, programs could potentially break in very unpredictable ways.
  • There is no filtering of events. Events are always delivered to components regardless of whether the components actually handle them or not. This is a general performance problem, particularly with high-frequency type events such as mouse moves.
  • For many components, the action() method passes a String parameter which is equivalent to either the label of the component (Button, MenuItem) or the item selected (List, Choice). For programs which use approach #2, this often leads to poor coding and unwieldy string-compare logic that doesn't localize well.

The Delegation Model

 Version 1.1 of the JavaTM platform introduced a new delegation-based event model in AWT in order to:
  • Resolve the problems mentioned previously
  • Provide a more robust framework to support more complex java programs.

Design Goals

 The primary design goals of the new model in the AWT are the following:
  • Simple and easy to learn
  • Support a clean separation between application and GUI code
  • Facilitate the creation of robust event handling code which is less error-prone (strong compile-time checking)
  • Flexible enough to enable varied application models for event flow and propagation
  • For visual tool builders, enable run-time discovery of both events that a component generates as well as the events it may observe
  • Support backward binary compatibility with the old model

Note: These goals are described from the particular perspective of the AWT. Since this model has also been designed to accommodate the JavaBeans architecture, the design goals from the JavaBeans perspective are described in the "Events" section of the JavaBeans Specification and may vary slightly from these goals.

Delegation Model Overview

Event types are encapsulated in a class hierarchy rooted at java.util.EventObject. An event is propagated from a "Source" object to a "Listener" object by invoking a method on the listener and passing in the instance of the event subclass which defines the event type generated.

A Listener is an object that implements a specific EventListener interface extended from the generic java.util.EventListener. An EventListener interface defines one or more methods which are to be invoked by the event source in response to each specific event type handled by the interface.

An Event Source is an object which originates or "fires" events. The source defines the set of events it emits by providing a set of set<EventType>Listener (for single-cast) and/or add<EventType>Listener (for mult-cast) methods which are used to register specific listeners for those events.

In an AWT program, the event source is typically a GUI component and the listener is commonly an "adapter" object which implements the appropriate listener (or set of listeners) in order for an application to control the flow/handling of events. The listener object could also be another AWT component which implements one or more listener interfaces for the purpose of hooking GUI objects up to each other.

Event Hierarchy

Events are no longer represented by a single Event class (like java.awt.Event) with numeric ids, but instead by a hierarchy of event classes. Each event class is defined by the data representing that event type or related group of events types.

Since a single event class may be used to represent more than one event type (i.e. MouseEvent represents mouse up, mouse down, mouse drag, mouse move, etc), some event classes may also contain an "id" (unique within that class) which maps to its specific event types.

The event classes contain no public fields; the data in the event is completely encapsulated by proper get<Attr>()/set<Attr>() methods (where set<Attr>() only exists for attributes on an event that could be modified by a listener).

Although these are the concrete set defined by the AWT, programs are free to define their own event types by subclassing either java.util.EventObject or one of the AWT event classes. Programs should choose event ID values which are greater than the constant:

        java.awt.AWTEvent.RESERVED_ID_MAX

Low-level vs. Semantic Events

The AWT provides two conceptual types of events: low-level and semantic.

A low-level event is one which represents a low-level input or window-system occurrence on a visual component on the screen. The low-level event classes defined by the AWT are as follows:

    java.util.EventObject

        java.awt.AWTEvent
            java.awt.event.ComponentEvent (component resized, moved, etc.)

            java.awt.event.FocusEvent (component got focus, lost focus)

            java.awt.event.InputEvent

                java.awt.event.KeyEvent (component got key-press, key-release, etc.)

                java.awt.event.MouseEvent (component got mouse-down, mouse-move, etc.)

            java.awt.event.ContainerEvent

            java.awt.event.WindowEvent

Semantic events are defined at a higher-level to encapsulate the semantics of a user interface component's model. The semantic event classes defined by the AWT are as follows:

    java.util.EventObject

        java.awt.AWTEvent

        java.awt.event.ActionEvent ("do a command")

        java.awt.event.AdjustmentEvent ("value was adjusted")

        java.awt.event.ItemEvent ("item state has changed")

        java.awt.event.TextEvent ("the value of the text object changed")

Note that these semantic events are not tied to specific screen-based component classes, but may apply across a set of components which implement a similar semantic model. For example, a Button object will fire an "action" event when it is pressed, a List object will fire an "action" event when an item is double-clicked, a MenuItem will fire an "action" event when it was selected from a menu, and a non-visual Timer object might fire an "action" when its timer goes off (the latter is a hypothetical case).

Event Listeners

An EventListener interface will typically have a separate method for each distinct event type the event class represents. So in essence, particular event semantics are defined by the combination of an Event class paired with a particular method in an EventListener. For example, the FocusListener interface defines two methods, focusGained() and focusLost(), one for each event type that FocusEvent class represents.

The API attempts to define a balance between providing a reasonable granularity of Listener interface types and not providing a separate interface for every single event type.

The low-level listener interfaces defined by the AWT are as follows:

    java.util.EventListener

        java.awt.event.ComponentListener

        java.awt.event.ContainerListener

        java.awt.event.FocusListener

        java.awt.event.KeyListener

        java.awt.event.MouseListener

        java.awt.event.MouseMotionListener

        java.awt.event.WindowListener

The semantic listener interfaces defined by the AWT are as follows:

    java.util.EventListener

        java.awt.event.ActionListener

        java.awt.event.AdjustmentListener

        java.awt.event.ItemListener

        java.awt.event.TextListener

Event Sources

Because the events fired by an event source are defined by particular methods on that object, it is completely clear from the API documentation (as well as by using run-time introspection techniques) exactly which events an object supports.

All AWT event sources support a multicast model for listeners. This means that multiple listeners can be added and removed from a single source. The API makes no guarantees about the order in which the events are delivered to a set of registered listeners for a given event on a given source. Additionally, any event which allows its properties to be modified (via setXXX() methods) will be explicitly copied such that each listener receives a replica of the original event. If the order in which events are delivered to listeners is a factor for your program, you should chain the listeners off a single listener which is registered on the source (the fact that the event data is encapsulated in a single object makes propagating the event extremely simple).

Event delivery is synchronous (as with 1.0's handleEvent()), however programs should not make the assumption that the delivery of an event to a set of listeners will occur on the same thread.

Once again, a distinction is drawn between low-level and semantic events. For low-level events, the source will be one of the visual component classes (Button, Scrollbar, etc) since the event is tightly bound to the actual component on the screen. The low-level listeners are defined on the following components:

  • java.awt.Component
    addComponentListener(ComponentListener l)

    addFocusListener(FocusListener l)

    addKeyListener(KeyListener l)

    addMouseListener(MouseListener l)

    addMouseMotionListener(MouseMotionListener l)
  • java.awt.Container
    addContainerListener(ContainerListener l)
  • java.awt.Dialog
    addWindowListener(WindowListener l)
  • java.awt.Frame
    addWindowListener(WindowListener l)

For semantic events, the source is typically a higher-level interface representing the semantic model (and this higher-level interface is commonly `implemented' by components using the model). Following are the semantic listeners defined for AWT components:

  • java.awt.Button
    addActionListener(ActionListener l)
  • java.awt.Choice (implements java.awt.ItemSelectable)
    addItemListener(ItemListener l)
  • java.awt.Checkbox (implements java.awt.ItemSelectable)
    addItemListener(ItemListener l)
  • java.awt.CheckboxMenuItem (implements java.awt.ItemSelectable)
    addItemListener(ItemListener l)
  • java.awt.List (implements java.awt.ItemSelectable)
    addActionListener(ActionListener l)

    addItemListener(ItemListener l)
  • java.awt.MenuItem
    addActionListener(ActionListener l)
  • java.awt.Scrollbar (implements java.awt.Adjustable)
    addAdjustmentListener(AdjustmentListener l)
  • java.awt.TextArea
    addTextListener(TextListener l)
  • java.awt.TextField
    addActionListener(ActionListener l)

    addTextListener(TextListener l)

Adapters

Since many of the EventListener interfaces are designed to listen to multiple event subtypes (i.e. the MouseListener listens to mouse-down, mouse-up, mouse-enter, etc.), the AWT will provide a a set of abstract "adapter" classes, one which implements each listener interface. This will allow programs to easily subclass the Adapters and override ONLY the methods representing event types they are interested in.

The Adapter classes provided by AWT are as follows:

    java.awt.event.ComponentAdapter

    java.awt.event.ContainerAdapter

    java.awt.event.FocusAdapter

    java.awt.event.KeyAdapter

    java.awt.event.MouseAdapter

    java.awt.event.MouseMotionAdapter

    java.awt.event.WindowAdapter

Note: There are no default Adapters provided for the semantic listeners, since each of those only contain a single method and an adapter would provide no real value.

Filtering for Performance

One of the great benefits of the new model is that since listeners are registered to handle specific event types, it's relatively easy for the toolkit to filter the events and deliver ONLY the events a component is interested in. This was not true with the old model!. Filtering should improve performance, especially with high frequency type events, such as mouse-moves.

All platforms should see some performance improvement from reduced event traffic, but the Solaris implementation should gain exceptional improvement since it's a network-based window system.

Code Example

Following is some sample code that uses the new model:

import java.awt.*;
import java.awt.event.*;

public class App {
    public void search() {
        /* do search operation ...*/
        System.out.println("Searching...");
    }
    public void sort() {
        /* do sort operation ...*/
        System.out.println("Sorting....");
    }

    static public void main(String args[]) {
       App app = new App();
       GUI gui = new GUI(app);
    }
}

class Command implements ActionListener  {
    static final int SEARCH = 0;
    static final int SORT = 1;
    int id;
    App app;

    public Command(int id, App app) {
        this.id = id;
        this.app = app;
    }

    public void actionPerformed(ActionEvent e) {
        switch(id) {
          case SEARCH:
            app.search();
            break;
          case SORT:
            app.sort();
            break;
        }
    }
}

class GUI {

    public GUI(App app) {
        Frame f = new Frame();
        f.setLayout(new FlowLayout());

        Command searchCmd = new Command(Command.SEARCH, app);
        Command sortCmd = new Command(Command.SORT, app);

        Button b;
        f.add(b = new Button("Search"));
        b.addActionListener(searchCmd);
        f.add(b = new Button("Sort"));
        b.addActionListener(sortCmd);

        List l;
        f.add(l = new List());
        l.add("Alphabetical");
        l.add("Chronological");
        l.addActionListener(sortCmd);
        f.pack();

        f.show();
    }
}

Note in particular the following differences between this example and how this would have been implemented in the old model:

  • The application code/logic is completely separate from the GUI. The GUI can be modified (or alternatives provided) without touching the application-specific code. This benefit may not be as apparent from this over-simplified case. However, as applications get larger and more complex, this becomes extremely important.
  • Absolutely no subclassing of AWT components is required.
  • ONLY the action events are delivered to this program; in the old model all other events would have also been delivered even though they performed no required function.
  • This code is not necessarily leaner than the code that would have been required for the old event model. This is mostly due to the requirement for writing the adapter class which listens to the events and dispatches them into application commands appropriately. The adapter classes are required because the Java language supports neither method references nor closures. In this context, it was believed that using interfaces/adapters would be the most type-safe option for making connections between objects. This code could be condensed by using the new JDK1.1 "Inner classes" java language feature.

Handling Events in Extended Components

For Java programs which are extending component classes via subclassing, it would be burdensome to require the registration of separate listener objects to respond to events. Therefore, for this case, the AWT defines that each component provide specific protected methods (that can be overridden by subclasses) which actually dispatch the events to listeners if they exist. This way a subclass can simply override one of these methods in order to process an event.

In order to make this as flexible as possible, this event processing capability is provided in two levels. The first is a single method on all components:

     protected void processEvent(AWTEvent)
All events for a component are first funneled through this method so that subclasses can choose to handle all events in a single place (similar to the 1.0 model's "handleEvent" with the main difference being that events are NOT propagated up the containment hierarchy in the new model).

The second option for processing events is provided at the event class level; there is a separate method for each class of event handled by that component:

     protected void processEventClass(EventClass)
For example, the java.awt.List component has the following event-class processing methods:
     protected void processActionEvent(ActionEvent e)

     protected void processItemEvent(ItemEvent e)
By default, the single processEvent method will invoke the proper event-class processing method. The event-class processing method by default will invoke any listeners which are registered. It's important to remember that these methods perform a critical function in the event processing for an AWT component and so if you override them you should remember to call the superclass's method somewhere within your own!

Selecting for Event Types

One of the goals of the listener model is to improve performance by NOT delivering events which components are not interested in. By default, if a listener type is not registered on a component, then those events will NOT be delivered and these processing methods will therefore NOT be called. So if you are using this extension mechanism for event-handling, you'll need to select for the specific types of events your component wishes to receive (in case no listener is registered). This can be done by using the following method on java.awt.Component:
     protected final void enableEvents(long eventsToEnable)
The parameter to this method is a bitwise mask of the event types you wish to enable. The event masks are defined in java.awt.AWTEvent. Note that changing this mask will not affect the delivery of events to listeners -- it only controls the delivery to the component's processing methods. The bottom line is that the set of events which are delivered to processEvent() is defined by the union of event types which have listeners registered and event types explicitly turned on via enableEvents().

Example using Extension Mechanism

Following is an example of how this extension mechanism may be used. For Example, if a subclass of java.awt.Canvas wishes to render some visual feedback when it receives/loses keyboard focus, it could do the following.

    public class TextCanvas extends Canvas {
      boolean haveFocus = false;

      public TextCanvas() {
          enableEvents(AWTEvent.FOCUS_EVENT_MASK); // ensure we get focus events
          ...
      }
      protected void processFocusEvent(FocusEvent e) {
          switch(e.getID()) {
            case FocusEvent.FOCUS_GAINED:
              haveFocus = true;
              break;
            case FocusEvent.FOCUS_LOST:
              haveFocus = false;
          }
          repaint(); // need to repaint with focus feedback on or off...

          super.processFocusEvent(e); // let superclass dispatch to listeners
      }
      public void paint(Graphics g) {
          if (haveFocus) {
              // render focus feedback...
          }
      }
      ...rest of TextCanvas class...
    }

A Word of Caution

In general we recommend you use the delegation-based listener model for most of your basic event handling needs and reserve the use of the above when you are truly extending the look or behavior of a component. This is because the above mechanism suffers from some of the same ills as the 1.0 event model (complex, error-prone logic in processing methods, forgetting to call "super.processEvent", etc.), and unless you clearly understand what you are doing, your program may not behave as you expect!

An alternative to using the above approach would be to simply have your component subclass implement the particular listener interface for the events it wishes to receive and then register itself as a listener. For example, the above code example would be rewritten to:

    public class TextCanvas extends Canvas implements FocusListener {
      boolean haveFocus = false;

      public TextCanvas() {
          addFocusListener(this); // ensure we get focus events
      }
      public void focusGained(FocusEvent e) {
           haveFocus = true;
           repaint();
          }
      public void focusLost(FocusEvent e) {
           haveFocus = false;
           repaint();
      }
      public void paint(Graphics g) {
          if (haveFocus) {
              // render focus feedback...
          }
      }
      ...rest of TextCanvas class...
    }

Consuming Events

There are cases where programs need to prevent certain types of events from being processed normally by a component (i.e. a builder wants to use mouse events to enable a user to graphically move a button around and it wants to prevent the mouse press from 'pushing' the button).

We have explicitly enabled this capability for input events only by providing two methods on java.awt.event.InputEvent:

     public void consume()

     public boolean isConsumed()
Note that if some object 'consumes' an input event, it is strictly an indication to the source component that the event should not be processed in its default manner (i.e. consuming a mousePressed event on a Button will prevent it from being activated). The event will still be dispatched to all listeners registered, regardless of whether a listener in the chain consumes the event.

The Event Queue

Another feature of the 1.1 event model is the addition of an event queue class:
     java.awt.EventQueue
This class provides a number of public instance methods to manipulate the queue:
     public synchronized void postEvent(AWTEvent e)

     public synchronized AWTEvent getNextEvent()

     public synchronized AWTEvent peekEvent()

     public synchronized AWTEvent peekEvent(int eventID)
Programs can actually use this class to instantiate their own event queue instances for the purpose of asynchronously posting events. The EventQueue class automatically instantiates an internal thread for dispatching the events appropriately.

In the default JDK implementation, all events generated on components are first posted to a special "system" EventQueue instance before being dispatched to their target component.

The Toolkit class provides a method to access the handle of the system EventQueue instance:

     public final EventQueue getSystemEventQueue()

It would obviously be a security problem to allow untrusted applets to freely manipulate the system event queue, therefore the getSystemEventQueue() method is protected by a SecurityManager check which disallows applets direct access to the system queue. We realize that applets would also like access to an event queue which is scoped to their own containment hierarchies and we are working on an architecture to allow that for a follow-on release.

Compatibility with the old Model

Our intention is to maintain binary compatibility for programs written to the old model for the 1.1 release. However, we strongly recommend new java programs migrate to the new model. We do not encourage the explicit mixing of the two models within a single Applet. However, we realize that programs which code to the new model may need/wish to use existing GUI classes which still use the old model and so we have done our best to ensure this works (for example, the hotjava browser is a java application which will need to be able to load both 1.0 and 1.1 style applets).

The way this works is that the AWT will recognize a component as being either a 1.0-event-model "target" OR a 1.1-event-model "source", but not both. A component is recognized to be a 1.1-event-model "source" by meeting one of the following conditions:

  1. A listener (of any kind) is registered
  2. An event type (of any kind) was explicitly enabled by calling enableEvents()
ELSE the component will be treated as a 1.0-event-model "target" and all events will be delivered to the 1.0 handleEvent method as before.

Note that this is an "all or nothing" distinction and that once the AWT determines a component is a particular event model type, ALL events on that component will be processed in that context. For example, if a TextField object has only a FocusListener registered, then only focus events will be dispatched to the textfield in the 1.1 mechanism and the old 1.0 handleEvent method will NEVER be called (not even for other event types!). So while it is possible to combine components which use the different models, it is not possible to get a single component to mix both models.

One key difference between the two models is that the old model would automatically propagate events up the containment hierarchy, while the new model does NOT propagate events in this way. The way this works for compatibility is that if an event originates on a component which is a 1.0-event-model "target", then it WILL be propagated up the hierarchy in the 1.0 fashion, regardless of the event model type of its ancestor containers. If an event originates on a 1.1-event-model "source", then that event will NOT propagate up the hierarchy, regardless of the event model type of its ancestor containers.

Send feedback to: java-awt@java.sun.com
Copyright © 1996, 1997 Sun Microsystems, Inc. All rights reserved.


Previous AWT Enhancements

Duke logo with toolbox Previous AWT Enhancements

The documents in the section describe enhancements made in version 1.1 of the JavaTM platform. For AWT changes made in the current version of the platform, see

AWT Enhancements

The AWT was modified in version 1.1 of the JavaTMDevelopment Kit to provide major quality improvements while introducing the beginnings of a richer infrastructure for larger-scale GUI development. Although changes and enhancements to the overall API were made, compatibility was maintained with the 1.0 API so that existing applets could continue to run.

A number of the 1.1 AWT changes and enhancements are aimed at the needs of tool developers. Good software tools are fundamental to the usability and success of Java technology. Additionally, the AWT since 1.1 supports the JavaBeans architecture. In fact, all AWT components in 1.1 are "simple" Java Beans.

The following documents summarize the API changes in the AWT API made in version 1.1:

  • Data Transfer/Clipboard
  • Desktop Colors
  • Delegation Event Model
  • Graphics and Images
  • Lightweight UI Framework
  • Mouseless Operation
  • Popup Menu
  • Printing
  • ScrollPane Container


Java AWT: Lightweight UI Framework

Duke logo doing a cartwheel Java AWT: Lightweight UI Framework

Last Updated: January 31, 1997

The Problem

 One of the issues with the 1.0 AWT is that creating new components requires creating subclasses of java.awt.Canvas or java.awt.Panel, which means that each new component owns its own opaque native window. This one-to-one mapping between components and native windows results in three problems:
  1. Native windows can be heavyweight, so it's undesirable to have too many of them.
  2. Native windows are opaque, so they can't be used to implement transparent regions.
  3. Native windows are handled differently across platforms, so the AWT has to struggle to maintain a consistent view across these varied platforms.
Hooks have been implemented that enable the creation of "lightweight" UI components; these hooks are called the Lightweight UI Framework.

Lightweight UI Framework

The Lightweight UI Framework is very simple -- it boils down to the ability to now directly extend the java.awt.Component and java.awt.Container classes in order to create components which do not have native opaque windows associated with them. These lightweight components and containers fit right into the existing AWT models, such as painting, layout, and events, and as such, require no special handling or additional APIs. Existing subclasses of Canvas and Panel can be easily migrated to lightweight versions by simply changing their superclass appropriately.

The advantages of creating lightweight components are the following:

  • The Lightweight component can now have transparent areas by simply not rendering to those areas in its paint() method (although, until we get full shape support from Java2D, the bounding box will remain rectangular).
  • The Lightweight component is "lighter" in that it requires no native data-structures or peer classes.
  • There is no native code required to process lightweight components, hence handling of lightweights is 100% implemented in common java code, which leads to complete consistency across platforms.

We are using this framework in an upcoming version of the toolkit (beyond 1.1) to implement pure-java versions of the base UI controls (Button, List, etc.) which implement a common look-and-feel across the platforms (and don't use the native peers).

Mixing Lightweight & Heavyweight Components

Lightweight components can be freely mixed with existing heavyweight components. This means that lightweight components can be made direct children of heavyweight containers, heavyweight components can be made direct children of lightweight containers, and heavyweight and lightweights can be mixed within containers (with the one caveat that the heavyweight sibling will always be "on top" if it overlaps with a lightweight, regardless of the specified z-order).

Putting Lightweight components in Existing Panels

The painting and event dispatching mechanism for lightweight components is handled by the Container class. This means that the painting of lightweight components is triggered from within the paint() method of its container. Therefore, if a lightweight component is placed inside of a Container instance where the paint method has been overridden but which does not call super.paint(), the paint() method of the lightweight component will never be called. This could be a common occurrence if you're using existing classes which extend Panel in order to implement the painting of a border or bevel, but which don't call "super.paint()" (because it was not an issue with 1.0.2). So if your lightweight components are not showing up, this is the first thing to check!

Double Buffering

Because lightweight components are entirely rendered in Java, the use of double-buffering in their containers can really smooth out their rendering to avoid flashing. By default, the Container class does not implement double-buffering, but this is extremely easy to do! Following is an example of a double-buffered Panel which implements smooth rendering for any lightweight components placed inside it:

public class DoubleBufferPanel extends Panel {
  Image offscreen;

  /**
   * null out the offscreen buffer as part of invalidation
   */
  public void invalidate() {
      super.invalidate();
      offscreen = null;
  }

  /**
   * override update to *not* erase the background before painting
   */
  public void update(Graphics g) {
      paint(g);
  }

  /**
   * paint children into an offscreen buffer, then blast entire image
   * at once.
   */
  public void paint(Graphics g) {
      if(offscreen == null) {
         offscreen = createImage(getSize().width, getSize().height);
      }
      Graphics og = offscreen.getGraphics();
      og.setClip(0,0,getSize().width, getSize().height);
      super.paint(og);
      g.drawImage(offscreen, 0, 0, null);
      og.dispose();
  }
}

Sample Code

Following is sample code showing the creation of a lightweight round button class, which shows off the transparency aspect of lightweight components.

import java.lang.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;

/**
 * RoundButton - a class that produces a lightweight button.
 */
public class RoundButton extends Component {

  String label;                      // The Button's text
  protected boolean pressed = false; // true if the button is detented.

  /**
   * Constructs a RoundButton with the specified label.
   * @param label the label of the button
   */
  public RoundButton(String label) {
      this.label = label;
      enableEvents(AWTEvent.MOUSE_EVENT_MASK);
  }

  /**
   * paints the RoundButton
   */
  public void paint(Graphics g) {
      int s = Math.min(getSize().width - 1, getSize().height - 1);

      // paint the interior of the button
      if(pressed) {
          g.setColor(getBackground().darker().darker());
      } else {
          g.setColor(getBackground());
      }
      g.fillArc(0, 0, s, s, 0, 360);

      // draw the perimeter of the button
      g.setColor(getBackground().darker().darker().darker());
      g.drawArc(0, 0, s, s, 0, 360);

      // draw the label centered in the button
      Font f = getFont();
      if(f != null) {
          FontMetrics fm = getFontMetrics(getFont());
          g.setColor(getForeground());
          g.drawString(label,
                       s/2 - fm.stringWidth(label)/2,
                       s/2 + fm.getMaxDescent());
      }
  }

  /**
   * The preferred size of the button.
   */
  public Dimension getPreferredSize() {
      Font f = getFont();
      if(f != null) {
          FontMetrics fm = getFontMetrics(getFont());
          int max = Math.max(fm.stringWidth(label) + 40, fm.getHeight() + 40);
          return new Dimension(max, max);
      } else {
          return new Dimension(100, 100);
      }
  }

  /**
   * The minimum size of the button.
   */
  public Dimension getMinimumSize() {
      return new Dimension(100, 100);
  }

   /**
    * Paints the button and distribute an action event to all listeners.
    */
   public void processMouseEvent(MouseEvent e) {
       Graphics g;
       switch(e.getID()) {
          case MouseEvent.MOUSE_PRESSED:
            // render myself inverted....
            pressed = true;

            // Repaint might flicker a bit. To avoid this, you can use
            // double buffering (see the Gauge example).
            repaint();
            break;
          case MouseEvent.MOUSE_RELEASED:
            // render myself normal again
            if(pressed == true) {
                pressed = false;
                // Repaint might flicker a bit. To avoid this, you can use
                // double buffering (see the Gauge example).
                repaint();
            }
            break;
          case MouseEvent.MOUSE_ENTERED:
            break;
          case MouseEvent.MOUSE_EXITED:
            if(pressed == true) {
                // Cancel! Don't send action event.
                pressed = false;

                // Repaint might flicker a bit. To avoid this, you can use
                // double buffering (see the DoubleBufferPanel example above).
                repaint();

                // Note: for a more complete button implementation,
                // you wouldn't want to cancel at this point, but
                // rather detect when the mouse re-entered, and
                // re-highlight the button. There are a few state
                // issues that that you need to handle, which we leave
                // this an an excercise for the reader (I always
                // wanted to say that!)
            }
            break;
       }
       super.processMouseEvent(e);
   }
}

Send feedback to:java-awt@java.sun.com
Copyright © 1997, Sun Microsystems, Inc. All rights reserved.


Java AWT: Mouseless Operation

Duke logo Java AWT: Mouseless Operation

Last Updated: February 3, 1997

Purpose

 Although typical GUIs today are designed to be driven with a mouse, there are numerous circumstances where mouseless operation in a GUI becomes important (and sometimes even critical) for usability. Some of those circumstances include:
  • Accelerated operation for the "power" user
  • Disabled access
  • Avoidance or treatment for RSI (repetitive stress injury)

AWT1.0 does not provide any explicit facilities for building mouseless operation into Java programs, except where the native peers components provide it by default (i.e. tabbed focus traversal, space-bar activation, etc.). For JDK1.1, the AWT will add some baseline support to better enable mouseless mode in Java programs, although it by no means provides a 100% solution to this problem. This support will be expanded in subsequent releases. The two features in the JavaTM platform since version 1.1 are:

  • Focus Traversal
  • Menu Shortcuts

Focus Traversal

Focus traversal is defined to be the ability to use keystrokes (not the mouse) to traverse components capable of accepting keyboard focus. Those keystrokes are defined to be <Tab> to move forward and <Shift-Tab> to move backward. Once the focus is owned by a component then it should be possible to activate/drive that component with further defined keystrokes (such as <space> to press a Button). It is the responsibility of the component (not the AWT), to implement the proper activation once it has focus

A component which is capable of accepting focus in this way should always render some form of visual feedback when it gets focus so that the user can easily see which component has focus as the user traverses using Tab/Shift-Tab. Typically this feedback takes the form of a colored bounding box drawn around the component.

The native toolkits on each platform provide varying degrees of support for focus traversal by default. However, explicit support for this has been implemented in the common java AWT code so that the behavior is more consistent across platforms.

The Focus Traversal API

The API is extremely simple; it consists of a new method on java.awt.Component and java.awt.peer.ComponentPeer:
    public boolean isFocusTraversable()

This method returns true if the component is a type inherently capable of accepting keyboard focus and returns false otherwise.

The reason this method also exists for the peer class is because the native peer components that are created by the AWT components have different traversal rules on different platforms. This allows the tailoring of this attribute appropriately on each platform (for example, on the Mac, Buttons cannot take focus, but on Motif and Microsoft Windows, they can).

All existing AWT components should have this attribute set properly by default, but there is the option to subclass a component and override this method to return a value appropriate for your program. In particular, if you are subclassing java.awt.Canvas to build your own custom component that is designed to take keyboard focus, then you should do the following three things:

  1. override isFocusTraversable() to return true (Canvas returns false by default)
  2. catch the mouse-down event on the component and invoke requestFocus() (to implement click-to-type for your component)
  3. when your component gets focus, provide visual feedback indicating it has the focus

If your component does not adhere to the above steps, users may have trouble getting focus into your component.

The AWT internally tracks which component has the focus so that it can move the focus forward or backward in response to a Tab or Shift-Tab keyboard event. This is handled by a private FocusManager object that is registered on the Window. The FocusManager can manage this focus migration correctly, no matter how deeply nested a window's containers are. The order of this traversal will be equal to the order of the components contained in the containers; by default this will be equal to the order the children were added to the container, however the Container's add(Component c, int pos) method can be used to control this ordering. The FocusManager automatically checks to see if a "focusTraversable" component is both visible and active before it assigns it the focus (hence, the isFocusTraversable() method need not take this state into account for its return value).

Note: We realize that a more flexible mechanism for configuring the order of traversal is needed and we are currently working on a solution to that problem.

Menu Shortcuts

The goal for the AWT Shortcut API is to provide an easy way for application developers to provide shortcuts as an aid to menu navigation. This API only addresses menu shortcuts, and does not touch on any other mouseless menu navigation issues.

A Shortcut is defined to be a keyboard equivalent of a menu command, such that invoking the appropriate key combination will cause the same action to be initiated as if the menu item had been selected. Shortcuts are also known as keyboard equivalents or accelerators.

The Shortcuts API

The API consists of a class:
    java.awt.MenuShortcut

java.awt.MenuItem then has the following additional methods:

    public MenuItem(String label, MenuShortcut s)

    public MenuShortcut getShortcut()

    public void setShortcut(MenuShortcut s)

    public void deleteShortcut();

java.awt.MenuBar has the following additional methods:

    public MenuItem getShortcutMenuItem(MenuShortcut s);

    public Enumeration shortcuts();

    boolean handleShortcut(KeyEvent e);

    public void deleteShortcut(MenuShortcut s);

Modifiers

Application shortcuts all have a common key modifier per-platform:
  • <Command> on Macs
  • <Control> on Windows
  • <Control> Motif

Note: ALT isn't supposed to be used for application shortcuts, other than QUIT, which is already mapped by the AWT.

Although most of the shortcut API is implemented in shared code, one method has been added to java.awt.Toolkit to return the appropriate modifier per platform:

        public int getMenuShortcutKeyMask();

Visual Indicators

In order for users to learn and use menu shortcuts, it's important that a menu item display some visual indicator for the shortcut it supports. This will be handled automatically by the AWT, in a manner most appropriate for the given platform.

Sample Code

 The code to create menu-items in 1.0:
        menu.add(new MenuItem("Save..."));

        menu.add(new MenuItem("Send..."));

The code to create menu-items with shortcuts in 1.1:

        // Specify an 's' shortcut for save, and 'shift-s' for send.

        menu.add(new MenuItem("Save...", new MenuShortcut('s'));

        menu.add(new MenuItem("Send...", new MenuShortcut('s', true));

Send feedback to:java-awt@java.sun.com
Copyright © 1996, 1997 Sun Microsystems, Inc. All rights reserved.


Java AWT: Popup Menu

Duke logo doing a cartwheel Java AWT: Popup Menu

Last Updated: February 3, 1997

Purpose

 Popup menus (also known as "context menus") are now a very common UI element in modern GUIs (Win95, CDE, etc.). The AWT in 1.0 supports only Pulldown menus (menus which are always attached to a menubar or menu-item) and needs an API to allow Java programs to be able to easily create popup menus.

Popup Menu API

 The primary goal for this API is to make the creation and invocation of popups extremely easy in Java programs. Additionally, we want to ensure that popups are not tightly bound to a single component and can be easily reused both within , as well as across, containment hierarchies.

The API consists of a new subclass of Menu:

    java.awt.PopupMenu

The main addition to this subclass is a method to invoke the popup:

    public void show(Component origin, int x, int y)

This method will invoke the popup at the x,y coordinate position relative to the component parameter (the intention is that all parameters can easily be extracted from a given mouse-down event object).

Popup Menu Ownership

Popup menus must have a valid "parent" component in order to be shown. This is to ensure that a popup menu can be instantiated and cached prior to being shown (to prevent any potential slow-down during the show operation, which from the user's perspective should happen simultaneously with the mouse event which triggered it). Popup menus can be attached-to/removed-from any component, using new methods in class java.awt.Component:
    add(PopupMenu popup)

    remove(MenuComponent popup)

Note that a popup menu can only be owned by one component at a time.

The "origin" parameter passed into the show() method can be any component contained within the containment hierarchy defined with the popup's parent as the root (it need not be the parent itself). This is particularly useful if you need to define a single popup for an entire window; you would attach the popup menu to the frame, but could invoke it in response to a mouse-down event on any component within that frame.

Popup Event Trigger

The main issue with popup menus is defining an appropriate event trigger definition, as this varies slightly across the different platforms:
  • In Windows, the menu is popped up on the mouse button *2* mouse UP.
  • In Motif, the menu is popped up on the mouse button *3* mouse DOWN (and it remains showing if the subsequent mouse UP happens within a small interval; else the menu is pulled down on the mouse DOWN)

The API provides a platform-independent abstraction so a program can detect a popup-menu trigger event without hard-coding platform-specific event-handling logic in the program. This is accomplished by providing the following method on java.awt.event.MouseEvent:

    public boolean isPopupTrigger()

Event Model Issues

The AWT's 1.0 event model has a limitation where menu events (the actions invoked when a menu item is selected) are not catchable in the menu itself, but must be caught on the parent frame. To work with the 1.0 event model, the popup menu events must be caught in the action() method of the component which owns it. Clearly this is not a desirable limitation for popup menus, as they are not designed to be tightly bound to a particular component. With the new 1.1 event model API, action listeners can be attached directly to the menu items themselves, alleviating this issue (See the AWT Delegation Event Model document for details).

Sample Code

 Following is a very simple sample program which shows the usage of this API using the 1.1 Delegation Event Model.

    import java.awt.*;
    import java.applet.*;
    import java.awt.event.*;

    public class PopupMenuTest extends Applet implements ActionListener {

    PopupMenu popup;

    public void init() {
            MenuItem mi;

        popup = new PopupMenu("Edit");

            mi = new MenuItem("Cut");
            mi.addActionListener(this);
        popup.add(mi);

            mi = new MenuItem("Copy");
            mi.addActionListener(this);
        popup.add(mi);

        popup.addSeparator();

            mi = new MenuItem("Paste");
            mi.addActionListener(this);
        popup.add(mi);

        add(popup); // add popup menu to applet

            enableEvents(AWTEvent.MOUSE_EVENT_MASK);

        resize(200, 200);
        }

    public void processMouseEvent(MouseEvent e) {

        if (e.isPopupTrigger()) {
            popup.show(e.getComponent(), e.getX(), e.getY());
        }
        super.processMouseEvent(e);
        }

        public void actionPerformed(ActionEvent e) {
        String command = e.getActionCommand();

            if (command.equals("Cut")) {
            // perform cut operation
            } else if (command.equals("Copy")) {
                // perform copy operation
            } else if (command.equals("Paste")) {
                // perform paste operation
            }
        }
    }

Send feedback to:java-awt@java.sun.com
Copyright © 1996, Sun Microsystems, Inc. All rights reserved.


Java AWT: Printing

Duke logo with magnifying glass Java AWT: Printing

Last Updated: December 6, 1999

Purpose

 The goal for the AWT printing API is to give developers an easy mechanism to print the AWT components using native platform facilities. This API is designed for use with the AWT Graphics model. Developers who prefer to work with Graphics2D should use 2D printing, available in the java.awt.print package.

The Printing API

 The printing API is very simple and consists primarily of one method in class java.awt.Toolkit:

PrintJob getPrintJob(Frame f, String jobtitle, JobAttributes jobAttributes,
PageAttributes pageAttributes)

and a class responsible for encapsulating all the information associated with a printing request:

    java.awt.PrintJob

The getPrintJob() method in Toolkit will take care of posting any platform specific print dialogs so that when it returns, the PrintJob object has already been configured to match the user's request. The JobAttributes and PageAttributes parameters provide the ability to pass in default attribute values for the print job. This allows the printing attributes appropriate for a particular application to be stored and applied in individual circumstances. If the user changes the default attributes in the print dialog, those changes are saved into the JobAttributes and PageAttributes instances passed to the method (so the program can choose to store those new defaults if desired).

The PrintJob object provides access to the relevant printing properties chosen by the user (page size, etc) as well as the print graphics contexts used to transparently render to the print device.

Print Graphics Context

The print graphics context is provided by an interface:
java.awt.PrintGraphics

The PrintJob object provides the method to obtain a handle to an object which is a subclass of Graphics AND implements the PrintGraphics interface:

Graphics getGraphics()

Since this object is a subclass of the Graphics class, it can simply be passed into existing paint() or print() methods (which use the standard Graphics drawing methods) and the underlying AWT implementation takes care of translating those calls to the appropriate print device (this is straightforward on Mac/Windows which support graphic print devices; on Solaris, a PostScript graphics object is required to generate appropriate PostScript).

It is often the case that from within a paint() or print() method, your program may want to detect whether it is rendering to the screen or to a print device (for example it would not necessarily want to print `highlighted' text which has been selected by the user). Since the graphics object returned from the PrintJob.getGraphics() method implements the PrintGraphics interface, this can easily be detected with the following test:

    public void paint(Graphics g) {

        if (g instanceof PrintGraphics)

            // printing is occurring

            ...

The primary method in the PrintGraphics interface is a method to obtain a handle to the associated PrintJob object:

PrintJob getPrintJob()

Pagination

 It is the program's responsibility to handle pagination. Each call to getGraphics() will return a print graphics context for a single page; when the program calls dispose() on the print graphics context, that page is flushed to the printer. The program must take care of determining appropriate page content and page breaking, given the specified page dimensions and resolution.

These printing attributes can be obtained by the following methods on java.awt.PrintJob:

Dimension getPageDimension()

int getPageResolution()

Printing Hierarchies of Components

If a program needs to print an entire containment hierarchy of AWT components (i.e. a Panel and any nested controls/containers within it), it should call the following java.awt.Component method on the root of the containment hierarchy (passing in the appropriate print graphics context):
public void printAll(Graphics g)

Calling this method will result in the complete traversal of the containment hierarchy such that the print() method will be called on all descendent components. The default implementation of the print() method simply calls paint(), so if a program has created a component which renders itself in the paint() method, printing should work "automagically". Note that all the base AWT components (Button, Scrollbar, etc.) are capable of printing themselves when their printAll() method is called (even though their rendering does not take place in the paint() method).

Print Dialogs

Although it is important for some programs to either extend or create their own print dialogs, this capability is currently not available via AWT printing, nor via 2D printing.

Security

Because it was considered dangerous to allow potentially untrusted applets to initiate print job requests (and potentially quietly print anything devious to the printer that they desire) the initiation of a PrintJob (via Toolkit.getPrintJob) is defined to be an operation bound by the Applet security restrictions implemented in a SecurityManager method. In addition, while printing may be permitted, access to the file system may not. In such a case, requests to print to a file programmatically will generate an exception and the user will be unable to select print to file.

It's important to note that this restriction does not limit applets' capability to render using a PrintGraphics object returned from a PrintJob; it just disallows untrusted applets to initiate the job. A more reasonable policy will be provided when the Java security architecture allows more customization.

Sample Code

A VERY simple example of how a print job can be initiated to print an AWT component:

import java.awt.*;
import java.awt.event.*;

public class PrintingTest extends Frame implements ActionListener {

    PrintCanvas canvas;

    public PrintingTest() {
        super("Printing Test");
        canvas = new PrintCanvas();
        add("Center", canvas);

        Button b = new Button("Print");
        b.setActionCommand("print");
        b.addActionListener(this);
        add("South", b);

        pack();
    }

    public void actionPerformed(ActionEvent e) {
        String cmd = e.getActionCommand();
        if (cmd.equals("print")) {
            PrintJob pjob = getToolkit().getPrintJob(this,
                               "Printing Test", null, null);

            if (pjob != null) {
                Graphics pg = pjob.getGraphics();

                if (pg != null) {
                    canvas.printAll(pg);
                    pg.dispose(); // flush page
                }
                pjob.end();

            }
        }
    }

    public static void main(String args[]) {
        PrintingTest test = new PrintingTest();
        test.show();
    }
}

class PrintCanvas extends Canvas {

    public Dimension getPreferredSize() {
        return new Dimension(100, 100);
    }

    public void paint(Graphics g) {
        Rectangle r = getBounds();

        g.setColor(Color.yellow);
        g.fillRect(0, 0, r.width, r.height);

        g.setColor(Color.blue);
        g.drawLine(0, 0, r.width, r.height);

        g.setColor(Color.red);
        g.drawLine(0, r.height, r.width, 0);
    }
}

Send feedback to:java-awt@java.sun.com
Copyright © 1996, 1997, 1999 Sun Microsystems, Inc. All rights reserved.


Java AWT: ScrollPane Container

Duke logo in box Java AWT: ScrollPane Container

Last Updated: February 3, 1997

The Problem

 In the AWT1.0, the task of implementing all scrolling behavior is left to the developer. Only a basic Scrollbar class is provided which must be managed by the Java program, meaning the Java program must catch the scrollbar events and then take appropriate action to update the contents being scrolled.

Not only is this a general burden to developers who are accustomed to better support for this in toolkits, but it is also a serious performance problem, since there is a round trip (native->java->native) for each individual scroll event that occurs, and the application must respond to the event and move its contents using slower java draw/move operations. This is particularly noticeable during the event-intensive scroll-drag operations.

ScrollPane API

To resolve this problem, a ScrollPane class was added to the AWT in version 1.1. ScrollPane provides a container that implements automatic scrolling for a single component child:
    java.awt.ScrollPane
The ScrollPane supports three modes for its scrollbars:
  1. Scrollbars "when needed": Scrollbars are displayed only when the size of the child exceeds the size of the scrollpane.
  2. Scrollbars "always": Scrollbars are always displayed regardless of the relative sizes of the child and parent.
  3. Scrollbars "never": Scrollbars are never displayed and the program is in total control of when scrolling occurs. This mode is useful when a program wishes to implement its own scrollbar controls.
The state of the vertical and horizontal scrollbars in cases 1 & 2 are represented by separate internal objects to the ScrollPane which implement the following interface:
       java.awt.Adjustable
Therefore, if a program wishes to set properties such as the unitIncrement,value, etc. on the scrollpane, it would first get the appropriate Adjustable and set the property there.

Sample Code

Following is sample code showing the use of this API in a simple case:

import java.awt.*;

public class Scroller extends Frame {

    public Scroller() {
        super("Scroller Example");

        ScrollPane scroller = new ScrollPane(ScrollPane.SCROLLBARS_AS_NEEDED);
        scroller.add(new DrawCanvas());

        Adjustable vadjust = scroller.getVAdjustable();
        Adjustable hadjust = scroller.getHAdjustable();
        hadjust.setUnitIncrement(10);
        vadjust.setUnitIncrement(10);

        scroller.setSize(200, 200);

        add("Center", scroller);
        pack();

    }
   // No more handleEvent method needed to implement scrolling!

    public static void main(String args[]) {
        Scroller test = new Scroller();
        test.show();
    }
}

class DrawCanvas extends Component {

    public Dimension getPreferredSize() {
        return new Dimension(300, 300);
    }

    public void paint(Graphics g) {
        // Note: For most efficient repainting, we should check the
        // clip rectangle in the Graphics object to determine the
        // damaged region and only paint that;  we don't do that here
        // for simplicity in this example
        //
        Rectangle r = getBounds();

        g.setColor(Color.black);
        g.fillRect(0, 0, r.width, r.height);

        g.setColor(Color.yellow);
        g.drawLine(0, 0, r.width, r.height);

        g.setColor(Color.white);
        g.drawLine(0, r.height, r.width, 0);
    }
}

Send feedback to:java-awt@java.sun.com
Copyright © 1996, 1997 Sun Microsystems, Inc. All rights reserved.


AWT graphics clip API

last updated: October 30, 1996

The Issue

Currently the AWT Graphics object has methods to implement an ever-decreasing clip area. There is a single clipRect() method to manipulate the clip area. This method will intersect the current clipping area with the indicated rectangle and set a new clip area to the intersection of the two. This operation is convenient for many graphics algorithms that might wish to use clipping to control paint distribution while operating within a Graphics object set up to clip rendering to a contextual "repaint region". Unfortunately, when clipping is used in the rendering process, it is usually only used for a small number of rendering operations. Without the ability to enlarge the clip area back to the original contextual clip established by the repaint process, clipping for rendering purposes becomes a one-shot process.

If a programmer wants to temporarily set the clip to a smaller area for one or two rendering operations and then restore it later, then another mechanism must be used. The currently available work-around is to copy the Graphics object using one of the create() methods and then set the temporary clip on the new Graphics object using the clipRect method and dispose of it when done. The original Graphics object will still have its original clip unmodified and can be used for further rendering.

Furthermore, all of the other attributes of the Graphics object can be queried, changed, and then restored to their original values. The clip area, when viewed as a rendering attribute, only partially follows this design model. There is a getClipRect() method to query the clip area as a Rectangle object, but that method is not extensible in the future when non-rectangular clip areas may be provided. In addition, even if you queried the current clip area there was no way to explicitly set the clip to this value after you have installed a more restrictive clip.

The new clip API

To resolve this problem, 1 new class:
    java.awt.Shape
is being added to the AWT and 3 new methods:
    getClip()
    setClip(Shape)
    setClip(int x, int y, int w, int h)
are being added to the AWT Graphics class.

In addition, the getClipRect() method is now deprecated in favor of the more general getClip() method detailed above and a new method:

    getClipBounds()
which returns the bounding box of the current clip area as a Rectangle regardless of its shape. This method is also named consistently with the recent terminology updates that were implemented across the AWT classes.

Sample Code

Following is sample code showing the use of the old API to perform temporary clipping:

    import java.awt.*;
    import java.applet.*;

    public class TempClipExample extends Applet {
    Image bgimg, img2;
    public void paint(Graphics g) {
        // Draw a background image
        g.drawImage(bgimg, 0, 0, this);
        // Draw the upper left 100x100 portion of another image at 10,10
        Graphics g2 = g.create();
        g2.clipRect(10, 10, 100, 100);
        g2.drawImage(img2, 10, 10, this);
        g2.dispose();	// reclaims resources more quickly
        // Now continue drawing with original clip area
        g.fillRect(0, 0, 10, 10);
    }
    }

Following is sample code showing the use of the new API to perform temporary clipping:

    import java.awt.*;
    import java.applet.*;

    public class TempClipExample extends Applet {
    Image bgimg, img2;
    public void paint(Graphics g) {
        // Draw a background image
        g.drawImage(bgimg, 0, 0, this);
        // Draw the upper left 100x100 portion of another image at 10,10
        Shape oldclip = g.getClip();
        g.clipRect(10, 10, 100, 100);
        g.drawImage(img2, 10, 10, this);
        g.setClip(oldclip);
        // Now continue drawing with original clip area
        g.fillRect(0, 0, 10, 10);
    }
    }

Send feedback to:java-awt@java.sun.com
Copyright © 1996, Sun Microsystems, Inc. All rights reserved.


AWT image rendering API

last updated: October 30, 1996

The Issue

Currently the AWT Graphics object has 4 methods to render an entire image with an optional scale and/or an optional background color.

There is no way to render a subset of the entire image without using either a cropping filter or the clipping mechanism of the Graphics object. This situation is further compounded by the fact that the clip attribute of the Graphics object can only be set to a more restrictive value, it can never be expanded or restored to a previous clip area.

The existing methods to scale an image also do not allow the programmer to flip an image horizontally or vertically by scaling it to a negative size or by any other means. Even though other arbitrary manipulations of images are not supported, the lack of flipping is notable mainly because it is easily managed with minor mathematical modifications to the already supported scaling algorithms.

Most of the existing Java interfaces that take rectangular arguments treat negative width and height values as meaning an empty rectangle. The existing drawImage methods could have allowed image flipping when told to scale the image to a negative size, but that would have conflicted with the empty negative rectangle protocol seen elsewhere. Instead of treating the negative values as a null operation (which arguably would have been the right thing to do), the existing drawImage methods consider negative width and height values to indicate "proportional values". In other words, if one of the values is negative then an appropriate value is substituted based upon the other non-negative quantity to maintain the aspect ratio of the original image. If both are negative then the image is drawn at its original size and scale. This behavior was designed to be compatible with the way that some browsers treat missing specifications of width and height attributes in HTML <img> tags. In essence, scaling an image to a negative width or height is compared to scaling the image to an unspecified width or height and a standard "proportional" algorithm is applied to obtain default values.

The new image rendering API

To resolve this problem, 2 new methods are being added to the AWT Graphics class to provide a complete scaling, flipping, cropping image rendering facility. The new methods are:
    drawImage(Image img,
          int dx1, int dy1, int dx2, int dy2,
          int sx1, int sy1, int sx2, int sy2,
          ImageObserver observer)
    drawImage(Image img,
          int dx1, int dy1, int dx2, int dy2,
          int sx1, int sy1, int sx2, int sy2,
          Color bgcolor, ImageObserver observer)

An interesting note about these new methods is that, while the former drawImage() methods may create a totally new representation of the image for the screen by rereading the raw image data in an asynchronous thread, the new methods will always use the pixels from the unscaled version of the image to draw to the screen. As a result, the 2 new methods will complete synchronously as long as the full size version of the image has previously been loaded and converted as indicated by a MediaTracker or other image status API.

Another interesting change in the coordinate specifications of the new methods is the use of two coordinates to define the source and destination rectangles. Since negative widths and heights carry existing meanings in the rest of the Java APIs, the new methods use the new coordinate pair specification to allow explicit control over which dimensions get flipped. This new system is also more convenient for some applications which may be tracking the corner of the image by following a user dragging the mouse. There is no need to decompose drag start and end coordinates into an x,y,w,h format.

Sample Code

Following is sample code showing the use of the old API to perform image cropping:

    import java.awt.*;
    import java.applet.*;

    public class ImgCropExample extends Applet {
    Image bgimg, img2;
    public void paint(Graphics g) {
        // Draw a background image
        g.drawImage(bgimg, 0, 0, this);
        // Draw the upper left 100x100 portion of another image at 10,10
        Graphics g2 = g.create();
        g2.clipRect(10, 10, 100, 100);
        g2.drawImage(img2, 10, 10, this);
        g2.dispose();	// reclaims resources more quickly
        // Now continue drawing with original clip area
        g.fillRect(0, 0, 10, 10);
    }
    }

Following is sample code showing the use of the new API to perform image cropping:

    import java.awt.*;
    import java.applet.*;

    public class ImgCropExample extends Applet {
    Image bgimg, img2;
    public void paint(Graphics g) {
        // Draw a background image
        g.drawImage(bgimg, 0, 0, this);
        // Draw the upper left 100x100 portion of another image at 10,10
        g.drawImage(img2,
            10, 10, 110, 110,
            0, 0, 100, 100, this);
        // Now continue drawing with original clip area
        g.fillRect(0, 0, 10, 10);
    }
    }

Following is sample code showing the use of the new API to perform image flipping:

    import java.awt.*;
    import java.applet.*;

    public class ImgCropExample extends Applet {
        Image img2;
    public void paint(Graphics g) {
        // Draw the center 100x100 portion of a 200x200 image
        // at location 10, 10, flipped horizontally.
        g.drawImage(img2,
            10, 10, 110, 110,
            150, 50, 50, 150, this);
    }
    }

Send feedback to:java-awt@java.sun.com
Copyright © 1996, Sun Microsystems, Inc. All rights reserved.


AWT image scaling API

last updated: October 30, 1996

The Issue

Java has provided a number of mechanisms to scale an image automatically at the time that the drawImage() is called. These mechanisms have caused a bit of confusion since the exact behavior was not well documented and the particular implementation chosen for the reference port behaved in a way that differed from most programmer's expectations.

In particular, when images are displayed on the screen, the Image data is converted to a format which matches the color capabilities of the screen. The original image data is not stored persistently, only the converted screen data is stored by the screen representations. If the data for the image is needed for some other purpose (such as filtering the data for a new image), then the raw data has to be reloaded from the original source.

Note that the original data is stored in a cache in case it is needed immediately after the first time it is loaded for a secondary purpose. If a single image is run through several filters, then the subsequent filtered images will often be able to use the cached converted data without having to reload the image file from the source, but this cached data cannot be relied on in general.
When the image is scaled using one of the drawImage method variants that allows the specification of a width and height, a separate screen representation is created for each size that is drawn. Furthermore, since scaling an image after it has been dithered for output on an 8-bit screen results in very poor quality output, the scaling is always done from the original image data. Even if the screen is 24 bits deep and thus the screen representation contains the original image data with no conversion loss the implementation is not smart enough to use the local copy and contacts the original source of the image anyway.

Another drawback of storing a separate image representation for each size drawn is the amount of memory consumed. The strategy of keeping a separate representation for each size drawn is meant to optimize rendering speed since the data is all ready to be copied to the screen byte for byte. This strategy ends up backfiring since the speed gain by having the scaled size precalculated often is more than offset by the pain and inconvenience of having to wait while the scaled variant is loaded and converted, especially if the image data needs to be reloaded over a slow network. Also, if the image is being drawn at many different sizes which will never be repeated the memory used to cache the scaled representations is wasted.

In short, there is no programmer control over whether or not the scaled version of the image is cached for subsequent rendering and whether or not the image scaling is done immediately or in the background.

Another issue which has bothered developers is that there is no way to create a new object which represents a scaled view of an existing image. An Image object can be scaled by supplying new width and height parameters to the drawImage call, but there is no way to encapsulate that information into an Image object so that by passing around that Image object, the desired size image will be drawn.

The new image scaling API and behavior

To resolve this problem a new strategy will be adopted for the drawImage methods that scale an image. In 1.1, all scaling by drawImage will be done "on the fly" at rendering time from the full sized screen representation.

There are two primary drawbacks of this change.

  1. Using the new drawImage to scale the image will take slightly longer than before since the pixel reordering will have to be performed at render time.
  2. The quality of the scaled images will be reduced on 8-bit screens due to the fact that the pixel reordering will be performed after the dithering process.

As it turns out, the first problem is much less dramatic than was originally feared. In the past couple of years processors have become very fast especially in comparison to the speeds of memory systems. As a result image scaling performance is mostly limited by memory access speed and the calculations necessary to determine which is the next pixel to copy to the screen for the particular scaling desired are not very noticeable compared to the work of moving the data to the screen.

The quality issue could have been a major problem. With the 8-bit color conversion code used in JDK implementations prior to 1.1 images degraded dramatically if they were scaled after dithering. Fortunately, new color conversion algorithms have been developed for 1.1 which increase the quality of the resulting dithered image so much that the results of scaling the dithered representations are typically as good, if not better than the results of the 1.0.2 images which were dithered after scaling.

Still, even though the implementation of image scaling was beefed up in 1.1 enough to make render-time on-the-fly scaling possible, there will be cases where the programmer wants every possible measure taken to improve the quality of the scaled image. To allow the programmer to choose when explicit scaling should be performed up front instead of at rendering time, two new filter classes will be available and a new convenience method will be added to the AWT Image class in 1.1. These same APIs can be used by programmers to create a new Image object representing a scaled version of that image encapsulated into its own Image object. The new image scaling classes are:

    java.awt.image.ReplicateScaleFilter
    java.awt.image.AreaAveragingScaleFilter
The new method in the Image class is:
    getScaledInstance(int width, int height, int hints)
The hints parameter controls what kind of algorithm is used to scale the image. There are hints which refer to specific algorithms to be used and there are more abstract hints which indicate whether or not to optimize the operation for speed or quality. The current set of legal values for the hints parameter are:
Image.SCALE_DEFAULT
Use the default scaling algorithm (which may be chosen based on the user's configuration)
Image.SCALE_FAST
Choose a scaling algorithm to optimize speed more than smoothness of the scaled image
Image.SCALE_SMOOTH
Choose a scaling algorithm to optimize smoothness of the scaled image more than speed
Image.SCALE_REPLICATE
Use the algorithm implemented by the ReplicateScaleFilter
Image.SCALE_AREA_AVERAGING
Use the algorithm implemented by the AreaAveragingScaleFilter

Sample Code

Following is sample code showing the use of the new API to scale an image:

    import java.awt.*;
    import java.applet.*;

    public class ImgScaleExample extends Applet {
    Image img, img2;
        public void init() {
        img = getImage(getDocumentBase(), "foo.gif");
        img2 = img.getScaledInstance(100, 100, Image.SCALE_DEFAULT);
    }

    public void paint(Graphics g) {
        // Draw the full size image
        g.drawImage(img, 0, 0, this);
        // Draw the scaled version of the image
        g.drawImage(img2, 10, 10, this);
        // Now draw a scaled version of the scaled image
        g.drawImage(img2, 110, 10, 50, 50, this);
    }
    }

Send feedback to:java-awt@java.sun.com
Copyright © 1996, Sun Microsystems, Inc. All rights reserved.


AWT memory image dynamic update API

last updated: November 14, 1996

The Issue

Currently the AWT provides a standard utility class to make an image out of an array of pixel values. This class isolates developers from the complex ImageProducer/ImageConsumer mechanisms if they simply want to calculate an image using a Java algorithm and then display the resulting image on the screen.

The MemoryImageSource class provides this facility but it only implements a static image capability. The first time an image is prepared for a screen by drawing the image, using the prepareImage method, or by using a MediaTracker to build the image, a snapshot of the pixels in the array will be converted into a screen representation. Then every time the image is drawn again at that same scale, the same buffered screen representation will be used, ignoring any changes the developer may have made to the original array of pixels in the meantime.

The implementation specifically does not reread the original array of pixel information for each rendering operation since image conversion is a slow process when compared to simply moving converted pixels to the screen. For drawImage to be fast, it works better if it can use a copy of the image that is already in the format that the display hardware uses to represent pixels. And thus we have a tradeoff between showing the image fast when it is not changing and dynamically incorporating changes to the original image data.

This implementation worked fine for images that were computed once and then the results were final. It was even workable for images that changed rarely since a new MemoryImageSource image could be constructed after each infrequent change or the original image could be flushed using the Image.flush() method to decache any existing screen representations. These workarounds were inefficient or unwieldy for more frequent updates such as those involved in animations since the entire image had to be reconverted even for minor modifications to the data, or even worse requiring more garbage collection than strictly necessary to reclaim space used by old discarded versions of the image.

The new memory image animation API

To simplify this capability, new methods are being added to MemoryImageSource so that developers can notify the image that new data is available from the original array. Since the image conversion process only occurs when the data in the original array actually changes, drawImage can still execute very fast. The new methods are:
    setAnimated(boolean animated)
    setFullBufferUpdates(boolean animated)
    newPixels()
    newPixels(int x, int y, int w, int h)
    newPixels(int x, int y, int w, int h,
          boolean framenotify)
    newPixels(byte[] newpix, ColorModel newmodel,
          int offset, int scansize)
    newPixels(int[] newpix, ColorModel newmodel,
          int offset, int scansize)
These new methods give the developer control over when the screen representations are updated, which region of the pixels is updated, when ImageObserver.FRAMEBITS notifications (which indicate when a single "frame" of animation is complete) are sent to the image observers, and the ability to switch to a new set of pixels and ColorModel.

Sample Code

Following is sample code showing the use of the old API to perform memory image buffer animation:

    import java.awt.*;
    import java.awt.image.*;
    import java.applet.*;

    public class AnimationExample extends Applet implements Runnable {
        Thread anim;
    MemoryImageSource imgsrc;
    Image memimg;
    int[] pixels;

    public void init() {
        pixels = new int[100 * 100];
        imgsrc = new MemoryImageSource(100, 100, pixels, 0, 100);
        memimg = createImage(imgsrc);
    }

        public void start() {
        anim = new Thread(this);
        anim.start();
    }

    public synchronized void stop() {
        anim = null;
        notify();
    }

    public synchronized void run() {
        while (Thread.currentThread() == anim) {
            int x = (int) (Math.random() * 100);
            int y = (int) (Math.random() * 100);
        int r = (int) (Math.random() * 255);
        int g = (int) (Math.random() * 255);
        int b = (int) (Math.random() * 255);
        pixels[y * 100 + x] =
            ((int) (Math.random() * 0xffffff)) | (0xff<<24);
        memimg.flush();
        repaint();
        try {wait(100);} catch (InterruptedException e) {return;}
        }
    }

    public void paint(Graphics g) {
        // Draw the animated image
        g.drawImage(memimg, 0, 0, this);
    }
    }

Following is sample code showing the use of the new API to perform memory image buffer animation:

    import java.awt.*;
    import java.awt.image.*;
    import java.applet.*;

    public class AnimationExample extends Applet implements Runnable {
        Thread anim;
    MemoryImageSource imgsrc;
    Image memimg;
    int[] pixels;

    public void init() {
        pixels = new int[100 * 100];
        imgsrc = new MemoryImageSource(100, 100, pixels, 0, 100);
        imgsrc.setAnimated(true);
        memimg = createImage(imgsrc);
    }

        public void start() {
        anim = new Thread(this);
        anim.start();
    }

    public synchronized void stop() {
        anim = null;
        notify();
    }

    public synchronized void run() {
        while (Thread.currentThread() == anim) {
            int x = (int) (Math.random() * 100);
            int y = (int) (Math.random() * 100);
        int r = (int) (Math.random() * 255);
        int g = (int) (Math.random() * 255);
        int b = (int) (Math.random() * 255);
        pixels[y * 100 + x] =
            ((int) (Math.random() * 0xffffff)) | (0xff<<24);
        imgsrc.newPixels(x, y, 1, 1);
        repaint();
        try {wait(100);} catch (InterruptedException e) {return;}
        }
    }

    public void paint(Graphics g) {
        // Draw the animated image
        g.drawImage(memimg, 0, 0, this);
    }
    }

Send feedback to:java-awt@java.sun.com
Copyright © 1996, Sun Microsystems, Inc. All rights reserved.


AWT 1.1 Graphics & Image enhancements

last updated: October 30, 1996

A number of graphics and imaging enhancements are being provided as of version 1.1 of the JavaTM platform. The following links take you to documentation detailing the issues and the new APIs developed to solve the problems.

  1. New methods to set and reset the Graphics Clip.
  2. New image rendering methods capable of simultaneously cropping, scaling, and flipping an image on the fly.
  3. New image scaling behavior and mechanisms were created to address some issues which were causing confusion with the existing implementations.
  4. New animation capabilities were added to the MemoryImageSource.
  5. New PixelGrabber methods were added to answer some needs we heard from the developer community.

Send feedback to:java-awt@java.sun.com
Copyright © 1996, Sun Microsystems, Inc. All rights reserved.


AWT PixelGrabber API updates

last updated: November 14, 1996

The Issue

The AWT image facility provides ways to retrieve or create images from many sources and to automate the process of displaying those images on the screen. The facility performs all of the required manipulations necessary on the image data behind an opaque external interface which shields users from all but the most abstract of image data information.

The interface provided is so opaque that in the initial development stages there was no direct way to access the pixel data of an image. The data could be accessed if a developer were willing to learn the intricacies of the complex ImageConsumer interface which is used by the image subsystem to communicate pixel data from image decoders to the screen, but most developers wanted an easier mechanism to get this data for the general case.

To satisfy this need a utility class was created to manage the ImageConsumer interface on behalf of the average developer who simply wanted to answer the question "What color is the pixel at location (x, y)?" The PixelGrabber class provided the ability to snapshot a rectangular region of pixels directly from an image's source to a Java integer array.

Three primary oversights have been identified with the interface provided by this class:

  • The data must be grabbed and stored into the array in the default ARGB (alpha RGB) convenience format Java uses for describing colors. The conversion process to convert the raw pixels into this format can consume a large amount of time especially when the developer only really needs the color information for isolated pixels scattered throughout the region of interest. Since the original ColorModel is discarded as the data is converted to the default representation, there is also no way to figure out what format the original data was in if that happens to be the desired goal of the process.
  • The developer must know what size array to create even before the data is snapshotted. Since many images do not know their dimensions until they load their data from the source for the first time, there can be a race condition where the developer must track the image loading until the dimensions are delivered and then instantiate a PixelGrabber and point it at the image source before the pixel data is delivered so that no data is lost requiring the image source to reload from scratch. Many developers would not even know how to best achieve this goal since the image progress is not very straightforward to track.
  • There was no way to start the grab operation without also waiting for the operation to complete and there was no way to stop the grab operation once started.

The new PixelGrabber methods

To enhance the capabilities of the PixelGrabber, new methods and constructors are being added:
    new PixelGrabber(Image img,
             int x, int y, int w, int h,
             boolean forceRGB)
    startGrabbing()
    abortGrabbing()
    getWidth()
    getHeight()
    getPixels()
    getColorModel()

Sample Code

Following is sample code showing the use of the new API to grab the pixels of an image of unknown dimensions in its original format:

    import java.awt.*;
    import java.awt.image.*;
    import java.applet.*;

    public class GrabExample extends Applet implements Runnable {
        Thread grab;
    Image img;
    PixelGrabber pg;

    public void init() {
        img = getImage(getDocumentBase(), "theImage.gif");
        pg = new PixelGrabber(img, 0, 0, -1, -1, false);
        // In reality, the init method shouldn't be kicking off
        // heavyweight operations like an image download, but
        // this demonstrates use of the asynchronous grabbing...
        pg.startGrabbing();
    }

        public void start() {
        grab = new Thread(this);
        grab.start();
    }

    public synchronized void stop() {
        grab.interrupt();
        grab = null;
    }

    public synchronized void run() {
        try {
        pg.grabPixels();
        repaint();
        } catch (InterruptedException e) {
        System.err.println("grab was interrupted");
        return;
        }
    }

    public void paint(Graphics g) {
        // Display some pixel values
        int status = pg.getStatus();
        if ((status & ABORT) != 0) {
        g.drawString("Image grab was aborted", 10, 100);
        } else if ((status & ALLBITS) != 0) {
        g.drawString("Image grab is complete", 10, 100);
        } else if ((status & FRAMEBITS) != 0) {
        g.drawString("Frame grab is complete", 10, 100);
        } else if ((status & SOMEBITS) != 0) {
        g.drawString("Image grab is under way", 10, 100);
        }
        if ((status & (WIDTH|ALLBITS|FRAMEBITS)) != 0) {
        FontMetrics fm = g.getFontMetrics();
        String caption = "First 3 pixels: ";
        int x = 10;
        int w = pg.getWidth();
        Object pix = pg.getPixels();
        ColorModel cm = pg.getColorModel();

        g.drawString(caption, x, 50);
        x += fm.stringWidth(caption);
        if (pix instanceof byte[]) {
            for (int i = 0; i < Math.min(3, w); i++) {
            String s = Integer.toString(((byte[])pix)[i]&0xff, 16);
            g.drawString(s, x, 50);
            x += fm.stringWidth(s + " ");
            }
        } else {
            for (int i = 0; i < Math.min(3, w); i++) {
            String s = Integer.toString(((int[])pix)[i], 16);
            g.drawString(s, x, 50);
            x += fm.stringWidth(s + " ");
            }
        }
        }
    }
    }

Send feedback to:java-awt@java.sun.com
Copyright © 1996, Sun Microsystems, Inc. All rights reserved.


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.JWindow
  • 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 setFocusableWindow(boolean focusableWindow)

    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.JWindow

setFocusableWindow/isFocusableWindow: These methods are declared final in JWindow to enforce the restriction that all JWindows constructed with a 'null' owner must be non-focusable. This restriction is necessary because Swing constructs such JWindows so that they are owned by a private, hidden Frame, and the new focus implementation requires that KeyEvents intended for a Window or its descendants be proxied through that Frame. Since X11 requires a window to be mapped in order to be focused, a JWindow with a 'null' owner could never receive KeyEvents on X11.

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().


Examples of Using the JDK 1.1 AWT

This page contains links to examples (applets and their source code) of using new features in the JDK 1.1 AWT. These examples were provided by the AWT team.

How to Run 1.1 Examples

To view the applets on the following pages, you can use the HotJava browser or the JDK Applet Viewer.

Because the applets on the following pages depend on 1.1 features, they do not run in 1.0 browsers! Microsoft and Netscape browsers are still based on 1.0 -- they don't run 1.1 applets.

If you attempt to view the following pages in a 1.0 browser such as Netscape Navigator 4.0, you will be given a button to press which will display a picture of what the applets would look like running under 1.1. The following examples all run successfully in the HotJava browser and the JDK Applet Viewer.

The Examples

  • Lightweight Components
    Includes general instructions for creating and using lightweight components. Contains applets that show off the following lightweight components: round buttons, Openlook buttons, spinners, and gauges.

  • JDK 1.1 Event Examples
    Includes examples of handling mouse, mouse motion, and window events using inner classes (anonymous or named). Also shows how to redispatch events.

  • Unicode (and using an inner class for event handling)
    Note: This example doesn't fully work under the 1.1beta3 release, since Symbol and Zapf Dingbat mapping to Unicode characters isn't supported until after beta3.

For the latest information on the AWT, consult The AWT Home Page.


JDK 1.1 Event Examples

Please wait while the applet determines what environment to run in...

Your browser is completely ignoring the <APPLET> tag!


Lightweight Components

Starting with the JDK 1.1 Beta 3 release, the AWT supports lightweight components. Lightweight components are essential in the following situations:
  • You want to create a custom component that isn't rectangular.
  • You want to create a custom component that's partly (or entirely) transparent.
  • You want to use multiple components that can draw in each others' areas.
  • Your program contains many components and would be too inefficient if implemented with heavyweight components.

This page tells you how to create lightweight components, and then gives you links to examples -- pages with applets that use lightweight components (source code included, of course). For more details about what lightweight components are and how they work, see Java AWT: Lightweight UI Framework.

How to Create Lightweight Components

To create a lightweight component, you need to create a class that directly extends one of the following classes:

  • Component
  • Container
  • a class that implements a lightweight component -- for example, a non-AWT class that is a subclass of Component or Container
Your class needs to provide both the look and the feel of the component. You'll typically need to implement the following methods:
  • One or more constructors. If the component responds to any events, such as mouse clicks, the constructor(s) should invoke the enableEvents method.
  • The paint method, so that it draws the component's representation onscreen.
  • As appropriate, methods to let the state of the component be changed programmatically -- for example, setText. Besides changing the component's internal state, each of these methods should call the repaint method if the component's appearance should change. If the component's size should change, then call the invalidate method before calling repaint.
  • As appropriate, methods to let listeners be registered and unregistered for the component. For example, a button should implement the addActionListener and removeActionListener methods, which should add the specified listener using the AWTEventMulticaster add and remove methods, respectively.
  • The contains method if the component responds to events to only part of its entire possible drawing area.
  • Any appropriate processXxx methods. For example, a button would implement processMouseEvent to change the button's state and to generate actionPerformed messages as appropriate.

Lightweight components place special requirements on their containers:

  • Lightweight components sometimes flash noticeably unless you put them in a container that performs double buffering. See the Gauge example for an example of a double-buffered container.
  • Lightweight components will not appear if their container implements a paint method that doesn't call super.paint. In other words, if you implement a container that performs some drawing -- for example, one that draws a box around its display area -- make sure the container's paint method invokes super.paint!

Code Examples and Applets

This section links to four pages, each with an example that illustrates an aspect of lightweight components. Each page includes one applet and links to the applet's source code. If you're using a browser that includes support for 1.1beta3, then your browser will be able to run the applet on each page. Otherwise, you'll need to use another tool, such as the JDK Applet Viewer, to view the applet on each page.

Note: You must use a 1.1 browser such as HotJava or the JDK Applet Viewer to view the applets on the following pages. If you have trouble running the applets, go here.

Here are the examples:

Round Button Example
Demonstrates how easy it is to create a lightweight component.

Openlook Button Example
Modifies the Round Button example to show a more realistic looking lightweight component.

Spinner Example
Demonstrates how to animate a lightweight component.

Gauge Example
Demonstrates how to animate a lightweight component using double buffering to eliminate flicker. Contains sourced code for both 1.1-only and "Swing" versions of the example. For more information on Swing, browse the the Swing release documentation.

Back to Examples of Using the JDK 1.1 AWT


Gauge Example

 Back to How to Create Lightweight Components

Gauge Lightweight Component Example

Your browser is completely ignoring the <APPLET> tag!

Source Code:

  • Gauge.java
  • DoubleBufferPanel.java
  • ExampleApplet.java
To see how this component might be written using Swing (the part of the JFC that implements a new component architecture), see this source code:
  • Gauge.java
  • ExampleApplet.java
No DoubleBufferPanel class is necessary because Swing provides one.


Openlook Button Example

 Back to How to Create Lightweight Components

Openlook Button Lightweight Component Example

Your browser is completely ignoring the <APPLET> tag!

Source Code:

  • OpenlookButton.java
  • ExampleApplet.java


Round Button Example

 Back to How to Create Lightweight Components

Round Button Lightweight Component Example

Your browser is completely ignoring the <APPLET> tag!

Source Code:

  • RoundButton.java
  • ExampleApplet.java


Spinner Example

 Back to How to Create Lightweight Components

Spinner Lightweight Component Example

Your browser is completely ignoring the <APPLET> tag!

Source Code:

  • Spinner.java
  • ExampleApplet.java


Unicode Example

Please wait while the applet determines what environment to run in...

Your browser is completely ignoring the <APPLET> tag!


V1.4 JavaBeans API Enhancements

Java

API Enhancements to the JavaBeansTM Component API in v1.4

 JavaBeansTM Component API
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 © 2002 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software


JavaBeans

Java

JavaBeansTM Component API

 Documentation Contents
The JavaBeans component API extends the Java platform's Write Once, Run AnywhereTM capability to reusable component development. In fact, the JavaBeans architecture takes interoperability a major step forward -- your code runs on every OS and also within any application environment. A developer who creates components based on the JavaBeans architecture (beans) secures a future in the emerging network software market without losing customers that use proprietary platforms, because beans interoperate with ActiveX, OpenDoc, and LiveConnect.

As of v 1.4, the java.beans package provides support for long-term persistence -- reading and writing a bean as a textual representation of its property values. Other changes in v 1.4 include improvements to the Introspector class, a JavaBeans Specification amendment to support retrieving listeners from a bean, and miscellaneous improvements in the treatment of event listeners.

API Enhancements

  • API Enhancements in v1.4

ActiveX Bridge Developer Guide

  • ActiveX Bridge Developer Guide

JavaBeans Tutorial

Located on the Java Software website:
  • JavaBeans Tutorial

Beans Specifications

  • BeanContext Specification (PDF | PS)
    Extensible Runtime Containment and Services Protocol for JavaBeans

Located on the Java Software website:
  • JavaBeansTM Specification (PDF and PS)

JavaBeans API Specification

(javadoc)
  • java.beans
  • java.beans.beancontext

For More Information

Located on the Java Software website:
  • The JavaBeans Home Page
  • Beans Development Kit and More Information
    Contains BeanBox test container, example beans, demo source code, and introductory documentation
  • Assorted persistence-related articles in The Swing Connection
    Contain examples of using persistence, including a downloadable graphical user interface (GUI) builder that reads and writes XML documents representing GUIs.

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-beans@java.sun.com 		Sun
Java Software


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. The resources for this application—boundprop.exe, BoundPropTest.dll, and JellyBean.dll—can be found in the boundprop subdirectory of this document, should you care to set it up and run it.

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. Resources for this application—cal.exe and JCalendarPanel.dll—can be found in the cal subdirectory of this document, should you care to set it up and run it. (Copy JCalendarPanel.dll to <jre_home>\axbridge\bin and register it; then execute cal.exe. You should see the following.

Sample calendar window


ActiveX Bridge

ActiveX Bridge Developer Guide

Implementation for SDK/JRE 1.4.2 and Above

This document includes the following topics:

  • Overview
  • Supported OSs and ActiveX Containers
  • Packaging the Bean
  • Using the Bean in an Application
  • Deployment
  • Java Objects in the ActiveX Bridge Environment
  • Other Topics
    • Methods
    • Properites
    • Ambient properties
    • Events
    • Security
    • JVM Configuration

The Example Applications chapter describes two example applications.

Overview

The ActiveX Bridge allow a component based on JavaBeans(TM) component architecture ("bean") to be effectively packaged as an ActiveX control, thereby allowing it to be used as a functional component in an ActiveX container.

Note that this implementation of the ActiveX Bridge may not be compatible with the previous implementation for SDK/JRE 1.1 through 1.3.1. In order to use the new bridge, beans will need to be repackaged.

Supported OSs and ActiveX Containers

For development purposes, this implementation supports the following OSs and ActiveX Containers:

OSs: Windows NT, 2000, XP.

ActiveX Containers: Visual Studio 6.0 with SP3.

Note that packaged beans should run on any Windows platform and in any ActiveX container—not just those platforms and containers listed above.

Packaging the Bean

Notes

1. Running the packager (packager.exe) requires that you have the following installed on your computer:

  • SDK 1.4.2 or higher
  • Microsoft Visual C++ 6.0 with SP3

2. In order for packager to work you must first run VCVARS32.BAT. cd to the /bin directory where it is located in your Microsoft Visual C++ installation and type VCVARS32.

Use packager.exe to generated the .dll for the bean.

Use of packager.exe is as follows:

Packager Usage

Usage: packager [-options] <jar file name> <bean name>

where options include:
   -clsid <class-id>         CLSID for the packaged bean
   -out <output directory>   destination directory for the packaged bean
   -reg                      consent to register the Active-X control

Additional Information

  • A .dll can contain only one packaged bean. Thus, a separate .jar file is required for each bean.
  • If one .jar file depends on another .jar file or .class file(s), then you will need to set CLASSPATH.
  • <jar file name> needs to include the path to the .jar file. The path may be full or relative.
  • <bean name> needs to be the fully qualified package name of the bean (e.g., sunw.demo.jelly.JellyBean.).
  • If the -clsid option is not used, the packaged bean CLSID will be generated randomly. This -clsid option allows you to specify the same CLSID for a given bean every time.
  • Default: Unless -out is specified, packager.exe will generate the .dll fill in the same directory in which it is executed. If you specify the -out parameter, then packager places the .dll file in the directory you specify. For example, you might want to place the .dll in a directory called <jre_home>\axbridge\bin where it could be deployed with an application. (Note that <jre_home> would be the public JRE, not the private one. The public JRE on Windows is normally located at C:\Program Files\Java\j2re1.4.2. The private JRE, associated with the SDK, is normally located at C:\j2sdk1.4.2\jre.)
  • If -out is not specified, or -out does not specify <jre_home>\axbridge\bin, then the -reg option should not be used.

Example

For example, suppose <bean>.jar is jelly.jar; jelly.jar is located at C:\my_bean_jars; the fully qualified bean name is sunw.demo.jelly.JellyBean; and the SDK is j2sdk1.4.2. You could run packager.exe as follows:

C:\j2sdk1.4.2\bin\packager -clsid {D824B185-AE3C-11D6-ABF5-00B0D07B8581} -out C:\Program Files\Java\j2re1.4.2\axbridge\bin -reg C:\my_bean_jars\jelly.jar sunw.demo.jelly.JellyBean

The packager would:

  • generate a .dll file with the bean name (JellyBean.dll) and put it in the j2re\axbridge\bin directory;
  • create a j2re1.4.2\axbridge\lib directory and place jelly.jar there;
  • register the bean .dll with the CLSID D824B185-AE3C-11D6-ABF5-00B0D07B8581.

Manually Registering the bean .dll

If you don't use the -reg option with packager.exe as shown above, you can manually register the .dll with regsvr32.exe. cd to the directory where the .dll file is located (e.g., C:\Program Files\Java\j2re1.4.2\axbridge\bin) and type:

<path_regsvr32>\regsvr32 <bean name>.dll

Suppose you are running Windows 2000. regsvr32.exe is located at C:\winnt\system32 on Windows 2000. Then to register JellyBean.dll you would do this:

C:\Program Files\Java\j2re1.4.2\axbridge\bin>C:\winnt\system32\regsvr32 JellyBean.dll

This will:

  • create a CLSID registry entry for JellyBean.dll under HKEY_CLASSES_ROOT;
  • create a j2re1.4.2\axbridge\lib directory and place jelly.jar there.

Using the Bean in an Application

Now that the bean is registered as an ActiveX control, you should be able to insert it into an ActiveX container. In the case of the ActiveX Control Test Container that comes with Visual Studio, on the main menu go to Edit>Insert New Control... and scroll down the list until you find the bean control. In the case of the JellyBean.dll control, it shows up as JellyBean Bean Control. Below it is shown inserted into the Visual Studio test container.

Deployment

To deploy a bean packaged as an ActiveX control in an application, you will need to include registration of the .dll as part of the installation process. The .dll should be installed into the <jre_home>axbridge\bin directory, and it should be registered there with regsvr32.exe. As stated previously, when the .dll is registered, the bean .jar will be placed in the <jre_home>\axbridge\lib directory.

Java Objects in the ActiveX Bridge Environment

Java objects are accessible via wrapper objects supporting the IDispatch interface; i.e., they are accessed indirectly through the ActiveX Bridge. For example, if you are working with a packaged bean in Visual Basic (VB) and want to pass a Java object as an argument to a bean method, it is necessary that either (1) the bean has a method that returns the required type of Java object; or (2) the Java object is available as a bean property.

For example, consider the calendar example, JCalendarPanel, in the Examples chapter.

If you were working directly in Java with this bean, you would create a Date object, set its properties, then pass it as an argument to the setSelectedDate() method of JCalendarePanel. The way this is done with the ActiveX Bridge as follows:

Assuming you are working in VB and have an instance of JCalendarPanel called JCalendarPanel1, in VB you could use the JCalendarPanel1.selectedDate property to get a Date object:

Set dat = JCalendarPanel1.selectedDate

Then you would use the VB methods of the Date object (dat) to set it. For instance:

dat.setYear (1986 - 1900)
dat.setMonth (11 - 1)
dat.setDate 24

Finally, you would use the setSelectedDate method of JCalendarPanel1 to set the date:

JCalendarPanel1.setSelectedDate dat

Other Considerations

Methods and Method Overloading

All the methods provided by the BeanInfo via getMethodDescriptors() are accessible from ActiveX containers.

However, if a method is overloaded, only the method which takes the highest number of arguments will be available. This is because COM IDL does not support overloading. However, the argument and return value type will be VARIANT. Each argument is optional. For any overloaded method you will need to refer to the bean documentation to know the exact number of arguments and their types. Methods or property names which are identical to any MIDL keyword are dropped.

Properties

All the properties are accessible though the bridge with the same access right as defined in the BeanInfo via PropertyDescriptor. The ActiveX bridge will invoke the accessor methods as defined in the PropertyDescriptor.

If the bean property is bound or constrained, the bindable or requestedit flags are set in the attributes of the COM property. The container is notified of the property change through IPropertyNotifySink interface. If the property is constrained and the container denies the property change, then the bean PropertyVetoException is thrown by the bridge.

For primitive types and for string, font, and color properties, most ActiveX containers like Visual Basic will allow direct manipulation of properties in their PropertySheet. For all other properties, such as arrays or objects, the properties will not be accessible in the PropertySheet but can still be invoked through the scripting language associated with the container.

Ambient Properties

The bridge will support four ambient properties that get translated to the bean properties if the bean component implements these properties. These ambient properties will be read and set on the bean component when the component is initialized and each time a change notification for the ambient properties is received.

DISPID_BACKCOLOR
DISPID_FORECOLOR
DISPID_FONT
DISPID_ENABLED

The bridge will forward ActiveX container ambient property changes to the bean via setting properties.

Events

All source interfaces that are declared as default in the EventSetDescriptor array returned by the BeanInfo will be merged into one interface which is declared as being the ActiveX default source interface. It is an ActiveX requirement that at least the default source interface is accessible by ActiveX containers.

Each method returned by the getListenerMethodDescriptors API of the EventSetDescriptor is mapped to an ActiveX event. The event name is the method name. Since all default interfaces of beans are merged to a unique interface, interfaces that contain the same method name are not allowed.

Consider, for example the java.awt.event.ActionListener source interface:

public interface ActionListener extends EventListener {

  public void actionPerformed(ActionEvent e);

}

The ActiveX event name generated from this interface definition is actionPerformed. For example, in case of Visual Basic the event signature looks like this:

Private Sub Button_actionPerformed (ByVal evt As Object)

  MsgBox evt.toString

End-Sub

The evt provided to the container is an automation object, which represents the java.awt.AWTEvent Object. Containers could access the information on the event by invoking the methods supported by the AWTEvent class.

Security

The bean packaged as an ActiveX control will be part of a stand-alone application. Hence it will be executed outside the applet sand box security model.

In Internet Explorer scripting of the bean is not safe, as it has been granted the AllPermission permission.

JVM Configuration

Note that you can configure the JVM through the Java Plug-in Control Panel. The following tabs are relevant to the ActiveX Bridge:

  • Basic
  • Advanced
  • Proxies

You can use the Java Console for debugging beans.


Extensible Runtime Containment and Services Protocol for JavaBeans Version 1.0

Send comments to java-beans@java.sun.com.

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:

  1. 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.
  2. 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.

    3. OR

  3. 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:

  1. Associate the newly instantiated Applet with the appropriate AppletContext.
  2. Instantiate an AppletStub() and associate that AppletStub with the Applet via
    1. an invocation of setStub().
    2. 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.0.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.0.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.0.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.0.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.0.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 Extensible Runtime Containment and Server Protocol for JavaBeans
    , Version 1.0

    Copyright © 2003 Sun Microsystems, Inc. All rights reserved.


Extensible Runtime Containment and Server Protocol for JavaBeans Version 1.0

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 © 2003 Sun Microsystems, Inc. All rights reserved.


Collections Framework Change Summary

Java

Collections Framework API Change Summary
This page summarizes the differences between the 1.2 and 1.3 releases of the Collections Framework, along with a brief rationale for each change.

Convenience Implementations

  • Added singletonList and singletonMap. Previously, there was a convenience implementation for singleton Set, but no corresponding implementation for List and Map.
  • Added EMPTY_MAP. Previously, there were constants for the empty Set and List, but no corresponding constant for Map.

Special-purpose Implementation

  • Added Map constuctor for WeakHashMap. The Map interface dictates that most Map implementations should have a "copy constructor" that takes a Map argument. WeakHashMap lacked such a constructor in the 1.2 release.

Copyright © 1995-99 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: collections-comments@java.sun.com 		Sun
Java Software


Collections Framework Change Summary for J2SDK 1.4

Java

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 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 © 2001 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: collections-comments@java.sun.com 		Sun
Java Software


Java Collections API Design FAQ
This document answers frequently asked questions concerning the design of the Java collections framework. It is derived from the large volume of traffic on the collections-comments alias. It serves as a design rationale for the collections framework.

Core Interfaces - General Questions

  1. Why don't you support immutability directly in the core collection interfaces so that you can do away with optional operations (and UnsupportedOperationException)?

  2. Won't programmers have to surround any code that calls optional operations with a try-catch clause in case they throw an UnsupportedOperationException?

  3. Why isn't there a core interface for "bags" (AKA multisets)?

  4. Why don't you provide for "gating functions" that facilitate the implementation of type-safe collections?

  5. Why didn't you use "Beans-style names" for consistency?

Collection Interface

  1. Why doesn't Collection extend Cloneable and Serializable?

  2. Why don't you provide an "apply" method in Collection to apply a given method ("upcall") to all the elements of the Collection?

  3. Why didn't you provide a "Predicate" interface, and related methods (e.g., a method to find the first element in the Collection satisfying the predicate)?

  4. Why don't you provide a form of the addAll method that takes an Enumeration (or an Iterator)?

  5. Why don't the concrete implementations in the JDK have Enumeration (or Iterator) constructors?

  6. Why don't you provide an Iterator.add method?

List Interface

  1. Why don't you rename the List interface to Sequence; doesn't "list" generally suggest "linked list"? Also, doesn't it conflict with java.awt.List?

  2. Why don't you rename List's set method to replace, to avoid confusion with Set.

Map Interface

  1. Why doesn't Map extend Collection?

Iterator Interface

  1. Why doesn't Iterator extend Enumeration?

  2. Why don't you provide an Iterator.peek method that allows you to look at the next element in an iteration without advancing the iterator?

Miscellaneous

  1. Why did you write a new collections framework instead of adopting JGL (a preexisting collections package from ObjectSpace, Inc.) into the JDK?

  2. Why don't you eliminate all of the methods and classes that return "views" (Collections backed by other collection-like objects). This would greatly reduce aliasing.

  3. Why don't you provide for "observable" collections that send out Events when they're modified?

Core Interfaces - General Questions

  1. Why don't you support immutability directly in the core collection interfaces so that you can do away with optional operations (and UnsupportedOperationException)?

    This is the most controversial design decision in the whole API. Clearly, static (compile time) type checking is highly desirable, and is the norm in Java. We would have supported it if we believed it were feasible. Unfortunately, attempts to achieve this goal cause an explosion in the size of the interface hierarchy, and do not succeed in eliminating the need for runtime exceptions (though they reduce it substantially).

    Doug Lea, who wrote a popular Java collections package that did reflect mutability distinctions in its interface hierarchy, no longer believes it is a viable approach, based on user experience with his collections package. In his words (from personal correspondence) "Much as it pains me to say it, strong static typing does not work for collection interfaces in Java."

    To illustrate the problem in gory detail, suppose you want to add the notion of modifiability to the Hierarchy. You need four new interfaces: ModifiableCollection, ModifiableSet, ModifiableList, and ModifiableMap. What was previously a simple hierarchy is now a messy heterarchy. Also, you need a new Iterator interface for use with unmodifiable Collections, that does not contain the remove operation. Now can you do away with UnsupportedOperationException? Unfortunately not.

    Consider arrays. They implement most of the List operations, but not remove and add. They are "fixed-size" Lists. If you want to capture this notion in the hierarchy, you have to add two new interfaces: VariableSizeList and VariableSizeMap. You don't have to add VariableSizeCollection and VariableSizeSet, because they'd be identical to ModifiableCollection and ModifiableSet, but you might choose to add them anyway for consistency's sake. Also, you need a new variety of ListIterator that doesn't support the add and remove operations, to go along with unmodifiable List. Now we're up to ten or twelve interfaces, plus two new Iterator interfaces, instead of our original four. Are we done? No.

    Consider logs (such as error logs, audit logs and journals for recoverable data objects). They are natural append-only sequences, that support all of the List operations except for remove and set (replace). They require a new core interface, and a new iterator.

    And what about immutable Collections, as opposed to unmodifiable ones? (i.e., Collections that cannot be changed by the client AND will never change for any other reason). Many argue that this is the most important distinction of all, because it allows multiple threads to access a collection concurrently without the need for synchronization. Adding this support to the type hierarchy requires four more interfaces.

    Now we're up to twenty or so interfaces and five iterators, and it's almost certain that there are still collections arising in practice that don't fit cleanly into any of the interfaces. For example, the collection-views returned by Map are natural delete-only collections. Also, there are collections that will reject certain elements on the basis of their value, so we still haven't done away with runtime exceptions.

    When all was said and done, we felt that it was a sound engineering compromise to sidestep the whole issue by providing a very small set of core interfaces that can throw a runtime exception.

  2. Won't programmers have to surround any code that calls optional operations with a try-catch clause in case they throw an UnsupportedOperationException?

    It was never our intention that programs should catch these exceptions: that's why they're unchecked (runtime) exceptions. They should only arise as a result of programming errors, in which case, your program will halt due to the uncaught exception.

  3. Why isn't there a core interface for "bags" (AKA multisets)?

    The Collection interface provides this functionality. We are not providing any public implementations of this interface, as we think that it wouldn't be used frequently enough to "pull its weight." We occasionally return such Collections, which are implemented easily atop AbstractCollection (for example, the Collection returned by Map.values).

  4. Why don't you provide for "gating functions" that facilitate the implementation of type-safe collections?

    We are extremely sympathetic to the desire for type-safe collections. Rather than adding a "band-aid" to the framework that enforces type-safety in an ad hoc fashion, the framework has been designed to mesh with all of the parameterized-types proposals currently being discussed. In the event that parameterized types are added to the language, the entire collections framework will support compile-time type-safe usage, with no need for explicit casts. Unfortunately, this won't happen in the the 1.2 release. In the meantime, people who desire runtime type safety can implement their own gating functions in "wrapper" collections surrounding JDK collections.

  5. Why didn't you use "Beans-style names" for consistency?

    While the names of the new collections methods do not adhere to the "Beans naming conventions", we believe that they are reasonable, consistent and appropriate to their purpose. It should be remembered that the Beans naming conventions do not apply to the JDK as a whole; the AWT did adopt these conventions, but that decision was somewhat controversial. We suspect that the collections APIs will be used quite pervasively, often with multiple method calls on a single line of code, so it is important that the names be short. Consider, for example, the Iterator methods. Currently, a loop over a collection looks like this:

        for (Iterator i = c.iterator(); i.hasNext(); )
        System.out.println(i.next());
    Everything fits neatly on one line, even if the Collection name is a long expression. If we named the methods "getIterator", "hasNextElement" and "getNextElement", this would no longer be the case. Thus, we adopted the "traditional" JDK style rather than the Beans style.

Collection Interface

  1. Why doesn't Collection extend Cloneable and Serializable?

    Many Collection implementations (including all of the ones provided by the JDK) will have a public clone method, but it would be mistake to require it of all Collections. For example, what does it mean to clone a Collection that's backed by a terabyte SQL database? Should the method call cause the company to requisition a new disk farm? Similar arguments hold for serializable.

    If the client doesn't know the actual type of a Collection, it's much more flexible and less error prone to have the client decide what type of Collection is desired, create an empty Collection of this type, and use the addAll method to copy the elements of the original collection into the new one.

  2. Why don't you provide an "apply" method in Collection to apply a given method ("upcall") to all the elements of the Collection?

    This is what is referred to as an "Internal Iterator" in the "Design Patterns" book (Gamma et al.). We considered providing it, but decided not to as it seems somewhat redundant to support internal and external iterators, and Java already has a precedent for external iterators (with Enumerations). The "throw weight" of this functionality is increased by the fact that it requires a public interface to describe upcalls.

  3. Why didn't you provide a "Predicate" interface, and related methods (e.g., a method to find the first element in the Collection satisfying the predicate)?

    It's easy to implement this functionality atop Iterators, and the resulting code may actually look cleaner as the user can inline the predicate. Thus, it's not clear whether this facility pulls its weight. It could be added to the Collections class at a later date (implemented atop Iterator), if it's deemed useful.

  4. Why don't you provide a form of the addAll method that takes an Enumeration (or an Iterator)?

    Because we don't believe in using Enumerations (or Iterators) as "poor man's collections." This was occasionally done in prior releases, but now that we have the Collection interface, it is the preferred way to pass around abstract collections of objects.

  5. Why don't the concrete implementations in the JDK have Enumeration (or Iterator) constructors?

    Again, this is an instance of an Enumeration serving as a "poor man's collection" and we're trying to discourage that. Note however, that we strongly suggest that all concrete implementations should have constructors that take a Collection (and create a new Collection with the same elements).

  6. Why don't you provide an Iterator.add method?

    The semantics are unclear, given that the contract for Iterator makes no guarantees about the order of iteration. Note, however, that ListIterator does provide an add operation, as it does guarantee the order of the iteration.

List Interface

  1. Why don't you rename the List interface to Sequence; doesn't "list" generally suggest "linked list"? Also, doesn't it conflict with java.awt.List?

    People were evenly divided as to whether List suggests linked lists. Given the implementation naming convention, <Implementation><Interface>, there was a strong desire to keep the core interface names short. Also, several existing names (AbstractSequentialList, LinkedList) would have been decidedly worse if we changed List to Sequence. The naming conflict can be dealt with by the following incantation:

        import java.util.*;
    import java.awt.*;
    import java.util.List;   // Dictates interpretation of "List"

  2. Why don't you rename List's set method to replace, to avoid confusion with Set.

    It was decided that the "set/get" naming convention was strongly enough enshrined in the language that we'd stick with it.

Map Interface

  1. Why doesn't Map extend Collection?

    This was by design. We feel that mappings are not collections and collections are not mappings. Thus, it makes little sense for Map to extend the Collection interface (or vice versa).

    If a Map is a Collection, what are the elements? The only reasonable answer is "Key-value pairs", but this provides a very limited (and not particularly useful) Map abstraction. You can't ask what value a given key maps to, nor can you delete the entry for a given key without knowing what value it maps to.

    Collection could be made to extend Map, but this raises the question: what are the keys? There's no really satisfactory answer, and forcing one leads to an unnatural interface.

    Maps can be viewed as Collections (of keys, values, or pairs), and this fact is reflected in the three "Collection view operations" on Maps (keySet, entrySet, and values). While it is, in principle, possible to view a List as a Map mapping indices to elements, this has the nasty property that deleting an element from the List changes the Key associated with every element before the deleted element. That's why we don't have a map view operation on Lists.

Iterator Interface

  1. Why doesn't Iterator extend Enumeration?

    We view the method names for Enumeration as unfortunate. They're very long, and very frequently used. Given that we were adding a method and creating a whole new framework, we felt that it would be foolish not to take advantage of the opportunity to improve the names. Of course we could support the new and old names in Iterator, but it doesn't seem worthwhile.

  2. Why don't you provide an Iterator.peek method that allows you to look at the next element in an iteration without advancing the iterator?

    It can be implemented atop the current Iterators (a similar pattern to java.io.PushbackInputStream). We believe that its use would be rare enough that it isn't worth including in the interface that everyone has to implement.

Miscellaneous

  1. Why did you write a new collections framework instead of adopting JGL (a preexisting collections package from ObjectSpace, Inc.) into the JDK?

    If you examine the goals for our Collections framework (in the Overview), you'll see that we are not really "playing in the same space" as JGL. Quoting from the "Design Goals" Section of the Java Collections Overview: "Our main design goal was to produce an API that was reasonably small, both in size, and (more importantly) in 'conceptual weight.'"

    JGL consists of approximately 130 classes and interfaces; its main goal was consistency with the C++ Standard Template Library (STL). This was not one of our goals. Java has traditionally stayed away from C++'s more complex features (e.g., multiple inheritance, operator overloading). Our entire framework, including all infrastructure, contains approximately 25 classes and interfaces.

    While this may cause some discomfort for some C++ programmers, we feel that it will be good for Java in the long run. As the Java libraries mature, they inevitably grow, but we are trying as hard as we can to keep them small and manageable, so that Java continues to be an easy, fun language to learn and to use.

  2. Why don't you eliminate all of the methods and classes that return "views" (Collections backed by other collection-like objects). This would greatly reduce aliasing.

    Given that we provide core collection interfaces behind which programmers can "hide" their own implementations, there will be aliased collections whether the JDK provides them or not. Eliminating all views from the JDK would greatly increase the cost of common operations like making a Collection out of an array, and would do away with many useful facilities (like synchronizing wrappers). One view that we see as being particularly useful is List.subList. The existence of this method means that people who write methods taking List on input do not have to write secondary forms taking an offset and a length (as they do for arrays).

  3. Why don't you provide for "observable" collections that send out Events when they're modified?

    Primarily, resource constraints. If we're going to commit to such an API, it has to be something that works for everyone, that we can live with for the long haul. We may provide such a facility some day. In the meantime, it's not difficult to implement such a facility on top of the public APIs.

Copyright © 1997-1999 Sun Microsystems, Inc., 901 San Antonia Ave., Palo Alto, CA 94303 USA. All rights reserved.

Please send comments to: collections-comments@java.sun.com 		Sun
Java Software


The Collections Framework

 Documentation Contents
The collections framework is a unified architecture for representing and manipulating collections, allowing them to be manipulated independently of the details of their representation. It reduces programming effort while increasing performance. It allows for interoperability among unrelated APIs, reduces effort in designing and learning new APIs, and fosters software reuse. The framework is based on six collection interfaces. It includes implementations of these interfaces, and algorithms to manipulate them.
Overview
  • Overview - An overview of the Collections framework.
API Specification
  • API Reference - An annotated outline of the classes and interfaces comprising the collections framework, with links into the JavaDoc.
Tutorial
  • Tutorial - A tutorial introduction to the collections framework with plenty of programming examples.
API Enhancements
  • API Enhancements in J2SDK 1.4 - An annotated list of API changes between the 1.3 and 1.4 releases.
  • API Enhancements in the Previous Release - An annotated list of previous API changes in the 1.3 release.
Design FAQ
  • Design FAQ- Answers to frequently asked questions concerning the design of the collections framework.

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: collections-comments@java.sun.com 		Sun
Java Software


Collections Framework Overview

Introduction

The Java 2 platform includes a new collections framework. A collection is an object that represents a group of objects (such as the familiar Vector class). A collections framework is a unified architecture for representing and manipulating collections, allowing them to be manipulated independently of the details of their representation.

The primary advantages of a collections framework are that it:

  • Reduces programming effort by providing useful data structures and algorithms so you don't have to write them yourself.
  • Increases performance by providing high-performance implementations of useful data structures and algorithms. Because the various implementations of each interface are interchangeable, programs can be easily tuned by switching implementations.
  • Provides interoperability between unrelated APIs by establishing a common language to pass collections back and forth.
  • Reduces the effort required to learn APIs by eliminating the need to learn multiple ad hoc collection APIs.
  • Reduces the effort required to design and implement APIs by eliminating the need to produce ad hoc collections APIs.
  • Fosters software reuse by providing a standard interface for collections and algorithms to manipulate them.

The collections framework consists of:

  • Collection Interfaces - Represent different types of collections, such as sets, lists and maps. These interfaces form the basis of the framework.
  • General-purpose Implementations - Primary implementations of the collection interfaces.
  • Legacy Implementations - The collection classes from earlier releases, Vector and Hashtable, have been retrofitted to implement the collection interfaces.
  • Wrapper Implementations - Add functionality, such as synchronization, to other implementations.
  • Convenience Implementations - High-performance "mini-implementations" of the collection interfaces.
  • Abstract Implementations - Partial implementations of the collection interfaces to facilitate custom implementations.
  • Algorithms - Static methods that perform useful functions on collections, such as sorting a list.
  • Infrastructure - Interfaces that provide essential support for the collection interfaces.
  • Array Utilities - Utility functions for arrays of primitives and reference objects. Not, strictly speaking, a part of the Collections Framework, this functionality is being added to the Java platform at the same time and relies on some of the same infrastructure.

Collection Interfaces

There are six collection interfaces. The most basic interface is Collection. Three interfaces extend Collection: Set, List, and SortedSet. The other two collection interfaces, Map and SortedMap, do not extend Collection, as they represent mappings rather than true collections. However, these interfaces contain collection-view operations, which allow them to be manipulated as collections.

All of the modification methods in the collection interfaces are labeled optional. Some implementations may not perform one or more of these operations, throwing a runtime exception (UnsupportedOperationException) if they are attempted. Implementations must specify in their documentation which optional operations they support. Several terms are introduced to aid in this specification:

  • Collections that do not support any modification operations (such as add, remove and clear) are referred to as unmodifiable. Collections that are not unmodifiable are referred to modifiable.
  • Collections that additionally guarantee that no change in the Collection object will ever be visible are referred to as immutable. Collections that are not immutable are referred to as mutable.
  • Lists that guarantee that their size remains constant even though the elements may change are referred to as fixed-size. Lists that are not fixed-size are referred to as variable-size.
  • Lists that support fast (generally constant time) indexed element access are known as random access lists. Lists that do not support fast indexed element access are known as sequential access lists. The RandomAccess marker interface is provided to allow lists to advertise the fact that they support random access. This allows generic algorithms to alter their behavior to provide good performance when applied to either random or sequential access lists.

Some implementations may restrict what elements (or in the case of Maps, keys and values) may be stored. Possible restrictions include requiring elements to:

  • Be of a particular type.
  • Be non-null.
  • Obey some arbitrary predicate.

Attempting to add an element that violates an implementation's restrictions results in a runtime exception, typically a ClassCastException, an IllegalArgumentException or a NullPointerException. Attempting to remove or test for the presence of an element that violates an implementation's restrictions may result in an exception, though some "restricted collections" may permit this usage.

Collection Implementations

Class that implement the collection interfaces typically have names of the form <Implementation-style><Interface>. The general purpose implementations are summarized in the table below:
 |  | Implementations
Hash Table | Resizable Array | Balanced Tree | Linked List | Hash Table + Linked List
Interfaces | Set | HashSet |  | TreeSet |  | LinkedHashSet
 | List |  | ArrayList |  | LinkedList |
 | Map | HashMap |  | TreeMap |  | LinkedHashMap

The general-purpose implementations support all of the optional operations in the collection interfaces, and have no restrictions on the elements they may contain. They are unsynchronized, but the Collections class contains static factories called synchronization wrappers that may be used to add synchronization to any unsynchronized collection. All of the new implementations have fail-fast iterators, which detect illegal concurrent modification, and fail quickly and cleanly (rather than behaving erratically).

The AbstractCollection, AbstractSet, AbstractList, AbstractSequentialList and AbstractMap classes provide skeletal implementations of the core collection interfaces, to minimize the effort required to implement them. The API documentation for these classes describes precisely how each method is implemented so the implementer knows which methods should be overridden, given the performance of the "basic operations" of a specific implementation.

Design Goals

The main design goal was to produce an API that was reasonably small, both in size, and, more importantly, in "conceptual weight." It was critical that the new functionality not seem alien to current Java programmers; it had to augment current facilities, rather than replacing them. At the same time, the new API had to be powerful enough to provide all the advantages described above.

To keep the number of core interfaces small, the interfaces do not attempt to capture such subtle distinctions as mutability, modifiability, resizability. Instead, certain calls in the core interfaces are optional, allowing implementations to throw an UnsupportedOperationException to indicate that they do not support a specified optional operation. Of course, collection implementers must clearly document which optional operations are supported by an implementation.

To keep the number of methods in each core interface small, an interface contains a method only if either:

  1. It is a truly fundamental operation: a basic operations in terms of which others could be reasonably defined,
  2. There is a compelling performance reason why an important implementation would want to override it.

It was critical that all reasonable representations of collections interoperate well. This included arrays, which cannot be made to implement the Collection interface directly without changing the language. Thus, the framework includes methods to allow collections to be dumped into arrays, arrays to be viewed as collections, and maps to be viewed as collections.

Copyright © 1995-99 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: collections-comments@java.sun.com 		Sun
Java Software


Annotated Outline of the Collections Framework

Java

Annotated Outline of Collections Framework
The collections framework consists of:
  • Collection Interfaces - The primary means by which collections are manipulated.
    • Collection - A group of objects. No assumptions are made about the order of the collection (if any), or whether it may contain duplicate elements.
    • Set - The familiar set abstraction. No duplicate elements permitted. May or may not be ordered. Extends the Collection interface.
    • List - Ordered collection, also known as a sequence. Duplicates are generally permitted. Allows positional access. Extends the Collection interface.
    • Map - A mapping from keys to values. Each key can map to at most one value.
    • SortedSet - A set whose elements are automatically sorted, either in their natural ordering (see the Comparable interface), or by a Comparator object provided when a SortedSet instance is created. Extends the Set interface.
    • SortedMap - A map whose mappings are automatically sorted by key, either in the keys' natural ordering or by a comparator provided when a SortedMap instance is created. Extends the Map interface.
  • General-Purpose Implementations - The primary implementations of the collection interfaces.
    • HashSet - Hash table implementation of the Set interface. The best all-around implementation of the Set interface.
    • TreeSet Red-black tree implementation of the SortedSet interface.
    • LinkedHashSet - Hash table and linked list implementation of the Set interface. An insertion-ordered Set implementation that runs nearly as fast as HashSet.
    • ArrayList - Resizable-array implementation of the List interface. (Essentially an unsynchronized Vector.) The best all-around implementation of the List interface.
    • LinkedList - Doubly-linked list implementation of the List interface. May provide better performance than the ArrayList implementation if elements are frequently inserted or deleted within the list. Useful for queues and double-ended queues (deques).
    • HashMap - Hash table implementation of the Map interface. (Essentially an unsynchronized Hashtable that supports null keys and values.) The best all-around implementation of the Map interface.
    • TreeMap Red-black tree implementation of the SortedMap interface.
    • LinkedHashMap - Hash table and linked list implementation of the Map interface. An insertion-ordered Map implementation that runs nearly as fast as HashMap. Also useful for building caches (see removeEldestEntry(Map.Entry) ).
  • Wrapper Implementations - Functionality-enhancing implementations for use with other implementations. Accessed soley through static factory methods.
    • Collections.unmodifiableInterface - Return an unmodifiable view of a specified collection that throws an UnsupportedOperationException if the user attempts to modify it.
    • Collections.synchronizedInterface - Return a synchronized collection that is backed by the specified (typically unsynchronized) collection. As long as all accesses to the backing collection are through the returned collection, thread-safety is guaranteed.
  • Convenience Implementations - High-performance "mini-implementations" of the collection interfaces.
    • Arrays.asList - Allows an array to be viewed as a list.
    • EMPTY_SET, EMPTY_LIST and EMPTY_MAP - Constants representing the empty set and list (immutable).
    • singleton, singletonList, and singletonMap - Returns an immutable "singleton" set, list, or map, containing only the specified object (or key-value mapping).
    • nCopies - Returns an immutable list consisting of n copies of a specified object.
  • Legacy Implementations - Older collection classes have been retrofitted to implement the collection interfaces.
    • Vector - Synchronized resizable-array implementation of the List interface with additional "legacy methods."
    • Hashtable - Synchronized hash table implementation of the Map interface that does not allow null keys or values, with additional "legacy methods."
  • Special Purpose Implementations
    • WeakHashMap - an implementation of the Map interface that stores only weak references to its keys. Storing only weak references allows key-value pairs to be garbage-collected when the key is no longer referenced outside of the WeakHashMap. This class provides the easiest way to harness the power of weak references. It is useful for implementing "registry-like" data structures, where the utility of an entry vanishes when its key is no longer reachable by any thread.
    • IdentityHashMap - 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.
  • Abstract Implementations - Partial implementations of the collection interfaces to facilitate custom implementations.
    • AbstractCollection - Skeletal implementation of a collection that is neither a set nor a list (such as a "bag" or multiset).
    • AbstractSet - Skeletal implementation of a set.
    • AbstractList - Skeletal implementation of a list backed by a random-access data store (such as an array).
    • AbstractSequentialList - Skeletal implementation of a list backed by a sequential-access data store (such as a linked list).
    • AbstractMap - Skeletal implementation of a map.
  • Algorithms
    • sort(List) - Sorts a list using a merge sort algorithm, which provides average-case performance comparable to a high-quality quicksort, guaranteed O(n*log n) performance (unlike quicksort), and stability (unlike quicksort). (A stable sort is one that does not reorder equal elements.)
    • binarySearch(List, Object) - Searches for an element in an ordered list using the binary search algorithm.
    • reverse(List) - Reverses the order of the elements in the a list.
    • shuffle(List) - Randomly permutes the elements in a list.
    • fill(List, Object) - Overwrites every element in a list with the specified value.
    • copy(List dest, List src) - Copies the source list into the destination list.
    • min(Collection) - Returns the minimum element in a collection.
    • max(Collection) - Returns the maximum element in a collection.
    • rotate(List list, int distance) - Rotates all of the elements in the list by the the specified distance.
    • replaceAll(List list, Object oldVal, Object newVal) - Replaces all occurrences of one specified value with another.
    • indexOfSubList(List source, List target) - Returns the index of the first sublist of source that is equal to target.
    • lastIndexOfSubList(List source, List target) - Returns the index of the last sublist of source that is equal to target.
    • swap(List list, int, int) - Swaps the elements at the specified positions in the specified list.
  • Infrastructure
    • Iterators - Similar to the familiar Enumeration interface, but more powerful, and with improved method names.
      • Iterator - In addition to the functionality of the Enumeration interface, allows the user to remove elements from the backing collection with well defined, useful semantics.
      • ListIterator - Iterator for use with lists. In addition to the functionality of the Iterator interface, supports bi-directional iteration, element replacement, element insertion and index retrieval.
    • Ordering
      • Comparable - Imparts a natural ordering to classes that implement it. The natural ordering may be used to sort a list or maintain order in a sorted set or map. Many classes have been retrofitted to implement this interface.
      • Comparator - Represents an order relation, which may be used to sort a list or maintain order in a sorted set or map. Can override a type's natural ordering, or order objects of a type that does not implement the Comparable interface.
    • Runtime Exceptions
      • UnsupportedOperationException - Thrown by collections if an unsupported optional operation is called.
      • ConcurrentModificationException - Thrown by iterators and list iterators if the backing collection is modified unexpectedly while the iteration is in progress. Also thrown by sublist views of lists if the backing list is modified unexpectedly.
    • Performance
      • RandomAccess - 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.
  • Array Utilities
    • Arrays - Contains static methods to sort, search, compare and fill arrays of primitives and Objects.

    Copyright © 1995-99 Sun Microsystems, Inc. All Rights Reserved.

    Please send comments to: collections-comments@java.sun.com     		Sun
    Java Software


CORBA and Java technologies

Java OMG Sun

CORBA Technology and the JavaTM 2 Platform, Standard Edition

The Java 2 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 2 platform. It consists of an Object Request Broker (ORB), APIs for the the RMI programming model, and APIs for the 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 J2SE leverage CORBA

Common Object Request Broker Architecture (CORBA) technology is the open standard for heterogeneous computing. CORBA complements the JavaTM platform by providing a distributed object framework, services to support that framework, and interoperability with other languages. The Java platform complements CORBA by providing "Write Once, Run AnywhereTM" portability, a highly productive implementation environment, and a very robust platform. By combining the Java platform with CORBA and other key enterprise technologies, the Java 2 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 2 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 JavaTM Standard Edition, v1.2 and higher includes an ORB that is available in every deployment of the Java 2 Platform, Standard Edition. To read more about the ORB class, follow the link.

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 JavaTM, 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 JavaTM 2 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 Java Language to OMG IDL Mapping Specification.

The IDL Programming Model

What is the IDL Programming Model

The IDL programming model, known as JavaTM 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.

JavaTM IDL is part of the Java 2 Platform, Standard Edition, v1.2 and above. To develop applications with Java IDL, use JavaTM 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 Tutorial: Getting Started with Java IDL .

  • For more information on how IDL maps to the Java language, see see the OMG IDL to Java Language Mapping Specification.

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 "Write Once, Run AnywhereTM" portability, its 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 JavaBeansTM technology (EJBTM).

Enterprise JavaBeans is part of the Java 2 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 © 2002 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software


Autodownload Files

Autdownload Files (Windows Only)

The table below lists various JRE releases and the .cab files that can be used for autodownloading them. Note that not every release of the JRE has an associated .cab file for autodownload.

JRE Release | .cab File for codebase attribute for Autodownload
1.3.0_05 | jinstall-1_3_0_05-win.cab
1.3.1_01 | jinstall-1_3_1_01-win.cab
1.3.1_02 | jinstall-1_3_1_02-win.cab
1.3.1_03 | jinstall-1_3_1_03-win.cab
1.3.1_04 | jinstall-1_3_1_04-win.cab
1.3.1_05 | jinstall-1_3_1_05-windows-i586.cab
1.3.1_06 | jinstall-1_3_1_06-windows-i586.cab
1.3.1_07 | jinstall-1_3_1_07-windows-i586.cab
1.3.1_08 | jinstall-1_3_1_08-windows-i586.cab
1.4.0 | jinstall-1_4_0-win.cab
1.4.0_01 | jinstall-1_4_0_01-win.cab
1.4.0_02 | jinstall-1_4_0_02-win.cab
1.4.0_03 | jinstall-1_4_0_03-win.cab
1.4.0_04 | jinstall-1_4_0_04-win.cab
1.4.1 | jinstall-1_4_1-windows-i586.cab
1.4.1_01 | jinstall-1_4_1_01-windows-i586.cab
1.4.1_02 | jinstall-1_4_1_02-windows-i586.cab
1.4.1_03 | jinstall-1_4_1_03-windows-i586.cab
1.4.2 | jinstall-1_4_2-windows-i586.cab


Drag and Drop

 Documentation Contents
Drag and Drop enables data transfer both across JavaTM programming language and native applications, between Java programming language applications, and within a single Java programming language application.
Enhancements
  • Enhancements in Java 2 Platform 1.4 include new support for data transfer using Swing. See Swing Data Transfer.

  • Enhancements in previous release Java 2 Platform 1.3 included two new methods in class java.awt.datatransfer.DataFlavor.
    • getReaderForText(Transferable transferable)
    • selectBestTextFlavor(DataFlavor[] availableFlavors)
    Without the use of these methods, unicode-encoded text will not be dragged onto some native-application documents correctly (an extra character will be left at the beginning of the text. These methods deliver ISO8859-1 text instead of unicode text to avoid this problem.
Drag and Drop Specification
  • Drag and Drop Specification. Also available in postscript and pdf

Drag and Drop API Specification
  • java.awt.dnd

Related Information

Located on the Java Software website:
  • The JFC Home Page

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send Drag and Drop comments to our Java Drag and Drop team: java-dnd@java.sun.com 		Sun Microsystems, Inc
Java Software


Copyright Page for Sun Microsystems, Inc.

Sun Microsystems, Inc.

Copyright 1996-1999 Sun Microsystems, Inc.
901 San Antonio Road, Palo Alto, California 94303-4900 U.S.A.

All rights reserved. Copyright in this document is owned by Sun Microsystems, Inc.

Sun Microsystems, Inc. (SUN) hereby grants to you a fully-paid, nonexclusive, nontransferable, perpetual, worldwide limited license (without the right to sublicense) under SUN's intellectual property rights that are essential to practice this specification. This license allows and is limited to the creation and distribution of clean room implementations of this specification that (i) include a complete implementation of the current version of this specification without subsetting or supersetting, (ii) implement all the interfaces and functionality of the standard java.* packages as defined by SUN, without subsetting or supersetting, (iii) do not add any additional packages, classes or methods to the java.* packages (iv) pass all test suites relating to the most recent published version of this specification that are available from SUN six (6) months prior to any beta release of the clean room implementation or upgrade thereto, (v) do not derive from SUN source code or binary materials, and (vi) do not include any SUN binary materials without an appropriate and separate license from SUN.

RESTRICTED RIGHTS LEGEND

Use, duplication, or disclosure by the U.S. Government is subject to restrictions of FAR 52.227-14(g)(2)(6/87) and FAR 52.227-19(6/87), or DFAR 252.227-7015(b)(6/95) and DFAR 227.7202-1(a).

This software and documentation 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.

SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.

TRADEMARKS

Sun, the Sun logo, Sun Microsystems, SunNet Manager, SunCore, SunWeb, Sun Workshop, Sun Workstation, Java, the Java Coffee Cup logo, JavaSoft, JavaBeans, HotJava, HotJava Views, Java WorkShop, Visual Java, JDK and all Java-based trademarks and logos, Solaris, the Solaris sunburst design, SolarNet, Solstice, NEO, Joe, Netra, NFS, PC-NFS, ONC, ONC+, OpenWindows, SNM, The Network Is The Computer, ToolTalk, Ultra, Ultracomputing, Ultraserver, Where The Network Is Going, and XView, are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries.

UNIX is a registered trademark in the United States and other countries, exclusively licensed through X/Open Company, Ltd. OPEN LOOK® is a registered trademark of Novell, Inc.

All SPARC trademarks are used under license and are trademarks or registered trademarks of SPARC International, Inc. in the United States and other countries. Products bearing SPARC trademarks are based upon an architecture developed by Sun Microsystems, Inc.

The OPEN LOOK® and Sun(TM) Graphical User Interfaces were developed by Sun Microsystems, Inc. for its users and licensees. Sun acknowledges the pioneering efforts of Xerox in researching and developing the concept of visual or graphical user interfaces for the computer industry. Sun holds a non-exclusive license from Xerox to the Xerox Graphical User Interface, which license also covers Sun's licensees who implement OPEN LOOK GUIs and otherwise comply with Sun's written license agreements.

X Window System is a trademark of the X Consortium, Inc.

OpenStep is a trademark owned by NeXT and is used under license.

THIS PUBLICATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.

THIS PUBLICATION COULD INCLUDE TECHNICAL INACCURACIES OR TYPOGRAPHICAL ERRORS. CHANGES ARE PERIODICALLY ADDED TO THE INFORMATION HEREIN; THESE CHANGES WILL BE INCORPORATED IN NEW EDITIONS OF THE PUBLICATION. SUN MICROSYSTEMS, INC. MAY MAKE IMPROVEMENTS AND/OR CHANGES IN THE PRODUCT(S) AND/OR THE PROGRAM(S) DESCRIBED IN THIS PUBLICATION AT ANY TIME.

For further information on Intellectual Property matters, see Java Trademark Guidelines or contact Sun Legal Department:

  • Trademarks, Karrie Malouf at (650) 336-7419
  • Patents at 415-336-0069


Drag and Drop subsystem for the Java Foundation Classes

Laurence P. G. Cable.

Send comments to java-dnd@java.sun.com.

1.0 Requirements

This specification is based upon an (incomplete) earlier work undertaken in 1996 to specify a Uniform Data Transfer Mechanism, Clipboard, and Drag and Drop facilities for AWT.

The AWT implementation in JDK1.1 introduced the Uniform Data Transfer Mechanism and the Clipboard protocol. This specification defines the API for the Drag and Drop facilities for JavaTM 2 Platform based upon, but extending these 1.1 UDT API’s.

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 JFC 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
    • 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

    5. 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 (JFC) 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 DropTarget(s) 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 users 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 users 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 users 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 users 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 {
    protected 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;

    protected boolean cursorDirty;
 }

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 users 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 users 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 preform 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.1

    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 boolean isDropTargetLocal();

     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 getTargetActions() method returns the drop actions, supported by, and returned from the current DropTarget (if any in the case of dropActionChanged()).

    The getDropAction() method returns the action that is currently selected by the users gesture.

    The getTargetActions() method returns the set of actions supported by the current DropTarget.

    The logical OR of these two results defines the actual effect of a Drop.

    The getGestureModifiers() returns the current state of the input device modifiers, usually the mouse buttons and keyboard modifiers, associated with the users gesture.

    The isDropTargetLocal() method returns true if the current DropTarget is contained within the same JVM as the DragSource, and false otherwise. This information can be useful to the implementor of the DragSource’s Transferable in order to implement certain local optimizations.

    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 users ends the gesture outside a DropTarget, or if the DropTarget invokes rejectDrop(), the isGetDropSuccess() 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 Component’s 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 and the data types available.

    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) 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” and the types of the data 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 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 return the current “actions”, or operations (ACTION_MOVE, ACTION_COPY, or ACTION_LINK) the DragSource associates with the current Drag and Drop gesture.

    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.EventObject2 {

    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 DataFlavor[] getDataFlavors();

    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 return the current “actions”, or operations (ACTION_MOVE, ACTION_COPY, or ACTION_REFERENCE) the DragSource associates with the current Drag and Drop 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 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 defined to be the intersection of both the Drop action selected by the users gesture, and the set of actions supported by the source, at the time of the Drop. The resulting action is normally the intersection of this value and the set of actions supported by the target at the time of the drop.

    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.ropComplete().

    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 {
    public static FlavorMap getSystemFlavorMap();

    public synchronized Map
        getNativesForFlavors(DataFlavor[] dfs);

    public synchronized Map
        getFlavorsForNatives(String[] natives);

    public static String
        encodeJavaMIMEType(DataFlavor df);

    public static String
        encodeJavaMimeType(java.util.mime.MimeType mime);

    public static boolean
        isEncodedJavaMimeType(String mimeStr);

    public static DataFlavor
        createFlavorFromEncodedJavaMimeType(String ejmts);

    public static java.util.mime.MimeType
        createMimeTypeFromEncodedJavaMimeType(
                            String ejmts
        );
}

    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 it’s 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);
}
    1It would be nice to design an API that would allow the DragSource to be notified of the DropTarget’s selected operation before the DropTarget invokes the source Transferable’s getTransferData() method, sadly however, OLE’s bass-ackwards DnD protocol forces the above design on us where the operation is reported after it has occurred, this makes life for the source implementor harder when supporting certain “Link” semantics.
    1
    2This could be a subclass of AWTEvent but there seems little motivation to make it so.

    Contents | Previous | Drag and Drop subsystem for the Java Foundation Classes
    ,

    Copyright © 2003 Sun Microsystems, Inc. All rights reserved.


1.0 Requirements 2

Drag and Drop subsystem for the Java Foundation Classes
Contents | Previous | Next

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

Contents | Previous | Next

Copyright © 2003 Sun Microsystems, Inc. All rights reserved.


Optional Package Overview

Java

Optional Packages - An Overview

Contents

  • What an optional package is
  • Installed optional packages
  • Download optional packages

What an optional package is

Note: Optional packages were formerly known as standard extensions or just extensions.

Optional packages are packages of Java classes and associated native code that application developers can use to extend the functionality of the core platform. The extension mechanism allows the Java virtual machine (VM) to use the optional-package classes in much the same way as the VM uses bootstrap classes. (Bootstrap classes are those implementing the core platform, contained in jre/lib/rt.jar and several other important jar files. These include classes of the public API such as java.lang, java.io, etc., and classes supporting the platform's internationalization/localization features.). Like bootstrap classes, classes in optional packages do not have to be placed on the class path. The extension mechanism also provides a way for needed optional packages to be retrieved from specified URLs when they are not already installed in the Java 2 Runtime Environment or Java 2 SDK.

Optional packages are embodied in JAR files, and every JAR file is a potential optional package. A JAR file can be made to play the role of an optional package in two ways:

  • by being placed in a special location in the Java 2 Runtime Environment or Java 2 SDK directory structure - in which case it is an installed optional package.
  • by being referenced in a specified way from the manifest of the JAR file of an applet or application - in which case it is a download optional package.
When the VM is searching for a class of a particular name, it will first look among the bootstrap classes. If it fails to find the desired class there, it will next look for the class among any installed optional packages. If it doesn't find the class among either the bootstrap classes or the installed optional packages, the VM will search among any download optional packages referenced by the application or applet. The VM only searches the class path if it fails to find a class among the bootstrap classes or optional package classes.

Installed optional packages

Installed optional packages are JAR files in the directory
lib/ext       [in the Java 2 Runtime Environment]
jre/lib/ext   [in the Java 2 SDK]
Classes within JAR files in this directory can be used by applets and applications much as if they were part of the set of bootstrap classes, without having to explicitly include them in the class path.

An installed optional package's native code binaries, if any, are placed in

jre\bin         [Microsoft Windows]
jre/lib/<arch>  [Solaris operating environment]
where <arch> is the Solaris processor architecture, either sparc or i386. Native libraries may also be placed in jre/lib/ext/<arch> for both Microsoft Windows and the Solaris operating environment, where <arch> will be i386 on Microsoft Windows systems. The jre/lib/ext/<arch> directory is searched after jre\bin or jre/lib/<arch>.

When the Java VM encounters a class name, it looks first for the class in the runtime environment. If it fails to find the desired class among the classes that are part of the standard runtime environment, the VM will search for the class in any JAR files in the optional packages directory.

Note that there is nothing special about any particular JAR file itself or the classes it contains that makes it an installed optional package. It is an installed optional package by virtue of its location in jre/lib/ext.

The manifest of an installed optional package's JAR file should contain version and vendor information for use by applets that need to use the optional packages classes. The attributes that specify the version and vendor information are described in Optional Package Versioning. Here is an example of what such a manifest might look like:

Manifest-version: 1.0
Extension-Name: javax.extension
Specification-Version: 1.0
Specification Vendor: Sun Microsystems, Inc.
Implementation-Vendor: Sun Microsystems, Inc.
Implementation-Vendor-Id: com.sun
Sealed: true
This version and vendor information can be used by the Java Plug-in when running an applet to see if optional packages needed by the applet are installed, are up to date, and are from the vendor requested by the applet. If not, the Java Plug-in can prompt the applet user to download the proper optional package. See Optional Package Versioning for more information.

If a class is not found after searching both the system classes and the classes in the installed optional packages, the extension mechanism will search for the class in a download optional package....

Download optional packages

A download optional package is a JAR files that is specified in the Class-Path header field in the manifest of another JAR files. Classes in download optional packages may be used by classes in the referencing JAR file. In a typical situation, an applet will be bundled in a JAR file whose manifest references a JAR file (or several JAR files) that will serve as an optional package for the purposes of that applet. Optional packages may reference each other in the same way.

A Class-Path header might look like this, for example:

Class-Path: servlet.jar infobus.jar acme/beans.jar
This specifies that the classes in the files servlet.jar, infobus.jar, and acme/beans.jar will serve as optional pakcages for purposes of the classes in the JAR file whose manifest contains this header. The URLs in the Class-Path field are given relative to the URL of the JAR file of the applet or application.

Unlike the case of installed optional packages, the location of the JAR files that serve as download optional packages is irrelevent. A download optional package is an optional package because it is specified as the value of the Class-Path header in another JAR file's manifest, not because it has any particular location.

Another difference between installed and download optional packages is that only applets and applications bundled in a JAR file can make use of download optional packages. Applets and applications not bundled in a JAR file don't have a manifest from which to reference download optional packages.

When searching for a class, the VM first searches among the classes in the system classes and in any installed optional packages. If the class is not found in either the system classes or in the installed optional packages, the VM will search for the class in any download optional packages referenced by the manifest of the application or applet. A download optional package will not be downloaded if a desired class is found among the installed optional packages, even if the download optional package is referenced by the manifest file of the applet or application.

The extension mechanism will not install a download optional package in the Java 2 Runtime Environment or Java 2 SDK directory structure. Download optional packages do not become installed extentions after they have once been downloaded.

Unlike installed optional packages, download optional packages cannot have any native code.

Copyright © 1997, 1998 Sun Microsystems, Inc. All Rights Reserved. Sun

Java Software


The Java Extension Mechanism

for Support of Optional Packages

 Documentation Contents
Note: Optional packages are the new name for what used to be known as standard extensions. The "extension mechanism" is that functionality of the Java 2 SDK and Java 2 Runtime Environment that supports the use of optional packages.

Optional packages are packages of Java classes (and any associated native code) that application developers can use to extend the functionality of the core platform. The extension mechanism allows the Java virtual machine (VM) to use the classes of the optional extension in much the same way as the VM uses classes in the Java 2 Platform. The extension mechanism also provides a way for needed optional packages to be retrieved from specified URLs when they are not already installed in the Java 2 SDK or Runtime Environment.

Overview
  • Overview - What optional packages are and how to use them.
Extension Mechanism Architecture
  • Extension Mechanism Architecture - Notes on the extension mechanism API and how optional packages use the Jar file format.
Enhancements Made in Previous Release J2SDK 1.3
  • Enhancements to the extension mechanism in version 1.3 of the Java 2 SDK included an extended set of manifest attributes that can be used for checking vendor and versioning information of installed optional packages. If an applet requires an optional package that isn't installed, or that is installed but has the wrong version number or is not from the appropriate vendor, the Java Plug-in can download the needed extension from a specified URL. For more information, see Optional-Package Versioning.
API Specification

The following classes play a role in the extension mechanism:

  • java.lang.ClassLoader
  • java.lang.Package
  • java.lang.Thread
  • java.net.JarURLConnection
  • java.net.URLClassLoader
  • java.security.SecureClassLoader
See also the API Details section of the mechanism specification for notes on these APIs.

Tutorial

Located on the Java Software website:
  • The Java Extension Mechanism trail of the Java Tutorial.

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software


The Extension Mechanism

Java

Extension Mechanism Architecture

Contents

  • Introduction
  • The Extension Mechanism
    • Architecture
    • Optional Package Deployment
    • Bundled Optional Packages
    • Installed Optional Packages
  • Optional Package Sealing
  • Optional Package Security
  • API Details

Introduction

Note: Optional packages are the new name for what used to be known as standard extensions. The "extension mechanism" is that functionality of the Java 2 SDK and Java 2 Runtime Environment that supports the use of optional packages.

This document describes the Java platform's mechanism for handling optional packages. An optional package is a group of packages housed in one or more JAR files that implement an API that extends the Java platform. Optional package classes extend the platform in the sense that the virtual machine can find and load them without their being on the class path, much as if they were classes in the platform's core API.

An implementation of an optional package may consist of code written in the Java programming language and, less commonly, platform-specific native code. In addition, it may include properties, localization catalogs, images, serialized data, and other resources specific to the optional package.

Support for optional packages in browsers such as Internet Explorer and Netscape Navigator is available through the Java Plug-in.

A optional package is an implementation of an open, standard API (examples of optional packages from Sun are JavaServlet, Java3D, JavaManagement). Most optional packages are rooted in the javax.* namespace, although there may be exceptions.

The Extension Mechanism

Architecture

The extension mechanism is designed to contain the following elements:
  • an optional package or application packaged as a JAR file can declare dependencies on other JAR files, thus allowing an application to consist of multiple modules, and,
  • the class loading mechanism is augmented to search installed optional packages (and other libraries) for classes, and, if that fails, to search along an application-specified path for classes.
Applications must therefore, in general, be prepared to specify and supply the optional packages (and, more generally, libraries) that it needs. The system will prefer installed copies of optional packages (and libraries) if they exist; otherwise, it will delegate to the class loader of the application to find and load the referenced optional package (and library) classes.

This architecture, since it allows applications, applets and servlets to extend their own class path, also permits packaging and deploying these as multiple JAR files.

Each optional package or application consists of at least one JAR file containing an optional manifest, code and assorted resources. As described below, this primary JAR file can also include additional information in its manifest to describe dependencies on other JAR files. The jar command line tool included with the Java 2 SDK provides a convenient means of packaging optional packages, although any ZIP-compatible archiving tool should work as well. (See the reference pages for the jar tool: [Windows][Solaris])

An optional package or application may refer to additional JAR files which will be referenced from the primary JAR, and these can optionally contain their own dependency information as well.

Packages comprising optional packages should be named per the standard package naming conventions when implementing optional packages. These conventions are outlined in The Java Language Specification, but the requirement that the domain prefix be specified in all upper case letters has been removed. For example, the package name com.sun.server is an accepted alternative to COM.sun.server. Unique package naming is recommended in order to avoid conflicts, because applications and optional packages may share the same class loader.

Optional Package Deployment

An optional package may either be bundled with an application or installed in the JRE for use by all applications. Bundled optional packages are provided at the same code base as the application and will automatically be downloaded in the case of network applications (applets). For this reason, bundled optional packages are often called download optional packages. Installed optional packages are loaded when first used and will be shared by all applications running on the same runtime environment.

When packaging optional packages, the JAR file manifest can be used to identify vendor and version information (see The Java Versioning Specification).

Classes for installed optional packages are shared by all code in the same virtual machine. Thus, installed optional packages are similar to the platform's core classes (in rt.jar), but with an associated class loader and a pre-configured security policy as described below.

Classes for bundled optional packages are private to the class loader of the application, applet or servlet. In the case of network applications such as applets, these optional packages will be automatically downloaded as needed. Since class loaders are currently associated with a codebase, this permits multiple applets originating from the same codebase to share implementations (JARs).

Bundled Optional Packages

The manifest for an application or optional package can specify one or more relative URLs referring to the JAR files and directories for the optional packages (and other libraries) that it needs. These relative URLs will be treated relative to the code base that the containing application or optional package JAR file was loaded from.

An application (or, more generally, JAR file) specifies the relative URLs of the optional packages (and libraries) that it needs via the manifest attribute Class-Path. This attribute lists the URLs to search for implementations of optional packages (or other libraries) if they cannot be found as optional packages installed on the host Java virtual machine*. These relative URLs may include JAR files and directories for any libraries or resources needed by the application or optional package. Relative URLs not ending with '/' are assumed to refer to JAR files. For example,

Class-Path: servlet.jar infobus.jar acme/beans.jar images/
Multiple Class-Path headers may be specified, and are combined sequentially.

Currently, the URLs must be relative to the code base of the JAR file for security reasons. Thus, remote optional packages will originate from the same code base as the application. A future enhancement will leverage the facilities of the Java 2 Platform's Security APIs to allow references to JAR files at other URLs.

Each relative URL is resolved against the code base that the containing application or optional package was loaded from. If the resulting URL is invalid or refers to a resource that cannot be found then it is ignored.

The resulting URLs are used to extend the class path for the application, applet, or servlet by inserting the URLs in the class path immediately following the URL of the containing JAR file. Any duplicate URLs are omitted. For example, given the following class path:

        a.jar b.jar
If optional package b.jar contained the following Class-Path manifest attribute:
        Class-Path: x.jar a.jar
Then the resulting application class path would be the following:
        a.jar b.jar x.jar
Of course, if x.jar had dependencies of its own then these would be added according to the same rules and so on for each subsequent URL. In the actual implementation, JAR file dependencies are processed lazily so that the JAR files are not actually opened until needed.

Installed Optional Packages

In Sun's implementation of the Java 2 Platform, the JAR files of a installed optional package are placed in a standard local code source
<java-home>\lib\ext                     [Windows]
<java-home>/lib/ext                     [Solaris]
Its native code libraries, if any, are placed in
<java-home>\bin                         [Windows]
<java-home>/lib/<arch>                  [Solaris]
Here <java-home> refers to the directory where the runtime software is installed (which is the top-level directory of the JRE or the jre directory in the Java 2 SDK), and <arch> refers to the Solaris processor architecture (sparc or x86).

A installed optional package may additionally contain one or more shared libraries (such as .dll files) and executables. Native libraries may also be placed in jre/lib/ext/<arch> for both Windows and Solaris, where <arch> will be x86 on Windows systems. The jre/lib/ext/<arch> directory is searched after jre\bin (Windows) or jre/lib/<arch> (Solaris).

Currently, an optional package that contains native code cannot be downloaded by network code, whether such code is trusted or not, into the virtual machine at execution time. An optional package that contains native code and is bundled with a network application must be installed in the Java 2 SDK or Java 2 Runtime Environment.

By default, installed optional packages in this standard directory are trusted. That is, they are granted the same privileges as if they were core platform classes (those in rt.jar). This default privilege is specified in the system policy file, but can be overridden for a particular optional package by adding the appropriate policy file entry.

Note also that if a installed optional package JAR is signed by a trusted entity, then it will be granted the privileges associated with the trusted signer.

Other locations for installed optional packages can be specified through the system property java.ext.dirs. This property specifies one or more directories to search for installed optional packages, each separated by File.pathSeparatorChar. The default setting for this property is the standard directory for installed optional packages indicated above.

Optional Package Sealing

JAR files and packages can be optionally sealed, so that an optional package or package can enforce consistency within a version.

A package sealed within a JAR specifies that all classes defined in that package must originate from the same JAR. Otherwise, a SecurityException is thrown.

A sealed JAR specifies that all packages defined by that JAR are sealed unless overridden specifically for a package.

A sealed package is specified via the manifest attribute, Sealed, whose value is true or false (case irrelevant). For example,

Name: javax/servlet/internal/
Sealed: true
specifies that the javax.servlet.internal package is sealed, and that all classes in that package must be loaded from the same JAR file.

If this attribute is missing, the package sealing attribute is that of the containing JAR file.

A sealed JAR is specified via the same manifest header, Sealed, with the value again of either true or false. For example,

Sealed: true
specifies that all packages in this archive are sealed unless explicitly overridden for a particular package with the Sealed attribute in a manifest entry.

If this attribute is missing, the module is assumed to not be sealed, for backwards compatibility. The system then defaults to examining package headers for sealing information.

Package sealing is also important for security, because it restricts access to package-protected members to only those classes defined in the package that originated from the same JAR file.

Package sealing is checked for installed as well as downloaded optional packages, and will result in a SecurityException if violated. Also, the null package is not sealable, so classes that are to be sealed must be placed in their own packages.

Optional Package Security

The code source for a installed optional package (namely <java-home>/lib/ext) has a pre-configured security policy associated with it. In Sun's implementation, the exact level of trust granted to JARs in this directory is specified by the standard security policy configuration file
<java-home>/lib/security/java.policy
The default policy is for a installed optional package to behave the same way it would if were part of the core platform. This follows from the common need for a installed optional package to load native code.

The Java Security Model provides some safety when installed optional package code is called from untrusted code. However optional package code must be carefully reviewed for potential security breaches wherever it uses privileged blocks.

A remotely loaded optional package that needs to use access-checked system services (such as file I/O) to function correctly must either be signed by a trusted entity or loaded from a trusted source.

Consult the Java security documentation for further details regarding how to write optional package and application code to use the Java 2 Platform's security features.

API Details

The following classes in the Java 2 platform support the extension mechanism:
  • public class java.lang.ClassLoader (changed)

    • The class loader delegation model allows a "parent" class loader to be specified which will always be searched first when loading a class or resource before attempting to load it locally. New class loader implementations override the methods findClass and findResource in order to specify how classes and resources are loaded locally.

    • getSystemClassLoader

      • Returns the system class loader for delegation. This is the default delegation parent for new ClassLoader instances, and is typically the class loader used to start the application.
    • loadClass

      • If the class has already been loaded then just return it. Otherwise, try loading the class from the parent class loader (or virtual machine's built-in class loader, called the bootstrap class loader, if no parent was specified). If still not found, then call the method findClass to load the class locally.

    • findClass

      • Looks in this class loader for the specified class. This method should be overridden in new class loader implementations. Its default implementation throws ClassNotFoundException.

    • getResource

      • Try fetching the resource from the parent class loader (or bootstrap class loader if no parent was specified). If still not found, then call the method getLocalResource to load the resource locally.

    • findResource

      • Looks in this class loader for the specified resource. This method should be overridden by new class loader implementations. Its default implementation returns null.

    • getResources

      • Returns an enumeration of all the resource URLs matching the specified resource name. This enumeration includes all of the matched resources of the parent class loader followed by the enumeration returned by findResources.

    • findResources

      • Returns an enumeration of all the local resource URLs matching the given name. This method should be overridden by new class loader implementations. Its default implementation returns null.

    The delegation model provides a consistent and well defined search policy for loading classes and resources that simplifies class loader implementation. These changes are backward compatible and will not affect existing class loader implementations. However, applications that wish to create their own class loaders and use optional packages must use the delegation model.

    The following example demonstrates a simple network class loader:

        public class NetClassLoader extends ClassLoader {
        URL url;

        public NetClassLoader(URL url, ClassLoader parent) {
            super(parent);
            this.url = url;
        }

        protected Class findClass(String name)
            throws ClassNotFoundException
        {
            .. load class from URL ...
        }

        protected URL findResource(String name) {
            try {
                URL u = new URL(url, name);
                if (u.openConnection() != null) {
                    return u;
                } else {
                    return null;
                }
            } catch (java.net.MalformedURLException mue) {
                   // handle exception
            } catch (java.io.IOException ioe) {
                   // handle exception
            }
        }
    }
    This example will search the parent class loader (or bootstrap class loader, if no parent was specified) for classes and resources before checking the given URL. Classes and resources will be loaded according to the delegation model as described above.
  • public class java.lang.Package

    • The method isSealed can be used to check if a package has been sealed, in which case it will return true. A second form of this method takes a URL and will return true if the package is sealed with respect to the specified URL. This can be used to in class loader implementations to keep track of currently sealed packages when loading new classes.

  • public class java.net.URLClassLoader

    • This class provides the basic class loader support for optional packages and applications. It overrides both the findClass and findResource methods to search one or more base URLs for classes and resources. The search is lazy, such that a URL is not opened until needed.

    URLClassLoader manages a search path of URLs that is used to load classes and resources. Initially, this is set to the URLs specified when the class loader was created, but can be extended by Class-Path manifest attribute as described above.

    URLClassLoader supports all of the manifest attributes for versioning specified in The Java Versioning Specification.

    In addition, the following main manifest attributes are supported:

    • Main-Class: <classname> (no default)

      • Specifies the main class of an application. This is used for invoking an application JAR file.

    • Class-Path: <urls..> (no default)

      • Local search path of relative JAR and directory URLs for loading classes and resources. URLs not ending in '/' are assumed to refer to JAR files.

    • Sealed: <true|false> (default false)

      • All of the packages defined in this JAR file, with the exception of the "null" package, are sealed. The "null" package can never be sealed. This header can also be used to seal individual packages.

*As used on this web site, the terms "Java Virtual Machine" or "JVM" mean a virtual machine for the Java platform.

Copyright © 1997-1999 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: Java Software

Sun


Extension Versioning

Java

Optional Package Versioning

 Optional Package Documentation

Note: Optional packages is the new term for what used to be known as standard extensions or just extensions.

This section includes the following topics:

  • Overview
  • Manifest Attributes for Use by Installed Optional Packages
  • Manifest Attributes for Use by Applet Jar Files
  • Java Plug-in Update Rules
  • Download and Installation of Optional Packages

Overview

Version 1.3 of the JavaTM 2 Platform introduced support for an expanded set of Jar-file manifest attributes that enable applets to specify version and vendor information for the optional packages that they require. The manifests of Jar-packaged applets can specify a URL at which the latest version of the optional package the Java Plug-in can download if

  • the needed optional package is not already installed in the Java runtime environment, or
  • the optional package is installed but has an out-of-date version number, or
  • the optional package is installed but is not from a specified vendor.

The manifest attributes that can be used to specify version and vendor information are described below.

Manifest Attributes for Use by Installed Optional Packages

The following portion of a sample manifest file illustrates the attributes that are available for use by optional packages.
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.0
The attributes in this example are:
Extension-Name
This attribute specifies a name for the optional package contained in the Jar file. The name should be a unique identifier such as the name of the main package comprising the optional package.
Specification-Vendor
This attribute identifies the company that originated the specification to which the optional package conforms.
Specification-Version
This attribute specifies the version number of the specification to which the implementation conforms.
Implementation-Vendor-Id
This attribute's value is a unique identifier for the company that produced the optional package implementation contained in the Jar file.
Implementation-Vendor
This attribute's value is the name of the company that produced the implementation of the optional package. This attribute should be used only for such purposes such as user feedback, and the Java Plug-in software does not use it to identify the optional package vendor. Rather, the Java Plug-in relies on the Implementation-Vendor-Id attribute to provide unique vendor identification.
Implementation-Version
This attribute indicates the vendor's version number for the implementation of the optional package.

Each optional package installed in the Java runtime environment can use these manifest attributes to identify itself. When the Java Plug-in is running an applet that requires an optional package, the plug-in can access these attributes to determine if the installed optional packages match the vendor and version criteria specified by the applet. The applet specifies such information by using the manifest attributes described in the following section. Note that all of the above manifest attributes should be included in an optional package's manifest. If the plug-in looks for but doesn't find one of these attributes in an optional package's manifest, it will assume that the optional package is not suitable for the applet.

Manifest Attributes for Use by Applet Jar Files

The following sample manifest file illustrates the attributes that are available for use by Jar-packaged applets. (This sample is for illustrative purposes only. No actual optional packages are available at the URLs mentioned in this example.)
Extension-List: javahelp java3d
javahelp-Extension-Name: javax.help
javahelp-Specification-Version: 1.0
javahelp-Implementation-Version: 1.0.3
javahelp-Implementation-Vendor-Id: com.sun
javahelp-Implementation-URL: http://java.sun.com/products/stdext/javahelp.jar
java3d-Extension-Name: javax.3d
java3d-Specification-Version: 1.0
java3d-Implementation-Version: 1.2.1
java3d-Implementation-Vendor-Id: com.sun
java3d-Implementation-URL: http://java.sun.com/products/stdext/java3d.jar
The attributes used in this example are:
Extension-List
This attribute indicates the optional packages that are needed by the applet. Each optional package listed in this attribute will have a set of additional attributes that the applet uses to specify which version and vendor of the optional package it requires.
<extension>-Extension-Name
This attribute is the unique name of the optional package. The Java Plug-in will compare the value of this attribute with the Extension-Name attribute in the manifests of installed optional packages to determine if the optional package is installed.
<extension>-Specification-Version (Optional)
This attribute specifies the minimum optional package specification version that is required by the applet. The Java Plug-in will compare the value of this attribute with the Specification-Version attribute of the installed optional package to determine if the optional package is up to date.
<extension>-Implementation-Version (Optional)
This attritute specifies the miminum optional package implementation version number that is required by the applet. The Java Plug-in will compare the value of this attribute with the Implementation-Version attribute of the installed optional package to see if a more recent implementation needs to be downloaded.
<extension>-Implementation-Vendor-Id (Optional)
This attribute can be used to identify the vendor of an optional package implementation if the applet requires an implementation from a specific vendor. The Java Plug-in will compare the value of this attribute with the Implementation-Vendor-Id attribute of the installed optional package.
<extension>-Implementation-URL
This attritute specifies a URL that can be used to obtain the most recent version of the optional package if the required version is not already installed.

Java Plug-in Update Rules

The Java Plug-in performs the following determinations when loading an applet whose manifest indicates that it needs one or more optional packages:

  • If an optional package with the correct value of the Extension-Name attribute is not installed, the Java Plug-in will prompt the user to let it download the optional package.
  • If an optional package with the correct value of the Extension-Name attribute is already installed, the Java Plug-in makes the following comparisons:
    • If the optional package's Specification-Version value is greater or equal to that required by the applet:
      • If the Implementation-Vendor-Id attributes match:
        • If the optional package's Implementation-Version is greater than or equal to that specified in the applet's manifest, do nothing - an up-to-date version of the optional package is already installed.
        • If the optional package's Implementation-Version is less than that specified in applet's manifest, the plug-in will prompt the user to download an upgrade from the same vendor.
      • If the Implementation-Vendor-Id attributes do not match, the Java Plug-in will prompt the user to download the optional package from the vendor specified in the applet's manifest.
    • If the optional package's Specification-Version value is less than that required by the applet:
      • If the optional package's Implementation-Vendor-Id matches that indicated in the applet's manifest, the Java Plug-in will prompt the user to download an updated optional package from the same vendor.
      • If the optional package's Implementation-Vendor-Id does not match that specified by the applet's manifest, the Java Plug-in will prompt the user to download the optional package from the vendor specified in the the applet's manifest.

If the applet's manifest doesn't contain one or more of the optional attributes, the plug-in will accept any value of the corresponding attribute in the optional package's manifest.

Download and Installation of Optional Packages

The following considerations pertain to optional packages that are downloaded by the Java Plug-in.

The optional package download URL as indicated in the applet manifest's <extension>-Implementation-URL attribute need not be limited to the Applet codebase.

All downloadable files should be signed using a DSA or RSA certificate. Any optional packages not so signed will not be installed but instead will be treated as a bundled optional package and loaded through the applet class loader, sharing the applet security attributes.

When the Java Plug-in retrieves an optional package from the URL indicated in the applet's manifest, it will check the optional package's manifest for a Main-Class attribute after verifying the optional package's signature. If the optional package's manifest file does not contain a Main-Class attribute, the Java Plug-in will simply drop the Jar file into the optional packages directory of the runtime environment (jre/lib/ext in the Java 2 SDK and lib/ext in the Java 2 Runtime Environment).

Some optional package Jar files may contain their own installer programs in either native code or as applications written in the Java programming language. Such an installer program may be necessary for purposes such as installing native libraries or accessing the Microsoft Windows registry, for example. If the Java Plug-in finds a Main-Class attribute in the optional package's manifest, it will assume that it indicates a class that serves as a Java-language installer and will invoke the main() method of that class.

An optional package's manifest may alternatively contain a Extension-Installation attribute. The value of this field will point to a native installation application that is to be used by the Java Plug-in to install the optional package.

The URL of an optional package as specified by the <extension>-Implementation-URL must point to a JAR-file. The plug-in will not download and install optional packages packaged as .exe or .bin files.

Some optional packages come packaged in different Jar files for different operating systems. Such cases can be accomodated by the <extension>-Implementation-URL attribute by using the $(os-name)$ construction in the attribute's value. Here is an example.

javaExt-Implementation-URL: http://.../stdext/javaExt-$(os-name)$.jar
Here, $(os-name)$ is the name of target operating system as defined by the os.name system property.
Copyright © 1999 Sun Microsystems, Inc. All Rights Reserved. Sun

Java Software


Java IDL: Using Adapter Activators

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
    $(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

%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
/j2se1.4/bin/idlj -fall -td classes Hello.idl
/j2se1.4/bin/javac -classpath classes -d classes HelloServant.java Server.java Client.java
/j2se1.4/bin/orbd -ORBInitialPort 10001 &
sleep 20
#servertool does not support script based register due to a bug
#using class instead
/j2se1.4/bin/java com.sun.corba.se.internal.Activation.ServerTool \
-ORBInitialPort 10001 -cmd \
register -server Server -classpath classes

        server registered (serverid = 257).

/j2se1.4/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.

Further Information

For more information on Adapter Activators, please refer to section 11.3.3 of the CORBA 2.3.1 Specification or the AdapterActivatorOperations API documentation.

Java IDL Home
Last updated: July 23, 2002


Java IDL Examples License

JavaTM IDL Examples License

/*

 * Copyright (c) 1996-2002 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.

 */

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.


Java IDL: Tutorial

Tutorial

Hello World Tutorial

Home Concepts Programming Reference Tutorial
Copyright © 1996-98 Sun Microsystems, Inc., 2550 Garcia Ave., Mtn. View, CA. 94043-1100 USA., All rights reserved.


Java IDL: Concepts

Concepts

Distributed Application Concepts

Using CORBA

Glossary

Home Concepts Programming Reference Tutorial
Copyright © 1996-98 Sun Microsystems, Inc., 2550 Garcia Ave., Mtn. View, CA. 94043-1100 USA., All rights reserved.


Getting Started with Java IDL

Getting Started with JavaTM IDL

Java TM 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.

Next: Writing the Interface Definition
Java IDL Home
Copyright ©2001 Sun Microsystems, Inc., 2550 Garcia Ave., Mtn. View, CA. 94043-1100 USA., All rights reserved.


Java IDL Technology Documentation

JavaTM IDL
Technology
Documentation

J2SETM v.1.4.1 Documentation Contents
Changes in CORBA (JavaTM IDL, Java RMI-IIOP) Features Between J2SE 1.3 and 1.4.1

JavaTM IDL technology ("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.

With which CORBA specifications does J2SE 1.4.1 comply?

Follow the link to this document for more information on Official Specifications for CORBA support in J2SE 1.4.1.

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 JavaBeansTM (EJBTM) technology, since the EJB remote object model is based on Java RMI technology.

Java IDL FAQ

This is a great reference! We've compiled loads of commonly asked questions into one place, so it's easy to search for answers to your questions!

  • Java IDL FAQ

Featured Technology

  • POA - Portable Object Adapter
  • Portable Interceptors **Advanced Topic**
  • INS - Interoperable Naming Service

Tutorials

Most of the tutorials are variations on the basic distributed "Hello World" application.

Introductory-Level Tutorials

The following documents provide introductory-level information on creating applications that use Java IDL. All use the POA-server side model. The differences are in the server implementations.

In order to best understand the material, progress through the examples in the order presented here.

  • Introductory "Hello World" example using Java IDL technology
  • "Hello World" example with a transient server (same code as above example, less descriptive material)
  • "Hello World" example with a persistent server
Other server-side models may be created using J2SE. If you'd like to use other server- side models, refer to these tutorials. Both of these tutorials use a transient server implementation.

  • "Hello World" example with a POA-Tie (Delegation) server-side model
  • "Hello World" example with an ImplBase (Inheritance) server-side model

Intermediate-Level Tutorials

The tutorials listed in this section are for developers who understand the material in the introductory-level tutorials, and are looking for more complex material.

  • Using the Interoperable Naming Service
  • CORBA Programming with J2SE 1.4: Programming Transient and Persistent Servers

Advanced-Level Tutorials

These tutorials are for experienced developers. The descriptive material is reduced, the sample code is commented for better understanding of the material.

  • Enterprise JavaBeans Components and CORBA Clients (click here for pdf version)
  • Portable Interceptors
  • Using Servant Activators
  • Using Servant Locators
  • Using Adapter Activators

Sample Code

  • Sample Code for Hello World provides the code for all created and generated files used in the POA server-side model tutorial

Other Sample Applications

  • Example: Interoperable Naming Service
  • Example: Callback Objects *not updated

Concepts

  • CORBA and the Java Programming Language
  • Java Developer Connection: Introduction to CORBA
  • Distributed Application Concepts
  • Using CORBA and Java IDL
  • Glossary

Programming Guide

  • Exceptions
  • Initialization
  • Naming Service
  • Dynamic Skeleton Interface
  • Mapping IDL to the Java Programming Language

Essential Java IDL API

  • 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

Java IDL Tools

  • idlj, the IDL-to-Java compiler (command-line documentation)
  • orbd - a daemon process containing a Bootstrap Service, a Transient Naming Service, a Persistent Naming Service, and a Server Manager
  • servertool - the ease-of-use interface for application programmers to register, unregister, startup, and shutdown a server.
  • tnameserv - the Transient Java IDL Naming Service (provided for backward compatibility)

For more information

The OMG is the official source of information for all CORBA and IIOP related information. The CORBA 2.3.1 Specification is available electronically from formal/99-10-07.pdf. The URLs for the CORBA specifications may change. If this link is broken, link to http://www.omg.org and search the specifications.

For more information on which OMG specifications are implemented in this release of the Java platform, see the compliance document.

For information on product limitations in this release of the Java IDL/RMI-IIOP technologies, see Java IDL Product Limitations.

For questions, please check the Java IDL FAQ and the user supported forum for Java IDL technology, which is available at http://forum.java.sun.com. For comments on the tutorial, or to report an error in the tutorial, please send us email at corba-tutorial@sun.com.

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Send questions or comments to: rmi-iiop@sun.com.

Sun


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 OMG specification at (ptc/00-08-07).

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, link to 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.

Home

Copyright © 1995-2001 Sun Microsystems, Inc. All Rights Reserved.


Changes in CORBA Features Between J2SE 1.4 and 1.4.1

 J2SE Documentation Contents

This release of the JavaTM 2 Platform, Standard Edition (J2SE), contains no new features or functionality over J2SE 1.4.

See Official Specifications for CORBA support in J2SE 1.4.1 for information on how Java IDL and RMI-IIOP comply with the CORBA Specifications.

Copyright © 2001 Sun Microsystems, Inc. All Rights Reserved. Sun

Java Software


Java IDL: Developing Clients

Developing Clients

This document was not updated for the J2SETM release. If you downloaded this document as part of the J2SETM documentation bundle, check the Web site at http://java.sun.com/j2se/1.4.2/docs/guide/idl/jidlClients.html for updates.

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.

Clients | Servers | Exceptions | Initialization | Naming

Copyright © 1996, 1997 Sun Microsystems, Inc., 2550 Garcia Ave., Mtn. View, CA. 94043-1100 USA., All rights reserved.


Java IDL: Distributed Application Concepts

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.

Distributed Application Concepts | Using CORBA | Glossary
Home
Copyright © 1996-98 Sun Microsystems, Inc., 2550 Garcia Ave., Mtn. View, CA. 94043-1100 USA., All rights reserved.


Java IDL: DSI Programming

Advanced Topic: The Dynamic Skeleton Interface (DSI)

This document was not updated for the J2SETM release. If you downloaded this document as part of the J2SETM documentation bundle, check the Web site at http://java.sun.com/j2se/1.4.2/docs/guide/idl/jidlDSI.html for updates.

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.

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.

Home

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.


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, link to 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, link to Java RMI-IIOP documentation.

New to J2SE 1.4 - 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 older version 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 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

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, 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 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, link to 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 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. 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, 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.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

    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

    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.

Home

Copyright © 1995-2001 Sun Microsystems, Inc. All Rights Reserved.


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, link to 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, link to Java RMI-IIOP documentation.

For more information on transient vs. persistent servers, please 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, link to the OMG Web site, and read Chapter 3 of the CORBA 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 than 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. Change to the directory that contains the file PersistentHello.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 -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, 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 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.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 Persistent). This step assumes the java/bin directory is included in your path.
       javac *.java Persistent/*.java
  4. Start orbd.

    To start orbd, enter:

      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.

  5. 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,

    1. Start the servertool from the command line as follows:

        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:

    2. 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.

  6. Run the client application:

      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 your JDK installation to the location where you have installed the JDK. Change the classpath to the directory where you have created the sample application.

#Change to location of your JDK installation.
JAVA_HOME=/usr/local/java/jdk1.4/solsparc

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

Java IDL Home


Java IDL: Example 3

Example 3: Hello World with Callback Object

This document was not updated for the J2SETM release. If you downloaded this document as part of the J2SETM documentation bundle, check the Web site at http://java.sun.com/j2se/1.4.2/docs/guide/idl/jidlExample3.html for updates.

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: (1) periodically ask for the stock price via a method request on the stock server or (2) ask to be notified by the server whenever a price change occurs. The second option is referred to as a "callback".

Example 3 illustrates how a client program can pass a callback object to a server. The server then issues a method request on the callback object and thereby notifies the client.

Example 3 is identical to Example 1 except for the callback enhancements. This page only discusses the code necessary to these enhancements.

Home

Copyright © 1995-98 Sun Microsystems, Inc. All Rights Reserved.


Java IDL: Exceptions

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), refer to the OMG document at http://www.omg.org/docs/omg/03-01-04.txt.

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, email us for more information at corba-tutorial@sun.com. When requesting the meaning of a minor code please include the following information:

  • The platform on which the client and server are running (e.g., Solaris, Linux, Win32)
  • The version of the JDK you are using (e.g., 1.4.0_01)
  • A complete stack trace
  • If you are using a naming service or an ORB from a different vendor, please provide the information on the vendor and version of the product.

Home

Copyright © 1996-98 Sun Microsystems, Inc., 2550 Garcia Ave., Mtn. View, CA. 94043-1100 USA., All rights reserved.


Java(TM) IDL FAQ

Java

JavaTM IDL FAQ

This is a document that attempts to answer many of the questions you may have about using JavaTM IDL technology. We will continue to update this document with your questions as we receive them. If you do not find your question answered here, please check the user-supported forum for Java IDL technology, which is available at http://forum.java.sun.com. For comments on the tutorials or other documents on this Web site, please send us email at corba-tutorial@sun.com.

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 J2SE 1.4. 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?

Features

  • What is the thread model supported by the JDK 1.4 CORBA implementation?
  • 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

  • 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

  • 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 classpath.

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 J2SE 1.4. Are there any compatibility issues that could affect this?

The idlj compiler now generates server-side mappings based on the POA Inheritance Model. 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.

Other information on compatibility between J2SE 1.3 and J2SE 1.4 can be found in the compatibility document at http://java.sun.com/j2se/1 .4/compatibility-CORBA.html.

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 at http://www.omg.org/docs/omg/03-01-04.txt.

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, email us for more information at corba-tutorial@sun.com. When requesting the meaning of a minor code please include the following information:

  • The platform on which the client and server are running (e.g., Solaris, Linux, Win32)
  • The version of the JDK you are using (e.g., 1.4.0_01)
  • A complete stack trace
  • If you are using a naming service or an ORB from another vendor, please provide that information

Features

What is the thread model supported by the JDK 1.4 CORBA implementation?

The Java CORBA ORB shipped in J2SE 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 J2SE v.1.4 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 on the Web at http://java.sun.com/j2se/1.4/docs/guide/idl/tutorial/jidl2machines.html.

Is Java IDL technology compliant with CORBA specifications?

For compliance information for CORBA technology shipped with J2SE v.1.4, read the CORBA compliance statement at http://java.sun.com/j2se/1 .4/docs/api/org/omg/CORBA/doc-files/compliance.html.

Compatibility/Interoperability

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",
            "" );

        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?

Our J2SE v.1.4 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 IOR discussion in INS tutorial) 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: http://java.sun.com/j2se/1.4/docs/guide/rmi-iiop/interop.pdf.

How do I connect to a 3rd-party Naming Service from Sun's ORB?

The recommended way is to use the Interoperable 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 and Port.

  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/technology/documents/formal/corba_language_mapping_specs.htm. 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: http://java.sun.com/j2se/1.4/docs/guide/rmi-iiop/interop.html.

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

Where can I download the idltojava compiler?

We highly recommend that you use the latest version of the IDL-to-Java compiler, idlj for all new code. If you still need to use idltojava for legacy applications, you can download the idltojava compiler for JDK 1.2 from http://developer.java.sun.com/developer/earlyAccess/jdk12/idltojava.html.

To get the latest version of the IDL-to-Java compiler, download the latest version of JavaTM 2 Platform, Standard Edition (J2SETM). When J2SE 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 "Write Once, Run AnywhereTM" 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 http://www.omg.org/cgi-bin/doc?standard-tags.

Copyright © 2000-2002 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software


Java IDL: Glossary

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, v1.4, 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 J2SDK v1.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 J2SDK v1.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 in J2SE v.1.4. 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 J2SE, v.1.4.

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 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.

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 v.1.4, 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.

Distributed Application Concepts | Using CORBA | Glossary
Home
Copyright © 1996-2001 Sun Microsystems, Inc., 2550 Garcia Ave., Mtn. View, CA. 94043-1100 USA., All rights reserved.


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.

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.

  • 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 ImplBase Inheritance model for server-side implementations. Do not create new applications using this model. For tutorials using the other server-side implementations, see the following documents:

  • Java IDL: The "Hello World" Example

    This document presents a tutorial describing creating a complete CORBA application using IDL to define the interfaces and using the Java IDL compiler to generate the default IDL-to-Java language mapping, which is the POA Inheritance model.

  • Java IDL: The "Hello World" Example with the POA-Tie Server-Side Model

    You might want to use the Tie delegate 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.

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 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. 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.

    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.java 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.

  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 -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 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 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

    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

    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.

Home

Copyright © 1995-2001 Sun Microsystems, Inc. All Rights Reserved.


Java IDL: Initialization

Initialization

This document was not updated for the J2SETM release. If you downloaded this document as part of the J2SETM documentation bundle, check the Web site at http://java.sun.com/j2se/1.4.2/docs/guide/idl/jidlInitialization.html for updates.

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.

Home

Copyright © 1996, 1997 Sun Microsystems, Inc., 2550 Garcia Ave., Mtn. View, CA. 94043-1100 USA., All rights reserved.


Java IDL and RMI-IIOP: Naming Services

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.

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 J2SE v.1.4. 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:

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 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 OMG specification at (ptc/00-08-07).

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.

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:

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:

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 and Port.

  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.
Java IDL Home


Sample code

 <
Java

Sample Code for Hello.idl

The JavaTM 2 SDK, Standard Edition, v1.4 includes many exciting new Java IDL features, for a list, link to Summary of Changes. The IDL-to-Java compiler, idlj now supports CORBA-standard features required for Portable Object Adapters. 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, 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();
  };
};

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.

Sun

Java Software


Java IDL: Developing Servers

Developing Servers

This document was not updated for the J2SETM release. If you downloaded this document as part of the J2SETM documentation bundle, check the Web site at http://java.sun.com/j2se/1.4.2/docs/guide/idl/jidlServers.html for updates.

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.

Clients | Servers | Exceptions | Initialization | Naming

Home
Fundamentals
Programming
References
Tutorial

Copyright © 1996, 1997 Sun Microsystems, Inc., 2550 Garcia Ave., Mtn. View, CA. 94043-1100 USA., All rights reserved.


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.

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 Tie Delegation/POA model for server-side implementation. For tutorials using the other server-side implementations, see the following documents:

  • Java IDL: The "Hello World" Example

    This document presents a tutorial describing creating a complete CORBA application using IDL to define the interfaces and using the Java IDL compiler to generate the default IDL-to-Java language mapping, which follows the POA Inheritance Model. For compatibility with servers written using J2SDK 1.3 and earlier, you may want to use to the ImplBase Inheritance Model.

  • 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). 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 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, 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 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
      // 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 J2SE v.1.4 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. Change to the directory that contains the file Hello.idl.

  2. 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.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.

    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.

  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 -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 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 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

    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

    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 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.

Home

Copyright © 1995-2001 Sun Microsystems, Inc. All Rights Reserved.


Java IDL: Using CORBA

Using CORBA and Java IDL

This document was not updated for the J2SETM release. If you downloaded this document as part of the J2SETM documentation bundle, check the Web site at http://java.sun.com/j2se/1.4.2/docs/guide/idl/jidlUsingCORBA.html for updates.

In the meantime, check out CORBA Technology and the Java Platform!

Distributed Application Concepts | Using CORBA | Glossary

CORBA Technology and the Java Platform
Home

Copyright © 1996-2001 Sun Microsystems, Inc., 2550 Garcia Ave., Mtn. View, CA. 94043-1100 USA., All rights reserved.


Limitations (Java[tm] IDL/Java[tm] RMI over IIOP Technologies)

Java

Limitations (JavaTM IDL/JavaTM RMI over IIOP)

This document lists some of the limitations regarding JavaTM IDL and JavaTM RMI over IIOP technology in this release of the JavaTM 2 Platform, Standard Edition (J2SETM). The limitations are outlined below.

The Official Specifications for CORBA Support in J2SE 1.4.1 document provides information outlining with which OMG Specifications this implementation of the Java IDL and Java RMI over IIOP technologies comply.

LIMITATIONS:

  • JavaTM SDK version interoperability
    When a J2SETM 1.3.x client talks to a J2SE 1.4 server 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, 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.

    New to J2SE 1.4.1: If one side is using J2SE 1.3.1.05, and the other side is using J2SE 1.4.1 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 J2SE 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 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 rmic compiler generates locally optimized stubs when used in conjunction with the -iiop option. However, the J2SE 1.4 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 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 1.4 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. One example of this is that java.util.Calendar in J2SE 1.4 cannot be sent back to J2SE 1.3.x.


orbd - The Object Request Broker Daemon (ORBD)

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.

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 J2SE v.1.4. 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:

  1. 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.

  2. 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:

  3. 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:

    Server Tool registering Hello Server

    The graphic above also shows the servertool listing all registered servers.

  4. 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.

  5. 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 © 2001 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software


Java IDL: Portable Interceptors (PI)

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 JavaTM 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-03-04

Consult the Java Developer's Forum on Distributed Computing at http://forum.java.sun.com/ for more information on Portable Interceptors.


Java IDL: Portable Object Adapter (POA)

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 at http://www.omg.org/docs/formal/99-10-07.pdf

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).

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 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, please 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, please refer to section 11.3.3 of the CORBA 2.3.1 Specification or the AdapterActivatorO perations API documentation.

If you are reading this documentation as part of the J2SE documentation bundle, check the Web site at http://java.sun.com/j2se/1.4.1/docs/guide/idl/POA.html#adapteractivator for updates to this topic.

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, please refer to section 11.3.4 of the CORBA 2.3.1 Specification.

If you are reading this documentation as part of the J2SE documentation bundle, check the Web site at http://java.sun.com/j2se/1.4.1/docs/guide/idl/POA.html#servantmanager for updates to this topic.

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 Web site. At the time of this writing, the specification can be found at http://www.omg.org/docs/formal/99-10-07.pdf.

Java IDL Home
Last updated: June 6, 2002


Java IDL: Programming Guide

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

Home Concepts Programming Reference Tutorial
Copyright © 1996-98 Sun Microsystems, Inc., 2550 Garcia Ave., Mtn. View, CA. 94043-1100 USA., All rights reserved.


Java IDL: Reference

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
  • new package org.omg.PortableServer - provides classes and interfaces for making the server side of your applications portable across multivendor ORBs
  • new 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
  • new 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

Home Concepts Programming Reference Tutorial
Copyright © 1996-98 Sun Microsystems, Inc., 2550 Garcia Ave., Mtn. View, CA. 94043-1100 USA., All rights reserved.


Java IDL: Using Servant Activators

Using Servant Activators

If you downloaded this document as part of the J2SE TM documentation bundle, check the Web site at http://java.sun.com/j2se/1.4.1/docs/guide/idl/index.html for updates.

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

**In progress, please check back for updates!

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.

Java IDL Home
Last updated: June 6, 2002


Java IDL: Using Servant Locators

Using Servant Locators

If you downloaded this document as part of the J2SE TM documentation bundle, check the Web site at http://java.sun.com/j2se/1.4.1/docs/guide/idl/index.html for updates.

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

**In progress, please check back for updates!

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.

Java IDL Home
Last updated: June 6, 2002


servertool - The Java(TM) 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 a pplication 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 © 2001 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software


Java IDL: Transient Naming Service -

Java IDL: Transient Naming Service - tnameserv

This document discusses using the Java IDL Transient Naming Service, tnameserv. In J2SE v. 1.4., Java IDL 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.

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);
       }
   }
}

Home

Copyright © 1996-2001 Sun Microsystems, Inc., 2550 Garcia Ave., Mtn. View, CA. 94043-1100 USA., All rights reserved.


Java IDL: Mapping IDL to Java

Java IDL: IDL to Java Language Mapping

This release of the JavaTM 2 Platform, Standard Edition, v.1.4, 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 v.1.4 conforms to the mappings specified by the following document: Official Specifications for CORBA support in J2SE 1.4.

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 1.4.

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

Java IDL Home


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

Previous: Developing the Hello World Server
Next: Running the Hello World Application
Tutorial home: Getting Started with Java IDL
Java IDL Home

Copyright © 1996-2001 Sun Microsystems, Inc., 2550 Garcia Ave., Mtn. View, CA. 94043-1100 USA., All rights reserved.


Getting Started with Java IDL: Running the Hello World Application

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.

Previous: Developing the Server
Previous: Developing the Client Application
Next: Using Stringified Object References
Java IDL Home
Copyright © 1996-2001 Sun Microsystems, Inc., 2550 Garcia Ave., Mtn. View, CA. 94043-1100 USA., All rights reserved.


Getting Started with Java IDL: Writing the Interface Definition

Getting Started with Java IDL:
Writing the Interface Definition

Note: All command and troubleshooting instructions apply to the Java 2 Platform, Standard Edition, version 1.4 and its version of idlj only.

Before you start working with Java IDL, you need to install version 1.4 of J2SE. J2SE v.1.4 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 the IDL-to-Java compiler options, follow the link.

New in J2SE v.1.4: 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, link to 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 j2sdk/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 J2SDK v.1.4 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. At this writing, the specification can be downloaded from http://cgi.omg.org/c gi-bin/doc?formal/99-10-07.

Next: Developing the Hello World Server
Previous: Getting Started with Java IDL
Java IDL Home

Copyright © 2001 Sun Microsystems, Inc., 901 San Antonio Rd., Palo Alto, CA. 94303-4900, USA., All rights reserved.


Getting Started with Java IDL: Developing the Hello World Server

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
// 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
      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 new to J2SE v.1.4, and 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

The document 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.

      New in J2SE v.1.4: 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, link to 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 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

    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 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.

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

Previous: Writing the Interface Definition
Next: Developing a Client Application
Tutorial home
Java IDL Home

Copyright © 1996-2001 Sun Microsystems, Inc., 2550 Garcia Ave., Mtn. View, CA. 94043-1100 USA., All rights reserved.


Getting Started with Java IDL: Using Stringified Object References

This document was not updated for the J2SETM release. If you downloaded this document as part of the J2SETM documentation bundle, check the Web site at http://java.sun.com/j2se/1.4.2/docs/guide/idl/tutorial/GSstring.html for updates.

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.

Developing the Hello World Server

Developing the Client Application
Tutorial home
Home

Copyright © 2002 Sun Microsystems, Inc., 2550 Garcia Ave., Mtn. View, CA. 94043-1100 USA., All rights reserved.


Java IDL: Running The "Hello World" Example on Two Machines

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 Sun Microsystems 2001


Java Image I/O

Java

JavaTM Image I/O

 Documentation Contents
The Java Image I/O API, developed through JSR-015, 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 current APIs for loading and saving images.

The API provides provides a framework for the addition of format-specific plugins. Plug-ins for several common formats are included with Java Image I/O, but third parties can use this API to create their own plugins to handle special formats.

Java Image I/O API Guide

The Java Image I/O API Guide (HTML | PDF | PS) describes the Java Image I/O API in more detail and demonstrates how to use Java Image I/O to read and write images and write custom plug-ins.

Java Image I/O API Specification

The Java Image I/O API Specification consists of these six packages:

javax.imageio
Contains the basic classes and interfaces for describing the contents of image files, including metadata and thumbnails; controlling the image reading and writing process; performing transcoding between formats; and reporting errors.

javax.imageio.event
Contains interfaces for dealing with synchronous notification of events during the reading and writing of images.

javax.imageio.metadata
Contains classes and interfaces for reading and writing image metadata.

javax.imageio.plugins.jpeg
Contains some support classes for the built-in JPEG reader and writer plug-ins.

javax.imageio.spi
Contains service-provider interfaces for: readers, writers, transcoders; and includes a runtime registry.

javax.imageio.stream
Contains classes and interfaces for low-level I/O from files and streams.

For More Information

See the Java Software websites:
  • JSR-015 Image I/O Framework Specification
  • The Java 2D Home Page
  • Java Advanced Imaging
  • The JFC Home Page

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: jsr015-comments@sun.com 		Sun Microsystems, Inc
Java Software


Java Image I/O API Guide: 3 - Writing Image I/O Applications

CONTENTS | PREV | NEXT JavaTM Image I/O API Guide

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Image I/O API Guide: 3 - Writing Image I/O Applications

CONTENTS | PREV | NEXT JavaTM Image I/O API Guide

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Image I/O API Guide: 3 - Writing Image I/O Applications

CONTENTS | PREV | NEXT JavaTM Image I/O API Guide

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Image I/O API Guide: 3 - Writing Image I/O Applications

CONTENTS | PREV | NEXT JavaTM Image I/O API Guide

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Image I/O API Guide: 3 - Writing Image I/O Applications

CONTENTS | PREV | NEXT JavaTM Image I/O API Guide

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Image I/O API Guide: 3 - Writing Image I/O Applications

CONTENTS | PREV | NEXT JavaTM Image I/O API Guide

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Image I/O API Guide: 3 - Writing Image I/O Applications

CONTENTS | PREV | NEXT JavaTM Image I/O API Guide

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Image I/O API Guide: 3 - Writing Image I/O Applications

CONTENTS | PREV | NEXT JavaTM Image I/O API Guide

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Image I/O API Guide: -

Copyright © 2001 Sun Microsystems, Inc.

901 San Antonio Road, Palo Alto, CA 94303 USA

All rights reserved. Copyright in this document is owned by Sun Microsystems, Inc.

Sun Microsystems, Inc. (SUN) hereby grants to you at no charge a nonexclusive, nontransferable, worldwide, limited license (without the right to sublicense) under Sun's intellectual property rights in the Java Image I/O API Specification (Specification) to use the Specification for internal evaluation purposes only. Other than this limited license, you acquire no right, title, or interest in or to the Specification and you shall have no right to use the Specification for productive or commercial use.

The Specification is the confidential and proprietary information of Sun Microsystems, Inc. (Confidential Information). You may not disclose such Confidential Information to any third part and shall use it only in accordance with the terms of this license.

THIS SPECIFICATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY YOU AS A RESULT OF USING THIS SPECIFICATION.

THIS SPECIFICATION COULD INCLUDE TECHNICAL INACCURACIES OR TYPOGRAPHICAL ERRORS. CHANGES ARE PERIODICALLY ADDED TO THE INFORMATION HEREIN; THESE CHANGES WILL BE INCORPORATED IN NEW EDITIONS OF THE SPECIFICATION. SUN MICROSYSTEMS, INC. MAY MAKE IMPROVEMENTS AND/OR CHANGES IN THE SPECIFICATION AT ANY TIME, IN ITS SOLE DISCRETION. SUN IS UNDER NO OBLIGATION TO PRODUCE FURTHER VERSIONS OF THE SPECIFICATION OR ANY PRODUCT OR TECHNOLOGY BASED UPON THE SPECIFICATION. NOR IS SUN UNDER ANY OBLIGATION TO LICENSE THE SPECIFICATION OR ANY ASSOCIATED TECHNOLOGY, NOW OR IN THE FUTURE, FOR PRODUCTIVE OR OTHER USE.

RESTRICTED RIGHTS LEGEND

Use, duplication, or disclosure by the U.S. government is subject to restrictions of FAR 52.227-14(g)(2)(6/87) and FAR 52.227-19(6/87), or DFAR 252.227- 7015(b)(6/95) and DFAR 227.7202-1(a).

Sun, the Sun Logo, Sun Microsystems, Jini, JavaBeans, JDK, Java Solaris, NEO, Netra, NFS, ONC, ONC+, OpenWindows, PC-NFS, EmbeddedJava, PersonalJava, SNM, SunNet Manager, Solaris sunburst design, Solstice, SunCore, SolarNet, SunWeb, Sun Workstation, The Network Is The Computer, ToolTalk, Ultra, Ultracomputing, Ultraserver, Where The Network Is Going, Sun WorkShop, XView, Java WorkShop, and the Java Coffee Cup logo are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries.


Java Image I/O API Guide: 4 - Writing Image I/O Plug-ins

CONTENTS | PREV | NEXT JavaTM Image I/O API Guide

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Image I/O API Guide: 4 - Writing Image I/O Plug-ins

CONTENTS | PREV | NEXT JavaTM Image I/O API Guide

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Image I/O API Guide: 4 - Writing Image I/O Plug-ins

CONTENTS | PREV | NEXT JavaTM Image I/O API Guide

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 JDK 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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Image I/O API Guide: 4 - Writing Image I/O Plug-ins

CONTENTS | PREV | NEXT JavaTM Image I/O API Guide

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Image I/O API Guide: 4 - Writing Image I/O Plug-ins

CONTENTS | PREV | NEXT JavaTM Image I/O API Guide

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Image I/O API Guide: 4 - Writing Image I/O Plug-ins

CONTENTS | PREV | NEXT JavaTM Image I/O API Guide

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Image I/O API Guide: 2 - Goals

CONTENTS | PREV | NEXT JavaTM Image I/O API Guide

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Image I/O API Guide: 2 - Goals

CONTENTS | PREV | NEXT JavaTM Image I/O API Guide

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Image I/O API Guide

PREV | NEXT JavaTM Image I/O API Guide

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Image I/O API Guide: 1 - Introduction

CONTENTS | PREV | NEXT JavaTM Image I/O API Guide

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:

CONTENTS | PREV | NEXT
Copyright © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Image I/O API Guide: 1 - Introduction

CONTENTS | PREV | NEXT JavaTM Image I/O API Guide

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Image I/O API Guide: 1 - Introduction

CONTENTS | PREV | NEXT JavaTM Image I/O API Guide

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 J2SE platform for the Solaris operating environment, Linux, and Microsoft Windows platforms. The availibility of a particular J2SE release on other platforms is determined by the platform vendor.

CONTENTS | PREV | NEXT
Copyright © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Image I/O API Guide: 1 - Introduction

CONTENTS | PREV | NEXT JavaTM Image I/O API Guide

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Image I/O API Guide: 1 - Introduction

CONTENTS | PREV | NEXT JavaTM Image I/O API Guide

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Image I/O API Guide

CONTENTS | PREV | NEXT

JavaTM Image I/O API Guide

Phil Race, Dan Rice, Raúl Vera

April 2001

CONTENTS | PREV | NEXT
Copyright © 2001 Sun Microsystems, Inc. All Rights Reserved.


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 © 1995-99 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-intl@java.sun.com

Sun
Java Software


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.
  • Javadoc
    • LWTextComponent - explains the structure of a lightweight text editing component that can be extended to an active client.
    • ActiveClient - explains the structure of an active client component.
  • 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 © 1995-99 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-intl@java.sun.com

Sun
Java Software


Input Method Framework

Documentation Contents

The input method framework enables the collaboration between text editing components and input methods in entering text. Input methods are software components that let the user enter text in ways other than simple typing on a keyboard. They are commonly used to enter Japanese, Chinese, or Korean - languages using thousands of different characters - on keyboards with far fewer keys. However, the framework also supports input methods for other languages and the use of entirely different input mechanisms, such as handwriting or speech recognition.

The input method framework provides two layers of public interfaces:

  • The input method client API provides interfaces and classes that enable text editing components to communicate with input methods and implement a well-integrated text input user interface.
  • The input method engine SPI provides interfaces that enable the development of input methods in the Java programming language that can be used with any Java runtime environment.

Overview and Specification

  • Overview
  • Specification

API and SPI Reference

  • Input method client API reference
  • Input method engine SPI reference

Tutorials

  • Input method client API tutorial
  • Input method engine SPI tutorial

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-intl@java.sun.com

Sun
Java Software


Input Method Framework Overview

Contents

  1. Introduction
  2. Goals
  3. Input Method Support in Other Frameworks
  4. Frequently Asked Questions
  5. References

1. Introduction

Input methods are software components that interpret user operations such as typing keys, speaking, or writing using a pen device to generate text input for applications. The most common input methods are the ones that let users type text in Chinese, Japanese, or Korean, languages that use thousands of different characters, on a regular-sized keyboard. The text is typed in a form that can be handled by regular-sized keyboards, for example, in a romanized form, and then converted into the form that's really intended. Typically a sequence of several characters needs to be typed and then converted in one chunk, and conversion may have to be retried because there may be several possible translations. Similarly, for hand-writing recognition, the user may write a series of characters, convert them, and select the correct text from several possible conversion results. This process is called composition, and the text that the input method is working on is called composed text. It ends when the user confirms the final conversion result and the text is committed.

During composition, the composed text logically belongs to the input method, but still needs to be displayed to the user. Input method frameworks cooperate with input methods to provide at least two ways to do this: They enable modern text editing components to display the text in the context of the document that it will eventually belong to, albeit in a style that indicates that the text still needs to be converted or confirmed by the input method. This is called on-the-spot style input. And they provide a separate window to display the text as a fall-back if a not-so-modern text editing component can't deal with the text until it's confirmed. We call this root-window style input.

The input method framework in the Java 2 platform enables the collaboration between text editing components and input methods in entering text. Its input method client API provides interfaces and classes that enable text editing components to communicate with input methods and implement a well-integrated text input user interface in the on-the-spot and below-the-spot styles; it also provides root-window style input as a fallback. Its service provider interface (SPI) for input method engines provides interfaces that enable the development of input methods in the Java programming language that can be used with any Java runtime environment; it also supports native input methods of the host platform.

2. Goals

"Write Once, Run Anywhere in the World" for Text Components

Text editing components that use the input method framework run on any Java application environment and support any text input methods available on that Java application environment without modifying or recompiling the text editing component. The framework isolates text editing components from differences in platforms and input method engines. It provides only one programming model for interacting with input methods. This lets developers write to a single API, and lets users choose whatever input method they prefer. When using native input methods, the framework maps to the platform input method APIs.

Although engine independence will be important to most developers, some high-end developers may want access to engine specific features. The framework allows this access.

"Write Once, Run Anywhere in the World" for Input Methods

Input methods written in the Java programming language and using the input method engine SPI can be installed into any Java application environment and support any text component running in that Java application environment. The framework isolates input methods from differences in platforms and text editing components. It provides only one programming model for interacting with text components. This lets developers write to a single SPI, and lets users choose whatever text editing component they prefer.

Language Independence

The input method framework is language independent in order to satisfy the needs of fully international applications. Although input methods are generally used for entering East Asian text, they may be useful for other languages as well. For example, a transliteration input method might be developed to allow Greek to be entered using Latin characters.

The framework handles input methods for different languages at the same time for truly multilingual text editing. While the choice of native input methods may be limited by the host operating system, any input method written in the Java programming language and using the input method engine SPI can be used at any time. Text created by an input method can have language attributes so that applications can perform language sensitive operations on the text.

Input Device Independence

The input method framework is designed to accommodate many possible input devices. Although keyboards are the predominant way of entering text today, other devices are gaining importance. For some platforms, pen-based input is the only way to enter text. Also, voice input is becoming more and more popular. The input method engine SPI opens the way to support these alternate devices.

Multiple Service Levels

Different programs have different needs for input method support. Tight integration with input methods provides the best user interface, but requires some additional programming. Some developers may not find that additional work worthwhile, but their applications still need to be able to receive East Asian text input. A few programs, such as games, want direct low-level keyboard input without interference from an input method. The framework lets programs choose one of the following levels of text input support.

Integrated Text Input User Interface

Modern programs intended to be used with East Asian languages usually provide a fully integrated user interface for text input operations and show the text being composed embedded in the document text. While converting text, the current candidate is highlighted, and when the user chooses a different candidate, the previous candidate text is replaced with the new one. This user interface support for input methods is known as on-the-spot style (or inline style). An alternative that Chinese-speaking users often prefer is the below-the-spot style, where composed text is shown in a separate composition window that is automatically positioned close to the insertion point where text will be inserted after being committed. The input method client API lets text editing components implement these integrated text input user interfaces.

Integration does not only mean displaying the composed text in the context of the target document. It also means that the text editing component understands "input method events", which let the input method communicate more information about the text than simple key events (for example, grammatical information), and that it can responds to requests for information from the input method that let the input method improve its functionality (for example, its accuracy).

Non-Integrated Text Input User Interface

For programs that do not want to deal with the user interface for text input operations, only final input text is sent to the application. In this case, the framework provides a user interface for input operations in a separate composition window outside the application. This is known as root-window style. It is less convenient because the user either has to manually position the window near the insertion point or to move his/her eyes between the composition window and the application window.

In this case, the application receives the input text as a sequence of key events. Therefore, there is no way to receive any information associated with the input text, such as grammatical information. Also, surrogate pairs (as defined in the Unicode Standard, version 2.0) are received as two separate key events.

No Input Method Support

Some applications, such as game software, may need only raw key input and no input method support. The framework provides a way to explicitly disable input method support.

Building Block Reuse

An important theme of object-oriented programming is reuse of program building blocks. The same building block may be used in many different applications, and several times within the same application. To make it easy to combine different text editing building blocks of possibly different capabilities, the input method framework interacts with each text editing component directly and individually.

As a consequence, many applications will not interact with the input method framework directly at all. Instead, they will use ready-made text editing components, such as the Swing text components, which will handle the interaction for them.

Close Integration with Other Frameworks

The input method framework is designed as an integral part of the Java platform. Interfaces that are necessary to exchange text between input methods and text components are designed to also support communication between other text-related frameworks, such as Java 2D and the Swing text components. Support for input method highlight drawing is integrated into Java 2D, so that text components can treat composed text just like any other text and the highlights just like any other style. Java 2D interacts with the input method framework to determine appropriate visual styles for input method highlights depending on the platform. The Swing text components use the input method framework to implement the best possible user interface with minimal additional programming.

3. Input Method Support in Other Frameworks

This chapter summarizes functionality in other Java platform frameworks that support input methods.

Text

The AttributedCharacterIterator interface provides a standard way of communicating text information with attributes between frameworks. It lets text readers access text without having to know how the text is stored in the information provider. Attribute information may include font and style attributes as well as language tags and grammatical annotations.

Abstract Window Toolkit

The Window class creates an initial input context for the window, and disposes this input context for the window when the window is disposed. Explicitly disposing input contexts allows to free up the (often substantial) resources allocated by native input methods.

The Component class has methods to handle input contexts and input method request handlers. Newly created Component instances other than windows initially share the input context of their containing window. The event handling in the Component class redirects incoming events to the input context associated with the component, and only passes them on to the component's listeners if they have not been consumed by an input method. Focus changes are communicated to the input context so it can activate or deactivate input methods.

The AWT classes that have knowledge of event or listener classes handle the InputMethodEvent and InputMethodListener classes.

The Graphics class defines a drawString method that accepts AttributedCharacterIterator instances as input. Instances of the TextLayout class can be constructed from AttributedCharacterIterator instances and used to draw text with input method highlights. Both ways of drawing text recognize input method highlights as attributes of the text and render them.

Swing

The Swing text components in the Java 2 platform are by default active clients of the input method framework. That means, applications using these text components will use on-the-spot or below-the-spot style input by default. Application developers are still responsible for ending input operations when some other operation is started that requires the text to be committed. They may also use the input method framework's methods to create a private input context, to select an input method, or to set an expected character subset.

4. Frequently Asked Questions

How are input methods supported in previous versions of the Java platform?

Here's the history of input method support in the Java platform:

  • 1.0: no input method support.
  • 1.1: host input methods supported for peered text components (TextArea, TextField).
  • 1.1.6: host input methods supported for lightweight components, root-window style only.
  • 1.2: introduces input method client API, enabling on-the-spot style for lightweight components. Swing text components become active clients.
  • 1.3: introduces input method engine SPI, enabling input methods written in the Java programming language. Introduces below-the-spot style.

Why is there no method that lets a client component choose an input method by name?

The input method framework lets client components select an input method by locale, but not by name. Which input method is used to enter text for a given language is the user's choice, and text components should be written to work with any input method. If text components want to take advantage of enhanced features of specific input methods, they can call getInputMethodControlObject and, if the result is an instance of a class they know about, call its methods.

How can I obtain a IIIMP adapter?

Version 1.2 of the Java 2 Runtime Environment included a client side adapter for the Internet-Intranet Input Method Protocol (IIIMP), a Sun Microsystems technology which enables the use of server-based input methods over the network. This adapter was included to allow the evaluation of this protocol at a time when there was no public interface that would let users install the adapter into a Java runtime environment as a separate software component. Version 1.3 of the Java 2 platform provides a public input method engine SPI, so that the adapter, like other input systems, can now be developed and distributed as a separate product and installed into any implementation of the Java 2 platform. A version of the IIIMP adapter that uses the SPI is currently being developed by Sun Microsystems. To obtain current information, go to the Solaris Developer Connection and search for "IIIM".

5. References

Information about the implementation of input methods on different platforms can be found in the following literature:

  • "Programmer's Supplement for Release 6," O'Reilly & Associates, Inc. (ISBN 1-56592-089-9).
  • "Inside Macintosh: Text," Addison-Wesley (ISBN 0-201-63298-5).
  • "Developing International Software for Windows 95 and Windows NT," Microsoft Press (ISBN 1-55615-840-8).
  • "IIIMP - Platform Independent Input Method for Internet and Java," Proc. Twelfth International Unicode/ISO 10646 Conference, Unicode Consortium.

Copyright © 1995-99 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-intl@java.sun.com

Sun
Java Software


Input Method Framework Specification

Contents

  1. Framework Architecture
  2. Client Components
  3. Input Styles
  4. Input Method Engines and Adapters
  5. Context Management
  6. Information Flow Through the Framework

1. Framework Architecture

The following picture shows the overall structure of the framework and its clients. Parts outlined in bold are integrated with the input method framework as part of the Java 2 platform; others can be developed and distributed separately by independent software vendors.

The following context describes this graphic

The input method client API defines the classes and interfaces that text editing components can use to implement an integrated text input user interface. The AWT text components TextArea and TextField provide on-the-spot or over-the-spot composition, depending on implementation. The text components of the Swing user interface toolkit provide an integrated text input user interface. The context management manages communication paths between the text editing components and input methods. The input method engine SPI defines the interfaces that allow input method engines and adapters to be plugged into the framework. Input method engines can be implemented directly in the Java programming language using these interfaces. To use native input methods integrated with the host input method manager, an adapter translates information between the data models used by native input methods and the input method framework and provides the composition window. Adapters for other input systems, such as Java Speech or the Internet-Intranet Input Method Protocol (IIIMP), can also be implemented using this interface.

2. Client Components

Every instance of the Component class is potentially a client of the input method framework. The framework distinguishes between four kinds of components:
  • Active clients are components whose getInputMethodRequests implementations return a non-null value. The framework assumes that these components actively use the input method client API and, in particular, provide an implementation of the InputMethodListener interface. These components are expected to handle events and requests for information coming from the input method and draw composed text that is sent to them.
  • Non-clients are components that have turned off input method support using the enableInputMethods method.
  • Peered clients are peered text components (instances of the TextComponent class). Their behavior is implementation dependent, and their input method support may be limited. In Sun's Java 2 runtime environment for Windows, peered text components behave mostly like active clients. In Sun's Java 2 runtime environment for Solaris, peered text components can receive input only from host input methods, and they do not support the below-the-spot input style (see below).
  • Passive clients are all remaining components. The framework assumes that passive clients don't use the input method client API, but still need to receive text input from input methods.
All four kinds of components may coexist in the same window. The input method framework, therefore, needs to determine the capabilities of components and adjust its behavior as the focus moves from one component to another.

Client components are not responsible for drawing candidate lists or for user interface elements that control the input method's behavior. Depending on the platform, this responsibility rests with input methods, the host input method manager, or the input method framework.

Input methods are not concerned with the differences between client components. They interact with them indirectly through the input method framework, which presents an interface similar to an active client and handles the differences internally.

3. Input Styles

The input method framework supports three input styles:
  • On-the-spot input, where the client component draws the composed text in the context of the document that it will eventually belong to, but in a style that indicates that the text still needs to be converted or confirmed by the input method. This is the default input style for active clients.
  • Below-the-spot input, where the composed text is shown in a separate composition window that is automatically positioned just below the insertion point where text will be inserted after being committed. The window's location is calculated first when the window is opened, then updated whenever committed text has been dispatched to the client component. If positioning the window below the insertion point would move it partially or entirely off-screen, it is moved above the insertion point. This input style may be selected for active clients as described below.
  • Root-window input, where the composed text is shown in a separate composition window that is not automatically positioned. This input style is used for passive clients.
The framework chooses between on-the-spot and below-the-spot input for active clients based on a system property or an AWT property "java.awt.im.style". The system property can be defined from the command line (by the end user), the AWT property in a localized awt.properties file (by the localizer or a system administrator). If both are defined, the system property takes precedence. If the property's value is "below-the-spot", below-the-spot input is used, otherwise on-the-spot input.

Support for below-the-spot input with native input methods is platform dependent. In Sun's Java 2 runtime environments, it is supported on Windows, but not on Solaris. Where it is not supported, on-the-spot input is used instead.

The input style used for peered text components (instances of the TextComponent class) is implementation dependent and may not be any of the styles described above. In Sun's Java 2 runtime environment for Windows, below-the-spot input may be selected as described above, otherwise over-the-spot input is used, where composed text is drawn in a separate window covering the insertion point. In Sun's Java 2 runtime environment for Solaris, the input style depends on the input method.

No input style is associated with non-clients.

Input methods are not concerned with the differences between input styles. They interact with client components indirectly through the input method framework, which presents an interface assuming on-the-spot input and handles the differences internally.

4. Input Method Engines and Adapters

The input method engine SPI enables the development of input methods in the Java programming language. Adapters for other input systems, such as Java Speech or the Internet-Intranet Input Method Protocol, can also be implemented using this interface. For information specific to the SPI, see the SPI package specification.

The SPI is also used for host input method adapters, which connect to native input methods integrated with the host input method managers, such as the Input Method Manager on Microsoft Windows, the Text Services Manager on MacOS, and XIM on Solaris. The host input method adapter plays the role of an input method within the input method framework, and translates events and requests between the data models used by AWT and the input method framework on one side and the host's input method manager on the other side. It also cooperates with the input context in managing the composition window - for passive clients interacting host input methods, typically the root window provided by the host input method manager is used. The adapter passes on requests for particular input methods to the host, but users can also use the host's selection mechanism to select input methods.

5. Context Management

InputContext instances manage communication contexts between client components and input methods. The main task of an input context is to maintain the connection from the current client component to its current input method. It dispatches input events such as key and mouse events from the component to the current input method, and input method events from the input method to the client component. It also dispatches requests for information from the input method to the client component.

Each InputContext instance provides its own text input environment, separate from all other input contexts. This allows applications to support multiple concurrent input operations. For example, in the middle of entering text into a document, a user can open a file dialog and enter a file name, without affecting the composition state of the text being entered into the document.

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. If necessary, components can create private input contexts. A component that doesn't have its own input context uses the one used by its parent. An input context has at most one current client component, the component that currently has the focus. When switching to a new client component, the input context calls its endComposition method to commit or cancel composed text for the previous client component.

The input context creates an input method instance for each input method engine that its client components need to use. Separate input method instances are created for each input context instance. The instances are kept until the input context is disposed, so that the instances can keep information about the text that was entered in the window.

The input context also handles input method selection and the composition window.

Selecting Input Methods

An input context has a current input method and a current locale.

The input method framework provides two separate ways of selecting input methods and input locales:

  • The method InputContext.selectInputMethod lets applications request an input method supporting a specified locale.
  • A user interface lets the user request an input method by name, and specify the input locale. A selection made from the user interface affects the currently active input context only.
The framework does not give preference to selections made either way, so the last successful selection made either way for an input context determines the current input method for an input context (note that selectInputMethod may fail if no available input method supports the requested locale).

Before switching to a new input method, the input context calls the old input method's endComposition method. The input context retains the old input method instance and reuses it when the same input method is selected again for this input context at a later point.

InputContext.selectInputMethod looks for an input method supporting the specified locale using the results of the InputMethodDescriptor.getAvailableLocales methods of all installed input methods. If the user has previously selected an input method with the specified locale from the user interface, this input method is chosen. Otherwise it is implementation dependent which input method is chosen if multiple input methods support the specified locale.

The user interface for selecting input methods is implementation dependent. It must provide the user with a list of all available input methods and let him/her select one of them. Where an input method supports multiple locales, the user interface also lets the user select the input locale (this facility may be omitted for host adapters if the host provides an alternative facility to select the input locale). Licensees developing Java runtime environments for their own platforms are encouraged to integrate the user interface with existing user interfaces for selecting keyboards or input methods.

In Sun's Java 2 runtime environments for Windows and Solaris, the user interface consists of three parts: a "Select Input Method" menu item added to the Window menu in Motif or the System menu in Windows, a user-defined input method selection key, and a pop-up menu brought up by either the "Select Input Method" menu item or the input method selection key. The "Select Input Method" item is only shown if the Java runtime environment has more than one input method available or the input method supports multiple locales (the host input method adapter is treated as a single input method). The popup menu lists the available input methods, with supported locales of multi-locale input methods as submenus, and lets the user select from this list. Sun's Java 2 runtime environment for Linux does not provide the "Select Input Method" menu item, i.e., the pop up menu is only brought up by pressing the input method selection key. The input method selection key definition is stored persistently using two preferences, one defining the base key code value and the other defining the modifiers. The "modifiers" preference is optional. If a modifiers entry is defined without matching keyCode entry, that modifiers entry is ignored. The following table shows the contents.

key name (String) | value (int)
"keyCode" | any java.awt.event.KeyEvent.VK_* value except VK_UNDEFINED
"modifiers" | any combination of java.awt.event.InputEvent.*_MASK

The Java 2 runtime looks for these preferences first in the user's preference tree node /java/awt/im/selectionKey, then, if no definition could be found, in the system preference node with the same path.

Composition Window

For passive clients and for active clients using below-the-spot input, the input method framework provides a composition window. The window is opened when the input method starts sending composed text; it is closed when all text is committed. At most one composition window is open at any time even if multiple compositions (using separate input contexts) are currently in progress.

For below-the-spot input, the window is automatically positioned just below the insertion point where text will be inserted after being committed. The window's location is calculated first when the window is opened, then updated whenever committed text has been dispatched to the client component. If positioning the window below the insertion point would move it partially or entirely off-screen, it is moved above the insertion point.

6. Information Flow Through the Framework

The framework provides two mechanisms to communicate information between the current client component and the current input method:
  • AWT events are used to pass information about user actions to the input method, and to notify the component of changes in the input text. This provides a programming interface that's consistent with other input operations. However, InputMethodEvents are typically dispatched synchronously to the component's methods, while other AWT events are dispatched asynchronously through the event queue.
  • The InputMethodRequests interface defines methods that an input method can call to request information from the client component. This invocation is synchronous.
Both event dispatching and calling InputMethodRequests methods are done indirectly through the input context. This lets the input context redirect information to a composition window if necessary. The composition window provides a full implementation of an active client, and so the input method can always assume it is interacting with an active client.

The following sections show the flow of events through the input method framework and explain the associated handling of input method requests. Four alternatives are described, depending on the kind of client component and the selected input style. All diagrams assume an input method implemented in the Java programming language using the input method engine SPI. Event flows for peered text components or native input methods are implementation dependent, may vary substantially, and are not shown.

Active Clients With On-the-Spot Input

The following context describes this graphic

Input events such as KeyEvent and MouseEvent are sent to the current input method through the InputContext object. If the input method uses the event for text composition, it marks the event consumed and generates an input method event to the component. The client component must have registered an InputMethodListener so it can handle InputMethodEvents coming from the input method and receive composed and committed text.

InputMethodRequests calls from the input method are forwarded to the object returned by the client component's getInputMethodRequests method.

Active Clients With Below-the-Spot Input

The following context describes this graphic

Input events such as KeyEvent and MouseEvent are sent to the current input method through the InputContext object. If the input method uses the event for text composition, it marks the event consumed and generates an input method event. Since below-the-spot input is selected, the event is redirected to the composition window, which handles it. When text is committed (partially or entirely), the composition window generates a new input method event holding the committed text for the client component. The client component must have registered an InputMethodListener so it can handle InputMethodEvents, which in this case come from the composition window and only contain committed text.

InputMethodRequests calls from the input method that relate to the display of composed text (getTextLocation, getLocationOffset) are handled by the composition window; all others are forwarded to the object returned by the client component's getInputMethodRequests method. The composition window uses the client component's getTextLocation implementation to position itself.

Passive Clients

The following context describes this graphic

Input events such as KeyEvent and MouseEvent are sent to the current input method through the InputContext object. If the input method uses the event for text composition, it marks the event consumed and generates an input method event. The event is redirected to the composition window, which handles it. When text is committed, the composition window translates it into key events for the actual client's key event listener. Only KEY_TYPED events are sent.

InputMethodRequests calls from the input method are handled by the composition window. Calls hat relate to the display of composed text (getTextLocation, getLocationOffset) are handled based on information about the composed text being displayed. All other calls are handled at all times based on the assumption that composition has just started and there's no committed text, because the composition window does not have access to text in the client component.

Non-Clients

The following context describes this graphic

Events for non-clients do not go to the input context. All events go straight to the component's listeners (here, the key listener).

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-intl@java.sun.com

Sun
Java Software


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 © 1995-99 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-intl@java.sun.com

Sun
Java Software


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.

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 © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-intl@java.sun.com

Sun
Java Software


: Class ActiveClient

Class Tree Index
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: INNER | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

Class ActiveClient

java.lang.Object
  |
  +--java.awt.Component
        |
        +--LWTextComponent
              |
              +--ActiveClient
public class ActiveClient
extends LWTextComponent
implements InputMethodListener, InputMethodRequests

Implements an integrated text input user interface. This class is an active client of the input method framework, that is, actively uses its APIs to accomplish integration.

This class directly implements the two client interfaces of the input method framework, InputMethodListener and InputMethodRequests. This is not required. Especially in cases where the public interface matters (such as in a class library), it may be more appropriate to hide the implementations of these two interfaces in separate classes.

See Also:
Serialized Form

Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
Constructor Summary
ActiveClient(String name)
Constructs an ActiveClient.
Method Summary
AttributedCharacterIterator | cancelLatestCommittedText(AttributedCharacterIterator.Attribute[] attributes) Returns null to indicate that the "Undo Commit" feature is not supported by this simple text component.
void | caretPositionChanged(InputMethodEvent event) Handles changes to the caret within composed text.
TextHitInfo | getCaret() Returns a text hit info indicating the current caret (insertion point).
AttributedCharacterIterator | getCommittedText(int beginIndex, int endIndex, AttributedCharacterIterator.Attribute[] attributes) Gets an iterator providing access to the entire text and attributes contained in the text editing component except for uncommitted text.
AttributedCharacterIterator | getDisplayText() Returns the text that the user has entered.
InputMethodRequests | getInputMethodRequests() Implements getInputMethodRequests for ActiveClient by returning "this".
int | getInsertPositionOffset() Gets the offset of the insert position in the committed text contained in the text editing component.
TextHitInfo | getLocationOffset(int x, int y) Gets the offset within the composed text for the specified absolute x and y coordinates on the screen.
AttributedCharacterIterator | getSelectedText(AttributedCharacterIterator.Attribute[] attributes) Gets the currently selected text from the text editing component.
Rectangle | getTextLocation(TextHitInfo offset) Gets the location of a specified offset in the current composed text, or of the selection in committed text.
void | inputMethodTextChanged(InputMethodEvent event) Handles changes to the text entered through an input method.
void | setFontSize(int size) Adjusts composed text for new font size.
Methods inherited from class LWTextComponent
focusGained, focusLost, getCaretRectangle, getCaretRectangle, getCommittedText, getCommittedText, getCommittedTextLength, getTextLayout, getTextOrigin, insertCharacter, invalidateTextLayout, keyPressed, keyReleased, keyTyped, paint
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addNotify, addPropertyChangeListener, addPropertyChangeListener, bounds, checkImage, checkImage, coalesceEvents, contains, contains, createImage, createImage, deliverEvent, disable, disableEvents, dispatchEvent, doLayout, enable, enable, enableEvents, enableInputMethods, firePropertyChange, getAlignmentX, getAlignmentY, getBackground, getBounds, getBounds, getColorModel, getComponentAt, getComponentAt, getComponentOrientation, getCursor, getDropTarget, getFont, getFontMetrics, getForeground, getGraphics, getHeight, getInputContext, getLocale, getLocation, getLocation, getLocationOnScreen, getMaximumSize, getMinimumSize, getName, getParent, getPeer, getPreferredSize, getSize, getSize, getToolkit, getTreeLock, getWidth, getX, getY, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, invalidate, isDisplayable, isDoubleBuffered, isEnabled, isFocusTraversable, isLightweight, isOpaque, isShowing, isValid, isVisible, keyDown, keyUp, layout, list, list, list, list, list, locate, location, lostFocus, minimumSize, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, paramString, postEvent, preferredSize, prepareImage, prepareImage, print, printAll, processComponentEvent, processEvent, processFocusEvent, processInputMethodEvent, processKeyEvent, processMouseEvent, processMouseMotionEvent, remove, removeComponentListener, removeFocusListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeNotify, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, repaint, requestFocus, reshape, resize, resize, setBackground, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setEnabled, setFont, setForeground, setLocale, setLocation, setLocation, setName, setSize, setSize, setVisible, show, show, size, toString, transferFocus, update, validate
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

ActiveClient

public ActiveClient(String name)
Constructs an ActiveClient. Input methods are always enabled for ActiveClient instances.
Parameters:
name - the component name to be displayed above the text
Method Detail

getInputMethodRequests

public InputMethodRequests getInputMethodRequests()
Implements getInputMethodRequests for ActiveClient by returning "this".
Returns:
"this"
Overrides:
getInputMethodRequests in class Component

setFontSize

public void setFontSize(int size)
Adjusts composed text for new font size.
Overrides:
setFontSize in class LWTextComponent

getDisplayText

public AttributedCharacterIterator getDisplayText()
Returns the text that the user has entered. This override returns the concatenation of committed text and composed text.
Overrides:
getDisplayText in class LWTextComponent

getCaret

public TextHitInfo getCaret()
Returns a text hit info indicating the current caret (insertion point). This override returns the caret provided by the input method while there is composed text; otherwise it returns a caret at the end of the committed text. The caret provided by the input method may be null.
Overrides:
getCaret in class LWTextComponent

inputMethodTextChanged

public void inputMethodTextChanged(InputMethodEvent event)
Handles changes to the text entered through an input method. Committed text contained in the event is appended to the committed text of the text component. Composed text contained in the event replaces any existing composed text in the text component. The caret defined in the event is saved and will be returned by getCaret if there is composed text. The component is redrawn.

In this simple component, we only keep input method highlight attributes. Smarter components may want to keep language, reading, input method segment, and other attributes as well.

Specified by:
inputMethodTextChanged in interface InputMethodListener

caretPositionChanged

public void caretPositionChanged(InputMethodEvent event)
Handles changes to the caret within composed text. The caret defined in the event is saved and will be returned by getCaret if there is composed text. The component is redrawn.
Specified by:
caretPositionChanged in interface InputMethodListener

getTextLocation

public Rectangle getTextLocation(TextHitInfo offset)
Gets the location of a specified offset in the current composed text, or of the selection in committed text.
Specified by:
getTextLocation in interface InputMethodRequests

getLocationOffset

public TextHitInfo getLocationOffset(int x,
                                     int y)
Gets the offset within the composed text for the specified absolute x and y coordinates on the screen.
Specified by:
getLocationOffset in interface InputMethodRequests

getInsertPositionOffset

public int getInsertPositionOffset()
Gets the offset of the insert position in the committed text contained in the text editing component. In this simple component, that's always at the end of the committed text.
Specified by:
getInsertPositionOffset in interface InputMethodRequests

getCommittedText

public AttributedCharacterIterator getCommittedText(int beginIndex,
                                                    int endIndex,
                                                    AttributedCharacterIterator.Attribute[] attributes)
Gets an iterator providing access to the entire text and attributes contained in the text editing component except for uncommitted text.
Specified by:
getCommittedText in interface InputMethodRequests

cancelLatestCommittedText

public AttributedCharacterIterator cancelLatestCommittedText(AttributedCharacterIterator.Attribute[] attributes)
Returns null to indicate that the "Undo Commit" feature is not supported by this simple text component.
Specified by:
cancelLatestCommittedText in interface InputMethodRequests

getSelectedText

public AttributedCharacterIterator getSelectedText(AttributedCharacterIterator.Attribute[] attributes)
Gets the currently selected text from the text editing component. Since this simple text component doesn't support selections, this is always an iterator over empty text.
Specified by:
getSelectedText in interface InputMethodRequests
Class Tree Index
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: INNER | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD
Java, Java 2D, and JDBC are trademarks or registered trademarks of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-1999 Sun Microsystems, Inc. 901 San Antonio Road
Palo Alto, California, 94303, U.S.A. All Rights Reserved.


 All Classes
ActiveClient
LWTextComponent


Input Method Framework Demo

alt="Applet that shows different ways of interacting with input methods"
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 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.


Generated Documentation (Untitled)

Frame Alert

This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client.
Link to Non-frame version.


: Index

Class Tree Index
PREV NEXT FRAMES NO FRAMES
A C F G I K L P S

A

ActiveClient - class ActiveClient.
Implements an integrated text input user interface.
ActiveClient(String) - Constructor for class ActiveClient
Constructs an ActiveClient.

C

cancelLatestCommittedText(AttributedCharacterIterator.Attribute[]) - Method in class ActiveClient
Returns null to indicate that the "Undo Commit" feature is not supported by this simple text component.
caretPositionChanged(InputMethodEvent) - Method in class ActiveClient
Handles changes to the caret within composed text.

F

focusGained(FocusEvent) - Method in class LWTextComponent
Turns on drawing of the component's thicker frame and the caret.
focusLost(FocusEvent) - Method in class LWTextComponent
Turns off drawing of the component's thicker frame and the caret.

G

getCaret() - Method in class ActiveClient
Returns a text hit info indicating the current caret (insertion point).
getCaret() - Method in class LWTextComponent
Returns a text hit info indicating the current caret (insertion point).
getCaretRectangle() - Method in class LWTextComponent
Returns a 0-width caret rectangle.
getCaretRectangle(TextHitInfo) - Method in class LWTextComponent
Returns a 0-width caret rectangle for the given text index.
getCommittedText() - Method in class LWTextComponent
Returns the text that the user has entered and committed.
getCommittedText(int, int) - Method in class LWTextComponent
Returns a subrange of the text that the user has entered and committed.
getCommittedText(int, int, AttributedCharacterIterator.Attribute[]) - Method in class ActiveClient
Gets an iterator providing access to the entire text and attributes contained in the text editing component except for uncommitted text.
getCommittedTextLength() - Method in class LWTextComponent
Returns the length of the text that the user has entered and committed.
getDisplayText() - Method in class ActiveClient
Returns the text that the user has entered.
getDisplayText() - Method in class LWTextComponent
Returns the text that the user has entered.
getInputMethodRequests() - Method in class ActiveClient
Implements getInputMethodRequests for ActiveClient by returning "this".
getInsertPositionOffset() - Method in class ActiveClient
Gets the offset of the insert position in the committed text contained in the text editing component.
getLocationOffset(int, int) - Method in class ActiveClient
Gets the offset within the composed text for the specified absolute x and y coordinates on the screen.
getSelectedText(AttributedCharacterIterator.Attribute[]) - Method in class ActiveClient
Gets the currently selected text from the text editing component.
getTextLayout() - Method in class LWTextComponent
Returns a text layout for the text that the user has entered.
getTextLocation(TextHitInfo) - Method in class ActiveClient
Gets the location of a specified offset in the current composed text, or of the selection in committed text.
getTextOrigin() - Method in class LWTextComponent
Returns the origin of the text.

I

inputMethodTextChanged(InputMethodEvent) - Method in class ActiveClient
Handles changes to the text entered through an input method.
insertCharacter(char) - Method in class LWTextComponent
Inserts the given character at the end of the text.
invalidateTextLayout() - Method in class LWTextComponent
Invalidates the cached text layout.

K

keyPressed(KeyEvent) - Method in class LWTextComponent
Ignores key pressed events.
keyReleased(KeyEvent) - Method in class LWTextComponent
Ignores key released events.
keyTyped(KeyEvent) - Method in class LWTextComponent
Handles the key typed event.

L

LWTextComponent - class LWTextComponent.
Implements a very simple lightweight text editing component.
LWTextComponent(String, boolean) - Constructor for class LWTextComponent
Constructs a LWTextComponent.

P

paint(Graphics) - Method in class LWTextComponent
Draws the component.

S

setFontSize(int) - Method in class ActiveClient
Adjusts composed text for new font size.
setFontSize(int) - Method in class LWTextComponent
A C F G I K L P S
Class Tree Index
PREV NEXT FRAMES NO FRAMES
Java, Java 2D, and JDBC are trademarks or registered trademarks of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-1999 Sun Microsystems, Inc. 901 San Antonio Road
Palo Alto, California, 94303, U.S.A. All Rights Reserved.


: Class LWTextComponent

Class Tree Index
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: INNER | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

Class LWTextComponent

java.lang.Object
  |
  +--java.awt.Component
        |
        +--LWTextComponent
Direct Known Subclasses:
ActiveClient
public class LWTextComponent
extends Component
implements KeyListener, FocusListener

Implements a very simple lightweight text editing component. It lets the user edit a single line of text using the keyboard. The only special character that it knows about is backspace; all other characters are added to the text. Selections are not supported, so there's only a simple caret indicating the insertion point. The component also displays a component name above the editable text line, and draws a black frame whose thickness indicates whether the component has the focus.

The component can be initialized to enable or disable input through input methods. Other than that, it doesn't do anything to support input methods, so input method interaction (if any) will occur in a separate composition window. However, the component is designed to be easily extended with full input method support. It distinguishes between "displayed text" and "committed text" - here, they're the same, but in a subclass that supports on-the-spot input, the displayed text would be the combination of committed text and composed text. The component also uses TextLayout to draw the text, so it can be easily extended to handle input method highlights.

See Also:
Serialized Form

Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
Constructor Summary
LWTextComponent(String name, boolean enableInputMethods)
Constructs a LWTextComponent.
Method Summary
void | focusGained(FocusEvent event) Turns on drawing of the component's thicker frame and the caret.
void | focusLost(FocusEvent event) Turns off drawing of the component's thicker frame and the caret.
TextHitInfo | getCaret() Returns a text hit info indicating the current caret (insertion point).
Rectangle | getCaretRectangle() Returns a 0-width caret rectangle.
Rectangle | getCaretRectangle(TextHitInfo caret) Returns a 0-width caret rectangle for the given text index.
AttributedCharacterIterator | getCommittedText() Returns the text that the user has entered and committed.
AttributedCharacterIterator | getCommittedText(int beginIndex, int endIndex) Returns a subrange of the text that the user has entered and committed.
int | getCommittedTextLength() Returns the length of the text that the user has entered and committed.
AttributedCharacterIterator | getDisplayText() Returns the text that the user has entered.
TextLayout | getTextLayout() Returns a text layout for the text that the user has entered.
Point | getTextOrigin() Returns the origin of the text.
void | insertCharacter(char c) Inserts the given character at the end of the text.
void | invalidateTextLayout() Invalidates the cached text layout.
void | keyPressed(KeyEvent event) Ignores key pressed events.
void | keyReleased(KeyEvent event) Ignores key released events.
void | keyTyped(KeyEvent event) Handles the key typed event.
void | paint(Graphics g) Draws the component.
void | setFontSize(int size)
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addNotify, addPropertyChangeListener, addPropertyChangeListener, bounds, checkImage, checkImage, coalesceEvents, contains, contains, createImage, createImage, deliverEvent, disable, disableEvents, dispatchEvent, doLayout, enable, enable, enableEvents, enableInputMethods, firePropertyChange, getAlignmentX, getAlignmentY, getBackground, getBounds, getBounds, getColorModel, getComponentAt, getComponentAt, getComponentOrientation, getCursor, getDropTarget, getFont, getFontMetrics, getForeground, getGraphics, getHeight, getInputContext, getInputMethodRequests, getLocale, getLocation, getLocation, getLocationOnScreen, getMaximumSize, getMinimumSize, getName, getParent, getPeer, getPreferredSize, getSize, getSize, getToolkit, getTreeLock, getWidth, getX, getY, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, invalidate, isDisplayable, isDoubleBuffered, isEnabled, isFocusTraversable, isLightweight, isOpaque, isShowing, isValid, isVisible, keyDown, keyUp, layout, list, list, list, list, list, locate, location, lostFocus, minimumSize, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, paramString, postEvent, preferredSize, prepareImage, prepareImage, print, printAll, processComponentEvent, processEvent, processFocusEvent, processInputMethodEvent, processKeyEvent, processMouseEvent, processMouseMotionEvent, remove, removeComponentListener, removeFocusListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeNotify, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, repaint, requestFocus, reshape, resize, resize, setBackground, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setEnabled, setFont, setForeground, setLocale, setLocation, setLocation, setName, setSize, setSize, setVisible, show, show, size, toString, transferFocus, update, validate
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

LWTextComponent

public LWTextComponent(String name,
                       boolean enableInputMethods)
Constructs a LWTextComponent.
Parameters:
name - the component name to be displayed above the text
enableInputMethods - whether to enable input methods for this component
Method Detail

setFontSize

public void setFontSize(int size)

paint

public void paint(Graphics g)
Draws the component. The following items are drawn:
  • the component's background
  • a frame, thicker if the component has the focus
  • the component name
  • the text that the user has entered
  • the caret, if the component has the focus
Overrides:
paint in class Component

getCommittedText

public AttributedCharacterIterator getCommittedText()
Returns the text that the user has entered and committed. Since this component does not support on-the-spot input, there's no composed text, so all text that has been entered is committed.
Returns:
an AttributedCharacterIterator for the text that the user has entered and committed

getCommittedText

public AttributedCharacterIterator getCommittedText(int beginIndex,
                                                    int endIndex)
Returns a subrange of the text that the user has entered and committed. Since this component does not support on-the-spot input, there's no composed text, so all text that has been entered is committed.
Parameters:
beginIndex - the index of the first character of the subrange
endIndex - the index of the character following the subrange
Returns:
an AttributedCharacterIterator for a subrange of the text that the user has entered and committed

getCommittedTextLength

public int getCommittedTextLength()
Returns the length of the text that the user has entered and committed. Since this component does not support on-the-spot input, there's no composed text, so all text that has been entered is committed.
Returns:
the length of the text that the user has entered and committed

getDisplayText

public AttributedCharacterIterator getDisplayText()
Returns the text that the user has entered. As TextLayout requires a font to be defined for each character, the default font is applied to the entire text. A subclass that supports on-the-spot input must override this method to include composed text.
Returns:
the text that the user has entered

getTextLayout

public TextLayout getTextLayout()
Returns a text layout for the text that the user has entered. This text layout is created from the text returned by getDisplayText. The text layout is cached until invalidateTextLayout is called.
Returns:
a text layout for the text that the user has entered, or null
See Also:
invalidateTextLayout(), getDisplayText()

invalidateTextLayout

public void invalidateTextLayout()
Invalidates the cached text layout. This must be called whenever the component's text is modified.
See Also:
getTextLayout()

getTextOrigin

public Point getTextOrigin()
Returns the origin of the text. This is the leftmost point on the baseline of the text.
Returns:
the origin of the text

getCaretRectangle

public Rectangle getCaretRectangle()
Returns a 0-width caret rectangle. This rectangle is derived from the caret returned by getCaret. getCaretRectangle returns null iff getCaret does.
Returns:
the caret rectangle, or null
See Also:
getCaret()

getCaretRectangle

public Rectangle getCaretRectangle(TextHitInfo caret)
Returns a 0-width caret rectangle for the given text index. It is calculated based on the text layout returned by getTextLayout, so this method can be used for the entire displayed text.
Parameters:
caret - the text index for which to calculate a caret rectangle
Returns:
the caret rectangle

getCaret

public TextHitInfo getCaret()
Returns a text hit info indicating the current caret (insertion point). This class always returns a caret at the end of the text that the user has entered. Subclasses may return a different caret or null.
Returns:
the caret, or null

insertCharacter

public void insertCharacter(char c)
Inserts the given character at the end of the text.
Parameters:
c - the character to be inserted

keyTyped

public void keyTyped(KeyEvent event)
Handles the key typed event. If the character is backspace, the last character is removed from the text that the user has entered. Otherwise, the character is appended to the text. Then, the text is redrawn.
Specified by:
keyTyped in interface KeyListener

keyPressed

public void keyPressed(KeyEvent event)
Ignores key pressed events.
Specified by:
keyPressed in interface KeyListener

keyReleased

public void keyReleased(KeyEvent event)
Ignores key released events.
Specified by:
keyReleased in interface KeyListener

focusGained

public void focusGained(FocusEvent event)
Turns on drawing of the component's thicker frame and the caret.
Specified by:
focusGained in interface FocusListener

focusLost

public void focusLost(FocusEvent event)
Turns off drawing of the component's thicker frame and the caret.
Specified by:
focusLost in interface FocusListener
Class Tree Index
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: INNER | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD
Java, Java 2D, and JDBC are trademarks or registered trademarks of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-1999 Sun Microsystems, Inc. 901 San Antonio Road
Palo Alto, California, 94303, U.S.A. All Rights Reserved.


: Class Hierarchy

Class Tree Index
PREV NEXT FRAMES NO FRAMES

Hierarchy For All Packages

Class Hierarchy

  • class java.lang.Object
    • class java.awt.Component (implements java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable)
      • class LWTextComponent (implements java.awt.event.FocusListener, java.awt.event.KeyListener)
        • class ActiveClient (implements java.awt.event.InputMethodListener, java.awt.im.InputMethodRequests)
Class Tree Index
PREV NEXT FRAMES NO FRAMES
Java, Java 2D, and JDBC are trademarks or registered trademarks of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-1999 Sun Microsystems, Inc. 901 San Antonio Road
Palo Alto, California, 94303, U.S.A. All Rights Reserved.


Serialized Form

Class ActiveClient implements Serializable

Serialized Fields

caret

TextHitInfo caret

composedText

AttributedCharacterIterator composedText

composedTextString

AttributedString composedTextString

Class LWTextComponent implements Serializable

Serialized Fields

committedText

StringBuffer committedText

name

String name

nameOriginY

int nameOriginY

textOriginX

int textOriginX

textOriginY

int textOriginY

Class Tree Index
PREV NEXT FRAMES NO FRAMES
Java, Java 2D, and JDBC are trademarks or registered trademarks of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-1999 Sun Microsystems, Inc. 901 San Antonio Road
Palo Alto, California, 94303, U.S.A. All Rights Reserved.


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 © 1999 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-intl@java.sun.com

Sun
Java Software


Supported Encodings

The classes java.io.InputStreamReader, java.io.OutputStreamWriter, java.lang.String, 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 2 platform. The java.lang package specification and the class description for java.nio.charset.Charset list the encodings that any implementation of the Java 2 platform, Standard Edition, v. 1.4.2 is required to support.

Sun's Java 2 Software Development Kit, Standard Edition, v. 1.4.2 for all platforms (SolarisTM operating environment, Linux, and Microsoft Windows) and the Java 2 Runtime Environment, Standard Edition, v. 1.4.2 for Solaris and Linux support all encodings shown on this page. Sun's Java 2 Runtime Environment, Standard Edition, v. 1.4.2 for Windows may be installed as a complete international version or as a European languages version. The J2RE installer by default 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 first 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 J2SE 1.4.2. 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)
Supported by java.nio, java.io and java.lang APIs

Canonical Name for java.nio API | Canonical Name for java.io and java.lang API | Description
US-ASCII | ASCII | American Standard Code for Information Interchange
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
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-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
UTF-8 | UTF8 | Eight-bit UCS Transformation Format
UTF-16 | UTF-16 | Sixteen-bit UCS Transformation Format, byte order identified by an optional byte-order mark
UTF-16BE | UnicodeBigUnmarked | Sixteen-bit Unicode Transformation Format, big-endian byte order
UTF-16LE | UnicodeLittleUnmarked | Sixteen-bit Unicode Transformation Format, little-endian byte order
Not available | UnicodeBig | Sixteen-bit Unicode Transformation Format, big-endian byte order, with byte-order mark
Not available | UnicodeLittle | Sixteen-bit Unicode Transformation Format, little-endian byte order, with byte-order mark

Extended Encoding Set (contained in lib/charsets.jar)
Supported by java.nio, java.io and java.lang APIs

Canonical Name for java.nio API | Canonical Name for java.io and java.lang API | Description
windows-1255 | Cp1255 | Windows Hebrew
windows-1256 | Cp1256 | Windows Arabic
windows-1258 | Cp1258 | Windows Vietnamese
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
windows-31j | MS932 | Windows Japanese
EUC-JP | EUC_JP | JISX 0201, 0208 and 0212, EUC encoding Japanese
x-EUC-JP-LINUX | EUC_JP_LINUX | JISX 0201, 0208 , EUC encoding Japanese
Shift_JIS | SJIS | Shift-JIS, Japanese
ISO-2022-JP | ISO2022JP | JIS X 0201, 0208, in ISO 2022 form, Japanese
x-mswin-936 | MS936 | Windows Simplified Chinese
GB18030 | GB18030 | Simplified Chinese, PRC standard
x-EUC-CN | EUC_CN | GB2312, EUC encoding, Simplified Chinese
GBK | GBK | GBK, Simplified Chinese
ISCII91 | ISCII91 | ISCII91 encoding of Indic scripts
x-windows-949 | MS949 | Windows Korean
EUC-KR | EUC_KR | KS C 5601, EUC encoding, Korean
ISO-2022-KR | ISO2022KR | ISO 2022 KR, Korean
x-windows-950 | MS950 | Windows Traditional Chinese
x-MS950-HKSCS | MS950_HKSCS | Windows Traditional Chinese with Hong Kong extensions
x-EUC-TW | EUC_TW | CNS11643 (Plane 1-3), EUC encoding, Traditional Chinese
Big5 | Big5 | Big5, Traditional Chinese
Big5-HKSCS | Big5_HKSCS | Big5 with Hong Kong extensions, Traditional Chinese
TIS-620 | TIS620 | TIS620, Thai

Extended Encoding Set (contained in lib/charsets.jar)
Supported by java.io and java.lang APIs

Canonical Name | Description
Big5_Solaris | Big5 with seven additional Hanzi ideograph character mappings for the Solaris zh_TW.BIG5 locale
Cp037 | USA, Canada (Bilingual, French), Netherlands, Portugal, Brazil, Australia
Cp273 | IBM Austria, Germany
Cp277 | IBM Denmark, Norway
Cp278 | IBM Finland, Sweden
Cp280 | IBM Italy
Cp284 | IBM Catalan/Spain, Spanish Latin America
Cp285 | IBM United Kingdom, Ireland
Cp297 | IBM France
Cp420 | IBM Arabic
Cp424 | IBM Hebrew
Cp437 | MS-DOS United States, Australia, New Zealand, South Africa
Cp500 | EBCDIC 500V1
Cp737 | PC Greek
Cp775 | PC Baltic
Cp838 | IBM Thailand extended SBCS
Cp850 | MS-DOS Latin-1
Cp852 | MS-DOS Latin-2
Cp855 | IBM Cyrillic
Cp856 | IBM Hebrew
Cp857 | IBM Turkish
Cp858 | Variant of Cp850 with Euro character
Cp860 | MS-DOS Portuguese
Cp861 | MS-DOS Icelandic
Cp862 | PC Hebrew
Cp863 | MS-DOS Canadian French
Cp864 | PC Arabic
Cp865 | MS-DOS Nordic
Cp866 | MS-DOS Russian
Cp868 | MS-DOS Pakistan
Cp869 | IBM Modern Greek
Cp870 | IBM Multilingual Latin-2
Cp871 | IBM Iceland
Cp874 | IBM Thai
Cp875 | IBM Greek
Cp918 | IBM Pakistan (Urdu)
Cp921 | IBM Latvia, Lithuania (AIX, DOS)
Cp922 | IBM Estonia (AIX, DOS)
Cp930 | Japanese Katakana-Kanji mixed with 4370 UDC, superset of 5026
Cp933 | Korean Mixed with 1880 UDC, superset of 5029
Cp935 | Simplified Chinese Host mixed with 1880 UDC, superset of 5031
Cp937 | Traditional Chinese Host miexed with 6204 UDC, superset of 5033
Cp939 | Japanese Latin Kanji mixed with 4370 UDC, superset of 5035
Cp942 | IBM OS/2 Japanese, superset of Cp932
Cp942C | Variant of Cp942
Cp943 | IBM OS/2 Japanese, superset of Cp932 and Shift-JIS
Cp943C | Variant of Cp943
Cp948 | OS/2 Chinese (Taiwan) superset of 938
Cp949 | PC Korean
Cp949C | Variant of Cp949
Cp950 | PC Chinese (Hong Kong, Taiwan)
Cp964 | AIX Chinese (Taiwan)
Cp970 | AIX Korean
Cp1006 | IBM AIX Pakistan (Urdu)
Cp1025 | IBM Multilingual Cyrillic: Bulgaria, Bosnia, Herzegovinia, Macedonia (FYR)
Cp1026 | IBM Latin-5, Turkey
Cp1046 | IBM Arabic - Windows
Cp1097 | IBM Iran (Farsi)/Persian
Cp1098 | IBM Iran (Farsi)/Persian (PC)
Cp1112 | IBM Latvia, Lithuania
Cp1122 | IBM Estonia
Cp1123 | IBM Ukraine
Cp1124 | IBM AIX Ukraine
Cp1140 | Variant of Cp037 with Euro character
Cp1141 | Variant of Cp273 with Euro character
Cp1142 | Variant of Cp277 with Euro character
Cp1143 | Variant of Cp278 with Euro character
Cp1144 | Variant of Cp280 with Euro character
Cp1145 | Variant of Cp284 with Euro character
Cp1146 | Variant of Cp285 with Euro character
Cp1147 | Variant of Cp297 with Euro character
Cp1148 | Variant of Cp500 with Euro character
Cp1149 | Variant of Cp871 with Euro character
Cp1381 | IBM OS/2, DOS People's Republic of China (PRC)
Cp1383 | IBM AIX People's Republic of China (PRC)
Cp33722 | IBM-eucJP - Japanese (superset of 5050)
ISO2022_CN_CNS | CNS11643 in ISO 2022 CN form, Traditional Chinese (conversion from Unicode only)
ISO2022_CN_GB | GB2312 in ISO 2022 CN form, Simplified Chinese (conversion from Unicode only)
JISAutoDetect | Detects and converts from Shift-JIS, EUC-JP, ISO 2022 JP (conversion to Unicode only)
MS874 | Windows Thai
MacArabic | Macintosh Arabic
MacCentralEurope | Macintosh Latin-2
MacCroatian | Macintosh Croatian
MacCyrillic | Macintosh Cyrillic
MacDingbat | Macintosh Dingbat
MacGreek | Macintosh Greek
MacHebrew | Macintosh Hebrew
MacIceland | Macintosh Iceland
MacRoman | Macintosh Roman
MacRomania | Macintosh Romania
MacSymbol | Macintosh Symbol
MacThai | Macintosh Thai
MacTurkish | Macintosh Turkish
MacUkraine | Macintosh Ukraine

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-intl@java.sun.com

Sun
Java Software


Internationalization Frequently Asked Questions

Java

Internationalization
Frequently Asked Questions

This page answers common questions about internationalization of the Java 2 platform, Standard Edition, version 1.4.2, and of Sun's Java 2 Runtime Environments, Standard Edition, version 1.4.2. For more information, see the Internationalization home page.

  • General Questions
  • Locales
  • Resource Bundles
  • Text Processing
  • Character Encodings
  • Text Input
  • Text Rendering
  • Component Orientation
  • Miscellaneous

General Questions

What is internationalization?

Internationalization allows software to be adapted to any language and cultural convention. During the internationalization process, the programmer isolates the parts of a program that are dependent on language and culture. For example, the programmer will isolate error messages because they must be translated during localization.

What is localization?

Localization is the process of adapting a program for use in a specific locale. A locale is a geographic or political region that shares the same language and customs. Localization includes the translation of text such as GUI labels, error messages, and online help. It also includes the culture-specific formatting of data items such as monetary values, times, dates, and numbers.

How do I go about internationalizing an existing program?

See the steps outlined in the Checklist section of the The Java Tutorial.

Locales

What is a locale?

A locale is a geographic or political region that shares the same language and customs. In the Java programming language, a locale is represented by a Locale object. Locale-sensitive operations, such as collation and date formatting, vary according to locale.

Where can I find some coding examples that use Locale objects?

See the Setting the Locale section of the The Java Tutorial.

Which locales are supported?

The supported locales vary between different implementations of the Java 2 platform and between areas of functionality. Information about the supported locales in Sun's Java 2 Runtime Environments is provided by the Supported Locales document.

Can a Java application use multiple locales?

Yes. This capability allows you to create multilingual applications.

Can I set the default locale from outside an application?

This depends on the implementation of the Java 2 platform you're using. The initial default locale is normally determined from the host operating system's locale. Version 1.4.2 of Sun's Java 2 Runtime Environments lets you override this by setting the user.language, user.country, and user.variant system properties from the command line. For example, to select Locale("th", "TH", "TH") as the initial default locale, you would use:

java -Duser.language=th -Duser.country=TH -Duser.variant=TH MainClass

Since not all runtime environments provide this feature, it should only be used for testing.

Resource Bundles

What is a resource bundle?

A ResourceBundle object allows you to isolate localizable elements from the rest of the application. With all resources separated into a bundle, the application simply loads the appropriate bundle for the active locale. If the user switches locales, the application just loads a different bundle.

Where can I find some coding examples that use ResourceBundle objects?

See the Isolating Locale-Specific Data section of the The Java Tutorial.

How do I specify non-ASCII strings in a properties file?

You can specify any Unicode character with the \uXXXX notation. (The XXXX denotes the 4 hexadecimal digits that comprise the Unicode value of a character.) For example, a properties file might have the following entries:

s1=hello there
s2=\uff2d\uff33\u30b4

If you have edited and saved the file in a non-ASCII encoding, you can convert it to ASCII with the native2ascii tool. For example, you might want to do this when editing a properties file in Shift-JIS, a popular Japanese encoding.

How do I compile a non-ASCII ListResourceBundle?

If your source file is in a non-ASCII encoding, you can direct the compiler to convert it into Unicode. For example, you would compile a Japanese resource bundle written in the Shift-JIS encoding as follows:

javac -encoding SJIS LabelsResource_ja.java

Text Processing

How do I format a date?

You can use the SimpleDateFormat to format and parse dates in a locale-sensitive manner. See the section on formatting Dates and Times in the The Java Tutorial.

Are formatters thread-safe?

Instances of java.text.Format and its subclasses are generally not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.

How does setting the default locale affect the results of sorting?

The Collator class, and its subclasses, are used for building sorting routines. These classes are locale-sensitive, and when created with the no-argument constructor will use the collating sequence of the default locale.

The Collator object supports different levels of decomposition and strength. How do I choose the right decomposition and strength in a locale?

Since decomposing takes time, turning decomposition off makes comparisons go faster. However, for Latin languages the NO_DECOMPOSITION mode is not useful if the text contains accents. You should use the default decomposition unless you really know what you're doing.

The strength property you choose depends on what your application is trying to accomplish. For example, when performing a text search you may allow a "weak" match, in which accents and differences in case (upper vs. lower) are ignored. This type of search employs the PRIMARY strength. If you are sorting a list of words, you might want to use the TERTIARY strength. In this mode the properties that must match are the base character, accent, and case.

Character Encodings

What is a character encoding?

A character encoding is a mapping between characters and code values.

What is Unicode?

In the Java programming language, char values represent Unicode characters. Unicode is a 16-bit character encoding that supports the world's major languages. You can learn more about the Unicode standard at the Unicode Consortium web site.

How do I convert data between Unicode and other character encodings?

The Converting Non-Unicode Text section of the The Java Tutorial explains how to perform the conversions within an application using high-level APIs, or see the java.nio.charset.Charset class if you need more direct access to character conversion. To convert data files, use the native2ascii tool.

Which character encodings are supported when converting text to and from Unicode?

See the Supported Encodings web page.

How do I create my own character converters?

The java.nio.charset.spi.CharsetProvider class lets developers create their own character converters.

What is the default encoding?

The default encoding is selected by the Java runtime based on the host operating system and its locale. For example, in the US locale on Windows, Cp1252 is used. In the Simplified Chinese locale on Solaris, either EUC_CN or GBK can be the default encoding, depending on the selection made when logging into Solaris.

The default encoding is significant because the Java programming language uses Unicode to represent characters, but the file system of the host operating system usually uses some other encoding. The default encoding has to match the encoding used by the host operating system to ensure correct interaction.

Why can't I use all European characters on Solaris?

There are many character encodings that don't support all European characters (such as "ß" or "é"), but we get this question particularly often from users of the Solaris C locale. On Solaris and Linux, the Java 2 Runtime Environment version 1.2 and higher determines the default encoding by calling the nl_langinfo function. On Solaris 7 and higher, this function returns "646" when run in the C locale, indicating ISO 646 or ASCII as the default encoding. ASCII only includes half the characters of ISO 8859-1, so many commonly used European characters are missing.

An easy workaround is to use the Solaris en_US locale, which uses ISO 8859-1 as its character encoding. You can set the Solaris locale from the login screen or by setting the the LC_ALL environment variable. Another solution is to explicitly specify the desired character encoding in your calls to String, java.io, and java.nio API that performs encoding conversion.

What is the UTF-8 encoding?

UTF-8 stands for Unicode (or UCS) Transformation Format, 8-bit encoding form. It is a transmission format for Unicode that is suitable for use with many network protocols and UNIX file systems.

Are the Cp1252 and ISO8859_1 encodings identical?

No. Cp1252 contains some additional characters in the range from 0x80 to 0x9F. See the Microsoft documentation for more information.

Text Input

What is the Input Method Framework?

The input method framework enables all text editing components to receive Japanese, Chinese, or Korean text input through input methods. An input method lets users enter thousands of different characters using keyboards with far fewer keys. Typically a sequence of several characters needs to be typed and then converted to create one or more characters. For specifications and examples see the web page, Input Method Framework.

What does it mean to switch input methods?

A user may have multiple input methods available. For example, the user may have input methods for different languages or input methods that accept various types of input. Such a user must be able to select the input method used for a particular language or the input method that provides the fastest input.

Can an input method be selected and activated programmatically?

An application can request an input method that supports a specific locale using the InputContext.selectInputMethod method, but it cannot select a specific input method - that selection is up to the user.

An application can activate an input method using the InputContext.setCompositionEnabled method.

Do the AWT and Swing (JFC) text components work with input methods?

See the Input Methods section of the Java 2 SDK Internationalization Overview.

Text Rendering

What choices does an application have in selecting fonts?

An application using lightweight components can select fonts in four different ways:

  • Using logical font names: The Java 2 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. Typically one logical font name maps to several physical fonts in order to cover a large range of characters.
  • Using physical font names: The Java 2 platform provides APIs that let an application determine which fonts are available to a given runtime and which characters these fonts can handle, and request these fonts using their real name (for example, "Times Roman" or "Helvetica"). The application can either let the user choose fonts or programmatically determine the fonts to be used.
  • Using the Lucida fonts: Sun's Java 2 Runtime Environments contain this family of physical fonts, which is also licensed for use in other implementations of the Java 2 platform. These fonts are physical fonts, but don't depend on the host operating system.
  • Using bundled physical fonts: An application can bundle TrueType fonts and instantiate them using the Font.createFont method.

An application using peered AWT components can only use logical font names.

What are the advantages and disadvantages of these four approaches?

Here's a brief summary:

  • Using logical font names:
    • Advantages: These font names are guaranteed to work anywhere, and they enable text rendering in at least the language that the host operating system is localized for (often a much larger range of languages).
    • Disadvantages: The physical fonts used for rendering the text vary between different implementations, host operating systems, and locales, so an application can not achieve the same look everywhere. Also, the mapping mechanisms often limit the range of characters that can be rendered. For example, in Sun's Java 2 Runtime Environments Japanese text can only be rendered on Japanese localized host operating systems, not on other localized systems even if Japanese fonts have been installed.
  • Using physical font names:
    • Advantages: This approach lets an application take full advantage of all available fonts, to accomplish both different text appearances and maximum language coverage.
    • Disadvantages: This approach is substantially harder to program.
  • Using the Lucida fonts:
    • Advantages: Applications using these fonts can achieve the same look wherever these fonts are available. Also, these fonts cover a large range of languages (especially European and Middle Eastern), so you can create fully multilingual applications for the supported languages.
    • Disadvantages: These fonts may not be available in all Java 2 runtime environments. Also, they currently do not cover the complete Unicode character set; in particular, Chinese, Japanese, and Korean are not supported.
  • Using bundled physical fonts:
    • Advantages: Applications using these fonts can achieve the same look everywhere, and have full control over which languages they support.
    • Disadvantages: The bundled fonts may be quite big, in particular if they support Chinese, Japanese, and Korean. Licensing issues need to be resolved.

Why doesn't my application display any Chinese, Japanese, or Korean characters even though I have fonts for these languages installed?

The answer depends on how your application selects fonts - see above.

  • Using logical font names: To use a physical font, it must be selected by the mapping mechanism. In Sun's Java 2 Runtime Environments, fonts for Chinese, Japanese, or Korean are only selected when running on host operating systems localized for these specific languages. To change the mapping, you need to modify a font.properties file - see below.
  • Using physical font names: Your application may not be selecting the fonts correctly, or the font may be using an encoding that's not supported by the Java 2 Runtime Environment.
  • Using the Lucida fonts: The Lucida fonts included in Sun's Java 2 Runtime Environments do not support Chinese, Japanese, or Korean.
  • Using bundled physical fonts: The fonts bundled with your application may not support these languages.

What is a font.properties file?

The font.properties files are used in Sun's Java 2 Runtime Environments to map logical font names to physical fonts. There are several files to support different mappings depending on host operating system version and locale. The files are located in the lib directory within the J2RE installation.

Note that font.properties files are implementation dependent. Not all implementations of the Java 2 platform use them, and the format and content vary between different runtime environments as well as between releases.

How do I add a physical font to the mapping of a logical font?

Since the mapping from logical fonts to physical fonts is implementation dependent, the answer varies. For Sun's Java 2 Runtime Environments, you need to create or modify a font.properties file - see the web page The font.properties Files. Note however that this is a modification of the J2RE, and Sun does not support modified J2REs. For other implementations, see their respective documentation.

Why can I see some characters in Swing components, but not in peered AWT components?

Swing user interface components use a different mechanism to render text than peered AWT components. The Swing components use the Graphics.drawString method, typically specifying a logical font name. The logical font name is then mapped to a set of physical fonts to cover a large range of characters. AWT components on the other hand are implemented using host operating system components. These host operating system components often do not support Unicode, so the text gets converted to some other character encoding, depending on the host operating system and locale. These encodings often cover a smaller range of characters than the physical fonts used to implement logical font names. For example, on a Japanese Windows 98 system, many European accented characters are mapped to the Arial font for Swing components, but get lost when converting the text to the Shift-JIS encoding for peered AWT components.

Why can't my application display all Unicode characters even though I have a Unicode font installed?

As in the Chinese/Japanese/Korean case above, this may be because text is not rendered using the Unicode font at all or only for some characters. If your application selects the Unicode font using its physical font name, and it still cannot render all characters, it could be that the Unicode font doesn't in fact cover the entire Unicode character set - sometimes a font is called a Unicode font if it just provides the tables that support the Unicode character encoding.

What font types do Sun's Java 2 Runtime Environments support?

See the Supported Fonts document.

Is it possible to display more than one language in Sun's Java 2 Runtime Environments?

The short answer is yes. The long answer needs to look at which languages you want to display at the same time, and how your application selects fonts.

  • It is quite common for a group of languages to share a small common character set - for example, the Western European languages can be written in the ISO 8859-1 character set. If you only need to display languages within such a group, you usually don't need to do anything - it will just work.
  • If the languages you need to display are all supported by the Lucida font family, and your application only needs to run on Java 2 runtime environments that contain this font family, you can simply use fonts from that family.
  • If you need to support languages using separate character ranges, and your application selects fonts using logical font names, you need to create a font.properties file that supports all the languages. See the web page, The font.properties Files, for details.
  • If you need to support languages using separate character ranges, and your application selects fonts using physical names, you need to select the fonts using information about the range of characters that they support.

Can Sun's Java 2 Runtime Environment render text in Thai, Lao, Burmese, or any of the Indic scripts?

Among the South and South-East Asian scripts, version 1.4.2 of Sun's Java 2 Runtime Environments supports Thai and Devanagari. For a complete list of all supported writing systems, see the Supported Locales document. Support for other writing systems may be added in future releases.

Component Orientation

Which user interface components implement component orientation in Sun's Java 2 Runtime Environments?

See the Supported Locales document.

Miscellaneous

Do Sun's Java 2 Runtime Environments support the Euro currency?

Yes, Sun's Java 2 Runtime Environments let you type the Euro character, render it, convert it from and to numerous character encodings, and use it when formatting numeric values as currency. For text input and rendering, you need the appropriate support in the host operating system - see the documentation for Windows and Solaris. For formatting with a currency symbol, Sun's Java 2 Runtime Environments v. 1.4.2 uses the Euro as the default currency for the member countries of the European Monetary Union.

Copyright © 2003 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-intl@java.sun.com

Sun
Java Software


Supported Fonts

The set of supported fonts varies between different implementations of the Java 2 platform. This page documents font support in Sun's Java 2 Software Development Kit, Standard Edition, v. 1.4 (J2SDK), and Java 2 Runtime Environment, Standard Edition, v. 1.4 (J2RE). 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 2 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 2 Runtime Environments look in two locations: the lib/fonts directory within the J2RE 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 J2RE, 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 2 Runtime Environments use font.properties files to define the mapping.

Adventurous users can modify the font.properties files or create new ones. For example, users may want to add additional physical fonts to a given mapping in order to extend the set of characters supported by a logical font.

The Lucida Fonts

Sun's Java 2 Software Development Kit and Java 2 Runtime Environments bundles several physical fonts of the "Lucida" design family. These fonts are also licensed for use in other implementations of the Java 2 platform. These fonts are physical fonts, but since they come with the Java 2 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 2 implementations. For example, the default download bundle of Sun's Java 2 Runtime Environment for Windows only contains the Lucida Sans plain font (but note that application developers can include all Lucida fonts with a J2RE that they redistribute with an application).

The following table shows which Unicode 3.0 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 2 Runtime Environments, the Lucida fonts do not support Chinese (Simplified), Chinese (Traditional), Japanese, and Korean.

The fonts are installed in the Java 2 Runtime Environment's lib/fonts directory as the following files (not all of them may be present):

LucidaSansDemiBold.ttf
LucidaSansDemiOblique.ttf
LucidaSansOblique.ttf
LucidaSansRegular.ttf
LucidaTypewriterBold.ttf
LucidaTypewriterBoldOblique.ttf
LucidaTypewriterOblique.ttf
LucidaTypewriterRegular.ttf
LucidaBrightDemiBold.ttf
LucidaBrightDemiItalic.ttf
LucidaBrightItalic.ttf
LucidaBrightRegular.ttf

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-intl@java.sun.com

Sun
Java Software


The font.properties Files

The Java 2 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 2 Runtime Environments use font.properties files to map logical font names to physical fonts. There are several files to support different mappings depending on host operating system version and locale. The files are located in the lib directory within the J2RE installation. Users can edit or create their own font.properties files to adjust the mappings to their particular system setup. Note however that this is a modification of the J2RE, and Sun does not support modified J2REs.

Note that font.properties files are implementation dependent. Not all implementations of the Java 2 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 1.4.2 of Sun's Java 2 Runtime Environments.

  1. Loading font.properties Files
  2. Names Used in font.properties Files
  3. Properties for All Platforms
  4. Properties for Windows
  5. Properties for Solaris and Linux

Loading font.properties Files

The font.properties files are properties files as specified by the Properties class and are loaded through that class. To find the appropriate file, the following information is used:

  • JavaHome - the J2RE's directory, as given by the "java.home" system property.
  • Language - the language of the initial default locale.
  • Country - the country of the initial default locale.
  • Encoding - the canonical name of the default encoding.
  • OS - a string identifying an operating system variant:
    • For Windows, "NT", "98", "2000", "Me", "XP".
    • For Solaris, empty.
    • For Linux, "Redhat", "Turbo", "SuSE".
  • Version - a string identifying the operating system version.

The runtime uses the first of the following files it finds:

    JavaHome/lib/font.properties.Language_Country_Encoding.OSVersion
    JavaHome/lib/font.properties.Language_Country_Encoding.OS
    JavaHome/lib/font.properties.Language_Country_Encoding.Version
    JavaHome/lib/font.properties.Language_Country_Encoding
    JavaHome/lib/font.properties.Language_Country.OSVersion
    JavaHome/lib/font.properties.Language_Country.OS
    JavaHome/lib/font.properties.Language_Country.Version
    JavaHome/lib/font.properties.Language_Country
    JavaHome/lib/font.properties.Language_Encoding.OSVersion
    JavaHome/lib/font.properties.Language_Encoding.OS
    JavaHome/lib/font.properties.Language_Encoding.Version
    JavaHome/lib/font.properties.Language_Encoding
    JavaHome/lib/font.properties.Language.OSVersion
    JavaHome/lib/font.properties.Language.OS
    JavaHome/lib/font.properties.Language.Version
    JavaHome/lib/font.properties.Language
    JavaHome/lib/font.properties.Encoding.OSVersion
    JavaHome/lib/font.properties.Encoding.OS
    JavaHome/lib/font.properties.Encoding.Version
    JavaHome/lib/font.properties.Encoding
    JavaHome/lib/font.properties.OSVersion
    JavaHome/lib/font.properties.OS
    JavaHome/lib/font.properties.Version
    JavaHome/lib/font.properties

Names Used in font.properties Files

Throughout the font.properties files, a number of different names are used:

  • LogicalFontName - one of the five logical font names: serif, sansserif, monospaced, dialog, and dialoginput. In font.properties files, these names are always in lowercase.

    Some existing font.properties files also use other names as logical font names, such as helvetica or zapfdingbats. This usage is deprecated, and support for it will be removed in a future release.

  • 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.
  • ComponentIndex - an integer identifying a component font entry within the set of entries for the same logical font and style. If there are n entries for a logical font and style, their indices must be 0 to n-1.
  • WindowsCharsetName - one of the following Windows charset names: ANSI_CHARSET, DEFAULT_CHARSET, SYMBOL_CHARSET, SHIFTJIS_CHARSET, GB2312_CHARSET, HANGEUL_CHARSET, CHINESEBIG5_CHARSET, OEM_CHARSET, JOHAB_CHARSET, HEBREW_CHARSET, ARABIC_CHARSET, GREEK_CHARSET, TURKISH_CHARSET, VIETNAMESE_CHARSET, THAI_CHARSET, EASTEUROPE_CHARSET, RUSSIAN_CHARSET, MAC_CHARSET, BALTIC_CHARSET.

Properties for All Platforms

Component Font Mappings

Component font mapping properties describe which physical fonts to use to render characters with a given logical font in a given style. Typically there are several component font entries for each combination of logical font and style so as to cover a wide range of Unicode characters. The entries are identified by component indices. When rendering a character, the runtime checks the component fonts in the sequence defined by the component indices and uses the first one that can render the character and is not excluded.

The keys have the form:

ComponentFontMappingKey:
    LogicalFontName.StyleName.ComponentIndex
    LogicalFontName.ComponentIndex

If the StyleName is omitted, it's assumed to be plain. Within one logical font, the style name plain must either be present for all entries or omitted for all entries. The ComponentIndex identifies a component font entry within the set of entries for the same logical font and style. If there are n entries for a logical font and style, their indices must be 0 to n-1. Component indices must be used consistently between different styles for the same logical font, because some other properties only refer to the logical font name and the component index.

The form of the values depends on the platform. For Solaris and Linux, the values are platform font names. For Windows, the values have the form:

    PlatformFontName , WindowsCharsetName

The Windows charset name identifies the primary character set that this font is supposed to cover. The Java 2 runtime environment uses this information to select the component font to use in peered AWT text components, and Windows may use it to substitute a different font if the specified one cannot be found.

Component Font Character Encodings

Component font character encoding properties indicate which character encoding AWT should use when accessing the corresponding component fonts. These properties are only needed if the component fonts cannot be accessed using Unicode - newer TrueType fonts can usually be accessed using Unicode and don't need this property.

The keys have the form:

    fontcharset.LogicalFontName.ComponentIndex

The values are fully qualified class names of character converters. In this release, character converters are accessed using the old sun.io interfaces, so only the character encodings provided by the Java 2 Runtime Environment can be used. The class names for the publicly supported character encodings are of the form:

    sun.io.CharToByteCanonicalName

In a future release, character converters will be accessed through the new java.nio.charset API, which will enable the use of third-party character converters.

Exclusion Ranges

The exclusion range properties specify Unicode character ranges which should be excluded from being rendered with a given component font. 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.

The keys have the form:

    exclusion.LogicalFontName.ComponentIndex

The values have the form:

ExclusionRangeValue:
    Range
    Range , ExclusionRangeValue

Range:
    Char - Char

Char:
    HexDigit HexDigit HexDigit HexDigit

A Char is a Unicode character represented as a hexadecimal value.

Font File Names

Font file name properties provide the names of the files containing the physical fonts used in the font.properties file. Providing a complete set of file names reduces startup time, since the runtime system doesn't need to open all available font files to find the fonts.

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 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.

Font Name Aliases

Font name aliases are deprecated, and support for them will be removed in a future release.

The keys have the form:

    alias.LogicalFontName

The values have the form:

    LogicalFontName

Missing Glyph Character

Missing glyph character definitions are deprecated, and support for them will be removed in a future release.

The keys have the form:

    default.char

The values have the form:

    Char

Properties for Windows

Text Input Character Set

Text input character set definitions are deprecated, and support for them will be removed in a future release.

The keys have the form:

    textinputcharset

The values have the form:

    WindowsCharsetName

Properties for Solaris and Linux

XFontSet Information

X font set definitions are deprecated, and support for them will be removed in a future release.

The keys have the forms:

    fontset.LogicalFontName.StyleName
    fontset.default

The values have the form:

FontSetValue:
    PlatformFontName
    PlatformFontName , FontSetValue

Copyright © 2003 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-intl@java.sun.com

Sun
Java Software


Internationalization

Documentation Contents

Internationalization is the process of designing an application so that it can be adapted to various languages and regions without engineering changes. Sometimes the term internationalization is abbreviated as i18n, because there are 18 letters between the first "i" and the last "n."

An internationalized program has the following characteristics:

  • With the addition of localization data, the same executable can run worldwide.
  • Textual elements, such as status messages and the GUI component labels, are not hardcoded in the program. Instead they are stored outside the source code and retrieved dynamically.
  • Support for new languages does not require recompilation.
  • Culturally-dependent data, such as dates and currencies, appear in formats that conform to the end user's region and language.
  • It can be localized quickly.

Acknowledgment: Much of the design and implementation of the internationalization API is by IBM's Center for Java Technology-- Silicon Valley. Java Software of Sun Microsystems is grateful for their work.

General Information

  • Internationalization Overview
  • Internationalization Trail of the Java Tutorial
  • Internationalization Articles
  • Frequently Asked Questions
  • Supported Locales
  • Supported Encodings

Fonts

  • Fonts and Text Layout section of the Java 2D API Guide
  • Supported Fonts
  • The font.properties Files

Input Methods

  • An overview of Input Methods
  • Input Method Framework

Demos

The demos will run in the appletviewer tool or in a browser that supports the feature set of version 1.1 of the Java platform or the Java 2 Platform.

  • Collation
  • Date and time formatting
  • Message formatting
  • Number formatting
  • Text boundaries

Tools

  • native2ascii - converts native-encoded characters to and from Unicode
    • Solaris version
    • Windows version

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-intl@java.sun.com

Sun
Java Software


Contents

Java 2 SDK Internationalization Overview

Introduction

Revision Date: 2 December 1999

The global Internet demands global software- that is, software that can be developed independently of the countries or languages of its users, and then localized for multiple countries or regions. The Java 2 Platform provides a rich set of APIs for developing global applications. These internationalization APIs are based on the Unicode 2.1 character encoding and include the ability to adapt text, numbers, dates, currency, and user-defined objects to any country's conventions.

This document summarizes the internationalization APIs and features of the Java 2 Platform. For coding examples and step-by-step instructions, see the Java Tutorial. The detailed APIs are found at The Java Platform API Specification.

For additional information, see the JDK Internationalization home page.

Locales

On the Java platform, a locale is simply an identifier for a particular combination of language and region. It is not a collection of locale-specific attributes. Instead, each locale-sensitive class maintains its own locale-specific information. With this design, there is no difference in how user and system objects maintain their locale-specific resources. Both use the standard localization mechanism.

Java programs are not assigned a single global locale. All locale-sensitive operations may be explicitly given a locale as an argument. This greatly simplifies multilingual programs. While a global locale is not enforced, a default locale is available for programs that do not wish to manage locales explicitly. A default locale also makes it possible to affect the behavior of the entire presentation with a single choice.

Java locales act as requests for certain behavior from another object. For example, a French Canadian locale passed to a Calendar object asks that the Calendar behave correctly for the customs of Quebec. It is up to the object accepting the locale to do the right thing. If the object has not been localized for a particular locale, it will try to find a "close" match with a locale for which it has been localized. Thus if a Calendar object was not localized for French Canada, but was localized for the French language in general, it would use the French localization instead.

Locale Class

A Locale object represents a specific geographical, political, or cultural region. An operation that requires a locale to perform its task is called locale-sensitive and uses the Locale object to tailor information for the user. For example, displaying a number is a locale-sensitive operation- the number should be formatted according to the customs and conventions of the user's native country, region, or culture.

Supported Locales

On the Java platform, there does not have to be a single set of supported locales, since each class maintains its own localizations. Nevertheless, there is a consistent set of localizations supported by the classes of the Java 2 Platform. Other implementations of the Java platform may support different locales. Those supported by the JDK software are summarized in the web page Supported Locales. Subsequent releases of the Java 2 SDK may include additional locales.

Localized Resources

All locale-sensitive classes must be able to access resources customized for the locales they support. To aid in the process of localization, it helps to have these resources grouped together by locale and separated from the locale-neutral parts of the program.

ResourceBundle Class

The class ResourceBundle is an abstract base class representing containers of resources. Programmers create subclasses of ResourceBundle that contain resources for a particular locale. New resources can be added to an instance of ResourceBundle, or new instances of ResourceBundle can be added to a system without affecting the code that uses them. Packaging resources as classes allows developers to take advantage of Java's class loading mechanism to find resources.

Resource bundles contain locale-specific objects. When a program needs a locale-specific resource, a String object for example, the program can load it from the resource bundle that is appropriate for the current user's locale. In this way, the programmer can write code that is largely independent of the user's locale isolating most, if not all, of the locale-specific information in resource bundles.

This allows Java programmers to write code that can:

  • be easily localized, or translated, into different languages

  • handle multiple locales at once

  • be easily modified later to support even more locales

ListResourceBundle Class

ListResourceBundle is an abstract subclass of ResourceBundle that manages resources for a locale in a convenient and easy to use list.

PropertyResourceBundle Class

PropertyResourceBundle is a concrete subclass of ResourceBundle that manages resources for a locale using a set of static strings from a property file.

Calendar and Time Zone Support

Version 1.0 of the JDK software introduced the java.util.Date class for the representation of dates and times. The java.util.Date class allowed for the interpretation of dates as year, month, day, hour, minute, and second values, and it formatted and parsed date strings. Unfortunately, the API for these functions was not amenable to internationalization. Only the "representation" part of this class is retained in version 1.1 of the JDKsoftware.

As of release 1.1 of JDK software, the Date class should only be used as a wrapper for a date or time. That is, Date objects represent a specific instant in time with millisecond precision. Instead, programmers should use the Calendar class to convert between date and time fields, and the DateFormat class to format and parse date strings. The corresponding methods in version 1.0 of the JDK software of the Date class have been deprecated.

Calendar Class

The class Calendar is an abstract base class which can convert between a point in time (represented as milliseconds from 00:00:00 GMT, Jan 1, 1970) and a set of integers representing the year, month, week and so on. GregorianCalendar is a concrete subclass of Calendar that does this according to the rules of the Gregorian calendar.

Calendar and its subclasses are useful for doing various manipulations with time values. Arithmetic can be performed on a Calendar object's fields and the resulting date determined. A Calendar object can produce all the time field values needed to implement the date-time formatting for a particular language and calendar style

TimeZone Class

The abstract class TimeZone encapsulates a time zone offset from UTC (Universal Coordinated Time) and a possible daylight-savings time offset. The class SimpleTimeZone is a concrete subclass that encapsulates some simple rules about daylight-savings time. These rules do not take into account historical changes in the laws affecting daylight-savings time. The Calendar class and its subclasses use the TimeZone and SimpleTimeZone classes to convert between local time and UTC, which is the internal representation used by Date objects. Most programs will not have to deal with TimeZone objects directly.

Formatting

It is in formatting data for output that many cultural conventions are applied. Numbers, dates, times, and messages may all require formatting before they can be displayed. The Java platform provides a set of flexible formatting classes that can handle both the standard locale formats and programmer defined custom formats. These formatting classes are also able to parse formatted strings back into their constituent objects.

Format Class

The class Format is an abstract base class for formatting locale-sensitive information such as dates, times, messages, and numbers. Three main subclasses are provided: DateFormat, NumberFormat, and MessageFormat. These three also provide subclasses of their own.

DateFormat Class

Dates and times are stored internally in a locale-independent way, but should be formatted so that they can be displayed in a locale-sensitive manner. For example, the same date might be formatted as:

  • November 3, 1997 (English)

  • 3 novembre 1997 (French)

The class DateFormat is an abstract base class for formatting and parsing date and time values in a locale-independent manner. It has a number of static factory methods for getting standard time formats for a given locale.

The DateFormat object uses Calendar and TimeZone objects in order to interpret time values. By default, a DateFormat object for a given locale will use the appropriate Calendar object for that locale and the system's default TimeZone object. The programmer can override these choices if desired.

SimpleDateFormat Class

The class SimpleDateFormat is a concrete class for formatting and parsing dates and times in a locale-sensitive manner. It allows for formatting (milliseconds to text), parsing (text to milliseconds), and normalization.

DateFormatSymbols Class

The class DateFormatSymbols is used to encapsulate localizable date-time formatting data, such as the names of the months, the names of the days of the week, time of day, and the time zone data. The DateFormat and SimpleDateFormat classes both use the DateFormatSymbols class to encapsulate this information.

Usually, programmers will not use the DateFormatSymbols directly. Rather, they will implement formatting with the DateFormat class's factory methods.

NumberFormat Class

The class NumberFormat is an abstract base class for formatting and parsing numeric data. It contains a number of static factory methods for getting different kinds of locale-specific number formats.

The NumberFormat class helps programmers to format and parse numbers for any locale. Code using this class can be completely independent of the locale conventions for decimal points, thousands-separators, the particular decimal digits used, or whether the number format is even decimal. The application can also display a number as a normal decimal number, currency, or percentage:

  • 1234.5 (decimal number)

  • $1,234.50 (U.S. currency)

  • Fr1.234,5 (French currency)

  • 123450% (percent)

DecimalFormat Class

Numbers are stored internally in a locale-independent way, but should be formatted so that they can be displayed in a locale-sensitive manner. For example, when using "#,###.00" as a pattern, the same number might be formatted as:

  • 1.234,56 (German)

  • 1,234.56 (English)

The class DecimalFormat, which is a concrete subclass of the NumberFormat class, can format decimal numbers. Programmers generally will not instantiate this class directly but will use the factory methods provided.

The DecimalFormat class has the ability to take a pattern string to specify how a number should be formatted. The pattern specifies attributes such as the precision of the number, whether leading zeros should be printed, and what currency symbols are used. The pattern string can be altered if a program needs to create a custom format.

DecimalFormatSymbols Class

The class DecimalFormatSymbols represents the set of symbols (such as the decimal separator, the grouping separator, and so on) needed by DecimalFormat to format numbers. DecimalFormat creates for itself an instance of DecimalFormatSymbols from its locale data. A programmer needing to change any of these symbols can get the DecimalFormatSymbols object from the DecimalFormat object and then modify it.

ChoiceFormat Class

The class ChoiceFormat is a concrete subclass of the NumberFormat class. The ChoiceFormat class allows the programmer to attach a format to a range of numbers. It is generally used in a MessageFormat object for handling plurals. See the "MessageFormat Class" section that follows for more information.

MessageFormat Class

Programs often need to build messages from sequences of strings, numbers and other data. For example, the text of a message displaying the number of files on a disk drive will vary:

  • The disk C contains 100 files.

  • The disk D contains 1 file.

  • The disk F contains 0 files.

If a message built from sequences of strings and numbers is hard-coded, it cannot be translated into other languages. For example, note the different positions of the parameters "3" and "G" in the following translations:

  • The disk G contains 3 files. (English)

  • Il y a 3 fichiers sur le disque G. (French)

The class MessageFormat provides a means to produce concatenated messages in language-neutral way. The MessageFormat object takes a set of objects, formats them, and then inserts the formatted strings into the pattern at the appropriate places.

ParsePosition Class

The class ParsePosition is used by the Format class and its subclasses to keep track of the current position during parsing. The parseObject() method in the Format class requires a ParsePosition object as an argument.

FieldPosition Class

The FieldPosition class is used by the Format class and its subclasses to identify fields in formatted output. One version of the format() method in the Format class requires a FieldPosition object as an argument.

Locale-Sensitive String Operations

Programs frequently need to manipulate strings. Common operations on strings include searching and sorting. Some tasks, such as collating strings or finding various boundaries in text, are surprisingly difficult to get right and are even more difficult when multiple languages must be considered. The Java 2 Platform provides classes for handling many of these common string manipulations in a locale-sensitive manner.

Collator Class

The Collator class performs locale-sensitive string comparison. Programmers use this class to build searching and alphabetical sorting routines for natural language text. Collator is an abstract base class. Its subclasses implement specific collation strategies. One subclass, RuleBasedCollator, is currently provided with the Java 2 Platform and is applicable to a wide set of languages. Other subclasses may be created to handle more specialized needs.

RuleBasedCollator Class

The RuleBasedCollator class, which is a concrete subclass of the Collator class, provides a simple, data-driven, table collator. Using RuleBasedCollator, a programmer can create a customized table-based collator. For example, a programmer can build a collator that will ignore (or notice) uppercase letters, accents, and Unicode combining characters.

CollationElementIterator Class

The CollationElementIterator class is used as an iterator to walk through each character of an international string. Programmers use the iterator to return the ordering priority of the positioned character. The ordering priority of a character, or key, defines how a character is collated in the given Collator object. The CollationElementIterator class is used by the compare() method of the RuleBasedCollator class.

CollationKey Class

A CollationKey object represents a string under the rules of a specific Collator object. Comparing two CollationKey objects returns the relative order of the strings they represent. Using CollationKey objects to compare strings is generally faster than using the Collator.compare() method. Thus, when the strings must be compared multiple times, for example when sorting a list of strings, it is more efficient to use CollationKey objects.

BreakIterator Class

The BreakIterator class indirectly implements methods for finding the position of the following types of boundaries in a string of text:

  • potential line break

  • sentence

  • word

  • character

The conventions on where to break lines, sentences, words, and characters vary from one language to another. Since the BreakIterator class is locale-sensitive, it can be used by programs that perform text operations. For example, consider a a word processing program that can highlight a character, cut a word, move the cursor to the next sentence, or word-wrap at a line ending. This word processing program would use break iterators to determine the logical boundaries in text, enabling it to perform text operations in a locale-sensitive manner.

StringCharacterIterator Class

The StringCharacterIterator class provides the ability to iterate over a string of Unicode characters in a bidirectional manner. This class uses a cursor to move within a range of text, and can return individual characters or their index values. The StringCharacterIterator class implements the character iterator functionality of the CharacterIterator interface.

CharacterIterator Interface

The CharacterIterator interface defines a protocol for bidirectional iteration over Unicode characters. Classes should implement this interface if they want to move about within a range of text and return individual Unicode characters or their index values. CharacterIterator is for searching is useful when performing character searches.

Character Set Conversion

The Java platform uses Unicode as its native character encoding; however, many Java programs still need to handle text data in other encodings. Java therefore provides a set of classes that convert many standard character encodings to and from Unicode. Java programs that need to deal with non-Unicode text data will typically convert that data into Unicode, process the data as Unicode, then convert the result back to the external character encoding. The InputStreamReader and OutputStreamWriter classes provide methods that can convert between other character encodings and Unicode.

Supported Encodings

The InputStreamReader, OutputStreamWriter, and String classes can convert between Unicode and the following set of character encodings listed in the web page Supported Encodings .

AWT Attributes

To aid in the internationalization of a program's GUI, the Java 2 Platform provides two these attributes for the Component class: Name and Locale.

Name Attribute

The Name attribute is a String object which serves as a non-localizable identifier for a Component object. New constructors for the Component class and its subclasses allow the Name attribute to be set. If these constructors are not used, Component objects are assigned a default Name. The method Component.getName() can be used to examine a Component object's Name attribute.

The Name attribute is particularly useful in writing Action handling routines in which a reference to the target is not known ahead of time. Such Action handlers are often generated by GUI builders. Previously, these routines tried to identify the target Component by looking at its label string. This approach failed when the label strings are localized. As of release 1.1 of the JDK software, programmers should use the Component.getName() method instead.

Locale Attribute

The Component class now contains a Locale attribute. This attribute is accessed by the methods getLocale() and setLocale()methods. If a Component object's Locale is not explicitly set, its value defaults to the Locale of the Component object's parent. If no Component in the hierarchy has an explicit Locale, the default is the value of Locale.getDefault().

The Locale attribute of Component allows the GUI (or portions of the GUI) to maintain its own default locale. This would be useful, for example, in an applet that used the Japanese locale even when the rest of the browser was using the USA locale.

Stream I/O

The Java 2 Platform provides features in the java.io package to improve the handling of character data: the new Reader and Writer classes, and an enhancement to the PrintStream class.

Reader and Writer Classes

The Reader and Writer class hierarchies provide the ability to perform I/O operations on character streams. These hierarchies parallel the InputStream and OutputStream class hierarchies, but operate on streams of characters rather than streams of bytes. Character streams make it easy to write programs that are not dependent upon a specific character encoding, and are therefore easier to internationalize. The Reader and Writer classes also have the ability to convert between Unicode and other character encodings. Please refer to the Character Streams document for more information about the Reader and Writer class hierarchies.

PrintStream Class

The PrintStream class produces output using the system's default character encoding and line terminator. This change allows methods such as System.out.println() to act more reasonably with non-ASCII data.

Character Classification

The Java platform stores character data in Unicode- an international character set standard. The Unicode Standard uses a 16-bit encoding to support all of the major scripts of the world, as well as common technical symbols. Most Java code is written in ASCII, a 7-bit standard, or ISO-Latin-1, an 8-bit standard, but is translated into Unicode before processing. Therefore, the Java character set is always represented in Unicode.

Version 1.0 of the JDK software introduced the Character class as an object wrapper to the char primitive type. The Character class also contained some static methods such as isLowerCase() and isDigit() for determining the properties of a character. This set of methods has been extended in version 1.1 of the JDK software to allow access to all the Unicode 2.1 defined properties for a character.

Input Methods

Input methods are software components that let the user enter text in ways other than simple typing on a keyboard. They are commonly used to enter Japanese, Chinese, or Korean - languages using thousands of different characters - on keyboards with far fewer keys. However, the Java 2 platform also supports input methods for other languages and the use of entirely different input mechanisms, such as handwriting or speech recognition.

The Java 2 platform enables the use of native input methods provided by the host operating system, such as Windows or Solaris, as well as the implementation and use of input methods written in the Java programming language.

The term input methods does not refer to class methods of the Java programming language.

Input Method Support in Swing

The Swing text components provide an integrated user interface for text input using input methods. Depending on the locale, one of two input styles is used. With on-the-spot (inline) input, the style used for most locales, the input methods insert the text directly into the text component while the text is being composed. With below-the-spot input, the style used for Chinese locales, a separate composition window is used, which is positioned automatically to be near the point where the text is to be inserted after being committed.

An application using Swing text components does not have to coordinate the interaction between the text components and input methods. However, it should call InputContext.endComposition when all text must be committed, such as when a document is saved or printed.

Input Method Framework

The input method framework enables the collaboration between text editing components and input methods in entering text. Programmers who develop text editing components or input methods use this framework. Other application developers generally make only minimal use of it. For example, they should call InputContext.endComposition when all text must be committed, such as when a document is saved or printed.

The Input Method Framework web page contains links to the specifications and API documentation.

Contents
java-intl@java.sun.com
Copyright © 1996-2000 Sun Microsystems, Inc. All rights reserved.


Contents | Prev | Next

Introduction
Locales
Locale Class
Supported Locales

Localized Resources
ResourceBundle Class
ListResourceBundle Class
PropertyResourceBundle Class

Calendar and Time Zone Support
Calendar Class
TimeZone Class

Formatting
Format Class
DateFormat Class
SimpleDateFormat Class
DateFormatSymbols Class
NumberFormat Class
DecimalFormat Class
DecimalFormatSymbols Class
ChoiceFormat Class
MessageFormat Class
ParsePosition Class
FieldPosition Class

Locale-Sensitive String Operations
Collator Class
RuleBasedCollator Class
CollationElementIterator Class
CollationKey Class
BreakIterator Class
StringCharacterIterator Class
CharacterIterator Interface

Character Set Conversion
Supported Encodings

AWT Attributes
Name Attribute
Locale Attribute

Stream I/O
Reader and Writer Classes
PrintStream Class

Character Classification
Input Methods
Input Method Support in Swing
Input Method Framework

Contents | Prev | Next
java-intl@java.sun.com
Copyright © 1996-1999 Sun Microsystems, Inc. All rights reserved.


Supported Locales

The set of supported locales varies between different implementations of the Java 2 platform as well as between different areas of functionality.

This page documents locale support in Sun's Java 2 Software Development Kit, Standard Edition, v. 1.4.2 (J2SDK), and Java 2 Runtime Environment, Standard Edition, v. 1.4.2 (J2RE) in the following areas:

  1. Enabled Locales for java.util and java.text Functionality
  2. Enabled Writing Systems for Java Foundation Classes
    1. Overview
    2. Text Input
    3. Text Rendering
    4. Component Orientation
    5. Drag and Drop
  3. User Interface Translation

Sun's Java 2 Runtime Environment, Standard Edition, v. 1.4.2 for Windows may be installed as a complete international version or as a European languages version. The J2RE installer by default 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 J2RE for Solaris and Linux and the J2SDK for any platform are always installed as complete international versions.

1. Enabled Locales for java.util and java.text Functionality

The support for locale-sensitive behavior in the java.util and java.text packages is almost entirely platform independent, so all locales are supported in the same way and simultaneously, independent of the host operating system and its localization. The only platform dependent functionality is the setting of the initial default locale and the initial default time zone based on the host operating system's locale and time zone.

Sun's Java 2 Software Development Kit, Standard Edition, v. 1.4.2 and the international versions of the Java 2 Runtime Environment, Standard Edition, v. 1.4.2 support all locales shown below. The European languages version of the Java 2 Runtime Environment, Standard Edition, v. 1.4.2 supports all locales for the following languages: Albanian, Belorussian, Bulgarian, Catalan, Croatian, Czech, Danish, Dutch, English, Estonian, Finnish, French, German, Greek, Hungarian, Icelandic, Italian, Latvian, Lithuanian, Macedonian, Norwegian, Polish, Portuguese, Romanian, Russian, Serbian, Serbo-Croatian, Slovak, Slovenian, Spanish, Swedish, Turkish, Ukrainian.

Fully Supported Locales

Language | Country | Locale ID
Arabic | Saudi Arabia | ar_SA
Chinese (Simplified) | China | zh_CN
Chinese (Traditional) | Taiwan | zh_TW
Dutch | Netherlands | nl_NL
English | Australia | en_AU
English | Canada | en_CA
English | United Kingdom | en_GB
English | United States | en_US
French | Canada | fr_CA
French | France | fr_FR
German | Germany | de_DE
Hebrew | Israel | iw_IL
Hindi | India | hi_IN
Italian | Italy | it_IT
Japanese | Japan | ja_JP
Korean | South Korea | ko_KR
Portuguese | Brazil | pt_BR
Spanish | Spain | es_ES
Swedish | Sweden | sv_SE
Thai (Western digits) | Thailand | th_TH
Thai (Thai digits) | Thailand | th_TH_TH

Also Provided, but not Tested

Language | Country | Locale ID
Albanian | Albania | sq_AL
Arabic | Algeria | ar_DZ
Arabic | Bahrain | ar_BH
Arabic | Egypt | ar_EG
Arabic | Iraq | ar_IQ
Arabic | Jordan | ar_JO
Arabic | Kuwait | ar_KW
Arabic | Lebanon | ar_LB
Arabic | Libya | ar_LY
Arabic | Morocco | ar_MA
Arabic | Oman | ar_OM
Arabic | Qatar | ar_QA
Arabic | Sudan | ar_SD
Arabic | Syria | ar_SY
Arabic | Tunisia | ar_TN
Arabic | United Arab Emirates | ar_AE
Arabic | Yemen | ar_YE
Belorussian | Belorussia | be_BY
Bulgarian | Bulgaria | bg_BG
Catalan | Spain | ca_ES
Chinese | Hong Kong | zh_HK
Croatian | Croatia | hr_HR
Czech | Czech Republic | cs_CZ
Danish | Denmark | da_DK
Dutch | Belgium | nl_BE
English | India | en_IN
English | Ireland | en_IE
English | New Zealand | en_NZ
English | South Africa | en_ZA
Estonian | Estonia | et_EE
Finnish | Finland | fi_FI
French | Belgium | fr_BE
French | Luxembourg | fr_LU
French | Switzerland | fr_CH
German | Austria | de_AT
German | Luxembourg | de_LU
German | Switzerland | de_CH
Greek | Greece | el_GR
Hungarian | Hungary | hu_HU
Icelandic | Iceland | is_IS
Italian | Switzerland | it_CH
Latvian | Latvia | lv_LV
Lithuanian | Lithuania | lt_LT
Macedonian | Macedonia | mk_MK
Norwegian (Bokmål) | Norway | no_NO
Norwegian (Nynorsk) | Norway | no_NO_NY
Polish | Poland | pl_PL
Portuguese | Portugal | pt_PT
Romanian | Romania | ro_RO
Russian | Russia | ru_RU
Serbian (Cyrillic) | Yugoslavia | sr_YU
Serbo-Croatian | Yugoslavia | sh_YU
Slovak | Slovakia | sk_SK
Slovenian | Slovenia | sl_SI
Spanish | Argentina | es_AR
Spanish | Bolivia | es_BO
Spanish | Chile | es_CL
Spanish | Colombia | es_CO
Spanish | Costa Rica | es_CR
Spanish | Dominican Republic | es_DO
Spanish | Ecuador | es_EC
Spanish | El Salvador | es_SV
Spanish | Guatemala | es_GT
Spanish | Honduras | es_HN
Spanish | Mexico | es_MX
Spanish | Nicaragua | es_NI
Spanish | Panama | es_PA
Spanish | Paraguay | es_PY
Spanish | Peru | es_PE
Spanish | Puerto Rico | es_PR
Spanish | Uruguay | es_UY
Spanish | Venezuela | es_VE
Turkish | Turkey | tr_TR
Ukrainian | Ukraine | uk_UA

2. Enabled Writing Systems for Java Foundation Classes

2.1 Overview

For the Java Foundation Classes (AWT, Swing, 2D, input method framework, drag and drop), locales can generally be characterized by just the writing system; there are no country or language specific distinctions. Writing system support in the JFC depends to some extent on the host operating system, and full support for simultaneous use of multiple languages is not always possible.

We consider a writing system supported by JFC if all functionality provided by JFC works adequately for this writing system in the following situations:

  • On Windows 98, ME, and NT 4.0, when running on a Windows system localized for a language using that writing system.
  • On Windows 2000 and XP, when running on a Windows system with both the user locale and the system locale set to a language using that writing system. For writing systems that don't have a Windows code page (for example, Devanagari), the system locale should be set to English (United States).
  • On Solaris and Linux, when running on a host operating system with the locale set to one using that writing system and one of the encodings shown for that writing system in the table below.

Sun's Java 2 Software Development Kit, Standard Edition, v. 1.4.2 and the international version of the Java 2 Runtime Environment, Standard Edition, v. 1.4.2 support all writing systems shown below. The European languages version of the Java 2 Runtime Environment, Standard Edition, v. 1.4.2 supports only the Cyrillic, Greek, and Latin writing systems. Peered AWT components are only supported for a subset of the writing systems - see the last column.

Details on various areas of functionality are provided in the sections below.

Fully Supported Writing Systems

Writing System | Languages | Windows Encodings | Solaris Encodings | Linux Encodings | Peered AWT Components
Arabic | Arabic | 1256 | 8859-6 | unsupported | unsupported
Chinese (Simplified) | Chinese | 936, GB18030 | gb2312, UTF-8, GBK, gb18030 | gb2312(3), gb18030(3) (4) | supported
Chinese (Traditional) | Chinese | 950, HKSCS | cns11643, UTF-8, BIG5, BIG5HK | (see below) | supported
Devanagari | Hindi | UTF-8(1) | UTF-8 | unsupported | unsupported
Hebrew | Hebrew | 1255 | 8859-8 | unsupported | unsupported
Japanese | Japanese | 932 | eucJP(2), UTF-8, PCK | eucJP(2) (3) (4) | supported
Korean | Korean | 949 | 5601, UTF-8 | (see below) | supported
Latin - Western European subset | English, French, German, Italian, Spanish, Swedish, etc. | 1252 | 8859-1, 8859-15 | UTF-8 (4), 8859-1(5) | supported
Thai | Thai | 874 | TIS620.2533, UTF-8 | unsupported | unsupported
(1) For Devanagari, the user locale should be set to Hindi and the system locale to English (United States).
(2) eucJP on Solaris supports the JIS character sets X 0201, X 0208, and X 0212; eucJP on Linux only X 0201 and X 0208.
(3) on Turbolinux 7 Workstation.
(4) on Red Hat 8.0.
(5) on RedHat 7.3, SuSE 8.0, Turbolinux 7 Workstation.

Also Provided, but not Tested

Writing System | Languages | Windows Code Page | Solaris Encodings | Linux Encodings | Peered AWT Components
Chinese (Traditional) | Chinese | (see above) | (see above) | BIG5(1) | supported
Cyrillic | Belorussian, Russian etc. | 1251 | 8859-5, KOI8-R, ANSI1251 | unsupported | supported
Greek | Greek | 1253 | 8859-7 | unsupported | supported
Korean | Korean | (see above) | (see above) | 5601(1) | supported
Latin - Baltic subset | Latvian, Lithuanian | 1257 | 8859-4, 8859-13 | unsupported | supported
Latin - Central European subset | Czech, Hungarian, Polish, etc. | 1250 | 8859-2 | unsupported | supported
Latin - Turkic subset | Turkish etc. | 1254 | 8859-9 | unsupported | supported
(1) on Red Hat 8.0.

2.2 Text Input

Support for text input consists of two parts: interpretation of keyboard layouts, and text composition using input methods. For interpretation of keyboard layouts, the Java 2 platform relies entirely on the host operating system. For text composition using input methods, Java 2 platform supports native input methods using the host operating system's input method manager as well as input methods developed in the Java programming language.

Locale support in input methods implemented in the Java programming language depends solely on the set of installed input methods, not on the host operating system and its localization. However, support for the use of input methods implemented in the Java programming language with peered components is implementation dependent - see below.

Support for keyboard layouts and and native input methods varies between platforms.

Windows

On Windows 98, ME, and NT, the J2RE supports use of any keyboard layout or IMM-based input method that can be installed into a particular localized version of the host operating system.

On Windows 2000 and XP, the J2RE supports use of any keyboard layout or IMM-based input method.

Global IME is not supported.

Input methods implemented in the Java programming language are supported in all components on all versions of Windows.

Solaris and Linux

The J2RE supports use of any keyboard layout or input method that can be used with a particular Solaris locale.

Input methods implemented in the Java programming language are supported in lightweight components (such as Swing text components), but not in peered components (such as AWT text components).

2.3 Text Rendering

Applications have two options for selecting fonts:

  • Using the logical font names Serif, SansSerif, Dialog, DialogInput, Monospaced.
  • Using a physical font, either requesting it by name or instantiating it using the Font.createFont method.

Text Rendering in Lightweight Components

When using logical font names, text in at least the writing system of the host locale and the Western European subset of the Latin writing system is supported.

When using physical fonts, we need to distinguish between simple and complex writing systems. Simple writing systems have a one-to-one mapping from characters to glyphs, and glyphs are placed on the baseline continuously from left to right. Complex writing systems may use different glyphs for the same character based on context, may for ligatures, may be written from right to left, and may reorder glyphs during line layout, or may have other rules for placing glyphs (in particular for combining marks).

The 2D text rendering system supports any combination of simple writing systems and the complex writing systems listed in the table above. Within these limitations, the range of supported writing systems is determined by the font. A single TrueType font might provide glyphs covering the entire Unicode character set and a Unicode based character-to-glyph mapping. Given such a font, 2D can support all simple writing systems as well as the complex writing systems shown in the table above. Other complex writing systems are not supported.

Text Rendering in Peered Components

When using logical font names, text in the writing system of the host operating system's locale is supported.

Physical fonts are not supported in peered components.

Text Rendering in Printing

There are three printing APIs:

  • The 2D printing API, using the java.awt.print.PrinterJob.getPrinterJob method.
  • The AWT printing API, using the java.awt.Toolkit.getPrintJob method.
  • The pluggable services printing API, using the javax.print package.

Text rendering using the AWT and 2D printing API works to the same extent as text rendering on the screen. Text rendering using the pluggable services printing API depends on the printing service used; the services provided by the J2RE work to the same extent as text rendering on the screen.

2.4 Component Orientation

The component orientation property is respected only by Swing components and layout managers, not by peered AWT components. It is independent of the host operating system. The following classes support component orientation:

java.awt.BorderLayout
java.awt.FlowLayout
java.awt.GridBagLayout
javax.swing.BorderFactory
javax.swing.BoxLayout
javax.swing.JApplet
javax.swing.JButton
javax.swing.JCheckBox
javax.swing.JCheckBoxMenuItem
javax.swing.JColorChooser
javax.swing.JComboBox
javax.swing.JDesktopPane
javax.swing.JDialog
javax.swing.JEditorPane
javax.swing.JFileChooser

javax.swing.JFrame
javax.swing.JInternalFrame
javax.swing.JLabel
javax.swing.JLayeredPane
javax.swing.JListBox
javax.swing.JMenu
javax.swing.JMenuBar
javax.swing.JMenuItem
javax.swing.JOptionPane
javax.swing.JPanel
javax.swing.JPasswordField
javax.swing.JPopupMenu
javax.swing.JProgressBar
javax.swing.JRadioButton

javax.swing.JRadioButtonMenuItem
javax.swing.JRootPane
javax.swing.JScrollPane
javax.swing.JSlider
javax.swing.JTabbedPane
javax.swing.JTextArea
javax.swing.JTextField
javax.swing.JTextPane
javax.swing.JToggleButton
javax.swing.JToolBar
javax.swing.JToolTip
javax.swing.JTree
javax.swing.ProgressMonitor
javax.swing.border.Border

2.5 Drag and Drop

On Windows 98, and ME, text in the writing system of the host operating system's localization can be transferred between applications.

On Windows NT, 2000, and XP, arbitrary Unicode text can be transferred between applications.

On Solaris and Linux, text in the character encoding of the host operating system's locale can be transferred between applications.

Applications that need to transfer arbitrary Unicode text independent of the host operating system, can do so using serialization: Create a Transferable which supports only one flavor: DataFlavor.stringFlavor. This flavor represents the serialized representation of a String. Make sure that the target supports stringFlavor as well. When the transfer occurs, the AWT will serialize out the String on one end and deserialize on the other. This is much slower than a native platform text transfer, but it will succeed where native transfers may not.

3. User Interface Translation

Java 2 Runtime Environment

The user interface elements provided by the Java 2 Runtime Environment, Standard Edition, v. 1.4.2, include Swing dialogs, messages written by the runtime environment to the standard output and standard error streams, as well as messages produced by the tools provided with the J2RE. These user interface elements are localized into the following languages:

Language | Locale ID
Chinese (Simplified) | zh_CN
Chinese (Traditional) | zh_TW
English | en
French | fr
German | de
Italian | it
Japanese | ja
Korean | ko
Spanish | es
Swedish | sv

Java 2 Software Development Kit

The user interface elements provided by the Java 2 Software Development Kit, Standard Edition, v. 1.4.2, include messages produced by the tools that are only part of the J2SDK in addition to the elements provided by the J2RE. The additional user interface elements are localized into the following languages:

Language | Locale ID
English | en
Japanese | ja

Copyright © 2003 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-intl@java.sun.com

Sun
Java Software


Collation

Please wait while the applet determines what environment to run in...

Your browser is completely ignoring the <APPLET> tag!


Date and Time Formatting Demo

Please wait while the applet determines what environment to run in...

Your browser is completely ignoring the <APPLET> tag!


Message Format

Please wait while the applet determines what environment to run in...

Your browser is completely ignoring the <APPLET> tag!


Number Format

Please wait while the applet determines what environment to run in...

Your browser is completely ignoring the <APPLET> tag!


Text Bound

Please wait while the applet determines what environment to run in...

Your browser is completely ignoring the <APPLET> tag!


I/O in the Java(TM) 2 Platform

Java

I/O in the JavaTM 2 Platform

 Documentation Contents
I/O functionality of the JavaTM 2 Platform provides for system input and output through data streams, serialization and the file system. In v 1.4, a new I/O (NIO) API was introduced that provides new features and improved performance.

Class java.io.File in the Java 2 platform is a true abstract representation of file and directory pathnames. Class File supports temporary files, conversion of abstract pathnames to URL's, comparability, and access to additional file attributes.

Java 2 Platform I/O Features

  • New I/O (NIO) API introduced in v1.4, which caused some changes in the java.io package
  • Features of java.io.File added in the Java 2 Platform v1.2
  • Other changes made to the java.io package in v1.2

Features introduced in JDKTM 1.1

For completeness, a discussion of the JDK 1.1 I/O changes can be found here:

  • Character Streams

Additional I/O reference material

  • java.io Package (API Documentation)
  • java.nio Package (API Documentation)
  • Troubleshooting tips

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software


Character streams (Introduced in JDK(TM) 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 © 1997,1999 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software


Features of java.io.File in the Java(TM) 2 Platform

Java

Features of java.io.File in the JavaTM 2 Platform

 JavaTM 2 SDK Contents
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 © 1999 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software


Minor changes to java.io in the Java 2 Platform v1.2

Java

Minor changes to java.io in the JavaTM 2 Platform v1.2

 JavaTM 2 SDK Contents
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 © 1999 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software


Troubleshooting

 JavaTM 2 SDK Contents
  • A File object represents a file name, not an actual file. Such objects are, moreover, immutable. Thus the code
        File f1 = new File("foo");
    File f2 = new File("bar");
    f1.renameTo(f2);
    will rename the file named "foo" (if it exists) to "bar". It will not change the value of the File object referred to by f1; in particular, the expression f1.getPath() will still evaluate to "foo".

  • The available method of the InputStream class and its subclasses does not necessarily return the maximum number of bytes that can be read without blocking. In particular, code of the form
        int n = in.available();
    byte buf = new byte[n];
    in.read(buf);
    is not guaranteed to read all of the remaining bytes from the given input stream. Similarly, the ready method of Reader and its subclasses may return false even if the stream is ready to be read.

  • The read(byte[]) and read(byte[], int, int) methods of InputStream and its subclasses are not guaranteed to read all available bytes. A loop may be required, for example, in order to read a large file into an array:
        for (int off = 0; off < size;) {
        int r = in.read(buf, off, buf.length - off);
        if (r == -1) break;
        off += r;
    }
    Alternatively, a BufferedInputStream may be used. Similar remarks apply to the read(char[]) and read(char[], int, int) methods of Reader and its subclasses.

  • The PrintStream and PrintWriter classes suppress all I/O errors. To see whether an error has occurred, invoke the checkError method.

  • PrintStream and PrintWriter objects do not always flush their output. To arrange for automatic flushing, use the two-argument constructors of these classes and specify true for the second argument.

Copyright © 1999 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software


JAR Features

Java

JavaTM Archive (JAR) Features

 Documentation Contents
JAR (Java Archive) is a platform-independent file format that aggregates many files into one. Multiple Java applets and their requisite components (.class files, images and sounds) can be bundled in a JAR file and subsequently downloaded to a browser in a single HTTP transaction, greatly improving the download speed. The JAR format also supports compression, which reduces the file size, further improving the download time. In addition, the applet author can digitally sign individual entries in a JAR file to authenticate their origin. It is fully backward-compatible with existing applet code and is fully extensible.

This version of the Java platform extends the utility of the JAR format. Enhancements include added functionality for the command-line JAR tool for creating Jar-file indexes for faster access to Jar-file contents. There are also new standard APIs for a "delete-on-close" mode for opening Jar files.

JAR File Specification and Overview
  • JAR File Specification
  • JAR File Overview
JAR Files and the Extensions Framework
  • The new extensions mechanism in the Java platform uses the JAR file format to package extension classes. Manifest attributes are available to support the extension mechanism and related features such as package sealing and package versioning. See the extensions specification for details.
Enhanced Jar Tool
  • The Jar tool has the new -i option for creating JAR file indexes. See the Jar tool reference pages:
    Jar tool reference page for Solaris
    Jar tool reference page for Windows
Reading and Writing JAR Files: API Specification
  • Package java.util.jar: classes for creating and reading JAR files
  • Class java.net.JarURLConnection: Abstract class for URL connections to JAR files using the jar protocol.

The API of classes java.util.zip and java.util.jar have been enhanced with the addition of the following:
  • java.util.zip.OPEN_READ
  • java.util.zip.OPEN_DELETE
  • java.util.zip.ZipFile(File file, int mode)
  • java.util.jar.JarFile(File file, boolean verify, int mode)
The previous implementation of caching downloaded Jar files created problems for long-running server application and for RMI. Each open JarURLConnection creates a temporary local file that holds Jar-file date, and a JarFile object is created on top of the temporary file. Because the open file handle/descriptor on each temporary file was never closed, the files could quickly take up disk space for long-running server applications. The new API provides a solution for this problem by supporting a new "delete-on-close" mode for opening Zip and Jar files.
Tutorial

On the Java Software website:
  • The Java Archive (JAR) File Format trail in the Java Tutorial.

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software


JAR File Specification

Contents

  • Introduction
  • The META-INF directory
  • Name-Value pairs and Sections
  • JAR Manifest
    • Overview
    • Manifest Specification
    • Main Attributes
    • Per-Entry Attributes
  • Signed JAR file
    • Overview
    • Signature File
      • Signature validation
      • The Magic Attribute
    • Digital Signatures
  • Notes on Manifest and Signature Files
  • JAR Index
    • Overview
    • Index File Specification
    • Backward Compatibility
  • Service Provider
    • Overview
    • Provider Configuration File
    • Example
  • API Details
  • See Also

Introduction

JAR file is a file format based on the popular ZIP file format and is used for aggregating many files into one. A JAR file is essentially a zip file that contains an optional META-INF directory. A JAR file can be created by the command-line jar tool, or by using the java.util.jar API in the Java platform. There is no restriction on the name of a JAR file, it can be any legal file name on a particular platform.

In many cases, JAR files are not just simple archives of java classes files and/or resources. They are used as building blocks for applications and extensions. The META-INF directory, if it exists, is used to store package and extension configuration data, including security, versioning, extension and services.

The META-INF directory

The following files/directories in the META-INF directory are recognized and interpreted by the Java 2 Platform to configure applications, extensions, class loaders and services:
  • MANIFEST.MF
The manifest file that is used to define extension and package related data.
  • INDEX.LIST
This file is generated by the new "-i" option of the jar tool, which contains location information for packages defined in an application or extension. It is part of the JarIndex implementation and used by class loaders to speed up their class loading process.
  • x.SF
The signature file for the JAR file. 'x' stands for the base file name.
  • x.DSA
The signature block file associated with the signature file with the same base file name. This file stores the digital signature of the corresponding signature file.
  • services/
This directory stores all the service provider configuration files.

Name-Value pairs and Sections

Before we go to the details of the contents of the individual configuration files, some format convention needs to be defined. In most cases, information contained within the manifest file and signature files is represented as so-called "name: value" pairs inspired by the RFC822 standard. We also call these pairs headers or attributes.

Groups of name-value pairs are known as a "section". Sections are separated from other sections by empty lines.

Binary data of any form is represented as base64. Continuations are required for binary data which causes line length to exceed 72 bytes. Examples of binary data are digests and signatures.

Implementations shall support header values of up to 65535 bytes.

All the specifications in this document use the same grammar in which terminal symbols are shown in fixed width font and non-terminal symbols are shown in italic type face.

Specification:

section: *header +newline
nonempty-section: +header +newline
newline: CR LF | LF | CR (not followed by LF)
header: name : value
name: alphanum *headerchar
value: SPACE *otherchar newline *continuation
continuation: SPACE *otherchar newline
alphanum: {A-Z} | {a-z} | {0-9}
headerchar: alphanum | - | _
otherchar: any UTF-8 character except NUL, CR and LF

; Also: To prevent mangling of files sent via straight e-mail, no
; header will start with the four letters "From".

Non-terminal symbols defined in the above specification will be referenced in the following specifications.

JAR Manifest

Overview

A JAR file manifest consists of a main section followed by a list of sections for individual JAR file entries, each separated by a newline. Both the main section and individual sections follow the section syntax specified above. They each have their own specific restrictions and rules.

The main section contains security and configuration information about the JAR file itself, as well as the application or extension that this JAR file is a part of. It also defines main attributes that apply to every individual manifest entry. No attribute in this section can have its name equal to "Name". This section is terminated by an empty line.

The individual sections define various attributes for packages or files contained in this JAR file. Not all files in the JAR file need to be listed in the manifest as entries, but all files which are to be signed must be listed. The manifest file itself must not be listed. Each section must start with an attribute with the name as "Name", and the value must be a relative path to the file, or an absolute URL referencing data outside the archive.

If there are multiple individual sections for the same file entry, the attributes in these sections are merged. If a certain attribute have different values in different sections, the last one is recognized.

Attributes which are not understood are ignored. Such attributes may include implementation specific information used by applications.

Manifest Specification:

manifest-file: main-section newline *individual-section
main-section: version-info newline *main-attribute
version-info: Manifest-Version : version-number
version-number : digit+{.digit+}*
main-attribute: (any legitimate main attribute) newline
individual-section: Name : value newline *perentry-attribute
perentry-attribute: (any legitimate perentry attribute) newline
newline : CR LF | LF | CR (not followed by LF)
digit: {0-9}

In the above specification, attributes that can appear in the main section are referred to as main attributes, whereas attributes that can appear in individual sections are referred to as per-entry attributes. Certain attributes can appear both in the main section and the individual sections, in which case the per-entry attribute value overrides the main attribute value for the specified entry. The two types of attributes are defined as follows.

Main Attributes

Main attributes are the attributes that are present in the main section of the manifest. They fall into the following different groups:
  • general main attributes
    • Manifest-Version:
      Defines the manifest file version. The value is a legitimate version number, as described in the above spec.
    • Created-By:

      • Defines the version and the vendor of the java implementation on top of which this manifest file is generated. This attribute is generated by the jar tool.
    • Signature-Version:

      • Defines the signature version of the jar file. The value should be a valid version-number string.
    • Class-Path :

      • The value of this attribute specifies the relative URLs of the extensions or libraries that this application or extension needs. URLs are separated by one or more spaces. The application or extension class loader uses the value of this attribute to construct its internal search path.
  • attribute defined for stand-alone applications
    • This attribute is used by stand-alone applications that are bundled into executable jar files which can be invoked by the java runtime directly by running "java -jar x.jar".
    • Main-Class :

      • The value of this attribute defines the relative path of the main application class which the launcher will load at startup time. The value must not have the .class extension appended to the class name.
  • attributes defined for applets
    • These attributes is used by an applet which is bundled into JAR files to define requirements, version and location information for the extensions which this applet depends on. (see Extension Versioning ).
    • Extension-List:

      • This attribute indicates the extensions that are needed by the applet. Each extension listed in this attribute will have a set of additional attributes that the applet uses to specify which version and vendor of the extension it requires.
    • <extension>-Extension-Name :

      • This attribute is the unique name of the extension. The Java Plug-in will compare the value of this attribute with the Extension-Name attribute in the manifests of installed extensions to determine if the extension is installed.
    • <extension>-Specification-Version

      • This attribute specifies the minimum extension specification version that is required by the applet. The Java Plug-in will compare the value of this attribute with the Specification-Version attribute of the installed extension to determine if the extension is up to date.
    • <extension>-Implementation-Version

      • This attritute specifies the minimum extension implementation version number that is required by the applet. The Java Plug-in will compare the value of this attribute with the Implementation-Version attribute of the installed extension to see if a more recent implementation needs to be downloaded.
    • <extension>-Implementation-Vendor-Id

      • This attribute can be used to identify the vendor of an extension implementation if the applet requires an implementation from a specific vendor. The Java Plug-in will compare the value of this attribute with the Implementation-Vendor-Id attribute of the installed extension.
    • <extension>-Implementation-URL

      • This attribute specifies a URL that can be used to obtain the most recent version of the extension if the required version is not already installed.
  • attribute defined for extension identification
    • This attribute is used by extensions to define their unique identity.
    • Extension-Name:
      • This attribute specifies a name for the extension contained in the Jar file. The name should be a unique identifier such as the name of the main package comprising the extension.
  • attributes defined for extension and package versioning and sealing information
    • These attributes define features of the extension which the JAR file is a part of. The value of these attributes apply to all the packages in the JAR file, but can be overridden by per-entry attributes.
    • Implementation-Title :
      • The value is a string that defines the title of the extension implementation.
    • Implementation-Version :

      • The value is a string that defines the version of the extension implementation.
    • Implementation-Vendor :

      • The value is a string that defines the organization that maintains the extension implementation.
    • Implementation-Vendor-Id :

      • The value is a string id that uniquely defines the organization that maintains the extension implementation.
    • Implementation-URL :

      • This attribute defines the URL from which the extension implementation can be downloaded from.
    • Specification-Title :

      • The value is a string that defines the title of the extension specification.
    • Specification-Version :

      • The value is a string that defines the version of the extension specification.
    • Specification-Vendor :

      • The value is a string that defines the organization that maintains the extension specification.
    • Sealed :

      • This attribute defines whether this JAR file is sealed or not. The value can be either "true" or "false", case is ignored. If it is set to "true", then all the packages in the JAR file are defaulted to be sealed, unless they are defined otherwise individually.

Per-Entry Attributes

Per-entry attributes apply only to the individual JAR file entry to which the manifest entry is associated with. If the same attribute also appeared in the main section, then the value of the per-entry attribute overwrites the main attribute's value. For example, if JAR file a.jar has the following manifest content:
    Manifest-Version: 1.0
    Created-By: 1.2 (Sun Microsystems Inc.)
    Sealed: true

    Name: foo/bar/
    Sealed: false

It means that all the packages archived in a.jar are sealed, except that package foo.bar is not.

The per-entry attributes fall into the following groups:

  • attributes defined for file contents:
    • Content-Type :

      • This attribute can be used to specify the MIME type and subtype of data for a specific file entry in the JAR file. The value should be a string in the form of type/subtype. For example "image/bmp" is an image type with a subtype of bmp (representing bitmap). This would indicate the file entry as an image with the data stored as a bitmap. RFC 1521 and 1522 discuss and define the MIME types definition.
  • attributes defined for package versioning and sealing information:

    • These are the same set of attributes defined above as main attributes that defines the extension package versioning and sealing information. When used as per-entry attributes, these attributes overwrites the main attributes but only apply to the individual file specified by the manifest entry.

  • attribute defined for beans objects:
    • Java-Bean:

      • Defines whether the specific jar file entry is a Java Beans object or not. The value should be either "true" or "false", case is ignored.
  • attributes defined for signing:

    • These attributes are used for signing and verifying purposes. More details here.
    • x-Digest-y:

      • The name of this attribute specifies the name of the digest algorithm used to compute the digest value for the corresponding jar file entry. The value of this attribute stores the actual digest value. The prefix 'x' specifies the algorithm name and the optional suffix 'y' indicates to which language the digest value should be verified against.
    • Magic:

      • This is an optional attribute that can be used by applications to indicate how verifier should compute the digest value contained in the manifest entry. The value of this attribute is a set of comma separated context specific strings. Detailed description is here.

Signed JAR File

Overview

A JAR file can be signed by using the command line jarsigner tool or directly through the java.security API. Every file entry will be signed if the JAR file is signed by jarsigner tool. Subsets of a JAR file can be signed by using the java.security API. A signed JAR file is exactly the same as the original JAR file, except that its manifest is updated and two additional files are added to the META-INF directory, a signature file and a signature block file. When jarsigner is not used, the signing program has to construct both the signature file and the signature block file.

For every file entry that is signed in the signed JAR file, an individual manifest entry is created for it, if it does not exist in the manifest before. Each manifest entry lists one or more digest attribute and an optional Magic attribute.

Signature File

Each signer is represented by a signature file with extension .SF. The major part of the file is similar to the manifest file. It consists of a main section which includes information supplied by the signer but not specific to any particular jar file entry, followed by a list of individual entries whose name must also be present in the manifest file. Each individual entry must contain at least the digest of the corresponding entry in the manifest file.

Paths or URL's appearing in the manifest file but not in the signature file are not used in calculation.

Signature Validation

The signature is first verified when the manifest is first parsed. This verification can be remembered, for efficiency. This only validates the signature directions themselves, not the actual archive files.

To validate a file, a digest value in the signature file is compared against a digest calculated against the corresponding entry in the manifest file. Then, a digest value in the manifest file is compared against a digest calculated against the actual data referenced in the "Name:" attribute, which specifies either a relative file path or URL.

Example manifest file:

    Manifest-Version: 1.0
     Created-By: 1.3 (Sun Microsystems, Inc)

     Name: common/class1.class
     MD5-Digest: (base64 representation of MD5 digest)

     Name: common/class2.class
     MD5-Digest: (base64 representation of MD5 digest)
     SHA-Digest: (base64 representation of SHA digest)

The corresponding signature file would be:
    Signature-Version: 1.0

     Name: common/class1.class
     MD5-Digest: (base64 representation of MD5 digest)

     Name: common/class2.class
     MD5-Digest: (base64 representation of MD5 digest)

The Magic Attribute

Another requirement to validate the signature on a given manifest entry is that the verifier understand the value or values of the Magic key-pair value in that entry's manifest entry.

The Magic attribute is optional but it is required that a parser understand the value of an entry's Magic key if it is verifying that entry's signature.

The value or values of the Magic attribute are a set of comma-separated context-specific strings. The spaces before and after the commas are ignored. Case is ignored. The exact meaning of the magic attributes is application specific. These values indicate how to compute the hash value contained in the manifest entry, and are therefore crucial to the proper verification of the signature. The keywords may be used for dynamic or embedded content, multiple hashes for multilingual documents, etc.

Here are two examples of the potential use of Magic attribute in the manifest file:

Name: http://www.scripts.com/index#script1
        SHA-Digest: (base64 representation of SHA hash)
        Magic: JavaScript, Dynamic

        Name: http://www.tourist.com/guide.html
        SHA-Digest: (base64 representation of SHA hash)
        SHA-Digest-French: (base64 representation of SHA hash)
        SHA-Digest-German: (base64 representation of SHA hash)
        Magic: Multilingual

In the first example, these Magic values may indicate that the result of an http query is the script embedded in the document, as opposed to the document itself, and also that the script is generated dynamically. These two pieces of information indicate how to compute the hash value against which to compare the manifest's digest value, thus comparing a valid signature.

In the second example, the Magic value indicates that the document retrieved may have been content-negotiated for a specific language, and that the digest to verify against is dependent on which language the document retrieved is written in.

Digital Signatures

A digital signature is a signed version of the .SF signature file. These are binary files not intended to be interpreted by humans.

Digital signature files have the same filename as the .SF file but different extension. The extension varies depending on the type of digital signature.

.RSA  (PKCS7 signature, MD5 + RSA)
.DSA  (PKCS7 signature, DSA)
.PGP  (Pretty Good Privacy Signature)

For those formats that do not support external signed data, the file shall consist of a signed copy of the .SF file. Thus some data may be duplicated and a verifier ought to compare the two files.

Formats that support external data either reference the .SF file, or perform calculations on it with implicit reference.

Each .SF file may have multiple digital signatures, but those signatures ought to be generated by the same legal entity.

File name extensions may be 1 to 3 alphanum characters. Extensions unrecognized are ignored.

Notes on Manifest and Signature Files

Following is a list of additional restrictions and rules that apply to manifest and signature files.
  • Before parsing:

    • If the last character of the file is an EOF character (code 26), the EOF is treated as whitespace. Two newlines are appended (one for editors that don't put a newline at the end of the last line, and one so that the grammar doesn't have to special-case the last entry, which may not have a blank line after it).
  • Attributes:

    • In all cases for all sections, attributes which are not understood are ignored.

    Attribute names are case insensitive. Programs which generate manifest and signature files should use the cases shown in this specification however.

    Attribute names cannot be repeated within a section.

  • Versions:

    • Manifest-Version and Signature-Version must be first, and in exactly that case (so that they can be recognized easily as magic strings). Other than that, the order of attributes within a main section is not significant.
  • Ordering:

    • The order of individual manifest entries is not significant.

    The order of individual signature entries is not significant, except that the digests that get signed are in that order.

  • Line length:

    • No line may be longer than 72 bytes (not characters), in its UTF8-encoded form. If a value would make the initial line longer than this, it should be continued on extra lines (each starting with a single SPACE).
  • Errors:

    • If a file cannot be parsed according to this spec, a warning should be output, and none of the signatures should be trusted.
  • Limitations:

    • Because header names cannot be continued, the maximum length of a header name is 70 bytes (there must be a colon and a SPACE after the name).

    NUL, CR, and LF can't be embedded in header values, and NUL, CR, LF and ":" can't be embedded in header names.

    Implementations should support 65535-byte (not character) header values, and 65535 headers per file. They might run out of memory, but there should not be hard-coded limits below these values.

  • Signers:

    • It is technically possible that different entities may use different signing algorithms to share a single signature file. This violates the standard, and the extra signature may be ignored.
  • Algorithms:

    • No digest algorithm or signature algorithm is mandated by this standard. However, at least one of MD5 and SHA digest algorithm must be supported.

JAR Index

Overview

Since 1.3, JarIndex is introduced to optimize the class searching process of class loaders for network applications, especially applets. Originally, an applet class loader uses a simple linear search algorithm to search each element on its internal search path, which is constructed from the "ARCHIVE" tag or the "Class-Path" main attribute. The class loader downloads and opens each element in its search path, until the class or resource is found. If the class loader tries to find a nonexistent resource, then all the jar files within the application or applet will have to be downloaded. For large network applications and applets this could result in slow startup, sluggish response and wasted network bandwidth. The JarIndex mechanism collects the contents of all the jar files defined in an applet and stores the information in an index file in the first jar file on the applet's class path. After the first jar file is downloaded, the applet class loader will use the collected content information for efficient downloading of jar files.

The existing jar tool is enhanced to be able to examine a list of jar files and generate directory information as to which classes and resources reside in which jar file. This directory information is stored in a simple text file named INDEX.LIST in the META-INF directory of the root jar file. When the classloader loads the root jar file, it reads the INDEX.LIST file and uses it to construct a hash table of mappings from file and package names to lists of jar file names. In order to find a class or a resource, the class loader queries the hashtable to find the proper jar file and then downloads it if necessary.

Once the class loader finds a INDEX.LIST file in a particular jar file, it always trusts the information listed in it. If a mapping is found for a particular class, but the class loader fails to find it by following the link, an InvalidJarIndexException is thrown. When this occurs, the application developer should rerun the jar tool on the extension to get the right information into the index file.

To prevent adding too much space overhead to the application and to speed up the construction of the in-memory hash table, the INDEX.LIST file is kept as small as possible. For classes with non-null package names, mappings are recorded at the package level. Normally one package name is mapped to one jar file, but if a particular package spans more than one jar file, then the mapped value of this package will be a list of jar files. For resource files with non-empty directory prefixes, mappings are also recorded at the directory level. Only for classes with null package name, and resource files which reside in the root directory, will the mapping be recorded at the individual file level.

Index File Specification

The INDEX.LIST file contains one or more sections each separated by a single blank line. Each section defines the content of a particular jar file, with a header defining the jar file path name, followed by a list of package or file names, one per line. All the jar file paths are relative to the code base of the root jar file. These path names are resolved in the same way as the current extension mechanism does for bundled extensions.

The UTF-8 encoding is used to support non ASCII characters in file or package names in the index file.

Specification

index file : version-info blankline section*
version-info : JarIndex-Version: version-number
version-number : digit+{.digit+}*
section : body blankline
body : header name*
header : char+.jar newline
name : char+ newline
char : any valid Unicode character except NULL, CR and LF
blankline: newline newline
newline : CR LF | LF | CR (not followed by LF)
digit: {0-9}

The INDEX.LIST file is generated by running jar -i. See the jar man page for more details.

Backward Compatibility

The new class loading scheme is totally backward compatible with applications developed on top of the current extension mechanism. When the class loader loads the first jar file and an INDEX.LIST file is found in the META-INF directory, it would construct the index hash table and use the new loading scheme for the extension. Otherwise, the class loader will simply use the original linear search algorithm.

Service Provider

Overview

Files in the META-INF/services directory are service provider configuration files. A service is a well-known set of interfaces and (usually abstract) classes. A service provider is a specific implementation of a service. The classes in a provider typically implement the interfaces and subclass the classes defined in the service itself. Service providers may be installed in an implementation of the Java platform in the form of extensions, that is, jar files placed into any of the usual extension directories. Providers may also be made available by adding them to the applet or application class path or by some other platform-specific means.

A service is represented by an abstract class. A provider of a given service contains one or more concrete classes that extend this service class with data and code specific to the provider. This provider class will typically not be the entire provider itself but rather a proxy that contains enough information to decide whether the provider is able to satisfy a particular request together with code that can create the actual provider on demand. The details of provider classes tend to be highly service-specific; no single class or interface could possibly unify them, so no such class has been defined. The only requirement enforced here is that provider classes must have a zero-argument constructor so that they may be instantiated during lookup.

Provider-Configuration File

A service provider identifies itself by placing a provider-configuration file in the resource directory META-INF/services. The file's name should consist of the fully-qualified name of the abstract service class. The file should contain a newline-separated list of unique concrete provider-class names. Space and tab characters, as well as blank lines, are ignored. The comment character is '#' (0x23); on each line all characters following the first comment character are ignored. The file must be encoded in UTF-8.

Example

Suppose we have a service class named java.io.spi.CharCodec. It has two abstract methods:

public abstract CharEncoder getEncoder(String encodingName);
  public abstract CharDecoder getDecoder(String encodingName);

Each method returns an appropriate object or null if it cannot translate the given encoding. Typical CharCodec providers will support more than one encoding.

If sun.io.StandardCodec is a provider of the CharCodec service then its jar file would contain the file META-INF/services/java.io.spi.CharCodec. This file would contain the single line:

sun.io.StandardCodec    # Standard codecs for the platform

To locate an encoder for a given encoding name, the internal I/O code would do something like this:

   CharEncoder getEncoder(String encodingName) {
Iterator ps = Service.providers(CharCodec.class);
while (ps.hasNext()) {
CharCodec
cc = (CharCodec)ps.next();
CharEncoder
ce = cc.getEncoder(encodingName);
if
(ce != null)
return ce;
}
return null;
}

The provider-lookup mechanism always executes in the security context of the caller. Trusted system code should typically invoke the methods in this class from within a privileged security context.

API Details

Package java.util.jar

See Also

Package java.security
Package java.util.zip

Copyright © 1999 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software


Jar Guide

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.

Sun logo Copyright © 1996-1999 Sun Microsystems, Inc., 901 San Antonio Road, Palo Alto, CA 94303-4900 USA. All rights reserved.


Blob

8.1 Blob Overview

A Blob object represents the Java programming language mapping of an SQL BLOB (Binary Large Object). An SQL BLOB is a built-in type that stores a Binary Large Object as a column value in a row of a database table. Methods in the interfaces ResultSet, CallableStatement, and PreparedStatement allow a programmer to access the SQL3 type BLOB in the same way that SQL92 built-in types are accessed. In other words, an application using the JDBC 2.0 API uses methods such as getBlob and setBlob for a BLOB value the same way it uses getInt and setInt for an INTEGER value or getString and setString for a CHAR or VARCHAR value.

In a standard implementation, a JDBC driver implements the Blob interface using the SQL type LOCATOR(BLOB) behind the scenes. A LOCATOR(BLOB) designates an SQL BLOB value residing on a database server, and operations on the locator achieve the same results as operations on the BLOB value itself. This means that a client can operate on a Blob instance without ever having to materialize the BLOB data on the client machine, which can improve performance significantly. Because the driver uses LOCATOR(BLOB) behind the scenes, its use is completely transparent to the programmer using a JDBC driver.

The standard behavior for a Blob instance is to remain valid until the transaction in which it was created is either committed or rolled back.

The Blob interface provides methods for getting the length of an SQL BLOB value, for materializing a BLOB value on the client, and for determining the position of a pattern of bytes within a BLOB value.

8.1.1 Creating a Blob Object

The following code fragment illustrates creating a Blob object, where stmt is a Statement object:

ResultSet rs = stmt.executeQuery("SELECT DATA FROM TABLE1");
rs.first();
Blob data = rs.getBlob("DATA");

The variable blob contains a logical pointer to the BLOB value that is stored in the column DATA in the first row of the result set rs. It does not contain the data in the BLOB value, but as far as JDBC methods are concerned, it is operated on as if it did.

8.1.2 Materializing Blob Data

Programmers can invoke methods in the JDBC API on a Blob object as if they were operating on the SQL BLOB it designates. However, if they want to operate on a Blob object as if it were an object in the Java programming language, they must first materialize it on the client. The Blob interface provides two methods for materializing a Blob object: getBinaryStream, which materializes the BLOB value as an input stream, and getBytes, which materializes all or part of the BLOB value as an array of bytes. The following code fragment materializes all of the data in the BLOB value designated by blob as an input stream:

java.io.InputStream in = blob.getBinaryStream();
byte b;
while ((in.read()) > -1) {
    b = in.read();
    System.out.println(b);
}
// prints out all the bytes in the BLOB value that blob designates

The next code fragment also materializes all of the data in the BLOB value designated by blob, but as an array of bytes instead of as an input stream.

long len = blob.length();
byte [] data = blob.getBytes(1, len);
for (int i = 0; i < len; i++) {
    byte b = data[i];
    System.out.println(b);
}
// prints out all the bytes in the BLOB value that blob designates

The variable data contains a copy of all of the bytes in the BLOB value that blob designates. This is true because the arguments passed to the method getBytes specify the entire BLOB value: the first argument tells it to return bytes starting with the first byte, and the second argument tells it to return the number of bytes in the length of the BLOB value. The following line of code illustrates materializing 1024 bytes starting with the 256th byte:

byte [] data = blob.getBytes(256, 1024);
byte b = data[0];
// data contains bytes 256 through 1280 in the BLOB value that blob
// designates; b contains the 256th byte

A point to keep in mind is that because of differences in SQL and the Java programming language, the first byte in a BLOB value is at position 1, whereas the first element of an array in the Java programming language is at index 0.

8.1.3 Storing a Blob Object

To store a Blob object in the database, it is passed as a parameter to the PreparedStatement method setBlob. For example, the following code fragment stores the Blob object stats by passing it as the first input parameter to the PreparedStatement object pstmt:

Blob stats = rs.getBlob("STATS");
PreparedStatement pstmt = con.prepareStatement(
    "UPDATE SIGHTINGS SET MEAS = ? WHERE AREA = 'NE'");
pstmt.setBlob(1, stats);
pstmt.executeUpdate();

The BLOB value designated by stats is now stored in the table SIGHTINGS in column MEAS in the row where column AREA contains NE.

8.2 Blob Interface Definition

package java.sql;
public interface Blob {
    long length() throws SQLException;
    InputStream getBinaryStream() throws SQLException;
    byte[] getBytes(long pos, int length) throws SQLException;
    long position(byte [] pattern, long start) throws SQLException;
    long position(Blob pattern, long start) throws SQLException;
}

8.3 Blob Methods

InputStream getBinaryStream() throws SQLException
Materializes the BLOB value designated by this Blob object as a stream of uninterpreted bytes.

RETURNS:

an InputStream object with the data of the BLOB value designated by this Blob object

EXAMPLE:

InputStream in = blob.getBinaryStream();
// in has the data in the BLOB value that blob designates

getBytes

byte[] getBytes(long pos, int length) throws SQLException

Materializes part or all of the BLOB value that this Blob object designates as an array of bytes. The byte array contains up to length consecutive bytes starting at position pos.

PARAMETERS:

pos the ordinal position in the BLOB value
of the first byte to be extracted; the
first byte is at position 1
length the number of consecutive bytes to be copied

RETURNS:

a byte array with up to length consecutive bytes from the BLOB value pointed to by this Blob object, starting with the byte at position pos

EXAMPLE:

byte [] part = blob.getBytes(5, 100);
// part contains the fifth through 104th bytes, inclusive, as an
// array of bytes

length

long length() throws SQLException
Returns the number of bytes in the BLOB value designated by this Blob object.

RETURNS:

the length of the BLOB value designated by this Blob object, in bytes

EXAMPLE:

Blob blob = rs.getBlob(2);
long len = blob.length();
// len contains the number of bytes in the BLOB value designated by
// blob (the BLOB value in the second column of the current row of the
// ResultSet object rs)

position

long position(byte [] pattern, long start) throws SQLException
Determines the position at which the byte array pattern begins within the BLOB value that this Blob object represents. The search for pattern begins at position start.

PARAMETERS:
pattern | the byte array for which to search
start | the position in the BLOB value at which to begin searching; the first byte is at position 1

RETURNS:

the position in the BLOB value at which the byte array pattern begins, which will be start or larger if the search, starting at position start, is successful; -1 otherwise

EXAMPLE:

byte [] part = blob.getBytes(5, 100);
long beginning = blob.position(part, 1024);
// if part is contained in the BLOB value that blob designates, from
// position 1024 on, beginning will contain the position at which
// part begins

position

long position(Blob pattern, long start) throws SQLException
Determines the byte position in the BLOB value designated by this Blob object at which pattern begins. The search begins at position start.

PARAMETERS:
pattern | the Blob object designating the BLOB value for which to search
start | the position in the BLOB value at which to begin searching; the first byte is at position 1

RETURNS:

the position at which the Blob object pattern begins, which will be start or larger if the search, starting at position start, is successful; -1 otherwise

EXAMPLE:

Blob blob2 = rs.getBlob(4);
long beginning = blob1.position(blob2, 512);
// if the BLOB value designated by blob2 is contained in the BLOB
// value designated by blob1, starting at position 512 or later,
// beginning will contain the position at which the BLOB value
// designated by blob2 begins

Copyright © 2000, Sun Microsystems, Inc. All rights reserved.


JDBC-ODBC Bridge Enhancements

Java logo

JDBCTM-ODBC Bridge Enhancements

 Documentation Contents
JDBC

The JDBC-ODBC Bridge allows applications written in the JavaTM programming language to use the JDBCTM API with many existing ODBC drivers. The Bridge is itself a driver based on JDBC technology ("JDBC driver") that is defined in the class sun.jdbc.odbc.JdbcOdbcDriver. The Bridge defines the JDBC sub protocol odbc.

Status of the JDBC-ODBC Bridge

The JDBC-ODBC Bridge should be considered a transitional solution. Sun Microsystems and DataDirect Technologies are working to make the Bridge more reliable and robust, but they do not consider it a supported product. With the development of pure Java JDBC drivers, the JDBC-ODBC Bridge should become unnecessary.

Why not just use ODBC?

The JDBC-ODBC Bridge offers several advantages over "naked" ODBC.
  • The ODBC API is strongly oriented toward C/C++ programmers. The JDBC-ODBC Bridge makes it unnecessary for programmers using the Java programming language to deal with non-Java language concepts.
  • The ODBC API is extremely complex and intermingles high level and low level functions. The JDBC-ODBC Bridge allows the programmer to rely on the JDBC API, which is relatively simple and easy to learn.
  • The JDBC-ODBC Bridge lets a program deal with ODBC through a standardized JDBC interface. That helps a program avoid being tied to ODBC when a better solution comes along.

Why use ODBC at all?

The ideal is "Pure Java": no native code, no platform dependent features. But you may need to begin your development effort right away, without waiting for your DBMS to offer a Java only JDBC driver. Partly native drivers, such as the JDBC-ODBC Bridge, let you create programs that easily adapt to Pure Java drivers as they become available.

What's New with the JDBC-ODBC Bridge?

  • A jdbc:odbc: connection can now have a charSet property, to specify a Character Encoding Scheme other than the client default. For possible values, see the Internationalization specification on the Java Software Web Site.

    • The following code fragment shows how to set 'Big5' as the character set for all character data.
           // Load the JDBC-ODBC bridge driver
       Class.forName(sun.jdbc.odbc.JdbcOdbcDriver) ;

       // setup the properties
       java.util.Properties prop = new java.util.Properties();
       prop.put("charSet", "Big5");
       prop.put("user", username);
       prop.put("password", password);

       // Connect to the database
       con = DriverManager.getConnection(url, prop);
  • The bridge now supports JDBC 2.0 features, which includes batch updates, scrollable cursors, and so on.
  • JDBC-ODBC bridge now offers most of the features required for a J2EE compatible JDBC driver.
  • Sample implementations of DataSource and ConnectionPoolDataSource are available with the JDBC-ODBC bridge.
  • CallableStatement OUT/INOUT parameter handling has been improved.
  • Automatic garbage collection of unclosed Statement objects has been implemented.
  • Improved support for updatable Resultset objects has been implemented.
  • Additional robustness and reliability checking as been introduced.

New DataSource Implementations in the JDBC-ODBC Bridge

Implementations of javax.sql.DataSource and javax.sql.ConnectionPoolDataSource are now available. Both are in the sun.jdbc.odbc.ee package. The following code fragment illustrates how to set DataSource properties. The last two lines use JNDI API to bind the DataSource object ds to "jdbc/OdbcDB1". Assume that the DataSource object is targeting an ODBC DSN "dsn1" connecting to an Oracle Database.
            // Establish the DataSource object instance
            sun.jdbc.odbc.ee.DataSource ds = new sun.jdbc.odbc.ee.DataSource();
            // Provide user credentials and database name
            ds.setUser("scott");
            ds.setPassword("tiger");
            ds.setDatabaseName("dsn1");
            ds.setCharSet("..."); // optional property
            ds.setLoginTimeout(100); // optional property
            // Establish initial context and bind to the datasource target
            InitialContext ic = new InitialContext();
            ic.bind("jdbc/OdbcDB1",ds);
In the preceding code, note that some properties are optional while some are required. Properties such as port number and role name are not implemented in the JDBC-ODBC bridge DataSource implementations as these properties are not applicable to ODBC paradigm.

Continuing the previous example, the following code fragment demonstrates retrieving the DataSource object by looking up the JNDI name "jdbc/OdbcDB1". With the DataSource object that is obtained, the code then activates tracing and creates two connections.

            // Get the initial context of JNDI and lookup the datasource.
            InitialContext ic = new InitialContext();
            javax.sql.DataSource ds1 = (javax.sql.DataSource) ic.lookup("jdbc/OdbcDB1");
            // Set the optional printwriter where the trace log is to be directed.
            ds1.setLogWriter(new PrintWriter(new FileOutputStream("/tmp/datasource.log")));
            Connection con1 = ds1.getConnection();
            Connection con2 = ds1.getConnection("system","manager");
The implementation of javax.sql.ConnectionPoolDataSource uses an underlying pool of JDBC-ODBC connections. A ConnectionPoolDataSource object is used to create PooledConnection objects, which are in turn used to get Connection objects. From the user's viewpoint, the Connection object is just like any other connection.

The following code fragment creates the ConnectionPoolDataSource object cpds and sets its properties. The final two lines use JNDI API to bind cpds to "jdbc/OdbcPool", which can later be supplied to the method InitialContext.lookup to retrieve cpds.

            // Establish ConnectionPoolDataSource instance
            sun.jdbc.odbc.ee.ConnectionPoolDataSource cpds =
                new sun.jdbc.odbc.ee.ConnectionPoolDataSource("jdbc/OdbcPool");
            // Provide user credentials and database name
            cpds.setUser("scott");
            cpds.setPassword("tiger");
            cpds.setDatabaseName("dsn1");
            cpds.setCharSet("...") // optional property
            cpds.setLoginTimeout(100); // optional property
            cpds.setMinPoolSize("10");
            cpds.setInitialPoolSize("15");
            cpds.setMaxPoolSize("20");
            cpds.setMaxIdleTime("300");
            cpds.setTimeoutFromPool("600");
            // Maintenance interval of the pool. A maintenance thread will remove
            // unwanted connections and cleanup the pool at the interval specified.
            // This cannot be zero.
            cpds.setMaintenanceInterval("900");
            InitialContext ic = new InitialContext();
            ic.bind("jdbc/OdbcPool",cpds);
In all cases in order get the ConnectionPoolDataSource to function as a pooled datasource, it is the responsibility of the application to configure the pool as described in the code example above. The default behavior of pooled datasource uses a zero minimum, initial and maximum pool sizes. Note that the JDBC-ODBC bridge implementation of ConnectionPoolDataSource does not yet include the pooling of Statement objects or the property propertyCycle.

The following code fragment shows how to use a ConnectionPoolDataSource object as simply a DataSource object. This is done by doing a JNDI lookup of "jdbc/OdbcPool" and casting it to a DataSource object instead of to a ConnectionPoolDataSource object.

            InitialContext ic = new InitialContext();
            javax.sql.DataSource ds1 = (javax.sql.DataSource) ic.lookup("jdbc/OdbcPool");
            // First getConnection will initializes the pool.
            Connection con1 = ds1.getConnection();
            Connection con2 = ds1.getConnection("system","manager");
            -------------
            -------------
            // An application need to close the connection explicitly. This will allow the pool to recycle the connection.
            con1.close();
            con2.close();
Using the implementation as a ConnectionPoolDataSource object is shown in the following line of code. Note that closing a PooledConnection object closes the actual physical connection, whereas closing a connection that was created from a PooledConnection object just returns it to the pool of connections.
            InitialContext ic = new InitialContext();
            javax.sql.ConnectionPoolDataSource cpds =
                (javax.sql.ConnectionPoolDataSource) ic.lookup("jdbc/OdbcPool");
            PooledConnection pc1 = cpds.getPooledConnection();
            Connection con1 = pc1.getConnection();
            PooledConnection pc2 = cpds.getPooledConnection("system","manager");
            Connection con2 = pc2.getConnection();
            -------------
            -------------
            // An application needs to close the connection explicitly. This will allow the pool to recycle the connection.
            con1.close();
            con2.close();
            Connection con3 = pc1.getConnection();
            Connection con4 = pc2.getConnection();
            -------------
            -------------
            // This will close the physical connection!
            pc1.close();
            pc2.close();
A pool of connections can be shut down in two ways. If the method shutDown is given the argument false, only those connections that are not being used will be closed. If the argument true is supplied, all connections will be closed immediately, regardless of whether they are being used or not.
            // Hot shutdown
            ((sun.jdbc.odbc.ee.ConnectionPoolDataSource) cpds).shutDown(true);
            or
            // Cold shutdown
            ((sun.jdbc.odbc.ee.ConnectionPoolDataSource) cpds).shutDown(false);

Java logo Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: jdbc-odbc@sun.com


Clob

10.1 Clob Overview

A Clob object represents the Java programming language mapping of an SQL CLOB (Character Large Object). An SQL CLOB is a built-in type that stores a Character Large Object as a column value in a row of a database table. Methods in the interfaces ResultSet, CallableStatement, and PreparedStatement allow a programmer to access the SQL3 type CLOB in the same way that more basic SQL types are accessed. In other words, an application using the JDBC 2.0 API uses methods such as getClob and setClob for a CLOB value the same way it uses getInt and setInt for an INTEGER value or getString and setString for a CHAR or VARCHAR value.

The default is for a JDBC driver to implement the Clob interface using the SQL type LOCATOR(CLOB) behind the scenes. A LOCATOR(CLOB) designates an SQL CLOB residing on a database server, and operations on the locator achieve the same results as operations on the CLOB itself. This means that a client can operate on a Clob instance without ever having to materialize the CLOB data on the client machine. The driver uses LOCATOR(CLOB) behind the scenes, making its use completely transparent to the JDBC programmer.

The standard behavior for a Clob instance is to remain valid until the transaction in which it was created is either committed or rolled back.

The interface Clob provides methods for getting the length of an SQL CLOB value, for materializing the data in a CLOB value on the client, and for searching for a substring or CLOB object within a CLOB value.

10.1.1 Creating a Clob Object

The following code fragment illustrates creating a Clob object, where rs is a ResultSet object:

Clob clob = rs.getClob(1);

The variable clob can now be used to operate on the CLOB value that is stored in the first column of the result set rs.

10.1.2 Materializing Clob Data

Programmers can invoke methods in the JDBC API on a Clob object as if they were operating on the SQL CLOB value it designates. However, if they want to operate on a Clob object as an object in the Java programming language, they must first materialize the data of the CLOB object on the client. The Clob interface provides three methods for materializing a Clob object as an object in the Java programming language:

  • getAsciiStream materializes the CLOB value as a byte stream containing Ascii bytes
Clob notes = rs.getClob("NOTES");
java.io.InputStream in = notes.getAsciiStream();
byte b = in.read();
// in contains the characters in the CLOB value designated by
// notes as Ascii bytes; b contains the first character as an Ascii
// byte
  • getCharacterStream materializes the CLOB value as a stream of Unicode characters
java.io.Reader reader = notes.getCharacterStream();
int c = Reader.read();
// c contains the first character in the CLOB that notes designates
  • getSubString materializes all or part of the CLOB value as a String object
String substring = notes.getSubString(10, 5);
// substring contains five characters, starting with the tenth
// character of the CLOB value that notes designates
long len = notes.length();
String substring = notes.getSubString(1, len);
// substring contains all of the characters in the CLOB object that
// notes designates

10.1.3 Storing a Clob Object

To store a Clob object in the database, it is passed as a parameter to the PreparedStatement method setClob. For example, the following code fragment stores the Clob object notes by passing it as the first input parameter to the PreparedStatement object pstmt:

Clob notes = rs.getClob("NOTES");
PreparedStatement pstmt = con.prepareStatement(
        "UPDATE SALES_STATS SET COMMENTS = ? WHERE SALES > 500000");
pstmt.setClob(1, notes);
pstmt.executeUpdate();

The CLOB value designated by notes is now stored in the table SALES_STATS in column COMMENTS in every row where the value in the column SALES is greater than 500000.

10.2 Clob Interface Definition

package java.sql;
public interface java.sql.Clob {
    long length() throws SQLException;
    InputStream getAsciiStream() throws SQLException;
    Reader getCharacterStream() throws SQLException;
    String getSubString(long pos, int length) throws SQLException;
    long position(String searchstr, long start) throws SQLException;
    long position(Clob searchstr, long start) throws SQLException;
}

10.3 Clob Methods

getAsciiStream

InputStream getAsciiStream() throws SQLException
Materializes the CLOB value designated by this Clob object as a stream of Ascii bytes.

RETURNS:

an InputStream object with all the data in the CLOB value designated by this Clob object as Ascii bytes

EXAMPLE:

java.io.InputStream in = clob.getAsciiStream();
byte b = in.read();
// in has all of the characters in the CLOB value designated by
// clob as Ascii bytes; b designates the first character as an Ascii
// byte

getCharacterStream

Reader getCharacterStream() throws SQLException
Materializes the CLOB value designated by this Clob object as a stream of Unicode characters.

RETURNS:

a Reader object with all the data in the CLOB value designated by this Clob object as Unicode characters

EXAMPLE:

Reader read = clob.getCharacterStream();
// read has all the data in the CLOB value designated by clob
// as Unicode characters

getSubString

length getSubString(long pos, int length) throws SQLException
Returns a copy of the portion of the CLOB value represented by this Clob object that starts at position pos and has up to length consecutive characters.

PARAMETERS:
pos | the position of the first char to extract from the CLOB value designated by this Clob object; the initial position is 1
length | the number of consecutive characters to be copied

RETURNS:

a String object containing a copy of up to length consecutive characters from the CLOB value represented by this Clob object, starting with the char at position pos

EXAMPLE:

String substr = clob.getSubString(1, 100);
// substr contains the first 100 characters in the CLOB value
// designated by clob (those in positions 1 through 100, inclusive)

length

long length() throws SQLExceptions
Returns the number of characters in the CLOB value designated by this Clob object.

RETURNS:

the length in characters of the CLOB value that this Clob object represents

EXAMPLE:

Clob clob = rs.getClob(3);
long len = clob.length();
// len contains the number of characters in the CLOB value
// designated by clob

position

long position(Clob searchstr, long start) throws SQLException
Determines the character position at which the Clob object searchstr begins within the CLOB value that this Clob object represents. The search begins at position start.

PARAMETERS:
searchstr | the Clob object for which to search
start | the position at which to begin searching; the first character is at position 1

RETURNS:

the position at which the Clob object searchstr begins, which will be start or larger if the search, starting at position start, is successful; -1 otherwise

EXAMPLE:

Clob clob2 = rs.getClob(4);
long beginning = clob.position(clob2, 1024);
// if clob2 is contained in clob starting at position 1024 or later,
// beginning will contain the position at which clob2 begins

position

long position(String searchstr, long start) throws SQLException
Determines the position at which the String searchstr begins within the CLOB value that this Clob object represents. The search begins at position start.

PARAMETERS:
searchstr | the string for which to search
start | the position at which to begin searching; the first character is at position 1

RETURNS:

the position at which the String object searchstr begins, which will be start or larger if the search, starting at position start, is successful; -1 otherwise

EXAMPLE:

String searchstr= clob.getSubString(5, 100);
long beginning = clob.position(searchstr, 1024);
// if searchstr is contained in clob from position 1024 on, beginning
// will contain the position at which searchstr begins

Copyright © 2000, Sun Microsystems, Inc. All rights reserved.


JDBC Documentation

Java logo

JDBCTM API Documentation

 Documentation Contents

The JDBCTM API provides universal data access from the JavaTM programming language. Using the JDBC 3.0 API, you can access virtually any data source, from relational databases to spreadsheets and flat files. JDBC technology also provides a common base on which tools and alternate interfaces can be built.

The JDBC 3.0 API is comprised of two packages:

  1. the java.sql package
  2. the javax.sql package, which adds server-side capabilities

You automatically get both packages when you download the JavaTM 2 Platform, Standard Edition, Version 1.4 (J2SETM).

JDBC Technology Drivers

To use the JDBC API with a particular database management system, you need a JDBC technology-based driver to mediate between JDBC technology and the database. Depending on various factors, a driver might be written purely in the Java programming language or in a mixture of the Java programming language and JavaTM Native Interface (JNI) native methods. The JDBC web site maintains a list of vendors with drivers currently available or under development.

The latest SDK includes a JDBC-ODBC Bridge driver that makes most Open Database Connectivity (ODBC) drivers available to programmers using the JDBC API. JDBC-ODBC Bridge Driver describes the current status of this software. Note that the bridge driver included in the JavaTM 2 Platform, Standard Edition, version 1.4 (J2SETM) is appropriate only for experimental use or when no other driver is available.

Getting Started
  • JDBCTM Technology Guide: Getting Started
The JDBCTM API Specification
  • Specifications
    • Specifications for all releases of the JDBC API are available from our download page

  • JDBC API JavadocTM Comments
    • java.sql package
    • javax.sql package
Online Tutorials
  • Basic Tutorial
  • Advanced Tutorial
  • Rowset Tutorial
Related Documents
  • Answers to Frequently-Asked Questions
  • Using Blob objects (Binary Large Objects) Chapter 8 of the JDBC Java Series book
  • Using Clob objects (Character Large Objects) Chapter 10 of the JDBC Java Series book
  • Java Series book JDBCTM API Tutorial and Reference, Second Edition
  • Java 2 SDK, Enterprise Edition, documentation web page

Home Page for JDBC API on java.sun.com

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: jdbc@sun.com or jdbc-odbc@sun.com

Java Software


 [Top] [Prev] [Next] [Bottom]

Summary of New Features

NOTE: The material in this chapter is based on JDBCtm API Tutorial and Reference, Second Edition: Universal Data Access for the Javatm 2 Platform, published by Addison Wesley as part of the Java series, ISBN 0-201-43328-1.

This appendix summarizes the new features in the JDBC 2.1 core API.

A.1 Overview of JDBC 2.1 Core API Changes

The JDBC 2.1 core API includes the JDBC 1.0 API and adds enhancements and new functionality to it. These additions put the Java programming language at the forefront of database computing, providing both universal data access and improved performance.

Applications that use earlier versions of the JDBC API can be run using the Java 2 platform with no problem, in keeping with the goal of backward compatibility. However, an application that takes advantage of the new 2.0 features must be run with a driver that implements those features.

The new features in the JDBC 2.1 core API fall into two broad categories: support for new functionality and support for the SQL3 data types.

  1. Support for new functionality
    • scrollable result sets
    • batch updates
    • programmatic inserts, deletes, and updates
    • other
      • performance hints
      • character streams for streams of internationalized Unicode characters
      • full precision for java.math.BigDecimal values
      • support for time zones in Date, Time, and Timestamp values

  2. Support for advanced data types
    • new SQL data types (SQL3 types)
    • increased support for storing persistent objects in the Java programming language

In addition to making the retrieval, storage, and manipulation of data more convenient, the new features make JDBC applications more efficient. For example, batch updates can increase performance dramatically. The new interfaces Blob, Clob, and Array allow applications to operate on large amounts of data without having to materialize the data on the client, which can mean a significant savings in transfer time and the amount of memory needed. Also, new methods for setting the fetch size and fetch direction let a programmer fine tune an application for more efficient data retrieval and processing.

A.2 Summary of New Functionality

The JDBC 2.1 core API adds important new functionality. The following sections briefly explain each new area of functionality and summarize the supporting API.

A.2.1 Scrollable Result Sets

Scrollable result sets provide the ability to move the cursor forward and backward to a specified position or to a position relative to the current position. The following interfaces have new methods that support scrollable result sets.

  • ResultSet
    • methods for moving the cursor to a particular row or to a relative position (either forward or backward)
    • methods for ascertaining the current position of the cursor
    • constants indicating the scrollability of a result set
  • Connection
    • new versions of the methods for creating Statement, PreparedStatement, and CallableStatement objects that make the result sets they produce scrollable
  • DatabaseMetaData
    • method indicating whether the DBMS and driver support scrollable result sets

A.2.2 Batch Updates

The new batch update facility provides the ability to send multiple updates to the database to be executed as a batch rather than sending each update separately. The following interfaces add methods that support batch updates, and the exception BatchUpdateException is new.

  • Statement, PreparedStatement, and CallableStatement
    • methods for adding update statements to a batch, clearing all update statements, and executing a batch
  • DatabaseMetaData
    • method indicating whether the DBMS and driver support batch updates
  • BatchUpdateException
    • exception thrown when an error occurs in a batch update

A.2.3 Programmatic Updates

Programmatic updates provide the ability to make updates using the JDBC API rather than SQL statements. The following interfaces have new methods and constants that support programmatic updates.

  • ResultSet
    • an updateXXX method for updating each data type
    • methods for inserting, deleting, or updating a row
    • methods indicating whether a row was inserted, deleted, or updated
    • method for cancelling a row update
    • constants indicating the updatability of a result set
  • DatabaseMetaData
    • methods indicating the visibility of changes to a result set
    • methods indicating whether a result set detects inserts, deletes, or updates
    • method indicating whether the DBMS and driver support updatable result sets

A.2.4 Other New Features

The JDBC 2.1 core API provides various other new features, which are summarized in the following list.

  • Performance enhancements-new methods that allow a programmer to fine tune the retrieval of rows from the database. These methods provide the ability to specify (1) the number of result set rows fetched from the database when more rows are needed and (2) the direction in which rows are fetched from the database.
    • ResultSet methods for getting and setting the current fetch size and fetch direction
    • Statement, PreparedStatement, and CallableStatement methods for getting and setting the default fetch size and default fetch direction that result sets generated by executing a query will have when they are first created
  • Character streams-new methods that allow character data to be retrieved or sent to the database as a stream of internationalized Unicode characters. These methods replace the deprecated getUnicodeStream and setUnicodeStream methods.
    • ResultSet.getCharacterStream
    • CallableStatement.getCharacterStream
    • PreparedStatement.setCharacterStream
  • Full precision for java.math.BigDecimal values-new versions of themethods that retrieve a java.math.BigDecimal value with full precision. Unlike the deprecated versions they replace, these new versions do not take a specified precision.
    • ResultSet.getBigDecimal
    • CallableStatement.getBigDecimal
  • Support for time zones-methods with new versions that take a Calendar object as a parameter, which allows the driver to use a specified time zone rather than the default when calculating a value for a date, time, or timestamp
    • ResultSet.getDate
    • ResultSet.getTime
    • ResultSet.getTimestamp
    • CallableStatement.getDate
    • CallableStatement.getTime
    • CallableStatement.getTimestamp
    • PreparedStatement.setDate
    • PreparedStatement.setTime
    • PreparedStatement.setTimestamp

A.3 Support for Advanced Data Types

The JDBC 2.1 core API adds support for using advanced data types, making it as easy to use them as it is to use simple data types. This support includes the ability to store, retrieve, and update even the new SQL data types that are essentially objects, blurring the distinction between object databases and relational databases. The next four sections ("What Are the SQL3 Data Types?" on page 120, "Summary of Support for the SQL3 Data Types" on page 121, "Mapping of the New SQL3 Types" on page 122, and "SQL Locators" on page 123) describe how the JDBC 2.0 core API provides support for these advanced data types.

In addition to being able to store objects defined in SQL as values in a database table, programmers writing Java applications can also store objects defined in the Java programming language as values in a database table. The section "Support for Storing Java Objects" on page 123 describes this capability.

Note that a driver is not required to implement functionality that its DBMS does not support, so not all drivers necessarily implement the functionality described here. DatabaseMetaData methods such as getTypeInfo, getColumns, and getUDTs may be called to get information about which data types a driver supports.

A.3.1 What Are the SQL3 Data Types?

This section briefly describes the new SQL3 data types. Their mapping to types in the Java programming language is described in section A.3.3 on page 122.

The SQL3 data types can be categorized as follows:

  • New built-in types-types for storing large objects. These are in addition to the standard built-in data types, such as CHAR, FLOAT, DATE, and so on.
    • BLOB (Binary Large Object)
    • CLOB (Character Large Object)
  • Constructed types-types based on a given base type
    • REF(structured type)-a reference to the specified SQL structured type
    • ARRAY[n]-an array of n elements that are all one data type
  • User-defined types (UDTs)-new types created with the SQL commandþCREATE TYPE
    • Distinct type-a new type based on the representation of a single built-in type
    • Structured type-a new type containing multiple attributes, each of which may be either a built-in or a user-defined data type
  • Locator types-types that are logical pointers to data that resides on the database server
    • LOCATOR(structured type)
    • LOCATOR(array)
    • LOCATOR(blob)
    • LOCATOR(clob)

A.3.2 Summary of Support for the SQL3 Data Types

The JDBC 2.1 core API supports the new SQL 3 data types by means of the following new interfaces, methods, and fields.

  • New interfaces for the new data types. The SQL3 types are mapped by the following new JDBC 2.1 core API interfaces:
    • java.sql.Array
    • java.sql.Blob
    • java.sql.Clob
    • java.sql.Ref
    • java.sql.Struct
  • New interfaces that support customizing the mapping of UDTs (SQL structured and distinct types) into classes in the Java programming language
    • SQLData
    • SQLInput
    • SQLOutput
  • New methods added to existing interfaces in order to retrieve, store, and update the new SQL3 types
    • new getXXX methods in the ResultSet interface to retrieve SQL3 type column values from a result set
    • new getXXX methods in the CallableStatement interface to retrieve SQL3 type values in output parameters
    • new setXXX methods in the PreparedStatement interface to set a SQL3 type column value
    • new updateXXX methods in the ResultSet interface to update values programmatically
  • New methods in the DatabaseMetaData and ResultSetMetaData interfaces for getting metadata about the new data types
  • New fields (constants) added to the class java.sql.Types to support the new data types and persistent storage
    • DISTINCT
    • STRUCT
    • ARRAY
    • BLOB
    • CLOB
    • REF
    • JAVA_OBJECT

A.3.3 Mapping of the New SQL3 Types

The JDBC 2.1 core API does not try to replicate the SQL3 types exactly; rather, its goal is to map them to types in the Java programming language so that they retain their functionality and are convenient to use. For example, SQL3 has what are called locator types, which are used on a client to designate data that is stored on a database server. Locators can be very useful for dealing with data that is large because they allow the data to be manipulated without having to be materialized on the client machine. SQL3 includes locators for the types ARRAY, BLOB, CLOB and structured types. The JDBC 2.1 core API does not include locators for these types directly (and not at all for structured types) but rather provides interfaces that are implemented such that the driver and DBMS use the appropriate locators behind the scenes. The result is that a developer using the JDBC API to access an SQL ARRAY, BLOB, or CLOB value need not even be aware of locators. See section A.3.4 on page 123 for more information about locators.

In the JDBC 2.1 core API, the following SQL3 types are mapped to interfaces in the Java programming language:

  • ARRAY-mapped to java.sql.Array
  • BLOB-mapped to java.sql.Blob
  • CLOB-mapped to java.sql.Clob
  • REF-mapped to java.sql.Ref
  • an SQL structured type-mapped to java.sql.Struct

Distinct types are not mapped to an interface because they are based on a single built-in type and thus can simply be mapped to the standard mapping for that built-in type. For example, the following is an SQL statement that creates the new type MONEY.

CREATE TYPE MONEY AS NUMERIC(10, 2)

This new UDT is based on the data type NUMERIC, which maps to java.math.BigDecimal, so the type MONEY maps to java.math.BigDecimal. This means that a value of type MONEY would be retrieved with the method getBigDecimal, stored with the method setBigDecimal, and updated with the method updateBigDecimal.

A.3.4 SQL Locators

An SQL LOCATOR is a logical pointer to data that resides on a database server. It typically refers to data that is too large to materialize on the client, such as images or audio. Locators exist only in a client environment, and their existence is transient. A standard implementation of the JDBC 2.1 core API will use locators internally for instances of the Blob, Clob, and Array interfaces. This means that Blob, Clob, and Array objects contain a locator that points to the data on the server rather than containing the data itself. Programmers operating on Blob, Clob, and Array instances are actually operating on the database objects they represent. This ability to operate on large database objects without bringing their data to the client is a major plus in performance.

Note that the JDBC 2.1 core API does not call for using the SQL LOCATOR(structured type). In a standard implementation, a Struct object contains the data of the structured type that it maps and is not implemented internally as a locator, as are Blob, Clob, and Array objects.

A.3.5 Support for Storing Java Objects

The JDBC API has always supported persistent storage of objects defined in the Java programming language through the methods getObject and setObject. But, of course, persistent storage of Java objects does not actually occur unless a DBMS also supports it. Up to this point, support was limited, but a new generation of DBMSs that recognize Java objects as a data type is emerging. In these DBMSs, termed Java relational DBMSs, an instance of a Java class can be stored as a column value in a database table.

[Top] [Prev] [Next] [Bottom]

Copyright © 1999, Sun Microsystems, Inc. All rights reserved.


 [Top] [Prev] [Next] [Bottom]

Summary of New Features

NOTE: Some of the material in this chapter is based on JDBCtm API Tutorial and Reference, Second Edition: Universal Data Access for the Javatm 2 Platform, published by Addison Wesley as part of the Java series, ISBN 0-201-43328-1.

This appendix summarizes the new features that have been added to the JDBC API over time. Note that in order to use a feature, you must be using a driver that supports that feature.

A.1 Overview of JDBC 3.0 API Changes

One of the major changes in the JDBC 3.0 API is that it includes the package javax.sql (the JDBC Optional Package) as well as the package java.sql. This overview is divided into two sections, the first giving new features introduced in the JDBC 3.0 API for both packages, and the second giving the features introduced in the JDBC 2.0 Optional Package. See the JDBC 3.0 API Specification for more detailed information.

A.1.1 Features Introduced in the JDBC 3.0 API

The JDBC 3.0 API introduces new material and changes in these areas:

  • Savepoint support
    Added the Savepoint interface, which contains new methods to set a savepoint, to release a savepoint, and to roll back a transaction to a designated savepoint.
  • Reuse of prepared statements by connection pools
    Added the ability for deployers to control how prepared statements are pooled and reused by connections.
  • Connection pool configuration
    Defined a number of properties for the ConnectionPoolDataSource interface. These properties can be used to describe how PooledConnection objects created by DataSource objects should be pooled.
  • Retrieval of parameter metadata
    Added the new interface ParameterMetaData, which describes the number, type, and properties of parameters to prepared statements.
  • Retrieval of auto-generated keys
    Added a means of retrieving values from columns containing automatically generated values.
  • Ability to have multiple open ResultSet objects
    Added the new method getMoreResults(int) that takes an argument that specifies whether ResultSet objects returned by a Statement should be closed before returning any subsequent ResultSet objects.
  • Passing parameters to CallableStatement objects by name
    Added methods to allow a string to identify the parameter to be set for a CallableStatement object.
  • Holdable cursor support
    Added the ability to specify whether a ResultSet object is kept open after a transaction has been committed.
  • BOOLEAN data type
    Added the data type java.sql.Types.BOOLEAN. BOOLEAN is logically equivalent to BIT.
  • Making internal updates to the data in Blob and Clob objects
    Added methods to allow the data contained in Blob and Clob objects to be altered.
  • Retrieving and updating the object referenced by a Ref object
    Added methods to retrieve the object referenced by a Ref object. Also added the ability to update a referenced object through the Ref object.
  • Updating of columns containing BLOB, CLOB, ARRAY and REF types
    Addition of the updateBlob, updateClob, updateArray, and updateRef methods to the ResultSet interface.
  • DATALINK/URL data type
    Added the data type java.sql.Types.DATALINK, allowing JDBC drivers to store and retrieve references to external data.
  • Transform groups and type mapping
    Described the effect of transform groups and how this is reflected in the metadata.
  • Relationship between the JDBC SPI (Service Provider Interface) and the Connector architecture
    Described the relationship between the JDBC SPI and the connector architecture.
  • DatabaseMetadata APIs
    Added metadata for retrieving SQL type hierarchies and various other kinds of information relating to new features.

A.1.2 Features Introduced in the JDBC 2.0 Optional Package

The following features, which were introduced in the javax.sql package, are now part of the JDBC 3.0 API and are included in the J2SE version 1.4:

  • Using a DataSource Object to Get a Connection

    Using the JNDI API and the new DataSource interface, an application does not need to specify a driver name in its code to make a connection to a data source. It can specify a logical name that has been registered with a JNDI naming service and retrieve a DataSource object that will get a connection to the desired data source. This capability makes code more portable and much easier to maintain.

  • Connection Pooling

    Connection pooling allows an application to (re)use database connections that have already been established instead of always having to create new connections. Because creating and destroying database connections is expensive, this feature is important for good performance, especially for server applications.

    The JDBC 2.0 Optional Package API provides hooks that allow connection pooling to be implemented on top of the JDBC driver layer. This makes it possible to have a single cache of connections available for all of the JDBC drivers in use.

  • Support for Distributed Transactions

    The JDBC 2.0 Optional Package API allows a JDBC driver to support the standard two-phase commit protocol defined in the Java Transaction API (JTA). This means that a transaction may be distributed over multiple servers, which lets developers write enterprise applications using Enterprise JavaBeanstm components that are transactional across multiple DBMS servers.

  • Rowsets

    RowSet objects are simply containers for tabular data that can be implemented on top of the JDBC API. Rowsets make it possible to pass rows of data across a network, so they are likely to be used extensively in distributed applications. Rowsets may be very lean by being disconnected from a data source, making it possible to display data on a thin client. They also make it possible to use scrolling when the underlying DBMS does not support scrollable result sets. A rowset is a JavaBeanstm component and consequently easy to use in building an application, especially with a development tool.

    Typically, a third party will provide a RowSet implementation, and the application programmer just uses it. The API for a RowSet implementation is generally very easy to use because most of a rowset's functionality is inherited from the ResultSet interface. The more complicated aspects of a rowset take place internally and are invisible to the application programmer. There are currently three Early Access implementations of the RowSet interface available from the Java Developer Connection (http://developer.java.sun.com/developer).

A.2 Overview of JDBC 2.0 Core API Changes

The JDBC 2.0 core API includes the JDBC 1.0 API and adds enhancements and new functionality to it. These additions put the Java programming language at the forefront of database computing, providing both universal data access and improved performance.

Applications that use earlier versions of the JDBC API can be run using the Java 2 platform with no problem, in keeping with the goal of backward compatibility. However, an application that takes advantage of the new 2.0 features must be run with a driver that implements those features.

The new features in the JDBC 2.0 core API fall into two broad categories: support for new functionality and support for the SQL99 data types.

  1. Support for new functionality
    • scrollable result sets
    • batch updates
    • programmatic inserts, deletes, and updates
    • other
      • performance hints
      • character streams for streams of internationalized Unicode characters
      • full precision for java.math.BigDecimal values
      • support for time zones in Date, Time, and Timestamp values

  2. Support for advanced data types
    • new SQL data types (SQL99 types)
    • increased support for storing persistent objects in the Java programming language

      In addition to making the retrieval, storage, and manipulation of data more convenient, the new features make JDBC applications more efficient. For example, batch updates can increase performance dramatically. The new interfaces Blob, Clob, and Array allow applications to operate on large amounts of data without having to materialize the data on the client, which can mean a significant savings in transfer time and the amount of memory needed. Also, new methods for setting the fetch size and fetch direction let a programmer fine tune an application for more efficient data retrieval and processing.

A.3 Summary of New Functionality

The JDBC 2.0 core API adds important new functionality. The following sections briefly explain each new area of functionality and summarize the supporting API.

A.3.1 Scrollable Result Sets

Scrollable result sets provide the ability to move the cursor forward and backward to a specified position or to a position relative to the current position. The following interfaces have new methods that support scrollable result sets.

  • ResultSet
    • methods for moving the cursor to a particular row or to a relative position (either forward or backward)
    • methods for ascertaining the current position of the cursor
    • constants indicating the scrollability of a result set
  • Connection
    • new versions of the methods for creating Statement, PreparedStatement, and CallableStatement objects that make the result sets they produce scrollable
  • DatabaseMetaData
    • method indicating whether the DBMS and driver support scrollable result sets

A.3.2 Batch Updates

The new batch update facility provides the ability to send multiple updates to the database to be executed as a batch rather than sending each update separately. The following interfaces add methods that support batch updates, and the exception BatchUpdateException is new.

  • Statement, PreparedStatement, and CallableStatement
    • methods for adding update statements to a batch, clearing all update statements, and executing a batch
  • DatabaseMetaData
    • method indicating whether the DBMS and driver support batch updates
  • BatchUpdateException
    • exception thrown when an error occurs in a batch update

A.3.3 Programmatic Updates

Programmatic updates provide the ability to make updates using the JDBC API rather than SQL statements. The following interfaces have new methods and constants that support programmatic updates.

  • ResultSet
    • an updater method for updating each data type
    • methods for inserting, deleting, or updating a row
    • methods indicating whether a row was inserted, deleted, or updated
    • method for cancelling a row update
    • constants indicating the updatability of a result set
  • DatabaseMetaData
    • methods indicating the visibility of changes to a result set
    • methods indicating whether a result set detects inserts, deletes, or updates
    • method indicating whether the DBMS and driver support updatable result sets

A.3.4 Other New Features

The JDBC 2.0 core API provides various other new features, which are summarized in the following list.

  • Performance enhancements-new methods that allow a programmer to fine tune the retrieval of rows from the database. These methods provide the ability to specify (1) the number of result set rows fetched from the database when more rows are needed and (2) the direction in which rows are fetched from the database.
    • ResultSet methods for getting and setting the current fetch size and fetch direction
    • Statement, PreparedStatement, and CallableStatement methods for getting and setting the default fetch size and default fetch direction that result sets generated by executing a query will have when they are first created
  • Character streams-new methods that allow character data to be retrieved or sent to the database as a stream of internationalized Unicode characters. These methods replace the deprecated getUnicodeStream and setUnicodeStream methods.
    • ResultSet.getCharacterStream
    • CallableStatement.getCharacterStream
    • PreparedStatement.setCharacterStream
  • Full precision for java.math.BigDecimal values-new versions of themethods that retrieve a java.math.BigDecimal value with full precision. Unlike the deprecated versions they replace, these new versions do not take a specified precision.
    • ResultSet.getBigDecimal
    • CallableStatement.getBigDecimal
  • Support for time zones-methods with new versions that take a Calendar object as a parameter, which allows the driver to use a specified time zone rather than the default when calculating a value for a date, time, or timestamp
    • ResultSet.getDate
    • ResultSet.getTime
    • ResultSet.getTimestamp
    • CallableStatement.getDate
    • CallableStatement.getTime
    • CallableStatement.getTimestamp
    • PreparedStatement.setDate
    • PreparedStatement.setTime
    • PreparedStatement.setTimestamp

A.4 Support for Advanced Data Types

The JDBC 2.0 core API adds support for using advanced data types, making it as easy to use them as it is to use simple data types. This support includes the ability to store, retrieve, and update even the new SQL data types that are essentially objects, blurring the distinction between object databases and relational databases. The next four sections ("What Are the SQL99 Data Types?" on page 145, "Summary of Support for the SQL99 Data Types" on page 146, "Mapping of the SQL99 Types" on page 148, and "SQL Locators" on page 149) describe how the JDBC 2.0 core API provides support for these advanced data types.

In addition to being able to store objects defined in SQL as values in a database table, programmers writing Java applications can also store objects defined in the Java programming language as values in a database table. The section "Support for Storing Java Objects" on page 149 describes this capability.

Note that a driver is not required to implement functionality that its DBMS does not support, so not all drivers necessarily implement the functionality described here. DatabaseMetaData methods such as getTypeInfo, getColumns, and getUDTs may be called to get information about which data types a driver supports.

A.4.1 What Are the SQL99 Data Types?

This section briefly describes the new SQL99 data types. Their mapping to types in the Java programming language is described in section A.4.3 on page 148.

The SQL99 data types can be categorized as follows:

  • New built-in types-types for storing large objects. These are in addition to the standard built-in data types, such as CHAR, FLOAT, DATE, and so on.
    • BLOB (Binary Large Object)
    • CLOB (Character Large Object)
  • Constructed types-types based on a given base type
    • REF(structured type)-a reference to the specified SQL structured type
    • ARRAY[n]-an array of n elements that are all one data type
  • User-defined types (UDTs)-new types created with the SQL commandþCREATE TYPE
    • Distinct type-a new type based on the representation of a single built-in type
    • Structured type-a new type containing multiple attributes, each of which may be either a built-in or a user-defined data type
  • Locator types-types that are logical pointers to data that resides on the database server
    • LOCATOR(structured type)
    • LOCATOR(array)
    • LOCATOR(blob)
    • LOCATOR(clob)

A.4.2 Summary of Support for the SQL99 Data Types

The JDBC 2.0 core API supports the SQL 99 data types by means of the following new interfaces, methods, and fields.

  • New interfaces for the new data types. The SQL99 types are mapped by the following JDBC 2.0 core API interfaces:
    • java.sql.Array
    • java.sql.Blob
    • java.sql.Clob
    • java.sql.Ref
    • java.sql.Struct
  • Interfaces that support customizing the mapping of UDTs (SQL structured and distinct types) into classes in the Java programming language
    • SQLData
    • SQLInput
    • SQLOutput
  • Methods added to existing interfaces in order to retrieve, store, and update the SQL99 types
    • new getter methods in the ResultSet interface to retrieve SQL99 type column values from a result set
    • new getter methods in the CallableStatement interface to retrieve SQL99 type values in output parameters
    • new setter methods in the PreparedStatement interface to set a SQL99 type column value
    • new updater methods in the ResultSet interface to update values programmatically
  • Methods in the DatabaseMetaData and ResultSetMetaData interfaces for getting metadata about the SQL99 data types
  • Fields (constants) added to the class java.sql.Types to support new data types and persistent storage
    • DISTINCT
    • STRUCT
    • ARRAY
    • BLOB
    • CLOB
    • REF
    • JAVA_OBJECT

A.4.3 Mapping of the SQL99 Types

The JDBC API does not try to replicate the SQL99 types exactly; rather, its goal is to map them to types in the Java programming language so that they retain their functionality and are convenient to use. For example, SQL99 has what are called locator types, which are used on a client to designate data that is stored on a database server. Locators can be very useful for dealing with data that is large because they allow the data to be manipulated without having to be materialized on the client machine. SQL99 includes locators for the types ARRAY, BLOB, CLOB and structured types. The JDBC API does not include locators for these types directly (and not at all for structured types) but rather provides interfaces that are implemented such that the driver and DBMS use the appropriate locators behind the scenes. The result is that a developer using the JDBC API to access an SQL ARRAY, BLOB, or CLOB value need not even be aware of locators.

The following SQL99 types are mapped to interfaces in the Java programming language:

  • ARRAY-mapped to java.sql.Array
  • BLOB-mapped to java.sql.Blob
  • CLOB-mapped to java.sql.Clob
  • REF-mapped to java.sql.Ref
  • an SQL structured type-mapped to java.sql.Struct

Distinct types are not mapped to an interface because they are based on a single built-in type and thus can simply be mapped to the standard mapping for that built-in type. For example, the following is an SQL statement that creates the new type MONEY.

CREATE TYPE MONEY AS NUMERIC(10, 2)

This new UDT is based on the data type NUMERIC, which maps to java.math.BigDecimal, so the type MONEY maps to java.math.BigDecimal. This means that a value of type MONEY would be retrieved with the method getBigDecimal, stored with the method setBigDecimal, and updated with the method updateBigDecimal.

A.4.4 SQL Locators

An SQL LOCATOR is a logical pointer to data that resides on a database server. It typically refers to data that is too large to materialize on the client, such as images or audio. Locators exist only in a client environment, and their existence is transient. A standard implementation will use locators internally for instances of the Blob, Clob, and Array interfaces. This means that Blob, Clob, and Array objects contain a locator that points to the data on the server rather than containing the data itself. Programmers operating on Blob, Clob, and Array instances are actually operating on the database objects they represent. This ability to operate on large database objects without bringing their data to the client is a major plus in performance.

Note that the JDBC API does not call for using the SQL LOCATOR(structured type). In a standard implementation, a Struct object contains the data of the structured type that it maps and is not implemented internally as a locator, as are Blob, Clob, and Array objects.

A.4.5 Support for Storing Java Objects

The JDBC API has always supported persistent storage of objects defined in the Java programming language through the methods getObject and setObject. But, of course, persistent storage of Java objects does not actually occur unless a DBMS also supports it. Up to this point, support was limited, but a new generation of DBMSs that recognize Java objects as a data type is emerging. In these DBMSs, termed Java relational DBMSs, an instance of a Java class can be stored as a column value in a database table.

[Top] [Prev] [Next] [Bottom]

Copyright © 2001, Sun Microsystems, Inc. All rights reserved.


JDBC-ODBC Bridge Enhancements

JDBCTM-ODBC Bridge Enhancements

 Documentation Contents
JDBC

The JDBC-ODBC Bridge allows applications written in the JavaTM programming language to use the JDBCTM API with many existing ODBC drivers. The Bridge is itself a driver based on JDBC technology ("JDBC driver") that is defined in the class sun.jdbc.odbc.JdbcOdbcDriver. The Bridge defines the JDBC sub protocol odbc.

Status of the JDBC-ODBC Bridge

The JDBC-ODBC Bridge should be considered a transitional solution. Sun Microsystems and DataDirect Technologies are working to make the Bridge more reliable and robust, but they do not consider it a supported product. With the development of pure Java JDBC drivers, the JDBC-ODBC Bridge should become unnecessary.

Why not just use ODBC?

The JDBC-ODBC Bridge offers several advantages over "naked" ODBC.
  • The ODBC API is strongly oriented toward C/C++ programmers. The JDBC-ODBC Bridge makes it unnecessary for programmers using the Java programming language to deal with non-Java language concepts.
  • The ODBC API is extremely complex and intermingles high level and low level functions. The JDBC-ODBC Bridge allows the programmer to rely on the JDBC API, which is relatively simple and easy to learn.
  • The JDBC-ODBC Bridge lets a program deal with ODBC through a standardized JDBC interface. That helps a program avoid being tied to ODBC when a better solution comes along.

Why use ODBC at all?

The ideal is "Pure Java": no native code, no platform dependent features. But you may need to begin your development effort right away, without waiting for your DBMS to offer a Java only JDBC driver. Partly native drivers, such as the JDBC-ODBC Bridge, let you create programs that easily adapt to Pure Java drivers as they become available.

What's New with the JDBC-ODBC Bridge?

  • A jdbc:odbc: connection can now have a charSet property, to specify a Character Encoding Scheme other than the client default. For possible values, see the JDK 1.1 Internationalization specification on the Java Software Web Site.

    • The following code fragment shows how to set 'Big5' as the character set for all character data.
           // Load the JDBC-ODBC bridge driver
       Class.forName(sun.jdbc.odbc.JdbcOdbcDriver) ;

       // setup the properties
       java.util.Properties prop = new java.util.Properties();
       prop.put("charSet", "Big5");
       prop.put("user", username);
       prop.put("password", password);

       // Connect to the database
       con = DriverManager.getConnection(url, prop);
  • The bridge now supports JDBC 2.0 features, which includes batch updates, scrollable cursors, and so on.
  • JDBC-ODBC bridge now offers most of the features required for a J2EE compatible JDBC driver.
  • Sample implementations of DataSource and ConnectionPoolDataSource are available with the JDBC-ODBC bridge.
  • CallableStatement OUT/INOUT parameter handling has been improved.
  • Automatic garbage collection of unclosed Statement objects has been implemented.
  • Improved support for updatable Resultset objects has been implemented.
  • Additional robustness and reliability checking as been introduced.

New DataSource Implementations in the JDBC-ODBC Bridge

Implementations of javax.sql.DataSource and javax.sql.ConnectionPoolDataSource are now available. Both are in the sun.jdbc.odbc.ee package. The following code fragment illustrates how to set DataSource properties. The last two lines use JNDI API to bind the DataSource object ds to "jdbc/OdbcDB1". Assume that the DataSource object is targeting an ODBC DSN "dsn1" connecting to an Oracle Database.
            // Establish the DataSource object instance
            sun.jdbc.odbc.ee.DataSource ds = new sun.jdbc.odbc.ee.DataSource();
            // Provide user credentials and database name
            ds.setUser("scott");
            ds.setPassword("tiger");
            ds.setDatabaseName("dsn1");
            ds.setCharSet("..."); // optional property
            ds.setLoginTimeout(100); // optional property
            // Establish initial context and bind to the datasource target
            InitialContext ic = new InitialContext();
            ic.bind("jdbc/OdbcDB1",ds);
In the preceding code, note that some properties are optional while some are required. Properties such as port number and role name are not implemented in the JDBC-ODBC bridge DataSource implementations as these properties are not applicable to ODBC paradigm.

Continuing the previous example, the following code fragment demonstrates retrieving the DataSource object by looking up the JNDI name "jdbc/OdbcDB1". With the DataSource object that is obtained, the code then activates tracing and creates two connections.

            // Get the initial context of JNDI and lookup the datasource.
            InitialContext ic = new InitialContext();
            javax.sql.DataSource ds1 = (javax.sql.DataSource) ic.lookup("jdbc/OdbcDB1");
            // Set the optional printwriter where the trace log is to be directed.
            ds1.setLogWriter(new PrintWriter(new FileOutputStream("/tmp/datasource.log")));
            Connection con1 = ds1.getConnection();
            Connection con2 = ds1.getConnection("system","manager");
The implementation of javax.sql.ConnectionPoolDataSource uses an underlying pool of JDBC-ODBC connections. A ConnectionPoolDataSource object is used to create PooledConnection objects, which are in turn used to get Connection objects. From the user's viewpoint, the Connection object is just like any other connection.

The following code fragment creates the ConnectionPoolDataSource object cpds and sets its properties. The final two lines use JNDI API to bind cpds to "jdbc/OdbcPool", which can later be supplied to the method InitialContext.lookup to retrieve cpds.

            // Establish ConnectionPoolDataSource instance
            sun.jdbc.odbc.ee.ConnectionPoolDataSource cpds =
                new sun.jdbc.odbc.ee.ConnectionPoolDataSource("jdbc/OdbcPool");
            // Provide user credentials and database name
            cpds.setUser("scott");
            cpds.setPassword("tiger");
            cpds.setDatabaseName("dsn1");
            cpds.setCharSet("...") // optional property
            cpds.setLoginTimeout(100); // optional property
            cpds.setMinPoolSize("10");
            cpds.setInitialPoolSize("15");
            cpds.setMaxPoolSize("20");
            cpds.setMaxIdleTime("300");
            cpds.setTimeoutFromPool("600");
            // Maintenance interval of the pool. A maintenance thread will remove
            // unwanted connections and cleanup the pool at the interval specified.
            // This cannot be zero.
            cpds.setMaintenanceInterval("900");
            InitialContext ic = new InitialContext();
            ic.bind("jdbc/OdbcPool",cpds);
In all cases in order get the ConnectionPoolDataSource to function as a pooled datasource, it is the responsibility of the application to configure the pool as described in the code example above. The default behavior of pooled datasource uses a zero minimum, initial and maximum pool sizes. Note that the JDBC-ODBC bridge implementation of ConnectionPoolDataSource does not yet include the pooling of Statement objects or the property propertyCycle.

The following code fragment shows how to use a ConnectionPoolDataSource object as simply a DataSource object. This is done by doing a JNDI lookup of "jdbc/OdbcPool" and casting it to a DataSource object instead of to a ConnectionPoolDataSource object.

            InitialContext ic = new InitialContext();
            javax.sql.DataSource ds1 = (javax.sql.DataSource) ic.lookup("jdbc/OdbcPool");
            // First getConnection will initializes the pool.
            Connection con1 = ds1.getConnection();
            Connection con2 = ds1.getConnection("system","manager");
            -------------
            -------------
            // An application need to close the connection explicitly. This will allow the pool to recycle the connection.
            con1.close();
            con2.close();
Using the implementation as a ConnectionPoolDataSource object is shown in the following line of code. Note that closing a PooledConnection object closes the actual physical connection, whereas closing a connection that was created from a PooledConnection object just returns it to the pool of connections.
            InitialContext ic = new InitialContext();
            javax.sql.ConnectionPoolDataSource cpds =
                (javax.sql.ConnectionPoolDataSource) ic.lookup("jdbc/OdbcPool");
            PooledConnection pc1 = cpds.getPooledConnection();
            Connection con1 = pc1.getConnection();
            PooledConnection pc2 = cpds.getPooledConnection("system","manager");
            Connection con2 = pc2.getConnection();
            -------------
            -------------
            // An application needs to close the connection explicitly. This will allow the pool to recycle the connection.
            con1.close();
            con2.close();
            Connection con3 = pc1.getConnection();
            Connection con4 = pc2.getConnection();
            -------------
            -------------
            // This will close the physical connection!
            pc1.close();
            pc2.close();
A pool of connections can be shut down in two ways. If the method shutDown is given the argument false, only those connections that are not being used will be closed. If the argument true is supplied, all connections will be closed immediately, regardless of whether they are being used or not.
            // Hot shutdown
            ((sun.jdbc.odbc.ee.ConnectionPoolDataSource) cpds).shutDown(true);
            or
            // Cold shutdown
            ((sun.jdbc.odbc.ee.ConnectionPoolDataSource) cpds).shutDown(false);

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: jdbc-odbc@sun.com


 [Top] [Prev] [Next]

9 - JDBC-ODBC Bridge Driver

9.1 Obtaining a JDBC Driver

It is recommended that you obtain a commercial JDBC driver from a vendor such as your database vendor or your database middleware vendor. Check the list of drivers currently available.

The JDBC-ODBC Bridge driver is recommended only for experimental use or when no other alternative is available.

9.2 JDBC-ODBC Bridge

If possible, use a Pure Java JDBC driver instead of the Bridge and an ODBC driver. This completely eliminates the client configuration required by ODBC. It also eliminates the potential that the Java VM could be corrupted by an error in the native code brought in by the Bridge (that is, the Bridge native library, the ODBC driver manager library, the ODBC driver library, and the database client library).

The JDBC-ODBC Bridge driver is recommended for use in prototyping efforts and for cases where no other JDBC technology-based driver exists. If a commercial, all-Java JDBC driver is available, we recommend that it be used instead of the Bridge.

9.2.1 What Is the JDBC-ODBC Bridge?

The JDBC-ODBC Bridge is a JDBC driver that implements JDBC operations by translating them into ODBC operations. To ODBC it appears as a normal application program. The Bridge implements JDBC for any database for which an ODBC driver is available. The Bridge is implemented as the sun.jdbc.odbc Java package and contains a native library used to access ODBC. The Bridge is a joint development of Merant and Java Software.

9.2.2 ODBC Compatibility and ODBC Versions Supported

On Solaris, the JDBC 2.0 bridge must be used with an ODBC 3.x driver manager. The bridge supports both ODBC 2.x and ODBC 3.x drivers, but has been tested with only ODBC 3.x drivers.

On NT, the JDBC 2.0 bridge supports the ODBC 2.x and ODBC 3.x driver manager and drivers. The JDBC 2.0 bridge has been tested only with an ODBC 3.x driver manager and with both ODBC 2.x and 3.x drivers.

Merant recommends that the JDBC 2.0 bridge be used with version 3.5 or higher of Merant's DataDirect ODBC drivers.

9.2.3 The Bridge Implementation

The Bridge is implemented in Java and uses Java native methods to call ODBC.

9.2.4 Installation

The Bridge is installed automatically with the Java 2 SDK, Standard Edition, as package sun.jdbc.odbc. See your ODBC driver vendor for information on installing and configuring ODBC. No special configuration is required for the Bridge. See your database vendor for client installation and configuration information. On Solaris, some ODBC driver managers name their libs libodbcinst.so and libodbc.so. The Bridge expects these libraries to be named libodbcinst.so.1 and libodbc.so.1, so symbolic links for these names must be created.

9.3 Using the Bridge

The Bridge is used by opening a JDBC connection using a URL with the odbc subprotocol. See below for URL examples. Before a connection can be established, the bridge driver class, sun.jdbc.odbc.JdbcOdbcDriver, must either be added to the java.lang.System property named jdbc.drivers, or it must be explicitly loaded using the Java class loader. Explicit loading is done with the following line of code:

    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
When loaded, the ODBC driver (like all good JDBC drivers) creates an instance of itself and registers this with the JDBC driver manager.

9.3.1 Using the Bridge from an Applet

JDBC used with a Pure Java JDBC driver works well with applets. The Bridge driver does not work well with applets.

9.3.2 Most Browsers Do Not Support the Bridge

Since the Bridge is an optional component of the Java 2 SDK, Standard Edition, it may not be provided by a browser. Even if it is provided, only trusted applets (those allowed to write to files) will be able to use the Bridge. This is required in order to preserve the security of the applet sandbox. Finally, even if the applet is trusted, ODBC and the DBMS client library must be configured on each client.

9.3.3 Tested Configurations

From Solaris, we have used the Bridge to access Oracle 8.1.5 using version 3.5 of Merant's ODBC drivers. From NT, we have used the Bridge to access SQL Server 6.x using the latest ODBC driver from Microsoft.

9.3.4 ODBC Drivers Known to Work with the Bridge

ODBC drivers are available for Oracle, Sybase, Informix, Microsoft SQL Server, and Ingres. The MERANT ODBC driver suite should be completely compatible with the JDBC-ODBC Bridge. To evaluate or purchase MERANT ODBC drivers, please contact MERANT DataDirect Sales at 1-800-547-4000 Option 2 or via the World Wide Web at http:\\www.merant.com. The MS SQL Server driver has also been used successfully on NT. Many other ODBC drivers will likely work.

9.3.5 What Is the JDBC URL Supported by the Bridge?

The Bridge driver uses the odbc subprotocol. URLs for this subprotocol are of the form:

    jdbc:odbc:<data-source-name>[<attribute-name>=<attribute-value>]*
For example:

    jdbc:odbc:sybase
    jdbc:odbc:mydb;UID=me;PWD=secret
    jdbc:odbc:ora123;Cachesize=300

9.3.6 Debugging

The Bridge provides extensive tracing when DriverManager tracing is enabled. The following line of code enables tracing and sends it to standard out:

     java.sql.DriverManager.setLogStream(java.lang.System.out);

9.4 New JDBC 2.0 API Features Supported by the Bridge

The JDBC-ODBC Bridge driver in this release supports the following new features in the JDBC 2.0 API:

  • batch updates
  • updatable result sets
  • scrollable result sets
  • the new BigDecimal methods
  • the new Date, Time, and Timestamp methods

The current release of the Bridge supports multi-threaded ODBC drivers and contains numerous bug fixes.

[Top] [Prev] [Next]

jdbc@wombat.eng.sun.com or jdbc-odbc@wombat.eng.sun.com
Copyright © 1996 - 1999 Sun Microsystems, Inc. All rights reserved.


 [Top] [Prev] [Next]

CallableStatement

NOTE: The material in this chapter is based on JDBCtm API Tutorial and Reference, Second Edition: Universal Data Access for the Javatm 2 Platform, published by Addison Wesley as part of the Java series, ISBN 0-201-43328-1.

7.1 CallableStatement Overview

A CallableStatement object provides a way to call stored procedures in a standard way for all RDBMSs. A stored procedure is stored in a database; the call to the stored procedure is what a CallableStatement object contains. This call is written in an escape syntax that may take one of two forms: one form with a result parameter, and the other without one. A result parameter, a kind of OUT parameter, is the return value for the stored procedure. Both forms may have a variable number of parameters used for input (IN parameters), output (OUT parameters), or both (INOUT parameters). A question mark serves as a placeholder for a parameter.

The syntax for invoking a stored procedure using the JDBC API is shown here. Note that the square brackets indicate that what is between them is optional; they are not themselves part of the syntax.

{call procedure_name[(?, ?, ...)]}

The syntax for a procedure that returns a result parameter is:

{? = call procedure_name[(?, ?, ...)]}

The syntax for a stored procedure with no parameters would look like this:

{call procedure_name}

Normally, anyone creating a CallableStatement object would already know that the DBMS being used supports stored procedures and what those procedures are. If one needed to check, however, various DatabaseMetaData methods will supply such information. For instance, the method supportsStoredProcedures will return true if the DBMS supports stored procedure calls, and the method getProcedures will return a description of the stored procedures available.

CallableStatement inherits Statement methods, which deal with SQL statements in general, and it also inherits PreparedStatement methods, which deal with IN parameters. All of the methods defined in CallableStatement deal with OUT parameters>OUT parameters or the output aspect of INOUT parameters: registering the JDBC types of the OUT parameters, retrieving values from them, or checking whether a returned value was JDBC NULL. Whereas the getXXX methods defined in ResultSet retrieve values from a result set, the getXXX methods in CallableStatement retrieve values from the OUT parameters and/or return value of a stored procedure.

7.1.1 Creating a CallableStatement Object

CallableStatement objects are created with the Connection method prepareCall. The following example, in which con is an active JDBC Connection object, creates an instance of CallableStatement.

CallableStatement cstmt = con.prepareCall(
    "{call getTestData(?, ?)}");

The variable cstmt contains a call to the stored procedure getTestData, which has two input parameters and no result parameter. Whether the ? placeholders are IN, OUT, or INOUT parameters depends on the stored procedure getTestData. This instance of a CallableStatement object was created using JDBC 1.0 API; consequently, any query in the stored procedure called by cstmt will produce a default ResultSet object (one that is non-scrollable and non-updatable).

The JDBC 2.0 API provides the means to create CallableStatement objects that can produce ResultSet objects that are scrollable and updatable, as the following code fragment demonstrates.

String sql = "{call getTestData(?, ?)}";
CallableStatement cstmt2 = con.prepareCall(sql,
    ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);

The variable cstmt2 contains the same call to the stored procedure TestData that cstmt does, but with cstmt2, any resultSet objects that TestData produces can be updated and are scrollable (though they will not be sensitive to updates made while they are open). Explanations for the constants used to indicate scrollability and updatability are given in the chapter "ResultSet."

7.1.2 IN Parameters

Passing in any IN parameter values to a CallableStatement object is done using the setXXX methods inherited from PreparedStatement. The type of the value being passed in determines which setXXX method to use (setFloat to pass in a float value, setBoolean to pass in a boolean, and so on). Of the programs that use parameters, the vast majority use only IN parameters.

7.1.3 Making Batch Updates

The ability to make batch updates is the same for CallableStatement objects as it is for PreparedStatement objects. In fact, a CallableStatement object is restricted to the same functionality that a PreparedStatement object has. More precisely, when using the batch update facility, a CallableStatement object can call only stored procedures that take input parameters or no parameters at all. Further, the stored procedure must return an update count. The CallableStatement.executeBatch method (inherited from PreparedStatement) will throw a BatchUpdateException if the stored procedure returns anything other than an update count or takes OUT or INOUT parameters.

The following code fragment illustrates using the batch update facility to associate two sets of parameters with a CallableStatement object.

CallableStatement cstmt = con.prepareCall(
            "{call updatePrices(?, ?)}");
cstmt.setString(1, "Colombian");
cstmt.setFloat(2, 8.49f);
cstmt.addBatch();

cstmt.setString(1, "Colombian_Decaf");
cstmt.setFloat(2, 9.49f);
cstmt.addBatch();

int [] updateCounts = cstmt.executeBatch();

The variable cstmt contains a call to the stored procedure updatePrices with two sets of parameters associated with it. When cstmt is executed, two update statements will be executed together as a batch: one with the parameters Colombian and 8.49f, and a second one with the parameters Colombian_Decaf and 9.49f. An f after a number, as in 8.49f, tells the Java compiler that the value is a float; otherwise, the compiler assumes that a number with decimal digits is a double and will not allow it to be used as a float.

7.1.4 OUT Parameters

If the stored procedure returns OUT parameters, the JDBC type of each OUT parameter must be registered before the CallableStatement object can be executed. This is necessary because some DBMSs require the SQL type (which the JDBC type represents), not because JDBC requires it. JDBC types, a set of generic SQL type identifiers that represent the most commonly used SQL types, are explained fully in the chapter "Mapping SQL and Java Types" on page 85.

Registering the JDBC type is done with the method registerOutParameter. Then after the statement has been executed, CallableStatement's getXXX methods can be used to retrieve OUT parameter values. The correct CallableStatement.getXXX method to use is the type in the Java programming language that corresponds to the JDBC type registered for that parameter. (The standard mapping from JDBC types to Java types is shown in Table 8.1 on page 105.) In other words, registerOutParameter uses a JDBC type (so that it matches the data type that the database will return), and getXXX casts this to a Java type.

To illustrate, the following code registers the OUT parameters, executes the stored procedure called by cstmt, and then retrieves the values returned in the OUT parameters. The method getByte retrieves a Java byte from the first OUT parameter, and getBigDecimal retrieves a java.math.BigDecimal object (with three digits after the decimal point) from the second OUT parameter. The method executeQuery is used to execute cstmt because the stored procedure that it calls returns a result set.

CallableStatement cstmt = con.prepareCall(
    "{call getTestData(?, ?)}");
cstmt.registerOutParameter(1, java.sql.Types.TINYINT);
cstmt.registerOutParameter(2, java.sql.Types.DECIMAL, 3);
ResultSet rs = cstmt.executeQuery();
// . . . retrieve result set values with rs.getXXX methods
byte x = cstmt.getByte(1);
java.math.BigDecimal n = cstmt.getBigDecimal(2);

Unlike ResultSet, CallableStatement does not provide a special mechanism for retrieving large OUT values incrementally. More specifically, it does not have getXXX methods for streams of data, such as getAsciiStream or getBinary-Stream. However, the JDBC 2.0 API provides CallableStatement methods for retrieving SQL3 datatypes as OUT or INOUT parameters, which includes the methods getBlob and getClob for retrieving binary large objects and character large objects.

7.1.5 Numbering of Parameters

When a method takes an int specifying which parameter to act upon (setXXX, getXXX, and registerOutParameter), that int refers to ? placeholder parameters only, with numbering starting at one. The parameter number does not refer to literal parameters that might be supplied to a stored procedure call. For example, the following code fragment illustrates a stored procedure call with one literal parameter and one ? parameter:

CallableStatement cstmt = con.prepareCall(
        "{call getTestData(25, ?)}");
cstmt.registerOutParameter(1, java.sql.Types.TINYINT);

In this code, the first argument to registerOutParameter, the int 1, refers to the first ? parameter (and in this case, the only ? parameter). It does not refer to the literal 25, which is the first parameter to the stored procedure.

7.1.6 INOUT Parameters

A parameter that supplies input as well as accepts output (an INOUT parameter) requires a call to the appropriate setXXX method (inherited from PreparedStatement) in addition to a call to the method registerOutParameter. The setXXX method sets a parameter's value as an input parameter, and the method registerOutParameter registers its JDBC type as an output parameter. The setXXX method provides a Java value that the driver converts to a JDBC value before sending it to the database. The JDBC type of this IN value and the JDBC type supplied to the method registerOutParameter should be the same. Then, to retrieve the output value, a corresponding getXXX method is used. For example, a parameter whose Java type is byte should use the method setByte to assign the input value, should supply a TINYINT as the JDBC type to registerOutParameter, and should use getByte to retrieve the output value. ("Mapping SQL and Java Types" on page 85 contains tables of type mappings.)

The following example assumes that there is a stored procedure reviseTotal whose only parameter is an INOUT parameter. The method setByte sets the parameter to 25, which the driver will send to the database as a JDBC TINYINT. Next registerOutParameter registers the parameter as a JDBC TINYINT. After the stored procedure is executed, a new JDBC TINYINT value is returned, and the method getByte will retrieve this new value as a Java byte. Since the stored procedure called in this example returns an update count, the method executeUpdate is used.

CallableStatement cstmt = con.prepareCall(
        "{call reviseTotal(?)}");
cstmt.setByte(1, (byte)25);
cstmt.registerOutParameter(1, java.sql.Types.TINYINT);
cstmt.executeUpdate();
byte x = cstmt.getByte(1);

7.1.7 Retrieve OUT Parameters after Results

Because of limitations imposed by some DBMSs, it is recommended that for maximum portability, all of the results in a ResultSet object generated by the execution of a CallableStatement object should be retrieved before OUT parameters are retrieved. When all values have been retrieved from a result set, the method ResultSet.next will return false.

If a CallableStatement object returns multiple ResultSet objects (which is possible only if it is executed with a call to the method execute), all of the results should be retrieved before OUT parameters are retrieved. In this case, to be sure that all results have been accessed, the Statement methods getResultSet, getUpdateCount, and getMoreResults need to be called until there are no more results. When all results have been exhausted, the method getMoreResults returns false, and the method getUpdateCount returns -1.

After all values have been retrieved from ResultSet objects (using ResultSet.getXXX methods), and after it has been determined that there are no more update counts, values from OUT parameters can be retrieved (using CallableStatement.getXXX methods).

7.1.8 Retrieving NULL Values as OUT Parameters

The value returned to an OUT parameter may be JDBC NULL. When this happens, the JDBC NULL value will be converted so that the value returned by a getXXX method will be null, 0, or false, depending on the getXXX method type. As with ResultSet objects, the only way to know if a value of 0 or false was originally JDBC NULL is to test it with the method wasNull, which returns true if the last value read by a getXXX method was JDBC NULL, and false otherwise.

[Top] [Prev] [Next]

Copyright © 1999, Sun Microsystems, Inc. All rights reserved.


 [Top] [Prev] [Next]

Connection

NOTE: The material in this chapter is based on JDBCtm API Tutorial and Reference, Second Edition: Universal Data Access for the Javatm 2 Platform, published by Addison Wesley as part of the Java series, ISBN 0-201-43328-1.

2.1 Connection Overview

A Connection object represents a connection with a database. A connection session includes the SQL statements that are executed and the results that are returned over that connection. A single application can have one or more connections with a single database, or it can have connections with many different databases.

A user can get information about a Connection object's database by invoking the Connection.getMetaData method. This method returns a DatabaseMetaData object that contains information about the database's tables, the SQL grammar it supports, its stored procedures, the capabilities of this connection, and so on.

2.1.1 Opening a Connection

The traditional way to establish a connection with a database is to call the method DriverManager.getConnection. This method takes a string containing a URL. The DriverManager class, referred to as the JDBC management layer, attempts to locate a driver that can connect to the database represented by that URL. The DriverManager class maintains a list of registered Driver classes, and when the method getConnection is called, it checks with each driver in the list until it finds one that can connect to the database specified in the URL. The Driver method connect uses this URL to actually establish the connection.

A user can bypass the JDBC management layer and call Driver methods directly. This could be useful in the rare case that two drivers can connect to a database and the user wants to explicitly select a particular driver. Normally, however, it is much easier to just let the DriverManager class handle opening a connection.

The following code exemplifies opening a connection to a database located at the URL jdbc:odbc:wombat with a user ID of oboy and 12Java as the password:

String url = "jdbc:odbc:wombat";
Connection con = DriverManager.getConnection(url, "oboy", "12Java");

The JDBC 2.0 Standard Extension API provides the DataSource interface as an alternative to the DriverManager for establishing a connection. When a DataSource class has been implemented appropriately, a DataSource object can be used to produce Connection objects that participate in connection pooling and/or Connection objects that can participate in distributed transactions. See the chapter "DataSource" for more information and to see example code for creating a connection using a DataSource object. This chapter also explains why using a DataSource object is the preferred alternative for creating a connection.

An application uses a Connection object produced by a DataSource object in essentially the same way it uses a Connection object produced by the DriverManager. There are some differences, however. If the Connection object is a pooled connection, an application should include a finally block to assure that the connection is closed even if an exception is thrown. That way a valid connection will always be put back into the pool of available connections.

If a Connection object is part of a distributed transaction, an application should not call the methods Connection.commit or Connection.rollback, nor should it turn on the connection's auto-commit mode. These would interfere with the transaction manager's handling of the distributed transaction.

2.1.2 URLs in General Use

When an application uses the DriverManager to create a Connection object, it must supply a URL to the DriverManager.getConnection method. Since URLs often cause some confusion, we will first give a brief explanation of URLs in general and then go on to a discussion of JDBC URLs.

A URL (Uniform Resource Locator) gives information for locating a resource on the Internet. It can be thought of as an address.

The first part of a URL specifies the protocol used to access information, and it is always followed by a colon. Some common protocols are ftp, which specifies "file transfer protocol," and http, which specifies "hypertext transfer protocol." If the protocol is file, it indicates that the resource is in a local file system rather than on the Internet.

      ftp://javasoft.com/docs/JDK-1_apidocs.zip
      http://java.sun.com/products/JDK/CurrentRelease
      file:/home/haroldw/docs/tutorial.html

The rest of a URL, everything after the first colon, gives information about where the data source is located. If the protocol is file, the rest of the URL is the path for the file. For the protocols ftp and http, the rest of the URL identifies the host and may optionally give a path to a more specific site. For example, here is the URL for the Java Software home page. This URL identifies only the host:

http://www.java.sun.com

By navigating from this home page, you can go to many other pages, one of which is the JDBC home page. The URL for the JDBC home page is more specific and looks like this:

http://www.java.sun.com/products/jdbc

2.1.3 JDBC URLs

A JDBC URL provides a way of identifying a data source so that the appropriate driver will recognize it and establish a connection with it. Driver writers are the ones who actually determine what the JDBC URL that identifies a particular driver will be. Users do not need to worry about how to form a JDBC URL; they simply use the URL supplied with the drivers they are using. JDBC's role is to recommend some conventions for driver writers to follow in structuring their JDBC URLs.

Since JDBC URLs are used with various kinds of drivers, the conventions are, of necessity, very flexible. First, they allow different drivers to use different schemes for naming databases. The odbc subprotocol, for example, lets the URL contain attribute values (but does not require them).

Second, JDBC URLs allow driver writers to encode all necessary connection information within them. This makes it possible, for example, for an applet that wants to talk to a given database to open the database connection without requiring the user to do any system administration chores.

Third, JDBC URLs allow a level of indirection. This means that the JDBC URL may refer to a logical host or database name that is dynamically translated to the actual name by a network naming system. This allows system administrators to avoid specifying particular hosts as part of the JDBC name. There are a number of different network name services (such as DNS, NIS, and DCE), and there is no restriction about which ones can be used.

The standard syntax for JDBC URLs is shown here. It has three parts, which are separated by colons.

    jdbc:<subprotocol>:<subname>

The three parts of a JDBC URL are broken down as follows:

  1. jdbc-the protocol. The protocol in a JDBC URL is always jdbc.

  2.  <subprotocol>-the name of the driver or the name of a database connectivity mechanism, which may be supported by one or more drivers. A prominent example of a subprotocol name is odbc, which has been reserved for URLs that specify ODBC-style data source names. For example, to access a database through a JDBC-ODBC bridge, one might use a URL such as the following:

        jdbc:odbc:fred

In this example, the subprotocol is odbc, and the subname fred is a local ODBC data source.

    If one wants to use a network name service (so that the database name in the JDBC URL does not have to be its actual name), the naming service can be the subprotocol. So, for example, one might have a URL like:

        jdbc:dcenaming:accounts-payable

In this example, the URL specifies that the local DCE naming service should resolve the database name accounts-payable into a more specific name that can be used to connect to the real database.

  3. <subname>-a way to identify the data source. The subname can vary, depending on the subprotocol, and it can have any internal syntax the driver writer chooses, including a subsubname. The point of a subname is to give enough information to locate the data source. In the previous example, fred is enough because ODBC provides the remainder of the information. A data source on a remote server requires more information, however. If the data source is to be accessed over the Internet, for example, the network address should be included in the JDBC URL as part of the subname and should adhere to the following standard URL naming convention:

         //hostname:port/subsubname

Supposing that dbnet is a protocol for connecting to a host on the Internet, a JDBC URL might look like this:

        jdbc:dbnet://wombat:356/fred

2.1.4	 The odbc Subprotocol

The subprotocol odbc is a special case. It has been reserved for URLs that specify ODBC-style data source names and has the special feature of allowing any number of attribute values to be specified after the subname (the data source name). The full syntax for the odbc subprotocol is:

  jdbc:odbc:<data-source-name>[;<attribute-name>=<attribute-value>]*

Thus all of the following are valid jdbc:odbc names:

     jdbc:odbc:qeor7
     jdbc:odbc:wombat
     jdbc:odbc:wombat;CacheSize=20;ExtensionCase=LOWER
     jdbc:odbc:qeora;UID=kgh;PWD=fooey

2.1.5	 Registering Subprotocols

A driver developer can reserve a name to be used as the subprotocol in a JDBC URL. When the DriverManager class presents this name to its list of registered drivers, the driver for which this name is reserved should recognize it and establish a connection to the database it identifies. For example, "odbc" is reserved for the JDBC-ODBC Bridge. If there were a Miracle Corporation, it might want to register "miracle" as the subprotocol for the JDBC driver that connects to its Miracle DBMS so that no one else would use that name.

Java Software is acting as an informal registry for JDBC subprotocol names. To register a subprotocol name, send email to:

    jdbc@eng.sun.com

2.1.6	 Sending SQL Statements

Once a connection is established, it is used to pass SQL statements to its underlying database. The JDBC API does not put any restrictions on the kinds of SQL statements that can be sent; this provides a great deal of flexibility, allowing the use of database-specific statements or even non-SQL statements. It requires, however, that the user be responsible for making sure that the underlying database can process the SQL statements being sent and suffer the consequences if it cannot. For example, an application that tries to send a stored procedure call to a DBMS that does not support stored procedures will be unsuccessful and will generate an exception.

The JDBC API provides three interfaces for sending SQL statements to the database, and corresponding methods in the Connection interface create instances of them. The interfaces for sending SQL statements and the Connection methods that create them are as follows:

  1. Statement-created by the Connection.createStatement methods. A Statement object is used for sending SQL statements with no parameters.

  2. PreparedStatement-created by the Connection.prepareStatement methods. A PreparedStatement object is used for precompiled SQL statements. These can take one or more parameters as input arguments (IN parameters). PreparedStatement has a group of methods that set the value of IN parameters, which are sent to the database when the statement is executed. PreparedStatement extends Statement and therefore includes Statement methods. A PreparedStatement object has the potential to be more efficient than a Statement object because it has been precompiled and stored for future use. Therefore, in order to improve performance, a PreparedStatement object is sometimes used for an SQL statement that is executed many times.

  3. CallableStatement-created by the Connection.prepareCall methods. CallableStatement objects are used to execute SQL stored procedures-a group of SQL statements that is called by name, much like invoking a function. A CallableStatement object inherits methods for handling IN parameters from PreparedStatement; it adds methods for handling OUT and INOUT parameters.

The following list gives a quick way to determine which Connection method is appropriate for creating different types of SQL statements:

  • createStatement methods-for a simple SQL statement (no parameters)

  • prepareStatement methods-for an SQL statement that is executed frequently

  • prepareCall methods-for a call to a stored procedure

The versions of these methods that take no arguments create statements that will produce default ResultSet objects; that is, they produce result sets that are not scrollable and that cannot be updated. With the JDBC 2.0 API, it is possible to create statements that will produce result sets that are scrollable and/or updatable. This is done by using new versions of the methods createStatement, prepareStatement, and prepareCall that take additional parameters for specifying the type of result set and the concurrency level of the result set being created. In Chapter 5, "ResultSet," the section on the types of ResultSet objects on page 52 explains the different types of ResultSet objects and the constants that specify them. The section "Concurrency Types" on page  53 does the same for concurrency levels. "Creating Different Types of Result Sets" on page  55 gives examples of how to create ResultSet objects using the new versions of the Connection methods for creating statements.

2.1.7	 Transactions

A transaction consists of one or more statements that have been executed, completed, and then either committed or rolled back. When the method commit or rollback is called, the current transaction ends and another one begins.

Generally a new Connection object is in auto-commit mode by default, meaning that when a statement is completed, the method commit will be called on that statement automatically. In this case, since each statement is committed individually, a transaction consists of only one statement. If auto-commit mode has been disabled, a transaction will not terminate until the method commit or rollback is called explicitly, so it will include all the statements that have been executed since the last invocation of either commit or rollback. In this second case, all the statements in the transaction are committed or rolled back as a group.

The beginning of a transaction requires no explicit call; it is implicitly initiated after disabling auto-commit mode or after calling the methods commit or rollback. The method commit makes permanent any changes an SQL statement makes to a database, and it also releases any locks held by the transaction. The method rollback will discard those changes.

 Sometimes a user doesn't want one change to take effect unless another one does also. This can be accomplished by disabling auto-commit and grouping both updates into one transaction. If both updates are successful, then the commit method is called, making the effects of both updates permanent; if one fails or both fail, then the rollback method is called, restoring the values that existed before the updates were executed.

Most JDBC drivers will support transactions. In order to be designated JDBC Compliant, a JDBC driver must support transactions.

The JDBC 2.0 Standard Extension API makes it possible for Connection objects to be part of a distributed transaction, a transaction that involves connections to more than one DBMS server. When a Connection object is part of a distributed transaction, a transaction manager determines when the methods commit or rollback are called on it. Thus, when a Connection object is participating in a distributed transaction, an application should not do anything that affects when a connection begins or ends.

In order to be able to participate in distributed transactions, a Connection object must be produced by a DataSource object that has been implemented to work with the middle tier server's distributed transaction infrastructure. Unlike Connection objects produced by the DriverManager, a Connection object produced by such a DataSource object will have its auto-commit mode disabled by default. A standard implementation of a DataSource object, on the other hand, will produce Connection objects that are exactly the same as those produced by the DriverManager class.

2.1.8	 Transaction Isolation Levels

If a DBMS supports transaction processing, it will have some way of managing potential conflicts that can arise when two transactions are operating on a database at the same time. A user can specify a transaction isolation level to indicate what level of care the DBMS should exercise in resolving potential conflicts. For example, what happens when one transaction changes a value and a second transaction reads that value before the change has been committed or rolled back? Should that be allowed, given that the changed value read by the second transaction will be invalid if the first transaction is rolled back? A JDBC user can instruct the DBMS to allow a value to be read before it has been committed (a "dirty read") with the following code, where con is the current connection:

con.setTransactionIsolation(TRANSACTION_READ_UNCOMMITTED);

The higher the transaction isolation level, the more care is taken to avoid conflicts. The Connection interface defines five levels, with the lowest specifying that transactions are not supported at all and the highest specifying that while one transaction is operating on a database, no other transactions may make any changes to the data read by that transaction. TRANSACTION_READ_UNCOMMITTED, used in the previous example, is one level up from the lowest level. Typically, the higher the level of isolation, the slower the application executes (due to increased locking overhead and decreased concurrency between users). The developer must balance the need for performance with the need for data consistency when making a decision about what isolation level to use. Of course, the level that can actually be supported depends on the capabilities of the underlying DBMS.

When a new Connection object is created, its transaction isolation level depends on the driver, but normally it is the default for the underlying data source. A user may call the method setIsolationLevel to change the transaction isolation level, and the new level will be in effect for the rest of the connection session. To change the transaction isolation level for just one transaction, one needs to set it before executing any statements in the transaction and then reset it after the transaction terminates. Changing the transaction isolation level during a transaction is not recommended, for it will trigger an immediate call to the method commit, causing any changes up to that point to be made permanent.

2.1.9	 Freeing DBMS Resources

It is recommended that programmers explicitly close connections and statements they have created when they are no longer needed.

A programmer writing code in the Java programming language and not using any outside resources does not need to worry about memory management. The garbage collector automatically removes objects when they are no longer being used and frees the memory they were using. When memory is running low, it will recycle discarded objects, making the memory they currently occupy available for quick reuse.

However, if an application uses external resources, as it does when it accesses a DBMS with the JDBC API, the garbage collector has no way of knowing the status of those resources. It will still recycle discarded objects, but if there is lots of free memory in the Java heap, it may garbage collect infrequently, even though the (small) amount of Java garbage is holding open large amounts of expensive database resources. Therefore, it is recommended that programmers explicitly close all connections (with the method Connection.close) and statements (with the method Statement.close) as soon as they are no longer needed, thereby freeing DBMS resources as early as possible. This applies especially to applications that are intended to work with different DBMSs because of variations from one DBMS to another.

Note that the method Connection.isClosed is guaranteed to return true only when it is called after the method Connection.close has been called. As a result, a programmer cannot depend on this method to indicate whether a connection is valid or not. Instead, a typical JDBC client can determine that a connection is invalid by catching the exception that is thrown when a JDBC operation is attempted.

2.1.10	 Using Type Maps

The two new SQL3 data types that are user-defined types (UDTs), SQL structured types and DISTINCT types, can be custom mapped to a class in the Java programming language. Like all the SQL3 data types, they have standard mappings, but a programmer may create a custom mapping as well. The fact that there is a custom mapping for a particular UDT is declared in a java.util.Map object. This Map object may be the one that is associated with a connection, or it may be one that is passed to a method.

A programmer declares a custom mapping by adding an entry to a Map object. This entry must contain two things: (1) the name of the UDT to be mapped and (2) the Class object for the class in the Java programming language to which the UDT is to be mapped. The class itself, which must implement the SQLData interface, will contain the specific mappings.

Each Connection object created using a JDBC 2.0 driver that supports custom mapping will have an empty type map to which custom mappings may be added. This type map is an instance of the interface java.util.Map, which is new in the Java 2 platform and replaces java.util.Dictionary. Until custom map entries are added to this type map, all operations for STRUCT and DISTINCT values will use the standard mappings (the Struct interface for STRUCT values and the underlying type for DISTINCT values).

The following code fragment, in which con is a Connection object and ADDRESSES is an SQL structured type, demonstrates retrieving the type map associated with con and adding a new entry to it. After the type map is modified, it is set as the new type map for con.

java.util.Map map = con.getTypeMap();
map.put("SchemaName.ADDRESSES", Class.forName("Addresses"));
con.setTypeMap();

The Map object map, the type map associated with con, now contains at least one custom mapping (or more if any mappings have already been added). The programmer will have previously created the class Addresses, probably using a tool to generate it. Note that it is an error to supply a class that does not implement the interface SQLData. The class Addresses, which does implement SQLData, will have a field for each attribute in ADDRESSES, and whenever a value of type ADDRESSES is operated on by a method in the Java programming language, the default will be to map it to an instance of the class Addresses. The type map associated with a connection is the default type map in the sense that a method will use it if no other type map is explicitly passed to it.

Note that the name of the UDT should be the fully-qualified name. For some DBMSs, this will be of the form catalogName.schemaName.UDTName. Many DBMSs, however, do not use this form and, for example, use a schema name but no catalog name. The important thing is to use the form appropriate for a particular DBMS. The DatabaseMetaData methods getCatalogs, getCatalogTerm, getCatalogSeparator, getSchemas and getSchemaTerm give information about a DBMS's catalogs, schemas, preferred terms, and the separator it uses.

Instead of modifying the existing type map, an application can replace it with a completely different type map. This is done with the Connection method setTypeMap, as shown in the following code fragment. It creates a new type map, gives it two entries (each with an SQL UDT name and the class to which values of that type should be mapped), and then installs the new type map as the one associated with the Connection con.

java.util.Map newConnectionMap = new java.util.HashTable();
newConnectionMap.put(
     "SchemaName.UDTName1", Class.forName("className1"));
newConnectionMap.put(
     "SchemaName.UDTName2", Class.forName("className2"));
con.setTypeMap(newConnectionMap);

The Map object newConnectionMap now replaces the type map originally associated with the Connection con, and it will be used for custom type mappings unless it is itself replaced. Note that the example uses the default constructor for the class HashTable to create the new type map. This class is one of many implementations of java.util.Map provided in the Java 2 platform API, and one of the others could have been used as well.

In the previous examples, the type map associated with a connection was modified to contain additional mappings or set to be a different type map altogether. In either case, though, the connection's type map is the default for custom mapping JDBC types to types in the Java programming language. The next example will show how to supersede the connection's type map by supplying a method with a different type map.

Methods whose implementations may involve a custom mapping for UDTs have two versions, one that takes a type map and one that does not. If a type map is passed to one of these methods, the given type map will be used instead of the one associated with the connection. For example, the Array methods getArray and getResultSet have versions that take a type map and versions that do not. If a type map is passed to a method, it will map the array elements using the given type map. If no type map is specified, the method will use the type map associated with the connection.

The capability for supplying a type map to a method makes it possible for values of the same user-defined type to have different mappings. For example, if two applications are using the same connection and operating on the same column value, one could use the type map associated with the connection, and the other could use a different type map by supplying it as an argument to the appropriate method.

The following code fragment creates a new type map and provides it as a parameter to the Array method getArray.

java.util.Map arrayMap = new java.util.HashTable();
arrayMap.put("SchemaName.DIMENSIONS", Class.forName("Dimensions"));
Dimensions [] d = (Dimensions [])array.getArray(arrayMap);

In the second line, the new type map arrayMap is given an entry with the fully-qualified name of an SQL structured type (SchemaName.DIMENSIONS) and the Java class object (Class.forName("Dimensions")). This establishes the mapping between the Java type Dimensions and the SQL type DIMENSIONS. In the third line, arrayMap is specified as the type map to use for mapping the contents of this Array object, whose base type is SchemaName.DIMENSIONS.

The method getArray will materialize the elements of the SQL3 ARRAY value designated by array, with each element being mapped according to the mapping specified in arrayMap. In other words, each element, which is a value of type Schema.DIMENSIONS, will be translated to an instance of the class Dimensions by mapping the attributes of each DIMENSIONS value to the fields of a Dimensions object. If the base type of the array does not match the UDT named in arrayMap, the driver will convert the array's elements according to the standard mapping. If no type map is specified to the method getArray, the driver uses the mapping indicated in the connection's type map. If that type map has no entry for Schema.DIMENSIONS, the driver will instead use the standard mapping.

[Top] [Prev] [Next]

Copyright © 1999, Sun Microsystems, Inc.   All rights
reserved.


 [Top] [Prev] [Next] [Bottom]

DataSource

NOTE: The material in this chapter is based on JDBCtm API Tutorial and Reference, Second Edition: Universal Data Access for the Javatm 2 Platform, published by Addison Wesley as part of the Java series, ISBN 0-201-43328-1.

4.1 DataSource Overview

A DataSource object is the representation of a data source in the Java programming language. In basic terms, a data source is a facility for storing data. It can be as sophisticated as a complex database for a large corporation or as simple as a file with rows and columns. A data source can reside on a remote server, or it can be on a local desktop machine. Applications access a data source using a connection, and a DataSource object can be thought of as a factory for connections to the particular data source that the DataSource instance represents. The DataSource interface provides two methods for establishing a connection with a data source.

Using a DataSource object is the preferred alternative to using the DriverManager for establishing a connection to a data source. They are similar to the extent that the DriverManager class and DataSource interface both have methods for creating a connection, methods for getting and setting a timeout limit for making a connection, and methods for getting and setting a stream for logging.

Their differences are more significant than their similarities, however. Unlike the DriverManager, a DataSource object has properties that identify and describe the data source it represents. Also, a DataSource object works with a Javatm Naming and Directory Interfacetm (JNDI) naming service and is created, deployed, and managed separately from the applications that use it. A driver vendor will provide a class that is a basic implementation of the DataSource interface as part of its JDBC 2.0 or 3.0 driver product. What a system administrator does to register a DataSource object with a JNDI naming service and what an application does to get a connection to a data source using a DataSource object registered with a JNDI naming service are described later in this chapter.

Being registered with a JNDI naming service gives a DataSource object two major advantages over the DriverManager. First, an application does not need to hardcode driver information, as it does with the DriverManager. A programmer can choose a logical name for the data source and register the logical name with a JNDI naming service. The application uses the logical name, and the JNDI naming service will supply the DataSource object associated with the logical name. The DataSource object can then be used to create a connection to the data source it represents.

The second major advantage is that the DataSource facility allows developers to implement a DataSource class to take advantage of features like connection pooling and distributed transactions. Connection pooling can increase performance dramatically by reusing connections rather than creating a new physical connection each time a connection is requested. The ability to use distributed transactions enables an application to do the heavy duty database work of large enterprises.

Although an application may use either the DriverManager or a DataSource object to get a connection, using a DataSource object offers significant advantages and is the recommended way to establish a connection.

4.1.1 Properties

A DataSource object has a set of properties that identify and describe the real world data source that it represents. These properties include information like the location of the database server, the name of the database, the network protocol to use to communicate with the server, and so on. DataSource properties follow the JavaBeans design pattern and are usually set when a DataSource object is deployed.

To encourage uniformity among DataSource implementations from different vendors, the JDBC 2.0 API specifies a standard set of properties and a standard name for each property. The following table gives the standard name, the data type, and a description for each of the standard properties. Note that a DataSource implementation does not have to support all of these properties; the table just shows the standard name that an implementation should use when it supports a property.

Table 4.1 Standard Data Source Properties
Property Name | Type | Description
databaseName property (DataSource interface)>databaseName | String | the name of a particular database on a server
dataSourceName property (DataSource interface)>dataSourceName | String | the logical name for the underlying XADataSource or ConnectionPoolDataSource object; used only when pooling of connections or distributed transactions are implemented
description property (DataSource interface)>description | String | a description of this data source
networkProtocol property (DataSource interface)>networkProtocol | String | the network protocol used to communicate with the server
password property (DataSource interface)>password | String | the user's database password
portNumber property (DataSource interface)>portNumber | int | the port number where a server is listening for requests
roleName property (DataSource interface)>roleName | String | the initial SQL rolename
serverName property (DataSource interface)>serverName | String | the database server name
user property (DataSource interface)>user | String | the user's account name

A DataSource object will, of course, have to support all of the properties that the data source it represents needs for making a connection, but the only property that all DataSource implementations are required to support is the description property. This standardizing of properties makes it possible, for instance, for a utility to be written that lists available data sources, giving a description of each along with the other property information that is available.

A DataSource object is not restricted to using only those properties specified in Table 4.1. A vendor may add its own properties, in which case it should give each new property a vendor-specific name.

If a DataSource object supports a property, it must supply getter and setter methods for it. The following code fragment illustrates the methods that a DataSource object ds would need to include if it supports, for example, the property serverName.

ds.setServerName("my_database_server");
String serverName = ds.getServerName();

Properties will most likely be set by a developer or system administrator using a GUI tool as part of the installation of the data source. Users connecting to the data source do not get or set properties. This is enforced by the fact that the DataSource interface does not include the getter and setter methods for properties; they are supplied only in a particular implementation. The effect of including getter and setter methods in the implementation but not the public interface creates some separation between the management API for DataSource objects and the API used by applications. Management tools can get at properties by using introspection.

4.1.2 Using JNDI

JNDI provides a uniform way for an application to find and access remote services over the network. The remote service may be any enterprise service, including a messaging service or an application-specific service, but, of course, a JDBC application is interested mainly in a database service. Once a DataSource object is created and registered with a JNDI naming service, an application can use the JNDI API to access that DataSource object, which can then be used to connect to the data source it represents.

4.1.3 Creating and Registering a DataSource Object

A DataSource object is usually created, deployed, and managed separately from the Java applications that use it. For example, the following code fragment creates a DataSource object, sets its properties, and registers it with a JNDI naming service. Note that a DataSource object for a particular data source is created and deployed by a developer or system administrator, not the user. The class VendorDataSource would most likely be supplied by a driver vendor. (The code example in the next section will show the code that a user would write to get a connection.) Note also that a GUI tool will probably be used to deploy a DataSource object, so the following code, shown here mainly for illustration, is what such a tool would execute.

VendorDataSource vds = new VendorDataSource();

vds.setServerName("my_database_server");
vds.setDatabaseName("my_database");
vds.setDescription("the data source for inventory and personnel");

Context ctx = new InitialContext();

ctx.bind("jdbc/AcmeDB", vds);

The first four lines represent API from a vendor's class VendorDataSource, an implementation of the javax.sql.DataSource interface. They create a DataSource object, vds, and set its serverName, databaseName, and description properties. The fifth and sixth lines use JNDI API to register vds with a JNDI naming service. The fifth line calls the default InitialContext constructor to create a Java object that references the initial JNDI naming context. System properties, which are not shown here, tell JNDI which naming service provider to use. The last line associates vds with a logical name for the data source that vds represents.

The JNDI namespace consists of an initial naming context and any number of subcontexts under it. It is hierarchical, similar to the directory/file structure in many file systems, with the initial context being analogous to the root of a file system and subcontexts being analogous to subdirectories. The root of the JNDI hierarchy is the initial context, here represented by the variable ctx. Under the initial context there may be many subcontexts, one of which is jdbc, the JNDI subcontext reserved for JDBC data sources. (The logical data source name may be in the subcontext jdbc or in a subcontext under jdbc.) The last element in the hierarchy is the object being registered, analogous to a file, which in this case is a logical name for a data source. The result of the preceding six lines of code is that the VendorDataSource object vds is associated with jdbc/AcmeDB. The following section shows how an application uses this to connect to a data source.

4.1.4 Connecting to a Data Source

In the previous section, a DataSource object, vds, was given properties and bound to the logical name AcmeDB. The following code fragment shows application code that uses this logical name to connect to the database that vds represented. The code then uses the connection to print lists with the name and title of each member of the sales and customer service departments.

Context ctx = new InitialContext();

DataSource ds = (DataSource)ctx.lookup("jdbc/AcmeDB");
Connection con = ds.getConnection("genius", "abracadabra");
con.setAutoCommit(false);
PreparedStatement pstmt = con.prepareStatement(
                            "SELECT NAME, TITLE FROM PERSONNEL WHERE DEPT = ?");
pstmt.setString(1, "SALES");
ResultSet rs = pstmt.executeQuery();

System.out.println("Sales Department:");
while (rs.next()) {
        String name = rs.getString("NAME");
        String title = rs.getString("TITLE");
        System.out.println(name + "     " + title);
}
pstmt.setString(1, "CUST_SERVICE");
ResultSet rs = pstmt.executeQuery();

System.out.println("Customer Service Department:");
while (rs.next()) {
        String name = rs.getString("NAME");
        String title = rs.getString("TITLE");
        System.out.println(name + "     " + title);
}
rs.close();
pstmt.close();

con.close();

The first two lines use JNDI API; the third line uses DataSource API. After the first line creates an instance of javax.naming.Context for the initial naming context, the second line calls the method lookup on it to get the DataSource object associated with jdbc/AcmeDB. Recall that in the previous code fragment, the last line of code associated jdbc/AcmeDB with vds, so the object returned by the lookup method refers to the same DataSource object that vds represented. However, the return value for the method lookup is a reference to a Java Object, the most generic of objects, so it must be cast to the more narrow DataSource before it can be assigned to the DataSource variable ds.

At this point ds refers to the same data source that vds referred to previously, the database my_database on the server my_database_server. Therefore, in the third line of code, calling the method DataSource.getConnection on ds and supplying it with a user name and password is enough to create a connection to my_database.

The rest of the code fragment uses a single transaction to execute two queries and print the results of each query. The DataSource implementation in this case is a basic implementation included with the JDBC driver. If the DataSource class had been implemented to work with an XADataSource class, and the preceding code example was executed in the context of a distributed transaction, the code could not have called the method Connection.commit. It also would not have set the auto-commit mode to false because that would have been unnecessary. The default for newly-created connections that can participate in distributed transactions is to have auto-commit mode turned off. The next section will discuss the three broad categories of DataSource implementations.

In addition to the version of getConnection that takes a user name and password, the DataSource interface provides a version of the method DataSource.getConnection that takes no parameters. It is available for situations where a data source does not require a user name and password because it uses a different security mechanism or where a data source does not restrict access.

4.1.5 DataSource Implementations

The DataSource interface may be implemented to provide three different kinds of connections. As a result of DataSource objects working with a JNDI service provider, all connections produced by a DataSource object offer the advantages of portability and easy maintenance, which are explained later in this chapter. Implementations of DataSource that work with implementations of the more specialized ConnectionPoolDataSource and XADataSource interfaces produce connections that are pooled or that can be used in distributed transactions. The following list summarizes the three general categories of classes that implement the DataSource interface:

  1. Basic DataSource class
    • provided by: driver vendor
    • advantages: portability, easy maintenance
  2. DataSource class implemented to provide connection pooling
    • provided by: application server vendor or driver vendor
    • works with: a ConnectionPoolDataSource class, which is always provided by a driver vendor
    • advantages: portability, easy maintenance; increased performance
  3. DataSource class implemented to provide distributed transactions
    • provided by: application server vendor such as an EJB server vendor
    • works with: an XADataSource class, which is always provided by a driver vendor
    • advantages: portability, easy maintenance; ability to participate in distributed transactions
      Note that a DataSource implementation that supports distributed transactions is almost always implemented to support connection pooling as well.

      An instance of a class that implements the DataSource interface represents one particular data source. Every connection produced by that instance will reference the same data source. In a basic DataSource implementation, a call to the method DataSource.getConnection returns a Connection object that, like the Connection object returned by the DriverManager facility, is a physical connection to the data source. Appendix A of the specification for the JDBC 2.0 Standard Extension API (available at http://java.sun.com/products/jdbc) gives a sample implementation of a basic DataSource class.

      DataSource objects that implement connection pooling likewise produce a connection to the particular data source that the DataSource class represents. The Connection object that the method DataSource.getConnection returns, however, is a handle to a PooledConnection object rather than being a physical connection. An application uses the Connection object just as it usually does and is generally unaware that it is in any way different. Connection pooling has no effect whatever on application code except that a pooled connection, as is true with all connections, should always be explicitly closed. When an application closes a connection that is pooled, the connection joins a pool of reusable connections. The next time DataSource.getConnection is called, a handle to one of these pooled connections will be returned if one is available. Because connection pooling avoids creating a new physical connection every time one is requested, it can help to make applications run significantly faster. Connection pooling is generally used, for example, by a web server that supports servlets and JavaServertm Pages.

      A DataSource class can likewise be implemented to work with a distributed transaction environment. An EJB server, for example, supports distributed transactions and requires a DataSource class that is implemented to interact with it. In this case, the DataSource.getConnection method returns a Connection object that can be used in a distributed transaction. As a rule, EJB servers provide a DataSource class that supports connection pooling as well as distributed transactions. Like connection pooling, transaction management is handled internally, so using distributed transactions is easy. The only requirement is that when a transaction is distributed (involves two or more data sources), the application cannot call the methods commit or rollback. It also cannot put the connection in auto-commit mode. The reason for these restrictions is that a transaction manager begins and ends a distributed transaction under the covers, so an application cannot do anything that would affect when a transaction begins or ends.

4.1.6 Logging and Tracing

The DataSource interface provides methods that allow a user to get and set the character stream to which tracing and error logging will be written. A user can trace a specific data source on a given stream, or multiple data sources can write log messages to the same stream provided that the stream is set for each data source. Log messages that are written to a log stream specific to a DataSource object are not written to the log stream maintained by the DriverManager.

4.1.7 Advantages of Using JNDI

There are major advantages to connecting to a data source using a DataSource object registered with a JNDI naming service rather than using the DriverManager facility. The first is that it makes code more portable. With the DriverManager, the name of a JDBC driver class, which usually identifies a particular driver vendor, is included in application code. This makes the application specific to that vendor's driver product and thus non-portable.

Another advantage is that it makes code much easier to maintain. If any of the necessary information about the data source changes, only the relevant DataSource properties need to be modified, not every application that connects to that data source. For example, if a database is moved to a different server and uses a different port number, only the DataSource object's serverName and portNumber properties need to be updated. A system administrator could keep all existing code usable with the following code fragment. In practice, a system administrator would probably use a GUI tool to set the properties, so the following code fragment illustrates the code a tool might execute internally.

Context ctx = new InitialContext()

DataSource ds = (DataSource)ctx.lookup("jdbc/AcmeDB");
ds.setServerName("my_new_database_server");

ds.setPortNumber("940");

The application programmer would not need to do anything at all to keep all of the applications using the data source running smoothly.

Yet another advantage is that applications using a DataSource object to get a connection will automatically benefit from connection pooling if the DataSource class has been implemented to support connection pooling. Likewise, an application will automatically be able to use distributed transactions if the DataSource class has been implemented to support them.

[Top] [Prev] [Next] [Bottom]

Copyright © 2001, Sun Microsystems, Inc. All rights reserved.


 [Top] [Prev] [Next]

DriverManager

NOTE: The material in this chapter is based on JDBCtm API Tutorial and Reference, Second Edition: Universal Data Access for the Javatm 2 Platform, published by Addison Wesley as part of the Java series, ISBN 0-201-43328-1.

3.1 DriverManager Overview

The DriverManager class is the traditional management layer of JDBC, working between the user and the drivers. It keeps track of the drivers that are available and handles establishing a connection between a database and the appropriate driver. In addition, the DriverManager class attends to things like driver login time limits and the printing of log and tracing messages.

Note that the javax.sql package, otherwise known as the JDBC 2.0 Standard Extension API, provides the DataSource interface as an alternate and preferred means of connecting to a data source. However, the DriverManager facility can still be used with drivers that support DataSource implementations.

For simple applications, the only method in the DriverManager class that a general programmer needs to use directly is DriverManager.getConnection. As its name implies, this method establishes a connection to a database. An application may call the DriverManager methods getDriver, getDrivers, and registerDriver as well as the Driver method connect, but in most cases it is better to let the DriverManager class manage the details of establishing a connection.

3.1.1 Keeping Track of Available Drivers

The DriverManager class maintains a list of Driver classes that have registered themselves by calling the method DriverManager.registerDriver. All Driver classes should be written with a static section (a static initializer) that creates an instance of the class and then registers it with the DriverManager class when it is loaded. Thus, a user would not normally call DriverManager.registerDriver directly; it should be called automatically by a Driver class when it is loaded. A Driver class is loaded, and therefore automatically registered with the DriverManager, in one of two ways:

  1. by calling the method Class.forName. This explicitly loads the driver class. Since it does not depend on any external setup, this way of loading a driver is the recommended one for using the DriverManager framework. The following code loads the class acme.db.Driver:
    Class.forName("acme.db.Driver");

    If acme.db.Driver has been written so that loading it causes an instance to be created and also calls DriverManager.registerDriver with that instance as the parameter (as it should do), then it is in the DriverManager's list of drivers and available for creating a connection.

  2. by adding the Driver class to the java.lang.System property jdbc.drivers. This is a list of driver classnames, separated by colons, that the DriverManager class loads. When the DriverManager class is initialized, it looks for the system property "jdbc.drivers," and if the user has entered one or more drivers, the DriverManager class attempts to load them. The following code illustrates how a programmer might enter three driver classes in ~/.hotjava/properties (HotJava loads these into the system properties list on startup):
jdbc.drivers=foo.bah.Driver:wombat.sql.Driver:bad.test.ourDriver
The first call to a DriverManager method will automatically cause these driver classes to be loaded.

Note that this second way of loading drivers requires a preset environment that is persistent. If there is any doubt about that being the case, it is safer to call the method Class.forName to explicitly load each driver. This is also the right method to use to bring in a particular driver since once the DriverManager class has been initialized, it will never recheck the jdbc.drivers property list.

In both of these cases, it is the responsibility of the newly-loaded Driver class to register itself by calling DriverManager.registerDriver. As mentioned, this should be done automatically when the class is loaded.

For security reasons, the JDBC management layer will keep track of which class loader provided which driver. Then when the DriverManager class is opening a connection, it will use only drivers that come from the local file system or from the same class loader as the code issuing the request for a connection.

3.1.2 Establishing a Connection

Once the Driver classes have been loaded and registered with the DriverManager class, they are available for establishing a connection with a database. When a request for a connection is made with a call to the DriverManager.getConnection method, the DriverManager tests each driver in turn to see if it can establish a connection.

It may sometimes be the case that more than one JDBC driver is capable of connecting to a given URL. For example, when connecting to a given remote database, it might be possible to use a JDBC-ODBC bridge driver, a JDBC-to-generic-network-protocol driver, or a driver supplied by the database vendor. In such cases, the order in which the drivers are tested is significant because the DriverManager will use the first driver it finds that can successfully connect to the given URL.

First the DriverManager tries to use each driver in the order it was registered. (The drivers listed in jdbc.drivers are always registered first.) It will skip any drivers that are untrusted code unless they have been loaded from the same source as the code that is trying to open the connection.

It tests the drivers by calling the method Driver.connect on each one in turn, passing them the URL that the user originally passed to the method DriverManager.getConnection. The first driver that recognizes the URL makes the connection.

At first glance this may seem inefficient, but it requires only a few procedure calls and string comparisons per connection since it is unlikely that dozens of drivers will be loaded concurrently.

The following code is an example of all that is normally needed to set up a connection with a driver such as a JDBC-ODBC bridge driver.

Class.forName("jdbc.odbc.JdbcOdbcDriver"); //loads the driver
String url = "jdbc:odbc:fred";
Connection con = DriverManager.getConnection(
        url, "userID", "passwd");

The variable con represents a connection to the data source "fred" that can be used to create and execute SQL statements.

With the addition of the JDBC 2.0 Standard Extension API, a DataSource object can be used to establish a connection with a data source. The DriverManager can still be used, but a DataSource object offers several advantages over the DriverManager and is the preferred alternative. Developers who are writing Enterprise JavaBeans components, however, should always use a DataSource object instead of the DriverManager. Using a properly implemented DataSource object is the only way to get connections that are pooled and that can participate in distributed transactions.

3.1.3 DriverManager Methods Are Static

All DriverManager methods are declared static, which means that they operate on the class as a whole and not on particular instances. In fact, the constructor for DriverManager is declared private to prevent users from instantiating it. Logically, there is one instance of the DriverManager class. This means that methods are called by qualifying them with DriverManager, as in the following line of code.

DriverManager.setLogWriter(out);

[Top] [Prev] [Next]

Copyright © 1999, Sun Microsystems, Inc.   All rights
reserved.


 [Top] [Prev] [Next] [Bottom]

Getting Started with the JDBC API

1 Introduction

1.1 What the JDBC 3.0 API Includes . . . . . . . . . . . . .
1.2 What Is the JDBC API?
1.2.1 What Does the JDBC API Do?
1.2.2 A Base for Other APIs
1.2.3 The JDBC API Versus ODBC and UDA
1.2.4 Two-tier and Three-tier Models
1.2.5 SQL Conformance
1.2.6 JDBC Products
1.2.7 Java Software Framework
1.2.8 JDBC Driver Types
1.2.9 Obtaining JDBC Drivers
1.2.10 Java-relational DBMSs
1.2.11 Other Products

2 Connection

2.1 Connection Overview . . . . . . . . . . . . .
2.1.1 Opening a Connection
2.1.2 URLs in General Use
2.1.3 JDBC URLs
2.1.4 The odbc Subprotocol
2.1.5 Registering Subprotocols
2.1.6 Sending SQL Statements
2.1.7 Transactions
2.1.8 Transaction Isolation Levels
2.1.9 Savepoints
2.1.10 Freeing DBMS Resources
2.1.11 Using Type Maps

3 DriverManager

3.1 DriverManager Overview . . . . . . . . . . . . .
3.1.1 Keeping Track of Available Drivers
3.1.2 Establishing a Connection
3.1.3 DriverManager Methods Are Static

4 DataSource

4.1 DataSource Overview . . . . . . . . . . . . .
4.1.1 Properties
4.1.2 Using JNDI
4.1.3 Creating and Registering a DataSource Object
4.1.4 Connecting to a Data Source
4.1.5 DataSource Implementations
4.1.6 Logging and Tracing
4.1.7 Advantages of Using JNDI

5 Statement

5.1 Statement Overview . . . . . . . . . . . . .
5.1.1 Creating Statement Objects
5.1.2 Executing Statements Using Statement Objects
5.1.3 Statement Completion
5.1.4 Retrieving Automatically Generated Keys
5.1.5 Closing Statements
5.1.6 SQL Escape Syntax in Statements
5.1.7 Sending Batch Updates
5.1.8 Giving Performance Hints
5.1.9 Executing Special Kinds of Statements

6 ResultSet

6.1 ResultSet Overview . . . . . . . . . . . . .
6.1.1 Rows and Columns
6.1.2 Cursors
6.1.3 Cursor Movement Examples
6.1.4 Determining the Number of Rows in a Result Set
6.1.5 Retrieving Column Values
6.1.6 Which getter Method to Use
6.1.7 Types of Result Sets
6.1.8 Concurrency Types
6.1.9 Holdability
6.1.10 Providing Performance Hints
6.1.11 Creating Different Types of Result Sets
6.1.12 Using a Prepared Statement to Create Result Sets
6.1.13 Requesting Features That Are Not Supported
6.1.14 Using updater Methods
6.1.15 Deleting a Row
6.1.16 Inserting Rows
6.1.17 Positioned Updates
6.1.18 Queries That Produce Updatable Result Sets
6.1.19 Using Streams for Very Large Row Values
6.1.20 NULL Result Values
6.1.21 Closing a ResultSet Object
6.1.22 JDBC Compliance

7 PreparedStatement

7.1 PreparedStatement Overview . . . . . . . . . . . . .
7.1.1 Creating PreparedStatement Objects
7.1.2 Passing IN Parameters
7.1.3 Parameter Metadata
7.1.4 Data Type Conformance on IN Parameters
7.1.5 Using setObject
7.1.6 Sending JDBC NULL as an IN parameter
7.1.7 Sending Very Large IN Parameters
7.1.8 Using PreparedStatement Objects in Batch Updates

8 CallableStatement

8.1 CallableStatement Overview . . . . . . . . . . . . .
8.1.1 Creating a CallableStatement Object
8.1.2 IN Parameters
8.1.3 Making Batch Updates
8.1.4 OUT Parameters
8.1.5 Numbering of Parameters
8.1.6 INOUT Parameters
8.1.7 Retrieve OUT Parameters after Results
8.1.8 Retrieving NULL Values as OUT Parameters

9 Mapping SQL and Java Types

9.1 Mapping Overview . . . . . . . . . . . . .
9.2 Mapping SQL Types to Java Types
9.3 Basic JDBC Types
9.3.1 CHAR, VARCHAR, and LONGVARCHAR
9.3.2 BINARY, VARBINARY, and LONGVARBINARY
9.3.3 BIT
9.3.4 BOOLEAN
9.3.5 TINYINT
9.3.6 SMALLINT
9.3.7 INTEGER
9.3.8 BIGINT
9.3.9 REAL
9.3.10 DOUBLE
9.3.11 FLOAT
9.3.12 DECIMAL and NUMERIC
9.3.13 DATE, TIME, and TIMESTAMP
9.4 Advanced JDBC Data Types
9.4.1 DATALINK
9.4.2 BLOB
9.4.3 CLOB
9.4.4 ARRAY
9.4.5 DISTINCT
9.4.6 STRUCT
9.4.7 REF
9.4.8 JAVA_OBJECT
9.5 Examples of Mapping
9.5.1 Simple SQL Statement
9.5.2 SQL Statement with IN Parameters
9.5.3 SQL Statement with INOUT Parameters
9.6 Custom Mapping
9.7 Dynamic Data Access
9.8 Storing Java Objects in a Database
9.9 Tables for Type Mapping
9.9.1 JDBC Types Mapped to Java Types
9.9.2 Java Types Mapped to JDBC Types
9.9.3 JDBC Types Mapped to Java Object Types
9.9.4 Java Object Types Mapped to JDBC Types
9.9.5 Conversions by setObject
9.9.6 Conversions by ResultSet.getter Methods
9.9.7 JDBC Types Mapped to Database-specific SQL Types

JDBC-ODBC Bridge Enhancements

Appendix A: Summary of New Features

A.1 Overview of JDBC 3.0 API Changes
A.1.1 Features Introduced in the JDBC 3.0 API
A.1.2 Features Introduced in the JDBC 2.0 Optional Package
A.2 Overview of JDBC 2.0 Core API Changes
A.3 Summary of New Functionality
A.3.1 Scrollable Result Sets
A.3.2 Batch Updates
A.3.3 Programmatic Updates
A.3.4 Other New Features
A.4 Support for Advanced Data Types
A.4.1 What Are the SQL99 Data Types?
A.4.2 Summary of Support for the SQL99 Data Types
A.4.3 Mapping of the SQL99 Types
A.4.4 SQL Locators
A.4.5 Support for Storing Java Objects

Appendix B: Sample Code

[Top] [Prev] [Next] [Bottom]

Copyright © 2001, Sun Microsystems, Inc. All rights reserved.


 [Top] [Prev] [Next]

Introduction

NOTE: The material in this chapter is based on JDBCtm API Tutorial and Reference, Second Edition: Universal Data Access for the Javatm 2 Platform, published by Addison Wesley as part of the Java series, ISBN 0-201-43328-1.

The JDBCtm API is the application programming interface that provides universal data access for the Javatm programming language. It includes the JDBC 1.0 API, which provides the basic functionality for data access. The JDBC 2.0 API supplements the basic API with more advanced features and provides a standard way to access the latest object-relational features being supported by today's relational database management systems. In addition, the new API includes features such as scrollable and updatable result sets and improved performance. It also extends JDBC technology beyond the client to the server with connection pooling and distributed transactions.

1.1 What the JDBC 2.0 API Includes

The JDBC 2.0 API includes all of the API that is part of the Javatm 2 SDK, Standard Edition, and also the API in the JDBC Standard Extension API. The following list defines various terms used in talking about the JDBC API.

  • JDBC 2.0 API-the complete JDBC API, including both the java.sql package (the JDBC 2.0 core API) and the javax.sql package (the JDBC Standard Extension API). The Java 2 SDK, Enterprise Edition, includes the complete JDBC 2.0 API.
  • JDBC 2.0 core API-the package java.sql; the JDBC API that is part of the Java 2 SDK, Standard Edition, which includes the JDBC 1.0 API plus the new JDBC API added in the java.sql package. Some of the new features in this package are scrollable result sets, batch updates, programmatic updates, and support for the new SQL3 data types.
  • JDBC Standard Extension API-the package javax.sql, which may be downloaded from http://java.sun.com/products/jdbc. This package makes it easier to build server-side applications using the Java platform by providing an open architecture that supports connection pooling and distributed transactions that span multiple database servers. The DataSource API plays an integral part in these capabilities and also works with the Javatm Naming and Directory Interfacetm (JNDI) to improve portability and make code maintenance easier. The javax.sql package also provides the RowSet API, which makes it easy to handle data sets from virtually any data source as JavaBeanstm components.
  • java.sql package-the JDBC 2.0 core API, which includes the JDBC 1.0 API plus the new API added in the Java 2 SDK, Standard Edition
  • javax.sql package-the JDBC Standard Extension API

In keeping with the policy of maintaining backward compatibility, applications written using the JDBC 1.0 API will continue to run with both the Java 2 SDK, Standard Edition, and the Java 2 SDK, Enterprise Edition, just as they have always run. Having been well designed from the beginning, the JDBC 1.0 API is essentially unchanged. Applications using features added in the JDBC 2.0 API will, of course, need to be run using a driver that supports those features.

The package java.sql, being part of the core API, is automatically included when the Java 2 SDK, Standard Edition, is downloaded. A driver vendor may bundle the package javax.sql with its driver product, but if a driver does not include the package, it can be downloaded from the JDBC website at the following URL:

http://java.sun.com/products/jdbc

It is also possible to get the javax.sql package by downloading the Java 2 SDK, Enterprise Edition, which includes both the java.sql and javax.sql packages. Programmers who are not writing Enterprise JavaBeanstm (EJB) components or other server code will probably want to download the Java 2 SDK, Standard Edition, rather than the Java 2 SDK, Enterprise Edition, to limit the amount of disc space used.

1.2 What Is the JDBC API?

The JDBC API is a Java API for accessing virtually any kind of tabular data. (As a point of interest, JDBC is the trademarked name and is not an acronym; nevertheless, JDBC is often thought of as standing for "Java Database Connectivity.") The JDBC API consists of a set of classes and interfaces written in the Java programming language that provide a standard API for tool/database developers and makes it possible to write industrial strength database applications using an all-Java API.

The JDBC API makes it easy to send SQL statements to relational database systems and supports all dialects of SQL. But the JDBC 2.0 API goes beyond SQL, also making it possible to interact with other kinds of data sources, such as files containing tabular data.

The value of the JDBC API is that an application can access virtually any data source and run on any platform with a Java Virtual Machine. In other words, with the JDBC API, it isn't necessary to write one program to access a Sybase database, another program to access an Oracle database, another program to access an IBM DB2 database, and so on. One can write a single program using the JDBC API, and the program will be able to send SQL or other statements to the appropriate data source. And, with an application written in the Java programming language, one doesn't have to worry about writing different applications to run on different platforms. The combination of the Java platform and the JDBC API lets a programmer write once and run anywhere.

The Java programming language, being robust, secure, easy to use, easy to understand, and automatically downloadable on a network, is an excellent language basis for database applications. What is needed is a way for Java applications to talk to a variety of different data sources. JDBC is the mechanism for doing this.

The JDBC 2.0 API extends what can be done with the Java platform. For example, the JDBC API makes it possible to publish a web page containing an applet that uses information obtained from a remote data source. Or an enterprise can use the JDBC API to connect all its employees (even if they are using a conglomeration of Windows, Macintosh, and UNIX machines) to one or more internal databases via an intranet. With more and more programmers using the Java programming language, the need for easy and universal data access from Java is continuing to grow.

MIS managers like the combination of the Java platform and JDBC technology because it makes disseminating information easy and economical. Businesses can continue to use their installed databases and access information easily even if it is stored on different database management systems or other data sources. Development time for new applications is short. Installation and version control are greatly simplified. A programmer can write an application or an update once, put it on the server, and everybody has access to the latest version. And for businesses selling information services, the combination of the Java and JDBC technologies offers a better way of getting out information updates to external customers.

1.2.1 What Does the JDBC API Do?

In simplest terms, a JDBC technology-based driver ("JDBC driver") makes it possible to do three things:

  1. Establish a connection with a data source
  2. Send queries and update statements to the data source
  3. Process the results

    The following code fragment gives a simple example of these three steps:

Connection con = DriverManager.getConnection(

                    "jdbc:myDriver:wombat", "myLogin", "myPassword");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");
while (rs.next()) {
    int x = rs.getInt("a");
    String s = rs.getString("b");
    float f = rs.getFloat("c");

    }

1.2.2 A Base for Other APIs

The JDBC API is used to invoke (or "call") SQL commands directly. It works very well in this capacity and is easier to use than other database connectivity APIs, but it was also designed to be a base upon which to build alternate interfaces and tools. An alternate interface tries to be "user-friendly" by using a more understandable or more convenient API that is translated behind the scenes into the JDBC API. Because the JDBC API is complete and powerful enough to be used as a base, it has had various kinds of alternate APIs developed on top of it, including the following:

  1. An embedded SQL for Java. A consortium including Oracle, IBM, Sun, and others has defined the SQLJ specification to provide this. JDBC requires that SQL statements basically be passed as uninterpreted strings to Java methods. An embedded SQL preprocessor provides compile-time type checking and allows a programmer to intermix SQL statements with Java programming language statements. For example, a Java variable can be used in an SQL statement to receive or provide SQL values. The SQLJ preprocessor effectively translates this Java/SQL mix into the Java programming language with JDBC calls.
  2. A direct mapping of relational database tables to Java classes. Java Software has announced the Java Blendtm product to provide this, and others have similar products. In this "object/relational" mapping, a table becomes a class, each row of the table becomes an instance of that class, and each column value corresponds to an attribute of that instance. Programmers can then operate directly on Java objects; the required SQL calls to fetch and store data are automatically generated "beneath the covers." Java Blend also allows more sophisticated mappings, for example, where rows of multiple tables are combined in a Java class.

As interest in JDBC technology has grown, other JDBC-based tools have been developed to make building programs easier. For example, an application might present a menu of database tasks from which to choose. After a task is selected, the application presents prompts and blanks for filling in information needed to carry out the selected task. With the requested input typed in, the application then automatically invokes the necessary JDBC commands. With the help of such an application, users can perform database tasks even when they have little or no knowledge of SQL syntax.

1.2.3 The JDBC API Versus ODBC and UDA

Prior to the development of the JDBC API, Microsoft's ODBC (Open DataBase Connectivity) API was the most widely used programming interface for accessing relational databases. It offers the ability to connect to almost all databases on almost all platforms. So why not just use ODBC from Java?

The answer is that you can use ODBC from Java, but this is best done with the help of the JDBC API in the form of the JDBC-ODBC Bridge. The question now becomes, "Why do you need the JDBC API?"

There are several answers to this question.

  1. ODBC is not appropriate for direct use from the Java programming language because it uses a C interface. Calls from Java to native C code have a number of drawbacks in the security, implementation, robustness, and automatic portability of applications.
  2. A literal translation of the ODBC C API into a Java API would not be desirable. For example, Java has no pointers (address variables), and ODBC makes copious use of them, including the notoriously error-prone generic pointer void *. You can think of JDBC as ODBC translated into a high-level object-oriented interface that is natural for programmers using the Java programming language.
  3. ODBC is hard to learn. It mixes simple and advanced features together, and it has complex options even for simple queries. The JDBC API, on the other hand, was designed to keep simple things simple while allowing more advanced capabilities where required. The JDBC API is also easier to use simply because it is a Java API, which means that a programmer does not need to worry about either memory management or data byte alignment.
  4. A Java API like JDBC is needed in order to enable a "pure Java" solution, that is, a solution that uses only Java API. When ODBC is used, the ODBC driver manager and drivers must be manually installed on every client machine. When the JDBC driver is written completely in Java, however, JDBC code is automatically installable, portable, and secure on all Java platforms from network computers to mainframes.

In summary, the JDBC API is a natural Java interface for working with SQL. It builds on ODBC rather than starting from scratch, so programmers familiar with ODBC will find it very easy to learn. The JDBC API retains some of the basic design features of ODBC; in fact, both interfaces are based on the Open Group (formerly X/Open) SQL CLI (Call Level Interface). The big difference is that the JDBC API builds on and reinforces the style and virtues of Java, and it goes beyond just sending SQL statements to a relational database management system.

Microsoft has introduced new APIs beyond ODBC such as OLE (Object Linking and Embedding) DB, ADO (ActiveX Data Objects), and RDS (Remote Data Service). In many ways these APIs move in the same direction as the JDBC API. For example, OLE DB and ADO are also object-oriented interfaces to databases that can be used to execute SQL statements. However, OLE DB is a low-level interface designed for tools rather than developers. ADO is newer and more like the JDBC API, but it is not pure Java. RDS provides functionality similar to the JDBC API's RowSet facility, but RDS is also not written in the Java programming language, and it is not portable.

Most recently, Microsoft has introduced UDA (Universal Data Access) as an umbrella term that covers OLE DB, ADO, RDS, and ODBC. The JDBC 2.0 API contains all of the important functionality of UDA plus features not found in UDA, such as SQL3 support.

1.2.4 Two-tier and Three-tier Models

The JDBC API supports both two-tier and three-tier models for database access.

Figure 1.1: illustrates a two-tier architecture for data access.

The DBMS-proprietary protocol provides two-way communication between the client machine and the database server

In the two-tier model, a Java applet or application talks directly to the data source. This requires a JDBC driver that can communicate with the particular data source being accessed. A user's commands are delivered to the database or other data source, and the results of those statements are sent back to the user. The data source may be located on another machine to which the user is connected via a network. This is referred to as a client/server configuration, with the user's machine as the client, and the machine housing the data source as the server. The network can be an intranet, which, for example, connects employees within a corporation, or it can be the Internet.

In the three-tier model, commands are sent to a "middle tier" of services, which then sends the commands to the data source. The data source processes the commands and sends the results back to the middle tier, which then sends them to the user. MIS directors find the three-tier model very attractive because the middle tier makes it possible to maintain control over access and the kinds of updates that can be made to corporate data. Another advantage is that it simplifies the deployment of applications. Finally, in many cases, the three-tier architecture can provide performance advantages.

Figure 1.2: illustrates a three-tier architecture for database access.

The DBMS-proprietary protocol provides two-way communication between the database server and the server machine. HTTP, RMI, CORBA or other calls provide two way communication between the server machine and the client machine

Until recently, the middle tier has typically been written in languages such as C or C++, which offer fast performance. However, with the introduction of optimizing compilers that translate Java bytecode into efficient machine-specific code and technologies such as Enterprise JavaBeanstm, the Java platform is fast becoming the standard platform for middle-tier development. This is a big plus, making it possible to take advantage of Java's robustness, multithreading, and security features.

With enterprises increasingly using the Java programming language for writing server code, the JDBC API is being used more and more in the middle tier of a three-tier architecture. Some of the features that make JDBC a server technology are its support for connection pooling, distributed transactions, and disconnected rowsets. And, of course, the JDBC API is what allows access to a data source from a Java middle tier.

1.2.5 SQL Conformance

SQL is the standard language for accessing relational databases. Unfortunately, SQL is not yet as standard as one would like.

One area of difficulty is that data types used by different DBMSs (DataBase Management Systems) sometimes vary, and the variations can be significant. JDBC deals with this by defining a set of generic SQL type identifiers in the class java.sql.Types. Note that, as used in this material, the terms "JDBC SQL type," "JDBC type," and "SQL type" are interchangeable and refer to the generic SQL type identifiers defined in java.sql.Types. There is a more complete discussion of data type conformance in the chapter "Mapping SQL and Java Types."

Another area of difficulty with SQL conformance is that although most DBMSs use a standard form of SQL for basic functionality, they do not conform to the more recently defined standard SQL syntax or semantics for more advanced functionality. For example, not all databases support stored procedures or outer joins, and those that do are not always consistent with each other. Also, support for SQL3 features and data types varies greatly. It is hoped that the portion of SQL that is truly standard will expand to include more and more functionality. In the meantime, however, the JDBC API must support SQL as it is.

One way the JDBC API deals with this problem is to allow any query string to be passed through to an underlying DBMS driver. This means that an application is free to use as much SQL functionality as desired, but it runs the risk of receiving an error on some DBMSs. In fact, an application query may be something other than SQL, or it may be a specialized derivative of SQL designed for specific DBMSs (for document or image queries, for example).

A second way JDBC deals with problems of SQL conformance is to provide ODBC-style escape clauses. The escape syntax provides a standard JDBC syntax for several of the more common areas of SQL divergence. For example, there are escapes for date literals and for stored procedure calls.

For complex applications, JDBC deals with SQL conformance in a third way. It provides descriptive information about the DBMS by means of the interface DatabaseMetaData so that applications can adapt to the requirements and capabilities of each DBMS. Typical end users, however, need not worry about metadata.

Because the JDBC API is used as a base API for developing database access tools and other APIs, it also has to address the problem of conformance for anything built on it. A JDBC driver must support at least ANSI SQL-92 Entry Level. (ANSI SQL-92 refers to the standards adopted by the American National Standards Institute in 1992. Entry Level refers to a specific list of SQL capabilities.) Note, however, that although the JDBC 2.0 API includes support for SQL3 and SQLJ, JDBC drivers are not required to support them.

Given the wide acceptance of the JDBC API by database vendors, connectivity vendors, Internet service vendors, and application writers, it has become the standard for data access from the Java programming language.

1.2.6 JDBC Products

The JDBC API is a natural choice for developers using the Java platform because it offers easy database access for Java applications and applets.

At the time of this writing, a number of JDBC-based products have already been deployed or are in development. The status of these products changes frequently, so the reader should consult the JDBC web page for the latest information. It can be found at the following URL:

http://java.sun.com/products/jdbc

1.2.7 Java Software Framework

Java Software provides three JDBC product components:

  • the JDBC driver manager (included as part of the Java 2 Platform)
  • the JDBC driver test suite (available from the JDBC web site)
  • the JDBC-ODBC bridge (included in the Solaris and Windows versions of the Java 2 Platform)

The JDBC DriverManager class has traditionally been the backbone of the JDBC architecture. It is quite small and simple; its primary function is to connect Java applications to the correct JDBC driver and then get out of the way. With the availability of the Standard Extension packages javax.naming and javax.sql, it is now also possible to use a DataSource object registered with a Java Naming and Directory Interfacetm (JNDI) naming service to establish a connection with a data source. Both means of getting a connection can be still used, but using a DataSource object is recommended whenever possible.

The JDBC driver test suite provides some confidence that JDBC drivers will run your program. These tests are not comprehensive or exhaustive, but they do exercise many of the important features in the JDBC API.

The JDBC-ODBC bridge allows ODBC drivers to be used as JDBC drivers. It was implemented as a way to get JDBC off the ground quickly, and long term will provide a way to access some of the data sources for which there are no JDBC drivers.

1.2.8 JDBC Driver Types

Figure 1.3: shows various driver implementation possibilities.

See long description [D]

JDBC technology-based drivers generally fit into one of four categories:

  1. JDBC-ODBC bridge plus ODBC driver: The Java Software bridge product provides JDBC access via ODBC drivers. Note that ODBC binary code, and in many cases database client code, must be loaded on each client machine that uses this driver. As a result, this kind of driver is most appropriate on a corporate network where client installations are not a major problem, or for application server code written in Java in a three-tier architecture.
  2. Native-API partly-Java driver: This kind of driver converts JDBC calls into calls on the client API for Oracle, Sybase, Informix, IBM DB2, or other DBMSs. Note that, like the bridge driver, this style of driver requires that some operating system-specific binary code be loaded on each client machine.
  3. JDBC-Net pure Java driver: This driver translates JDBC calls into a DBMS-independent net protocol, which is then translated to a DBMS protocol by a server. This net server middleware is able to connect its pure Java clients to many different databases. The specific protocol used depends on the vendor. In general, this is the most flexible JDBC alternative. It is likely that all vendors of this solution will provide products suitable for intranet use. In order for these products to support Internet access as well, they must handle the additional requirements for security, access through firewalls, and so forth, that the Web imposes.
  4. Native-protocol pure Java driver: This kind of driver converts JDBC calls directly into the network protocol used by DBMSs. This allows a direct call from the client machine to the DBMS server and is an excellent solution for intranet access. Since many of these protocols are proprietary, the database vendors themselves are the primary source. Several that are now available include Oracle, Sybase, Informix, IBM DB2, Inprise InterBase, and Microsoft SQL Server.

Driver categories 3 and 4 are the preferred way to access databases using the JDBC API. Driver categories 1 and 2 are interim solutions where direct pure Java drivers are not yet available. There are possible variations on categories 1 and 2 (not shown in the following table) that require middleware, but these are generally less desirable solutions. Categories 3 and 4 offer all the advantages of Java technology, including automatic installation (for example, downloading the JDBC driver with an applet that uses it).

Table 1.1 shows the four categories and their properties. The table uses the following definitions for types of network connections:

  • Direct -a connection that a JDBC client makes directly to the DBMS server, which may be remote
  • Indirect--a connection that a JDBC client makes to a middleware process that acts as a bridge to the DBMS server

    DRIVER CATEGORY

    ALL JAVA

    NETWORK CONNECTION

    1 - JDBC-ODBC Bridge

    No

    Direct

    2 - Native API as basis

    No

    Direct

    3 - JDBC-Net

    client Yes

    server Maybe

    Indirect

    4 - Native protocol as basis

    Yes

    Direct

1.2.9 Obtaining JDBC Drivers

At the time of this writing, there are dozens of drivers in Category 1, ODBC drivers that can be used with Java Software's bridge. There are about a dozen Category 2 drivers built on top of native APIs for DBMSs. Many Category 3 drivers are available, and there are Category 4 drivers for all of the major DBMSs.

To get the latest information on drivers, check the JDBC web site at

 http://java.sun.com/products/jdbc

Java Software and Intersolv, a leading database connectivity vendor, worked together to produce the JDBC-ODBC Bridge and the JDBC Driver Test Suite.

1.2.10 Java-relational DBMSs

A new generation of DBMSs that are Java-aware is emerging. These new DBMSs, called Java-relational DBMSs, include new data types that allow an object in the Java programming language to be used as a column value in a database table. The new JDBC 2.0 features support this new generation of DBMSs, and several database vendors are creating products with Java-relational capabilities. It should be noted, however, that the 2.0 mechanisms are optional. If a DBMS does not support this feature, a JDBC 2.0 driver is not required to implement it.

1.2.11 Other Products

Various JDBC application development tools are under way. Watch the Java Software pages for updates.

[Top] [Prev] [Next]

Copyright © 1999, Sun Microsystems, Inc. All rights reserved.


An application written in the Java programming language uses the JDBC
DriverManager class API to access a driver based on JDBC technology
("JDBC driver"). There are various JDBC driver alternatives. A JDBC-Net
driver connects to a middle tier server and translates JDBC calls into a
DBMS-independent net protocol.  The server then translates this to a DBMS
protocol.  Other driver implementations access a DBMS directly using
proprietary database access protocols.


 [Top] [Prev] [Next]

Mapping SQL and Java Types

NOTE: The material in this chapter is based on JDBCtm API Tutorial and Reference, Second Edition: Universal Data Access for the Javatm 2 Platform, published by Addison Wesley as part of the Java series, ISBN 0-201-43328-1.

8.1 Mapping Overview

Because data types in SQL and data types in the Java programming language are not identical, there needs to be some mechanism for transferring data between an application using Java types and a database using SQL types. (Note that the phrase "Java types," as used in this book, stands for "types in the Java programming language.")

In order to transfer data between a database and an application written in the Java programming language, the JDBC API provides three sets of methods:

  1. Methods on the ResultSet class for retrieving SQL SELECT results as Java types
  2. Methods on the PreparedStatement class for sending Java types as SQL statement parameters
  3. Methods on the CallableStatement class for retrieving SQL OUT parameters as Java types

This section brings together information about data types affecting various classes and interfaces and puts all the tables showing the mappings between SQL types and Java types in one place for easy reference. It also describes each of the generic SQL data types, including the SQL3 types.

8.2 Mapping SQL Types to Java Types

Unfortunately there are significant variations between the SQL types supported by different database products. Even when different databases support SQL types with the same semantics, they may give those types different names. For example, most of the major databases support an SQL data type for large binary values, but Oracle calls this type LONG RAW, Sybase calls it IMAGE, Informix calls it BYTE, and DB2 calls it LONG VARCHAR FOR BIT DATA.

Fortunately, JDBC programmers will normally not need to concern themselves with the actual SQL type names used by a target database. Most of the time JDBC programmers will be programming against existing database tables, and they need not concern themselves with the exact SQL type names that were used to create these tables.

JDBC defines a set of generic SQL type identifiers in the class java.sql.Types. These types have been designed to represent the most commonly used SQL types. In programming with the JDBC API, programmers will normally be able to use these JDBC types to reference generic SQL types, without having to be concerned about the exact SQL type name used by the target database. These JDBC types are fully described in the next section.

The one major place where programmers may need to use SQL type names is in the SQL CREATE TABLE statement when they are creating a new database table. In this case programmers must take care to use SQL type names that are supported by their target databases. The table "JDBC Types Mapped to Database-specific SQL Types" on page 111 provides some suggestions for suitable SQL type names to be used for JDBC types for some of the major databases. We recommend that you consult your database documentation if you need exact definitions of the behavior of the various SQL types on a particular database.

If you want to be able to write portable JDBC programs that can create tables on a variety of different databases, you have two main choices. First, you can restrict yourself to using only very widely accepted SQL type names such as INTEGER, NUMERIC, or VARCHAR, which are likely to work for all databases. Or second, you can use the java.sql.DatabaseMetaData.getTypeInfo method to discover which SQL types are actually supported by a given database and select a database-specific SQL type name that matches a given JDBC type.

JDBC defines a standard mapping from the JDBC database types to Java types. For example, a JDBC INTEGER is normally mapped to a Java int. This supports a simple interface for reading and writing JDBC values as simple Java types.

The Java types do not need to be exactly isomorphic to the JDBC types; they just need to be able to represent them with enough type information to correctly store and retrieve parameters and recover results from SQL statements. For example, a Java String object does not precisely match any of the JDBC CHAR types, but it gives enough type information to represent CHAR, VARCHAR, or LONGVARCHAR successfully.

8.3 Basic JDBC Types

This section describes the JDBC data types supported by both the JDBC 1.0 and 2.0 API. It also explains how they are related to standard SQL types and to types in the Java programming language. New JDBC data types introduced in the JDBC 2.0 core API are described in section 8.4 on page 94.

8.3.1 CHAR, VARCHAR, and LONGVARCHAR

The JDBC types CHAR, VARCHAR, and LONGVARCHAR are closely related. CHAR represents a small, fixed-length character string, VARCHAR represents a small, variable-length character string, and LONGVARCHAR represents a large, variable-length character string.

The SQL CHAR type corresponding to JDBC CHAR is defined in SQL-92 and is supported by all the major databases. It takes a parameter that specifies the string length. Thus CHAR(12) defines a 12-character string. All the major databases support CHAR lengths up to at least 254 characters.

The SQL VARCHAR type corresponding to JDBC VARCHAR is defined in SQL-92 and is supported by all the major databases. It takes a parameter that specifies the maximum length of the string. Thus VARCHAR(12) defines a string whose length may be up to 12 characters. All the major databases support VARCHAR lengths up to 254 characters. When a string value is assigned to a VARCHAR variable, the database remembers the length of the assigned string and on a SELECT, it will return the exact original string.

Unfortunately there is no consistent SQL mapping for the JDBC LONGVARCHAR type. All the major databases support some kind of very large variable-length string supporting up to at least a gigabyte of data, but the SQL type names vary. See the table "JDBC Types Mapped to Database-specific SQL Types" on page 111 for some examples.

Java programmers do not need to distinguish among the three types of JDBC strings, CHAR, VARCHAR, and LONGVARCHAR. Each can be expressed as a Java String, and it is possible to read and write an SQL statement correctly without knowing the exact data type that was expected.

CHAR, VARCHAR, and LONGVARCHAR could have been mapped to either String or char[], but String is more appropriate for normal use. Also, the String class makes conversions between String and char[] easy: There is a method for converting a String object to a char[] and also a constructor for turning a char[] into a String object.

One issue that had to be addressed is how to handle fixed-length SQL strings of type CHAR(n). The answer is that JDBC drivers (or the DBMS) perform appropriate padding with spaces. Thus, when a CHAR(n) field is retrieved from the database, the driver will convert it to a Java String object of length n, which may include some padding spaces at the end. Conversely, when a String object is sent to a CHAR(n) field, the driver and/or the database will add any necessary padding spaces to the end of the string to bring it up to length n.

The method ResultSet.getString, which allocates and returns a new String object, is recommended for retrieving data from CHAR, VARCHAR, and LONGVARCHAR fields. This is suitable for retrieving normal data, but can be unwieldy if the JDBC type LONGVARCHAR is being used to store multi-megabyte strings. To handle this case, two methods in the ResultSet interface allow programmers to retrieve a LONGVARCHAR value as a Java input stream from which they can subsequently read data in whatever size chunks they prefer. These methods are getAsciiStream and getCharacterStream, which deliver the data stored in a LONGVARCHAR column as a stream of ASCII or Unicode characters. Note that the method getUnicodeStream has been deprecated.

The SQL3 CLOB data type, which is described later in this chapter, provides an alternate means of representing large amounts of character data.

8.3.2 BINARY, VARBINARY, and LONGVARBINARY

The JDBC types BINARY, VARBINARY, and LONGVARBINARY are closely related. BINARY represents a small, fixed-length binary value, VARBINARY represents a small, variable-length binary value, and LONGVARBINARY represents a large, variable-length binary value.

Unfortunately, the use of these various BINARY types has not been standardized and support varies considerably among the major databases.

The SQL BINARY type corresponding to JDBC BINARY is a nonstandard SQL extension and is only implemented on some databases. It takes a parameter that specifies the number of binary bytes. Thus BINARY(12) defines a 12-byte binary type. Typically, BINARY values are limited to 254 bytes.

The SQL VARBINARY type corresponding to JDBC VARBINARY is a nonstandard SQL extension and is only implemented on some databases. It takes a parameter that specifies the maximum number of binary bytes. Thus VARBINARY(12) defines a binary type whose length may be up to 12 bytes. Typically, VARBINARY values are limited to 254 bytes. When a binary value is assigned to a VARBINARY variable, the database remembers the length of the assigned value and on a SELECT, it will return the exact original value.

Regrettably, there is no consistent SQL type name corresponding to the JDBC LONGVARBINARY type. All the major databases support some kind of very large variable length binary type supporting up to at least a gigabyte of data, but the SQL type names vary. See the table "JDBC Types Mapped to Database-specific SQL Types" on page 111 for some examples.

BINARY, VARBINARY, and LONGVARBINARY can all be expressed identically as byte arrays in the Java programming language. Since it is possible to read and write SQL statements correctly without knowing the exact BINARY data type that was expected, there is no need for programmers writing code in the Java programming language to distinguish among them.

The method recommended for retrieving BINARY and VARBINARY values is ResultSet.getBytes. If a column of type JDBC LONGVARBINARY stores a byte array that is many megabytes long, however, the method getBinaryStream is recommended. Similar to the situation with LONGVARCHAR, this method allows a programmer to retrieve a LONGVARBINARY value as a Java input stream that can be read later in smaller chunks.

The SQL3 BLOB data type, which is described later in this chapter, provides an alternate means of representing large amounts of binary data.

8.3.3 BIT

The JDBC type BIT represents a single bit value that can be zero or one.

SQL-92 defines an SQL BIT type. However, unlike the JDBC BIT type, this SQL-92 BIT type can be used as a parameterized type to define a fixed-length binary string. Fortunately, SQL-92 also permits the use of the simple non-parameterized BIT type to represent a single binary digit, and this usage corresponds to the JDBC BIT type. Unfortunately, the SQL-92 BIT type is only required in "full" SQL-92 and is currently supported by only a subset of the major databases. Portable code may therefore prefer to use the JDBC SMALLINT type, which is widely supported.

The recommended Java mapping for the JDBC BIT type is as a Java boolean.

8.3.4 TINYINT

The JDBC type TINYINT represents an 8-bit integer value between 0 and 255 that may be signed or unsigned.

The corresponding SQL type, TINYINT, is currently supported by only a subset of the major databases. Portable code may therefore prefer to use the JDBC SMALLINT type, which is widely supported.

The recommended Java mapping for the JDBC TINYINT type is as either a Java byte or a Java short. The 8-bit Java byte type represents a signed value from -128 to 127, so it may not always be appropriate for larger TINYINT values, whereas the 16-bit Java short will always be able to hold all TINYINT values.

8.3.5 SMALLINT

The JDBC type SMALLINT represents a 16-bit signed integer value between -32768 and 32767.

The corresponding SQL type, SMALLINT, is defined in SQL-92 and is supported by all the major databases. The SQL-92 standard leaves the precision of SMALLINT up to the implementation, but in practice, all the major databases support at least 16 bits.

The recommended Java mapping for the JDBC SMALLINT type is as a Java short.

8.3.6 INTEGER

The JDBC type INTEGER represents a 32-bit signed integer value ranging between -2147483648 and 2147483647.

The corresponding SQL type, INTEGER, is defined in SQL-92 and is widely supported by all the major databases. The SQL-92 standard leaves the precision of INTEGER up to the implementation, but in practice all the major databases support at least 32 bits.

The recommended Java mapping for the INTEGER type is as a Java int.

8.3.7 BIGINT

The JDBC type BIGINT represents a 64-bit signed integer value between -9223372036854775808 and 9223372036854775807.

The corresponding SQL type BIGINT is a nonstandard extension to SQL. In practice the SQL BIGINT type is not yet currently implemented by any of the major databases, and we recommend that its use be avoided in code that is intended to be portable.

The recommended Java mapping for the BIGINT type is as a Java long.

8.3.8 REAL

The JDBC type REAL represents a "single precision" floating point number that supports seven digits of mantissa.

The corresponding SQL type REAL is defined in SQL-92 and is widely, though not universally, supported by the major databases. The SQL-92 standard leaves the precision of REAL up to the implementation, but in practice all the major databases supporting REAL support a mantissa precision of at least seven digits.

The recommended Java mapping for the REAL type is as a Java float.

8.3.9 DOUBLE

The JDBC type DOUBLE represents a "double precision" floating point number that supports 15 digits of mantissa.

The corresponding SQL type is DOUBLE PRECISION, which is defined in SQL-92 and is widely supported by the major databases. The SQL-92 standard leaves the precision of DOUBLE PRECISION up to the implementation, but in practice all the major databases supporting DOUBLE PRECISION support a mantissa precision of at least 15 digits.

The recommended Java mapping for the DOUBLE type is as a Java double.

8.3.10 FLOAT

The JDBC type FLOAT is basically equivalent to the JDBC type DOUBLE. We provided both FLOAT and DOUBLE in a possibly misguided attempt at consistency with previous database APIs. FLOAT represents a "double precision" floating point number that supports 15 digits of mantissa.

The corresponding SQL type FLOAT is defined in SQL-92. The SQL-92 standard leaves the precision of FLOAT up to the implementation, but in practice all the major databases supporting FLOAT support a mantissa precision of at least 15 digits.

The recommended Java mapping for the FLOAT type is as a Java double. However, because of the potential confusion between the double precision SQL FLOAT and the single precision Java float, we recommend that JDBC programmers should normally use the JDBC DOUBLE type in preference to FLOAT.

8.3.11 DECIMAL and NUMERIC

The JDBC types DECIMAL and NUMERIC are very similar. They both represent fixed-precision decimal values. ame="1007716"> The corresponding SQL types DECIMAL and NUMERIC are defined in SQL-92 and are very widely implemented. These SQL types take precision and scale parameters. The precision is the total number of decimal digits supported, and the scale is the number of decimal digits after the decimal point. For most DBMSs, the scale is less than or equal to the precision. So for example, the value "12.345" has a precision of 5 and a scale of 3, and the value ".11" has a precision of 2 and a scale of 2. JDBC requires that all DECIMAL and NUMERIC types support both a precision and a scale of at least 15.

The sole distinction between DECIMAL and NUMERIC is that the SQL-92 specification requires that NUMERIC types be represented with exactly the specified precision, whereas for DECIMAL types, it allows an implementation to add additional precision beyond that specified when the type was created. Thus a column created with type NUMERIC(12,4) will always be represented with exactly 12 digits, whereas a column created with type DECIMAL(12,4) might be represented by some larger number of digits.

The recommended Java mapping for the DECIMAL and NUMERIC types is java.math.BigDecimal. The java.math.BigDecimal type provides math operations to allow BigDecimal types to be added, subtracted, multiplied, and divided with other BigDecimal types, with integer types, and with floating point types.

The method recommended for retrieving DECIMAL and NUMERIC values is ResultSet.getBigDecimal. JDBC also allows access to these SQL types as simple Strings or arrays of char. Thus, Java programmers can use getString to receive a DECIMAL or NUMERIC result. However, this makes the common case where DECIMAL or NUMERIC are used for currency values rather awkward, since it means that application writers have to perform math on strings. It is also possible to retrieve these SQL types as any of the Java numeric types.

8.3.12 DATE, TIME, and TIMESTAMP

There are three JDBC types relating to time:

  • The JDBC DATE type represents a date consisting of day, month, and year. The corresponding SQL DATE type is defined in SQL-92, but it is implemented by only a subset of the major databases. Some databases offer alternative SQL types that support similar semantics.
  • The JDBC TIME type represents a time consisting of hours, minutes, and seconds. The corresponding SQL TIME type is defined in SQL-92, but it is implemented by only a subset of the major databases. As with DATE, some databases offer alternative SQL types that support similar semantics.
  • The JDBC TIMESTAMP type represents DATE plus TIME plus a nanosecond field. The corresponding SQL TIMESTAMP type is defined in SQL-92, but it is implemented by only a very small number of databases.

Because the standard Java class java.util.Date does not match any of these three JDBC date/time types exactly (it includes both DATE and TIME information but has no nanoseconds), JDBC defines three subclasses of java.util.Date to correspond to the SQL types. They are:

  • java.sql.Date for SQL DATE information. The hour, minute, second, and millisecond fields of the java.util.Date base class should be set to zero. If the number of milliseconds supplied to the java.sql.Date constructor is negative, the driver will compute the date as the number of milliseconds before January 1, 1970. Otherwise, the date is computed as the specified number of milliseconds after January 1, 1970.

  • java.sql.Time for SQL TIME information. The year, month, and day fields of the java.util.Date base class are set to 1970, January, and 1. This is the "zero" date in the Java epoch.
  • java.sql.Timestamp for SQL TIMESTAMP information. This class extends java.util.Date by adding a nanoseconds field.

All three of the JDBC time-related classes are subclasses of java.util.Date, and as such, they can be used where a java.util.Date is expected. For example, internationalization methods take a java.util.Date object as an argument, so they can be passed instances of any of the JDBC time-related classes.

A JDBC Timestamp object has its parent's date and time components and also a separate nanoseconds component. If a java.sql.Timestamp object is used where a java.util.Date object is expected, the nanoseconds component is lost. However, since a java.util.Date object is stored with a precision of one millisecond, it is possible to maintain this degree of precision when converting a java.sql.Timestamp object to a java.util.Date object. This is done by converting the nanoseconds in the nanoseconds component to whole milliseconds (by dividing the number of nanoseconds by 1,000,000) and then adding the result to the java.util.Date object. Up to 999,999 nanoseconds may be lost in this conversion, but the resulting java.util.Date object will be accurate to within one millisecond.

The following code fragment is an example of converting a java.sql.Timestamp object to a java.util.Date object that is accurate to within one millisecond.

Timestamp t = new Timestamp(98724573287540L);
java.util.Date d;
d = new java.util.Date(t.getTime() + (t.getNanos() / 1000000));

New methods in the JDBC 2.0 core API make it possible for the driver to take a specified time zone into account when calculating a date, time, or timestamp. The time zone information is included in a java.util.Calendar object that is passed to new versions of the methods for getting and setting Date, Time, and Timestamp values. When no time zone is specified, the driver uses the time zone of the virtual machine running the application when it calculates a date, time, or timestamp.

8.4 Advanced JDBC Data Types

The ISO (International Organization for Standardization) and IEC (the International Electrotechnical Commission) have defined new data types that are commonly referred to as SQL3 types. Of these new SQL3 data types, BLOB, CLOB, ARRAY, and REF are predefined types, whereas the SQL structured type and the DISTINCT type are user-defined types (UDTs). These new types, with the exception of DISTINCT, are mapped to interfaces that are new in the JDBC 2.0 core API. This section describes each data type briefly; more complete information on each type can be found in the reference chapter for the corresponding interface. There is a chapter on the DISTINCT data type, but because DISTINCT types are mapped to a built-in type, there is no separate interface for it.

The new data types in the JDBC 2.0 core API represent a significant expansion in the types of data that can be used in a relational database. In general, they are more like objects; in fact, two of the new data types are UDTs that can optionally be custom mapped to classes in the Java programming language. A third UDT (JAVA_OBJECT) is itself an instance of a class defined in the Java programming language. Despite their advanced nature, all of the new data types in the JDBC 2.0 core API can be used as conveniently as the data types in the JDBC 1.0 API. For example, they can be used as column values in database tables, and they can be retrieved and stored using the appropriate getXXX and setXXX methods.

8.4.1 BLOB

The JDBC type BLOB represents an SQL3 BLOB (Binary Large Object).

A JDBC BLOB value is mapped to an instance of the Blob interface in the Java programming language. If a driver follows the standard implementation, a Blob object logically points to the BLOB value on the server rather than containing its binary data, greatly improving efficiency. The Blob interface provides methods for materializing the BLOB data on the client when that is desired.

8.4.2 CLOB

The JDBC type CLOB represents the SQL3 type CLOB (Character Large Object).

A JDBC CLOB value is mapped to an instance of the Clob interface in the Java programming language. If a driver follows the standard implementation, a Clob object logically points to the CLOB value on the server rather than containing its character data, greatly improving efficiency. Two of the methods on the Clob interface materialize the data of a CLOB object on the client.

8.4.3 ARRAY

The JDBC type ARRAY represents the SQL3 type ARRAY.

An ARRAY value is mapped to an instance of the Array interface in the Java programming language. If a driver follows the standard implementation, an Array object logically points to an ARRAY value on the server rather than containing the elements of the ARRAY object, which can greatly increase efficiency. The Array interface contains methods for materializing the elements of the ARRAY object on the client in the form of either an array or a ResultSet object.

8.4.4 DISTINCT

The JDBC type DISTINCT field (Types class)>DISTINCT represents the SQL3 type DISTINCT.

The standard mapping for a DISTINCT type is to the Java type to which the base type of a DISTINCT object would be mapped. For example, a DISTINCT type based on a CHAR would be mapped to a String object, and a DISTINCT type based on an SQL INTEGER would be mapped to an int.

The DISTINCT type may optionally have a custom mapping to a class in the Java programming language. A custom mapping consists of a class that implements the interface SQLData and an entry in a java.util.Map object.

8.4.5 STRUCT

The JDBC type STRUCT represents the SQL3 structured type. An SQL structured type, which is defined by a user with a CREATE TYPE statement, consists of one or more attributes. These attributes may be any SQL data type, built-in or user-defined.

The standard mapping for the SQL type STRUCT is to a Struct object in the Java programming language. A Struct object contains a value for each attribute of the STRUCT value it represents.

A STRUCT value may optionally be custom mapped to a class in the Java programming language, and each attribute in the STRUCT may be mapped to a field in the class. A custom mapping consists of a class that implements the interface SQLData and an entry in a java.util.Map object.

8.4.6 REF

The JDBC type REF represents an SQL3 type REF<structured type>. An SQL REF references (logically points to) an instance of an SQL structured type, which the REF persistently and uniquely identifies. In the Java programming language, the interface Ref represents an SQL REF.

If an application wants to point to an instance of an SQL structured type in the database rather than having its attribute values materialized on the client, it can use the type REF<structured type>, a reference to that SQL structured type.

A REF value is a unique identifier created specifically for a particular instance of an SQL structured type. It is persistently stored with the instance it references in a special table on the server. An application can select the REF value from its special table and use it in place of the structured type instance it identifies.

8.4.7 JAVA_OBJECT

The JDBC type JAVA_OBJECT, added in the JDBC 2.0 core API, makes it easier to use objects in the Java programming language as values in a database. JAVA_OBJECT is simply a type code for an instance of a class defined in the Java programming language that is stored as a database object. The type JAVA_OBJECT is used by a database whose type system has been extended so that it can store Java objects directly. The JAVA_OBJECT value may be stored as a serialized Java object, or it may be stored in some vendor-specific format.

The type JAVA_OBJECT is one of the possible values for the column DATA_TYPE in the ResultSet objects returned by various DatabaseMetaData methods, including getTypeInfo, getColumns, and getUDTs. The method getUDTs, part of the new JDBC 2.0 core API, will return information about the Java objects contained in a particular schema when it is given the appropriate parameters. Having this information available facilitates using a Java class as a database type.

For DBMSs that support them, values of type JAVA_OBJECT are stored in a database table using the method PreparedStatement.setObject. They are retrieved with the methods ResultSet.getObject or CallableStatement.getObject and updated with the ResultSet.updateObject method.

For example, assuming that instances of the class Engineer are stored in the column ENGINEERS in the table PERSONNEL, the following code fragment, in which stmt is a Statement object, prints out the names of all of the engineers.

ResultSet rs = stmt.executeQuery("SELECT ENGINEERS FROM PERSONNEL");
while (rs.next()) {
    Engineer eng = (Engineer)rs.getObject("ENGINEERS");
    System.out.println(eng.lastName + ", " + eng.firstName);
}

After the query returns the ResultSet object rs, which contains all of the instances of Engineer, the code retrieves each instance in turn with the method getObject. The value returned by getObject is an Object type, so it must be narrowed to the more specific type Engineer before being assigned to the variable eng.

8.5 Examples of Mapping

In any situation where a program written in the Java programming language retrieves data from a database, there has to be some form of mapping and data conversion. In most cases, programmers using the JDBC API will be programming with knowledge of their target database's schema. In other words, they know, for example, what tables the database contains and the data type for each column in those tables. They can therefore use the strongly typed access methods in the interfaces ResultSet, PreparedStatement, and CallableStatement. This section presents three different scenarios, describing the data mapping and conversion required in each case.

8.5.1 Simple SQL Statement

In the most common case, a user executes a simple SQL statement and gets back a ResultSet object with the results. Each value returned by the database and stored in a ResultSet column will have a JDBC data type. A call to a ResultSet.getXXX method will retrieve that value as a Java data type. For example, if a ResultSet column contains a JDBC FLOAT value, the method getDouble will retrieve that value as a Java double. Table 8.6 on page 110 shows which getXXX methods may be used to retrieve which JDBC types. (A user who does not know the type of a ResultSet column can get that information by calling the method ResultSet.getMetaData and then calling the method ResultSetMetaData.getColumnType.)

8.5.2 SQL Statement with IN Parameters

In another possible scenario, the user sends an SQL query that takes input parameters. In this case, the user calls the PreparedStatement.setXXX methods to assign a value to each input parameter. For example, PreparedStatement.setLong(1, 2345678) will assign the value 2345678 to the first parameter as a Java long. The driver will convert 2345678 to a JDBC BIGINT in order to send it to the database. Which JDBC type the driver sends to the database is determined by the standard mapping from Java types to JDBC types, shown in Table 8.2 on page 106.

8.5.3 SQL Statement with INOUT Parameters

In yet another scenario, a user wants to call a stored procedure, assign values to its INOUT parameters, retrieve values from a ResultSet object, and retrieve values from the parameters. This case is rather uncommon and more complicated than most, but it gives a good illustration of mapping and data conversion.

In this scenario, the first thing to do is to assign values to the INOUT parameters using PreparedStatement.setXXX methods. In addition, because the parameters will also be used for output, the programmer must register each parameter with the JDBC type of the value that the database will return to it. This is done with the method CallableStatement.registerOutParameter, which takes one of the JDBC types defined in the class Types. A programmer retrieves the values stored in the output parameters with CallableStatement.getXXX methods.

The XXX type used for CallableStatement.getXXX must map to the JDBC type registered for that parameter. For example, if the database is expected to return an output value whose type is JDBC REAL, the parameter should have been registered as java.sql.Types.REAL. Then to retrieve the JDBC REAL value, the method CallableStatement.getFloat should be called (the mapping from JDBC types to Java types is shown in Table 8.1 on page 105). The method getFloat will return the value stored in the output parameter after converting it from a JDBC REAL to a Java float. To accommodate various databases and make an application more portable, it is recommended that values be retrieved from ResultSet objects before values are retrieved from output parameters.

The following code demonstrates calling a stored procedure named getTestData, which has two parameters that are both INOUT parameters and which also returns a normal JDBC ResultSet. First the Connection object con creates the CallableStatement object cstmt. Then the method setByte sets the first parameter to 25 as a Java byte. The driver will convert 25 to a JDBC TINYINT and send it to the database. The method setBigDecimal sets the second parameter with an input value of 83.75. The driver will convert this Java BigDecimal object to a JDBC NUMERIC value. Next the two parameters are registered as OUT parameters, the first parameter as a JDBC TINYINT and the second parameter as a JDBC NUMERIC with two digits after the decimal point. After cstmt is executed, the values are retrieved from the ResultSet object using ResultSet.getXXX methods. The method getString gets the value in the first column as a Java String object, getInt gets the value in the second column as a Java int, and the second getInt retrieves the value in the third column as a Java int.

Then CallableStatement.getXXX methods retrieve the values stored in the output parameters. The method getByte retrieves the JDBC TINYINT as a Java byte, and getBigDecimal retrieves the JDBC NUMERIC as a Java BigDecimal object with two digits after the decimal point. Note that when a parameter is both an input and an output parameter, the setXXX method uses the same Java type as the getXXX method (as in setByte and getByte). The registerOutParameter method registers it to the JDBC type that is mapped from the Java type (a Java byte maps to a JDBC TINYINT, as shown in Table 8.2 on page 106).

CallableStatement cstmt = con.prepareCall(
    "{call getTestData(?, ?)}");
cstmt.setByte(1, 25);
cstmt.setBigDecimal(2, 83.75);
// register the first parameter as a JDBC TINYINT and the second
// as a JDBC NUMERIC with two digits after the decimal point
cstmt.registerOutParameter(1, java.sql.Types.TINYINT);
cstmt.registerOutParameter(2, java.sql.Types.NUMERIC, 2);
ResultSet rs = cstmt.executeQuery();
// retrieve and print values in result set
while (rs.next()) {
    String name = rs.getString(1);
    int score = rs.getInt(2);
    int percentile = rs.getInt(3);
    System.out.print("name = " + name + ", score = " + score);

    System.out.println(", percentile = " + percentile);
}
// retrieve values in output parameters
byte x = cstmt.getByte(1);
java.math.BigDecimal n = cstmt.getBigDecimal(2);

To generalize, the XXX in CallableStatement.getXXX and CallableStatement.setXXX methods is a Java type. For setXXX methods, the driver converts the Java type to a JDBC type before sending it to the database (using the standard mappings shown in Table 8.2 on page 106). For getXXX methods, the driver converts the JDBC type returned by the database to a Java type (using the standard mappings shown in Table 8.1 on page 105) before returning it to the getXXX method.

The method registerOutParameter always takes a JDBC type as an argument, and the method setObject may take a JDBC type as an argument.

Note that if a JDBC type is supplied in its optional third argument, the method setObject will cause an explicit conversion of the parameter value from a Java type to the JDBC type specified. If no target JDBC type is supplied to setObject, the parameter value will be converted to the JDBC type that is the standard mapping from the Java Object type (as shown in Table 8.4 on page 108). The driver will perform the explicit or implicit conversion before sending the parameter to the database.

8.6 Custom Mapping

The SQL3 user-defined types (UDTs), structured types and DISTINCT types, can be custom mapped to classes in the Java programming language. If a custom mapping has been set up, the driver will use that mapping instead of the standard mapping when it converts a UDT from a JDBC type to a Java type or vice versa.

UDTs are retrieved from the database with the methods ResultSet.getObject and CallableStatement.getObject; UDTs are sent back to the database with the method PreparedStatement.setObject. When an application calls a getObject method to retrieve a UDT, the driver will check to see if the type map associated with the connection has an entry for the UDT. If it does, the driver will use that type map to custom map the UDT; if there is no matching entry, the driver will use the standard mapping.

Almost all custom mapping is done using the connection's type map. It is possible, however, to have the driver use a different type map. The methods for which a custom mapping is possible have two versions, one that takes a type map and one that does not. The usual situation is not to supply a type map, in which case the driver uses the connection's type map by default. When a type map is supplied to a method, it supersedes the connection's type map, and the driver will use it instead of the type map associated with the connection to map a UDT. If the type map supplied has no entry for the UDT, the driver will use the standard mapping.

The setObject method does not take a type map as a parameter, so it operates a little differently. If setObject is passed an instance of a class that implements the SQLData interface, that is, an object that was custom mapped when it was retrieved, the driver will already have set up the mechanism for mapping it. The driver will convert the class instance, mapping the UDT back to its SQL type before sending it to the database. If the parameter to be set by the method setObject has not been custom mapped, the driver will use the standard mapping to convert it before sending it to the database.

The fact that only the methods getObject and setObject can be used to retrieve or store SQL structured types ensures that a custom mapping will be used if there is one. Four methods in the Array interface may be passed a type map so that if the ARRAY elements are UDTs, they can be custom mapped when the elements are materialized on the client. The Struct method getAttributes also has a version that takes a type map, which is used to custom map an SQL structured type's attributes before bringing them over to the client.

8.7 Dynamic Data Access

In most cases, the user wants to access results or parameters whose data types are known at compile time. However, some applications, such as generic browsers or query tools, are compiled with no knowledge of the database schema they will access. For this reason, JDBC provides support for fully dynamically typed data access in addition to static data type access.

Three methods facilitate accessing values whose data types are not known at compile time:

  • ResultSet.getObject
  • PreparedStatement.setObject
  • CallableStatement.getObject

If, for example, an application wants to be able to accept a variety of types as results in a ResultSet object, it can use the method ResultSet.getObject.

The methods ResultSet.getObject and CallableStatement.getObject retrieve a value as a Java Object. Since Object is the base class for all Java objects, an instance of any Java class can be retrieved as an instance of Object. However, the following Java types are built-in "primitive" types and are therefore not instances of the class Object: boolean, char, byte, short, int, long, float, and double. As a result, these types cannot be retrieved by getObject methods. However, each of these primitive types has a corresponding class that serves as a wrapper. Instances of these classes are objects, which means that they can be retrieved with the methods ResultSet.getObject and CallableStatement.getObject. Table 8.3 on page 107 shows the mapping from a JDBC type to a Java Object type. This table differs from the standard mapping from JDBC type to Java type in that each primitive Java type is replaced by its wrapper class, except that JDBC TINYINT and JDBC SMALLINT are mapped to the Java class Integer.

8.8 Storing Java Objects in a Database

Additions to the JDBC 2.0 core API make it easier to store Java objects in a database. The PreparedStatement.setObject method in the JDBC 1.0 API has always provided some support for persistent storage of objects defined in the Java programming language. With the new data type JAVA_OBJECT, in conjunction with the new method DatabaseMetaData.getUDTs, it is now easier to keep track of the Java objects stored in a database.

8.9 Tables for Type Mapping

This section contains the following tables relating to JDBC and Java data types:

Table 8.1-JDBC Types Mapped to Java Types

This table shows the conceptual correspondence between JDBC types and Java types. A programmer should write code with this mapping in mind. For example, if a value in the database is a SMALLINT, a short should be the data type used in a JDBC application.
All CallableStatement.getXXX methods except for getObject use this mapping. The getObject methods for both the CallableStatement and ResultSet interfaces use the mapping in "JDBC Types Mapped to Java Object Types" on page 107.

Table 8.2-Java Types Mapped to JDBC Types

This table shows the mapping a driver should use for the ResultSet.updateXXX methods and for IN parameters. PreparedStatement.setXXX methods and RowSet.setXXX methods use this table for mapping an IN parameter, which is a Java type, to the JDBC type that will be sent to the database. Note that the setObject methods for these two interfaces use the mapping shown in "Java Object Types Mapped to JDBC Types" on page 108.

Table 8.3-JDBC Types Mapped to Java Object Types

ResultSet.getObject and CallableStatement.getObject use the mapping shown in this table for standard mappings.

Table 8.4-Java Object Types Mapped to JDBC Types

PreparedStatement.setObject and RowSet.setObject use the mapping shown in this table when no parameter specifying a target JDBC type is provided.

Table 8.5-Conversions by setObject from Java Object Types to JDBC Types

This table shows which JDBC types may be specified as the target JDBC type to the methods PreparedStatement.setObject and RowSet.setObject.

Table 8.6-Type Conversions Supported by ResultSet.getXXX Methods

This table shows which JDBC types may be returned by ResultSet.getXXX methods. A bold X indicates the method recommended for retrieving a JDBC type. A plain x indicates for which JDBC types it is possible to use a getXXX method.
This table also shows the conversions used by the SQLInput.readXXX methods, except that they use only the recommended conversions.

Table 8.7-JDBC Types Mapped to Database-specific SQL Types

This table shows the names used by individual databases for their data types that most closely correspond to the JDBC types.

8.9.1 JDBC Types Mapped to Java Types
JDBC Type | Java Type
CHAR | String
VARCHAR | String
LONGVARCHAR | String
NUMERIC | java.math.BigDecimal
DECIMAL | java.math.BigDecimal
BIT | boolean
TINYINT | byte
SMALLINT | short
INTEGER | int
BIGINT | long
REAL | float
FLOAT | double
DOUBLE | double
BINARY | byte[]
VARBINARY | byte[]
LONGVARBINARY | byte[]
DATE | java.sql.Date
TIME | java.sql.Time
TIMESTAMP | java.sql.Timestamp
CLOB | Clob
BLOB | Blob
ARRAY | Array
DISTINCT | mapping of underlying type
STRUCT | Struct
REF | Ref
JAVA_OBJECT | underlying Java class

This table has two purposes. First, it illustrates the general correspondence between types in the Java programming language and the SQL types. Second, it shows the mapping used by CallableStatement.getXXX methods and SQLInput.readXXX methods. (Note that the mapping used by the CallableStatement.getObject method is shown in Table 8.3.)

8.9.2 Java Types Mapped to JDBC Types
Java Type | JDBC Type
String | CHAR, VARCHAR, or LONGVARCHAR
java.math.BigDecimal | NUMERIC
boolean | BIT
byte | TINYINT
short | SMALLINT
int | INTEGER
long | BIGINT
float | REAL
double | DOUBLE
byte[] | BINARY, VARBINARY, or LONGVARBINARY
java.sql.Date | DATE
java.sql.Time | TIME
java.sql.Timestamp | TIMESTAMP
Clob | CLOB
Blob | BLOB
Array | ARRAY
Struct | STRUCT
Ref | REF
Java class | JAVA_OBJECT

This table shows the conversions used for IN parameters before they are sent to the DBMS, used by the PreparedStatement.setXXX and RowSet.setXXX methods. These same conversions are also used by ResultSet.updateXXX methods and SQLOutput.writeXXX methods. (Note that the PreparedStatement.setObject and RowSet.setObject methods use the mapping in Table 8.4.)

The mapping for String will normally be VARCHAR but will turn into LONGVARCHAR if the given value exceeds the driver's limit on VARCHAR values. The same is true for byte[], which may be mapped to either VARBINARY or LONGVARBINARY values, depending on the driver's limit on VARBINARY values. In most cases, the choice between CHAR and VARCHAR is not significant. In any case, drivers will just make the right choice. The same is true for the choice between BINARY and VARBINARY.

8.9.3 JDBC Types Mapped to Java Object Types
JDBC Type | Java Object Type
CHAR | String
VARCHAR | String
LONGVARCHAR | String
NUMERIC | java.math.BigDecimal
DECIMAL | java.math.BigDecimal
BIT | Boolean
TINYINT | Integer
SMALLINT | Integer
INTEGER | Integer
BIGINT | Long
REAL | Float
FLOAT | Double
DOUBLE | Double
BINARY | byte[]
VARBINARY | byte[]
LONGVARBINARY | byte[]
DATE | java.sql.Date
TIME | java.sql.Time
TIMESTAMP | java.sql.Timestamp
DISTINCT | Object type of underlying type
CLOB | Clob
BLOB | Blob
ARRAY | Array
STRUCT | Struct or SQLData
REF | Ref
JAVA_OBJECT | underlying Java class

This table shows the mapping from JDBC types to Java object types that is used by the ResultSet.getObject and CallableStatement.getObject methods.

8.9.4 Java Object Types Mapped to JDBC Types
Java Object Type | JDBC Type
String | CHAR, VARCHAR, or LONGVARCHAR
java.math.BigDecimal | NUMERIC
Boolean | BIT
Integer | INTEGER
Long | BIGINT
Float | REAL
Double | DOUBLE
byte[] | BINARY, VARBINARY, or LONGVARBINARY
java.sql.Date | DATE
java.sql.Time | TIME
java.sql.Timestamp | TIMESTAMP
Clob | CLOB
Blob | BLOB
Array | ARRAY
Struct | STRUCT
Ref | REF
Java class | JAVA_OBJECT

These are the mappings used by the PreparedStatement.setObject method when no parameter specifying a target JDBC type is given. (The JDBC types that may be specified to the PreparedStatement.setObject method are shown in Table 8.5.)

Note that the mapping for String will normally be VARCHAR but will turn into LONGVARCHAR if the given value exceeds the driver's limit on VARCHAR values. The case is similar for byte[], which will be VARBINARY or LONGVARBINARY, depending on the driver's limit for VARBINARY values.

8.9.5 Conversions by setObject

Conversions by setObject [D]

An "x" means that the given Java object type may be converted to the given JDBC type. This table show the possible values for the parameter specifying a target JDBC type that is passed to the method PreparedStatement.setObject or RowSet.setObject. Note that some conversions may fail at run time if the value presented is invalid.

8.9.6 Conversions by ResultSet.getXXX Methods

Conversions by ResultSet.getXXX Methods [D]
SQLInput.readXXX methods support only the recommended conversions. An "x" means that the method can retrieve the JDBC type. An "X" means that the method is recommended for retrieving the JDBC type.

8.9.7 JDBC Types Mapped to Database-specific SQL Types

There is considerable variation among the different SQL types supported by the different databases. Table 8.7 shows the database-specific SQL types that best match the JDBC type for various major databases. The presence of a database-specific type name indicates that the given type can be used to achieve the semantics of the corresponding JDBC type, though the database-specific type may also provide additional semantics.

Notes and Lamentations:

  1. Some databases provide extra precision for some integral and floating-point types.
  2. Some databases provide a DATE or DATETIME type that can be used to contain either a DATE or a TIME or both.
  3. VARCHAR and VARCHAR2 are currently synonyms in Oracle8.
  4. For LONGVARCHAR, DB2 also supports "CLOB(n)" with a limit of 2 gigabytes.
  5. For LONGVARBINARY, DB2 also supports "BLOB(n)" with a limit of 2 gigabytes.
  6. Handling of BINARY, VARBINARY, and LONGVARBINARY literals in SQL statements varies widely among databases. We recommend using PreparedStatement.setBytes to set values in a portable way.
  7. Handling of DATE, TIME, and TIMESTAMP literals in SQL statements varies widely among databases. We recommend using the JDBC SQL escape syntax for dates and times (see "SQL Escape Syntax in Statements" on page 36) to set Date, Time, and Timestamp values in a portable way.

Types mapped to Database-specific SQL types [D]

See long description for previous image

[Top] [Prev] [Next]

Copyright © 1999, Sun Microsystems, Inc. All rights reserved.


 [Top] [Prev] [Next]

PreparedStatement

NOTE: The material in this chapter is based on JDBCtm API Tutorial and Reference, Second Edition: Universal Data Access for the Javatm 2 Platform, published by Addison Wesley as part of the Java series, ISBN 0-201-43328-1.

6.1 PreparedStatement Overview

The PreparedStatement interface inherits from Statement and differs from it in two ways:

  1. Instances of PreparedStatement contain an SQL statement that has already been compiled. This is what makes a statement "prepared."
  2. The SQL statement contained in a PreparedStatement object may have one or more IN parameters. An IN parameter is a parameter whose value is not specified when the SQL statement is created. Instead, the statement has a question mark ("?") as a placeholder for each IN parameter. The "?" is also known as a parameter marker. An application must set a value for each question mark in a prepared statement before executing the prepared statement.

Because PreparedStatement objects are precompiled, their execution can be faster than that of Statement objects. Consequently, an SQL statement that is executed many times is often created as a PreparedStatement object to increase efficiency.

Being a subclass of Statement, PreparedStatement inherits all the functionality of Statement. In addition, it adds a set of methods that are needed for setting the values to be sent to the database in place of the placeholders for IN parameters. Also, the three methods execute, executeQuery, and executeUpdate are modified so that they take no argument. The Statement forms of these methods (the forms that take an SQL statement parameter) should never be used with a PreparedStatement object.

6.1.1 Creating PreparedStatement Objects

The following code fragment, where con is a Connection object, creates a PreparedStatement object containing an SQL update statement with two placeholders for IN parameters:

PreparedStatement pstmt = con.prepareStatement(
    "UPDATE table4 SET m = ? WHERE x = ?");

The object pstmt now contains the statement "UPDATE table4 SET m = ? WHERE x = ?", which has already been sent to the DBMS and been prepared for execution.

As with Statement objects, it is possible to create a PreparedStatement object that contains a query rather than an update statement; in fact, this is often done to improve efficiency for SQL statements that are executed many times. Using the new version of the method prepareStatement included in the JDBC 2.0 core API, the PreparedStatement object can produce ResultSet objects that are scrollable and updatable. For example, the following code fragment creates a PreparedStatement object such that each time it is executed, it will produce a ResultSet object that is scrollable and updatable.

PreparedStatement pstmt2 = con.prepareStatement(
            "SELECT a, b, c FROM Table1", ResultSet.TYPE_SCROLL_SENSITIVE,
            ResultSet.CONCUR_UPDATABLE);
ResultSet rs = pstmt2.executeQuery();

The object that rs represents is a result set with all the values stored in columns a, b, and c of Table1, and rs is scrollable and can be updated. Each time pstmt2 is executed, it will produce a result set that is scrollable and updatable.

6.1.2 Passing IN Parameters

Before a PreparedStatement object is executed, the value of each ? parameter must be set. This is done by calling a setXXX method, where XXX is the appropriate type for the parameter. For example, if the parameter is of type long in the Java programming language, the method to use is setLong. The first argument to the setXXX methods is the ordinal position of the parameter to be set, with numbering starting at 1. The second argument is the value to which the parameter is to be set. For example, the following code sets the first parameter to 123456789 and the second parameter to 100000000:

pstmt.setLong(1, 123456789);
pstmt.setLong(2, 100000000);

Once a parameter value has been set for a given statement, it can be used for multiple executions of that statement until it is cleared by a call to the method clearParameters or until a new value is set.

When a connection has its auto-commit mode enabled, each statement is committed automatically when it is completed. Some database systems do not retain prepared statements across commits, so for them, the driver will have to recompile the prepared statement after each commit. This means that for these DBMSs, it may actually be less efficient to use a PreparedStatement object in place of a Statement object that is executed many times.

Using pstmt, the PreparedStatement object created above, the following code illustrates setting values for the two parameter placeholders and executing pstmt 10 times. In this example, the first parameter is set to "Hi" and remains constant. The second parameter is set to a different value each time around the for loop, starting with 0 and ending with 9.

pstmt.setString(1, "Hi");
for (int i = 0; i < 10; i++) {
    pstmt.setInt(2, i);
    int rowCount = pstmt.executeUpdate();
}

New features in the JDBC 2.0 API make it possible to set a parameter placeholder with an SQL3 data type, as shown in the following example, where statistics is a Blob object representing an SQL BLOB value, and departments is an Array object representing an SQL ARRAY value.

PreparedStatement pstmt = con.prepareStatement(
      "UPDATE Table3 SET Stats = ? WHERE Depts = ?");
pstmt.setBlob(1, statistics);
pstmt.setArray(2, departments);

6.1.3 Data Type Conformance on IN Parameters

The XXX in a setXXX method is a type in the Java programming language. It also implicitly specifies a JDBC type because the driver will map the Java type to its corresponding JDBC type (following the mapping specified in "Java Types Mapped to JDBC Types" on page 106) and send that JDBC type to the database. For example, the following code fragment sets the second parameter of the PreparedStatement object pstmt to 44, with a Java type of short:

pstmt.setShort(2, 44);

The driver will send 44 to the database as a JDBC SMALLINT, which is the standard mapping from a Java short.

It is the programmer's responsibility to make sure that the type in the Java programming language for each IN parameter maps to a JDBC type that is compatible with the JDBC data type expected by the database. Consider the case where the database expects a JDBC SMALLINT. If the method setByte is used, the driver will send a JDBC TINYINT to the database. This will probably work because many database systems convert from one related type to another, and generally a TINYINT can be used anywhere a SMALLINT is used. However, for an application to work with the most database systems possible, it is best to use types in the Java programming language that correspond to the exact JDBC types expected by the database. If the expected JDBC type is SMALLINT, using setShort instead of setByte will make an application more portable. The table "Java Types Mapped to JDBC Types" in the chapter "Mapping SQL and Java Types" can be used to determine which setXXX method to use.

6.1.4 Using setObject

A programmer can explicitly convert an input parameter to a particular JDBC type by using the method setObject. This method can take a third argument, which specifies the target JDBC type. The driver will convert the Object in the Java programming language to the specified JDBC type before sending it to the database.

If no JDBC type is given, the driver will simply map the Java Object to its default JDBC type and then send it to the database. This is similar to what happens with the regular setXXX methods; in both cases, the driver maps the Java type of the value to the appropriate JDBC type before sending it to the database. The difference is that the setXXX methods use the standard mapping, whereas the setObject method uses the mapping to object types.

The capability of the method setObject to accept any Java object allows an application to be generic and accept input for a parameter at run time. In this situation the type of the input is not known when the application is compiled. By using setObject, the application can accept any Java object type as input and convert it to the JDBC type expected by the database.

The JDBC 2.0 core API includes a new implementation of the method setObject that applies to a user-defined type (UDT) that has been custom mapped to a class in the Java programming language. The custom mapping of an SQL UDT is specified in a class that implements the SQLData interface. When a UDT instance is retrieved from the database via the method getObject, it will be mapped to an instance of the Java class that implemented SQLData for it. When that custom mapped instance is passed to the method setObject, setObject will call the SQLOutput.writeObject method that is defined in the appropriate SQLData implementation, thereby converting the instance of a Java class back to an SQL UDT.

The details of custom mapping are hidden from the user. When an application invokes the method setObject, the value being stored will automatically be custom mapped if there is a custom mapping for it. As a result, code in which the method setObject performs a custom mapping looks identical to code in which setObject uses the standard mapping. UDTs can only be stored using the setObject method, which is a way of ensuring that UDTs with a custom mapping are mapped appropriately.

In all of the cases discussed so far, the value passed to the method setObject was originally an SQL data type that was retrieved from a table column. Before returning it to the database, the driver needed to convert it back to its SQL data type. If a database is one of the new generation of Java-aware DBMSs, called a Java relational DBMS, it can store an instance of a class defined in the Java programming language as well as values defined in SQL. A class instance may be stored as a serialized Java object or in some other format defined by the DBMS.

The following example shows the use of the method setObject to store emp, an instance of the class Employee. After the salary field of emp is increased by 50 per cent, emp is sent back to the database. The column EMPLOYEE in the table PERSONNEL stores instances of Employee.

emp.salary = emp.salary * 1.5;
PreparedStatement pstmt = con.prepareStatement(
    "UPDATE PERSONNEL SET EMPLOYEE = ? WHERE EMPLOYEE_NO = 300485");
pstmt.setObject(1, emp);
pstmt.executeUpdate();

Note that the syntax in this example is the same as that in the JDBC 1.0 API and is also the same as that used to store instances of UDTs that have been custom mapped.

6.1.5 Sending JDBC NULL as an IN parameter

The setNull method allows a programmer to send a JDBC NULL (a generic SQL NULL) value to the database as an IN parameter. Note, however, that one must still specify the JDBC type of the parameter.

A JDBC NULL will also be sent to the database when a Java null value is passed to a setXXX method (if it takes Java objects as arguments). The method setObject, however, can take a null value only if the JDBC type is specified.

6.1.6 Sending Very Large IN Parameters

The methods setBytes and setString are capable of sending unlimited amounts of data. Sometimes, however, programmers prefer to pass in large blobs of data in smaller chunks. This can be accomplished by setting an IN parameter to a Java input stream. When the statement is executed, the JDBC driver will make repeated calls to this input stream, reading its contents and transmitting those contents as the actual parameter data.

The JDBC 1.0 API provides two methods for setting IN parameters to input streams: setBinaryStream for streams containing uninterpreted bytes and setAsciiStream for streams containing ASCII characters. A third method, set-UnicodeStream for streams containing Unicode characters, has been deprecated; the new JDBC 2.0 core API method setCharacterStream should be used in its place. These stream methods take one more argument than the other setXXX methods because the total length of the stream must be specified. This is necessary because some database systems need to know the total transfer size before any data is sent.

The following code illustrates using a stream to send the contents of a file as an IN parameter.

java.io.File file = new java.io.File("/tmp/data");
int fileLength = file.length();
java.io.InputStream fin = new java.io.FileInputStream(file);
java.sql.PreparedStatement pstmt = con.prepareStatement(
    "UPDATE Table5 SET stuff = ? WHERE index = 4");
pstmt.setBinaryStream (1, fin, fileLength);
pstmt.executeUpdate();

When the statement executes, the input stream fin will get called repeatedly to deliver up its data.

Another way to send large IN parameters to the database is to use SQL3 types like BLOB and CLOB. This is different from using streams in that BLOB and CLOB values are originally retrieved from the database, where they were created as SQL types. Using streams makes it possible to send the contents of a file written in the Java programming language to the database.

6.1.7 Using PreparedStatement Objects in Batch Updates

The JDBC 2.0 core API provides the ability to send multiple updates to the database for execution as a batch. The Statement method addBatch is given an SQL update statement as a parameter, and the SQL statement is added to the Statement object's list of commands to be executed in the next batch. The interface PreparedStatement has its own version of the method addBatch, which adds a set of parameters to the batch, as shown in the following code fragment.

PreparedStatement pstmt = con.prepareStatement(
         "UPDATE Table4 SET History = ? WHERE ID = ?");
pstmt.setClob(1, clob1);
pstmt.setLong(2, 350985839);
pstmt.addBatch();

pstmt.setClob(1, clob2);
pstmt.setLong(2, 350985840);
pstmt.addBatch();

int [] updateCounts = pstmt.executeBatch();

When the PreparedStatement object in pstmt is executed, it will be executed twice, once with the parameters clob1 and 350985839, and a second time with the parameters clob2 and 350985840. If either update command returns anything other than a single update count, the method executeBatch will throw an exception.

[Top] [Prev] [Next]

Copyright © 1999, Sun Microsystems, Inc. All rights reserved.


 [Top] [Prev] [Next]

ResultSet

NOTE: The material in this chapter is based on JDBCtm API Tutorial and Reference, Second Edition: Universal Data Access for the Javatm 2 Platform, published by Addison Wesley as part of the Java series, ISBN 0-201-43328-1.

5.1 ResultSet Overview

A ResultSet is a Java object that contains the results of executing an SQL query. In other words, it contains the rows that satisfy the conditions of the query. The data stored in a ResultSet object is retrieved through a set of get methods that allows access to the various columns of the current row. The ResultSet.next method is used to move to the next row of the ResultSet, making it the current row.

The general form of a result set is a table with column headings and the corresponding values returned by a query. For example, if your query is SELECT a, b, c FROM Table1, your result set will have the following form:

a           b               c
----------  ------------    -----------
12345       Cupertino       2459723.495
83472       Redmond         1.0
83492       Boston          35069473.43

The following code fragment is an example of executing an SQL statement that will return a collection of rows, with column a as an int, column b as a String, and column c as a float:

java.sql.Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");
while (rs.next()) {
    // retrieve and print the values for the current row
    int i = rs.getInt("a");
    String s = rs.getString("b");
    float f = rs.getFloat("c");
    System.out.println("ROW = " + i + " " + s + " " + f);
}

5.1.1 Rows and Columns

A relational database is made up of tables, with each table consisting of rows and columns. A row in a relational database table can be thought of as representing an instance of the entity that the table represents. For example, if there is a table of employees, each row will contain information about a particular employee. Each piece of data about the employee is stored in a column, so, for instance, the table of employees could have columns for an identification number, a name, a salary, and a date of hire. The columns in a row would contain the ID number, name, salary, and date of hire for a particular employee.

A result set is also a table with rows and columns, but it contains only the column values from a database table that satisfy the conditions of a query. In other words, a result set row will contain a subset of the columns in the underlying database table (unless the query selects everything in the table, in which case the result set table will include all of the column values for every row in the database table). In the past, a column value in a relational database table (and consequently in a result set table) had to be atomic; that is, it could be only one indivisible value. For instance, an array could not be a column value because an array may be made up of multiple elements. With the advent of SQL3 data types, however, the permissible content of table columns has expanded dramatically. It is now possible for an array or even a user-defined structured type to be a column value. Because this new capability allows a relational database to store instances of complex types as column values, it makes a relational database more like an object database, blurring the distinction between relational and object databases. Programmers can take advantage of these new data types if they use a JDBC 2.0 driver that supports SQL3 types.

5.1.2 Cursors

A ResultSet object maintains a cursor, which points to its current row of data. The cursor moves down one row each time the method next is called. When a ResultSet object is first created, the cursor is positioned before the first row, so the first call to the next method puts the cursor on the first row, making it the current row. ResultSet rows can be retrieved in sequence from top to bottom as the cursor moves down one row with each successive call to the method next. This ability to move its cursor only forward is the default behavior for a ResultSet and is the only cursor movement possible with drivers that implement only the JDBC 1.0 API. This kind of result set has the type ResultSet.TYPE_FORWARD_ONLY and is referred to as a forward only result set.

If a driver implements the cursor movement methods in the JDBC 2.0 core API, its result sets can be scrollable. A scrollable result set's cursor can move both forward and backward as well as to a particular row. The following methods move the cursor backward, to the first row, to the last row, to a particular row number, to a specified number of rows from the current row, and so on: previous, first, last, absolute, relative, afterLast, and beforeFirst. An explanation and example of how to make a result set scrollable will be presented in the section "Creating Different Types of Result Sets" on page 55.

When a cursor is positioned on a row in a ResultSet object (not before the first row or after the last row), that row becomes the current row. This means that any methods called while the cursor is positioned on that row will (1) operate on values in that row (methods such as getXXX and updateXXX), (2) operate on the row as a whole (such as the methods updateRow, insertRow, deleteRow, refresh-Row), or (3) use that row as a starting point for moving to other rows (such as the method relative).

A cursor remains valid until the ResultSet object or its parent Statement object is closed.

5.1.3 Cursor Movement Examples

As stated in the previous section, the standard cursor movement for forward only result sets is to use the method next to iterate through each row of a result set once from top to bottom. With scrollable result sets, it is possible to revisit a row or to iterate through the result set multiple times. This is possible because the cursor can be moved before the first row at any time (with the method beforeFirst method (ResultSet interface)>beforeFirst). The cursor can begin another iteration through the result set with the method next. The following example positions the cursor before the first row and then iterates forward through the contents of the result set. The methods getString and getFloat retrieve the column values for each row until there are no more rows, at which time the method next returns the value false.

rs.beforeFirst();
while (rs.next()) {
    System.out.println(rs.getString("EMP_NO") +
        " " + rs.getFloat("SALARY");
}

It is also possible to iterate through a result set backwards, as is shown in the next example. The cursor is first moved to the very end of the result set (with the method afterLast), and then the method previous is invoked within a while loop to iterate through the contents of the result set by moving to the previous row with each iteration. The method previous returns false when there are no more rows, so the loop ends after all the rows have been visited.

rs.afterLast();
while (rs.previous()) {
    System.out.println(rs.getString("EMP_NO") +
        " " + rs.getFloat("SALARY");
}

The interface ResultSet offers still other ways to iterate through the rows of a scrollable result set. Care should be taken, however, to avoid incorrect alternatives such as the one illustrated in the following example:

// incorrect!
while (!rs.isAfterLast()) {
  rs.relative(1);
  System.out.println(
    rs.getString("EMP_NO") + " " + rs.getFloat("SALARY"));
}

This example attempts to iterate forward through a scrollable result set and is incorrect for several reasons. One error is that if ResultSet.isAfterLast is called when the result set is empty, it will return a value of false since there is no last row. The loop body will be executed, which is not what is wanted. An additional problem occurs when the cursor is positioned before the first row of a result set that contains data. In this case, calling rs.relative(1) is erroneous because there is no current row. The method relative moves the cursor the specified number of rows from the current row, and it must be invoked only while the cursor is on the current row.

The following code fragment fixes the problems in the previous example. Here a call to the method ResultSet.first is used to distinguish the case of an empty result set from one that contains data. Because ResultSet.isAfterLast is called only when the result set is non-empty, the loop control works correctly. Since ResultSet.first method (ResultSet interface)>first initially positions the cursor on the first row, the method ResultSet.relative(1) steps through the rows of the result set as expected.

if (rs.first()) {
  while (!rs.isAfterLast()) {
    System.out.println(
         rs.getString("EMP_NO") + " " + rs.getFloat("SALARY"));
    rs.relative(1);
    }
}

5.1.4 Determining the Number of Rows in a Result Set

With the new cursor movement methods, it is easy to see how many rows a scrollable ResultSet object contains. All that is necessary is to go to the last row of the result set and get the number of that row. In the following example, rs will have one row for each employee.

ResultSet rs = stmt.executeQuery(
        "SELECT LAST_NAME, FIRST_NAME FROM EMPLOYEES");
rs.last();
int numberOfRows = rs.getRow();
System.out.println("XYZ, Inc. has " + numberOfRows + " employees");
rs.beforeFirst();
while (next()) {
    . . . // retrieve first and last names of each employee
}

Though not as convenient, it is also possible to find out how many rows a nonscrollable result set has. The following example shows one way to determine the number of rows.

ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM EMPLOYEES");
rs.next();
int count = rs.getInt(1);
System.out.println("XYZ, Inc. has " + count + " employees");

ResultSet rs2 = stmt.executeQuery(
        "SELECT LAST_NAME, FIRST_NAME FROM EMPLOYEES");
while (rs2.next()) {
    . . . // retrieve first and last names of each employee
}

With the scrollable result set, the cursor was just repositioned to start iterating through the same result set to retrieve its data. In the preceding example, however, one query is needed to get the count, and another query is needed to get a result set with the data that is desired. Both queries must, of course, produce result sets of the same size for the count to be accurate.

A second way to determine the number of rows in a forward-only result set is to iterate through the result set, incrementing a variable with each iteration, which is shown in the following example. Because an application can iterate through a forward-only result set just once, the same query needs to be executed twice. In the iteration through the first rs, the number of rows is counted; in the iteration through the second rs, the data is retrieved.

ResultSet rs = stmt.executeQuery(
        "SELECT LAST_NAME, FIRST_NAME FROM EMPLOYEES");
int count = 0;
while (rs.next()) {
    count++;
}
System.out.println("Company XYZ has " + count " employees.");
rs = stmt.executeQuery(
        "SELECT LAST_NAME, FIRST_NAME FROM EMPLOYEES");
while (rs.next()) {
    . . . // retrieve first and last names of each employee
}

5.1.5 Retrieving Column Values

The ResultSet.getXXX methods provide the means for retrieving column values from the current row. For maximum portability with forward only result sets, values should be retrieved from left to right, and column values should be read only once. With scrollable result sets, however, there are no such restrictions.

Either the column name or the column number can be used to designate the column from which to retrieve data. For example, if the second column of a ResultSet object rs is named TITLE, and it stores values as strings, either of the following will retrieve the value stored in that column:

String s = rs.getString(2);
String s = rs.getString("TITLE");

Note that columns are numbered from left to right starting with column 1. Also, column names used as input to getXXX methods are case insensitive.

The option of using the column name was provided so that a user who specifies column names in a query can use those same names as the arguments to getXXX methods. If, on the other hand, the SELECT statement does not specify column names (as in "SELECT * FROM TABLE1" or in cases where a column is derived), column numbers should be used. In such situations, there is no way for the user to know for sure what the column names are.

In some cases, it is possible for an SQL query to return a result set that has more than one column with the same name. If a column name is used as the parameter to a getXXX method, getXXX will return the value of the first matching column name. Thus, if there are multiple columns with the same name, one needs to use a column index to be sure that the correct column value is retrieved. It may also be slightly more efficient to use column numbers.

If the name of a column is known but not its index, the method findColumn can be used to find the column number.

Information about the columns in a ResultSet is available by calling the method ResultSet.getMetaData. The ResultSetMetaData object returned gives the number, types, and properties of its ResultSet object's columns.

5.1.6 Which getXXX Method to Use

JDBC drivers support type coercion. When a getXXX method is invoked, the driver attempts to convert the underlying data to the type XXX in the Java programming language and then returns a suitable value. For example, if the getXXX method is getString, and the data type of the data in the underlying database is VARCHAR, the JDBC Compliant driver will convert the VARCHAR value to a String object in the Java programming language. That String object will be the value returned by getString.

The JDBC 2.0 API adds new ResultSet.getXXX methods for retrieving the new SQL3 data types. These methods work the same way the getXXX methods in the JDBC 1.0 API work; that is, they map the SQL3 JDBC type to a type in the Java programming language and return that type. For example, the method getClob retrieves a JDBC CLOB value from the database and returns a Clob object, which is an instance of the java.sql.Clob interface.

The method getObject will retrieve any data type. This is possible because Object, being the type from which every other object type in the Java programming language is derived, is the most generic type. This is especially useful when the underlying data type is a database-specific type or when a generic application needs to be able to accept any data type. The method getObject, as would be expected from its name, returns a Java Object that must be narrowed if it is to be used as a more specific type. In other words, it must be cast from its generic Object type to its more derived type before it can be used as that derived type. The following code fragment illustrates using the method getObject to retrieve a Struct value from the column ADDRESS in the current row of the ResultSet object rs. The Object that getObject returns is narrowed to a Struct before assigning it to the variable address.

Struct address = (Struct)rs.getObject("ADDRESS");

The method getObject is not only the one method capable of retrieving values of any data type but also the only ResultSet.getXXX method that does custom mapping. Therefore, to be custom mapped, a data type has to be retrieved with the method getObject. The two SQL data types that can be custom mapped are the user-defined types, SQL structured types and DISTINCT types. A JDBC DISTINCT value is normally retrieved with the getXXX method appropriate for its underlying type, but if it has a custom mapping, it must be retrieved by the method getObject in order to be custom mapped. A JDBC STRUCT can only be retrieved with the method getObject, guaranteeing that if there is a custom mapping for a JDBC STRUCT value, it will be used.

use of ResultSet.getXXX methods to retriee JDBC types [D]

An "x" indicates that the getXXX method may legally be used to retrieve the given JDBC type.

An "X" indicates that the getXXX method is recommended for retrieving the given JDBC type.

5.1.7 Types of Result Sets

Results sets may have different levels of functionality. For example, they may be scrollable or nonscrollable. A scrollable result set has a cursor that moves both forward and backward and can be moved to a particular row. Also, result sets may be sensitive or insensitive to changes made while they are open; that is, they may or may not reflect changes to column values that are modified in the database. A developer should always keep in mind the fact that adding capabilities to a ResultSet object incurs additional overhead, so it should be done only as necessary.

Based on the capabilities of scrollability and sensitivity to changes, there are three types of result sets available with the JDBC 2.0 core API. The following constants, defined in the ResultSet interface, are used to specify these three types of result sets:

  1. TYPE_FORWARD_ONLY
    • The result set is nonscrollable; its cursor moves forward only, from top to bottom.
    • The view of the data in the result set depends on whether the DBMS materializes results incrementally.
  2. TYPE_SCROLL_INSENSITIVE
    • The result set is scrollable: Its cursor can move forward or backward and can be moved to a particular row or to a row whose position is relative to its current position.
    • The result set generally does not show changes to the underlying database that are made while it is open. The membership, order, and column values of rows are typically fixed when the result set is created.
  3. TYPE_SCROLL_SENSITIVE
    • The result set is scrollable; its cursor can move forward or backward and can be moved to a particular row or to a row whose position is relative to its current position.
    • The result set is sensitive to changes made while it is open. If the underlying column values are modified, the new values are visible, thus providing a dynamic view of the underlying data. The membership and ordering of rows in the result set may be fixed or not, depending on the implementation.

5.1.8 Concurrency Types

A result set may have different update capabilities. As with scrollability, making a ResultSet object updatable increases overhead and should be done only when necessary. That said, it is often more convenient to make updates programmatically, and that can only be done if a result set is made updatable. The JDBC 2.0 core API offers two update capabilities, specified by the following constants in the ResultSet interface:

  1. CONCUR_READ_ONLY
    • Indicates a result set that cannot be updated programmatically
    • The one concurrency type available to drivers that implement only the JDBC 1.0 API
    • Offers the highest level of concurrency (allows the largest number of simultaneous users). When a ResultSet object with read-only concurrency needs to set a lock, it uses a read-only lock. This allow users to read data but not to change it. Because there is no limit to the number of read-only locks that may be held on data at one time, there is no limit to the number of concurrent users unless the DBMS or driver imposes one.
  2. CONCUR_UPDATABLE
    • Indicates a result set that can be updated programmatically
    • Available to drivers that implement the JDBC 2.0 core API
    • Reduces the level on concurrency. Updatable results sets may use write-only locks so that only one user at a time has access to a data item. This eliminates the possibility that two or more users might change the same data, thus ensuring database consistency. However, the price for this consistency is a reduced level of concurrency.

To allow a higher level of concurrency, an updatable result set may be implemented so that it uses an optimistic concurrency control scheme. This implementation assumes that conflicts will be rare and avoids using write-only locks, thereby permitting more users concurrent access to data. Before committing any updates, it determines whether a conflict has occurred by comparing rows either by value or by a version number. If there has been an update conflict between two transactions, one of the transactions will be aborted in order to maintain consistency. Optimistic concurrency control implementations can increase concurrency; however, if there are too many conflicts, they may actually reduce performance.

5.1.9 Providing Performance Hints

Many DBMSs and drivers are optimized to give the best performance under various circumstances, which means that generally a database programmer is best advised to use their default settings. However, for programmers who may want to fine tune database performance for a particular application, the JDBC 2.0 API provides methods that give hints to the driver for making access to result set data more efficient. These performance hints are exactly that, just hints; a JDBC Compliant driver may choose to ignore them.

The following two hints give the driver suggestions for improving performance:

  1. The number of rows that should be fetched from the database each time new rows are needed The number of rows to be fetched is called the fetch size, and it can be set by two different methods: Statement.setFetchSize and ResultSet.setFetchSize. The statement that creates a ResultSet object sets the default fetch size for that ResultSet object, using the Statement method setFetchSize. The following code fragment sets the fetch size for the ResultSet object rs to 25. Until the fetch size is changed, any result set created by the Statement object stmt will automatically have a fetch size of 25.
    Statement stmt = con.createStatement();
stmt.setFetchSize(25);
ResultSet rs = stmt.executeQuery(SELECT * FROM EMPLOYEES);
    A result set can, at any time, change its default fetch size by setting a new fetch size with the ResultSet version of the method setFetchSize. Continuing from the previous code fragment, the following line of code changes the fetch size of rs to 50:
    rs.setFetchSize(50);
    Normally the most efficient fetch size is already the default for the driver. The method setFetchSize simply allows a programmer to experiment to see if a certain fetch size is more efficient than the default for a particular application.

  2. The direction in which rows will be processed

    The interface ResultSet defines the following three constants for specifying the direction in which to process rows: FETCH_FORWARD, FETCH_REVERSE, and FETCH_UNKNOWN. As with the fetch size, there are two methods for setting the fetch direction, one in the interface Statement, and the other in the interface ResultSet. The statement that creates the result set determines the default fetch direction by using the Statement method setFetchDirection. The following code fragment sets the fetch direction for the ResultSet object rs so that it will process rows from the bottom up. Until the fetch direction is changed, any result set created by the Statement object stmt will automatically have a fetch direction of backward.

    Statement stmt = con.createStatement();
stmt.setFetchDirection(FETCH_REVERSE);
ResultSet rs = stmt.executeQuery(SELECT * FROM EMPLOYEES);
    A result set can, at any time, change its default fetch direction by setting a new fetch direction with the ResultSet method setFetchDirection. Continuing from the previous code fragment, the following line of code changes the fetch direction of rs to forward.
    rs.setFetchDirection(FETCH_FORWARD);
    The ResultSet object rs will hint that the driver process rows in a forward direction. This hint will be in effect until the method ResultSet.setFetchDirection is again called on rs to change the suggested fetch direction.

    As with the fetch size, drivers are commonly optimized to use the most efficient fetch direction, and changing the default may actually work against this optimization. The method setFetchDirection simply allows a programmer to try to fine tune an application for even better performance.

5.1.10 Creating Different Types of Result Sets

A result set is created by executing a query, and the type of result set depends on the arguments that are supplied to the Connection method createStatement (or prepareStatement or prepareCall). The following code fragment, which uses only JDBC 1.0 API, supplies no arguments to the method createStatement and thus creates a default ResultSet object, one that is forward-only and uses read-only concurrency.

Connection con = DriverManager.getConnection(
        "jdbc:my_subprotocol:my_subname");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(
    "SELECT EMP_NO, SALARY FROM EMPLOYEES");

The variable rs represents a ResultSet object that contains the values for the columns EMP_NO and SALARY from every row in the table EMPLOYEES. This result set is not scrollable, so only the method next can be used to move the cursor from the top down through the rows of the result set. The ResultSet object rs cannot be updated, and since no performance hints were given, the driver is free to do whatever it thinks will produce the best performance. The transaction isolation level was likewise not set, so rs will use the default transaction isolation level of the underlying database. (See "Transaction Isolation Levels" on page 22 for an explanation of transaction isolation levels.)

The next example uses the new JDBC 2.0 core API to create a scrollable result set that is sensitive to updates (by specifying ResultSet.TYPE_SCROLL_SENSITIVE) and that is updatable (by specifying ResultSet.CONCUR_UPDATABLE).

Connection con = DriverManager.getConnection(
        "jdbc:my_subprotocol:my_subname");

Statement stmt = con.createStatement(
        ResultSet.TYPE_SCROLL_SENSITIVE,
         ResultSet.CONCUR_UPDATABLE);
stmt.setFetchSize(25);

ResultSet rs2 = stmt.executeQuery(
        "SELECT EMP_NO, SALARY FROM EMPLOYEES");

The variable rs2 contains the same values as rs, from the previous example, but unlike rs, it is scrollable, updatable, and sensitive to changes in the underlying table's data. It also hints that the driver should fetch 25 rows from the database each time new rows are needed. Each time the Statement object stmt is executed, it will create a result set that is scrollable, is updatable, is sensitive to changes in its data, and has a fetch size of 25. The result set may change its fetch size, but it cannot change its type or concurrency.

As stated previously, there is a cost to making a result set scrollable or updatable, so it is good practice to create result sets with these features only when they are needed.

5.1.11 Using a Prepared Statement to Create Result Sets

Because PreparedStatement and CallableStatement objects inherit the methods defined in the Statement interface, they, too, can create different types of ResultSet objects.

The following code fragment creates a result set using a PreparedStatement object instead of a Statement object. The result set has the same attributes as in the previous example, except that a transaction isolation level is set for the connection.

Connection con = DriverManager.getConnection(
            "jdbc:my_subprotocol:my_subname");
con.setTransactionIsolation(TRANSACTION_READ_COMMITTED);

PreparedStatement pstmt = con.prepareStatement(
            "SELECT EMP_NO, SALARY FROM EMPLOYEES WHERE EMP_NO = ?",
            ResultSet.TYPE_SCROLL_SENSITIVE,
            ResultSet.CONCUR_UPDATABLE);
pstmt.setFetchSize(25);
pstmt.setString(1, "1000010");

ResultSet rs3 = pstmt.executeQuery();

The variable rs3 contains the values from the columns EMP_NO and SALARY for the row where the value for EMP_NO is 1000010. The ResultSet object rs3 is like rs2 in that it is scrollable, is updatable, is sensitive to changes in its data, and hints that the driver should fetch 25 rows at a time from the database. It is different in that its connection specifies that dirty reads (reading values before they are committed) will be prevented. Because no transaction isolation level was set for rs2, it will by default have the isolation level of the underlying database.

5.1.12 Requesting Features That Are Not Supported

With the addition of new functionality in the JDBC 2.0 API, it is possible for an application to request features that a DBMS or driver do not support. If the driver does not support scrollable result sets, for example, it may return a forward-only result set. Also, some queries will return a result set that cannot be updated, so requesting an updatable result set would have no effect for those queries. A general rule is that a query should include the primary key as one of the columns it selects, and it should reference only one table.

New methods in the JDBC 2.0 API let an application discover which result set features a driver supports. If there is any doubt about whether a feature is supported, it is advisable to call these methods before requesting the feature. The following DatabaseMetaData methods indicate whether a driver supports a given result set type or a given result set concurrency:

  • DatabaseMetaData.supportsResultSetType - returns a boolean indicating whether the driver supports the given result set type
  • DatabaseMetaData.supportsResultSetConcurrency - returns a boolean indicating whether the driver supports the given concurrency type in combination with the given result set type

The following ResultSet methods return the result set type and result set concurrency for the particular result set on which the method is called:

  • ResultSet.getType - returns the type of this result set
  • ResultSet.getConcurrency - returns the concurrency mode of this result set

If an application specifies a scrollable result set and the driver does not support scrolling, the driver will issue a warning on the Connection object that produced the statement and return a result set that is forward-only. Even if the driver supports scrollable result sets, it is possible for an application to request a scrollable type that the driver does not support. In such a case, the driver will issue an SQLWarning on the Connection object that produced the statement and return a scrollable result set of a type that it does support, even if it differs from the exact type requested. For example, if an application requests a TYPE_SCROLL_SENSITIVE result set and the driver does not support that type, it could return a TYPE_SCROLL_INSENSITIVE result set if it supports that type. The driver would also alert the application that it did not return the exact type requested by issuing an SQLWarning on the Connection object that produced the statement requesting the unsupported result set type.

Similarly, if an application specifies an updatable result set, a driver that does not support updatable result sets will issue an SQLWarning on the Connection object that produced the statement and return a read-only result set. If the application requests both an unsupported result set type and an unsupported concurrency type, the driver should choose the result set type first.

In some situations, a driver may need to choose an alternate result set type or concurrency type at statement execution time. For example, a SELECT statement that contains a join over multiple tables might produce a result set that is not updatable. In such a situation, the driver will issue an SQLWarning on the Statement, PreparedStatement, or CallableStatement object that tried to create the result set instead of issuing it on the Connection object. The driver will then choose an appropriate result set type and/or concurrency type according to the guidelines in the preceding two paragraphs.

5.1.13 Using updateXXX Methods

A ResultSet object may be updated (have its rows modified, inserted, or deleted) programmatically if its concurrency type is CONCUR_UPDATABLE. The JDBC 2.0 API adds updateXXX methods and various other methods to the ResultSet interface so that rows can be programmatically updated in both the ResultSet object and the database.

The new updateXXX methods make it possible to update values in a result set without using SQL commands. There is an updateXXX method for each data type, and as with the getXXX and setXXX methods, the XXX is a data type in the Java programming language. As with the setXXX methods, the driver converts this data type to an SQL data type before sending it to the database. So for example, the method updateBoolean sends a JDBC BIT value to the database, and the method updateCharacterStream sends a JDBC LONGVARCHAR value to the database.

The updateXXX methods take two parameters, the first to indicate which column is to be updated, and the second to give the value to assign to the specified column. As is true with the getXXX methods, the column can be specified by giving either its name or its index. If an application retrieved a value from a result set by using the column name, it will generally use the column name when it wants to update that value. Similarly, if the getXXX method was given a column index to retrieve a value, the corresponding updateXXX method will generally use the column index to update that value.

Note that the column index used with ResultSet methods refers to the column number in the result set, not the column number in the database table, which might well be different. (The column numbers will be the same only in the case where all of a table's columns are selected.) In both result set tables and database tables, the index for the first column is 1, the index for the second column is 2, and so on.

In the following code fragment, the value in the third column of the ResultSet object rs is retrieved using the method getInt, and the method updateInt is used to update that column value with an int value of 88:

int n = rs.getInt(3); // n contains the value in column 3 of rs
. . .
rs.updateInt(3, 88); // the value in column 3 of rs is set to 88
int n = rs.getInt(3); // n = 88

If the third column is named SCORES, the following lines of code will also update the third column of the ResultSet object rs by assigning it the int value 88:

int n = rs.getInt("SCORES");
. . .
rs.updateInt("SCORES", 88);

The updateXXX methods update a value in the current row of the result set, but they do not update the value in the underlying database table. It is the method updateRow that updates the database. It is very important that the updateRow method be called while the cursor is still on the current row (the row to be updated). In fact, if an application moves the cursor before it calls updateRow, the driver must discard the update, and neither the result set nor the database will be updated.

An application may explicitly cancel the updates to a row by calling the method cancelRowUpdates. To take effect, it must be called after the method updateXXX is called and before the method updateRow is called. If cancelRowUpdates is called at any other time, it has no effect.

The following example demonstrates updating the second and third columns in the fourth row of the ResultSet object rs. Since updates affect the current row, the cursor is first moved to the row to be updated, which in this case is the fourth row. Next the method updateString is called to change the value in the second column of rs to 321 Kasten. The method updateFloat changes the value in the third column of rs to 10101.0. Finally, the method updateRow is called to update the row in the database that contains the two modified column values.

rs.absolute(4);
rs.updateString(2, "321 Kasten");
rs.updateFloat(3, 10101.0f);
rs.updateRow();

If the second column is named ADDRESS and the third column is named AMOUNT, the following code will have exactly the same effect as the previous example.

rs.absolute(4);
rs.updateString("ADDRESS", "321 Kasten");
rs.updateFloat("AMOUNT", 10101.0f);
rs.updateRow();

In addition to making updates programmatically, the JDBC 2.0 core API provides the ability to send batch updates. The batch update facility operates through a Statement object, which is explained in the section "Sending Batch Updates" on page 39.

5.1.14 Deleting a Row

The JDBC 2.0 API provides the method deleteRow so that a row in a ResultSet object can be deleted using only methods in the Java programming language. This method deletes the current row, so before calling deleteRow, an application must position the cursor on the row it wants to delete. Unlike the updateXXX methods, which affect only a row in the result set, this method affects both the current row in the result set and the underlying row in the database. The following two lines of code remove the first row of the ResultSet object rs and also delete the underlying row from the database (which may or may not be the first row of the database table).

rs.first();
rs.deleteRow();

5.1.15 Inserting Rows

New rows may be inserted into a result set table and into the underlying database table using new methods in the JDBC 2.0 core API. To make this possible, the API defines the concept of an insert row. This is a special row, associated with the result set but not part of it, that serves as a staging area for building the row that is to be inserted. To access the insert row, an application calls the ResultSet method moveToInsertRow, which positions the cursor on the insert row. Then it calls the appropriate updateXXX methods to add column values to the insert row. When all of the columns of the row to be inserted have been set, the application calls the method insertRow. This method adds the insert row to both the result set and the underlying database simultaneously. Finally, the application needs to position the cursor on a row back in the result set.

The following code fragment demonstrates these steps for inserting a row from an application written in the Java programming language.

rs.moveToInsertRow();
rs.updateObject(1, myArray);
rs.updateInt(2, 3857);
rs.updateString(3, "Mysteries");
rs.insertRow();
rs.first();

Several details deserve attention. First, it is possible to retrieve values from the insert row using the ResultSet.getXXX methods. Until a value has been assigned to the insert row with an updateXXX method, however, its contents are undefined. Therefore, if a getXXX method is called after the moveToInsertRow method has been called but before an updateXXX method has been called, the value it returns will be undefined.

Second, calling an updateXXX method on the insert row is different from calling it on a row in the ResultSet object. When the cursor is on a row in a result set, a call to an updateXXX method changes a value in the result set. When the cursor is on the insert row, a call to an updateXXX method updates a value in the insert row but does nothing to the result set. In both cases, though, the updateXXX method has no effect on the underlying database.

Third, calling the method insertRow, which adds the insert row to both the result set and database, may throw an SQLException if the number of columns in the insert row does not match the number of columns in the database table. For example, if a column is not given a value by calling an updateXXX method, an SQLException will be thrown unless that column allows null values. Also, if the result set is missing a column, that, too, will cause an SQLException to be thrown unless the column allows null values.

Fourth, a result set keeps track of where its cursor was positioned when the cursor moved to the insert row. As a result, a call to the method ResultSet.moveToCurrentRow will return the cursor to the row that was the current row immediately before the method moveToInsertRow was called. The other cursor movement methods also work from the insert row, including those that use positioning relative to the current row.

5.1.16 Positioned Updates

Before the JDBC 2.0 API made programmatic updates available in the Java programming language, the only way to change a row that had been fetched with a result set was to use what is called a positioned update. A positioned update is done with SQL commands and requires a named cursor to indicate the result set row in which updates are to be made.

The Statement interface provides the method setCursorName, which allows an application to specify a cursor name for the cursor associated with the next result set produced by a statement. This name can then be used in SQL positioned update or delete statements to identify the current row in the ResultSet object generated by the statement. In order to enable a positioned update or delete on a result set, the query that produces it must have the following form:

SELECT . . . FROM . . . WHERE . . . FOR UPDATE . . .

Including the words "FOR UPDATE" ensures that the cursor has the proper isolation level to support an update.

After the method executeQuery has been called on the statement, the cursor name for the resulting ResultSet object can be obtained by calling the ResultSet method getCursorName. If a DBMS allows positioned updates or positioned deletes, the name of the cursor can be supplied as a parameter to the SQL command for updates or deletes. A Statement object other than the one that created the ResultSet object must be used for the positioned update. The following code fragment, in which stmt and stmt2 are two different Statement objects, demonstrates the form for naming a cursor and then using it in an SQL update statement:

stmt.setCursorName("x");
ResultSet rs = stmt.executeQuery(
        "SELECT . . . FROM . . . WHERE . . . FOR UPDATE . . .")
String cursorName = rs.getCursorName;
int updateCount = stmt2.executeUpdate(
        "UPDATE . . . WHERE CURRENT OF " + cursorName);

Note that just because the method getCursorName has been invoked on a ResultSet object does not necessarily mean that it can be updated using the ResultSet.updateXXX methods available in the JDBC 2.0 core API. In order to update a ResultSet object using the updateXXX methods, the executeQuery statement that produces the result set must include the specification CONCUR_UPDATABLE. Positioned updates, however, are possible for a result set created without this specification if all the proper steps are taken: (1) a cursor is named, (2) the SQL query that produces the result set is of the form SELECT . . . FROM . . . WHERE . . . FOR UPDATE . . ., and (3) the SQL update statement is of the form UPDATE . . . WHERE CURRENT OF <cursorName>.

Not all DBMSs support positioned updates. To verify that a DBMS supports positioned updates, an application can call the DatabaseMetaData methods supportsPositionedDelete and supportsPositionedUpdate to discover whether a particular connection supports these operations. When they are supported, the DBMS/driver must ensure that rows selected are properly locked so that positioned updates do not result in update anomalies or other concurrency problems.

5.1.17 Queries That Produce Updatable Result Sets

Some queries will produce result sets that cannot be updated no matter what the result set type. For example, a query that does not select the primary key column might generate a result set that cannot be updated. Because of differences in database implementations, the JDBC 2.0 core API does not specify an exact set of SQL queries that must yield updatable result sets. Instead it defines a set of criteria that should generally produce updatable result sets for JDBC Compliant drivers that support updatability. If queries adhere to the following guidelines, a developer can generally expect that they will produce updatable result sets:

  1. The query references only a single table in the database
  2. The query does not contain a join operation or a GROUP BY clause
  3. The query selects the primary key of the table it references

    If inserts are to be performed on the result set, an SQL query should satisfy conditions one through three plus the following three additional conditions:

  4. The user has read/write database privileges on the table
  5. The query selects all of the nonnullable columns in the underlying table
  6. The query selects all columns that do not have a default value

The fourth and fifth conditions are necessary because a row to be inserted into a table must have a value for each column in the table unless the column accepts null values or default values. If the result set on which insertion operations are to be performed does not contain every column that requires a value, the insertion will fail.

Result sets created by means other than the execution of a query, such as those returned by several methods in the DatabaseMetaData interface, are not scrollable or updatable, nor are they required to be.

5.1.18 Using Streams for Very Large Row Values

Two new interfaces in the JDBC 2.0 core API, Blob and Clob, are the mapping of the SQL3 data types BLOB (Binary Large Object) and CLOB (Character LargeObject) in the Java programming language. With the availability of these data types, databases will undoubtedly start using them to store very large binary or character objects. If this is the case, the ResultSet methods getBlob and getClob should be used to retrieve them.

Using only the JDBC 1.0 API, a ResultSet object still makes it possible to retrieve arbitrarily large LONGVARBINARY or LONGVARCHAR data. The methods getBytes and getString return data as one large chunk (up to the limits imposed by the return value of Statement.getMaxFieldSize). It is possible to retrieve this large chunk of data in smaller, fixed-size chunks. This is done by having the ResultSet class return java.io.Input streams from which data can be read in chunks. Note that these streams must be accessed immediately because they will be closed automatically when the next getXXX method is called on the ResultSet object. (This behavior is not a limitation of the JDBC API but rather a constraint on large blob access imposed by the underlying implementations in some database -systems.)

The JDBC 1.0 API has three separate methods for getting streams, each with a different return value:

  • getBinaryStream - returns a stream that simply provides the raw bytes from the database without any conversion
  • getAsciiStream - returns a stream that provides one-byte ASCII characters. This method can be more efficient for a DBMS that stores characters in ASCII format.
  • getUnicodeStream - returns a stream that provides two-byte Unicode characters. This method, though still available, has been deprecated in favor of the new method getCharacterStream. (See below.)

The following method for retrieving streams of both ASCII and Unicode characters is new in the JDBC 2.0 core API:

  • getCharacterStream - returns a java.io.Reader object that provides Unicode characters. No matter how a DBMS stores characters, the driver will return them as a stream of Unicode characters.

Note that the stream returned by getAsciiStream returns a stream of bytes in which each byte is an ASCII character. This differs from getCharacterStream, which returns a stream of two-byte Unicode characters. The method getCharacterStream can be used for both ASCII and Unicode characters because the driver will convert ASCII characters to Unicode before it returns a Reader object. If you must use getUnicodeStream because your DBMS and driver do not support the JDBC 2.0 API, note also that JDBC Unicode streams return big-endian data; that is, they expect data with the high byte first and the low byte second. This conforms to the standard endian defined by the Java programming language, which is important if a program is to be portable. Refer to The Javatm Virtual Machine Specification, by Tim Lindholm and Frank Yellin, for more detailed information about big-endian order.

The following code fragment demonstrates how to use the getAsciiStream method.

java.sql.Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT x FROM Table2");
// Now retrieve the column 1 results in 4 K chunks:
byte [] buff = new byte[4096];
while (rs.next()) {
    java.io.InputStream fin = rs.getAsciiStream(1);
    for (;;) {
        int size = fin.read(buff);
        if (size == -1) { // at end of stream
                    break;
        }

        // Send the newly-filled buffer to some ASCII output stream
        output.write(buff, 0, size);
    }
}

5.1.19 NULL Result Values

To determine if a given result value is JDBC NULL, one must first read the column and then use the method ResultSet.wasNull. This is true because a JDBC NULL retrieved by one of the ResultSet.getXXX methods may be converted to either null, 0, or false, depending on the type of the value.

The following list shows which values are returned by the various getXXX methods when they have retrieved a JDBC NULL.

  • null-for those getXXX methods that return objects in the Java programming language (getString, getBigDecimal, getBytes, getDate, getTime, getTime-stamp,  getAsciiStream, getCharacterStream, getUnicodeStream, getBinary-Stream, getObject, getArray, getBlob, getClob, and getRef)

  • 0 (zero)-for getByte, getShort, getInt, getLong, getFloat, and getDouble

  • false-for getBoolean

For example, if the method getInt returns 0 from a column that allows null values, an application cannot know for sure whether the value in the database was 0 or NULL until it calls the method wasNull, as shown in the following code fragment, where rs is a ResultSet object.

int n = rs.getInt(3);
boolean b = rs.wasNull();

If b is true, the value stored in the third column of the current row of rs is JDBC NULL. The method wasNull checks only the last value retrieved, so to determine whether n was NULL, wasNull had to be called before another getXXX method was invoked.

5.1.20	 Closing a ResultSet Object

Normally, nothing needs to be done to close a ResultSet object; it is automatically closed by the Statement object that generated it when that Statement object is closed, is re-executed, or is used to retrieve the next result from a sequence of multiple results. The method close is provided so that a ResultSet object can be closed explicitly, thereby immediately releasing the resources held by the ResultSet object. This could be necessary when several statements are being used and the automatic close does not occur soon enough to prevent database resource conflicts.

5.1.21	 JDBC Compliance

Drivers that are JDBC Compliant should normally support scrollable result sets, but they are not required to do so. The intent is for JDBC drivers to implement scrollable result sets using the support provided by the underlying database systems. If the DBMS does not provide support for scrollability, then the driver may omit this feature.

Making scrollability optional is not meant to encourage omitting it. It is simply meant to minimize the complexity of implementing JDBC drivers for data sources that do not support scrollability. Indeed, the recommended alternative is for a driver to implement scrollability as a layer on top of the DBMS. One way to do this is to implement a result set as a rowset. The RowSet interface, which provides methods for doing this, is part of the JDBC Standard Extension API.

[Top] [Prev] [Next]

Copyright © 1999, Sun Microsystems, Inc.   All rights
reserved.


[Top] [Prev] [Next]

Appendix B - Sample Code

    // The following code can be used as a template.  Simply
// substitute the appropriate url, login, and password, and then substitute the
// SQL statement you want to send to the database.

//----------------------------------------------------------------------------
//
// Module:	SimpleSelect.java
//
// Description:	Test program for ODBC API interface.  This java application
// will connect to a JDBC driver, issue a select statement
// and display all result columns and rows
//
// Product:	JDBC to ODBC Bridge
//
// Author:	Karl Moss
//
// Date:	February, 1996
//
// Copyright:	1990-1996 INTERSOLV, Inc.
// This software contains confidential and proprietary
// information of INTERSOLV, Inc.
//----------------------------------------------------------------------------

import java.net.URL;
import java.sql.*;

class SimpleSelect {

public static void main (String args[]) {
    String url   = "jdbc:odbc:my-dsn";
    String query = "SELECT * FROM emp";

    try {

        // Load the jdbc-odbc bridge driver

        Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");

        DriverManager.setLogStream(System.out);

        // Attempt to connect to a driver.  Each one
        // of the registered drivers will be loaded until
        // one is found that can process this URL

        Connection con = DriverManager.getConnection (
            url, "my-user", "my-passwd");

        // If we were unable to connect, an exception
        // would have been thrown.  So, if we get here,
        // we are successfully connected to the URL

        // Check for, and display and warnings generated
        // by the connect.

        checkForWarning (con.getWarnings ());

        // Get the DatabaseMetaData object and display
        // some information about the connection

        DatabaseMetaData dma = con.getMetaData ();

        System.out.println("\nConnected to " + dma.getURL());
        System.out.println("Driver       " +
            dma.getDriverName());
        System.out.println("Version      " +
            dma.getDriverVersion());
        System.out.println("");

        // Create a Statement object so we can submit
        // SQL statements to the driver

        Statement stmt = con.createStatement ();

        // Submit a query, creating a ResultSet object

        ResultSet rs = stmt.executeQuery (query);

        // Display all columns and rows from the result set

        dispResultSet (rs);

        // Close the result set

        rs.close();

        // Close the statement

        stmt.close();

        // Close the connection

        con.close();
    }
    catch (SQLException ex) {

        // A SQLException was generated.  Catch it and
        // display the error information.  Note that there
        // could be multiple error objects chained
        // together

    System.out.println ("\n*** SQLException caught ***\n");

    while (ex != null) {
        System.out.println ("SQLState: " +
                ex.getSQLState ());
        System.out.println ("Message:  " + ex.getMessage ());
        System.out.println ("Vendor:   " +
                ex.getErrorCode ());
        ex = ex.getNextException ();
        System.out.println ("");
        }
    }
    catch (java.lang.Exception ex) {

        // Got some other type of exception.  Dump it.

        ex.printStackTrace ();
    }
}

//-------------------------------------------------------------------
// checkForWarning
// Checks for and displays warnings.  Returns true if a warning
// existed
//-------------------------------------------------------------------

private static boolean checkForWarning (SQLWarning warn)
        throws SQLException  {
    boolean rc = false;

    // If a SQLWarning object was given, display the
    // warning messages.  Note that there could be
    // multiple warnings chained together

    if (warn != null) {
        System.out.println ("\n *** Warning ***\n");
        rc = true;
        while (warn != null) {
            System.out.println ("SQLState: " +
                warn.getSQLState ());
            System.out.println ("Message:  " +
                warn.getMessage ());
            System.out.println ("Vendor:   " +
                warn.getErrorCode ());
            System.out.println ("");
            warn = warn.getNextWarning ();
        }
    }
    return rc;
}

//-------------------------------------------------------------------
// dispResultSet
// Displays all columns and rows in the given result set
//-------------------------------------------------------------------

private static void dispResultSet (ResultSet rs)
    throws SQLException
{
    int i;

    // Get the ResultSetMetaData.  This will be used for
    // the column headings

    ResultSetMetaData rsmd = rs.getMetaData ();

    // Get the number of columns in the result set

    int numCols = rsmd.getColumnCount ();

    // Display column headings

    for (i=1; i<=numCols; i++) {
        if (i > 1) System.out.print(",");
        System.out.print(rsmd.getColumnLabel(i));
    }
    System.out.println("");

    // Display data, fetching until end of the result set

    boolean more = rs.next ();
    while (more) {

        // Loop through each column, getting the
        // column data and displaying

        for (i=1; i<=numCols; i++) {
            if (i > 1) System.out.print(",");
            System.out.print(rs.getString(i));
        }
        System.out.println("");

        // Fetch the next result set row

        more = rs.next ();
    }
}

}

[Top] [Prev] [Next]
jdbc@wombat.eng.sun.com or jdbc-odbc@wombat.eng.sun.com
Copyright © 1999 Sun Microsystems, Inc. All rights reserved.


 [Top] [Prev] [Next]

Statement

NOTE: The material in this chapter is based on JDBCtm API Tutorial and Reference, Second Edition: Universal Data Access for the Javatm 2 Platform, published by Addison Wesley as part of the Java series, ISBN 0-201-43328-1.

4.1 Statement Overview

A Statement object is used to send SQL statements to a database. There are actually three kinds of Statement objects, all of which act as containers for executing SQL statements on a given connection: Statement, PreparedStatement, which inherits from Statement, and CallableStatement, which inherits from PreparedStatement. They are specialized for sending particular types of SQL statements; a Statement object is used to execute a simple SQL statement with no parameters, a PreparedStatement object is used to execute a precompiled SQL statement with or without IN parameters, and a CallableStatement object is used to execute a call to a database stored procedure.

The Statement interface provides basic methods for executing statements and retrieving results. The PreparedStatement interface adds methods for dealing with IN parameters; the CallableStatement interface adds methods for dealing with OUT parameters.

In the JDBC 2.0 core API, the ResultSet interface has a set of new updateXXX methods and other new related methods that make it possible to update table column values programmatically. This new API also adds methods to the Statement interface (and PreparedStatement and CallableStatement interfaces) so that update statements may be executed as a batch rather than singly.

4.1.1 Creating Statement Objects

Once a connection to a particular database is established, that connection can be used to send SQL statements. A Statement object is created with the Connection method createStatement, as in the following code fragment:

Connection con = DriverManager.getConnection(url, "sunny", "");
Statement stmt = con.createStatement();

The SQL statement that will be sent to the database is supplied as the argument to one of the execute methods on a Statement object. This is demonstrated in the following example, which uses the method executeQuery:

ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table2");

The variable rs references a result set that cannot be updated and in which the cursor can move only forward, which is the default behavior for ResultSet objects. The JDBC 2.0 core API adds a new version of the method Connection.createStatement that makes it possible to create Statement objects that produce result sets that are scrollable and/or updatable.

4.1.2 Executing Statements Using Statement Objects

The Statement interface provides three different methods for executing SQL statements: executeQuery, executeUpdate, and execute. The correct method to use is determined by what the SQL statement produces.

The method executeQuery is designed for statements that produce a single result set, such as SELECT statements.

The method executeUpdate is used to execute INSERT, UPDATE, or DELETE statements and also SQL DDL (Data Definition Language) statements like CREATE TABLE, DROP TABLE, and ALTER TABLE. The effect of an INSERT, UPDATE, or DELETE statement is a modification of one or more columns in zero or more rows in a table. The return value of executeUpdate is an integer (referred to as the update count) that indicates the number of rows that were affected. For statements such as CREATE TABLE or DROP TABLE, which do not operate on rows, the return value of executeUpdate is always zero.

The method execute is used to execute statements that return more than one result set, more than one update count, or a combination of the two. Because it is an advanced feature that the majority of programmers will never use, it is explained in its own section later in this overview.

All of the methods for executing statements close the calling Statement object's current result set if there is one open. This means that any processing of the current ResultSet object needs to be completed before a Statement object is re-executed.

It should be noted that the PreparedStatement interface, which inherits all of the methods in the Statement interface, has its own versions of the methods executeQuery, executeUpdate and execute. Statement objects do not themselves contain an SQL statement; therefore, one must be provided as the argument to the Statement.execute methods. PreparedStatement objects do not supply an SQL statement as a parameter to these methods because they already contain a precompiled SQL statement. CallableStatement objects inherit the PreparedStatement forms of these methods. Supplying a parameter to the PreparedStatement or CallableStatement versions of these methods will cause an SQLException to be thrown.

4.1.3 Statement Completion

When a connection is in auto-commit mode, the statements being executed within it are committed or rolled back when they are completed. A statement is considered complete when it has been executed and all its results have been returned. For the method executeQuery, which returns one result set, the statement is completed when all the rows of the ResultSet object have been retrieved. For the method executeUpdate, a statement is completed when it is executed. In the rare cases where the method execute is called, however, a statement is not complete until all of the result sets or update counts it generated have been retrieved.

Some DBMSs treat each statement in a stored procedure as a separate statement; others treat the entire procedure as one compound statement. This difference becomes important when auto-commit is enabled because it affects when the method commit is called. In the first case, each statement is individually committed; in the second, all are committed together.

4.1.4 Closing Statements

Statement objects will be closed automatically by the Java garbage collector. Nevertheless, it is recommended as good programming practice that they be closed explicitly when they are no longer needed. This frees DBMS resources immediately and helps avoid potential memory problems.

4.1.5 SQL Escape Syntax in Statements

Statement objects may contain SQL statements that use SQL escape syntax. Escape syntax signals the driver that the code within it should be handled differently. When escape processing is enabled (by calling Statement.setEscapeProcessing(true) or RowSet.setEscapeProcessing(true)), the driver will scan for any escape syntax and translate it into code that the particular database understands. This makes escape syntax DBMS-independent and allows a programmer to use features that might not otherwise be available.

An escape clause is demarcated by curly braces and a key word, which indicates the kind of escape clause.

    {keyword . . . parameters . . . }

The following keywords are used to identify escape clauses:

  • escape for LIKE escape characters The percent sign percent sign (%) wildcard>(%) and underscore underbar (_) wildcard>(_) characters work like wild cards in SQL LIKE clauses (% matches zero or more characters, and _ matches exactly one character). In order to interpret them literally, they can be preceded by a backslash (\), which is a special escape character in strings. One can specify which character to use as the escape character by including the following syntax at the end of a query:
        {escape 'escape-character'}
    For example, the following query, using the backslash character as an escape character, finds identifier names that begin with an underbar.
    stmt.executeQuery("SELECT name FROM Identifiers
      WHERE Id LIKE '\_%' {escape '\'}");
  • fn for scalar functions

    Almost all DBMSs have numeric, string, time, date, system, and conversion functions on scalar values. One of these functions can be used by putting it in escape syntax with the keyword fn followed by the name of the desired function and its arguments. For example, the following code calls the function concat with two arguments to be concatenated:

        {fn concat("Hot", "Java")};
    The name of the current database user can be obtained with the following syntax:
        {fn user()};
    Scalar functions may be supported by different DBMSs with slightly different syntax, and they may not be supported by all drivers. Various DatabaseMetaData methods will list the functions that are supported. For example, the method getNumericFunctions returns a comma-separated list of the Open Group CLI names of numeric functions, the method getStringFunctions returns string functions, and so on. The driver will either map the escaped function call into the appropriate syntax or implement the function directly itself. However, a driver is required to implement only those scalar functions that the DBMS supports.

  • d, t, and ts for date and time literals DBMSs differ in the syntax they use for date, time, and timestamp literals. The JDBC API supports ISO standard format for the syntax of these literals, using an escape clause that the driver must translate to the DBMS representation. For example, a date is specified in a JDBC SQL statement with the following syntax:
        {d 'yyyy-mm-dd'}
    In this syntax, yyyy is the year, mm is the month, and dd is the day. The driver will replace the escape clause with the equivalent DBMS-specific representation. For example, the driver might replace {d 1999-02-28} with '28-FEB-99' if that is the appropriate format for the underlying database. There are analogous escape clauses for TIME and TIMESTAMP:
            {t 'hh:mm:ss'}
        {ts 'yyyy-mm-dd hh:mm:ss.f . . .'}
    The fractional seconds (.f . . .) portion of the TIMESTAMP can be omitted.

  • call or ?= call for stored procedures If a database supports stored procedures, they can be invoked from JDBC with the syntax shown below. Note that the square brackets ([ ]) indicate that what is between them is optional, and they are not part of the syntax.
        {call procedure_name[(?, ?, . . .)]}

    or, where a procedure returns a result parameter:

        {? = call procedure_name[(?, ?, . . .)]}
    Input arguments may be either literals or parameters. See the section "Numbering of Parameters" on page 81 for more information. One can call the method DatabaseMetaData.supportsStoredProcedures to see if the database supports stored procedures.

  • oj for outer joins The syntax for an outer join is:
            {oj outer-join}
    In this syntax, outer-join has the form
    table {LEFT|RIGHT|FULL} OUTER JOIN {table | outer-join}
    ON search-condition
    (Note that curly braces ({}) in the preceding line indicate that one of the items between them must be used; they are not part of the syntax.) The following SELECT statement uses the escape syntax for an outer join.
    Statement stmt = con.createStatement("SELECT * FROM {oj TABLE1
    LEFT OUTER JOIN TABLE2 ON DEPT_NO = 003420930}");
    Outer joins are an advanced feature and are not supported by all DBMSs; consult the SQL grammar for an explanation of them. JDBC provides three DatabaseMetaData methods for determining the kinds of outer joins a driver supports: supportsOuterJoins, supportsFullOuterJoins, and supportsLimitedOuterJoins.

The method Statement.setEscapeProcessing turns escape processing on or off, with the default being on. A programmer might turn it off to cut down on processing time when performance is paramount, but it would normally be turned on. It should be noted that the method setEscapeProcessing does not work for PreparedStatement objects because the statement may have already been sent to the database before it can be called. See page 69, the overview of the PreparedStatement interface, regarding precompilation.

4.1.6 Sending Batch Updates

The batch update facility provided by the JDBC 2.0 core API allows a Statement object to submit multiple update commands together as a single unit, or batch, to the underlying DBMS. This ability to submit multiple updates as a batch rather than having to send each update individually can improve performance greatly in some situations.

The following code fragment demonstrates how to send a batch update to a database. In this example, a new row is inserted into three different tables in order to add a new employee to a company database. The code fragment starts by turning off the Connection object con's auto-commit mode in order to allow multiple statements to be sent together as a transaction. After creating the Statement object stmt, it adds three SQL INSERT INTO commands to the batch with the method addBatch and then sends the batch to the database with the method executeBatch. The code looks like this:

Statement stmt = con.createStatement();
con.setAutoCommit(false);

stmt.addBatch("INSERT INTO employees VALUES (1000, 'Joe Jones')");
stmt.addBatch("INSERT INTO departments VALUES (260, 'Shoe')");
stmt.addBatch("INSERT INTO emp_dept VALUES (1000, '260')");

int [] updateCounts = stmt.executeBatch();

Because the connection's auto-commit mode is disabled, the application is free to decide whether or not to commit the transaction if an error occurs or if some of the commands in the batch fail to execute. For example, the application may not commit the changes if any of the insertions fail, thereby avoiding the situation where employee information exists in some tables but not in others.

In the JDBC 2.0 core API, a Statement object is created with an associated list of commands. This list is empty to begin with; commands are added to the list with the Statement method addBatch. The commands added to the list must all return only a simple update count. If, for example, one of the commands is a query (a SELECT statement), which will return a result set, the method executeBatch will throw a BatchUpdateException. A Statement object's list of commands can be emptied by calling the method clearBatch on it.

In the preceding example, the method executeBatch submits stmt's list of commands to the underlying DBMS for execution. The DBMS executes each command in the order in which it was added to the batch and returns an update count for each command in the batch, also in order. If one of the commands does not return an update count, its return value cannot be added to the array of update counts that the method executeBatch returns. In this case, the method executeBatch will throw a BatchUpdateException. This exception keeps track of the update counts for the commands that executed successfully before the error occurred, and the order of these update counts likewise follows the order of the commands in the batch.

In the following code fragment, an application uses a try/catch block, and if a BatchUpdateException is thrown, it retrieves the exception's array of update counts to discover which commands in a batch update executed successfully before the BatchUpdateException object was thrown.

try {
    stmt.addBatch("INSERT INTO employees VALUES (" +
                "1000, 'Joe Jones')");
    stmt.addBatch("INSERT INTO departments VALUES (260, 'Shoe')");
    stmt.addBatch("INSERT INTO emp_dept VALUES (1000, '260')");

    int [] updateCounts = stmt.executeBatch();

} catch(BatchUpdateException b) {
    System.err.println("Update counts of successful commands: ");
    int [] updateCounts = b.getUpdateCounts();
    for (int  i = 0; i < updateCounts.length; i ++) {
        System.err.print(updateCounts[i] + "  ");
    }
    System.err.println("");
}

If a printout was generated and looked similar to the following, the first two commands succeeded and the third one failed.

Update counts of successful commands:
1   1

JDBC drivers are not required to support batch updates, so a particular driver might not implement the methods addBatch, clearBatch, and executeBatch. Normally a programmer knows whether a driver that he/she is working with supports batch updates, but if an application wants to check, it can call the DatabaseMetaData method supportsBatchUpdates to find out. In the following code fragment, a batch update is used only if the driver supports batch updates; otherwise, each update is sent as a separate statement. The connection's auto-commit mode is disabled so that in either case, all the updates are included in one transaction.

con.setAutoCommit(false);
    if(dbmd.supportsBatchUpdates) {
    stmt.addBatch("INSERT INTO . . .");
    stmt.addBatch("DELETE . . .");
    stmt.addBatch("INSERT INTO . . .");
    . . .
    stmt.executeBatch();
} else {
    System.err.print("Driver does not support batch updates; ");
    System.err.println("sending updates in separate statements.");
    stmt.executeUpdate("INSERT INTO . . .");
    stmt.executeUpdate("DELETE . . .");
    stmt.executeUpdate("INSERT INTO . . .");
    . . .
con.commit();

4.1.7 Giving Performance Hints

The Statement interface contains two methods for giving performance hints to the driver: setFetchDirection and setFetchSize. These methods are also available in the ResultSet interface and do exactly the same thing. The difference is that the Statement methods set the default for all of the ResultSet objects produced by a particular Statement object, whereas the ResultSet methods can be called any time during the life of the ResultSet object to change the fetch direction or the fetch size. See the section "Providing Performance Hints" on page 54 for a full discussion of these methods.

Both the Statement and ResultSet interfaces have the corresponding get methods: getFetchDirection and getFetchSize. If Statement.getFetchDirection is called before a fetch direction has been set, the value returned is implementation-specific, that is, it is up to the driver. The same is true for the method Statement.getFetchSize.

4.1.8 Executing Special Kinds of Statements

The execute method should be used only when it is possible that a statement may return more than one ResultSet object, more than one update count, or a combination of ResultSet objects and update counts. These multiple possibilities for results, though rare, are possible when one is executing certain stored procedures or dynamically executing an unknown SQL string (that is, unknown to the application programmer at compile time). For example, a user might execute a stored procedure (using a CallableStatement object), and that stored procedure could perform an update, then a select, then an update, then a select, and so on. In more typical situations, someone using a stored procedure will already know what it returns.

[Top] [Prev] [Next]

Copyright © 1999, Sun Microsystems, Inc.   All rights
reserved.


Untitled Document

 | TINYINT | SMALLINT | INTEGER | BIGINT | REAL | FLOAT | DOUBLE | DECIMAL | NUMERIC | BIT | CHAR | VARCHAR | LONGVARCHAR | BINARY | VARBINARY | LONGVARBINARY | DATE | TIME | TIMESTAMP | CLOB | BLOB | ARRAY | REF | STRUCT | JAVA OBJECT
getByte | y | x | x | x | x | x | x | x | x | x | x | x | x |  |  |  |  |  |  |  |  |  |  |  |
getShort | x | y | x | x | x | x | x | x | x | x | x | x | x |  |  |  |  |  |  |  |  |  |  |  |
getInt | x | x | y | x | x | x | x | x | x | x | x | x | x |  |  |  |  |  |  |  |  |  |  |  |
getLong | x | x | x | y | x | x | x | x | x | x | x | x | x |  |  |  |  |  |  |  |  |  |  |  |
getFloat | x | x | x | x | y | x | x | x | x | x | x | x | x |  |  |  |  |  |  |  |  |  |  |  |
getDouble | x | x | x | x | x | y | y | x | x | x | x | x | x |  |  |  |  |  |  |  |  |  |  |  |
getBigDecimal | x | x | x | x | x | x | x | y | y | x | x | x | x |  |  |  |  |  |  |  |  |  |  |  |
getBoolean | x | x | x | x | x | x | x | x | x | y | x | x | x |  |  |  |  |  |  |  |  |  |  |  |
getString | x | x | x | x | x | x | x | x | x | x | y | y | x | x | x | x | x | x | x |  |  |  |  |  |
getBytes |  |  |  |  |  |  |  |  |  |  |  |  |  | y | y | x |  |  |  |  |  |  |  |  |
getDate |  |  |  |  |  |  |  |  |  |  | x | x | x |  |  |  | y |  | x |  |  |  |  |  |
getTime |  |  |  |  |  |  |  |  |  |  | x | x | x |  |  |  |  | y | x |  |  |  |  |  |
getTimestamp |  |  |  |  |  |  |  |  |  |  | x | x | x |  |  |  | x | x | y |  |  |  |  |  |
getAsciiStream |  |  |  |  |  |  |  |  |  |  | x | x | y | x | x | x |  |  |  |  |  |  |  |  |
getUnicodeStream |  |  |  |  |  |  |  |  |  |  | x | x | y | x | x | x |  |  |  |  |  |  |  |  |
getBinaryStream |  |  |  |  |  |  |  |  |  |  |  |  |  | x | x | y |  |  |  |  |  |  |  |  |
getClob |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  | y |  |  |  |  |
getBlob |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  | y |  |  |  |
getArray |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  | y |  |  |
getRef |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  | y |  |
getCharacterStream |  |  |  |  |  |  |  |  |  |  | x | x | y | x | x | x |  |  |  |  |  |  |  |  |
getObject | x | x | x | x | x | x | x | x | x | x | x | x | x | x | x | x | x | x | x | x | x | x | x | y | y


Untitled Document

 | TINYINT | SMALLINT | INTEGER | BIGINT | REAL | FLOAT | DOUBLE | DECIMAL | NUMERIC | BIT | CHAR | VARCHAR | LONGVARCHAR | BINARY | VARBINARY | LONGVARBINARY | DATE | TIME | TIMESTAMP | ARRAY | BLOB | CLOB | STRUCT | REF | JAVA OBJECT
String | x | x | x | x | x | x | x | x | x | x | x | x | x | x | x | x | x | x | x |  |  |  |  |  |
java.math.BigDecimal | x | x | x | x | x | x | x | x | x | x | x | x | x |  |  |  |  |  |  |  |  |  |  |  |
Boolean | x | x | x | x | x | x | x | x | x | x | x | x | x |  |  |  |  |  |  |  |  |  |  |  |
Integer | x | x | x | x | x | x | x | x | x | x | x | x | x |  |  |  |  |  |  |  |  |  |  |  |
Long | x | x | x | x | x | x | x | x | x | x | x | x | x |  |  |  |  |  |  |  |  |  |  |  |
Float | x | x | x | x | x | x | x | x | x | x | x | x | x |  |  |  |  |  |  |  |  |  |  |  |
Double | x | x | x | x | x | x | x | x | x | x | x | x | x |  |  |  |  |  |  |  |  |  |  |  |
byte[] |  |  |  |  |  |  |  |  |  |  |  |  |  | x | x | x |  |  |  |  |  |  |  |  |
java.sql.Date |  |  |  |  |  |  |  |  |  |  | x | x | x |  |  |  | x |  | x |  |  |  |  |  |
java.sql.Time |  |  |  |  |  |  |  |  |  |  | x | x | x |  |  |  |  | x |  |  |  |  |  |  |
java.sql.Timestamp |  |  |  |  |  |  |  |  |  |  | x | x | x |  |  |  | x | x | x |  |  |  |  |  |
Array |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  | x |  |  |  |  |
Blob |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  | x |  |  |  |
Clob |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  | x |  |  |
Struct |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  | x |  |
Ref |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  | x |
Java class |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  | x


Untitled Document

 | TINYINT | SMALLINT | INTEGER | BIGINT | REAL | FLOAT | DOUBLE | DECIMAL | NUMERIC | BIT | CHAR | VARCHAR | LONGVARCHAR | BINARY | VARBINARY | LONGVARBINARY | DATE | TIME | TIMESTAMP | CLOB | BLOB | ARRAY | REF | STRUCT | JAVA OBJECT
getByte | y | x | x | x | x | x | x | x | x | x | x | x | x |  |  |  |  |  |  |  |  |  |  |  |
getShort | x | y | x | x | x | x | x | x | x | x | x | x | x |  |  |  |  |  |  |  |  |  |  |  |
getInt | x | x | y | x | x | x | x | x | x | x | x | x | x |  |  |  |  |  |  |  |  |  |  |  |
getLong | x | x | x | y | x | x | x | x | x | x | x | x | x |  |  |  |  |  |  |  |  |  |  |  |
getFloat | x | x | x | x | y | x | x | x | x | x | x | x | x |  |  |  |  |  |  |  |  |  |  |  |
getDouble | x | x | x | x | x | y | y | x | x | x | x | x | x |  |  |  |  |  |  |  |  |  |  |  |
getBigDecimal | x | x | x | x | x | x | x | y | y | x | x | x | x |  |  |  |  |  |  |  |  |  |  |  |
getBoolean | x | x | x | x | x | x | x | x | x | y | x | x | x |  |  |  |  |  |  |  |  |  |  |  |
getString | x | x | x | x | x | x | x | x | x | x | y | y | x | x | x | x | x | x | x |  |  |  |  |  |
getBytes |  |  |  |  |  |  |  |  |  |  |  |  |  | y | y | x |  |  |  |  |  |  |  |  |
getDate |  |  |  |  |  |  |  |  |  |  | x | x | x |  |  |  | y |  | x |  |  |  |  |  |
getTime |  |  |  |  |  |  |  |  |  |  | x | x | x |  |  |  |  | y | x |  |  |  |  |  |
getTimestamp |  |  |  |  |  |  |  |  |  |  | x | x | x |  |  |  | x | x | y |  |  |  |  |  |
getAsciiStream |  |  |  |  |  |  |  |  |  |  | x | x | y | x | x | x |  |  |  |  |  |  |  |  |
getBinaryStream |  |  |  |  |  |  |  |  |  |  |  |  |  | x | x | y |  |  |  |  |  |  |  |  |
getCharacterStream |  |  |  |  |  |  |  |  |  |  | x | x | y | x | x | x |  |  |  |  |  |  |  |  |
getClob |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  | y |  |  |  |  |
getBlob |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  | y |  |  |  |
getArray |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  | y |  |  |
getRef |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  | y |  |
getObject | x | x | x | x | x | x | x | x | x | x | x | x | x | x | x | x | x | x | x | x | x | x | x | y | y


Untitled Document

JDBC Type Name | Oracle 8.1 | Sybase 11.9 | Informix 9.2 | IBM DB2 5.2 (Unix, NT) | Microsoft SQL Server 7.0 | Microsoft Access 7.0 | Sybase SQL Anywhere 6.0
BIT |  | BIT |  |  | BIT | BIT | BIT
TINYINT |  | TINYINT | SMALLINT |  | TINYINT | BYTE | TINYINT
SMALLINT | SMALLINT, NUMBER(38,0) | SMALLINT | SMALLINT | SMALLINT | SMALLINT | SMALLINT | SMALLINT
INTEGER | INTEGER, NUMBER(38,0) | INTEGER | INTEGER, SERIAL | INTEGER | INTEGER | INTEGER, COUNTER | INTEGER
BIGINT |  |  | INT8, SERIAL8 | BIGINT |  |  |
REAL | REAL, NUMBER | REAL | REAL | REAL | REAL | REAL | REAL
FLOAT | FLOAT, NUMBER | FLOAT | FLOAT | FLOAT | FLOAT |  | FLOAT
DOUBLE | DOUBLE PRECISION, NUMBER | DOUBLE PRECISION | DOUBLE PRECISION | FLOAT | DOUBLE PRECISION | DOUBLE | DOUBLE PRECISION
NUMERIC(p,s) | NUMERIC(p,s), NUMBER(p,s) | NUMERIC(p,s) | NUMERIC(p,s) | NUMERIC(p,s) | NUMERIC(p,s) | CURRENCY | NUMERIC(p,s)
DECIMAL(p,s) | DECIMAL(p,s), NUMBER(p,s) | DECIMAL(p,s), MONEY | DECIMAL(p,s) | DECIMAL(p,s) | DECIMAL(p,s), MONEY |  | DECIMAL(p,s)
CHAR(n) | CHAR(n) n <= 2000 | CHAR(n) n <= 255 | CHAR(n) n <= 32767 | CHAR(n) n <= 254 | CHAR(n) n <= 8000 | CHAR(n) n <= 255 | CHAR(n) n <= 32,767
VARCHAR(n) | VARCHAR(n) n <= 4000 | VARCHAR(n) n <= 255 | VARCHAR(n) n <= 255 | VARCHAR(n) n <= 4000 | VARCHAR(n) n <= 8000 | VARCHAR(n) n <= 255 | VARCHAR(n) n <= 32,767
LONGVARCHAR | LONG limit is 2 Gigabytes | TEXT limit is 2 Gigabytes | TEXT limit is 2 Gigabytes | LONG VARCHAR limit is 32,700 bytes | TEXT limit is 2 Gigabytes | LONGCHAR limit is 2.0 Gigabytes | LONG VARCHAR limit is 2 Gigabytes
BINARY(n) |  | BINARY(n) n <= 255 | BYTE | CHAR(n) FOR BIT DATA n <= 254 | BINARY(n) n <= 8000 | BINARY(n) n <= 255 | BINARY n <= 32,767
VARBINARY | RAW(n) n <= 2000 | VARBINARY(n) n <= 255 | BYTE | VARCHAR(n) FOR BIT DATA n <= 4000 | VARBINARY(n) n <= 8000 | VARBINARY(n) n <= 255 |
LONGVARBINARY | LONG RAW limit is 2 Gigabyts | IMAGE limit is 2 Gigabytes | BYTE limit is 2 Gigabytes | LONG VARCHAR FOR BIT DATA limit is 32,700 bytes | IMAGE limit is 2 Gigabytes | LONGBINARY limit is 1.0 Gigabytes | IMAGE limit is 2 Gigabytes
DATE |  |  | DATE | DATE |  |  | DATE
TIME |  |  | DATETIME HOUR TO SECOND | TIME |  |  | TIME
TIMESTAMP | DATE | DATETIME, SMALLDATETIME | DATETIME YEAR TO FRACTION(S) | TIMESTAMP | DATETIME | DATETIME | TIMESTAMP
CLOB | CLOB |  | CLOB | CLOB(n) n <= 2,147,483,647 bytes |  |  |
BLOB | BLOB, BFILE |  | BLOB | BLOB(n) n <= 15,000,000 bytes |  |  |
ARRAY | VARRAY |  | LIST, SET, MULTISET |  |  |  |
STRUCT | OBJECT |  | ROW |  |  |  |
DISTINCT |  |  | DISTINCT |  |  |  |
REF | REF |  |  |  |  |  |
JAVA_OBJECT |  |  | OPAQUE |  |  |  |


Java Naming and Directory Interface

Java

Java Naming and Directory InterfaceTM

Documentation Contents
The Java Naming and Directory InterfaceTM (JNDI) provides naming and directory functionality to applications written in the JavaTM programming language. It is designed to be independent of any specific naming or directory service implementation. Thus a variety of services--new, emerging, and already deployed ones--can be accessed in a common way.

The JNDI architecture consists of an API (Application Programming Interface) and an SPI (Service Provider Interface). Java applications use this API to access a variety of naming and directory services. The SPI enables a variety of naming and directory services to be plugged in transparently, allowing the Java application using the API of the JNDI technology to access their services.

JavaTM 2 SDK, v 1.4 includes JNDI and four service providers (listed below). These packages are also available separately for use with the JDK 1.1.x, the Java 2 SDK, v 1.2 and v 1.3.

Enhancements Since Version 1.4.1

LDAP Service Provider
  • Support for LDAPS URLs.

Enhancements Since Version 1.4.0

DNS Service Provider
  • Support for controlling timeouts when submitting UDP queries.
  • Support for automatic discovery of DNS service.

LDAP Service Provider
  • Support for connection pooling.
  • Support for automatic discovery of LDAP service via DNS.
  • Support for use of multiple URLs for configuration.

Enhancements Since Version 1.3

DNS Service Provider
An Internet Domain Naming System (DNS) service provider has been added. This component enables applications to read data stored in the DNS.

Security Enhancements to the LDAP Service Provider
These enhancements bring the LDAP service provider in conformance with standard LDAP security requirements (RFC 2829) and promote better interoperability with widely deployed LDAP servers.

  • Support for the "Start TLS" (Transport Layer Security) extension (RFC 2830) and External SASL authentication mechanism. This enables applications to establish secure sessions over existing LDAP connections. This feature introduces two new classes.
    • javax.naming.ldap.StartTlsRequest
    • javax.naming.ldap.StartTlsResponse
  • Support for the GSS-API/Kerberos v5 SASL authentication mechanism (RFC 2222). This enables secure, authenticated access to the Windows 2000 and XP Active Directory servers.
  • Support for the Digest-MD5 SASL authentication mechanism (RFC 2831).

See the LDAP Service Provider documentation and the JNDI Tutorial for details and examples.

"corbaname" and "corbaloc" URL Support
The COS naming service provider supports the Interoperable Naming Service (INS) specification (99-12-03). This enables applications to use the "corbaname" URL from the initial context and to configure the provider by using the "corbaname" and "corbaloc" URLs.

JNDI Tutorial

  • JNDI Tutorial - A tutorial introduction to the JNDI technology with programming examples.

JNDI Architecture Documents

  • Executive Summary - also available in Postscript and PDF
  • JNDI API - also available in Postscript and PDF
  • JNDI SPI - also available in Postscript and PDF
JNDI API and SPI Specification
(javadoc)
  • JNDI API and SPI Specification - A list of the packages included in the JNDI technology.
JNDI Service Providers
To use JNDI with a particular naming or directory service, you need a JNDI service provider, which is a module that plugs in beneath the JNDI API to access the naming or directory service. The Java Software Web site maintains a list of service providers available for JNDI.

Java 2 SDK, v 1.4 includes the following service providers:

  • The LDAP Service Provider
  • The COS Naming Service Provider
  • The RMI Registry Service Provider
  • The DNS Service Provider

For More Information

  • Subscribe to the JNDI-INTEREST list
  • Source to a demonstration namespace browser written using JNDI and Swing
  • Related documents
  • The JNDI Home Page

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: jndi@java.sun.com 		Sun Microsystems, Inc
Java Software


JNDI/COS Naming Service Provider

COS Naming Service Provider for the
Java Naming and Directory InterfaceTM (JNDI)

Please send feedback to jndi@java.sun.com

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 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 © 1999-2001 Sun Microsystems, Inc., All Rights Reserved.


JNDI/DNS Service Provider

DNS Service Provider for the
Java Naming Directory InterfaceTM (JNDI)

Please send feedback to jndi@java.sun.com

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
Class | Where Specified
IN | RFC 1035
HS | RFC 1035
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 Name objects with right-to-left, dot-separated syntax, and with backslash (\) as the escape character. Escape sequences of the form \DDD may also be used, where DDD is 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 Name object 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 DirContext object. 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.url property 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.url property 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.conf file.) 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 DirContext interface. 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.url property, 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");

Copyright © 2002 Sun Microsystems, Inc. All rights reserved.


JNDI/LDAP Service Provider

LDAP Naming Service Provider for the
Java Naming and Directory InterfaceTM (JNDI)

Please send feedback to jndi@java.sun.com

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 |

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.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. No other type of customization of the pooling criteria is supported. In addition, a connection that requires the use of a custom socket factory or one that has enabled protocol tracing (via the com.sun.jndi.ldap.trace.ber environment property) cannot be pooled.

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 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.4 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 © 2002 Sun Microsystems, Inc. All rights reserved.


JNDI/LDAP Supplement: Guidelines for LDAP Service Providers

JNDI Implementor Guidelines for LDAP Service Providers

Draft 0.4.2

Please send feedback to jndi@java.sun.com

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,

env.put(Context.BATCHSIZE, "24");
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.
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,

env.put(LdapContext.CONTROL_FACTORIES,
        "com.sun.jndi.ldap.ctl.ResponseControlFactory");
sets the ResponseControlFactory class as the control factory to try.
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,

env.put(Context.INITIAL_CONTEXT_FACTORY,
        "com.sun.jndi.ldap.LdapCtxFactory");
selects Sun's LDAP provider.
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. If there is a property that you feel belongs on this list, please send a description of it to jndi@java.sun.com.

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.
    2. 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.

      2. 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.

      3. 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.

      4. 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.

      5. 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.

      6. 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 © 2002 Sun Microsystems, Inc. All rights reserved.


JNDI/RMI Registry Service Provider

RMI Registry Service Provider for the
Java Naming and Directory InterfaceTM (JNDI)

Please send feedback to jndi@java.sun.com

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.
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 © 1999-2001 Sun Microsystems, Inc., All Rights Reserved.


Outline of the JNDI API

Java

Outline of the Java Naming and Directory Interface TM (JNDI)
The JNDI consists of these packages:
  • javax.naming
      Contains classes and interfaces for accessing naming services.

  • javax.naming.directory
      Extends the core javax.naming package to provide functionality for accessing directories in addition to naming services.

  • 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 LDAPv3 extended operations and controls.

  • javax.naming.spi
      Contains the classes and interfaces that allow various naming and directory service providers to be dynamically plugged in beneath the JNDI.

Copyright © 1995-2001 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: jndi@java.sun.com 		Sun
Java Software


Java Naming and Directory Interface

The Java Naming and Directory InterfaceTM technology (JNDI) provides a unified interface to multiple naming and directory services. As part of the Java enterprise API set, JNDI enables seamless connectivity to heterogeneous enterprise naming and directory services. Developers can now build powerful and portable directory-enabled Java applications using this industry-standard interface.

The JNDI specification was developed by Sun Microsystems with a number of leading industry partners, including Novell, Netscape, SCO, and BEA.

Duke icon The 1.2 version of the specification and reference implementation are now available for download at the Java Software Web site.

Technical Overview

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 providi ng 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) may be used as the top-level naming facilit y for different organizations within an enterprise. The organizations themselves may 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 Java 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, an application can attach its own objects to the namespace. Such a facility enables any Java application to discover and retrieve objects of any type.

JNDI 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, new and existing ones in the installed base, can be a ccessed in a common way.

JNDI also defines a service provider's interface which allows various directory and naming service drivers to be plugged in.

Examples

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);

where building7 is the naming context representing a physical building that provides a convenient context for referring to the printers.

JNDI does all the work of locating the information needed to construct the printer object.

As another example, 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)", controls);

Other application examples include access to security credentials stored in an enterprise-wide directory service, access to electronic mail addresses, and access to addresses of a variety of existing services such as databases, network file systems, etc.

Overview of Interfaces

The Naming Interface - javax.naming

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, crea ting and destroying subcontexts of the same type, etc.

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, an application might use the name of a printer to look up the correspond ing Printer object, and then print to it directly:

Printer printer = (Printer)
 ctx.lookup("treekiller");
printer.print(report);

The application 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.

The Directory Interface - javax.naming.directory

Directory Objects and Attributes. The DirContext interface enables the directory capability by defining methods for examining and updating attributes associated with a directory object. Each directory object contains a set of zero or more objects of class Attribute. Each attribute is denoted by a string identifier and can have zero or more values of any type.

Directory Objects as Naming Context. 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.

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 invo kes the DirContext.search() method on the directory object, which returns the matching directory objects along with the requested attributes.

The Event Interface - javax.naming.event

Naming Events. The NamingEvent class represents an event generated by a naming or directory service. Examples of a NamingEvent are a change to a directory entry's attribute or a rename of a directory entry.

Naming Listeners. A NamingListener is an object that registers interests in NamingEvents. Listeners register with a context to receive notification of changes in the context, its children, or its subtree.

The LDAP Interface - javax.naming.ldap

The LdapContext interface allows an application to use LDAP v3-specific features, including extensions and controls, not already covered by the more generic DirContext interface.

The Service Provider Interface - javax.naming.spi

The JNDI SPI provides the means by which different naming/directory service providers can develop and hook up their implementations so that the corresponding services are accessible from applications that use JNDI. In add ition, because JNDI allows specification of names that span multiple namespaces, if one service provider implementation needs to interact with another in order to complete an operation, the SPI provides methods that allow different provid er implementations to cooperate to complete client JNDI operations.

http://java.sun.com/jndi

Copyright © 1999, Sun Microsystems, Inc. All rights reserved.


CONTENTS | PREV | NEXT JNDI API

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 ©1997-1999 Sun Microsystems, Inc. All Rights Reserved.


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

/*
 *
 * @(#)Search.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.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 ©1997-1999 Sun Microsystems, Inc. All Rights Reserved.


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
 * “cn=Barbara Jensen, ou=Product Development, o=Ace Industry, c=US”.
 * Retrieve all attributes from the entry.
 *
 */
#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 Babs’ entry */
    if ( ldap_search_s( ld, ENTRYDN, LDAP_SCOPE_SUBTREE,
            “(objectclass=*)”, 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.2.2 Read Using JNDI

/*
 * @(#)Rdentry.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 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 ©1997-1999 Sun Microsystems, Inc. All Rights Reserved.


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 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.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 ©1997-1999 Sun Microsystems, Inc. All Rights Reserved.


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 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 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 ©1997-1999 Sun Microsystems, Inc. All Rights Reserved.


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 ©1997-1999 Sun Microsystems, Inc. All Rights Reserved.


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 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 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 ©1997-1999 Sun Microsystems, Inc. All Rights Reserved.


Appendix C: JNDI Change History

CONTENTS | PREV | NEXT JNDI API

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 ©1997-1999 Sun Microsystems, Inc. All Rights Reserved.


CONTENTS | PREV | NEXT JNDI API

Java Naming and Directory Interface TM
Application Programming Interface

(JNDI API)

Please send comments to:

jndi@java.sun.com.

JNDI 1.2/JavaTM 2 Platform, Standard Edition, v 1.3
July 14, 1999
CONTENTS | PREV | NEXT

Copyright ©1997-1999 Sun Microsystems, Inc. All Rights Reserved.


1 Introduction

CONTENTS | PREV | NEXT JNDI API

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 ©1997-1999 Sun Microsystems, Inc. All Rights Reserved.


2 Goals and Design Principles

CONTENTS | PREV | NEXT JNDI API

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 ©1997-1999 Sun Microsystems, Inc. All Rights Reserved.


3 Overview of the Architecture

CONTENTS | PREV | NEXT JNDI API

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 ©1997-1999 Sun Microsystems, Inc. All Rights Reserved.


4 Fundamentals

CONTENTS | PREV | NEXT JNDI API

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 ©1997-1999 Sun Microsystems, Inc. All Rights Reserved.


5 Overview of the Interface

CONTENTS | PREV | NEXT JNDI API

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 <a href= API documentation." WIDTH="591" HEIGHT="405" ALIGN="BOTTOM" BORDER="0" NATURALSIZEFLAG="3">

(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. The information in this graphic is available in the <a href= API documentation." WIDTH="1002" HEIGHT="434" ALIGN="BOTTOM" BORDER="0" NATURALSIZEFLAG="3">

(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" NATURALSIZEFLAG="3">

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" NATURALSIZEFLAG="3">

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 ©1997-1999 Sun Microsystems, Inc. All Rights Reserved.


6 Configuration

CONTENTS | PREV | NEXT JNDI API

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 ©1997-1999 Sun Microsystems, Inc. All Rights Reserved.


7 Scenarios

CONTENTS | PREV | NEXT JNDI API

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 ©1997-1999 Sun Microsystems, Inc. All Rights Reserved.


8 Security Considerations

CONTENTS | PREV | NEXT JNDI API

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 ©1997-1999 Sun Microsystems, Inc. All Rights Reserved.


9 Design Choices

CONTENTS | PREV | NEXT JNDI API

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 ©1997-1999 Sun Microsystems, Inc. All Rights Reserved.


CONTENTS | PREV | NEXT JNDI API

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 ©1997-1999 Sun Microsystems, Inc. All Rights Reserved.


Appendix B: Legend for Class Diagram

CONTENTS | PREV | NEXT JNDI API

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 ©1997-1999 Sun Microsystems, Inc. All Rights Reserved.


CONTENTS | PREV | NEXT JNDI API

Appendix 1:
JNDI Standard Environment Properties

JNDI Environment Properties 1

Environment Configuration

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

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

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

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

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

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 ©1997-1999 Sun Microsystems, Inc. All Rights Reserved.


 [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]

jndi@java.sun.com
Copyright © 1999, Sun Microsystems, Inc. All rights reserved.


Copyright © 1999 by Sun Microsystems Inc.

901 San Antonio Road, Palo Alto, CA 94303.

All rights reserved.

RESTRICTED RIGHTS: Use, duplication or disclosure by the government is subject to the restrictions as set forth in subparagraph (c) (1) (ii) of the Rights in Technical Data and Computer Software Clause as DFARS 252.227-7013 and FAR 52.227-19.

Sun, Sun Microsystems, the Sun logo, Java, and JavaSoft, are trademarks or registered trademarks of Sun Microsystems, Inc.

THIS PUBLICATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MECHANTABILITY, FITNESS FOR A PARTICULAR USE, OR NON-INFRINGEMENT.

THIS PUBLICATION COULD INCLUDE TECHNICAL INACCURACIES OR TYPOGRAPHICAL ERRORS. CHANGES ARE PERIODICALLY ADDED TO THE INFORMATION HEREIN; THESE CHANGES WILL BE INCORPORATED IN NEW EDITIONS OF THE PUBLICATION. SUN MICROSYSTEMS, INC., MAY MAKE NEW IMPROVEMENTS AND/OR CHANGES IN THE PRODUCT(S) AND/OR THE PROGRAM(S) DESCRIBED IN THIS PUBLICATION AT ANY TIME.

jndi@java.sun.com
Copyright © 1999, Sun Microsystems, Inc. All rights reserved.


 [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 package javax.naming.spi. 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 <a href= 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:

  1. Define the class for the object (e.g., BSDPrinter) that implements Referenceable or is a subclass of Reference.
  2. Define the Reference and its reference addresses for the object.
  3. 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:

  1. Define the class for the object (e.g., BSDPrinter).
  2. Define the URL scheme for the object.
  3. 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:

  1. Define the class for the object (e.g., BSDPrinter).
  2. 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").
  3. 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:

  1. Define object factories that implement ObjectFactory.
  2. 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.

jndi@java.sun.com
Copyright © 1999, Sun Microsystems, Inc. All rights reserved.


 [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]

jndi@java.sun.com
Copyright © 1999, Sun Microsystems, Inc. All rights reserved.


 [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:

  1. The interface: A rounded rectangle
  2. The class: A rectangle
  3. The abstract class: A rectangle with an empty dot
  4. The final class: A rectangle with a black dot
  5. 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]

jndi@java.sun.com
Copyright © 1999, Sun Microsystems, Inc. All rights reserved.


 [Top] [Prev] [Next] [Bottom]

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 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.
 */
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 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.
 */
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 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.
 */
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]

jndi@java.sun.com
Copyright © 1999, Sun Microsystems, Inc. All rights reserved.


 [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 © 1999, Sun Microsystems, Inc. All rights reserved.


JNI - Java Native Interface

Java

Java Native Interface

 Documentation Contents
JavaTM Native Interface (JNI) is a standard programming interface for writing Java native methods and embedding the JavaTM virtual machine* into native applications. The primary goal is binary compatibility of native method libraries across all Java virtual machine implementations on a given platform.

The Java 2 SDK supports the old native method interface (NMI) only when using the classic virtual machine. NMI was originally implemented in Java Development Kit (JDKTM) 1.0. The old NMI is not part of the Java platform standard, and programmers are strongly encouraged to migrate their existing NMI code to the JNI.

JNI Enhancements
  • AWT Native Interface
  • JNI Enhancements in v 1.2
    • (Clarified June 2001)
  • JNI Enhancements in v 1.4

JNI 1.1 Specification
  • JNI 1.1 Specification
Other Information

  • The Java Tutorial has a trail on the Java Native Interface:
    Java Native Interface Tutorial

  • For JNI FAQs and information about the book The Java Native Interface: Programmer's Guide and Specification, see this document on the Java Software website:
    Java Native Interface Tips

*As used on this web site, the terms "Java virtual machine" or "JVM" mean a virtual machine for the Java platform.

Copyright © 2003 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: jni@java.sun.com 		Sun


JNI Enhancements in the Java 2 SDK

Java

JNI Enhancements
Introduced in version 1.2 of the JavaTM 2 SDK

 JNI Documentation

JNI has been enhanced in the Java 2 SDK to:

  • incorporate new features in the evolving Java platform,
  • ensure an efficient and stable interface for Java/native code integration.

Changes to the JNI are made based on feedback from users . Please continue to send your comments, suggestions, and concerns to jni@java.sun.com.

New Constants

#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 */

Enhancements to the Existing API

  • Class Operations
    • FindClass
  • Invocation API
    • JNI_CreateJavaVM
    • AttachCurrentThread
    • DetachCurrentThread
    • DestroyJavaVM

New Functions

  • Library and Version Management
    • JNI_OnLoad
    • JNI_OnUnload
  • Local Reference Management
    • EnsureLocalCapacity
    • PushLocalFrame
    • PopLocalFrame
    • NewLocalRef
  • Exceptions
    • ExceptionCheck
  • Weak Global References
    • NewWeakGlobalRef
    • DeleteWeakGlobalRef
  • Array Operations
    • GetPrimitiveArrayCritical
    • ReleasePrimitiveArrayCritical
  • String Operations
    • GetStringRegion
    • GetStringUTFRegion
    • GetStringCritical
    • ReleaseStringCritical
  • Reflection Support
    • FromReflectedMethod
    • FromReflectedField
    • ToReflectedMethod
    • ToReflectedField
  • Invocation API
    • GetEnv

Class Operations

In the enhanced Java security model, non-system classes can load native code. The JNI function FindClass has been extended so that it finds classes loaded with a class loader.

jclass FindClass(JNIEnv *env, const char *name);

In JDK 1.1, FindClass searched only local classes in CLASSPATH. The resulting classes did not have a class loader.

The Java security model has been extended to allow non-system classes to load and call native methods. In the Java 2 Platform, FindClass locates the class loader associated with the current native method. If the native code 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.

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.getBaseClassLoader 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.

Library and Version Management

In JDK 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.

In the Java 2 SDK, 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 versioning control and resource management, JNI libraries in the Java 2 Platform may optionally export the following two functions:

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.

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.

Local Reference Management

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.

JDK 1.1 provides a DeleteLocalRef function 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.

The Java 2 SDK provides an additional set of functions for local reference lifetime management.

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 Java 2 SDK, 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.

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.

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.

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.

Exceptions

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.

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 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.

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.

void DeleteWeakGlobalRef(JNIEnv *env, jweak obj);

Delete the VM resources needed for the given weak global reference.

Array Operations

In JDK 1.1, programmers can use Get/ReleaseArrayElements 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 allow native code to obtain a direct pointer to array elements even if the VM does not support pinning.

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/ReleaseArrayElements 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.

String Operations

In JDK 1.1, programmers can get primitive array elements in a user-supplied buffer. The Java 2 SDK allows native code to obtain Unicode or UTF-8 characters in a user-supplied buffer.

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.

< void GetStringUTFRegion(JNIEnv *env, jstring str, jsize start, jsize len, char *buf);

Translates len number of Unicode characters beginning at offset start into UTF-8 format and place the result in the given buffer buf.

Throws StringIndexOutOfBoundsException on index overflow.

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.

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.

jmethodID FromReflectedMethod(JNIEnv *env, jobject method);

Converts a java.lang.reflect.Method or java.lang.reflect.Constructor object to a method ID.

jfieldID FromReflectedField(JNIEnv *env, jobject field);

Converts a java.lang.reflect.Field to a field ID.

jobject ToReflectedMethod(JNIEnv *env, jclass cls,
   jmethodID methodID);

Converts a method ID derived from cls to a java.lang.reflect.Method or java.lang.reflect.Constructor object.

Throws OutOfMemoryError and returns 0 if fails.

jobject ToReflectedField(JNIEnv *env, jclass cls,
   jfieldID fieldID);

Converts a field ID derived from cls to a java.lang.reflect.Field object.

Throws OutOfMemoryError and returns 0 if fails.

Invocation API

jint JNI_CreateJavaVM(JavaVM **pvm, void **penv, void *args);

In JDK 1.1, the second argument to JNI_CreateJavaVM is always a pointer to JNIEnv *. The third argument is a pointer to a JDK 1.1 specific structure (JDK1_1InitArgs). The JDK1_1InitArgs structure is clearly not designed to be portable on all VMs.

In the Java 2 SDK, we introduce a standard VM initialization structure. Backward compatibility is preserved. If the VM initialization argument points to a JDK1_1InitArgs structure, JNI_CreateJavaVM still returns the 1.1 version of JNI interface pointer. The VM returns the 1.2 version of JNI interface pointer if the third argument points to a JavaVMInitArgs structure. Unlike JDK1_1InitArgs, which contains a fixed set of options, JavaVMInitArgs 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 JNI_VERSION_1_2. (In contrast, the version field in JDK1_1InitArgs must be set to JNI_VERSION_1_1.) The options field is an array of the following type:
typedef struct JavaVMOption {
    char *optionString;
    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 Java 2 SDK 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 Java 2 SDK:

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 Java 2 SDK, there is no longer any need to call
 * JNI_GetDefaultJavaVMInitArgs.
 */
res = JNI_CreateJavaVM(&vm, (void **)&env, &vm_args);
if (res < 0) ...

The Java 2 SDK still supports JDK1_1InitArgs in exactly the same way as JDK 1.1.

jint AttachCurrentThread(JavaVM *vm, void **penv, void *args);

In JDK 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.

In the Java 2 SDK, 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 JNI_VERSION_1_2 */
    char *name;    /* the name of the thread, or NULL */
    jobject group; /* global ref of a ThreadGroup object, or NULL */
} JavaVMAttachArgs;

jint DetachCurrentThread(JavaVM *vm);

In JDK 1.1, the main thread cannot be detached from the VM. It must call DestroyJavaVM to unload the entire VM.

In the Java 2 SDK, the main thread can be detached from the VM.

jint DestroyJavaVM(JavaVM *vm);

The support for DestroyJavaVM was not complete in 1.1. Only the main thread may call DestroyJavaVM. In the Java 2 SDK, 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 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 user-level thread. The Java 2 SDK still does not support VM unloading, however. DestroyJavaVM always returns an error code.

jint GetEnv(JavaVM *vm, void **env, jint version);

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.
Copyright © 1995-99 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: jni@java.sun.com 		Sun


JNI Enhancements in the Java 2 SDK

Java

JNI Enhancements
Introduced in Version 1.4
of the JavaTM 2 SDK

 JNI Documentation

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: jni@java.sun.com 		Sun


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 © 2003 Sun Microsystems, Inc. All rights reserved.


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.

Loading and Linking Native Methods

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.
_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 only JNI functions that are safe to call are ExceptionOccurred(), ExceptionDescribe(), and ExceptionClear(). The ExceptionDescribe() function prints a debugging message about the pending exception.

Contents | Previous | Next

Copyright © 2003 Sun Microsystems, Inc. All rights reserved.


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
  • Object Operations
  • Accessing Fields of Objects
  • Calling Instance Methods
  • Accessing Static Fields
  • Calling Static Methods
  • String Operations
  • Array Operations
  • Registering Native Methods
  • Monitor Operations
  • 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,
    NULL,
    NULL,
    NULL,
    GetSuperclass,
    IsAssignableFrom,
    NULL,

    Throw,
    ThrowNew,
    ExceptionOccurred,
    ExceptionDescribe,
    ExceptionClear,
    FatalError,
    NULL,
    NULL,

    NewGlobalRef,
    DeleteGlobalRef,
    DeleteLocalRef,
    IsSameObject,
    NULL,
    NULL,

    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,
};

Version Information

GetVersion

jint GetVersion(JNIEnv *env);

Returns the version of the native method interface.

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 JDK1.1, GetVersion() returns 0x00010001.

Class Operations

DefineClass

jclass DefineClass(JNIEnv *env, 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.

PARAMETERS:

env: the JNI interface pointer.

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.

FindClass

jclass FindClass(JNIEnv *env, const char *name);

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.

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.

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.

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.

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.

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.

PARAMETERS:

env: the JNI interface pointer.

clazz: a subclass of java.lang.Throwable.

message: the message used to construct the java.lang.Throwable object.

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.

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.

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.

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.

PARAMETERS:

env: the JNI interface pointer.

msg: an error message.

Global and Local 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().

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.

PARAMETERS:

env: the JNI interface pointer.

globalRef: a global reference.

DeleteLocalRef

void DeleteLocalRef(JNIEnv *env, jobject localRef);

Deletes the local reference pointed to by localRef.

PARAMETERS:

env: the JNI interface pointer.

localRef: a local reference.

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.

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, 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.

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.

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.

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.

PARAMETERS:

env: the JNI interface pointer.

obj: a Java object (must not be NULL).

RETURNS:

Returns a Java class object.

IsInstanceOf

jboolean IsInstanceOf(JNIEnv *env, jobject obj,
jclass clazz);

Tests whether an object is an instance of a class.

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.

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.

PARAMETERS:

env: the JNI interface pointer.

clazz: a Java class object.

name: the field name in a 0-terminated UTF-8 string.

sig: the field signature in a 0-terminated 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-1 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

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-2 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

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.

PARAMETERS:

env: the JNI interface pointer.

clazz: a Java class object.

name: the method name in a 0-terminated UTF-8 string.

sig: the method signature in 0-terminated 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, 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-3 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

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, 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-4 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

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.

PARAMETERS:

env: the JNI interface pointer.

clazz: a Java class object.

name: the static field name in a 0-terminated UTF-8 string.

sig: the field signature in a 0-terminated 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-5 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

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-6 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

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.

PARAMETERS:

env: the JNI interface pointer.

clazz: a Java class object.

name: the static method name in a 0-terminated UTF-8 string.

sig: the method signature in a 0-terminated 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-7 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

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.

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.

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.

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().

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 UTF-8 characters.

PARAMETERS:

env: the JNI interface pointer.

bytes: the pointer to a 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 UTF-8 length in bytes of a string.

PARAMETERS:

env: the JNI interface pointer.

string: a Java string object.

RETURNS:

Returns the UTF-8 length of the string.

GetStringUTFChars

const jbyte* GetStringUTFChars(JNIEnv *env, jstring string,
jboolean *isCopy);

Returns a pointer to an array of UTF-8 characters of the string. 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.

PARAMETERS:

env: the JNI interface pointer.

string: a Java string object.

isCopy: a pointer to a boolean.

RETURNS:

Returns a pointer to a 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().

PARAMETERS:

env: the JNI interface pointer.

string: a Java string object.

utf: a pointer to a UTF-8 string.

Array Operations

GetArrayLength

jsize GetArrayLength(JNIEnv *env, jarray array);

Returns the number of elements in the array.

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.

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.

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.

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-8 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

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-9 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

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-11 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

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-12 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

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, 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-13 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
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.

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 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, ...);
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.

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.

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.

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.

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.

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.

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 © 2003 Sun Microsystems, Inc. All rights reserved.


Introduction

Chapter 1

This chapter introduces the Java Native Interface (JNI). The JNI is a native programming interface. It allows Java code that runs inside a Java Virtual Machine (VM) to interoperate with applications and libraries written in other programming languages, such as C, C++, and assembly.

The most important benefit of the JNI is that it imposes no restrictions on the implementation of the underlying Java VM. Therefore, Java VM vendors can add support for the JNI without affecting other parts of the VM. Programmers can write one version of a native application or library and expect it to work with all Java VMs supporting the JNI.

This chapter covers the following topics:

  • Java Native Interface Overview
  • Background
  • Objectives
  • Java Native Interface Approach
  • Programming to the JNI
  • Changes in JDK 1.1.2

Java Native Interface Overview

While you can write applications entirely in Java, there are situations where Java alone does not meet the needs of your application. Programmers use the JNI to write Java native methods to handle those situations when an application cannot be written entirely in Java.

The following examples illustrate when you need to use Java native methods:

  • The standard Java class library does not support the platform-dependent features needed by the application.
  • You already have a library written in another language, and wish to make it accessible to Java code through the JNI.
  • You want to implement a small portion of time-critical code in a lower-level language such as assembly.

By programming through the JNI, you can use native methods to:

  • Create, inspect, and update Java objects (including arrays and strings).
  • Call Java methods.
  • Catch and throw exceptions.
  • Load classes and obtain class information.
  • Perform runtime type checking.

You can also use the JNI with the Invocation API to enable an arbitrary native application to embed the Java VM. This allows programmers to easily make their existing applications Java-enabled without having to link with the VM source code.

Background

Currently, VMs from different vendors offer different native method interfaces. These different interfaces force programmers to produce, maintain, and distribute multiple versions of native method libraries on a given platform.

We briefly examine some of the existing native method interfaces, such as:

  • JDK 1.0 native method interface
  • Netscape’s Java Runtime Interface
  • Microsoft’s Raw Native Interface and Java/COM interface

JDK 1.0 Native Method Interface

JDK 1.0 shipped with a native method interface. Unfortunately, there are two major reasons that this interface is unsuitable for adoption by other Java VMs.

First, the native code accesses fields in Java objects as members of C structures. However, the Java Language Specification does not define how objects are laid out in memory. If a Java VM lays out objects differently in memory, then the programmer would have to recompile the native method libraries.

Second, JDK 1.0’s native method interface relies on a conservative garbage collector. The unrestricted use of the unhand macro, for example, makes it necessary to conservatively scan the native stack.

Java Runtime Interface

Netscape proposed the Java Runtime Interface (JRI), a general interface for services provided in the Java virtual machine. JRI is designed with portability in mind---it makes few assumptions about the implementation details in the underlying Java VM. The JRI addresses a wide range of issues, including native methods, debugging, reflection, embedding (invocation), and so on.

Raw Native Interface and Java/COM Interface

The Microsoft Java VM supports two native method interfaces. At the low level, it provides an efficient Raw Native Interface (RNI). The RNI offers a high degree of source-level backward compatibility with the JDK’s native method interface, although it has one major difference. Instead of relying on conservative garbage collection, the native code must use RNI functions to interact explicitly with the garbage collector.

At a higher level, Microsoft's Java/COM interface offers a language-independent standard binary interface to the Java VM. Java code can use a COM object as if it were a Java object. A Java class can also be exposed to the rest of the system as a COM class.

Objectives

We believe that a uniform, well-thought-out standard interface offers the following benefits for everyone:

  • Each VM vendor can support a larger body of native code.
  • Tool builders will not have to maintain different kinds of native method interfaces.
  • Application programmers will be able to write one version of their native code and this version will run on different VMs.

The best way to achieve a standard native method interface is to involve all parties with an interest in Java VMs. Therefore we organized a series of discussions among the Java licensees on the design of a uniform native method interface. It is clear from the discussions that the standard native method interface must satisfy the following requirements:

  • Binary compatibility - The primary goal is binary compatibility of native method libraries across all Java VM implementations on a given platform. Programmers should maintain only one version of their native method libraries for a given platform.
  • Efficiency - To support time-critical code, the native method interface must impose little overhead. All known techniques to ensure VM-independence (and thus binary compatibility) carry a certain amount of overhead. We must somehow strike a compromise between efficiency and VM-independence.
  • Functionality - The interface must expose enough Java VM internals to allow native methods to accomplish useful tasks.

Java Native Interface Approach

We hoped to adopt one of the existing approaches as the standard interface, because this would have imposed the least burden on programmers who had to learn multiple interfaces in different VMs. Unfortunately, no existing solutions are completely satisfactory in achieving our goals.

Netscape’s JRI is the closest to what we envision as a portable native method interface, and was used as the starting point of our design. Readers familiar with the JRI will notice the similarities in the API naming convention, the use of method and field IDs, the use of local and global references, and so on. Despite our best efforts, however, the JNI is not binary-compatible with the JRI, although a VM can support both the JRI and the JNI.

Microsoft’s RNI is an improvement over JDK 1.0 because it solves the problem of native methods working with a nonconservative garbage collector. The RNI, however, is not suitable as a VM-independent native method interface. Like the JDK, RNI native methods access Java objects as C structures. This leads to two problems:

  • RNI exposes the layout of internal Java objects to native code.
  • Direct access of Java objects as C structures makes it impossible to efficiently incorporate “write barriers,” which are necessary in advanced garbage collection algorithms.

As a binary standard, COM ensures complete binary compatibility across different VMs. Invoking a COM method requires only an indirect call, which carries little overhead. In addition, COM objects are a great improvement over dynamic-link libraries in solving versioning problems.

The use of COM as the standard Java native method interface, however, is hampered by a few factors:

  • First, the Java/COM interface lacks certain desired functions, such as accessing private fields and raising general exceptions.
  • Second, the Java/COM interface automatically provides the standard IUnknown and IDispatch COM interfaces for Java objects, so that native code can access public methods and fields. Unfortunately, the IDispatch interface does not deal with overloaded Java methods and is case-insensitive in matching method names. Furthermore, all Java methods exposed through the IDispatch interface are wrapped to perform dynamic type checking and coercion. This is because the IDispatch interface is designed with weakly-typed languages (such as Basic) in mind.
  • Third, instead of dealing with individual low-level functions, COM is designed to allow software components (including full-fledged applications) to work together. We believe that it is not appropriate to treat all Java classes or low-level native methods as software components.
  • Fourth, the immediate adoption of COM is hampered by the lack of its support on UNIX platforms.

Although we do not expose Java objects to the native code as COM objects, the JNI interface itself is binary-compatible with COM. We use the same jump table structure and calling convention that COM does. This means that, as soon as cross-platform support for COM is available, the JNI can become a COM interface to the Java VM.

We do not believe that the JNI should be the only native method interface supported by a given Java VM. A standard interface benefits programmers who would like to load their native code libraries into different Java VMs. In some cases, the programmer may have to use a lower-level, VM-specific interface to achieve top efficiency. In other cases, the programmer might use a higher-level interface to build software components. Indeed, we hope that, as the Java environment and component software technologies become more mature, native methods will gradually lose their significance.

Programming to the JNI

Native method programmers should start programming to the JNI. Programming to the JNI insulates you from unknowns, such as the vendor’s VM that the end user might be running. By conforming to the JNI standard, you will give a native library the best chance to run in a given Java VM. For example, although JDK 1.1 will continue to support the old-style native method interface that was implemented in JDK 1.0, it is certain that future versions of the JDK will stop supporting the old-style native method interface. Native methods relying on the old-style interface will have to be rewritten.

If you are implementing a Java VM, you should implement the JNI. We (Javasoft and the licensees) have tried our best to ensure that the JNI does not impose any overhead or restrictions on your VM implementation, including object representation, garbage collection scheme, and so on. Please let us know if you run into any problems we might have overlooked.

Changes in JDK 1.1.2

To better support the Java Runtime Environment (JRE), the Invocation API has been extended in JDK 1.1.2 in a few minor ways. The changes do not break any existing code. The JNI Native Method Interface has not been changed.

  • The reserved0 field in the JDK1_1InitArgs structure has been renamed to version. The JDK1_1InitArgs structure holds the initialization arguments to JNI_CreateJavaVM. Callers of JNI_GetDefaultJavaVMInitArgs and JNI_CreateJavaVM must set the version field to 0x00010001. JNI_GetDefaultJavaVMInitArgs has been changed to return a jint indicating whether the requested version is supported.
  • The reserved1 field in the JDK1_1InitArgs structure has been renamed to properties. This is a NULL-terminated array of strings. Each string has the format:
    • name=value

    indicating a system property. (This facility corresponds to the -D option in the java command line.)

  • In JDK 1.1.1, the thread calling DestroyJavaVM must be the only user thread in the VM. JDK 1.1.2 has lifted this restriction. If DestroyJavaVM is called when there is more than one user thread, the VM waits until the current thread is the only user thread, and then tries to destroy itself.

Contents | Previous | Next

Copyright © 2003 Sun Microsystems, Inc. All rights reserved.


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.

To enhance the embeddability of the Java VM, the Invocation API is extended in JDK 1.1.2 in a few minor ways.

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 */

    JDK1_1InitArgs vm_args; /* JDK 1.1 VM initialization arguments */

    vm_args.version = 0x00010001; /* New in 1.1.2: VM version */
    /* Get the default initialization arguments and set the class
     * path */
    JNI_GetDefaultJavaVMInitArgs(&vm_args);
    vm_args.classpath = ...;

    /* load and initialize a Java VM, return a JNI interface
     * pointer in env */
    JNI_CreateJavaVM(&jvm, &env, &vm_args);

    /* 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 reaonable 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.

Unloading the VM

The main thread cannot detach itself from the VM. Instead, it must call DestroyJavaVM() to unload the entire VM.

The VM waits until the main thread is the only 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 main 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.

Initialization Structures

Different Java VM implementation will likely require different initialization arguments. It is difficult to come up with a standard initialization structure suitable for all present and future Java VMs. As a compromise, we reserve the first field (version) to identify the content of the initialization structure. Native applications embedding JDK 1.1.2 must set the version field to 0x00010001. VM implementations are encouraged to use the same initialization structure as JDK, although other implementations may choose to ignore some of the initialization arguments supported by JDK.

Version numbers 0x80000000 to 0xFFFFFFFF are reserved, and should not be recognized by any VM implementation.

The following code shows the structure used to initialize the Java VM in JDK 1.1.2.

typedef struct JDK1_1InitArgs {
   /* The first two fields were reserved in JDK 1.1, and
      formally introduced in JDK 1.1.2. */
   /* Java VM version */
    jint version;

   /* System properties. */
    char **properties;

   /* whether to check the Java source files are newer than
    * compiled class files. */
    jint checkSource;

   /* maximum native stack size of Java-created threads. */
    jint nativeStackSize;

   /* maximum Java stack size. */
    jint javaStackSize;

   /* initial heap size. */
    jint minHeapSize;

   /* maximum heap size. */
    jint maxHeapSize;

   /* controls whether Java byte code should be verified:
    * 0 -- none, 1 -- remotely loaded code, 2 -- all code. */
    jint verifyMode;

   /* the local directory path for class loading. */
    const char *classpath;

   /* a hook for a function that redirects all VM messages. */
    jint (*vfprintf)(FILE *fp, const char *format,
                     va_list args);

   /* a VM exit hook. */
    void (*exit)(jint code);

   /* a VM abort hook. */
    void (*abort)();

   /* whether to enable class GC. */
    jint enableClassGC;

   /* whether GC messages will appear. */
    jint enableVerboseGC;

   /* whether asynchronous GC is allowed. */
    jint disableAsyncGC;

   /* Three reserved fields. */
    jint reserved0;
    jint reserved1;
    jint reserved2;
} JDK1_1InitArgs;

In JDK 1.1.2, the initialization structure provides hooks so that a native application can redirect VM messages and obtain control when the VM terminates.

The structure below is passed as an argument when a native thread attaches to a Java VM in JDK 1.1.2. In actuality, no arguments are required for a native thread to attach to the JDK 1.1.2. The JDK1_1AttachArgs structure consists only of a padding slot for those C compilers that do not permit empty structures.

typedef struct JDK1_1AttachArgs {
   /*
    * JDK 1.1 does not need any arguments to attach a
    * native thread. The padding is here to satisfy the C
    * compiler which does not permit empty structures.
    */
    void *__padding;
} JDK1_1AttachArgs;

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,
};

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 must1 set the vm_args->version field to the JNI version it expects the VM to support. In JDK 1.1.2, vm_args->version must be set to 0x00010001. After this function returns, vm_args->version will be set to the actual JNI version the VM supports.

PARAMETERS:

vm_args: a pointer to a VM-specific initialization structure in to which the default arguments are filled.

RETURNS:

Returns “0” if the requested version is supported; returns 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.

JDK 1.1.2 does not support creating more than one VM in a single process.

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 “0” on success; returns a negative number on failure.

JNI_CreateJavaVM

jint JNI_CreateJavaVM(JavaVM **p_vm, JNIEnv **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.

JDK 1.1 does not support creating more than one VM in a single process. The version field in vm_args must2 be set to 0x00010001.

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 “0” on success; returns a negative number on failure.

DestroyJavaVM

jint DestroyJavaVM(JavaVM *vm);

Unloads a Java VM and reclaims its resources. Only the main thread can unload the VM. The system waits until the main thread is only remaining user thread before it destroys the VM.

PARAMETERS:

vm: the Java VM that will be destroyed.

RETURNS:

Returns “0” on success; returns a negative number on failure.

JDK 1.1.2 does not support unloading the VM.

AttachCurrentThread

jint AttachCurrentThread(JavaVM *vm, JNIEnv **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.

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: VM-specific thread attachment arguments.

RETURNS:

Returns “0” on success; returns a negative number on failure.

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.

The main thread, which is the thread that created the Java VM, cannot be detached from the VM. Instead, the main thread must call JNI_DestroyJavaVM() to unload the entire VM.

PARAMETERS:

vm: the VM from which the current thread will be detached.

RETURNS:

Returns “0” on success; returns a negative number on failure.

1JDK 1.1 did not require the native code to set the version field. For backward compatibility, JDK 1.1.2 assumes that the requested version is 0x00010001 if the version field is not set. Future versions of JDK will require the version field to be set to an appropriate value.
2JDK 1.1 did not require the native code to set the version field. For backward compatibility, JDK 1.1.2 assumes that the requested version is 0x00010001 if the version field is not set. Future versions of JDK will require the version field to be set to an appropriate value.

Contents | Previous

Copyright © 2003 Sun Microsystems, Inc. All rights reserved.


Java Native Interface Specification
Contents | Previous | Next

Contents

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

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

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

Global and Local References

NewGlobalRef

DeleteGlobalRef

DeleteLocalRef

Object Operations

AllocObject

NewObject NewObjectA NewObjectV

GetObjectClass

IsInstanceOf

IsSameObject

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 Call<type>MethodV Routines

CallNonvirtual<type>Method Routines CallNonvirtual<type>MethodA Routines 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 CallStatic<type>MethodV Routines

String Operations

NewString

GetStringLength

GetStringChars

ReleaseStringChars

NewStringUTF

GetStringUTFLength

GetStringUTFChars

ReleaseStringUTFChars

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

Registering Native Methods

RegisterNatives

UnregisterNatives

Monitor Operations

MonitorEnter

MonitorExit

Java VM Interface

GetJavaVM

5. The Invocation API

Overview

Creating the VM

Attaching to the VM

Unloading the VM

Initialization Structures

Invocation API Functions

JNI_GetDefaultJavaVMInitArgs

JNI_GetCreatedJavaVMs

JNI_CreateJavaVM

DestroyJavaVM

AttachCurrentThread

DetachCurrentThread

Contents | Previous | Next

Copyright © 2003 Sun Microsystems, Inc. All rights reserved.


JNI Types and Data Structures

Chapter 3

This chapter discusses how the JNI maps Java types to native C types.

Primitive Types

Table 3-1 describes Java primitive types and their machine-dependent native equivalents.

Table 3-1 Primitive Types and Native Equivalents
Java Type | Native Type | Description
boolean | jboolean | unsigned 8 bits
byte | jbyte | signed 8 bits
char | jchar | unsigned 16 bits
short | jshort | signed 16 bits
int | jint | signed 32 bits
long | jlong | signed 64 bits
float | jfloat | 32 bits
double | jdouble | 64 bits
void | void | N/A

The following definition is provided for convenience.

#define JNI_FALSE  0
#define JNI_TRUE   1

The jsize integer type is used to describe cardinal indices and sizes:

typedef jint jsize;

Reference Types

The JNI includes a number of reference types that correspond to different kinds of Java objects. JNI reference types are organized in the hierarchy shown in Figure 3-1.

The top of the heirarchy is jobject. Subclasses of jobject are jclass, jstring, jarray and jthrowable. Subclasses of jarray are jobjectArray, jbooleanArray, jbyteArray, jcharArray, jshortArray, jintArray, jlongArray, jfloatArray, jdoubleArray.

Figure 3-1 Reference Type Hierarchy

In C, all other JNI reference types are defined to be the same as jobject. For example:

typedef jobject jclass;

In C++, JNI introduces a set of dummy classes to enforce the subtyping relationship. For example:

class _jobject {};
class _jclass : public _jobject {};
...
typedef _jobject *jobject;
typedef _jclass *jclass;

Field and Method IDs

Method and field IDs are regular C pointer types:

struct _jfieldID;              /* opaque structure */
typedef struct _jfieldID *jfieldID;   /* field IDs */

struct _jmethodID;              /* opaque structure */
typedef struct _jmethodID *jmethodID; /* method IDs */

The Value Type

The jvalue union type is used as the element type in argument arrays. It is declared as follows:

typedef union jvalue {
    jboolean z;
    jbyte    b;
    jchar    c;
    jshort   s;
    jint     i;
    jlong    j;
    jfloat   f;
    jdouble  d;
    jobject  l;
} jvalue;

Type Signatures

The JNI uses the Java VM’s representation of type signatures. Table 3-2 shows these type signatures.

Table 3-2 Java VM 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

For example, the Java method:

long f (int n, String s, int[] arr);

has the following type signature:

(ILjava/lang/String;[I)J

UTF-8 Strings

The JNI uses UTF-8 strings to represent various string types. UTF-8 strings are the same as those used by the Java VM. UTF-8 strings are encoded so that character sequences that contain only nonnull ASCII characters can be represented using only one byte per character, but characters of up to 16 bits can be represented. All characters in the range \u0001 to \u007F are represented by a single byte, as follows:

Byte consisting of 0 in the first position followed by bits 0 through 6 of the bits representing the value of the character.

The seven bits of data in the byte give the value of the character that is represented. The null character (\u000) and characters in the range \u0080 to \u07FF are represented by a pair of bytes, x and y, as follows:

The x byte with 110 in the first 3 positions followed by bits 6 through 10 of the bits representing the value of the character. The y byte with 10 in the first 2 positions followed by bits 0 through 5 representing the value of the character.

The bytes represent the character with the value ((x&0x1f)<<6)+(y&0x3f).

Characters in the range \u0800 to \uFFFF are represented by three bytes, x, y, and z:

The x byte with 1110 followed by bits 12 through 15 of the bits representing the character. The y byte with 10 followed by bits 6 through 11. The z byte with 10 followed by bits 0 through 5.

The character with the value ((x&0xf)<<12)+(y&0x3f)<<6)+(z&0x3f) is represented by the three bytes.

There are two differences between this format and the “standard” UTF-8 format. First, the null byte (byte)0 is encoded using the two-byte format rather than the one-byte format. This means that Java VM UTF-8 strings never have embedded nulls. Second, only the one-byte, two-byte, and three-byte formats are used. The Java VM does not recognize the longer UTF-8 formats.

Contents | Previous | Next

Copyright © 2003 Sun Microsystems, Inc. All rights reserved.


Java(tm) Platform Debugger Architecture

Java

JavaTM Platform Debugger Architecture

 Home Page

Architecture Overview

The JavaTM Platform Debugger Architecture is structured as follows:
             Components                         Debugger Interfaces

                /    |--------------|
               /     |     VM       |
 debuggee ----(      |--------------|  <------- JVMDI - Java VM Debug Interface
               \     |   back-end   |
                \    |--------------|
                /           |
 comm channel -(            |  <--------------- JDWP - Java Debug Wire Protocol
                \           |
                     |--------------|
                     | front-end    |
                     |--------------|  <------- JDI - Java Debug Interface
                     |      UI      |
                     |--------------|

What is the Java Platform Debugger Architecture (JPDA)?

JPDA is a multi-tiered debugging architecture that allows tools developers to easily create debugger applications which run portably across platforms, virtual machine (VM) implementations and SDK versions.

JPDA consists of three layers:

JVMDI - Java VM Debug Interface
Defines the debugging services a VM provides.
JDWP - Java Debug Wire Protocol
Defines the communication between debuggee and debugger processes.
JDI - Java Debug Interface
Defines a high-level Java language interface which tool developers can easily use to write remote debugger applications.

Reference implementation

In addition to the specification of these interfaces, Sun Microsystems also provides a reference implementation, which consists of:
  • JVMDI implementations on multiple Sun VMs (see VM documentation).
  • A back-end which uses JVMDI to implement the debuggee side of JDWP.
  • A front-end which uses the debugger side of JDWP to implement JDI.
  • Two simple example debugger applications which are built on JDI.
This provides a layered implementation in which any layer may be substituted.

Using JPDA

A debugger developer may hook into JPDA at any layer. Since the JDI is the highest level and easiest to use we encourage developers to use this interface. Suppose a company develops a debugger using JDI. They can use it with the reference implementation and it will automatically work with the VMs and platforms Sun supports. It can also work, for example, with the reference implementation front-end and a debuggee running another company's VM that implements JDWP (which might use or by-pass JVMDI).

Some debuggers are built on top of lower layers, JDWP (for example if the front-end is not written in the Java language) or JVMDI (for specialized debuggers which need low-level functionality).

Components

debuggee

    The debuggee is the process being debugged, it consists of the application being debugged (not shown), the VM running the application and the back-end of the debugger.

Java Virtual Machine (VM)

    This refers to the VM running the application being debugged.

    The debugger architecture is being designed for use in wide spectrum of VM implementations.

    The VM implements the Java Virtual Machine Debug Interface (JVMDI).

back-end

    The back-end of the debugger is responsible for communicating requests from the debugger front-end to the debuggee VM and for communicating the response to these requests (including desired events) to the front-end. The back-end communicates with the front-end over a communications channel using the Java Debug Wire Protocol (JDWP). The back-end communicates with the debuggee VM using the Java Virtual Machine Debug Interface (JVMDI).

    It is clear from experience that debugger support code, running on the debuggee and written in Java, contends with the debuggee in ways that cause hangs and other undesired behavior. Thus, the back-end is native code. This, in turn, implies that the JVMDI be a pure native interface.

communications channel

    The communications channel is the link between the front and back ends of the debugger. The transport mechanism used is unspecified; possible mechanisms include: sockets, serial lines, and shared memory. However, the format and semantics of the serialized bit-stream flowing over the channel is specified by the Java Debug Wire Protocol (JDWP).

front-end

    The debugger front-end implements the high-level Java Debug Interface (JDI). The front-end uses the information from the low-level Java Debug Wire Protocol (JDWP).

User Interface (UI)

    The user interface to the debugger is not specified; the intent is that tool vendors will provide value added implementations. We provide an example simple graphical user interface (GUI) which serves as test harness and as a starting point for the development of more complex GUIs. A version of JDB is also available as an example.

    The example UIs are clients of the Java Debug Interface (JDI).

Debugger Interfaces

Java Virtual Machine Debugger Interface (JVMDI)
    A native interface implemented by the VM.

    Defines the services a VM must provide for debugging. Includes requests for information (for example, current stack frame), actions (for example, set a breakpoint), and notification (for example, when a breakpoint has been hit). A debugger may make use of VM information other than this (for example, Java Native Interface (JNI)), but this is the source of all debugger specific information.

    Specifying the VM Interface allows any VM implementor to plug easily into the debugging architecture. It also allows alternate communication channel implementations. VM implementations which do not adhere to this interface can still provide access via the Java Debug Wire Protocol (JDWP).

    See also:

      JVMDI Specification

Java Debug Wire Protocol (JDWP)
    Defines the format of information and requests transferred between the debuggee process and the debugger front-end. It does not define the transport mechanism (socket, serial line, shared memory, ...).

    The specification of the protocol allows the debuggee and debugger front-end to run under separate VM implementations and/or on separate platforms. It also allows the front-end to be written in a language other than Java, or the debuggee to be non-native (e.g. Java).

    Information and requests are roughly at the level of the Java Virtual Machine Debug Interface (JVMDI), but will include additional information and requests necessitated by bandwidth issues, examples include information filtering and batching.

    See also:

      JDWP Specification

Java Debug Interface (JDI)
    A 100% Java interface implemented by the front-end.

    Defines information and requests at a user code level.

    While debugger implementors could directly use the Java Debug Wire Protocol (JDWP) or Java Virtual Machine Debug Interface (JVMDI), this interface greatly facilitates the integration of debugging capabilities into development environments. We recommend the JDI layer for all debugger development.

    See also:

      JDI Specification

Copyright © 2001 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-debugger@sun.com

Sun


JPDA Connection and Invocation

Java

Connection and Invocation Details

Contents

Transports
Connectors
Sun VM Invocation Options
Debugging Plug-in Applets
Connecting with JDB

Transports

A JPDA transport is a form of inter-process communication used by a debugger application process and the virtual machine that is being debugged (often called the target VM). JDI and JDWP admit the existence of transports and refer to individual transports by a unique name, but the JDI and JDWP specifications do not require specific transport implementations to exist. Transport implementations can allow communications between processes running in a single machine, on different machines, or either.

In establishing a connection between a debugger application and a target VM, one side acts as a server, listening for a connection. At some later time the other side attaches to the listener and a connection is established. JPDA transports allow either the debugger application or the target VM to act as a server. During the establishment of a connection, transport addresses are used to identify the other side of a connection. Transport addresses are strings; their format depends on the transport implementation.

The JPDA reference implementation on Microsoft Windows provides two transports: a shared memory transport and a socket transport. The JPDA reference implementation on the Solaris operating environment provides a socket transport. Future versions of the JPDA reference implementation may include additional transports, Future versions of the JPDA specification may provide an interface for plugging additional transports into an implementation.

Socket Transport

The JPDA reference implementation provides a socket transport on both the Solaris operating environment and Microsoft Windows platforms. The socket transport uses standard TCP/IP sockets to communicate information between debugger applications and target VM. With the socket transport, the debugger application and target VM can reside either on the same machine or on different machines. 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 and when selecting a JDI connector.

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 transport uses Microsoft Windows shared memory primitives to communicate information between debugger applications and 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 and when selecting a JDI connector.

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.

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 the Solaris operating environment, 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.

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..

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 | yes | "" | Port number at which to listen for a connection..

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.

Sun VM Invocation Options

This section describes the options necessary to invoke Sun VMs for debugging. If your debugger application uses the JDI Sun Command Line Launching Connector, the appropriate options are set for you. In other cases, when the VM is invoked manually, you will need to set them.

The Java HotSpot VM requires the -Xdebug and -Xrunjdwp options.

-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.

-Xrunjdwp sub-options

The -Xrunjdwp option can be further qualified with sub-options. The sub-options are specified as follows:

    -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.
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.
stdalloc | no | "n" | By default, the JDWP reference implementation uses an alternate allocator for its memory allocation. If "y", the standard C runtime library allocator will be used. This option is mainly for testing; use it with care. Deadlocks can occur in this VM if the alternative allocator is disabled.
strict | no | "n" | If "y", assume strict JVMDI conformance. This will disable all workarounds to known bugs in JVMDI implementations. This option is mainly for testing and should be used with care.
suspend | no | "y" | If "y", VMStartEvent has a suspendPolicy of SUSPEND_ALL. If "n", VMStartEvent has a suspendPolicy of SUSPEND_NONE.

-Xrunjdwp Examples

-Xrunjdwp: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.
-Xrunjdwp: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.
-Xrunjdwp:transport=dt_socket,address=myhost:8000
Attach to a running debugger application via socket on host myhost at port 8000. Suspend this VM before main class loads.
-Xrunjdwp:transport=dt_shmem,address=mysharedmemory
Attach to a running debugger application via shared memory at transport address "mysharedmemory". Suspend this VM before main class loads.
-Xrunjdwp: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.
-Xrunjdwp: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 operating environment). The -listen option provides access to one of the listening connectors in the reference implementation (shared memory on Microsoft Windows, sockets on the Solaris operating environment). 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.

Copyright © 2001 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-debugger@sun.com

Sun


JPDA Enhancements

 Back to JPDA Guide
The version 1.4 family of the Java 2 SDK includes the following JPDA enhancements:
Full Speed Debugging
Enable "HotSwap" Class File Replacement
Instance Filters
Support For Debugging Other Languages
VMDeathRequests

Full Speed Debugging

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:
-Xrunjdwp:transport=dt_socket,server=y,onuncaught=y,launch=myDebuggerLaunchScript
For details on launch "onthrow" and launch "onuncaught", see Connection and Invocation Details . Setting a breakpoint only inhibits compilation (full speed execution) for the method containing the breakpoint. Execution reverts to the interpreter during some debug operations such as single-stepping and when method entry/exit or watchpoints are set.

As of version 1.4.1, full-speed debugging is available with both the Java HotSpot Client Vm (default) and Java HotSpot Server VM (invoked with the -server command-line flag). In the Java 2 SDK v1.4.0, full-speed debugging was available only with the Java HotSpot Client VM.

Enable "HotSwap" Class File Replacement

This new feature encapsulates the ability to substitute modified code in a running application through the debugger APIs. For example, one can recompile a single class and replace the old instance with the new instance.

This change was made to address these issues:

  • Tool (IDE) vendors want the ability to do fix-and-continue debugging. That is, while debugging, identify a problem, fix it, and continue debugging with fixed code.
  • Organizations deploying long running servers wish to be able to fix bugs without taking down the server.

HotSwap adds functionality to the JavaTM Platform Debugger Architecture (JPDA) to allow a class to be updated while under the control of a debugger. The two central components of this functionality are RedefineClasses which replaces the class definitions and PopFrame which pops frames off the stack allowing a method which has been redefined to be re-executed.

In the reference implementation, this functionality is implemented at the Java Virtual Machine Debug Interface (JVMDI) layer and made available through the higher layers of JPDA - the Java Debug Wire Protocol (JDWP) and the Java Debug Interface (JDI).

Redefinition Functionality
JDI | VirtualMachine.redefineClasses(Map classToBytes)
JDWP | RedefineClasses (Cmd 18) in VirtualMachine (CmdSet 1)
JVMDI | RedefineClasses(jint classCount, JVMDI_class_definition *classDefs)

Pop Frame Functionality
JDI | ThreadReference.popFrames(StackFrame frame)
JDWP | PopFrames (Cmd 4) in StackFrame (CmdSet 16)
JVMDI | PopFrame(jthread thread)

All functionality at each layer is independently optional. The GetCapabilities function at the JVMDI layer; the CapabilitiesNew command at the JDWP layer; and the canRedefineClasses, canAddMethod, canUnrestrictedlyRedefineClasses, and canPopFrames, methods at the JDI layer describe what functionality is implemented.

The bug report associated with this change is 4287595.

Instance Filters

BreakpointRequest, MethodExitRequest, ExceptionRequest, StepRequest, WatchpointRequest and MethodEntryRequest classes now have the capability of adding instance filters by using the addInstanceFilter method. Instance filters restrict the events generated by a request to those in which the currently executing instance is the object specified.

Support For Debugging Other Languages
The Java Platform Debugger Architecture has been extended so that non-Java programming language source, which is translated to Java programming language source, can be debugged in the future. The table below describes the new APIs and APIs with comments that have changed. This information is based on the SourceDebugExtension.

New APIs | APIs with Changed Comments
JVMDI
GetSourceDebugExtension
JDWP - ReferenceType (2) Command Set
SourceDebugExtension Command (12)
JDWP - VirtualMachine (1) Command Set
SetDefaultStratum Command (19)
JDI - VirtualMachine interface
void setDefaultStratum(String stratum)
String getDefaultStratum()
JDI - ReferenceType interface
String sourceNames(String stratum) | String sourceName()
String sourcePaths(String stratum)
List allLineLocations(String stratum, String sourceName) | List allLineLocations()
List locationsOfLine(String stratum, String sourceName, int lineNumber) | List locationsOfLine(int lineNumber)
List availableStrata()
String defaultStratum()
String sourceDebugExtension()
JDI - Method interface
List allLineLocations(String stratum, String sourceName) | List allLineLocations()
List locationsOfLine(String stratum, String sourceName, int lineNumber) | List locationsOfLine(int lineNumber)
JDI - Location interface
  class comment (strata defined)
int lineNumber(String stratum) | int lineNumber()
String sourceName(String stratum) | String sourceName()
String sourcePath(String stratum)
String sourcePath()

VMDeathRequests
Using class VMDeathRequest, a request can be made for notification when the target VM terminates. When an enabled VMDeathRequest is satisfied, an EventSet containing a VMDeathEvent will be placed on the EventQueue.

Even without creating a VMDeathRequest, a single unsolicited VMDeathEvent will be sent with a suspend policy of SUSPEND_NONE. This request would typically be created so that a VMDeathEvent with a suspend policy of SUSPEND_ALL will be sent. This event can be used to assure completion of any processing which requires the VM to be alive (e.g. event processing). Note: the unsolicited VMDeathEvent will still be sent.

Copyright © 2001 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-debugger@sun.com 		Sun


Java(tm) Platform Debugger Architecture

Java

JavaTM Platform Debugger Architecture

 Documentation Contents
The Java Platform Debugger Architecture (JPDA) consists of three interfaces designed for use by debuggers in development environments for desktop systems. The Java Virtual Machine Debugger Interface defines the services a VM must provide for debugging. The Java Debug Wire Protocol defines the format of information and requests transferred between the process being debugged and the debugger front end, which implements the Java Debug Interface. The Java Debug Interface defines information and requests at the user code level.
Enhancements in the Java 2 SDK, v1.4
  • Enhancements in the Java 2 SDK, v1.4
Design
  • JPDA Overview
    • Modularity
    • Walk-through
    • Porting
  • Architecture
    • Architecture Overview
    • Debugger Interfaces
      • JavaTM Virtual Machine Debug Interface
      • JavaTM Debugger Wire Protocol
      • JavaTM Debug Interface
Interface Reference
  • Java Virtual Machine Debug Interface (JVMDI)
    • Specification

  • Java Debug Wire Protocol (JDWP)
    • Specification

  • Java Debug Interface (JDI)
    • Specification

Implementation

  • Connection and Invocation Details

More Information

  • JPDA Home Page

Examples

The demo/jpda/examples.jar file in the SDK software contains JPDA examples, including source code for the jdb Java Debugger and the prototype javadt GUI debugger.
Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-debugger@sun.com

Sun


Java(tm) Debug Wire Protocol

Java

JavaTM Debug Wire Protocol

 JPDA

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). 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 and the Java Platform Debugger Architecture website.

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 JVMDI 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 methodID must uniquely identify the method 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.

Protocol details

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-debugger@sun.com

Sun


JPDA Overview

Java

JavaTM Platform Debugger Architecture
Overview

 Home Page
The Java Platform Debugger Architecture (JPDA) consists of two interfaces (JVMDI and JDI), a protocol (JDWP) and two software components which tie them together (back-end and front-end). 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.

JVMDI Modularity

The Java Virtual Machine Debug Interface (JVMDI) 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, JVMDI is implemented by a VM and the client is the JPDA back-end. In the reference implementation of JPDA, JVMDI 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 Java 2 SDK, Standard Edition.

Many VMs other than the Java HotSpot VM implement JVMDI. The reference implementation of the back-end has been ported to other platforms. And there are JVMDI 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 J2SE SDK, located in tools.jar) provides the debugger side.

JVMDI 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 JVMDI. In particular, let's say the requested value is an integer, the following JVMDI function call is made:

    error = jvmdi->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 JVMDI 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 JVMDI interface. In particular, it calls the event handling function passing a breakpoint event structure:

    typedef struct {
             jthread thread;
             jclass clazz;
             jmethodID method;
             jlocation location;
         } JVMDI_breakpoint_event_data;
The back-end has set the event handling function to be:
    static void eventHook(JNIEnv *env, JVMDI_Event *event) { ...
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 JVMDI implementation -- a JVMDI implementation must dig deeply into VM data structures and must set hooks into the VM implementation in order to get events. Adding JVMDI to a VM without JVMDI support is a significant undertaking. Depending on the complexity of the VM and the amount of optional JVMDI implemented, it might be a three to twelve month project. Porting a VM which has JVMDI support to a new platform is primarily the work of porting the non-JVMDI portions of the VM -- JVMDI 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 J2SE 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. Plans are to eventually add an SPI to the JDI to allow these addition. Currently, however, these require changes to the source.

Copyright © 2001 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-debugger@sun.com

Sun


Java(tm) Virtual Machine Debug Interface Reference

Java

JavaTM Virtual Machine Debug Interface Reference

Contents

Introduction
Using JVMDI Functions
Errors
Handling Events
Starting a VM with a JVMDI Client

Introduction

 The JavaTM Virtual Machine Debug Interface (JVMDI) is a programming interface used by debuggers and other programming tools. It provides a way both to inspect the state and to control the execution of applications running in the JavaTM Virtual Machine.

JVMDI is a two-way interface. The JVMDI client can be notified of interesting occurrences through events. The JVMDI can query and control the application through many different functions, either in response to events or independent of them.

JVMDI clients run in the same virtual machine as the application being debugged and access JVMDI through a native interface. The native, in-process interface allows maximal control with minimal intrusion on the part of a debugging tool. Typically, JVMDI clients are relatively compact. They can be controlled by a separate process which implements the bulk of a debugger's function without interfering with the target application's normal execution.

JVMDI is the lowest layer within the Java Platform Debugger Architecture. This architecture also contains higher-level, out-of-process debugger interfaces. The higher-level interfaces are more appropriate than JVMDI for most debugging tools. For more information on the Java Platform Debugger Architecture, see the Java Platform Debugger Architecture documentation for this release and the Java Platform Debugger Architecture website.

Using JVMDI Functions

For function and constant definitions, add

        #include <jvmdi.h>
to your source code.

Like Java Native Interface (JNI) functions, JVMDI functions are accessed through a function table. The JVMDI function table can be obtained through the JNI GetEnv function. For example, the following code obtains the function table for version 1 of the JVMDI.

        JVMDI_Interface_1 *jvmdi;
        ...
        (*jvm)->GetEnv(jvm, &jvmdi, JVMDI_VERSION_1);

JVMDI functions always return a jvmdiError value indicating return status. Some functions can return additional values through pointers provided by the calling function. In some cases, JVMDI functions allocate memory that your program must explicitly deallocate. This is indicated in the individual JVMDI function descriptions. Empty lists, arrays, sequences, etc are returned as allocated zero length arrays (not as NULL).

JVMDI functions identify objects with JNI references. References passed to JVMDI functions can be either global or local, but they must be strong references. All references returned by JVMDI functions are strong, global references.

In the event that the JVMDI function encounters an error (any return value other than JVMDI_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.

JVMDI extends the data types defined by JNI with the following: jthread and jthreadGroup are subtypes of jobject, representing the corresponding objects; jframeID is a pointer type representing a single stack frame of a suspended or current thread (it is invalid upon the resumption of the thread); jlocation is a 64 bit unsigned value, representing a monotonically increasing executable position within a method; jvmdiError is a jint, discussed above.

JVMDI functions fall into these categories:

  • Memory Management
    • Set Allocation Hooks
    • Allocate Memory
    • Deallocate Memory
  • Thread Execution Functions
    • Get Thread Status
    • 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 Current Contended Monitor
    • Run Debug Thread
  • Thread Groups
    • Get Top Thread Groups
    • Get Thread Group Info
    • Get Thread Group Children
  • Stack Frame Access
    • Get Thread's Frame Count
    • Get Thread's Current Frame
    • Pop Frame from Thread's Stack
    • Get Caller Frame
    • Frame Location
    • Notify Frame Pop
  • Local Variable Access
    • Get Local Variable
    • Set Local Variable
  • Breakpoints
    • Set a Breakpoint
    • Clear a Breakpoint
    • Clear All Breakpoints
  • Watched Fields
    • Set a Field Access Watch
    • Clear a Field Access Watch
    • Set a Field Modification Watch
    • Clear a Field Modification Watch
  • Class Information
    • Class Signature
    • Class Status
    • Source File Name
    • Class Modifier Flags
    • Class Methods
    • Class Fields
    • Implemented Interfaces
    • Is an Interface
    • Is an Array
    • Class Loader
    • Source Debug Extension
  • Object Information
    • Object Hash Code
    • Get Monitor Info
  • Field Information
    • Field Name and Signature
    • Field Declaring Class
    • Field Modifier Flags
    • Is Field Synthetic
  • Method Information
    • Method Name and Signature
    • Method Declaring Class
    • Method Modifier Flags
    • Maximum Stack
    • Local Slots
    • Argument Slots
    • Source Line Numbers
    • Method Location
    • Local Variables
    • Exception Handlers
    • Thrown Exceptions
    • Get Bytecodes
    • Is Method Native
    • Is Method Synthetic
  • Raw Monitor Support
    • Create Raw Monitor
    • Destroy Raw Monitor
    • Raw Monitor Enter
    • Raw Monitor Exit
    • Raw Monitor Wait
    • Raw Monitor Notify
    • Raw Monitor Notify All
  • Events
    • Set Event Hook
    • Enable/Disable Events
  • Miscellaneous Functions
    • Get Loaded Classes
    • Get Classloader Classes
    • Redefine Classes
    • Get Version Number
    • Get Capabilities

Memory Management

Many JVMDI functions require memory allocation. By default, memory comes from platform-specific allocation functions, such as a malloc(). A system built on JVMDI can provide its own memory allocation scheme. This might be useful, for example, to allocate memory in advance, so a debugger can continue to function in low-memory situations. Also, replacing the default memory allocation functions with debugger-specific functions can reduce the potential for deadlock on systems where malloc cannot be entered by a debugger thread while an application thread is suspended while executing inside a memory management function.

Set Allocation Hooks

jvmdiError
SetAllocationHooks(JVMDI_AllocHook ahook, JVMDI_DeallocHook dhook)

Set the functions which will perform allocation and deallocation. The hook functions are defined as follows.

typedef jvmdiError (*JVMDI_AllocHook)(jlong size, jbyte** memPtr)
typedef jvmdiError (*JVMDI_DeallocHook)(jbyte* buffer)

JVMDI will call ahook to allocate memory, dhook to deallocate memory. This overrides JVMDI's default memory allocator. To restore the default allocator, call SetAllocationHooks with ahook and dhook set to NULL.

The ahook function should look in size for the number of bytes to allocate and return them via memPtr. The function should return JVMDI_ERROR_NULL_POINTER if passed null pointers, JVMDI_ERROR_OUT_OF_MEMORY if it cannot honor a memory request, and JVMDI_ERROR_NONE otherwise.

The dhook function should look in buffer for the memory to be deallocated. The function should return JVMDI_ERROR_NULL_POINTER if passed null pointers, JVMDI_ERROR_NONE otherwise.

Parameters:

ahook
the function to use for memory allocation, or NULL to revert to the default allocator.
dhook
the function to use for memory deallocation, or NULL to revert to the default deallocator.

SetAllocationHooks always returns JVMDI_ERROR_NONE.

Allocate Memory

jvmdiError
Allocate(jlong size, jbyte** memPtr)

Allocate an area of memory through the JVMDI allocator. The allocated memory should be freed with Deallocate.

Parameters:

size
the number of bytes to allocate.
memPtr
on return, a pointer to the beginning of the memory allocated by the allocator specified in SetAllocationHooks.

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

Deallocate Memory

jvmdiError
Deallocate(jbyte* mem)
Deallocate mem using the JVMDI allocator. This function should be used to deallocate any memory allocated and returned by a JVMDI function or any memory allocated with Allocate.

Parameters:

mem
a pointer to the beginning of the allocated memory.

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

Thread Execution Functions

Get Thread Status

jvmdiError
GetThreadStatus(jthread thread, jint *threadStatusPtr, jint *suspendStatusPtr)

Get status information for a thread.

Parameters:

thread
the thread to query
threadStatusPtr
on return, points to the current status of the thread. If the thread is suspended, the returned status refers to the thread status before suspension. The thread status is one of the following values.
JVMDI_THREAD_STATUS_UNKNOWN
Status unknown.

JVMDI_THREAD_STATUS_ZOMBIE
Thread has completed execution.

JVMDI_THREAD_STATUS_RUNNING
Thread is runnable.

JVMDI_THREAD_STATUS_SLEEPING
Thread sleeping. (Thread.sleep() has been called.)

JVMDI_THREAD_STATUS_MONITOR
Thread is waiting to enter a synchronization block.

JVMDI_THREAD_STATUS_WAIT
Thread waiting. (Object.wait() has been called.)
suspendStatusPtr
on return, points to information on suspension. The suspend status is a combination of zero or more of the following bit flags.

JVMDI_SUSPEND_STATUS_SUSPENDED
Thread suspended. (java.lang.Thread.suspend() or SuspendThread or SuspendThreadList has been called.)

JVMDI_SUSPEND_STATUS_BREAK
Thread has hit a breakpoint. This bit is only valid if the thread is the current thread or the thread is suspended.
This function returns either a universal error or one of the following errors:

JVMDI_ERROR_INVALID_THREAD
thread was invalid.

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

Get All Threads

jvmdiError
GetAllThreads(jint *threadsCountPtr, jthread **threadsPtr)

Get all running threads known to the virtual machine. Native threads which are not attached to the VM are not included in the returned list.

Parameters:

threadsCountPtr
on return, points to the number of running threads.
threadsPtr
on return, points to an array of references, one for each running thread. Threads in the array are JNI global references and must be explicitly freed with the JNI function DeleteGlobalRef. The returned thread array should be freed with Deallocate.
This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

Suspend Thread

jvmdiError
SuspendThread(jthread thread)

Suspend the specified thread. If the calling thread is specified, this function will not return until some other thread calls ResumeThread or ResumeThreadList.

Parameters:

thread
the thread to suspend

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_INVALID_THREAD
thread was invalid.

JVMDI_ERROR_THREAD_SUSPENDED
Thread already suspended.

Suspend Thread List

jvmdiError
SuspendThreadList(jint reqCount, jthread *reqList, jvmdiError *results)
Suspend the reqCount threads specified in the reqList array. If the calling thread is specified in the reqList array, this function will not return until some other thread calls ResumeThread or ResumeThreadList.

Parameters:

reqCount
the number of threads to suspend
reqList
the list of threads to suspend
results
the list of per-thread suspend results

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_ILLEGAL_ARGUMENT
reqCount is less than zero (0).

Note that the function return value does not include per-thread error conditions; per-thread error conditions are returned via the results array.

The results array element for a specific thread contains either a universal error or one of the following errors:

JVMDI_ERROR_INVALID_THREAD
thread was invalid.

JVMDI_ERROR_THREAD_SUSPENDED
Thread already suspended.

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

Resume Thread

jvmdiError
ResumeThread(jthread thread)

Resume a suspended thread. Any thread suspended through java.lang.Thread.suspend(), SuspendThread or SuspendThreadList will resume execution.

Parameters:

thread
the thread to resume

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_INVALID_THREAD
thread was invalid.

JVMDI_ERROR_THREAD_NOT_SUSPENDED
Thread was not suspended.

JVMDI_ERROR_INVALID_TYPESTATE
The state of the thread has been modified, and is now inconsistent.

Resume Thread List

jvmdiError
ResumeThreadList(jint reqCount, jthread *reqList, jvmdiError *results)

Resume the reqCount threads specified in the reqList array. Any thread suspended through java.lang.Thread.suspend(), SuspendThread, or SuspendThreadList will resume execution.

Parameters:

reqCount
the number of threads to resume
reqList
the list of threads to resume
results
the list of per-thread resume results

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_ILLEGAL_ARGUMENT
reqCount is less than zero (0).

The results array element for a specific thread contains either a universal error or one of the following errors:

JVMDI_ERROR_INVALID_THREAD
thread was invalid.

JVMDI_ERROR_THREAD_NOT_SUSPENDED
Thread was not suspended.

JVMDI_ERROR_INVALID_TYPESTATE
The state of the thread has been modified, and is now inconsistent.

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

Stop Thread

jvmdiError
StopThread(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.

Parameters:

thread
the thread to stop
exception
the asynchronous exception object

The function returns one of the following error code:

JVMDI_ERROR_INVALID_THREAD

Interrupt Thread

jvmdiError
InterruptThread(jthread thread)

Interrupt the specified thread (similar to java.lang.Thread.interrupt).

Parameters:

thread
the thread to interrupt

The function returns one of the following error code:

JVMDI_ERROR_INVALID_THREAD

Get Thread Info

typedef struct {
    char *name;             /* Name in UTF-8 */
    jint priority;
    jboolean is_daemon;
    jthreadGroup thread_group;
    jobject context_class_loader;
} JVMDI_thread_info;

jvmdiError
GetThreadInfo(jthread thread, JVMDI_thread_info *infoPtr)

Get thread information. The fields of the JVMDI_thread_info structure are filled in with details of the specified thread.

Parameters:

thread
the thread to query
infoPtr
on return, filled with information describing the specified thread. Returned objects (thread group and context class loader) are global references and must be explicitly freed with the JNI function DeleteGlobalRef. The returned thread name string should be freed with Deallocate

For JDK 1.1 implementations which don't recognize context class loaders, the context_class_loader field should be NULL.

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_INVALID_THREAD
thread was invalid.

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

Get Owned Monitor Info

typedef struct {
    jint owned_monitor_count;
    jobject *owned_monitors;
} JVMDI_owned_monitor_info;

jvmdiError
GetOwnedMonitorInfo(jthread thread, JVMDI_owned_monitor_info *infoPtr)

Get information about the monitors owned by the specified thread. The fields of the JVMDI_owned_monitor_info structure are filled in with details of the owned monitors. If this function is called for a thread different than the current thread, the specified thread must be suspended.

This is an optional feature which may not be implemented for all virtual machines. Use GetCapabilities to determine whether this and other features are supported in a particular virtual machine.

Parameters:

thread
the thread to query
infoPtr
on return, filled with owned monitor information. Returned objects (array of owned monitors) are global references and must be explicitly freed with the JNI function DeleteGlobalRef. The owned_monitors buffer containing the array should be freed with Deallocate

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_INVALID_THREAD
thread was invalid.

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_THREAD_NOT_SUSPENDED
thread must be suspended before calling.

JVMDI_ERROR_NOT_IMPLEMENTED
Optional feature not present in this VM.

Get Current Contended Monitor

jvmdiError
GetCurrentContendedMonitor(jthread thread, jobject *monitorPtr)

Get the object, if any, whose monitor the specified thread is waiting to enter or waiting to regain through java.lang.Object.wait. If this function is called for a thread different than the current thread, the specified thread must be suspended.

This is an optional feature which may not be implemented for all virtual machines. Use GetCapabilities to determine whether this and other features are supported in a particular virtual machine.

Parameters:

thread
the thread to query
monitorPtr
on return, filled with the current contended monitor, or NULL if there is none. The contended monitor object is a global reference and must be explicitly freed with the JNI function DeleteGlobalRef.

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_INVALID_THREAD
thread was invalid.

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_THREAD_NOT_SUSPENDED
thread must be suspended before calling.

JVMDI_ERROR_NOT_IMPLEMENTED
Optional feature not present in this VM.

Run Debug Thread

typedef void (*JVMDI_StartFunction)(void *);
jvmdiError
RunDebugThread(jthread thread, JVMDI_StartFunction proc, void *arg, int priority);

Starts the execution of a debugger thread. with the specified native function. The start function is given the single argument, arg, and the specified priority. This function allows the creation of debugger threads for handling communication with another process or for handling events without the need to load a special subclass of java.lang.Thread or implementor of java.lang.Runnable. Instead, the created thread can completely native. 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, but it is recommended that all such calls to Java programming language code be done during debugger initialization to avoid any interaction with the application being debugged.

The new thread is started as a daemon thread.

Upon execution of proc, the new thread will be attached to the VM.

Parameters:

thread
the thread to run
proc
the start function
arg
the argument to the start function
priority
the priority of the started thread. Any thread priority allowed by java.lang.Thread.setPriority can be used including
  • JVMDI_THREAD_MIN_PRIORITY
  • JVMDI_THREAD_NORM_PRIORITY
  • JVMDI_THREAD_MAX_PRIORITY

This function returns one of the following error codes:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_INVALID_THREAD
thread was invalid.

JVMDI_ERROR_INVALID_PRIORITY

Thread Groups

Get Top Thread Groups

jvmdiError
GetTopThreadGroups(jint *groupCountPtr, jthreadGroup **groupsPtr)

Return all top-level (parentless) thread groups in the VM.

Parameters:

groupCountPtr
on return, points to the number of top-level thread groups
groupsPtr
on return, refers to a pointer to the top-level thread group array. Returned group array contains global references which must be explicitly freed with the JNI function DeleteGlobalRef. The group array array buffer should be freed with Deallocate

This function returns one of the following error codes:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

Get Thread Group Info

typedef struct {
    jthreadGroup parent;
    char *name;             /* Name in UTF-8 */
    jint  max_priority;
    jboolean is_daemon;
} JVMDI_thread_group_info;

jvmdiError
GetThreadGroupInfo(jthreadGroup group, JVMDI_thread_group_info *infoPtr)

Get information about the thread group. The fields of the JVMDI_thread_group_info structure are filled in with details of the specified thread group.

Parameters:

group
the thread group to query
infoPtr
on return, filled with information describing the specified thread group. The returned thread group parent is a global references and must be explicitly freed with the JNI function DeleteGlobalRef. The returned thread group name string should be freed with Deallocate

This function returns one of the following error codes:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_INVALID_THREAD_GROUP

Get Thread Group Children

jvmdiError
GetThreadGroupChildren(jthreadGroup group,
                 jint *threadCountPtr, jthread **threadsPtr,
                 jint *groupCountPtr, jthreadGroup **groupsPtr)
Get the threads and thread groups created within the given thread group.

Parameters:

group
the group to query.
threadCountPtr
on return, points to the number of owned threads
threadsPtr
on return, refers to a pointer to the owned thread array. Returned thread array contains global references which must be explicitly freed with the JNI function DeleteGlobalRef. The thread array buffer should be freed with Deallocate
groupCountPtr
on return, points to the number of child thread groups
groupsPtr
on return, refers to a pointer to the child thread group array. Returned group array contains global references which must be explicitly freed with the JNI function DeleteGlobalRef. The group array array buffer should be freed with Deallocate

This function returns one of the following error codes:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_INVALID_THREAD_GROUP

Stack Frame Access

Get Thread's Frame Count

jvmdiError
GetFrameCount(jthread thread, jint *countPtr)

Get the number of frames currently in the specified thread's call stack.

If this function is called for a thread different than the current thread, the specified thread must be suspended.

Parameters:

thread
The thread to query
countPtr
on return, points to the number of frames in the call stack.
This function returns either a universal error or one of the following errors:

JVMDI_ERROR_INVALID_THREAD
thread was invalid.

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_THREAD_NOT_SUSPENDED
Thread was not suspended.

Get Thread's Current Frame

jvmdiError
GetCurrentFrame(jthread thread, jframeID *framePtr)

Get the jframeID value for the current stack frame of thread and return via framePtr.

If this function is called for a thread different than the current thread, the specified thread must be suspended. The returned frame ID value remains valid only until thread continues executing. The thread must be in a Java programming language or JNI method.

Parameters:

thread
The thread to query
framePtr
on return, points to the frame ID for the current stack frame of this thread.
This function returns either a universal error or one of the following errors:

JVMDI_ERROR_INVALID_THREAD
thread was invalid.

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_THREAD_NOT_SUSPENDED
Thread was not suspended.

JVMDI_ERROR_NO_MORE_FRAMES
There are no more Java programming language or JNI frames on the call stack.

Pop Frame from Thread's Stack

jvmdiError
PopFrame(jthread thread)

Pop the topmost stack frame of thread's stack. Popping a frame takes you to the frame for the caller of the topmost stack frame.. When the thread is resumed, the thread state is reset to the state immediately before the called method was invoked: the operand stack is restored (objectref if appropriate and arguments are added back), 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

Locks acquired by a popped frame are released when it is popped. This applies to synchronized methods that are popped, and to any synchronized blocks within them.

Finally blocks are not executed.

Changes to global state are not addressed.

If this function is called for a thread different than the current thread, the specified thread must be suspended. The thread must be in a Java programming language or JNI method.

All frame IDs for this thread are invalidated.

No JVMDI events are generated by this function.

Native frames may not be popped, nor may a Java frame be popped if its caller is native code.

This is an optional feature which may not be implemented for all virtual machines. Examine can_pop_frame of GetCapabilities to determine whether this feature is supported in a particular virtual machine.

Parameters:

thread
The thread whose top frame is to be popped.
This function returns either a universal error or one of the following errors:

JVMDI_ERROR_INVALID_THREAD
thread was invalid.

JVMDI_ERROR_OPAQUE_FRAME
frame is a native frame.

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_THREAD_NOT_SUSPENDED
Thread was not suspended or current thread.

JVMDI_ERROR_NO_MORE_FRAMES
There are no more Java programming language frames on the call stack.

JVMDI_ERROR_NOT_IMPLEMENTED
This functionality is not implemented (can_pop_frame capability is false).

Get Caller Frame

jvmdiError
GetCallerFrame(jframeID called, jframeID *framePtr)
For frame, return the frame that called it via framePtr. Both called and the caller must be in a Java programming language or JNI method.

Parameters:

called
the called frame.
framePtr
on return, points to the frame ID for the calling frame.

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_INVALID_FRAMEID
Invalid jframeID.

JVMDI_ERROR_NO_MORE_FRAMES
The caller frame is not in a Java programming language or JNI method.

Frame Location

jvmdiError
GetFrameLocation(jframeID frame, jclass *classPtr, jmethodID *methodPtr,
                       jlocation *locationPtr)

For a Java programming language frame, return the location of the instruction currently executing.

Parameters:

frame
the frame to query.
classPtr
on return, points to the class for the current location. The returned class is a JNI global reference must be explicitly freed with the JNI function DeleteGlobalRef.
methodPtr
on return, points to the method for the current location.
locationPtr
on return, points to the index of the currently executing instruction.

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_INVALID_FRAMEID
frame is not a valid frame ID.

Notify Frame Pop

jvmdiError
NotifyFramePop(jframeID frame);
When frame is popped from the stack, generate a JVMDI_EVENT_FRAME_POP event. See Events.

Parameters:

frame
the frame for which the frame pop event will be generated.

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_INVALID_FRAMEID
frame is not a valid frame ID.

Local Variable Access

Get Local Variable

jvmdiError
GetLocalObject(jframeID frame, jint slot, jobject *valuePtr)
jvmdiError
GetLocalInt(jframeID frame, jint slot, jint *valuePtr)
jvmdiError
GetLocalLong(jframeID frame, jint slot, jlong *valuePtr)
jvmdiError
GetLocalFloat(jframeID frame, jint slot, jfloat *valuePtr)
jvmdiError
GetLocalDouble(jframeID frame, jint slot, jdouble *valuePtr)

These functions are used to retrieve the value of a local variable. GetLocalInt can be used to retrieve int, char, byte, and boolean values. The variable is identified by the frame containing its value and the variable's slot number. The mapping of variables to slot numbers can be obtained with the function GetLocalVariableTable.

Parameters:

frame
the frame containing the variable's value.
slot
the variable's slot number.
valuePtr
on return, points to the variable's value. For GetLocalObject, the returned value is a global reference and must be explicitly freed with the JNI function DeleteGlobalRef().

The functions return one of the following error codes:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_INVALID_FRAMEID
Invalid frame.

JVMDI_ERROR_INVALID_SLOT
Invalid slot.

JVMDI_ERROR_TYPE_MISMATCH
The variable is not an appropriate type for the function used.

JVMDI_ERROR_OPAQUE_FRAME

Set Local Variable

jvmdiError
SetLocalObject(jframeID frame, jint slot, jobject value)
jvmdiError
SetLocalInt(jframeID frame, jint slot, jint value)
jvmdiError
SetLocalLong(jframeID frame, jint slot, jlong value)
jvmdiError
SetLocalFloat(jframeID frame, jint slot, jfloat value)
jvmdiError
SetLocalDouble(jframeID frame, jint slot, jdouble value)

These functions are used to set the value of a local variable. SetLocalInt can be used to set int, char, byte, and boolean values. The variable is identified by the frame containing its value and the variable's slot number. The mapping of variables to slot numbers can be obtained with the function GetLocalVariableTable.

Parameters:

frame
the frame containing the variable's value.
slot
the variable's slot number.
value
the new value for the variable

The functions return one of the following error codes:

JVMDI_ERROR_OPAQUE_FRAME
Invalid pointer.

JVMDI_ERROR_INVALID_FRAMEID
Invalid frame.

JVMDI_ERROR_INVALID_SLOT
Invalid slot.

JVMDI_ERROR_TYPE_MISMATCH
The variable is not an appropriate type for the function used.

Breakpoints

Set a Breakpoint

jvmdiError
SetBreakpoint(jclass clazz, jmethodID method, jlocation location)

Set a breakpoint at the instruction indicated by clazz, method, and location. An instruction can only have one breakpoint.

Whenever the designated instruction is about to be executed, a JVMDI_EVENT_BREAKPOINT event is generated. See Events.

Parameters:

clazz
the class in which to set the breakpoint
method
the method in which to set the breakpoint
location
the index of the instruction at which to set the breakpoint

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_INVALID_METHODID
Invalid method.

JVMDI_ERROR_INVALID_CLASS
Invalid clazz.

JVMDI_ERROR_INVALID_LOCATION
Invalid location.

JVMDI_ERROR_DUPLICATE
The designated bytecode already has a breakpoint.

Clear a Breakpoint

jvmdiError
ClearBreakpoint(jclass clazz, jmethodID method, jlocation location)

Clear the breakpoint at the bytecode indicated by clazz, method, and location.

Parameters:

clazz
the class in which to clear the breakpoint
method
the method in which to clear the breakpoint
location
the index of the instruction at which to clear the breakpoint

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_INVALID_METHODID
Invalid method.

JVMDI_ERROR_INVALID_CLASS
Invalid clazz.

JVMDI_ERROR_INVALID_LOCATION
Invalid location.

JVMDI_ERROR_NOT_FOUND
There's no breakpoint at the designated bytecode.

Clear All Breakpoints

jvmdiError
ClearAllBreakpoints()
Clear all breakpoints in this virtual machine.

Watched Fields

Set a Field Access Watch

jvmdiError
SetFieldAccessWatch(jclass clazz, jfieldID field)

Generate a JVMDI_EVENT_FIELD_ACCESS event when the field specified by clazz and field is about to be accessed. An event will be generated for each access of the field until it is cancelled with ClearFieldAccessWatch. Field accesses from Java programming language code or from JNI are watched, fields modified by other means are not watched. Note that JVMDI 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.

This is an optional feature which may not be implemented for all virtual machines. Use GetCapabilities to determine whether this and other features are supported in a particular virtual machine.

Parameters:

clazz
the class containing the field to watch
field
the field to watch

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_INVALID_FIELDID
The jfieldID specified in field is not a valid field ID.

JVMDI_ERROR_INVALID_CLASS
The jclass specified in clazz is no a valid class.

JVMDI_ERROR_DUPLICATE
The designated field is already being watched for accesses.

JVMDI_ERROR_NOT_IMPLEMENTED
Optional feature not present in this VM.

Clear a Field Access Watch

jvmdiError
ClearFieldAccessWatch(jclass clazz, jfieldID field)

Cancel a field access watch previously set by SetFieldAccessWatch, on the field specified by clazz and field.

Parameters:

clazz
the class containing the field to watch
field
the field to watch

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_INVALID_FIELDID
The jfieldID specified in field is not a valid field ID.

JVMDI_ERROR_INVALID_CLASS
The jclass specified in clazz is no a valid class.

JVMDI_ERROR_NOT_FOUND
The designated field is not being watched for accesses.

Set a Field Modification Watch

jvmdiError
SetFieldModificationWatch(jclass clazz, jfieldID field)

Generate a JVMDI_EVENT_FIELD_MODIFICATION event when the field specified by clazz and field is about to be modified. An event will be generated for each modification of the field until it is cancelled with ClearFieldModificationWatch. Field modifications from Java programming language code or from JNI are watched, fields modified by other means are not watched. Note that JVMDI users should be aware that their own field modifications will trigger the watch. A field can only have one field modification watch set.

This is an optional feature which may not be implemented for all virtual machines. Use GetCapabilities to determine whether this and other features are supported in a particular virtual machine.

Parameters:

clazz
the class containing the field to watch
field
the field to watch

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_INVALID_FIELDID
The jfieldID specified in field is not a valid field ID.

JVMDI_ERROR_INVALID_CLASS
The jclass specified in clazz is no a valid class.

JVMDI_ERROR_DUPLICATE
The designated field is already being watched for modifications.

JVMDI_ERROR_NOT_IMPLEMENTED
Optional feature not present in this VM.

Clear a Field Modification Watch

jvmdiError
ClearFieldModificationWatch(jclass clazz, jfieldID field)

Cancel a field modification watch previously set by SetFieldModificationWatch, on the field specified by clazz and field.

Parameters:

clazz
the class containing the field to watch
field
the field to watch

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_INVALID_FIELDID
The jfieldID specified in field is not a valid field ID.

JVMDI_ERROR_INVALID_CLASS
The jclass specified in clazz is no a valid class.

JVMDI_ERROR_NOT_FOUND
The designated field is not being watched for modifications.

Class Information

Class Signature

jvmdiError
GetClassSignature(jclass clazz, char **sigPtr)
For the class indicated by clazz, return the class signature via sigPtr. The return value is a UTF-8 string.

The returned signature for primitive classes (for example, java.lang.Integer.TYPE) is the signature of the corresponding primitive type (for example, "I").

Parameters:

clazz
the class to query
sigPtr
on return, refers to a pointer to the class's signature (UTF-8). The returned signature string should be freed with Deallocate

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_INVALID_CLASS
Invalid clazz.

Class Status

jvmdiError
GetClassStatus(jclass clazz, jint *statusPtr)
Get the status of the class. Zero or more of the following bits can be set.
JVMDI_CLASS_STATUS_VERIFIED
Class bytecodes have been verified.
JVMDI_CLASS_STATUS_PREPARED
Class preparation is complete.
JVMDI_CLASS_STATUS_INITIALIZED
Class initialization is complete. Static initializer has been run.
JVMDI_CLASS_STATUS_ERROR
Error during initialization makes class unusable.

The status value for primitive classes (for example, java.lang.Integer.TYPE) and for arrays is undefined.

Parameters:

clazz
the class to query
statusPtr
on return, points to the current state of this class as one or more of flags described above.

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_INVALID_CLASS
Invalid clazz.

Source File Name

jvmdiError
GetSourceFileName(jclass clazz, char **sourceNamePtr)
For the class indicated by clazz, return the source file name via sourceNamePtr. The returned UTF-8 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 JVMDI_ERROR_ABSENT_INFORMATION.

Parameters:

clazz
the class to query
sourceNamePtr
on return, refers to a pointer to the class's source file name (UTF-8). The returned file name string should be freed with Deallocate

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_INVALID_CLASS
Invalid clazz.

JVMDI_ERROR_ABSENT_INFORMATION
Class information does not include a source path. This includes the case where the class is an array class or primitive class.

Class Modifier Flags

jvmdiError
GetClassModifiers(jclass clazz, jint *modifiersPtr)
For the class indicated by clazz, return the access flags via modifiersPtr. Access flag definitions and information about class modifiers can be found in 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.

Parameters:

clazz
the class to query
modifiersPtr
on return, points to the current access flags of this class.

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_INVALID_CLASS
Invalid clazz.

Class Methods

jvmdiError
GetClassMethods(jclass clazz, jint *methodCountPtr, jmethodID **methodsPtr)
For the class indicated by clazz, return a count of methods via methodCountPtr and a list of method IDs via methodsPtr. The method list contains constructors and static initializers as well as true methods. Only directly declared methods are returned (not inherited methods). Methods are returned in the order they occur in the class file. An empty method list is returned for array classes and primitive classes (for example, java.lang.Integer.TYPE).

Parameters:

clazz
the class to query
methodCountPtr
on return, points to the number of methods declared in this class.
methodsPtr
on return, points to the method ID array. The JVMDI allocator provides memory for the array. You must deallocate the array using Deallocate().

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_INVALID_CLASS
Invalid clazz.

JVMDI_ERROR_CLASS_NOT_PREPARED

Class Fields

jvmdiError
GetClassFields(jclass clazz, jint *fieldCountPtr, jfieldID **fieldsPtr)
For the class indicated by clazz, return a count of fields via fieldCountPtr and a list of field IDs via fieldsPtr. 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.

Parameters:

clazz
the class to query
fieldCountPtr
on return, points to the number of fields declared in this class.
fieldsPtr
on return, points to the field ID array. The JVMDI allocator provides memory for the array. You must deallocate it using Deallocate().

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_INVALID_CLASS
Invalid clazz.

JVMDI_ERROR_CLASS_NOT_PREPARED

Implemented Interfaces

jvmdiError
GetImplementedInterfaces(jclass clazz,
                       jint *interfaceCountPtr,
                       jclass **interfacesPtr);
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).

Parameters:

clazz
the class to query
interfaceCountPtr
on return, points to the number of interfaces.
interfacesPtr
on return, points to the interface array. Interfaces in the array are JNI global references and must be explicitly freed with the JNI function DeleteGlobalRef. The returned interface array should be freed with Deallocate.

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_INVALID_CLASS
Invalid clazz.

JVMDI_ERROR_CLASS_NOT_PREPARED

Is an Interface

jvmdiError
IsInterface(jclass clazz, jboolean *isInterfacePtr)
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.

Parameters:

clazz
the class to query
isInterfacePtr
on return, points to the boolean result of this function.

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_INVALID_CLASS
Invalid clazz.

Is an Array

jvmdiError
IsArrayClass(jclass clazz, jboolean *isArrayClassPtr)
Determines whether a class object reference represents an array. The jboolean result is JNI_TRUE if the class is an array, JNI_FALSE otherwise.

Parameters:

clazz
the class to query
isArrayClassPtr
on return, points to the boolean result of this function.

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_INVALID_CLASS
Invalid clazz.

Class Loader

jvmdiError
GetClassLoader(jclass clazz, jobject *classloaderPtr)
For the class indicated by clazz, return via classloaderPtr a reference to the class loader for the class. If the class was not created by a class loader, classloaderPtr points to NULL.

Parameters:

clazz
the class to query
classloaderPtr
on return, points to the class loader that loaded this class or interface, or NULL if there it has no class loader. The returned classloader is a JNI global reference and must be explicitly freed with the JNI function DeleteGlobalRef.

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_INVALID_CLASS
Invalid clazz.

Source Debug Extension

jvmdiError
GetSourceDebugExtension(jclass clazz, char **sourceDebugExtensionPtr)
For the class indicated by clazz, return the debug extension via sourceDebugExtensionPtr. The returned UTF-8 string contains exactly the debug extension information present in the class file of clazz.

Parameters:

clazz
the class to query
sourceDebugExtensionPtr
on return, refers to a pointer to the class's debug extension name (UTF-8). The returned debug extension string should be freed with Deallocate

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_INVALID_CLASS
Invalid clazz.

JVMDI_ERROR_ABSENT_INFORMATION
Class information does not include a debug extension.

Object Information

Object Hash Code

jvmdiError
GetObjectHashCode(jobject object, jint *hashCodePtr)
For the object indicated by object return via hashCodePtr a hash code that can be used in maintaining hash table of object references. This function guarantees the same hash code value for a particular object throughout its life

Parameters:

object
the object to query
hashCodePtr
on return, points to the object's hash code

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_INVALID_OBJECT
Invalid object.

Get Monitor Info

typedef struct {
    jthread owner;
    jint entry_count;
    jint waiter_count;
    jthread *waiters;
} JVMDI_monitor_info;

jvmdiError
GetMonitorInfo(jobject object, JVMDI_monitor_info *infoPtr)

Get information about the the object's monitor The fields of the JVMDI_owned_monitor_info structure are filled in with details of the monitor. Each thread that might affect the monitor state must either be suspended or must be the current thread.

This is an optional feature which may not be implemented for all virtual machines. Use GetCapabilities to determine whether this and other features are supported in a particular virtual machine.

Parameters:

object
the object to query
infoPtr
on return, filled with monitor information for the specified object. Returned objects (owner, array of waiters) are global references and must be explicitly freed with the JNI function DeleteGlobalRef. The returned waiter array buffer should be freed with Deallocate

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_INVALID_OBJECT
thread was invalid.

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_THREAD_NOT_SUSPENDED
thread must be suspended before calling.

JVMDI_ERROR_NOT_IMPLEMENTED
Optional feature not present in this VM.

Field Information

Field Name and Signature

jvmdiError
GetFieldName(jclass clazz, jfieldID field,
                   char **namePtr, char **signaturePtr)
For the field indicated by clazz and field, return the field name via namePtr and field signature via signaturePtr.

Parameters:

clazz
the class to query
field
the field to query
namePtr
on return, refers to a pointer to the UTF-8 field name. The string should be freed with Deallocate
signaturePtr
on return, refers to a pointer to the UTF-8 field signature. The string should be freed with Deallocate

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_INVALID_FIELDID
Invalid field.

JVMDI_ERROR_INVALID_CLASS
Invalid clazz.

Field Declaring Class

jvmdiError
GetFieldDeclaringClass(jclass clazz, jfieldID field, jclass *declaringClassPtr)
For the field indicated by clazz and field return the class that defined it via declaringClassPtr. The declaring class will either be clazz. a superclass, or an implemented interface.

Parameters:

clazz
the class to query
field
the field to query
declaringClassPtr
on return, points to the declaring class The returned class is a JNI global reference and must be explicitly freed with freed with the JNI function DeleteGlobalRef.

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_INVALID_FIELDID
Invalid field.

JVMDI_ERROR_INVALID_CLASS
Invalid clazz.

Field Modifier Flags

jvmdiError
GetFieldModifiers(jclass clazz, jfieldID field, jint *modifiersPtr)
For the field indicated by clazz and field return the access flags via modifiersPtr. Access flag definitions and information about field modifiers can be found in the Java virtual machine specification.

Parameters:

clazz
the class to query
field
the field to query
modifiersPtr
on return, points to the access flags.

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_INVALID_FIELDID
Invalid method.

JVMDI_ERROR_INVALID_CLASS
Invalid clazz.

Is Field Synthetic

jvmdiError
IsFieldSynthetic(jclass clazz, jfieldID field, jboolean *isSyntheticPtr)

For the field indicated by clazz and field, return a value indicating whether the field is synthetic via isSyntheticPtr Synthetic fields are generated by the compiler but not present in the original source code.

This is an optional feature which may not be implemented for all virtual machines. Use GetCapabilities to determine whether this and other features are supported in a particular virtual machine.

Parameters:

clazz
the class to query
field
the field to query
isSyntheticPtr
on return, points to the boolean result of this function.

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_INVALID_FIELDID
Invalid field.

JVMDI_ERROR_INVALID_CLASS
Invalid clazz.

JVMDI_ERROR_NOT_IMPLEMENTED
Optional feature not present in this VM.

Method Information

Method Name and Signature

jvmdiError
GetMethodName(jclass clazz, jmethodID method,
                    char **namePtr, char **signaturePtr)

For the method indicated by clazz and method, return the method name via namePtr and method signature via signaturePtr. The signature is a JNI signature also called a method descriptor in the Java Virtual Machine Specification; note this is different then method signature as defined in the Java Language Specification.

Parameters:

clazz
the class to query
method
the method to query
namePtr
on return, refers to a pointer to the UTF-8 method name. The string should be freed with Deallocate
signaturePtr
on return, refers to a pointer to the UTF-8 method signature. The string should be freed with Deallocate

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_INVALID_METHODID
Invalid method.

JVMDI_ERROR_INVALID_CLASS
Invalid clazz.

Method Declaring Class

jvmdiError
GetMethodDeclaringClass(jclass clazz, jmethodID method,
                                 jclass *declaringClassPtr)
For the method indicated by clazz and method, return the Class that defined it via declaringClassPtr.

Parameters:

clazz
the class to query
method
the method to query
declaringClassPtr
on return, points to the declaring class The returned class is a JNI global reference and must be explicitly freed with freed with the JNI function DeleteGlobalRef.

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_INVALID_METHODID
Invalid method.

JVMDI_ERROR_INVALID_CLASS
Invalid clazz.

Method Modifier Flags

jvmdiError
GetMethodModifiers(jclass clazz, jmethodID method,
                         jint *modifiersPtr)
For the method indicated by clazz and method return the access flags via modifiersPtr. Access flag definitions and information about method modifiers can be found in the Java virtual machine specification.

Parameters:

clazz
the class to query
method
the method to query
modifiersPtr
on return, points to the access flags.

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_INVALID_METHODID
Invalid method.

JVMDI_ERROR_INVALID_CLASS
Invalid clazz.

Maximum Stack

jvmdiError
GetMaxStack(jclass clazz, jmethodID method, jint *maxPtr)
For the method indicated by clazz and method, return via maxPtr the maximum number of words that can be on the stack while the method is executing.

Parameters:

clazz
the class to query
method
the method to query
maxPtr
on return, points to the maximum number of stack words

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_INVALID_METHODID
Invalid method.

JVMDI_ERROR_INVALID_CLASS
Invalid clazz.

Locals Slots

jvmdiError
GetMaxLocals(jclass clazz, jmethodID method,
                  jint *maxPtr);
For the method indicated by clazz and method, return via maxPtr the number of local variable slots used by the whole method. Note that two-word arguments use two slots.

Parameters:

clazz
the class to query
method
the method to query
maxPtr
on return, points to the maximum number of local slots

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_INVALID_METHODID
Invalid method.

JVMDI_ERROR_INVALID_CLASS
Invalid clazz.

Argument Slots

jvmdiError
GetArgumentsSize(jclass clazz, jmethodID method, jint *sizePtr)
For the method indicated by clazz and method, return via maxPtr the number of local variable slots used by the method's arguments. Note that two-word arguments use two slots.

Parameters:

clazz
the class to query
method
the method to query
sizePtr
on return, points to the number of argument slots

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_INVALID_METHODID
Invalid method.

JVMDI_ERROR_INVALID_CLASS
Invalid clazz.

Source Line Numbers

jvmdiError
GetLineNumberTable(jclass clazz, jmethodID method,
              jint *entryCountPtr,
             JVMDI_line_number_entry **tablePtr)
For the method indicated by clazz and method, return a table of source line number entries. The size of the table is returned via entryCountPtr and the table itself is returned via tablePtr. A table entry is an instance of the following structure:
typedef struct {
    jlocation start_location;
    jint line_number;
} JVMDI_line_number_entry;

Parameters:

clazz
the class to query
method
the method to query
entryCountPtr
on return, points to the number of entries in the table
tablePtr
on return, points to the line number table pointer. The JVMDI allocator provides space for the table. You must deallocate the table using Deallocate().

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NONE
No error.

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_INVALID_METHODID
Invalid method.

JVMDI_ERROR_INVALID_CLASS
Invalid clazz.

JVMDI_ERROR_ABSENT_INFORMATION
Class information does not include line numbers.

Method Location

jvmdiError
GetMethodLocation(jclass clazz, jmethodID method,
                        jlocation *startLocationPtr,
                        jlocation *endLocationPtr)
For the method indicated by clazz and method, return the beginning and ending addresses through startLocationPtr and endLocationPtr. In a conventional byte code indexing scheme, these values are always zero and the byte code count minus one.

Parameters:

clazz
the class to query
method
the method to query
startLocationPtr
on return, points to the first location, or -1 if location information is not available.
endLocationPtr
on return, points to the last location, or -1 if location information is not available.

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_INVALID_METHODID
Invalid method.

JVMDI_ERROR_INVALID_CLASS
Invalid clazz.

JVMDI_ERROR_ABSENT_INFORMATION
Class information does not include method sizes.

Local Variables

jvmdiError
GetLocalVariableTable(jclass clazz, jmethodID method,
                            jint *entryCountPtr,
                            JVMDI_local_variable_entry **tablePtr)
For the method indicated by clazz and method, return a table of local variables. The size of the table is returned via entryCountPtr and the table itself is returned via tablePtr. A table entry has this structure:
typedef struct {
    jlocation start_location;   /* variable valid start_location */
    jint length;                /* up to start_location+length */
    char *name;                 /* name in UTF-8 */
    char *signature;            /* type signature in UTF-8 */
    jint slot;                  /* variable slot, see JVMDI_GetLocal*()  */
} JVMDI_local_variable_entry;

Parameters:

clazz
the class to query
method
the method to query
entryCountPtr
on return, points to the number of entries in the table
tablePtr
on return, points to the local variable table pointer. The JVMDI allocator provides space for the table. In addition, each name and signature string in the table is allocated with the JVMDI allocator. You must deallocate these buffers using Deallocate.

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_INVALID_METHODID
Invalid method.

JVMDI_ERROR_INVALID_CLASS
Invalid clazz.

JVMDI_ERROR_ABSENT_INFORMATION
Class information does not include local variable information.

Exception Handlers

jvmdiError
GetExceptionHandlerTable(jclass clazz, jmethodID method,
                               jint *entryCountPtr,
                               JVMDI_exception_handler_entry **tablePtr)
For the method indicated by clazz and method, return a table of exception handlers. The size of the table is returned via entryCountPtr and the table itself is returned via tablePtr. A table entry has this structure:
typedef struct {
    jlocation start_location;
    jlocation end_location;
    jlocation handler_location;
    jclass exception;           /* if null, all exceptions */
} JVMDI_exception_handler_entry;

A call to this function may trigger class loading for the thrown exception classes that have not yet been loaded. It should not be called while threads are suspended.

Parameters:

clazz
the class to query
method
the method to query
entryCountPtr
on return, points to the number of entries in the table
tablePtr
on return, points to the exception handler table pointer. The JVMDI allocator provides space for the table. You must deallocate the table using Deallocate(). The classes returned in the "exception" field of JVMDI_exception_handler_entry are global references and must be explicitly freed with the JNI function Deallocate

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_INVALID_METHODID
Invalid method.

JVMDI_ERROR_INVALID_CLASS
Invalid clazz.

Thrown Exceptions

jvmdiError
GetThrownExceptions(jclass clazz, jmethodID method,
                          jint *exceptionCountPtr, jclass **exceptionsPtr)
For the method indicated by clazz and method, return an array of exception classes the method might throw. The number of exceptions is returned via exceptionCountPtr. The exceptions array is returned via exceptionsPtr.

A call to this function may trigger class loading for the thrown exception classes that have not yet been loaded. It should not be called while threads are suspended.

Parameters:

clazz
the class to query
method
the method to query
exceptionCountPtr
on return, points to the number of running threads.
exceptionsPtr
on return, points to an array of references, one for each thrown exception. Exception classes in the array are JNI global references and must be explicitly freed with the JNI function DeleteGlobalRef. The returned exception array should be freed with Deallocate.

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_INVALID_METHODID
Invalid method.

JVMDI_ERROR_INVALID_CLASS
Invalid class.

Get Bytecodes

jvmdiError
GetBytecodes(jclass clazz, jmethodID method, jint *bytecodeCountPtr,
                         jbyte **bytecodesPtr)
For the method indicated by clazz and method, return the byte codes that implement the method. The number of bytecodes is returned via bytecodeCountPtr. The byte codes themselves are returned via bytecodesPtr.

This is an optional feature which may not be implemented for all virtual machines. Use GetCapabilities to determine whether this and other features are supported in a particular virtual machine.

Parameters:

clazz
the class to query
method
the method to query
bytecodeCountPtr
on return, points to the length of the byte code array
bytecodesPtr
on return, points to the pointer to the byte code array The JVMDI memory allocator provides memory for the byte code array. You must deallocate the table using Deallocate().

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_INVALID_CLASS
Invalid clazz.

JVMDI_ERROR_INVALID_METHODID
Invalid method.

JVMDI_ERROR_NOT_IMPLEMENTED
Optional feature not present in this VM.

Is Method Native

jvmdiError
IsMethodNative(jclass clazz, jmethodID method, jboolean *isNativePtr)

For the method indicated by clazz and method, return a value indicating whether the method is native via isNativePtr

Parameters:

clazz
the class to query
method
the method to query
isNativePtr
on return, points to the boolean result of this function.

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_INVALID_METHODID
Invalid method.

JVMDI_ERROR_INVALID_CLASS
Invalid clazz.

Is Method Synthetic

jvmdiError
IsMethodSynthetic(jclass clazz, jmethodID method, jboolean *isSyntheticPtr)

For the method indicated by clazz and method, return a value indicating whether the method is synthetic via isSyntheticPtr. Synthetic methods are generated by the compiler but not present in the original source code.

This is an optional feature which may not be implemented for all virtual machines. Use GetCapabilities to determine whether this and other features are supported in a particular virtual machine.

Parameters:

clazz
the class to query
method
the method to query
isSyntheticPtr
on return, points to the boolean result of this function.

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

JVMDI_ERROR_INVALID_METHODID
Invalid method.

JVMDI_ERROR_INVALID_CLASS
Invalid clazz.

JVMDI_ERROR_NOT_IMPLEMENTED
Optional feature not present in this VM.

Raw Monitor Support

Create Raw Monitor

jvmdiError
CreateRawMonitor(char *name, JVMDI_RawMonitor *monitorPtr)
Create a raw monitor.

Parameters:

name
a name in UTF-8 to identify the monitor
monitorPtr
on return, points to the created monitor.

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

Destroy Raw Monitor

jvmdiError
DestroyRawMonitor(JVMDI_RawMonitor monitor)
Destroy the raw monitor.

Parameters:

monitor
the monitor

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_INVALID_MONITOR
Invalid monitor.

Raw Monitor Enter

jvmdiError
RawMonitorEnter(JVMDI_RawMonitor monitor)
Gain exclusive ownership of a raw monitor.

Parameters:

monitor
the monitor

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_INVALID_MONITOR
Invalid monitor.

Raw Monitor Exit

jvmdiError
RawMonitorExit(JVMDI_RawMonitor monitor)
Release exclusive ownership of a raw monitor.

Parameters:

monitor
the monitor

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_INVALID_MONITOR
Invalid monitor.

JVMDI_ERROR_NOT_MONITOR_OWNER

Raw Monitor Wait

jvmdiError
RawMonitorWait(JVMDI_RawMonitor monitor, jlong millis)
Wait for notification of the raw monitor.

Parameters:

monitor
the monitor
millis
the timeout, in milliseconds

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_INVALID_MONITOR
Invalid monitor.

JVMDI_ERROR_NOT_MONITOR_OWNER

JVMDI_ERROR_INTERRUPT

Raw Monitor Notify

jvmdiError
RawMonitorNotify(JVMDI_RawMonitor monitor)
Notify a single thread waiting on the raw monitor.

Parameters:

monitor
the monitor

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_INVALID_MONITOR
Invalid monitor.

JVMDI_ERROR_NOT_MONITOR_OWNER

Raw Monitor Notify All

jvmdiError
RawMonitorNotifyAll(JVMDI_RawMonitor monitor)
Notify all threads waiting on the raw monitor.

Parameters:

monitor
the monitor

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_INVALID_MONITOR
Invalid monitor.

JVMDI_ERROR_NOT_MONITOR_OWNER

Events

Set Event Hook

typedef void (*JVMDI_EventHook)(JNIEnv *env , JVMDI_Event *event);

jvmdiError
SetEventHook(JVMDI_EventHook hook)
Set the function to be called on every event. Details on events are described later in this document.

Parameters:

hook
the new event hook, or NULL to remove the existing hook.

This function returns a universal error on error.

Enable/Disable Events

jvmdiError
SetEventNotificationMode(jint mode, jint eventType, jthread thread, ...)
Control the generation of events. If mode is JVMDI_ENABLE, the event eventType is enabled; if mode is JVMDI_DISABLE, the event is 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.

Global and per-thread enabling of events is independent. For example, if MethodEntry is initially disabled both globally and on each thread, MethodEntry is still disabled per-thread when it is enabled globally. When an executing thread encounters a potential event condition, an event will be sent if either that event is globally enabled OR that event is enabled for the executing thread. Thus globally enabling an event applies to threads created after the call as well.

See below for information on specific events.

The following events cannot be controlled (enabled or disabled) at the thread level through this function.

  • JVMDI_EVENT_VM_INIT
  • JVMDI_EVENT_VM_DEATH
  • JVMDI_EVENT_THREAD_START
  • JVMDI_EVENT_CLASS_UNLOAD

The following event cannot be controlled (enabled or disabled) at the global level through this function.

  • JVMDI_EVENT_SINGLE_STEP

Initially, no events are enabled at the thread level. All events except the following are enabled at the global level.

  • JVMDI_EVENT_SINGLE_STEP
  • JVMDI_EVENT_EXCEPTION_CATCH
  • JVMDI_EVENT_METHOD_ENTRY
  • JVMDI_EVENT_METHOD_EXIT
Set the function to be called on every event. Details on events are described later in this document.

Parameters:

mode
JVMDI_ENABLE or JVMDI_DISABLE
eventType
the event to control
thread
the thread to control, or NULL for all threads

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_INVALID_THREAD
If thread is invalid or the thread has not run.

JVMDI_ERROR_INVALID_EVENT_TYPE
If eventType is invalid value.

JVMDI_ERROR_ILLEGAL_ARGUMENT
If thread argument is specified with one of the following events:
  • JVMDI_EVENT_VM_INIT
  • JVMDI_EVENT_VM_DEATH
  • JVMDI_EVENT_THREAD_START
  • JVMDI_EVENT_CLASS_UNLOAD

Miscellaneous Functions

Get Loaded Classes

jvmdiError
GetLoadedClasses(jint *classCountPtr, jclass **classesPtr)

Return an array of all classes loaded in the virtual machine. The number of classes in the array is returned via classCountPtr, and the array itself via classesPtr. You must deallocate the array using Deallocate().

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.

Parameters:

classCountPtr
on return, points to the number of classes.
classesPtr
on return, points to an array of references, one for each class. Classes in the array are JNI global references and must be explicitly freed with the JNI function DeleteGlobalRef. The returned class array should be freed with Deallocate.

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

Get Classloader Classes

jvmdiError
GetClassLoaderClasses(jobject initiatingLoader, jint *classCountPtr, jclass **classesPtr)

Returns an array of all classes for which this class loader has been recorded as the 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.

For JDK 1.1 implementations which don't recognize the distinction between initiating and defining classloaders, this function should return all classes loaded in the virtual machine. The number of classes in the array is returned via classCountPtr, and the array itself via classesPtr. You must deallocate the array using Deallocate().

The initiatingLoader argument must not be null. The set of classes initiated by the system class loader is identical to the set of classes defined by that loader. This set can be determined by calling GetLoadedClasses and selecting those classes with a null class loader.

Parameters:

initiatingLoader
the initiating class loader.
classCountPtr
on return, points to the number of classes.
classesPtr
on return, points to an array of references, one for each class. Classes in the array are JNI global references and must be explicitly freed with the JNI function DeleteGlobalRef. The returned class array should be freed with Deallocate.

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

Redefine Classes

typedef struct {
    jclass clazz;              /* Class to be redefined */
    jint class_byte_count;     /* number of bytes defining class (below) */
    jbyte *class_bytes;        /* bytes defining class */
                               /* (in Class File Format of JVM spec) */
} JVMDI_class_definition;

jvmdiError
RedefineClasses(jint classCount, JVMDI_class_definition *classDefs)

All classes given are redefined according to the definitions supplied. If any redefined methods have active stack frames, those active frames continue to run the bytecodes of the original method. The redefined methods will be used on new invokes. Any JVMDI function or event which returns a jmethodID, will return OBSOLETE_METHOD_ID when referring to the original method (for example, when examining a stack frame where the original method is still executing) unless it is equivalent to the redefined method (see below). The original method ID refers to the redefined method. Care should be taken thoughout a JVMDI client to handle OBSOLETE_METHOD_ID. If reseting of stack frames is desired, use PopFrame to pop frames with OBSOLETE_METHOD_IDs.

An original and a redefined method should be considered equivalent if:

  • their bytecodes are the same except for indicies into the constant pool and
  • the referenced constants are equal.

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 preexisting static variables will remain as they were prior to the call. However, completely uninitialized (new) static variables will be assigned their default value.

If a redefined class has instances then all those instances will have the fields defined by the redefined class at the completion of the call. Preexisting fields will retain their previous values. Any new fields will have their default values; no instance initializers or constructors are run.

Threads need not be suspended.

All breakpoints in the class are cleared.

All attributes are updated.

No JVMDI events are generated by this function.

This is an optional feature which may not be implemented for all virtual machines. Examine can_redefine_classes, can_add_method and can_unrestrictedly_redefine_classes of GetCapabilities to determine whether this feature is supported in a particular virtual machine.

Parameters:

classCount
the number of classes specified in classDefs
classDefs
the array of new class definitions
This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer: classDefs or one of class_bytes is NULL.

JVMDI_ERROR_INVALID_CLASS
An element of classDefs is not a valid class.

JVMDI_ERROR_UNSUPPORTED_VERSION
A new class file has a version number not supported by this VM.

JVMDI_ERROR_INVALID_CLASS_FORMAT
A new class file is malformed (The VM would return a ClassFormatError).

JVMDI_ERROR_CIRCULAR_CLASS_DEFINITION
The new class file definitions would lead to a circular definition (the VM would return a ClassCircularityError).

JVMDI_ERROR_FAILS_VERIFICATION
The class bytes fail verification.

JVMDI_ERROR_NAMES_DONT_MATCH
The class name defined in the new class file is different from the name in the old class object.

JVMDI_ERROR_NOT_IMPLEMENTED
No aspect of this functionality is implemented (can_redefine_classes capability is false).

JVMDI_ERROR_ADD_METHOD_NOT_IMPLEMENTED
A new class file would require adding a method, (and can_add_method capability is false).

JVMDI_ERROR_SCHEMA_CHANGE_NOT_IMPLEMENTED
The new class version changes fields (and can_unrestrictedly_redefine_classes is false).

JVMDI_ERROR_HIERARCHY_CHANGE_NOT_IMPLEMENTED
A direct superclass is different for the new class version, or the set of directly implemented interfaces is different (and can_unrestrictedly_redefine_classes is false).

JVMDI_ERROR_DELETE_METHOD_NOT_IMPLEMENTED
The new class version does not declare a method declared in the old class version. (and can_unrestrictedly_redefine_classes is false).

JVMDI_ERROR_CLASS_MODIFIERS_CHANGE_NOT_IMPLEMENTED
The new version of a class has different class modifiers (public, abstract, final, ...) then the old version (and can_unrestrictedly_redefine_classes is false).

JVMDI_ERROR_METHOD_MODIFIERS_CHANGE_NOT_IMPLEMENTED
The new version of a class has a different method modifier (public, abstract, synchronized, ...) then the old version (and can_unrestrictedly_redefine_classes is false).

Get Version Number

jvmdiError
GetVersionNumber(jint *versionPtr)
Return the JVMDI version via versionPtr The return value is the version identifier. The low-order 16 bits represent the minor version number. The next 12 bits represent the major version number. The high-order 4 bits are undefined.

Parameters:

versionPtr
on return, points to the JVMDI version.

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

Get Capabilities

typedef struct {
    unsigned int can_watch_field_modification        : 1;
    unsigned int can_watch_field_access              : 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 reserved1                           : 1;
    unsigned int reserved2                           : 1;
    unsigned int reserved3                           : 1;
    unsigned int can_pop_frame                       : 1;
    unsigned int reserved4                           : 1;
    unsigned int can_redefine_classes                : 1;
    unsigned int can_add_method                      : 1;
    unsigned int can_unrestrictedly_redefine_classes : 1;
    unsigned int reserved5                           : 1;
} JVMDI_capabilities;

jvmdiError
GetCapabilities(JVMDI_capabilities *capabilitiesPtr)
Return via capabilitiesPtr the optional JVMDI features supported by this implementation. The capabilities structure contains a number of boolean flags indicating whether the named feature is supported.

Parameters:

capabilitiesPtr
on return, points to the JVMDI capabilities.

This function returns either a universal error or one of the following errors:

JVMDI_ERROR_NULL_POINTER
Invalid pointer.

Errors

Every JVMDI function returns a jvmdiError error code.

Universal Errors

The following errors may be returned by any JVMDI function (and are thus not listed in the function descriptions):

JVMDI_ERROR_NONE
No error has occurred. This is the error code that is returned on successful completion of the function.

JVMDI_ERROR_OUT_OF_MEMORY
The function needed to allocate memory and no more memory was available for allocation.

JVMDI_ERROR_ACCESS_DENIED
Debugging has not been enabled in this virtual machine. JVMDI cannot be used.

JVMDI_ERROR_UNATTACHED_THREAD
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.

JVMDI_ERROR_VM_DEAD
The virtual machine is not running.

JVMDI_ERROR_INTERNAL
An unexpected internal error has occurred.

Function Specific Errors

The following errors are returned by some JVMDI functions (and are listed in the function descriptions):

JVMDI_ERROR_INVALID_THREAD
passed thread is NULL, is not a valid thread or has exited

JVMDI_ERROR_INVALID_FIELDID
invalid field

JVMDI_ERROR_INVALID_METHODID
invalid method

JVMDI_ERROR_INVALID_LOCATION
invalid location

JVMDI_ERROR_INVALID_FRAMEID
invalid jframeID

JVMDI_ERROR_NO_MORE_FRAMES
There are no more Java programming language or JNI frames on the call stack.

JVMDI_ERROR_OPAQUE_FRAME
information about the frame is not available (e.g. for native frames)

JVMDI_ERROR_NOT_CURRENT_FRAME
operation can only be performed on current frame

JVMDI_ERROR_TYPE_MISMATCH
the variable is not an appropriate type for the function used

JVMDI_ERROR_INVALID_SLOT
invalid slot

JVMDI_ERROR_DUPLICATE
item already set

JVMDI_ERROR_THREAD_NOT_SUSPENDED
thread was not suspended

JVMDI_ERROR_THREAD_SUSPENDED
thread already suspended

JVMDI_ERROR_INVALID_OBJECT
invalid object

JVMDI_ERROR_INVALID_CLASS
invalid class

JVMDI_ERROR_CLASS_NOT_PREPARED
class has been loaded but not yet prepared

JVMDI_ERROR_NULL_POINTER
invalid pointer

JVMDI_ERROR_ABSENT_INFORMATION
The requested information is not available.

JVMDI_ERROR_INVALID_EVENT_TYPE
The specified event type id is not recognized.

JVMDI_ERROR_NOT_IMPLEMENTED
The functionality is not implemented in this virtual machine

JVMDI_ERROR_INVALID_THREAD_GROUP
thread group invalid

JVMDI_ERROR_INVALID_PRIORITY
invalid priority

JVMDI_ERROR_NOT_FOUND
Desired element (e.g. field or breakpoint) not found

JVMDI_ERROR_INVALID_MONITOR
invalid monitor

JVMDI_ERROR_ILLEGAL_ARGUMENT
illegal argument

JVMDI_ERROR_NOT_MONITOR_OWNER
This thread doesn't own the monitor.

JVMDI_ERROR_ABSENT_INFORMATION
Desired information is not available.

JVMDI_ERROR_INTERRUPT
The call has been interrupted before completion.

JVMDI_ERROR_INVALID_TYPESTATE
The state of the thread has been modified, and is now inconsistent.

JVMDI_ERROR_UNSUPPORTED_VERSION
A new class file has a version number not supported by this VM.

JVMDI_ERROR_INVALID_CLASS_FORMAT
A new class file is malformed (The VM would return a ClassFormatError).

JVMDI_ERROR_CIRCULAR_CLASS_DEFINITION
The new class file definitions would lead to a circular definition (the VM would return a ClassCircularityError).

JVMDI_ERROR_ADD_METHOD_NOT_IMPLEMENTED
A new class file would require adding a method, and can_add_method is false.

JVMDI_ERROR_SCHEMA_CHANGE_NOT_IMPLEMENTED
A new class file would require a schema change, and can_unrestrictedly_redefine_classes is false.

JVMDI_ERROR_FAILS_VERIFICATION
The class bytes fail verification.

JVMDI_ERROR_HIERARCHY_CHANGE_NOT_IMPLEMENTED
A direct superclass is different for the new class version, or the set of directly implemented interfaces is different and can_unrestrictedly_redefine_classes is false.

JVMDI_ERROR_DELETE_METHOD_NOT_IMPLEMENTED
The new class version does not declare a method declared in the old class version and can_unrestrictedly_redefine_classes is false.

JVMDI_ERROR_NAMES_DONT_MATCH
The class name defined in the new class file is different from the name in the old class object.

JVMDI_ERROR_CLASS_MODIFIERS_CHANGE_NOT_IMPLEMENTED
The new version of a class has different class modifiers (public, abstract, final, ...) then the old version (and can_unrestrictedly_redefine_classes is false).

JVMDI_ERROR_METHOD_MODIFIERS_CHANGE_NOT_IMPLEMENTED
The new version of a class has a different method modifier (public, abstract, synchronized, ...) then the old version (and can_unrestrictedly_redefine_classes is false).

Handling Events
  • Introduction
  • Single Step Event
    • JVMDI_EVENT_SINGLE_STEP
  • Breakpoint Event
    • JVMDI_EVENT_BREAKPOINT
  • Field Events
    • JVMDI_EVENT_FIELD_ACCESS
    • JVMDI_EVENT_FIELD_MODIFICATION
  • Frame Events
    • JVMDI_EVENT_FRAME_POP
    • JVMDI_EVENT_METHOD_ENTRY
    • JVMDI_EVENT_METHOD_EXIT
  • Exception Event
    • JVMDI_EVENT_EXCEPTION
  • Exception Catch Event
    • JVMDI_EVENT_EXCEPTION_CATCH
  • User Defined Event
    • JVMDI_EVENT_USER_DEFINED
  • Thread Events
    • JVMDI_EVENT_THREAD_END
    • JVMDI_EVENT_THREAD_START
  • Class Events
    • JVMDI_EVENT_CLASS_LOAD
    • JVMDI_EVENT_CLASS_UNLOAD
    • JVMDI_EVENT_CLASS_PREPARE
  • VM Initialization Event
    • JVMDI_EVENT_VM_INIT
  • VM Death Event
    • JVMDI_EVENT_VM_DEATH

JVMDI clients can be informed of many events that occur in application programs.

To handle Events, designate a hook function with SetEventHook. For each event the hook function will be called with a JVMDI_Event argument describing the event type and, depending on the event, additional information. The hook function is usually called from within application threads and the JVMDI implementation does not queue events in any way. This means that event hook 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 hook can overwrite any current pending exception in the current application thread. Care must be taken to preserve a pending exception when an event hook makes a JNI call that might generate an exception.
  • Event hook functions must be re-entrant. The JVMDI implementation does not queue events. If a JVMDI client needs to process events one at a time, it can use a raw monitor inside the event hook function to serialize event processing.

Some JVMDI events identify objects with JNI references. All such references are passed to the event hook function via the JVMDI_Event argument. All references in JVMDI events are JNI local references and will become invalid after the event hook returns. The JVMDI_Event data structure is allocated locally and deallocated when the event hook function returns.

Events can be enabled and disabled with the function SetEventNotificationMode. Some events are enabled at application startup; others are not. Refer to the documentation for this function for details.

A thread that generates an event does not change its execution status. If an event should cause a thread to be suspended, then the event hook function is responsible for explicitly suspending the thread with SuspendThread.

The JVMDI_Event contains the event kind and a union of event-specific structures containing more information.

typedef struct {
    jint kind;		/* the discriminant */

    union {
    /* kind = JVMDI_EVENT_SINGLE_STEP */
        JVMDI_single_step_event_data single_step;

        /* kind = JVMDI_EVENT_BREAKPOINT */
        JVMDI_breakpoint_event_data breakpoint;

        /* kind = JVMDI_EVENT_FRAME_POP */
        /* kind = JVMDI_EVENT_METHOD_ENTRY */
        /* kind = JVMDI_EVENT_METHOD_EXIT */
        JVMDI_frame_event_data frame;

        /* kind = JVMDI_EVENT_FIELD_ACCESS */
        JVMDI_field_access_event_data field_access;

        /* kind = JVMDI_EVENT_FIELD_MODIFICATION */
        JVMDI_field_modification_event_data field_modification;

        /* kind = JVMDI_EVENT_EXCEPTION */
        JVMDI_exception_event_data exception;

        /* kind = JVMDI_EVENT_EXCEPTION_CATCH */
        JVMDI_exception_catch_event_data exception_catch;

        /* kind = JVMDI_EVENT_USER_DEFINED */
        JVMDI_user_event_data user;

        /* kind = JVMDI_EVENT_THREAD_END or */
        /* JVMDI_EVENT_THREAD_START */
        JVMDI_thread_change_event_data thread_change;

        /* kind = JVMDI_EVENT_CLASS_LOAD, */
        /* JVMDI_EVENT_CLASS_UNLOAD, or */
        /* JVMDI_EVENT_CLASS_PREPARE */
        JVMDI_class_event_data class_event;

        /* kind = JVMDI_EVENT_VM_DEATH, JVMDI_EVENT_VM_INIT */
        /* no additional fields */
    } u;
} JVMDI_Event;

More information on specific events is given in the sections below.

Single Step Events (JVMDI_EVENT_SINGLE_STEP)

    typedef struct {
        jthread thread;
        jclass clazz;
        jmethodID method;
        jlocation location;
    } JVMDI_single_step_event_data;

Single step events allow the JVMDI client 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 the VM Specification; however, some implementations may define location differently. In any case the clazz, method, and location fields of the event structure 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.

Single step events are disabled by default and can be enabled for a thread by calling SetEventNotificationMode

Breakpoint Events (JVMDI_EVENT_BREAKPOINT)

    typedef struct {
        jthread thread;
        jclass clazz;
        jmethodID method;
        jlocation location;
    } JVMDI_breakpoint_event_data;

Breakpoint Events are generated whenever a thread reaches a location designated as a breakpoint with SetBreakpoint. The clazz, method, and location fields of the event structure uniquely identify the current location and allow the mapping to source file and line number when that information is available.

Breakpoint reporting, in general, can be enabled or disabled by calling SetEventNotificationMode and are enabled by default. If they are disabled, set breakpoints are ignored.

Field Events (JVMDI_EVENT_FIELD_ACCESS, JVMDI_EVENT_FIELD_MODIFICATION)

    /* kind = JVMDI_EVENT_FIELD_ACCESS */
    typedef struct {
        jthread thread;
        jclass clazz;
        jmethodID method;
        jlocation location;
        jclass field_clazz;
        jobject object;
        jfieldID field;
    } JVMDI_field_access_event_data;

    /* kind = JVMDI_EVENT_FIELD_MODIFICATION */
    typedef struct {
        jthread thread;
        jclass clazz;
        jmethodID method;
        jlocation location;
        jclass field_clazz;
        jobject object;
        jfieldID field;
        char signature_type;
        jvalue new_value;
    } JVMDI_field_modification_event_data;

Field Events are generated whenever a thread accesses or modifies a field designated as a watchpoint with SetFieldAccessWatch or with SetFieldModificationWatch. The clazz, method, and location fields of the event structures uniquely identify the current location and allow the mapping to source file and line number when that information is available. The field_clazz and field fields uniquely identify the field which is being accessed or modified. The object identifies the containing object if the field is an instance field. It is NULL otherwise.

Field watchpoint reporting, in general, can be enabled or disabled by calling SetEventNotificationMode and are enabled by default. If they are disabled, set watches are ignored.

Frame Events (JVMDI_EVENT_FRAME_POP, JVMDI_EVENT_METHOD_ENTRY, JVMDI_EVENT_METHOD_EXIT)

    typedef struct {
        jthread thread;
        jclass clazz;
        jmethodID method;
        jframeID frame;
    } JVMDI_frame_event_data;

Method entry events are generated upon entry of Java programming language or native methods. Method exit events are generated upon exit from a Java programming language or native methods. Frame pop events are generated upon exit from a single method in a single frame as specified in a call to NotifyFramePop. If a method terminates by throwing an exception to its caller, neither a method exit event nor a frame pop event will be generated. JVMDI clients can check for this occurrence by monitoring exception catch events

The clazz and method fields uniquely identify the method being entered or exited. The frame field provides access to the stack frame for the method. On method entry, the location reported by GetFrameLocation identifies the initial executable location in the method. On method exit or frame pop, the location reported by GetFrameLocation identifies the executable location in the returning method, immediately prior to the return.

Method entry and exit are disabled by default and can be enabled by calling SetEventNotificationMode. Frame pop events are enabled by default and can be disabled similarly.

Exception Events (JVMDI_EVENT_EXCEPTION)

    typedef struct {
        jthread thread;
        jclass clazz;
        jmethodID method;
        jlocation location;
        jobject exception;
        jclass catch_clazz;
        jmethodID catch_method;
        jlocation catch_location;
    } JVMDI_exception_event_data;

Exception events are generated whenever an exception is first detected in a Java programming language method. 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 clazz, method, and location fields of the event structure 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_clazz, catch_method, and catch_location identify the location of the catch clause, if any, that handles 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. JVMDI clients can check for this occurrence by monitoring exception catch events

Exception events are enabled by default and can be disabled by calling SetEventNotificationMode.

Exception Catch Events (JVMDI_EVENT_EXCEPTION_CATCH)

    typedef struct {
        jthread thread;
        jclass clazz;
        jmethodID method;
        jlocation location;
        jobject exception;
    } JVMDI_exception_catch_event_data;

Exception catch events are generated whenever a thrown exception is caught. 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.

The clazz, method, and location fields of the event structure 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.

Exception catch events are disabled by default and can be enabled by calling SetEventNotificationMode.

User Defined Events (JVMDI_EVENT_USER_DEFINED)

    typedef struct {
        jobject object;
        jint key;
    } JVMDI_user_event_data;

The meaning of user defined events and the fields in the user event data structure are defined by particular JVMDI implementations.

Thread Events (JVMDI_EVENT_THREAD_END, JVMDI_EVENT_THREAD_START)

    typedef struct {
        jthread thread;
    } JVMDI_thread_change_event_data;

Thread start events are generated by a new thread before its initial method executes. 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 before its thread start event is generated and after its thread end event is generated. It is possible for other events to be generated for a thread before its thread start event, but no events are generated after its thread end event.

Thread events are enabled by default and can be disabled by calling SetEventNotificationMode.

Class Events (JVMDI_EVENT_CLASS_LOAD, JVMDI_EVENT_CLASS_UNLOAD, JVMDI_EVENT_CLASS_PREPARE)

    typedef struct {
        jthread thread;
        jclass clazz;
    } JVMDI_class_event_data;

Class events signal a change in status for a particular class.

A class load event is generated when a class is first loaded. The order of class load events are generated by a particular thread are guaranteed to match the order of class loading within that thread. Arrays of non-primitive types have class load events. Arrays of primitive types do not have class load events (they are considered loaded at the time of VM initialization). Primitive classes (for example, java.lang.Integer.TYPE) do not have class load events.

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).

A class unload event is generated when the class is about to be unloaded. Class unload events take place during garbage collection and must be handled extremely carefully. The garbage collector holds many locks and has suspended all other threads, so the event handler cannot depend on the ability to acquire any locks. The class unload event handler should do as little as possible, perhaps by queueing information to be processed later.

Class events are enabled by default and can be disabled by calling SetEventNotificationMode.

VM Initialization Event (JVMDI_EVENT_VM_INIT)

The VM initialization event signals the completion of VM initialization. Once this event is generated, the JVMDI client is free to call any JNI or JVMDI 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.

VM Death Event (JVMDI_EVENT_VM_DEATH)

The VM death event notifies the JVMDI client of the termination of the VM.

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 of the events are reported through the event hook in the order specified in the following paragraphs.

If the current location is at the entry point of a method, the JVMDI_EVENT_METHOD_ENTRY 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 which cleared a pending exception has returned), the JVMDI_EVENT_EXCEPTION_CATCH event is reported before any other event at the current location in the same thread.

If a JVMDI_EVENT_SINGLE_STEP event or JVMDI_EVENT_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, JVMDI_EVENT_EXCEPTION, JVMDI_EVENT_FIELD_ACCESS, and JVMDI_EVENT_FIELD_MODIFICATION). 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 JVMDI_EVENT_METHOD_EXIT event and the JVMDI_EVENT_FRAME_POP 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 JVMDI client 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, then the co-located event y is reported for the current thread and location. If x does not precede y, then 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 JVMDI_EVENT_SINGLE_STEP, 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.

  • JVMDI_EVENT_USER_DEFINED
  • JVMDI_EVENT_VM_INIT
  • JVMDI_EVENT_VM_DEATH
  • JVMDI_EVENT_THREAD_START
  • JVMDI_EVENT_THREAD_END
  • JVMDI_EVENT_CLASS_LOAD
  • JVMDI_EVENT_CLASS_UNLOAD
  • JVMDI_EVENT_CLASS_PREPARE

Starting a VM with a JVMDI Client

The initial loading of a JVMDI client at VM startup can vary from VM to VM. The following description applies to the Sun J2SE SDK 1.2 classic VM for Windows and Solaris.

The following command-line arguments are required on VM startup to properly load and run JVMDI clients.

-Xdebug
Enables debugging
-Xnoagent
Prevents the default debug agent (used with jdb) from running.
-Djava.compiler=NONE
Disables the JIT. The classic VM does not support debugging with the JIT enabled.
-Xrun:
Identifies the library containing the JVMDI client as well as an options string to be passed in at startup. The library must export a startup function with the following prototype.
JNIEXPORT jint JNICALL
JVM_OnLoad(JavaVM *vm, char *options, void *reserved)
This function will be called at startup by the VM. For example, if the option -Xrunfoo:opt1,opt2 is specified, the VM will attempt to load the shared library foo.dll under Windows or libfoo.so under Solaris. It will then attempt to find JVM_OnLoad and call it with "opt1,opt2" as the second argument. Since the VM is not initialized at the time of this call, there is very little that can be done safely inside JVM_OnLoad. It can safely process the options and set an event hook with SetEventHook. Once that event hook is called for the VM initialization event, the JVMDI client can complete its initialization.
Copyright © 1996-2001 Sun Microsystems, Inc. All Rights Reserved.

Send questions or comments to: java-debugger@sun.com.

Sun


SourceDebugExtension Class File Attribute

Java virtual machine class file attributes are described in section 4.7 of the The Java Virtual Machine Specification. The definition of the added attribute is in the context of The Java Virtual Machine Specification:

The SourceDebugExtension attribute is an optional attribute in the attributes table of the ClassFile structure. There can be no more than one SourceDebugExtension attribute in the attributes table of a given ClassFile structure.

The SourceDebugExtension attribute has the following format:

    SourceDebugExtension_attribute {
       u2 attribute_name_index;
       u4 attribute_length;
       u1 debug_extension[attribute_length];
    }
The items of the SourceDebugExtension_attribute structure are as follows:

attribute_name_index
The value of the attribute_name_index item must be a valid index into the constant_pool table. The constant_pool entry at that index must be a CONSTANT_Utf8_info structure representing the string "SourceDebugExtension".

attribute_length
The value of the attribute_length item indicates the length of the attribute, excluding the initial six bytes. The value of the attribute_length item is thus the number of bytes in the debug_extension[] item.

debug_extension[]
The debug_extension array holds a string, which must be in UTF-8 format. There is no terminating zero byte.

The string in the debug_extension item will be interpreted as extended debugging information. The content of this string has no semantic effect on the Java Virtual Machine.

Copyright © 2001 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-debugger@sun.com

Sun


All Classes (Java Debug Interface)

 All Classes
AbsentInformationException
AccessWatchpointEvent
AccessWatchpointRequest
Accessible
ArrayReference
ArrayType
AttachingConnector
BooleanType
BooleanValue
Bootstrap
BreakpointEvent
BreakpointRequest
ByteType
ByteValue
CharType
CharValue
ClassLoaderReference
ClassNotLoadedException
ClassNotPreparedException
ClassObjectReference
ClassPrepareEvent
ClassPrepareRequest
ClassType
ClassUnloadEvent
ClassUnloadRequest
Connector
Connector.Argument
Connector.BooleanArgument
Connector.IntegerArgument
Connector.SelectedArgument
Connector.StringArgument
DoubleType
DoubleValue
DuplicateRequestException
Event
EventIterator
EventQueue
EventRequest
EventRequestManager
EventSet
ExceptionEvent
ExceptionRequest
Field
FloatType
FloatValue
IllegalConnectorArgumentsException
IncompatibleThreadStateException
InconsistentDebugInfoException
IntegerType
IntegerValue
InterfaceType
InternalException
InvalidCodeIndexException
InvalidLineNumberException
InvalidRequestStateException
InvalidStackFrameException
InvalidTypeException
InvocationException
LaunchingConnector
ListeningConnector
LocalVariable
Locatable
LocatableEvent
Location
LongType
LongValue
Method
MethodEntryEvent
MethodEntryRequest
MethodExitEvent
MethodExitRequest
Mirror
ModificationWatchpointEvent
ModificationWatchpointRequest
NativeMethodException
ObjectCollectedException
ObjectReference
PathSearchingVirtualMachine
PrimitiveType
PrimitiveValue
ReferenceType
ShortType
ShortValue
StackFrame
StepEvent
StepRequest
StringReference
ThreadDeathEvent
ThreadDeathRequest
ThreadGroupReference
ThreadReference
ThreadStartEvent
ThreadStartRequest
Transport
Type
TypeComponent
VMDeathEvent
VMDeathRequest
VMDisconnectEvent
VMDisconnectedException
VMMismatchException
VMOutOfMemoryException
VMStartEvent
VMStartException
Value
VirtualMachine
VirtualMachineManager
VoidType
VoidValue
WatchpointEvent
WatchpointRequest


Constant Field Values (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Constant Field Values

Contents
  • com.sun.*
com.sun.*

com.sun.jdi.ClassType
public static final int INVOKE_SINGLE_THREADED 1

com.sun.jdi.ObjectReference
public static final int | INVOKE_NONVIRTUAL | 2
public static final int | INVOKE_SINGLE_THREADED | 1

com.sun.jdi.ThreadReference
public static final int | THREAD_STATUS_MONITOR | 3
public static final int | THREAD_STATUS_NOT_STARTED | 5
public static final int | THREAD_STATUS_RUNNING | 1
public static final int | THREAD_STATUS_SLEEPING | 2
public static final int | THREAD_STATUS_UNKNOWN | -1
public static final int | THREAD_STATUS_WAIT | 4
public static final int | THREAD_STATUS_ZOMBIE | 0

com.sun.jdi.VirtualMachine
public static final int | TRACE_ALL | 16777215
public static final int | TRACE_EVENTS | 4
public static final int | TRACE_NONE | 0
public static final int | TRACE_OBJREFS | 16
public static final int | TRACE_RECEIVES | 2
public static final int | TRACE_REFTYPES | 8
public static final int | TRACE_SENDS | 1

com.sun.jdi.request.EventRequest
public static final int | SUSPEND_ALL | 2
public static final int | SUSPEND_EVENT_THREAD | 1
public static final int | SUSPEND_NONE | 0

com.sun.jdi.request.StepRequest
public static final int | STEP_INTO | 1
public static final int | STEP_LINE | -2
public static final int | STEP_MIN | -1
public static final int | STEP_OUT | 3
public static final int | STEP_OVER | 2

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


API Help (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

How This API Document Is Organized

This API (Application Programming Interface) document has pages corresponding to the items in the navigation bar, described as follows.

Overview

The Overview page is the front page of this API document and provides a list of all packages with a summary for each. This page can also contain an overall description of the set of packages.

Package

Each package has a page that contains a list of its classes and interfaces, with a summary for each. This page can contain four categories:

  • Interfaces (italic)
  • Classes
  • Exceptions
  • Errors

Class/Interface

Each class, interface, nested class and nested interface has its own separate page. Each of these pages has three sections consisting of a class/interface description, summary tables, and detailed member descriptions:

  • Class inheritance diagram
  • Direct Subclasses
  • All Known Subinterfaces
  • All Known Implementing Classes
  • Class/interface declaration
  • Class/interface description

  • Nested Class Summary
  • Field Summary
  • Constructor Summary
  • Method Summary

  • Field Detail
  • Constructor Detail
  • Method Detail
Each summary entry contains the first sentence from the detailed description for that item. The summary entries are alphabetical, while the detailed descriptions are in the order they appear in the source code. This preserves the logical groupings established by the programmer.

Use

Each documented package, class and interface has its own Use page. This page describes what packages, classes, methods, constructors and fields use any part of the given class 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.

Tree (Class Hierarchy)

There is a Class Hierarchy page for all packages, plus a hierarchy for each package. Each hierarchy page contains a list of classes and a list of interfaces. The classes are organized by inheritance structure starting with java.lang.Object. The interfaces do not inherit from java.lang.Object.
  • When viewing the Overview page, clicking on "Tree" displays the hierarchy for all packages.
  • When viewing a particular package, class or interface page, clicking "Tree" displays the hierarchy for only that package.

Index

The Index contains an alphabetic list of all classes, interfaces, constructors, methods, and fields.

Prev/Next

These links take you to the next or previous class, interface, package, or related page.

Frames/No Frames

These links show and hide the HTML frames. All pages are available with or without frames.

Serialized Form

Each serializable or externalizable 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 description.

This help file applies to API documentation generated using the standard doclet.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Java Debug Interface

Frame Alert

This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client.
Link toNon-frame version.


Index (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES
A B C D E F G H I L M N O P R S T U V W

A

AbsentInformationException - exception com.sun.jdi.AbsentInformationException.
Thrown to indicate line number or variable information is not available.
AbsentInformationException() - Constructor for class com.sun.jdi.AbsentInformationException
AbsentInformationException(String) - Constructor for class com.sun.jdi.AbsentInformationException
AccessWatchpointEvent - interface com.sun.jdi.event.AccessWatchpointEvent.
Notification of a field access in the target VM.
AccessWatchpointRequest - interface com.sun.jdi.request.AccessWatchpointRequest.
Request for notification when the contents of a field are accessed in the target VM.
Accessible - interface com.sun.jdi.Accessible.
Provides information on the accessibility of a type or type component.
ArrayReference - interface com.sun.jdi.ArrayReference.
Provides access to an array object and its components in the target VM.
ArrayType - interface com.sun.jdi.ArrayType.
Provides access to the class of an array and the type of its components in the target VM.
AttachingConnector - interface com.sun.jdi.connect.AttachingConnector.
A connector which attaches to a previously running target VM.
accept(Map) - Method in interface com.sun.jdi.connect.ListeningConnector
Waits for a target VM to attach to this connector.
accessWatchpointRequests() - Method in interface com.sun.jdi.request.EventRequestManager
Return an unmodifiable list of the enabled and disabled access watchpoint requests.
addClassExclusionFilter(String) - Method in interface com.sun.jdi.request.ClassPrepareRequest
Restricts the events generated by this request to the preparation of reference types whose name does not match this restricted regular expression.
addClassExclusionFilter(String) - Method in interface com.sun.jdi.request.ClassUnloadRequest
Restricts the events generated by this request to the unloading of reference types whose name does not match a restricted regular expression.
addClassExclusionFilter(String) - Method in interface com.sun.jdi.request.ExceptionRequest
Restricts the events generated by this request to those whose location is in a class whose name does not match a restricted regular expression.
addClassExclusionFilter(String) - Method in interface com.sun.jdi.request.MethodEntryRequest
Restricts the events generated by this request to those whose method is in a class whose name does not match this restricted regular expression, e.g.
addClassExclusionFilter(String) - Method in interface com.sun.jdi.request.MethodExitRequest
Restricts the events generated by this request to those whose method is in a class whose name does not match this restricted regular expression.
addClassExclusionFilter(String) - Method in interface com.sun.jdi.request.StepRequest
Restricts the events generated by this request to those whose location is in a class whose name does not match a restricted regular expression.
addClassExclusionFilter(String) - Method in interface com.sun.jdi.request.WatchpointRequest
Restricts the events generated by this request to those whose location is in a class whose name does not match this restricted regular expression.
addClassFilter(ReferenceType) - Method in interface com.sun.jdi.request.ClassPrepareRequest
Restricts the events generated by this request to be the preparation of the given reference type and any subtypes.
addClassFilter(String) - Method in interface com.sun.jdi.request.ClassPrepareRequest
Restricts the events generated by this request to the preparation of reference types whose name matches this restricted regular expression.
addClassFilter(String) - Method in interface com.sun.jdi.request.ClassUnloadRequest
Restricts the events generated by this request to the unloading of reference types whose name matches a restricted regular expression.
addClassFilter(ReferenceType) - Method in interface com.sun.jdi.request.ExceptionRequest
Restricts the events generated by this request to those whose location is in the given reference type or any of its subtypes.
addClassFilter(String) - Method in interface com.sun.jdi.request.ExceptionRequest
Restricts the events generated by this request to those whose location is in a class whose name matches a restricted regular expression.
addClassFilter(ReferenceType) - Method in interface com.sun.jdi.request.MethodEntryRequest
Restricts the events generated by this request to those whose method is in the given reference type or any of its subtypes.
addClassFilter(String) - Method in interface com.sun.jdi.request.MethodEntryRequest
Restricts the events generated by this request to those whose method is in a class whose name matches this restricted regular expression.
addClassFilter(ReferenceType) - Method in interface com.sun.jdi.request.MethodExitRequest
Restricts the events generated by this request to those whose method is in the given reference type or any of its subtypes.
addClassFilter(String) - Method in interface com.sun.jdi.request.MethodExitRequest
Restricts the events generated by this request to those whose method is in a class whose name matches a restricted regular expression.
addClassFilter(ReferenceType) - Method in interface com.sun.jdi.request.StepRequest
Restricts the events generated by this request to those whose location is in the given reference type or any of its subtypes.
addClassFilter(String) - Method in interface com.sun.jdi.request.StepRequest
Restricts the events generated by this request to those whose location is in a class whose name matches a restricted regular expression.
addClassFilter(ReferenceType) - Method in interface com.sun.jdi.request.WatchpointRequest
Restricts the events generated by this request to those whose location is in the given reference type or any of its subtypes.
addClassFilter(String) - Method in interface com.sun.jdi.request.WatchpointRequest
Restricts the events generated by this request to those whose location is in a class whose name matches a restricted regular expression.
addCountFilter(int) - Method in interface com.sun.jdi.request.EventRequest
Limit the requested event to be reported at most once after a given number of occurrences.
addInstanceFilter(ObjectReference) - Method in interface com.sun.jdi.request.BreakpointRequest
Restricts the events generated by this request to those in which the currently executing instance is the object specified.
addInstanceFilter(ObjectReference) - Method in interface com.sun.jdi.request.ExceptionRequest
Restricts the events generated by this request to those in which the currently executing instance ("this") is the object specified.
addInstanceFilter(ObjectReference) - Method in interface com.sun.jdi.request.MethodEntryRequest
Restricts the events generated by this request to those in which the currently executing instance ("this") is the object specified.
addInstanceFilter(ObjectReference) - Method in interface com.sun.jdi.request.MethodExitRequest
Restricts the events generated by this request to those in which the currently executing instance ("this") is the object specified.
addInstanceFilter(ObjectReference) - Method in interface com.sun.jdi.request.StepRequest
Restricts the events generated by this request to those in which the currently executing instance ("this") is the object specified.
addInstanceFilter(ObjectReference) - Method in interface com.sun.jdi.request.WatchpointRequest
Restricts the events generated by this request to those in which the currently executing instance ("this") is the object specified.
addThreadFilter(ThreadReference) - Method in interface com.sun.jdi.request.BreakpointRequest
Restricts the events generated by this request to those in the given thread.
addThreadFilter(ThreadReference) - Method in interface com.sun.jdi.request.ExceptionRequest
Restricts the events generated by this request to those in the given thread.
addThreadFilter(ThreadReference) - Method in interface com.sun.jdi.request.MethodEntryRequest
Restricts the events generated by this request to those in the given thread.
addThreadFilter(ThreadReference) - Method in interface com.sun.jdi.request.MethodExitRequest
Restricts the events generated by this request to those in the given thread.
addThreadFilter(ThreadReference) - Method in interface com.sun.jdi.request.ThreadDeathRequest
Restricts the events generated by this request to those in the given thread.
addThreadFilter(ThreadReference) - Method in interface com.sun.jdi.request.ThreadStartRequest
Restricts the events generated by this request to those in the given thread.
addThreadFilter(ThreadReference) - Method in interface com.sun.jdi.request.WatchpointRequest
Restricts the events generated by this request to those in the given thread.
allClasses() - Method in interface com.sun.jdi.VirtualMachine
Returns all loaded types.
allConnectors() - Method in interface com.sun.jdi.VirtualMachineManager
Returns the list of all known Connector objects.
allFields() - Method in interface com.sun.jdi.ReferenceType
Returns a list containing each Field declared in this type, and its superclasses, implemented interfaces, and/or superinterfaces.
allInterfaces() - Method in interface com.sun.jdi.ClassType
Gets the interfaces directly and indirectly implemented by this class.
allLineLocations() - Method in interface com.sun.jdi.Method
Returns a list containing a Location object for each executable source line in this method.
allLineLocations(String, String) - Method in interface com.sun.jdi.Method
Returns a list containing a Location object for each executable source line in this method.
allLineLocations() - Method in interface com.sun.jdi.ReferenceType
Returns a list containing a Location object for each executable source line in this reference type.
allLineLocations(String, String) - Method in interface com.sun.jdi.ReferenceType
Returns a list containing a Location object for each executable source line in this reference type.
allMethods() - Method in interface com.sun.jdi.ReferenceType
Returns a list containing each Method declared in this type, and its superclasses, implemented interfaces, and/or superinterfaces.
allThreads() - Method in interface com.sun.jdi.VirtualMachine
Returns a list of the currently running threads.
argumentNames() - Method in class com.sun.jdi.connect.IllegalConnectorArgumentsException
Return a List containing the names of the invalid or inconsistent arguments.
argumentTypeNames() - Method in interface com.sun.jdi.Method
Returns a list containing a text representation of the type of each formal parameter of this method.
argumentTypes() - Method in interface com.sun.jdi.Method
Returns a list containing the type of each formal parameter of this method.
arguments() - Method in interface com.sun.jdi.Method
Returns a list containing each LocalVariable that is declared as an argument of this method.
attach(Map) - Method in interface com.sun.jdi.connect.AttachingConnector
Attaches to a running application and and returns a mirror of its VM.
attachingConnectors() - Method in interface com.sun.jdi.VirtualMachineManager
Returns the list of known AttachingConnector objects.
availableStrata() - Method in interface com.sun.jdi.ReferenceType
Return the available strata for this reference type.

B

BooleanType - interface com.sun.jdi.BooleanType.
The type of all primitive boolean values accessed in the target VM.
BooleanValue - interface com.sun.jdi.BooleanValue.
Provides access to a primitive boolean value in the target VM.
Bootstrap - class com.sun.jdi.Bootstrap.
Initial class that provides access to the default implementation of JDI interfaces.
Bootstrap() - Constructor for class com.sun.jdi.Bootstrap
BreakpointEvent - interface com.sun.jdi.event.BreakpointEvent.
Notification of a breakpoint in the target VM.
BreakpointRequest - interface com.sun.jdi.request.BreakpointRequest.
Identifies a Location in the target VM at which execution should be stopped.
ByteType - interface com.sun.jdi.ByteType.
The type of all primitive byte values accessed in the target VM.
ByteValue - interface com.sun.jdi.ByteValue.
Provides access to a primitive byte value in the target VM.
baseDirectory() - Method in interface com.sun.jdi.PathSearchingVirtualMachine
Get the base directory used for path searching.
booleanValue() - Method in interface com.sun.jdi.PrimitiveValue
Converts this value to a BooleanValue and returns the result as a boolean.
booleanValue() - Method in interface com.sun.jdi.connect.Connector.BooleanArgument
Return the value of the argument as a boolean.
bootClassPath() - Method in interface com.sun.jdi.PathSearchingVirtualMachine
Get the boot class path for this virtual machine.
breakpointRequests() - Method in interface com.sun.jdi.request.EventRequestManager
Return an unmodifiable list of the enabled and disabled breakpoint requests.
byteValue() - Method in interface com.sun.jdi.PrimitiveValue
Converts this value to a ByteValue and returns the result as a byte.
bytecodes() - Method in interface com.sun.jdi.Method
Returns an array containing the bytecodes for this method.

C

CharType - interface com.sun.jdi.CharType.
The type of all primitive char values accessed in the target VM.
CharValue - interface com.sun.jdi.CharValue.
Provides access to a primitive char value in the target VM.
ClassLoaderReference - interface com.sun.jdi.ClassLoaderReference.
A class loader object from the target VM.
ClassNotLoadedException - exception com.sun.jdi.ClassNotLoadedException.
Thrown to indicate that the requested class has not yet been loaded through the appropriate class loader.
ClassNotLoadedException(String) - Constructor for class com.sun.jdi.ClassNotLoadedException
ClassNotLoadedException(String, String) - Constructor for class com.sun.jdi.ClassNotLoadedException
ClassNotPreparedException - exception com.sun.jdi.ClassNotPreparedException.
Thrown to indicate that the requested operation cannot be completed because the specified class has not yet been prepared.
ClassNotPreparedException() - Constructor for class com.sun.jdi.ClassNotPreparedException
ClassNotPreparedException(String) - Constructor for class com.sun.jdi.ClassNotPreparedException
ClassObjectReference - interface com.sun.jdi.ClassObjectReference.
An instance of java.lang.Class from the target VM.
ClassPrepareEvent - interface com.sun.jdi.event.ClassPrepareEvent.
Notification of a class prepare in the target VM.
ClassPrepareRequest - interface com.sun.jdi.request.ClassPrepareRequest.
Request for notification when a class is prepared in the target VM.
ClassType - interface com.sun.jdi.ClassType.
A mirror of a class in the target VM.
ClassUnloadEvent - interface com.sun.jdi.event.ClassUnloadEvent.
Notification of a class unload in the target VM.
ClassUnloadRequest - interface com.sun.jdi.request.ClassUnloadRequest.
Request for notification when a class is unloaded in the target VM.
Connector - interface com.sun.jdi.connect.Connector.
A method of connection between a debugger and a target VM.
Connector.Argument - interface com.sun.jdi.connect.Connector.Argument.
Specification for and value of a Connector argument.
Connector.BooleanArgument - interface com.sun.jdi.connect.Connector.BooleanArgument.
Specification for and value of a Connector argument, whose value is Boolean.
Connector.IntegerArgument - interface com.sun.jdi.connect.Connector.IntegerArgument.
Specification for and value of a Connector argument, whose value is an integer.
Connector.SelectedArgument - interface com.sun.jdi.connect.Connector.SelectedArgument.
Specification for and value of a Connector argument, whose value is a String selected from a list of choices.
Connector.StringArgument - interface com.sun.jdi.connect.Connector.StringArgument.
Specification for and value of a Connector argument, whose value is a String.
canAddMethod() - Method in interface com.sun.jdi.VirtualMachine
Determines if the target VM supports the addition of methods when performing class redefinition.
canGetBytecodes() - Method in interface com.sun.jdi.VirtualMachine
Determines if the target VM supports the retrieval of a method's bytecodes.
canGetCurrentContendedMonitor() - Method in interface com.sun.jdi.VirtualMachine
Determines if the target VM supports the retrieval of the monitor for which a thread is currently waiting.
canGetMonitorInfo() - Method in interface com.sun.jdi.VirtualMachine
Determines if the target VM supports the retrieval of the monitor information for an object.
canGetOwnedMonitorInfo() - Method in interface com.sun.jdi.VirtualMachine
Determines if the target VM supports the retrieval of the monitors owned by a thread.
canGetSourceDebugExtension() - Method in interface com.sun.jdi.VirtualMachine
Determines if the target VM supports getting the source debug extension.
canGetSyntheticAttribute() - Method in interface com.sun.jdi.VirtualMachine
Determines if the target VM supports the query of the synthetic attribute of a method or field.
canPopFrames() - Method in interface com.sun.jdi.VirtualMachine
Determines if the target VM supports popping frames of a threads stack.
canRedefineClasses() - Method in interface com.sun.jdi.VirtualMachine
Determines if the target VM supports any level of class redefinition.
canRequestVMDeathEvent() - Method in interface com.sun.jdi.VirtualMachine
Determines if the target VM supports the creation of VMDeathRequests.
canUnrestrictedlyRedefineClasses() - Method in interface com.sun.jdi.VirtualMachine
Determines if the target VM supports unrestricted changes when performing class redefinition.
canUseInstanceFilters() - Method in interface com.sun.jdi.VirtualMachine
Determines if the target VM supports filtering events by specific instance object.
canWatchFieldAccess() - Method in interface com.sun.jdi.VirtualMachine
Determines if the target VM supports watchpoints for field access.
canWatchFieldModification() - Method in interface com.sun.jdi.VirtualMachine
Determines if the target VM supports watchpoints for field modification.
catchLocation() - Method in interface com.sun.jdi.event.ExceptionEvent
Gets the location where the exception will be caught.
charValue() - Method in interface com.sun.jdi.PrimitiveValue
Converts this value to a CharValue and returns the result as a char.
choices() - Method in interface com.sun.jdi.connect.Connector.SelectedArgument
Return the possible values for the argument
classLoader() - Method in interface com.sun.jdi.ReferenceType
Gets the classloader object which loaded the class corresponding to this type.
className() - Method in class com.sun.jdi.ClassNotLoadedException
className() - Method in interface com.sun.jdi.event.ClassUnloadEvent
Returns the name of the class that has been unloaded.
classObject() - Method in interface com.sun.jdi.ReferenceType
Returns the class object that corresponds to this type in the target VM.
classPath() - Method in interface com.sun.jdi.PathSearchingVirtualMachine
Get the class path for this virtual machine.
classPrepareRequests() - Method in interface com.sun.jdi.request.EventRequestManager
Return an unmodifiable list of the enabled and disabled class prepare requests.
classSignature() - Method in interface com.sun.jdi.event.ClassUnloadEvent
Returns the JNI-style signature of the class that has been unloaded.
classUnloadRequests() - Method in interface com.sun.jdi.request.EventRequestManager
Return an unmodifiable list of the enabled and disabled class unload requests.
classesByName(String) - Method in interface com.sun.jdi.VirtualMachine
Returns the loaded reference types that match a given name.
codeIndex() - Method in interface com.sun.jdi.Location
Gets the code position within this location's method.
com.sun.jdi - package 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 - package com.sun.jdi.connect
This package defines connections between the virtual machine using the JDI and the target virtual machine.
com.sun.jdi.event - package com.sun.jdi.event
This package defines JDI events and event processing.
com.sun.jdi.request - package com.sun.jdi.request
This package is used to request that a JDI event be sent under specified conditions.
componentSignature() - Method in interface com.sun.jdi.ArrayType
Gets the JNI signature of the components of this array class.
componentType() - Method in interface com.sun.jdi.ArrayType
Returns the component type of this array, as specified in the array declaration.
componentTypeName() - Method in interface com.sun.jdi.ArrayType
Returns a text representation of the component type of this array.
concreteMethodByName(String, String) - Method in interface com.sun.jdi.ClassType
Returns a the single non-abstract Method visible from this class that has the given name and signature.
connectedVirtualMachines() - Method in interface com.sun.jdi.VirtualMachineManager
Lists all target VMs which are connected to the debugger.
createAccessWatchpointRequest(Field) - Method in interface com.sun.jdi.request.EventRequestManager
Creates a new disabled watchpoint which watches accesses to the specified field.
createBreakpointRequest(Location) - Method in interface com.sun.jdi.request.EventRequestManager
Creates a new disabled BreakpointRequest.
createClassPrepareRequest() - Method in interface com.sun.jdi.request.EventRequestManager
Creates a new disabled ClassPrepareRequest.
createClassUnloadRequest() - Method in interface com.sun.jdi.request.EventRequestManager
Creates a new disabled ClassUnloadRequest.
createExceptionRequest(ReferenceType, boolean, boolean) - Method in interface com.sun.jdi.request.EventRequestManager
Creates a new disabled ExceptionRequest.
createMethodEntryRequest() - Method in interface com.sun.jdi.request.EventRequestManager
Creates a new disabled MethodEntryRequest.
createMethodExitRequest() - Method in interface com.sun.jdi.request.EventRequestManager
Creates a new disabled MethodExitRequest.
createModificationWatchpointRequest(Field) - Method in interface com.sun.jdi.request.EventRequestManager
Creates a new disabled watchpoint which watches accesses to the specified field.
createStepRequest(ThreadReference, int, int) - Method in interface com.sun.jdi.request.EventRequestManager
Creates a new disabled StepRequest.
createThreadDeathRequest() - Method in interface com.sun.jdi.request.EventRequestManager
Creates a new disabled ThreadDeathRequest.
createThreadStartRequest() - Method in interface com.sun.jdi.request.EventRequestManager
Creates a new disabled ThreadStartRequest.
createVMDeathRequest() - Method in interface com.sun.jdi.request.EventRequestManager
Creates a new disabled VMDeathRequest.
currentContendedMonitor() - Method in interface com.sun.jdi.ThreadReference
Returns an ObjectReference for the monitor, if any, for which this thread is currently waiting.

D

DoubleType - interface com.sun.jdi.DoubleType.
The type of all primitive double values accessed in the target VM.
DoubleValue - interface com.sun.jdi.DoubleValue.
Provides access to a primitive double value in the target VM.
DuplicateRequestException - exception com.sun.jdi.request.DuplicateRequestException.
Thrown to indicate a duplicate event request.
DuplicateRequestException() - Constructor for class com.sun.jdi.request.DuplicateRequestException
DuplicateRequestException(String) - Constructor for class com.sun.jdi.request.DuplicateRequestException
declaringType() - Method in interface com.sun.jdi.Location
Gets the type to which this Location belongs.
declaringType() - Method in interface com.sun.jdi.TypeComponent
Returns the type in which this component was declared.
defaultArguments() - Method in interface com.sun.jdi.connect.Connector
Returns the arguments accepted by this Connector and their default values.
defaultConnector() - Method in interface com.sun.jdi.VirtualMachineManager
Identifies the default connector.
defaultStratum() - Method in interface com.sun.jdi.ReferenceType
Returns the default stratum for this reference type.
definedClasses() - Method in interface com.sun.jdi.ClassLoaderReference
Returns a list of all loaded classes that were defined by this class loader.
deleteAllBreakpoints() - Method in interface com.sun.jdi.request.EventRequestManager
Remove all breakpoints managed by this EventRequestManager.
deleteEventRequest(EventRequest) - Method in interface com.sun.jdi.request.EventRequestManager
Removes an eventRequest.
deleteEventRequests(List) - Method in interface com.sun.jdi.request.EventRequestManager
Removes a list of EventRequests.
depth() - Method in interface com.sun.jdi.request.StepRequest
description() - Method in interface com.sun.jdi.VirtualMachine
Returns text information on the target VM and the debugger support that mirrors it.
description() - Method in interface com.sun.jdi.connect.Connector.Argument
Returns a human-readable description of this argument and its purpose.
description() - Method in interface com.sun.jdi.connect.Connector
Returns a human-readable description of this connector and its purpose.
disable() - Method in interface com.sun.jdi.request.EventRequest
Same as setEnabled(false).
disableCollection() - Method in interface com.sun.jdi.ObjectReference
Prevents garbage collection for this object.
dispose() - Method in interface com.sun.jdi.VirtualMachine
Invalidates this virtual machine mirror.
doubleValue() - Method in interface com.sun.jdi.PrimitiveValue
Converts this value to a DoubleValue and returns the result as a double.

E

Event - interface com.sun.jdi.event.Event.
An occurrence in a target VM that is of interest to a debugger.
EventIterator - interface com.sun.jdi.event.EventIterator.
EventIterators are unmodifiable.
EventQueue - interface com.sun.jdi.event.EventQueue.
Manager of incoming debugger events for a target VM.
EventRequest - interface com.sun.jdi.request.EventRequest.
Represents a request for notification of an event.
EventRequestManager - interface com.sun.jdi.request.EventRequestManager.
Manages the creation and deletion of EventRequests.
EventSet - interface com.sun.jdi.event.EventSet.
Several Event objects may be created at a given time by the target VirtualMachine.
ExceptionEvent - interface com.sun.jdi.event.ExceptionEvent.
Notification of an exception in the target VM.
ExceptionRequest - interface com.sun.jdi.request.ExceptionRequest.
Request for notification when an exception occurs in the target VM.
enable() - Method in interface com.sun.jdi.request.EventRequest
Same as setEnabled(true).
enableCollection() - Method in interface com.sun.jdi.ObjectReference
Permits garbage collection for this object.
entryCount() - Method in interface com.sun.jdi.ObjectReference
Returns the number times this object's monitor has been entered by the current owning thread.
equals(Object) - Method in interface com.sun.jdi.BooleanValue
Compares the specified Object with this BooleanValue for equality.
equals(Object) - Method in interface com.sun.jdi.ByteValue
Compares the specified Object with this ByteValue for equality.
equals(Object) - Method in interface com.sun.jdi.CharValue
Compares the specified Object with this CharValue for equality.
equals(Object) - Method in interface com.sun.jdi.DoubleValue
Compares the specified Object with this DoubleValue for equality.
equals(Object) - Method in interface com.sun.jdi.Field
Compares the specified Object with this field for equality.
equals(Object) - Method in interface com.sun.jdi.FloatValue
Compares the specified Object with this FloatValue for equality.
equals(Object) - Method in interface com.sun.jdi.IntegerValue
Compares the specified Object with this IntegerValue for equality.
equals(Object) - Method in interface com.sun.jdi.LocalVariable
Compares the specified Object with this LocalVariable for equality.
equals(Object) - Method in interface com.sun.jdi.Location
Compares the specified Object with this Location for equality.
equals(Object) - Method in interface com.sun.jdi.LongValue
Compares the specified Object with this LongValue for equality.
equals(Object) - Method in interface com.sun.jdi.Method
Compares the specified Object with this method for equality.
equals(Object) - Method in interface com.sun.jdi.ObjectReference
Compares the specified Object with this ObjectReference for equality.
equals(Object) - Method in interface com.sun.jdi.ReferenceType
Compares the specified Object with this ReferenceType for equality.
equals(Object) - Method in interface com.sun.jdi.ShortValue
Compares the specified Object with this ShortValue for equality.
equals(Object) - Method in interface com.sun.jdi.VoidValue
Compares the specified Object with this VoidValue for equality.
errorCode() - Method in class com.sun.jdi.InternalException
eventIterator() - Method in interface com.sun.jdi.event.EventSet
Return an iterator specific to Event objects.
eventQueue() - Method in interface com.sun.jdi.VirtualMachine
Returns the event queue for this virtual machine.
eventRequestManager() - Method in interface com.sun.jdi.VirtualMachine
Returns the event request manager for this virtual machine.
exception() - Method in class com.sun.jdi.InvocationException
exception() - Method in interface com.sun.jdi.event.ExceptionEvent
Gets the thrown exception object.
exception() - Method in interface com.sun.jdi.request.ExceptionRequest
Returns exception type for which exception events are requested.
exceptionRequests() - Method in interface com.sun.jdi.request.EventRequestManager
Return an unmodifiable list of the enabled and disabled exception requests.
exit(int) - Method in interface com.sun.jdi.VirtualMachine
Causes the mirrored VM to terminate with the given error code.

F

Field - interface com.sun.jdi.Field.
A class or instance variable in the target VM.
FloatType - interface com.sun.jdi.FloatType.
The type of all primitive float values accessed in the target VM.
FloatValue - interface com.sun.jdi.FloatValue.
Provides access to a primitive float value in the target VM.
failedToInitialize() - Method in interface com.sun.jdi.ReferenceType
Determines if initialization failed for this class.
field() - Method in interface com.sun.jdi.event.WatchpointEvent
Returns the field that is about to be accessed/modified.
field() - Method in interface com.sun.jdi.request.WatchpointRequest
Gets the Field being watched by this WatchpointRequest.
fieldByName(String) - Method in interface com.sun.jdi.ReferenceType
Finds the visible Field with the given non-ambiguous name.
fields() - Method in interface com.sun.jdi.ReferenceType
Returns a list containing each Field declared in this type.
floatValue() - Method in interface com.sun.jdi.PrimitiveValue
Converts this value to a FloatValue and returns the result as a float.
frame(int) - Method in interface com.sun.jdi.ThreadReference
Returns the StackFrame at the given index in the thread's current call stack.
frameCount() - Method in interface com.sun.jdi.ThreadReference
Returns the number of stack frames in the thread's current call stack.
frames() - Method in interface com.sun.jdi.ThreadReference
Returns a List containing each StackFrame in the thread's current call stack.
frames(int, int) - Method in interface com.sun.jdi.ThreadReference
Returns a List containing a range of StackFrame mirrors from the thread's current call stack.

G

getDefaultStratum() - Method in interface com.sun.jdi.VirtualMachine
Return this VM's default stratum.
getProperty(Object) - Method in interface com.sun.jdi.request.EventRequest
Returns the value of the property with the specified key.
getValue(int) - Method in interface com.sun.jdi.ArrayReference
Returns an array component value.
getValue(Field) - Method in interface com.sun.jdi.ObjectReference
Gets the value of a given instance or static field in this object.
getValue(Field) - Method in interface com.sun.jdi.ReferenceType
Gets the Value of a given static Field in this type.
getValue(LocalVariable) - Method in interface com.sun.jdi.StackFrame
Gets the Value of a LocalVariable in this frame.
getValues() - Method in interface com.sun.jdi.ArrayReference
Returns all of the components in this array.
getValues(int, int) - Method in interface com.sun.jdi.ArrayReference
Returns a range of array components.
getValues(List) - Method in interface com.sun.jdi.ObjectReference
Gets the value of multiple instance and/or static fields in this object.
getValues(List) - Method in interface com.sun.jdi.ReferenceType
Returns a map containing the Value of each static Field in the given list.
getValues(List) - Method in interface com.sun.jdi.StackFrame
Returns the values of multiple local variables in this frame.

H

hashCode() - Method in interface com.sun.jdi.BooleanValue
Returns the hash code value for this BooleanValue.
hashCode() - Method in interface com.sun.jdi.ByteValue
Returns the hash code value for this BooleanValue.
hashCode() - Method in interface com.sun.jdi.CharValue
Returns the hash code value for this CharValue.
hashCode() - Method in interface com.sun.jdi.DoubleValue
Returns the hash code value for this DoubleValue.
hashCode() - Method in interface com.sun.jdi.Field
Returns the hash code value for this Field.
hashCode() - Method in interface com.sun.jdi.FloatValue
Returns the hash code value for this FloatValue.
hashCode() - Method in interface com.sun.jdi.IntegerValue
Returns the hash code value for this IntegerValue.
hashCode() - Method in interface com.sun.jdi.LocalVariable
Returns the hash code value for this LocalVariable.
hashCode() - Method in interface com.sun.jdi.Location
Returns the hash code value for this Location.
hashCode() - Method in interface com.sun.jdi.LongValue
Returns the hash code value for this LongValue.
hashCode() - Method in interface com.sun.jdi.Method
Returns the hash code value for this Method.
hashCode() - Method in interface com.sun.jdi.ObjectReference
Returns the hash code value for this ObjectReference.
hashCode() - Method in interface com.sun.jdi.ReferenceType
Returns the hash code value for this ObjectReference.
hashCode() - Method in interface com.sun.jdi.ShortValue
Returns the hash code value for this ShortValue.
hashCode() - Method in interface com.sun.jdi.VoidValue
Returns the hash code value for this VoidValue.

I

INVOKE_NONVIRTUAL - Static variable in interface com.sun.jdi.ObjectReference
Perform non-virtual method invocation
INVOKE_SINGLE_THREADED - Static variable in interface com.sun.jdi.ClassType
Perform method invocation with only the invoking thread resumed
INVOKE_SINGLE_THREADED - Static variable in interface com.sun.jdi.ObjectReference
Perform method invocation with only the invoking thread resumed
IllegalConnectorArgumentsException - exception com.sun.jdi.connect.IllegalConnectorArgumentsException.
Thrown to indicate an invalid argument or inconsistent passed to a Connector.
IllegalConnectorArgumentsException(String, String) - Constructor for class com.sun.jdi.connect.IllegalConnectorArgumentsException
Construct an IllegalConnectorArgumentsException with the specified detail message and the name of the argument which is invalid or inconsistent.
IllegalConnectorArgumentsException(String, List) - Constructor for class com.sun.jdi.connect.IllegalConnectorArgumentsException
Construct an IllegalConnectorArgumentsException with the specified detail message and a List of names of arguments which are invalid or inconsistent.
IncompatibleThreadStateException - exception com.sun.jdi.IncompatibleThreadStateException.
Thrown to indicate that the requested operation cannot be completed while the specified thread is in its current state.
IncompatibleThreadStateException() - Constructor for class com.sun.jdi.IncompatibleThreadStateException
IncompatibleThreadStateException(String) - Constructor for class com.sun.jdi.IncompatibleThreadStateException
InconsistentDebugInfoException - exception com.sun.jdi.InconsistentDebugInfoException.
Thrown to indicate that there is an inconistency in the debug information provided by the target VM.
InconsistentDebugInfoException() - Constructor for class com.sun.jdi.InconsistentDebugInfoException
InconsistentDebugInfoException(String) - Constructor for class com.sun.jdi.InconsistentDebugInfoException
IntegerType - interface com.sun.jdi.IntegerType.
The type of all primitive int values accessed in the target VM.
IntegerValue - interface com.sun.jdi.IntegerValue.
Provides access to a primitive int value in the target VM.
InterfaceType - interface com.sun.jdi.InterfaceType.
A mirror of an interface in the target VM.
InternalException - exception com.sun.jdi.InternalException.
Thrown to indicate that an unexpected internal error has occurred.
InternalException() - Constructor for class com.sun.jdi.InternalException
InternalException(String) - Constructor for class com.sun.jdi.InternalException
InternalException(int) - Constructor for class com.sun.jdi.InternalException
InternalException(String, int) - Constructor for class com.sun.jdi.InternalException
InvalidCodeIndexException - exception com.sun.jdi.InvalidCodeIndexException.
Deprecated. This exception is no longer thrown
InvalidCodeIndexException() - Constructor for class com.sun.jdi.InvalidCodeIndexException
Deprecated.
InvalidCodeIndexException(String) - Constructor for class com.sun.jdi.InvalidCodeIndexException
Deprecated.
InvalidLineNumberException - exception com.sun.jdi.InvalidLineNumberException.
Deprecated. This exception is no longer thrown
InvalidLineNumberException() - Constructor for class com.sun.jdi.InvalidLineNumberException
Deprecated.
InvalidLineNumberException(String) - Constructor for class com.sun.jdi.InvalidLineNumberException
Deprecated.
InvalidRequestStateException - exception com.sun.jdi.request.InvalidRequestStateException.
Thrown to indicate that the requested event cannot be modified because it is enabled.
InvalidRequestStateException() - Constructor for class com.sun.jdi.request.InvalidRequestStateException
InvalidRequestStateException(String) - Constructor for class com.sun.jdi.request.InvalidRequestStateException
InvalidStackFrameException - exception com.sun.jdi.InvalidStackFrameException.
Thrown to indicate that the requested operation cannot be completed because the specified stack frame is no longer valid.
InvalidStackFrameException() - Constructor for class com.sun.jdi.InvalidStackFrameException
InvalidStackFrameException(String) - Constructor for class com.sun.jdi.InvalidStackFrameException
InvalidTypeException - exception com.sun.jdi.InvalidTypeException.
Thrown to indicate a type mismatch in setting the value of a field or variable.
InvalidTypeException() - Constructor for class com.sun.jdi.InvalidTypeException
InvalidTypeException(String) - Constructor for class com.sun.jdi.InvalidTypeException
InvocationException - exception com.sun.jdi.InvocationException.
Thrown to indicate an exception occurred in an invoked method within the target VM.
InvocationException(ObjectReference) - Constructor for class com.sun.jdi.InvocationException
implementors() - Method in interface com.sun.jdi.InterfaceType
Gets the currently prepared classes which directly implement this interface.
intValue() - Method in interface com.sun.jdi.PrimitiveValue
Converts this value to an IntegerValue and returns the result as an int.
intValue() - Method in interface com.sun.jdi.connect.Connector.IntegerArgument
Return the value of the argument as a int.
interfaces() - Method in interface com.sun.jdi.ClassType
Gets the interfaces directly implemented by this class.
interrupt() - Method in interface com.sun.jdi.ThreadReference
Interrupts this thread unless the thread has been suspended by the debugger.
invokeMethod(ThreadReference, Method, List, int) - Method in interface com.sun.jdi.ClassType
Invokes the specified static Method in the target VM.
invokeMethod(ThreadReference, Method, List, int) - Method in interface com.sun.jdi.ObjectReference
Invokes the specified Method on this object in the target VM.
isAbstract() - Method in interface com.sun.jdi.Method
Determine if this method is abstract.
isAbstract() - Method in interface com.sun.jdi.ReferenceType
Determines if this type was declared abstract.
isArgument() - Method in interface com.sun.jdi.LocalVariable
Determines if this variable is an argument to its method.
isAtBreakpoint() - Method in interface com.sun.jdi.ThreadReference
Determines whether the thread is suspended at a breakpoint.
isCollected() - Method in interface com.sun.jdi.ObjectReference
Determines if this object has been garbage collected in the target VM.
isConstructor() - Method in interface com.sun.jdi.Method
Determine if this method is a constructor.
isEnabled() - Method in interface com.sun.jdi.request.EventRequest
Determines if this event request is currently enabled.
isFinal() - Method in interface com.sun.jdi.ReferenceType
Determines if this type was declared final.
isFinal() - Method in interface com.sun.jdi.TypeComponent
Determines if this TypeComponent is final.
isInitialized() - Method in interface com.sun.jdi.ReferenceType
Determines if this type has been initialized.
isNative() - Method in interface com.sun.jdi.Method
Determine if this method is native.
isObsolete() - Method in interface com.sun.jdi.Method
Determine if this method is obsolete.
isPackagePrivate() - Method in interface com.sun.jdi.Accessible
Determines if this object mirrors a package private item.
isPrepared() - Method in interface com.sun.jdi.ReferenceType
Determines if this type has been prepared.
isPrivate() - Method in interface com.sun.jdi.Accessible
Determines if this object mirrors a private item.
isProtected() - Method in interface com.sun.jdi.Accessible
Determines if this object mirrors a protected item.
isPublic() - Method in interface com.sun.jdi.Accessible
Determines if this object mirrors a public item.
isStatic() - Method in interface com.sun.jdi.ReferenceType
Determines if this type was declared static.
isStatic() - Method in interface com.sun.jdi.TypeComponent
Determines if this TypeComponent is static.
isStaticInitializer() - Method in interface com.sun.jdi.Method
Determine if this method is a static initializer.
isSuspended() - Method in interface com.sun.jdi.ThreadReference
Determines whether the thread has been suspended by the the debugger.
isSynchronized() - Method in interface com.sun.jdi.Method
Determine if this method is synchronized.
isSynthetic() - Method in interface com.sun.jdi.TypeComponent
Determines if this TypeComponent is synthetic.
isTransient() - Method in interface com.sun.jdi.Field
Determine if this is a transient field.
isValid(String) - Method in interface com.sun.jdi.connect.Connector.Argument
Performs basic sanity check of argument.
isValid(String) - Method in interface com.sun.jdi.connect.Connector.BooleanArgument
Performs basic sanity check of argument.
isValid(String) - Method in interface com.sun.jdi.connect.Connector.IntegerArgument
Performs basic sanity check of argument.
isValid(int) - Method in interface com.sun.jdi.connect.Connector.IntegerArgument
Performs basic sanity check of argument.
isValid(String) - Method in interface com.sun.jdi.connect.Connector.SelectedArgument
Performs basic sanity check of argument.
isValid(String) - Method in interface com.sun.jdi.connect.Connector.StringArgument
Performs basic sanity check of argument.
isVerified() - Method in interface com.sun.jdi.ReferenceType
Determines if this type has been verified.
isVisible(StackFrame) - Method in interface com.sun.jdi.LocalVariable
Determines whether this variable can be accessed from the given StackFrame.
isVolatile() - Method in interface com.sun.jdi.Field
Determine if this is a volatile field.

L

LaunchingConnector - interface com.sun.jdi.connect.LaunchingConnector.
A connector which can launch a target VM before connecting to it.
ListeningConnector - interface com.sun.jdi.connect.ListeningConnector.
A connector which listens for a connection initiated by a target VM.
LocalVariable - interface com.sun.jdi.LocalVariable.
A local variable in the target VM.
Locatable - interface com.sun.jdi.Locatable.
A mirror that has a Location.
LocatableEvent - interface com.sun.jdi.event.LocatableEvent.
Abstract superinterface of events which have both location and thread.
Location - interface com.sun.jdi.Location.
A point within the executing code of the target VM.
LongType - interface com.sun.jdi.LongType.
The type of all primitive long values accessed in the target VM.
LongValue - interface com.sun.jdi.LongValue.
Provides access to a primitive long value in the target VM.
label() - Method in interface com.sun.jdi.connect.Connector.Argument
Returns a short human-readable label for this argument.
launch(Map) - Method in interface com.sun.jdi.connect.LaunchingConnector
Launches an application and connects to its VM.
launchingConnectors() - Method in interface com.sun.jdi.VirtualMachineManager
Returns the list of known LaunchingConnector objects.
length() - Method in interface com.sun.jdi.ArrayReference
Returns the number of components in this array.
lineNumber() - Method in interface com.sun.jdi.Location
Gets the line number of this Location.
lineNumber(String) - Method in interface com.sun.jdi.Location
The line number of this Location.
listeningConnectors() - Method in interface com.sun.jdi.VirtualMachineManager
Returns the list of known ListeningConnector objects.
location() - Method in interface com.sun.jdi.Locatable
Returns the Location of this mirror, if there is executable code associated with it.
location() - Method in interface com.sun.jdi.Method
Returns the Location of this method, if there is executable code associated with it.
location() - Method in interface com.sun.jdi.StackFrame
Returns the Location of the current instruction in the frame.
location() - Method in interface com.sun.jdi.request.BreakpointRequest
Returns the location of the requested breakpoint.
locationOfCodeIndex(long) - Method in interface com.sun.jdi.Method
Returns a Location for the given code index.
locationsOfLine(int) - Method in interface com.sun.jdi.Method
Returns a List containing all Location objects that map to the given line number.
locationsOfLine(String, String, int) - Method in interface com.sun.jdi.Method
Returns a List containing all Location objects that map to the given line number and source name.
locationsOfLine(int) - Method in interface com.sun.jdi.ReferenceType
Returns a List containing all Location objects that map to the given line number.
locationsOfLine(String, String, int) - Method in interface com.sun.jdi.ReferenceType
Returns a List containing all Location objects that map to the given line number.
longValue() - Method in interface com.sun.jdi.PrimitiveValue
Converts this value to a LongValue and returns the result as a long.

M

Method - interface com.sun.jdi.Method.
A static or instance method in the target VM.
MethodEntryEvent - interface com.sun.jdi.event.MethodEntryEvent.
Notification of a method invocation in the target VM.
MethodEntryRequest - interface com.sun.jdi.request.MethodEntryRequest.
Request for notification when a method is invoked in the target VM.
MethodExitEvent - interface com.sun.jdi.event.MethodExitEvent.
Notification of a method return in the target VM.
MethodExitRequest - interface com.sun.jdi.request.MethodExitRequest.
Request for notification when a method returns in the target VM.
Mirror - interface com.sun.jdi.Mirror.
A proxy used by a debugger to examine or manipulate some entity in another virtual machine.
ModificationWatchpointEvent - interface com.sun.jdi.event.ModificationWatchpointEvent.
Notification of a field modification in the target VM.
ModificationWatchpointRequest - interface com.sun.jdi.request.ModificationWatchpointRequest.
Request for notification when a field is set.
majorInterfaceVersion() - Method in interface com.sun.jdi.VirtualMachineManager
Returns the major version number of the JDI interface.
max() - Method in interface com.sun.jdi.connect.Connector.IntegerArgument
The upper bound for the value.
method() - Method in interface com.sun.jdi.Location
Gets the method containing this Location.
method() - Method in interface com.sun.jdi.event.MethodEntryEvent
Returns the method that was entered.
method() - Method in interface com.sun.jdi.event.MethodExitEvent
Returns the method that was exited.
methodEntryRequests() - Method in interface com.sun.jdi.request.EventRequestManager
Return an unmodifiable list of the enabled and disabled method entry requests.
methodExitRequests() - Method in interface com.sun.jdi.request.EventRequestManager
Return an unmodifiable list of the enabled and disabled method exit requests.
methods() - Method in interface com.sun.jdi.ReferenceType
Returns a list containing each Method declared directly in this type.
methodsByName(String) - Method in interface com.sun.jdi.ReferenceType
Returns a List containing each visible Method that has the given name.
methodsByName(String, String) - Method in interface com.sun.jdi.ReferenceType
Returns a List containing each visible Method that has the given name and signature.
min() - Method in interface com.sun.jdi.connect.Connector.IntegerArgument
The lower bound for the value.
minorInterfaceVersion() - Method in interface com.sun.jdi.VirtualMachineManager
Returns the minor version number of the JDI interface.
mirrorOf(boolean) - Method in interface com.sun.jdi.VirtualMachine
Creates a BooleanValue for the given value.
mirrorOf(byte) - Method in interface com.sun.jdi.VirtualMachine
Creates a ByteValue for the given value.
mirrorOf(char) - Method in interface com.sun.jdi.VirtualMachine
Creates a CharValue for the given value.
mirrorOf(short) - Method in interface com.sun.jdi.VirtualMachine
Creates a ShortValue for the given value.
mirrorOf(int) - Method in interface com.sun.jdi.VirtualMachine
Creates an IntegerValue for the given value.
mirrorOf(long) - Method in interface com.sun.jdi.VirtualMachine
Creates a LongValue for the given value.
mirrorOf(float) - Method in interface com.sun.jdi.VirtualMachine
Creates a FloatValue for the given value.
mirrorOf(double) - Method in interface com.sun.jdi.VirtualMachine
Creates a DoubleValue for the given value.
mirrorOf(String) - Method in interface com.sun.jdi.VirtualMachine
Creates a string in this virtual machine.
modificationWatchpointRequests() - Method in interface com.sun.jdi.request.EventRequestManager
Return an unmodifiable list of the enabled and disabled modification watchpoint requests.
modifiers() - Method in interface com.sun.jdi.Accessible
Returns the JavaTM programming language modifiers, encoded in an integer.
mustSpecify() - Method in interface com.sun.jdi.connect.Connector.Argument
Indicates whether the argument must be specified.

N

NativeMethodException - exception com.sun.jdi.NativeMethodException.
Thrown to indicate an operation cannot be completed because it is not valid for a native method.
NativeMethodException() - Constructor for class com.sun.jdi.NativeMethodException
NativeMethodException(String) - Constructor for class com.sun.jdi.NativeMethodException
name() - Method in interface com.sun.jdi.LocalVariable
Gets the name of the local variable.
name() - Method in interface com.sun.jdi.ReferenceType
Gets the fully qualified name of this type.
name() - Method in interface com.sun.jdi.ThreadGroupReference
Returns the name of this thread group.
name() - Method in interface com.sun.jdi.ThreadReference
Returns the name of this thread.
name() - Method in interface com.sun.jdi.Type
name() - Method in interface com.sun.jdi.TypeComponent
Gets the name of this type component.
name() - Method in interface com.sun.jdi.VirtualMachine
Returns the name of the target VM as reported by the property java.vm.name.
name() - Method in interface com.sun.jdi.connect.Connector.Argument
Returns a short, unique identifier for the argument.
name() - Method in interface com.sun.jdi.connect.Connector
Returns a short identifier for the connector.
name() - Method in interface com.sun.jdi.connect.Transport
Returns a short identifier for the transport.
nestedTypes() - Method in interface com.sun.jdi.ReferenceType
Returns a List containing ReferenceType objects that are declared within this type and are currently loaded into the Virtual Machine.
newInstance(int) - Method in interface com.sun.jdi.ArrayType
Creates a new instance of this array class in the target VM.
newInstance(ThreadReference, Method, List, int) - Method in interface com.sun.jdi.ClassType
Constructs a new instance of this type, using the given constructor Method in the target VM.
nextEvent() - Method in interface com.sun.jdi.event.EventIterator
notifyCaught() - Method in interface com.sun.jdi.request.ExceptionRequest
Returns whether caught exceptions of the requested type will generate events when they are thrown.
notifyUncaught() - Method in interface com.sun.jdi.request.ExceptionRequest
Returns whether uncaught exceptions of the requested type will generate events when they are thrown.

O

ObjectCollectedException - exception com.sun.jdi.ObjectCollectedException.
Thrown to indicate that the requested operation cannot be completed because the specified object has been garbage collected.
ObjectCollectedException() - Constructor for class com.sun.jdi.ObjectCollectedException
ObjectCollectedException(String) - Constructor for class com.sun.jdi.ObjectCollectedException
ObjectReference - interface com.sun.jdi.ObjectReference.
An object that currently exists in the target VM.
object() - Method in interface com.sun.jdi.event.WatchpointEvent
Returns the object whose field is about to be accessed/modified.
ownedMonitors() - Method in interface com.sun.jdi.ThreadReference
Returns a List containing an ObjectReference for each monitor owned by the thread.
owningThread() - Method in interface com.sun.jdi.ObjectReference
Returns an ThreadReference for the thread, if any, which currently owns this object's monitor.

P

PathSearchingVirtualMachine - interface com.sun.jdi.PathSearchingVirtualMachine.
A virtual machine which searches for classes through paths
PrimitiveType - interface com.sun.jdi.PrimitiveType.
The type associated with non-object values in a target VM.
PrimitiveValue - interface com.sun.jdi.PrimitiveValue.
The value assigned to a field or variable of primitive type in a target VM.
parent() - Method in interface com.sun.jdi.ThreadGroupReference
Returns the parent of this thread group.
popFrames(StackFrame) - Method in interface com.sun.jdi.ThreadReference
Pop stack frames.
process() - Method in interface com.sun.jdi.VirtualMachine
Returns the Process object for this virtual machine if launched by a LaunchingConnector
process() - Method in class com.sun.jdi.connect.VMStartException
putProperty(Object, Object) - Method in interface com.sun.jdi.request.EventRequest
Add an arbitrary key/value "property" to this request.

R

ReferenceType - interface com.sun.jdi.ReferenceType.
The type of an object in a target VM.
redefineClasses(Map) - Method in interface com.sun.jdi.VirtualMachine
All classes given are redefined according to the definitions supplied.
referenceType() - Method in interface com.sun.jdi.ObjectReference
Gets the ReferenceType that mirrors the type of this object.
referenceType() - Method in interface com.sun.jdi.event.ClassPrepareEvent
Returns the reference type for which this event was generated.
reflectedType() - Method in interface com.sun.jdi.ClassObjectReference
Returns the ReferenceType corresponding to this class object.
remove() - Method in interface com.sun.jdi.event.EventQueue
Waits forever for the next available event.
remove(long) - Method in interface com.sun.jdi.event.EventQueue
Waits a specified time for the next available event.
request() - Method in interface com.sun.jdi.event.Event
resume() - Method in interface com.sun.jdi.ThreadGroupReference
Resumes all threads in this thread group.
resume() - Method in interface com.sun.jdi.ThreadReference
Resumes this thread.
resume() - Method in interface com.sun.jdi.VirtualMachine
Continues the execution of the application running in this virtual machine.
resume() - Method in interface com.sun.jdi.event.EventSet
Resumes threads suspended by this event set.
returnType() - Method in interface com.sun.jdi.Method
Returns the return type, as specified in the declaration of this method.
returnTypeName() - Method in interface com.sun.jdi.Method
Returns a text representation of the return type, as specified in the declaration of this method.

S

STEP_INTO - Static variable in interface com.sun.jdi.request.StepRequest
Step into any newly pushed frames
STEP_LINE - Static variable in interface com.sun.jdi.request.StepRequest
Step to the next location on a different line
STEP_MIN - Static variable in interface com.sun.jdi.request.StepRequest
Step to the next available location
STEP_OUT - Static variable in interface com.sun.jdi.request.StepRequest
Step out of the current frame
STEP_OVER - Static variable in interface com.sun.jdi.request.StepRequest
Step over any newly pushed frames
SUSPEND_ALL - Static variable in interface com.sun.jdi.request.EventRequest
Suspend all threads when the event occurs
SUSPEND_EVENT_THREAD - Static variable in interface com.sun.jdi.request.EventRequest
Suspend only the thread which generated the event when the event occurs
SUSPEND_NONE - Static variable in interface com.sun.jdi.request.EventRequest
Suspend no threads when the event occurs
ShortType - interface com.sun.jdi.ShortType.
The type of all primitive short values accessed in the target VM.
ShortValue - interface com.sun.jdi.ShortValue.
Provides access to a primitive short value in the target VM.
StackFrame - interface com.sun.jdi.StackFrame.
The state of one method invocation on a thread's call stack.
StepEvent - interface com.sun.jdi.event.StepEvent.
Notification of step completion in the target VM.
StepRequest - interface com.sun.jdi.request.StepRequest.
Request for notification when a step occurs in the target VM.
StringReference - interface com.sun.jdi.StringReference.
A string object from the target VM.
setDebugTraceMode(int) - Method in interface com.sun.jdi.VirtualMachine
Traces the activities performed by the com.sun.jdi implementation.
setDefaultStratum(String) - Method in interface com.sun.jdi.VirtualMachine
Set this VM's default stratum (see Location for a discussion of strata).
setEnabled(boolean) - Method in interface com.sun.jdi.request.EventRequest
Enables or disables this event request.
setSuspendPolicy(int) - Method in interface com.sun.jdi.request.EventRequest
Determines the threads to suspend when the requested event occurs in the target VM.
setValue(int, Value) - Method in interface com.sun.jdi.ArrayReference
Replaces an array component with another value.
setValue(Field, Value) - Method in interface com.sun.jdi.ClassType
Assigns a value to a static field.
setValue(Field, Value) - Method in interface com.sun.jdi.ObjectReference
Sets the value of a given instance or static field in this object.
setValue(LocalVariable, Value) - Method in interface com.sun.jdi.StackFrame
Sets the Value of a LocalVariable in this frame.
setValue(String) - Method in interface com.sun.jdi.connect.Connector.Argument
Sets the value of the argument.
setValue(boolean) - Method in interface com.sun.jdi.connect.Connector.BooleanArgument
Sets the value of the argument.
setValue(int) - Method in interface com.sun.jdi.connect.Connector.IntegerArgument
Sets the value of the argument.
setValues(List) - Method in interface com.sun.jdi.ArrayReference
Replaces all array components with other values.
setValues(int, List, int, int) - Method in interface com.sun.jdi.ArrayReference
Replaces a range of array components with other values.
shortValue() - Method in interface com.sun.jdi.PrimitiveValue
Converts this value to a ShortValue and returns the result as a short.
signature() - Method in interface com.sun.jdi.LocalVariable
Gets the JNI signature of the local variable.
signature() - Method in interface com.sun.jdi.Type
Returns the JNI-style signature for this type.
signature() - Method in interface com.sun.jdi.TypeComponent
Gets the JNI-style signature for this type component.
size() - Method in interface com.sun.jdi.request.StepRequest
sourceDebugExtension() - Method in interface com.sun.jdi.ReferenceType
Get the source debug extension of this type.
sourceName() - Method in interface com.sun.jdi.Location
Gets an identifing name for the source corresponding to this location.
sourceName(String) - Method in interface com.sun.jdi.Location
Gets an identifing name for the source corresponding to this location.
sourceName() - Method in interface com.sun.jdi.ReferenceType
Gets an identifying name for the source corresponding to the declaration of this type.
sourceNames(String) - Method in interface com.sun.jdi.ReferenceType
Gets the identifying names for all the source corresponding to the declaration of this type.
sourcePath() - Method in interface com.sun.jdi.Location
Gets the path to the source corresponding to this location.
sourcePath(String) - Method in interface com.sun.jdi.Location
Gets the path to the source corresponding to this location.
sourcePaths(String) - Method in interface com.sun.jdi.ReferenceType
Gets the paths to the source corresponding to the declaration of this type.
startListening(Map) - Method in interface com.sun.jdi.connect.ListeningConnector
Listens for one or more connections initiated by target VMs.
status() - Method in interface com.sun.jdi.ThreadReference
Returns the thread's status.
stepRequests() - Method in interface com.sun.jdi.request.EventRequestManager
Return an unmodifiable list of the enabled and disabled step requests.
stop(ObjectReference) - Method in interface com.sun.jdi.ThreadReference
Stops this thread with an asynchronous exception.
stopListening(Map) - Method in interface com.sun.jdi.connect.ListeningConnector
Cancels listening for connections.
stringValueOf(boolean) - Method in interface com.sun.jdi.connect.Connector.BooleanArgument
Return the string representation of the value parameter.
stringValueOf(int) - Method in interface com.sun.jdi.connect.Connector.IntegerArgument
Return the string representation of the value parameter.
subclasses() - Method in interface com.sun.jdi.ClassType
Gets the currently loaded, direct subclasses of this class.
subinterfaces() - Method in interface com.sun.jdi.InterfaceType
Gets the currently prepared interfaces which directly extend this interface.
superclass() - Method in interface com.sun.jdi.ClassType
Gets the superclass of this class.
superinterfaces() - Method in interface com.sun.jdi.InterfaceType
Gets the interfaces directly extended by this interface.
supportsMultipleConnections() - Method in interface com.sun.jdi.connect.ListeningConnector
Indicates whether this listening connector supports multiple connections for a single argument map.
suspend() - Method in interface com.sun.jdi.ThreadGroupReference
Suspends all threads in this thread group.
suspend() - Method in interface com.sun.jdi.ThreadReference
Suspends this thread.
suspend() - Method in interface com.sun.jdi.VirtualMachine
Suspends the execution of the application running in this virtual machine.
suspendCount() - Method in interface com.sun.jdi.ThreadReference
Returns the number of pending suspends for this thread.
suspendPolicy() - Method in interface com.sun.jdi.event.EventSet
Returns the policy used to suspend threads in the target VM for this event set.
suspendPolicy() - Method in interface com.sun.jdi.request.EventRequest
Returns a value which describes the threads to suspend when the requested event occurs in the target VM.

T

THREAD_STATUS_MONITOR - Static variable in interface com.sun.jdi.ThreadReference
Thread is waiting on a java monitor
THREAD_STATUS_NOT_STARTED - Static variable in interface com.sun.jdi.ThreadReference
Thread has not yet been started
THREAD_STATUS_RUNNING - Static variable in interface com.sun.jdi.ThreadReference
Thread is runnable
THREAD_STATUS_SLEEPING - Static variable in interface com.sun.jdi.ThreadReference
Thread is sleeping - Thread.sleep() or JVM_Sleep() was called
THREAD_STATUS_UNKNOWN - Static variable in interface com.sun.jdi.ThreadReference
Thread status is unknown
THREAD_STATUS_WAIT - Static variable in interface com.sun.jdi.ThreadReference
Thread is waiting - Thread.wait() or JVM_MonitorWait() was called
THREAD_STATUS_ZOMBIE - Static variable in interface com.sun.jdi.ThreadReference
Thread has completed execution
TRACE_ALL - Static variable in interface com.sun.jdi.VirtualMachine
All tracing is enabled.
TRACE_EVENTS - Static variable in interface com.sun.jdi.VirtualMachine
Tracing enabled for internal event handling.
TRACE_NONE - Static variable in interface com.sun.jdi.VirtualMachine
All tracing is disabled.
TRACE_OBJREFS - Static variable in interface com.sun.jdi.VirtualMachine
Tracing enabled for internal management of object references.
TRACE_RECEIVES - Static variable in interface com.sun.jdi.VirtualMachine
Tracing enabled for JDWP packets received from target VM.
TRACE_REFTYPES - Static variable in interface com.sun.jdi.VirtualMachine
Tracing enabled for internal managment of reference types.
TRACE_SENDS - Static variable in interface com.sun.jdi.VirtualMachine
Tracing enabled for JDWP packets sent to target VM.
ThreadDeathEvent - interface com.sun.jdi.event.ThreadDeathEvent.
Notification of a completed thread in the target VM.
ThreadDeathRequest - interface com.sun.jdi.request.ThreadDeathRequest.
Request for notification when a thread terminates in the target VM.
ThreadGroupReference - interface com.sun.jdi.ThreadGroupReference.
A thread group object from the target VM.
ThreadReference - interface com.sun.jdi.ThreadReference.
A thread object from the target VM.
ThreadStartEvent - interface com.sun.jdi.event.ThreadStartEvent.
Notification of a new running thread in the target VM.
ThreadStartRequest - interface com.sun.jdi.request.ThreadStartRequest.
Request for notification when a thread starts execution in the target VM.
Transport - interface com.sun.jdi.connect.Transport.
A method of communication between a debugger and a target VM.
Type - interface com.sun.jdi.Type.
The mirror for a type in the target VM.
TypeComponent - interface com.sun.jdi.TypeComponent.
An entity declared within a user defined type (class or interface).
thisObject() - Method in interface com.sun.jdi.StackFrame
Returns the value of 'this' for the current frame.
thread() - Method in interface com.sun.jdi.StackFrame
Returns the thread under which this frame's method is running.
thread() - Method in interface com.sun.jdi.event.ClassPrepareEvent
Returns the thread in which this event has occurred.
thread() - Method in interface com.sun.jdi.event.LocatableEvent
Returns the thread in which this event has occurred.
thread() - Method in interface com.sun.jdi.event.ThreadDeathEvent
Returns the thread which is terminating.
thread() - Method in interface com.sun.jdi.event.ThreadStartEvent
Returns the thread which has started.
thread() - Method in interface com.sun.jdi.event.VMStartEvent
Returns the initial thread of the VM which has started.
thread() - Method in interface com.sun.jdi.request.StepRequest
threadDeathRequests() - Method in interface com.sun.jdi.request.EventRequestManager
Return an unmodifiable list of the enabled and disabled thread death requests.
threadGroup() - Method in interface com.sun.jdi.ThreadReference
Returns this thread's thread group.
threadGroups() - Method in interface com.sun.jdi.ThreadGroupReference
Returns a List containing each ThreadGroupReference in this thread group.
threadStartRequests() - Method in interface com.sun.jdi.request.EventRequestManager
Return an unmodifiable list of the enabled and disabled thread start requests.
threads() - Method in interface com.sun.jdi.ThreadGroupReference
Returns a List containing each ThreadReference in this thread group.
toString() - Method in interface com.sun.jdi.Mirror
Returns a String describing this mirror
topLevelThreadGroups() - Method in interface com.sun.jdi.VirtualMachine
Returns each thread group which does not have a parent.
transport() - Method in interface com.sun.jdi.connect.Connector
Returns the transport mechanism used by this connector to establish connections with a target VM.
type() - Method in interface com.sun.jdi.Field
Returns the type of this field.
type() - Method in interface com.sun.jdi.LocalVariable
Returns the type of this variable.
type() - Method in interface com.sun.jdi.Value
Returns the run-time type of this value.
typeName() - Method in interface com.sun.jdi.Field
Returns a text representation of the type of this field.
typeName() - Method in interface com.sun.jdi.LocalVariable
Returns a text representation of the type of this variable.

U

uniqueID() - Method in interface com.sun.jdi.ObjectReference
Returns a unique identifier for this ObjectReference.

V

VMDeathEvent - interface com.sun.jdi.event.VMDeathEvent.
Notification of target VM termination.
VMDeathRequest - interface com.sun.jdi.request.VMDeathRequest.
Request for notification when the target VM terminates.
VMDisconnectEvent - interface com.sun.jdi.event.VMDisconnectEvent.
Notification of disconnection from target VM.
VMDisconnectedException - exception com.sun.jdi.VMDisconnectedException.
Unchecked exception thrown to indicate that the requested operation cannot be completed because there is no longer a connection to the target VM.
VMDisconnectedException() - Constructor for class com.sun.jdi.VMDisconnectedException
VMDisconnectedException(String) - Constructor for class com.sun.jdi.VMDisconnectedException
VMMismatchException - exception com.sun.jdi.VMMismatchException.
Thrown to indicate that the requested operation cannot be completed because the a mirror from one target VM is being combined with a mirror from another target VM.
VMMismatchException() - Constructor for class com.sun.jdi.VMMismatchException
VMMismatchException(String) - Constructor for class com.sun.jdi.VMMismatchException
VMOutOfMemoryException - exception com.sun.jdi.VMOutOfMemoryException.
Thrown to indicate that the requested operation cannot be completed because the target VM has run out of memory.
VMOutOfMemoryException() - Constructor for class com.sun.jdi.VMOutOfMemoryException
VMOutOfMemoryException(String) - Constructor for class com.sun.jdi.VMOutOfMemoryException
VMStartEvent - interface com.sun.jdi.event.VMStartEvent.
Notification of initialization of a target VM.
VMStartException - exception com.sun.jdi.connect.VMStartException.
A target VM was successfully launched, but terminated with an error before a connection could be established.
VMStartException(Process) - Constructor for class com.sun.jdi.connect.VMStartException
VMStartException(String, Process) - Constructor for class com.sun.jdi.connect.VMStartException
Value - interface com.sun.jdi.Value.
The mirror for a value in the target VM.
VirtualMachine - interface com.sun.jdi.VirtualMachine.
A virtual machine targeted for debugging.
VirtualMachineManager - interface com.sun.jdi.VirtualMachineManager.
A manager of connections to target virtual machines.
VoidType - interface com.sun.jdi.VoidType.
The type of all primitive void values accessed in the target VM.
VoidValue - interface com.sun.jdi.VoidValue.
Provides access to a primitive void value in the target VM.
value() - Method in interface com.sun.jdi.BooleanValue
Returns this BooleanValue as a boolean.
value() - Method in interface com.sun.jdi.ByteValue
Returns this ByteValue as a byte.
value() - Method in interface com.sun.jdi.CharValue
Returns this CharValue as a char.
value() - Method in interface com.sun.jdi.DoubleValue
Returns this DoubleValue as a double.
value() - Method in interface com.sun.jdi.FloatValue
Returns this FloatValue as a float.
value() - Method in interface com.sun.jdi.IntegerValue
Returns this IntegerValue as an int.
value() - Method in interface com.sun.jdi.LongValue
Returns this LongValue as a long.
value() - Method in interface com.sun.jdi.ShortValue
Returns this ShortValue as a short.
value() - Method in interface com.sun.jdi.StringReference
Returns the StringReference as a String.
value() - Method in interface com.sun.jdi.connect.Connector.Argument
Returns the current value of the argument.
valueCurrent() - Method in interface com.sun.jdi.event.WatchpointEvent
Current value of the field.
valueToBe() - Method in interface com.sun.jdi.event.ModificationWatchpointEvent
Value that will be assigned to the field when the instruction completes.
variables() - Method in interface com.sun.jdi.Method
Returns a list containing each LocalVariable declared in this method.
variablesByName(String) - Method in interface com.sun.jdi.Method
Returns a list containing each LocalVariable of a given name in this method.
version() - Method in interface com.sun.jdi.VirtualMachine
Returns the version of the Java Runtime Environment in the target VM as reported by the property java.version.
virtualMachine() - Method in interface com.sun.jdi.Mirror
Gets the VirtualMachine to which this Mirror belongs.
virtualMachineManager() - Static method in class com.sun.jdi.Bootstrap
visibleClasses() - Method in interface com.sun.jdi.ClassLoaderReference
Returns a list of all classes for which this class loader has been recorded as the initiating loader in the target VM.
visibleFields() - Method in interface com.sun.jdi.ReferenceType
Returns a list containing each unhidden and unambiguous Field in this type.
visibleMethods() - Method in interface com.sun.jdi.ReferenceType
Returns a list containing each Method declared or inherited by this type.
visibleVariableByName(String) - Method in interface com.sun.jdi.StackFrame
Finds a LocalVariable that matches the given name and is visible at the current frame location.
visibleVariables() - Method in interface com.sun.jdi.StackFrame
Returns a list containing each LocalVariable that can be accessed from this frame's location.
vmDeathRequests() - Method in interface com.sun.jdi.request.EventRequestManager
Return an unmodifiable list of the enabled and disabled VM death requests.

W

WatchpointEvent - interface com.sun.jdi.event.WatchpointEvent.
Notification of a field triggered event encountered by a thread in the target VM.
WatchpointRequest - interface com.sun.jdi.request.WatchpointRequest.
Identifies a Field in the target VM being watched.
waitingThreads() - Method in interface com.sun.jdi.ObjectReference
Returns a List containing a ThreadReference for each thread currently waiting for this object's monitor.
A B C D E F G H I L M N O P R S T U V W
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Overview (Java Debug Interface)

Java Debug Interface
All Classes

Packages
com.sun.jdi
com.sun.jdi.connect
com.sun.jdi.event
com.sun.jdi.request


Overview (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

JavaTM Debug Interface

The JavaTM Debug Interface (JDI) is a high level Java API providing information useful for debuggers and similiar systems needing access to the running state of a (usually remote) virtual machine.

See:
Description

Packages
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.
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.

The JavaTM Debug Interface (JDI) is a high level Java API providing information useful for debuggers and similiar systems needing access to the running state of a (usually remote) virtual machine.

The JDI provides introspective access to a running virtual machine's state, Class, Array, Interface, and primitive types, and instances of those types.

The JDI also provides explicit control over a virtual machine's execution. The ability to suspend and resume threads, and to set breakpoints, watchpoints, ... Notification of exceptions, class loading, thread creation... The ability to inspect a suspended thread's state, local variables, stack backtrace...

JDI is the highest-layer of the Java Platform Debugger Architecture (JPDA). For more information on the Java Platform Debugger Architecture, see the Java Platform Debugger Architecture documentation for this release and the Java Platform Debugger Architecture website.

Global Exceptions:

This section documents exceptions which apply to the entire API and are thus not documented on individual methods.

VMMismatchException

Any method on a Mirror that takes a Mirror as an parameter directly or indirectly (e.g., as a element in a List) will throw VMMismatchException if the mirrors are from different virtual machines.

NullPointerException

Any method which takes a Object as an parameter will throw NullPointerException if null is passed directly or indirectly -- unless null is explicitly mentioned as a valid parameter.

NOTE: The exceptions below may be thrown whenever the specified conditions are met but a guarantee that they are thrown only exists when a valid result cannot be returned.

VMDisconnectedException

Any method on ObjectReference, ReferenceType, EventRequest, StackFrame, or VirtualMachine or which takes one of these directly or indirectly as an parameter may throw VMDisconnectedException if the target VM is disconnected and the VMDisconnectEvent has been or is available to be read from the EventQueue.

VMOutOfMemoryException

Any method on ObjectReference, ReferenceType, EventRequest, StackFrame, or VirtualMachine or which takes one of these directly or indirectly as an parameter may throw VMOutOfMemoryException if the target VM has run out of memory.

ObjectCollectedException

Any method on ObjectReference or which directly or indirectly takes ObjectReference as parameter may throw ObjectCollectedException if the mirrored object has been garbage collected.

Any method on ReferenceType or which directly or indirectly takes ReferenceType as parameter may throw ObjectCollectedException if the mirrored type has been unloaded.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Class Hierarchy (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Hierarchy For All Packages

Package Hierarchies:
com.sun.jdi, com.sun.jdi.connect, com.sun.jdi.event, com.sun.jdi.request

Class Hierarchy

  • class java.lang.Object
    • class com.sun.jdi.Bootstrap
    • class java.lang.Throwable (implements java.io.Serializable)
      • class java.lang.Exception
        • class com.sun.jdi.AbsentInformationException
        • class com.sun.jdi.ClassNotLoadedException
        • class com.sun.jdi.connect.IllegalConnectorArgumentsException
        • class com.sun.jdi.IncompatibleThreadStateException
        • class com.sun.jdi.InvalidTypeException
        • class com.sun.jdi.InvocationException
        • class java.lang.RuntimeException
          • class com.sun.jdi.ClassNotPreparedException
          • class com.sun.jdi.request.DuplicateRequestException
          • class com.sun.jdi.InconsistentDebugInfoException
          • class com.sun.jdi.InternalException
          • class com.sun.jdi.InvalidCodeIndexException
          • class com.sun.jdi.InvalidLineNumberException
          • class com.sun.jdi.request.InvalidRequestStateException
          • class com.sun.jdi.InvalidStackFrameException
          • class com.sun.jdi.NativeMethodException
          • class com.sun.jdi.ObjectCollectedException
          • class com.sun.jdi.VMDisconnectedException
          • class com.sun.jdi.VMMismatchException
          • class com.sun.jdi.VMOutOfMemoryException
        • class com.sun.jdi.connect.VMStartException

Interface Hierarchy

  • interface com.sun.jdi.Accessible
    • interface com.sun.jdi.ArrayType
    • interface com.sun.jdi.ClassType
    • interface com.sun.jdi.Field (also extends java.lang.Comparable, com.sun.jdi.TypeComponent)
    • interface com.sun.jdi.InterfaceType
    • interface com.sun.jdi.Method (also extends java.lang.Comparable, com.sun.jdi.Locatable, com.sun.jdi.TypeComponent)
    • interface com.sun.jdi.ReferenceType (also extends java.lang.Comparable, com.sun.jdi.Type)
      • interface com.sun.jdi.ArrayType
      • interface com.sun.jdi.ClassType
      • interface com.sun.jdi.InterfaceType
    • interface com.sun.jdi.TypeComponent (also extends com.sun.jdi.Mirror)
      • interface com.sun.jdi.Field (also extends java.lang.Comparable)
      • interface com.sun.jdi.Method (also extends java.lang.Comparable, com.sun.jdi.Locatable)
  • interface java.util.Collection
    • interface com.sun.jdi.event.EventSet (also extends com.sun.jdi.Mirror, java.util.Set)
    • interface java.util.Set
      • interface com.sun.jdi.event.EventSet (also extends com.sun.jdi.Mirror)
  • interface java.lang.Comparable
    • interface com.sun.jdi.ArrayType
    • interface com.sun.jdi.ByteValue (also extends com.sun.jdi.PrimitiveValue)
    • interface com.sun.jdi.CharValue (also extends com.sun.jdi.PrimitiveValue)
    • interface com.sun.jdi.ClassType
    • interface com.sun.jdi.DoubleValue (also extends com.sun.jdi.PrimitiveValue)
    • interface com.sun.jdi.Field (also extends com.sun.jdi.TypeComponent)
    • interface com.sun.jdi.FloatValue (also extends com.sun.jdi.PrimitiveValue)
    • interface com.sun.jdi.IntegerValue (also extends com.sun.jdi.PrimitiveValue)
    • interface com.sun.jdi.InterfaceType
    • interface com.sun.jdi.LocalVariable (also extends com.sun.jdi.Mirror)
    • interface com.sun.jdi.Location (also extends com.sun.jdi.Mirror)
    • interface com.sun.jdi.LongValue (also extends com.sun.jdi.PrimitiveValue)
    • interface com.sun.jdi.Method (also extends com.sun.jdi.Locatable, com.sun.jdi.TypeComponent)
    • interface com.sun.jdi.ReferenceType (also extends com.sun.jdi.Accessible, com.sun.jdi.Type)
      • interface com.sun.jdi.ArrayType
      • interface com.sun.jdi.ClassType
      • interface com.sun.jdi.InterfaceType
    • interface com.sun.jdi.ShortValue (also extends com.sun.jdi.PrimitiveValue)
  • interface com.sun.jdi.connect.Connector
    • interface com.sun.jdi.connect.AttachingConnector
    • interface com.sun.jdi.connect.LaunchingConnector
    • interface com.sun.jdi.connect.ListeningConnector
  • interface java.util.Iterator
    • interface com.sun.jdi.event.EventIterator
  • interface com.sun.jdi.Locatable
    • interface com.sun.jdi.event.AccessWatchpointEvent
    • interface com.sun.jdi.event.BreakpointEvent
    • interface com.sun.jdi.request.BreakpointRequest (also extends com.sun.jdi.request.EventRequest)
    • interface com.sun.jdi.event.ExceptionEvent
    • interface com.sun.jdi.event.LocatableEvent (also extends com.sun.jdi.event.Event)
      • interface com.sun.jdi.event.AccessWatchpointEvent
      • interface com.sun.jdi.event.BreakpointEvent
      • interface com.sun.jdi.event.ExceptionEvent
      • interface com.sun.jdi.event.MethodEntryEvent
      • interface com.sun.jdi.event.MethodExitEvent
      • interface com.sun.jdi.event.ModificationWatchpointEvent
      • interface com.sun.jdi.event.StepEvent
      • interface com.sun.jdi.event.WatchpointEvent
        • interface com.sun.jdi.event.AccessWatchpointEvent
        • interface com.sun.jdi.event.ModificationWatchpointEvent
    • interface com.sun.jdi.Method (also extends java.lang.Comparable, com.sun.jdi.TypeComponent)
    • interface com.sun.jdi.event.MethodEntryEvent
    • interface com.sun.jdi.event.MethodExitEvent
    • interface com.sun.jdi.event.ModificationWatchpointEvent
    • interface com.sun.jdi.StackFrame (also extends com.sun.jdi.Mirror)
    • interface com.sun.jdi.event.StepEvent
    • interface com.sun.jdi.event.WatchpointEvent
      • interface com.sun.jdi.event.AccessWatchpointEvent
      • interface com.sun.jdi.event.ModificationWatchpointEvent
  • interface com.sun.jdi.Mirror
    • interface com.sun.jdi.event.AccessWatchpointEvent
    • interface com.sun.jdi.request.AccessWatchpointRequest
    • interface com.sun.jdi.ArrayReference
    • interface com.sun.jdi.ArrayType
    • interface com.sun.jdi.BooleanType
    • interface com.sun.jdi.BooleanValue
    • interface com.sun.jdi.event.BreakpointEvent
    • interface com.sun.jdi.request.BreakpointRequest (also extends com.sun.jdi.request.EventRequest, com.sun.jdi.Locatable)
    • interface com.sun.jdi.ByteType
    • interface com.sun.jdi.ByteValue (also extends java.lang.Comparable, com.sun.jdi.PrimitiveValue)
    • interface com.sun.jdi.CharType
    • interface com.sun.jdi.CharValue (also extends java.lang.Comparable, com.sun.jdi.PrimitiveValue)
    • interface com.sun.jdi.ClassLoaderReference
    • interface com.sun.jdi.ClassObjectReference
    • interface com.sun.jdi.event.ClassPrepareEvent
    • interface com.sun.jdi.request.ClassPrepareRequest
    • interface com.sun.jdi.ClassType
    • interface com.sun.jdi.event.ClassUnloadEvent
    • interface com.sun.jdi.request.ClassUnloadRequest
    • interface com.sun.jdi.DoubleType
    • interface com.sun.jdi.DoubleValue (also extends java.lang.Comparable, com.sun.jdi.PrimitiveValue)
    • interface com.sun.jdi.event.Event
      • interface com.sun.jdi.event.AccessWatchpointEvent
      • interface com.sun.jdi.event.BreakpointEvent
      • interface com.sun.jdi.event.ClassPrepareEvent
      • interface com.sun.jdi.event.ClassUnloadEvent
      • interface com.sun.jdi.event.ExceptionEvent
      • interface com.sun.jdi.event.LocatableEvent (also extends com.sun.jdi.Locatable)
        • interface com.sun.jdi.event.AccessWatchpointEvent
        • interface com.sun.jdi.event.BreakpointEvent
        • interface com.sun.jdi.event.ExceptionEvent
        • interface com.sun.jdi.event.MethodEntryEvent
        • interface com.sun.jdi.event.MethodExitEvent
        • interface com.sun.jdi.event.ModificationWatchpointEvent
        • interface com.sun.jdi.event.StepEvent
        • interface com.sun.jdi.event.WatchpointEvent
          • interface com.sun.jdi.event.AccessWatchpointEvent
          • interface com.sun.jdi.event.ModificationWatchpointEvent
      • interface com.sun.jdi.event.MethodEntryEvent
      • interface com.sun.jdi.event.MethodExitEvent
      • interface com.sun.jdi.event.ModificationWatchpointEvent
      • interface com.sun.jdi.event.StepEvent
      • interface com.sun.jdi.event.ThreadDeathEvent
      • interface com.sun.jdi.event.ThreadStartEvent
      • interface com.sun.jdi.event.VMDeathEvent
      • interface com.sun.jdi.event.VMDisconnectEvent
      • interface com.sun.jdi.event.VMStartEvent
      • interface com.sun.jdi.event.WatchpointEvent
        • interface com.sun.jdi.event.AccessWatchpointEvent
        • interface com.sun.jdi.event.ModificationWatchpointEvent
    • interface com.sun.jdi.event.EventQueue
    • interface com.sun.jdi.request.EventRequest
      • interface com.sun.jdi.request.AccessWatchpointRequest
      • interface com.sun.jdi.request.BreakpointRequest (also extends com.sun.jdi.Locatable)
      • interface com.sun.jdi.request.ClassPrepareRequest
      • interface com.sun.jdi.request.ClassUnloadRequest
      • interface com.sun.jdi.request.ExceptionRequest
      • interface com.sun.jdi.request.MethodEntryRequest
      • interface com.sun.jdi.request.MethodExitRequest
      • interface com.sun.jdi.request.ModificationWatchpointRequest
      • interface com.sun.jdi.request.StepRequest
      • interface com.sun.jdi.request.ThreadDeathRequest
      • interface com.sun.jdi.request.ThreadStartRequest
      • interface com.sun.jdi.request.VMDeathRequest
      • interface com.sun.jdi.request.WatchpointRequest
        • interface com.sun.jdi.request.AccessWatchpointRequest
        • interface com.sun.jdi.request.ModificationWatchpointRequest
    • interface com.sun.jdi.request.EventRequestManager
    • interface com.sun.jdi.event.EventSet (also extends java.util.Set)
    • interface com.sun.jdi.event.ExceptionEvent
    • interface com.sun.jdi.request.ExceptionRequest
    • interface com.sun.jdi.Field (also extends java.lang.Comparable, com.sun.jdi.TypeComponent)
    • interface com.sun.jdi.FloatType
    • interface com.sun.jdi.FloatValue (also extends java.lang.Comparable, com.sun.jdi.PrimitiveValue)
    • interface com.sun.jdi.IntegerType
    • interface com.sun.jdi.IntegerValue (also extends java.lang.Comparable, com.sun.jdi.PrimitiveValue)
    • interface com.sun.jdi.InterfaceType
    • interface com.sun.jdi.LocalVariable (also extends java.lang.Comparable)
    • interface com.sun.jdi.event.LocatableEvent (also extends com.sun.jdi.event.Event, com.sun.jdi.Locatable)
      • interface com.sun.jdi.event.AccessWatchpointEvent
      • interface com.sun.jdi.event.BreakpointEvent
      • interface com.sun.jdi.event.ExceptionEvent
      • interface com.sun.jdi.event.MethodEntryEvent
      • interface com.sun.jdi.event.MethodExitEvent
      • interface com.sun.jdi.event.ModificationWatchpointEvent
      • interface com.sun.jdi.event.StepEvent
      • interface com.sun.jdi.event.WatchpointEvent
        • interface com.sun.jdi.event.AccessWatchpointEvent
        • interface com.sun.jdi.event.ModificationWatchpointEvent
    • interface com.sun.jdi.Location (also extends java.lang.Comparable)
    • interface com.sun.jdi.LongType
    • interface com.sun.jdi.LongValue (also extends java.lang.Comparable, com.sun.jdi.PrimitiveValue)
    • interface com.sun.jdi.Method (also extends java.lang.Comparable, com.sun.jdi.Locatable, com.sun.jdi.TypeComponent)
    • interface com.sun.jdi.event.MethodEntryEvent
    • interface com.sun.jdi.request.MethodEntryRequest
    • interface com.sun.jdi.event.MethodExitEvent
    • interface com.sun.jdi.request.MethodExitRequest
    • interface com.sun.jdi.event.ModificationWatchpointEvent
    • interface com.sun.jdi.request.ModificationWatchpointRequest
    • interface com.sun.jdi.ObjectReference
      • interface com.sun.jdi.ArrayReference
      • interface com.sun.jdi.ClassLoaderReference
      • interface com.sun.jdi.ClassObjectReference
      • interface com.sun.jdi.StringReference
      • interface com.sun.jdi.ThreadGroupReference
      • interface com.sun.jdi.ThreadReference
    • interface com.sun.jdi.PathSearchingVirtualMachine
    • interface com.sun.jdi.PrimitiveType
      • interface com.sun.jdi.BooleanType
      • interface com.sun.jdi.ByteType
      • interface com.sun.jdi.CharType
      • interface com.sun.jdi.DoubleType
      • interface com.sun.jdi.FloatType
      • interface com.sun.jdi.IntegerType
      • interface com.sun.jdi.LongType
      • interface com.sun.jdi.ShortType
    • interface com.sun.jdi.PrimitiveValue
      • interface com.sun.jdi.BooleanValue
      • interface com.sun.jdi.ByteValue (also extends java.lang.Comparable)
      • interface com.sun.jdi.CharValue (also extends java.lang.Comparable)
      • interface com.sun.jdi.DoubleValue (also extends java.lang.Comparable)
      • interface com.sun.jdi.FloatValue (also extends java.lang.Comparable)
      • interface com.sun.jdi.IntegerValue (also extends java.lang.Comparable)
      • interface com.sun.jdi.LongValue (also extends java.lang.Comparable)
      • interface com.sun.jdi.ShortValue (also extends java.lang.Comparable)
    • interface com.sun.jdi.ReferenceType (also extends com.sun.jdi.Accessible, java.lang.Comparable, com.sun.jdi.Type)
      • interface com.sun.jdi.ArrayType
      • interface com.sun.jdi.ClassType
      • interface com.sun.jdi.InterfaceType
    • interface com.sun.jdi.ShortType
    • interface com.sun.jdi.ShortValue (also extends java.lang.Comparable, com.sun.jdi.PrimitiveValue)
    • interface com.sun.jdi.StackFrame (also extends com.sun.jdi.Locatable)
    • interface com.sun.jdi.event.StepEvent
    • interface com.sun.jdi.request.StepRequest
    • interface com.sun.jdi.StringReference
    • interface com.sun.jdi.event.ThreadDeathEvent
    • interface com.sun.jdi.request.ThreadDeathRequest
    • interface com.sun.jdi.ThreadGroupReference
    • interface com.sun.jdi.ThreadReference
    • interface com.sun.jdi.event.ThreadStartEvent
    • interface com.sun.jdi.request.ThreadStartRequest
    • interface com.sun.jdi.Type
      • interface com.sun.jdi.ArrayType
      • interface com.sun.jdi.BooleanType
      • interface com.sun.jdi.ByteType
      • interface com.sun.jdi.CharType
      • interface com.sun.jdi.ClassType
      • interface com.sun.jdi.DoubleType
      • interface com.sun.jdi.FloatType
      • interface com.sun.jdi.IntegerType
      • interface com.sun.jdi.InterfaceType
      • interface com.sun.jdi.LongType
      • interface com.sun.jdi.PrimitiveType
        • interface com.sun.jdi.BooleanType
        • interface com.sun.jdi.ByteType
        • interface com.sun.jdi.CharType
        • interface com.sun.jdi.DoubleType
        • interface com.sun.jdi.FloatType
        • interface com.sun.jdi.IntegerType
        • interface com.sun.jdi.LongType
        • interface com.sun.jdi.ShortType
      • interface com.sun.jdi.ReferenceType (also extends com.sun.jdi.Accessible, java.lang.Comparable)
        • interface com.sun.jdi.ArrayType
        • interface com.sun.jdi.ClassType
        • interface com.sun.jdi.InterfaceType
      • interface com.sun.jdi.ShortType
      • interface com.sun.jdi.VoidType
    • interface com.sun.jdi.TypeComponent (also extends com.sun.jdi.Accessible)
      • interface com.sun.jdi.Field (also extends java.lang.Comparable)
      • interface com.sun.jdi.Method (also extends java.lang.Comparable, com.sun.jdi.Locatable)
    • interface com.sun.jdi.Value
      • interface com.sun.jdi.ArrayReference
      • interface com.sun.jdi.BooleanValue
      • interface com.sun.jdi.ByteValue (also extends java.lang.Comparable, com.sun.jdi.PrimitiveValue)
      • interface com.sun.jdi.CharValue (also extends java.lang.Comparable, com.sun.jdi.PrimitiveValue)
      • interface com.sun.jdi.ClassLoaderReference
      • interface com.sun.jdi.ClassObjectReference
      • interface com.sun.jdi.DoubleValue (also extends java.lang.Comparable, com.sun.jdi.PrimitiveValue)
      • interface com.sun.jdi.FloatValue (also extends java.lang.Comparable, com.sun.jdi.PrimitiveValue)
      • interface com.sun.jdi.IntegerValue (also extends java.lang.Comparable, com.sun.jdi.PrimitiveValue)
      • interface com.sun.jdi.LongValue (also extends java.lang.Comparable, com.sun.jdi.PrimitiveValue)
      • interface com.sun.jdi.ObjectReference
        • interface com.sun.jdi.ArrayReference
        • interface com.sun.jdi.ClassLoaderReference
        • interface com.sun.jdi.ClassObjectReference
        • interface com.sun.jdi.StringReference
        • interface com.sun.jdi.ThreadGroupReference
        • interface com.sun.jdi.ThreadReference
      • interface com.sun.jdi.PrimitiveValue
        • interface com.sun.jdi.BooleanValue
        • interface com.sun.jdi.ByteValue (also extends java.lang.Comparable)
        • interface com.sun.jdi.CharValue (also extends java.lang.Comparable)
        • interface com.sun.jdi.DoubleValue (also extends java.lang.Comparable)
        • interface com.sun.jdi.FloatValue (also extends java.lang.Comparable)
        • interface com.sun.jdi.IntegerValue (also extends java.lang.Comparable)
        • interface com.sun.jdi.LongValue (also extends java.lang.Comparable)
        • interface com.sun.jdi.ShortValue (also extends java.lang.Comparable)
      • interface com.sun.jdi.ShortValue (also extends java.lang.Comparable, com.sun.jdi.PrimitiveValue)
      • interface com.sun.jdi.StringReference
      • interface com.sun.jdi.ThreadGroupReference
      • interface com.sun.jdi.ThreadReference
      • interface com.sun.jdi.VoidValue
    • interface com.sun.jdi.VirtualMachine
      • interface com.sun.jdi.PathSearchingVirtualMachine
    • interface com.sun.jdi.event.VMDeathEvent
    • interface com.sun.jdi.request.VMDeathRequest
    • interface com.sun.jdi.event.VMDisconnectEvent
    • interface com.sun.jdi.event.VMStartEvent
    • interface com.sun.jdi.VoidType
    • interface com.sun.jdi.VoidValue
    • interface com.sun.jdi.event.WatchpointEvent
      • interface com.sun.jdi.event.AccessWatchpointEvent
      • interface com.sun.jdi.event.ModificationWatchpointEvent
    • interface com.sun.jdi.request.WatchpointRequest
      • interface com.sun.jdi.request.AccessWatchpointRequest
      • interface com.sun.jdi.request.ModificationWatchpointRequest
  • interface java.io.Serializable
    • interface com.sun.jdi.connect.Connector.Argument
      • interface com.sun.jdi.connect.Connector.BooleanArgument
      • interface com.sun.jdi.connect.Connector.IntegerArgument
      • interface com.sun.jdi.connect.Connector.SelectedArgument
      • interface com.sun.jdi.connect.Connector.StringArgument
    • interface com.sun.jdi.connect.Connector.BooleanArgument
    • interface com.sun.jdi.connect.Connector.IntegerArgument
    • interface com.sun.jdi.connect.Connector.SelectedArgument
    • interface com.sun.jdi.connect.Connector.StringArgument
  • interface com.sun.jdi.connect.Transport
  • interface com.sun.jdi.VirtualMachineManager
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Serialized Form (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Serialized Form

Package com.sun.jdi

Class com.sun.jdi.AbsentInformationException extends Exception implements Serializable

Class com.sun.jdi.ClassNotLoadedException extends Exception implements Serializable

Serialized Fields

className

String className

Class com.sun.jdi.ClassNotPreparedException extends RuntimeException implements Serializable

Class com.sun.jdi.IncompatibleThreadStateException extends Exception implements Serializable

Class com.sun.jdi.InconsistentDebugInfoException extends RuntimeException implements Serializable

Class com.sun.jdi.InternalException extends RuntimeException implements Serializable

Serialized Fields

errorCode

int errorCode

Class com.sun.jdi.InvalidCodeIndexException extends RuntimeException implements Serializable

Class com.sun.jdi.InvalidLineNumberException extends RuntimeException implements Serializable

Class com.sun.jdi.InvalidStackFrameException extends RuntimeException implements Serializable

Class com.sun.jdi.InvalidTypeException extends Exception implements Serializable

Class com.sun.jdi.InvocationException extends Exception implements Serializable

Serialized Fields

exception

ObjectReference exception

Class com.sun.jdi.NativeMethodException extends RuntimeException implements Serializable

Class com.sun.jdi.ObjectCollectedException extends RuntimeException implements Serializable

Class com.sun.jdi.VMDisconnectedException extends RuntimeException implements Serializable

Class com.sun.jdi.VMMismatchException extends RuntimeException implements Serializable

Class com.sun.jdi.VMOutOfMemoryException extends RuntimeException implements Serializable

Package com.sun.jdi.request

Class com.sun.jdi.request.DuplicateRequestException extends RuntimeException implements Serializable

Class com.sun.jdi.request.InvalidRequestStateException extends RuntimeException implements Serializable

Package com.sun.jdi.connect

Class com.sun.jdi.connect.IllegalConnectorArgumentsException extends Exception implements Serializable

Serialized Fields

names

List names

Class com.sun.jdi.connect.VMStartException extends Exception implements Serializable

Serialized Fields

process

Process process

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


AbsentInformationException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Class AbsentInformationException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by com.sun.jdi.AbsentInformationException
All Implemented Interfaces:
Serializable
public class AbsentInformationException
extends Exception

Thrown to indicate line number or variable information is not available.

Since:
1.3
See Also:
Serialized Form

Constructor Summary
AbsentInformationException()
AbsentInformationException(String s)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

AbsentInformationException

public AbsentInformationException()

AbsentInformationException

public AbsentInformationException(String s)
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Accessible (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface Accessible

All Known Subinterfaces:
ArrayType, ClassType, Field, InterfaceType, Method, ReferenceType, TypeComponent
public interface Accessible

Provides information on the accessibility of a type or type component. Mirrors for program elements which allow an an access specifier (private, protected, public) provide information on that part of the declaration through this interface.

Since:
1.3

Method Summary
boolean | isPackagePrivate() Determines if this object mirrors a package private item.
boolean | isPrivate() Determines if this object mirrors a private item.
boolean | isProtected() Determines if this object mirrors a protected item.
boolean | isPublic() Determines if this object mirrors a public item.
int | modifiers() Returns the JavaTM programming language modifiers, encoded in an integer.

Method Detail

modifiers

public int modifiers()
Returns the JavaTM programming language modifiers, encoded in an integer.

The modifier encodings are defined in the Java Virtual Machine Specification, in the access_flag tables for classes, fields, and methods.

isPrivate

public boolean isPrivate()
Determines if this object mirrors a private item. For ArrayType, the return value depends on the array component type. For primitive arrays the return value is always false. For object arrays, the return value is the same as would be returned for the component type. For primitive classes, such as Integer.TYPE, the return value is always false.

Returns:
true for items with private access; false otherwise.

isPackagePrivate

public boolean isPackagePrivate()
Determines if this object mirrors a package private item. A package private item is declared with no access specifier. For ArrayType, the return value depends on the array component type. For primitive arrays the return value is always false. For object arrays, the return value is the same as would be returned for the component type. For primitive classes, such as Integer.TYPE, the return value is always false.

Returns:
true for items with package private access; false otherwise.

isProtected

public boolean isProtected()
Determines if this object mirrors a protected item. For ArrayType, the return value depends on the array component type. For primitive arrays the return value is always false. For object arrays, the return value is the same as would be returned for the component type. For primitive classes, such as Integer.TYPE, the return value is always false.

Returns:
true for items with private access; false otherwise.

isPublic

public boolean isPublic()
Determines if this object mirrors a public item. For ArrayType, the return value depends on the array component type. For primitive arrays the return value is always true. For object arrays, the return value is the same as would be returned for the component type. For primitive classes, such as Integer.TYPE, the return value is always true.

Returns:
true for items with public access; false otherwise.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


ArrayReference (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface ArrayReference

All Superinterfaces:
Mirror, ObjectReference, Value
public interface ArrayReference
extends ObjectReference

Provides access to an array object and its components in the target VM. Each array component is mirrored by a Value object. The array components, in aggregate, are placed in List objects instead of arrays for consistency with the rest of the API and for interoperability with other APIs.

Since:
1.3

Field Summary
Fields inherited from interface com.sun.jdi.ObjectReference
INVOKE_NONVIRTUAL, INVOKE_SINGLE_THREADED
Method Summary
Value | getValue(int index) Returns an array component value.
List | getValues() Returns all of the components in this array.
List | getValues(int index, int length) Returns a range of array components.
int | length() Returns the number of components in this array.
void | setValue(int index, Value value) Replaces an array component with another value.
void | setValues(int index, List values, int srcIndex, int length) Replaces a range of array components with other values.
void | setValues(List values) Replaces all array components with other values.
Methods inherited from interface com.sun.jdi.ObjectReference
disableCollection, enableCollection, entryCount, equals, getValue, getValues, hashCode, invokeMethod, isCollected, owningThread, referenceType, setValue, uniqueID, waitingThreads
Methods inherited from interface com.sun.jdi.Value
type
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Method Detail

length

public int length()
Returns the number of components in this array.

Returns:
the integer count of components in this array.

getValue

public Value getValue(int index)
Returns an array component value.

Parameters:
index - the index of the component to retrieve
Returns:
the Value at the given index.
Throws:
IndexOutOfBoundsException - if index is outside the range of this array, that is, if either of the following are true:
    index < 0
    index >= length()

getValues

public List getValues()
Returns all of the components in this array.

Returns:
a list of Value objects, one for each array component ordered by array index. For zero length arrays, an empty list is returned.

getValues

public List getValues(int index,
                      int length)
Returns a range of array components.

Parameters:
index - the index of the first component to retrieve
length - the number of components to retrieve, or -1 to retrieve all components to the end of this array.
Returns:
a list of Value objects, one for each requested array component ordered by array index. When there are no elements in the specified range (e.g. length is zero) an empty list is returned
Throws:
IndexOutOfBoundsException - if the range specified with index and length is not within the range of the array, that is, if either of the following are true:
    index < 0
    index > length()
or if length != -1 and either of the following are true:
    length < 0
    index + length >  length()

setValue

public void setValue(int index,
                     Value value)
              throws InvalidTypeException,
                     ClassNotLoadedException
Replaces an array component with another value.

Object values must be assignment compatible with the component type (This implies that the component type must be loaded through the declaring class's class loader). Primitive values must be either assignment compatible with the component type or must be convertible to the component type without loss of information. See JLS section 5.2 for more information on assignment compatibility.

Parameters:
value - the new value
index - the index of the component to set
Throws:
IndexOutOfBoundsException - if index is outside the range of this array, that is, if either of the following are true:
    index < 0
    index >= length()
InvalidTypeException - if the type of value is not compatible with the declared type of array components.
ClassNotLoadedException - if the array component type has not yet been loaded through the appropriate class loader.
See Also:
ArrayType.componentType()

setValues

public void setValues(List values)
               throws InvalidTypeException,
                      ClassNotLoadedException
Replaces all array components with other values. If the given list is larger in size than the array, the values at the end of the list are ignored.

Object values must be assignment compatible with the element type (This implies that the component type must be loaded through the enclosing class's class loader). Primitive values must be either assignment compatible with the component type or must be convertible to the component type without loss of information. See JLS section 5.2 for more information on assignment compatibility.

Parameters:
values - a list of Value objects to be placed in this array. If values.size() is less that the length of the array, the first values.size() elements are set.
Throws:
InvalidTypeException - if any of the new values is not compatible with the declared type of array components.
ClassNotLoadedException - if the array component type has not yet been loaded through the appropriate class loader.
See Also:
ArrayType.componentType()

setValues

public void setValues(int index,
                      List values,
                      int srcIndex,
                      int length)
               throws InvalidTypeException,
                      ClassNotLoadedException
Replaces a range of array components with other values.

Object values must be assignment compatible with the component type (This implies that the component type must be loaded through the enclosing class's class loader). Primitive values must be either assignment compatible with the component type or must be convertible to the component type without loss of information. See JLS section 5.2 for more information on assignment compatibility.

Parameters:
index - the index of the first component to set.
values - a list of Value objects to be placed in this array.
srcIndex - the index of the first source value to use.
length - the number of components to set, or -1 to set all components to the end of this array or the end of values (whichever comes first).
Throws:
InvalidTypeException - if any element of values is not compatible with the declared type of array components.
IndexOutOfBoundsException - if the array range specified with index and length is not within the range of the array, or if the source range specified with srcIndex and length is not within values, that is, if any of the following are true:
    index < 0
    index > length()
    srcIndex < 0
    srcIndex > values.size()
or if length != -1 and any of the following are true:
    length < 0
    index + length > length()
    srcIndex + length > values.size()
ClassNotLoadedException
See Also:
ArrayType.componentType()
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ArrayType (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface ArrayType

All Superinterfaces:
Accessible, Comparable, Mirror, ReferenceType, Type
public interface ArrayType
extends ReferenceType

Provides access to the class of an array and the type of its components in the target VM.

Since:
1.3
See Also:
ArrayReference

Method Summary
String | componentSignature() Gets the JNI signature of the components of this array class.
Type | componentType() Returns the component type of this array, as specified in the array declaration.
String | componentTypeName() Returns a text representation of the component type of this array.
ArrayReference | newInstance(int length) Creates a new instance of this array class in the target VM.
Methods inherited from interface com.sun.jdi.ReferenceType
allFields, allLineLocations, allLineLocations, allMethods, availableStrata, classLoader, classObject, defaultStratum, equals, failedToInitialize, fieldByName, fields, getValue, getValues, hashCode, isAbstract, isFinal, isInitialized, isPrepared, isStatic, isVerified, locationsOfLine, locationsOfLine, methods, methodsByName, methodsByName, name, nestedTypes, sourceDebugExtension, sourceName, sourceNames, sourcePaths, visibleFields, visibleMethods
Methods inherited from interface com.sun.jdi.Type
signature
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine
Methods inherited from interface java.lang.Comparable
compareTo
Methods inherited from interface com.sun.jdi.Accessible
isPackagePrivate, isPrivate, isProtected, isPublic, modifiers

Method Detail

newInstance

public ArrayReference newInstance(int length)
Creates a new instance of this array class in the target VM. The array is created with the given length and each component is initialized to is standard default value.

Parameters:
length - the number of components in the new array
Returns:
the newly created ArrayReference mirroring the new object in the target VM.

componentSignature

public String componentSignature()
Gets the JNI signature of the components of this array class. The signature describes the declared type of the components. If the components are objects, their actual type in a particular run-time context may be a subclass of the declared class.

Returns:
a string containing the JNI signature of array components.

componentTypeName

public String componentTypeName()
Returns a text representation of the component type of this array.

Returns:
a text representation of the component type.

componentType

public Type componentType()
                   throws ClassNotLoadedException
Returns the component type of this array, as specified in the array declaration.

Note: The component type of a array will always be created or loaded before the array - see the Java Virtual Machine Specification, section 5.3.3 Creating Array Classes. However, although the component type will be loaded it may not yet be prepared, in which case the type will be returned but attempts to perform some operations on the returned type (e.g. fields()) will throw a ClassNotPreparedException. Use ReferenceType.isPrepared() to determine if a reference type is prepared.

Returns:
the Type of this array's components.
Throws:
ClassNotLoadedException
See Also:
Type, Field.type() - for usage examples
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


BooleanType (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface BooleanType

All Superinterfaces:
Mirror, PrimitiveType, Type
public interface BooleanType
extends PrimitiveType

The type of all primitive boolean values accessed in the target VM. Calls to Value.type() will return an implementor of this interface.

Since:
1.3
See Also:
BooleanValue

Methods inherited from interface com.sun.jdi.Type
name, signature
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


BooleanValue (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface BooleanValue

All Superinterfaces:
Mirror, PrimitiveValue, Value
public interface BooleanValue
extends PrimitiveValue

Provides access to a primitive boolean value in the target VM.

Since:
1.3

Method Summary
boolean | equals(Object obj) Compares the specified Object with this BooleanValue for equality.
int | hashCode() Returns the hash code value for this BooleanValue.
boolean | value() Returns this BooleanValue as a boolean.
Methods inherited from interface com.sun.jdi.PrimitiveValue
booleanValue, byteValue, charValue, doubleValue, floatValue, intValue, longValue, shortValue
Methods inherited from interface com.sun.jdi.Value
type
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Method Detail

value

public boolean value()
Returns this BooleanValue as a boolean.

Returns:
the boolean mirrored by this object.

equals

public boolean equals(Object obj)
Compares the specified Object with this BooleanValue for equality.

Returns:
true if the Object is a BooleanValue and if applying "==" to the two mirrored primitives would evaluate to true; false otherwise.

hashCode

public int hashCode()
Returns the hash code value for this BooleanValue.

Returns:
the integer hash code
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Bootstrap (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Class Bootstrap

java.lang.Object
    extended by com.sun.jdi.Bootstrap
public class Bootstrap
extends Object

Initial class that provides access to the default implementation of JDI interfaces. A debugger application uses this class to access the single instance of the VirtualMachineManager interface.

Since:
1.3

Constructor Summary
Bootstrap()
Method Summary
static VirtualMachineManager virtualMachineManager()
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

Bootstrap

public Bootstrap()
Method Detail

virtualMachineManager

public static VirtualMachineManager virtualMachineManager()
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


ByteType (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface ByteType

All Superinterfaces:
Mirror, PrimitiveType, Type
public interface ByteType
extends PrimitiveType

The type of all primitive byte values accessed in the target VM. Calls to Value.type() will return an implementor of this interface.

Since:
1.3
See Also:
ByteValue

Methods inherited from interface com.sun.jdi.Type
name, signature
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ByteValue (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface ByteValue

All Superinterfaces:
Comparable, Mirror, PrimitiveValue, Value
public interface ByteValue
extends PrimitiveValue, Comparable

Provides access to a primitive byte value in the target VM.

Since:
1.3

Method Summary
boolean | equals(Object obj) Compares the specified Object with this ByteValue for equality.
int | hashCode() Returns the hash code value for this BooleanValue.
byte | value() Returns this ByteValue as a byte.
Methods inherited from interface com.sun.jdi.PrimitiveValue
booleanValue, byteValue, charValue, doubleValue, floatValue, intValue, longValue, shortValue
Methods inherited from interface com.sun.jdi.Value
type
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine
Methods inherited from interface java.lang.Comparable
compareTo

Method Detail

value

public byte value()
Returns this ByteValue as a byte.

Returns:
the byte mirrored by this object.

equals

public boolean equals(Object obj)
Compares the specified Object with this ByteValue for equality.

Returns:
true if the Object is a ByteValue and if applying "==" to the two mirrored primitives would evaluate to true; false otherwise.

hashCode

public int hashCode()
Returns the hash code value for this BooleanValue.

Returns:
the integer hash code
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


CharType (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface CharType

All Superinterfaces:
Mirror, PrimitiveType, Type
public interface CharType
extends PrimitiveType

The type of all primitive char values accessed in the target VM. Calls to Value.type() will return an implementor of this interface.

Since:
1.3
See Also:
CharValue

Methods inherited from interface com.sun.jdi.Type
name, signature
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


CharValue (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface CharValue

All Superinterfaces:
Comparable, Mirror, PrimitiveValue, Value
public interface CharValue
extends PrimitiveValue, Comparable

Provides access to a primitive char value in the target VM.

Since:
1.3

Method Summary
boolean | equals(Object obj) Compares the specified Object with this CharValue for equality.
int | hashCode() Returns the hash code value for this CharValue.
char | value() Returns this CharValue as a char.
Methods inherited from interface com.sun.jdi.PrimitiveValue
booleanValue, byteValue, charValue, doubleValue, floatValue, intValue, longValue, shortValue
Methods inherited from interface com.sun.jdi.Value
type
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine
Methods inherited from interface java.lang.Comparable
compareTo

Method Detail

value

public char value()
Returns this CharValue as a char.

Returns:
the char mirrored by this object.

equals

public boolean equals(Object obj)
Compares the specified Object with this CharValue for equality.

Returns:
true if the Object is a CharValue and if applying "==" to the two mirrored primitives would evaluate to true; false otherwise.

hashCode

public int hashCode()
Returns the hash code value for this CharValue.

Returns:
the integer hash code
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ClassLoaderReference (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface ClassLoaderReference

All Superinterfaces:
Mirror, ObjectReference, Value
public interface ClassLoaderReference
extends ObjectReference

A class loader object from the target VM. A ClassLoaderReference is an ObjectReference with additional access to classloader-specific information from the target VM. Instances ClassLoaderReference are obtained through calls to ReferenceType.classLoader()

Since:
1.3
See Also:
ObjectReference

Field Summary
Fields inherited from interface com.sun.jdi.ObjectReference
INVOKE_NONVIRTUAL, INVOKE_SINGLE_THREADED
Method Summary
List | definedClasses() Returns a list of all loaded classes that were defined by this class loader.
List | visibleClasses() Returns a list of all classes for which this class loader has been recorded as the initiating loader in the target VM.
Methods inherited from interface com.sun.jdi.ObjectReference
disableCollection, enableCollection, entryCount, equals, getValue, getValues, hashCode, invokeMethod, isCollected, owningThread, referenceType, setValue, uniqueID, waitingThreads
Methods inherited from interface com.sun.jdi.Value
type
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Method Detail

definedClasses

public List definedClasses()
Returns a list of all loaded classes that were defined by this class loader. No ordering of this list guaranteed.

The returned list will include reference types loaded at least to the point of preparation and types (like array) for which preparation is not defined.

Returns:
a List of ReferenceType objects mirroring types loaded by this class loader. The list has length 0 if no types have been defined by this classloader.

visibleClasses

public List visibleClasses()
Returns a list of all classes for which this class loader has been recorded as the initiating loader in the target VM. The list contains ReferenceTypes defined directly by this loader (as returned by definedClasses()) 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.

See the revised Java Virtual Machine Specification section 5.3 Creation and Loading for more information on the initiating classloader.

Note that unlike definedClasses() and VirtualMachine.allClasses(), some of the returned reference types may not be prepared. Attempts to perform some operations on unprepared reference types (e.g. fields()) will throw a ClassNotPreparedException. Use ReferenceType.isPrepared() to determine if a reference type is prepared.

Returns:
a List of ReferenceType objects mirroring classes initiated by this class loader. The list has length 0 if no classes are visible to this classloader.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ClassNotLoadedException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Class ClassNotLoadedException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by com.sun.jdi.ClassNotLoadedException
All Implemented Interfaces:
Serializable
public class ClassNotLoadedException
extends Exception

Thrown to indicate that the requested class has not yet been loaded through the appropriate class loader.

Due to the lazy class linking performed by many VMs, it is possible for a field or variable to be visible in a program before the associated class is loaded. Until the class is loaded all that is available is a signature string. If an attempt is made to set the value of such a field or variable from JDI, the appropriate type checking cannot be done because the destination class has not been loaded. The same is true for the element class of array elements.

It is not advisable to solve this problem by attempting a class load on the fly in this case. There are two problems in having the debugger load a class instead of waiting for it to load over the normal course of events.

  • There can be no guarantee that running the appropriate class loader won't cause a deadlock in loading the class. Class loaders can consist of arbitrary JavaTM programming language code and the class loading methods are usually synchronized. Most of the work done by a debugger happens when threads are suspended. If another application thread is suspended within the same class loader, a deadlock is very possible.
  • Changing the order in which classes are normally loaded may either mask or reveal bugs in the application. An unintrusive debugger should strive to leave unchanged the behavior of the application being debugged.
To avoid these potential problems, this exception is thrown.

Note that this exception will be thrown until the class in question is visible to the class loader of enclosing class. (That is, the class loader of the enclosing class must be an initiating class loader for the class in question.) See the Java Virtual Machine Specification for more details.

Since:
1.3
See Also:
Serialized Form

Constructor Summary
ClassNotLoadedException(String className)
ClassNotLoadedException(String className, String message)
Method Summary
 String className()
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

ClassNotLoadedException

public ClassNotLoadedException(String className)

ClassNotLoadedException

public ClassNotLoadedException(String className,
                               String message)
Method Detail

className

public String className()
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ClassNotPreparedException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Class ClassNotPreparedException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by com.sun.jdi.ClassNotPreparedException
All Implemented Interfaces:
Serializable
public class ClassNotPreparedException
extends RuntimeException

Thrown to indicate that the requested operation cannot be completed because the specified class has not yet been prepared.

Since:
1.3
See Also:
Serialized Form

Constructor Summary
ClassNotPreparedException()
ClassNotPreparedException(String s)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

ClassNotPreparedException

public ClassNotPreparedException()

ClassNotPreparedException

public ClassNotPreparedException(String s)
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ClassObjectReference (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface ClassObjectReference

All Superinterfaces:
Mirror, ObjectReference, Value
public interface ClassObjectReference
extends ObjectReference

An instance of java.lang.Class from the target VM. Use this interface to access type information for the class, array, or interface that this object reflects.

Since:
1.3
See Also:
ReferenceType

Field Summary
Fields inherited from interface com.sun.jdi.ObjectReference
INVOKE_NONVIRTUAL, INVOKE_SINGLE_THREADED
Method Summary
 ReferenceType reflectedType()
Returns the ReferenceType corresponding to this class object.
Methods inherited from interface com.sun.jdi.ObjectReference
disableCollection, enableCollection, entryCount, equals, getValue, getValues, hashCode, invokeMethod, isCollected, owningThread, referenceType, setValue, uniqueID, waitingThreads
Methods inherited from interface com.sun.jdi.Value
type
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Method Detail

reflectedType

public ReferenceType reflectedType()
Returns the ReferenceType corresponding to this class object. The returned type can be used to obtain detailed information about the class.

Returns:
the ReferenceType reflected by this class object.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ClassType (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface ClassType

All Superinterfaces:
Accessible, Comparable, Mirror, ReferenceType, Type
public interface ClassType
extends ReferenceType

A mirror of a class in the target VM. A ClassType is a refinement of ReferenceType that applies to true classes in the JLS sense of the definition (not an interface, not an array type). Any ObjectReference that mirrors an instance of such a class will have a ClassType as its type.

Since:
1.3
See Also:
ObjectReference

Field Summary
static int INVOKE_SINGLE_THREADED
Perform method invocation with only the invoking thread resumed
Method Summary
List | allInterfaces() Gets the interfaces directly and indirectly implemented by this class.
Method | concreteMethodByName(String name, String signature) Returns a the single non-abstract Method visible from this class that has the given name and signature.
List | interfaces() Gets the interfaces directly implemented by this class.
Value | invokeMethod(ThreadReference thread, Method method, List arguments, int options) Invokes the specified static Method in the target VM.
ObjectReference | newInstance(ThreadReference thread, Method method, List arguments, int options) Constructs a new instance of this type, using the given constructor Method in the target VM.
void | setValue(Field field, Value value) Assigns a value to a static field.
List | subclasses() Gets the currently loaded, direct subclasses of this class.
ClassType | superclass() Gets the superclass of this class.
Methods inherited from interface com.sun.jdi.ReferenceType
allFields, allLineLocations, allLineLocations, allMethods, availableStrata, classLoader, classObject, defaultStratum, equals, failedToInitialize, fieldByName, fields, getValue, getValues, hashCode, isAbstract, isFinal, isInitialized, isPrepared, isStatic, isVerified, locationsOfLine, locationsOfLine, methods, methodsByName, methodsByName, name, nestedTypes, sourceDebugExtension, sourceName, sourceNames, sourcePaths, visibleFields, visibleMethods
Methods inherited from interface com.sun.jdi.Type
signature
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine
Methods inherited from interface java.lang.Comparable
compareTo
Methods inherited from interface com.sun.jdi.Accessible
isPackagePrivate, isPrivate, isProtected, isPublic, modifiers

Field Detail

INVOKE_SINGLE_THREADED

public static final int INVOKE_SINGLE_THREADED
Perform method invocation with only the invoking thread resumed

See Also:
Constant Field Values
Method Detail

superclass

public ClassType superclass()
Gets the superclass of this class.

Returns:
a ClassType that mirrors the superclass of this class in the target VM. If no such class exists, returns null

interfaces

public List interfaces()
Gets the interfaces directly implemented by this class. Only the interfaces that are declared with the "implements" keyword in this class are included.

Returns:
a List of InterfaceType objects each mirroring a direct interface this ClassType in the target VM. If none exist, returns a zero length List.
Throws:
ClassNotPreparedException - if this class not yet been prepared.

allInterfaces

public List allInterfaces()
Gets the interfaces directly and indirectly implemented by this class. Interfaces returned by interfaces() are returned as well all superinterfaces.

Returns:
a List of InterfaceType objects each mirroring an interface of this ClassType in the target VM. If none exist, returns a zero length List.
Throws:
ClassNotPreparedException - if this class not yet been prepared.

subclasses

public List subclasses()
Gets the currently loaded, direct subclasses of this class. No ordering of this list is guaranteed.

Returns:
a List of ClassType objects each mirroring a loaded subclass of this class in the target VM. If no such classes exist, this method returns a zero-length list.

setValue

public void setValue(Field field,
                     Value value)
              throws InvalidTypeException,
                     ClassNotLoadedException
Assigns a value to a static field. The Field must be valid for this ClassType; that is, it must be from the mirrored object's class or a superclass of that class. The field must not be final.

Object values must be assignment compatible with the field type (This implies that the field type must be loaded through the enclosing class's class loader). Primitive values must be either assignment compatible with the field type or must be convertible to the field type without loss of information. See JLS section 5.2 for more information on assignment compatibility.

Parameters:
field - the field to set.
value - the value to be assigned.
Throws:
IllegalArgumentException - if the field is not static, the field is final, or the field does not exist in this class.
ClassNotLoadedException - if the field type has not yet been loaded through the appropriate class loader.
InvalidTypeException - if the value's type does not match the field's declared type.

invokeMethod

public Value invokeMethod(ThreadReference thread,
                          Method method,
                          List arguments,
                          int options)
                   throws InvalidTypeException,
                          ClassNotLoadedException,
                          IncompatibleThreadStateException,
                          InvocationException
Invokes the specified static Method in the target VM. The specified method can be defined in this class, or in a superclass. The method must be a static method but not a static initializer. Use newInstance(com.sun.jdi.ThreadReference, com.sun.jdi.Method, java.util.List, int) to create a new object and run its constructor.

The method invocation will occur in the specified thread. Method invocation can occur only if the specified thread has been suspended by an event which occurred in that thread. Method invocation is not supported when the target VM has been suspended through VirtualMachine.suspend() or when the specified thread is suspended through ThreadReference.suspend().

The specified method is invoked with the arguments in the specified argument list. The method invocation is synchronous; this method does not return until the invoked method returns in the target VM. If the invoked method throws an exception, this method will throw an InvocationException which contains a mirror to the exception object thrown.

Object arguments must be assignment compatible with the argument type (This implies that the argument type must be loaded through the enclosing class's class loader). Primitive arguments must be either assignment compatible with the argument type or must be convertible to the argument type without loss of information. See JLS section 5.2 for more information on assignment compatibility.

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 VirtualMachine.suspend() or ThreadReference.suspend(). 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 ThreadReference.resume(), 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 invocation can be prevented by specifying the INVOKE_SINGLE_THREADED bit flag in the options argument; 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 VirtualMachine.dispose()) the method invocation continues.

Parameters:
thread - the thread in which to invoke.
method - the Method to invoke.
arguments - the list of Value arguments bound to the invoked method. Values from the list are assigned to arguments in the order they appear in the method signature.
options - the integer bit flag options.
Returns:
a Value mirror of the invoked method's return value.
Throws:
IllegalArgumentException - if the method is not a member of this class or a superclass, if the size of the argument list does not match the number of declared arguemnts for the method, or if the method is an initializer, constructor or static intializer.
{@link - InvalidTypeException} if any argument in the argument list is not assignable to the corresponding method argument type.
ClassNotLoadedException - if any argument type has not yet been loaded through the appropriate class loader.
IncompatibleThreadStateException - if the specified thread has not been suspended by an event.
InvocationException - if the method invocation resulted in an exception in the target VM.
InvalidTypeException - If the arguments do not meet this requirement -- Object arguments must be assignment compatible with the argument type. This implies that the argument type must be loaded through the enclosing class's class loader. Primitive arguments must be either assignment compatible with the argument type or must be convertible to the argument type without loss of information. See JLS section 5.2 for more information on assignment compatibility.

newInstance

public ObjectReference newInstance(ThreadReference thread,
                                   Method method,
                                   List arguments,
                                   int options)
                            throws InvalidTypeException,
                                   ClassNotLoadedException,
                                   IncompatibleThreadStateException,
                                   InvocationException
Constructs a new instance of this type, using the given constructor Method in the target VM. The specified constructor must be defined in this class.

Instance creation will occur in the specified thread. Instance creation can occur only if the specified thread has been suspended by an event which occurred in that thread. Instance creation is not supported when the target VM has been suspended through VirtualMachine.suspend() or when the specified thread is suspended through ThreadReference.suspend().

The specified constructor is invoked with the arguments in the specified argument list. The invocation is synchronous; this method does not return until the constructor returns in the target VM. If the invoked method throws an exception, this method will throw an InvocationException which contains a mirror to the exception object thrown.

Object arguments must be assignment compatible with the argument type (This implies that the argument type must be loaded through the enclosing class's class loader). Primitive arguments must be either assignment compatible with the argument type or must be convertible to the argument type without loss of information. See JLS section 5.2 for more information on assignment compatibility.

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 VirtualMachine.suspend() or ThreadReference.suspend(). 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 ThreadReference.resume(), 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 invocation can be prevented by specifying the INVOKE_SINGLE_THREADED bit flag in the options argument; 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 VirtualMachine.dispose()) the method invocation continues.

Parameters:
thread - the thread in which to invoke.
method - the constructor Method to invoke.
arguments - the list of Value arguments bound to the invoked constructor. Values from the list are assigned to arguments in the order they appear in the constructor signature.
options - the integer bit flag options.
Returns:
an ObjectReference mirror of the newly created object.
Throws:
IllegalArgumentException - if the method is not a member of this class, if the size of the argument list does not match the number of declared arguments for the constructor, or if the method is not a constructor.
{@link - InvalidTypeException} if any argument in the argument list is not assignable to the corresponding method argument type.
ClassNotLoadedException - if any argument type has not yet been loaded through the appropriate class loader.
IncompatibleThreadStateException - if the specified thread has not been suspended by an event.
InvocationException - if the method invocation resulted in an exception in the target VM.
InvalidTypeException - If the arguments do not meet this requirement -- Object arguments must be assignment compatible with the argument type. This implies that the argument type must be loaded through the enclosing class's class loader. Primitive arguments must be either assignment compatible with the argument type or must be convertible to the argument type without loss of information. See JLS section 5.2 for more information on assignment compatibility.

concreteMethodByName

public Method concreteMethodByName(String name,
                                   String signature)
Returns a the single non-abstract Method visible from this class that has the given name and signature. See ReferenceType.methodsByName(java.lang.String, java.lang.String) for information on signature format.

The returned method (if non-null) is a component of ClassType.

Parameters:
name - the name of the method to find.
signature - the signature of the method to find
Returns:
the Method that matches the given name and signature or null if there is no match.
Throws:
ClassNotPreparedException - if methods are not yet available becasue the class has not yet been prepared.
See Also:
ReferenceType.visibleMethods(),
ReferenceType.methodsByName(java.lang.String name),
ReferenceType.methodsByName(java.lang.String name, java.lang.String signature)
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DoubleType (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface DoubleType

All Superinterfaces:
Mirror, PrimitiveType, Type
public interface DoubleType
extends PrimitiveType

The type of all primitive double values accessed in the target VM. Calls to Value.type() will return an implementor of this interface.

Since:
1.3
See Also:
DoubleValue

Methods inherited from interface com.sun.jdi.Type
name, signature
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DoubleValue (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface DoubleValue

All Superinterfaces:
Comparable, Mirror, PrimitiveValue, Value
public interface DoubleValue
extends PrimitiveValue, Comparable

Provides access to a primitive double value in the target VM.

Since:
1.3

Method Summary
boolean | equals(Object obj) Compares the specified Object with this DoubleValue for equality.
int | hashCode() Returns the hash code value for this DoubleValue.
double | value() Returns this DoubleValue as a double.
Methods inherited from interface com.sun.jdi.PrimitiveValue
booleanValue, byteValue, charValue, doubleValue, floatValue, intValue, longValue, shortValue
Methods inherited from interface com.sun.jdi.Value
type
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine
Methods inherited from interface java.lang.Comparable
compareTo

Method Detail

value

public double value()
Returns this DoubleValue as a double.

Returns:
the double mirrored by this object.

equals

public boolean equals(Object obj)
Compares the specified Object with this DoubleValue for equality.

Returns:
true if the Object is a DoubleValue and if applying "==" to the two mirrored primitives would evaluate to true; false otherwise.

hashCode

public int hashCode()
Returns the hash code value for this DoubleValue.

Returns:
the integer hash code
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Field (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface Field

All Superinterfaces:
Accessible, Comparable, Mirror, TypeComponent
public interface Field
extends TypeComponent, Comparable

A class or instance variable in the target VM. See TypeComponent for general information about Field and Method mirrors.

Since:
1.3
See Also:
ObjectReference, ReferenceType

Method Summary
boolean | equals(Object obj) Compares the specified Object with this field for equality.
int | hashCode() Returns the hash code value for this Field.
boolean | isTransient() Determine if this is a transient field.
boolean | isVolatile() Determine if this is a volatile field.
Type | type() Returns the type of this field.
String | typeName() Returns a text representation of the type of this field.
Methods inherited from interface com.sun.jdi.TypeComponent
declaringType, isFinal, isStatic, isSynthetic, name, signature
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine
Methods inherited from interface com.sun.jdi.Accessible
isPackagePrivate, isPrivate, isProtected, isPublic, modifiers
Methods inherited from interface java.lang.Comparable
compareTo

Method Detail

typeName

public String typeName()
Returns a text representation of the type of this field. Where the type is the type specified in the declaration of this field.

This type name is always available even if the type has not yet been created or loaded.

Returns:
a String representing the type of this field.

type

public Type type()
          throws ClassNotLoadedException
Returns the type of this field. Where the type is the type specified in the declaration of this field.

For example, if a target class defines:

    short s;
    Date d;
    byte[] ba;
And the JDI client defines these Field objects:
    Field sField = targetClass.fieldByName("s");
    Field dField = targetClass.fieldByName("d");
    Field baField = targetClass.fieldByName("ba");
to mirror the corresponding fields, then sField.type() is a ShortType, dField.type() is the ReferenceType for java.util.Date and ((ArrayType)(baField.type())).componentType() is a ByteType.

Note: if the type of this field is a reference type (class, interface, or array) and it has not been created or loaded by the declaring type's class loader - that is, declaringType() .classLoader(), then ClassNotLoadedException will be thrown. Also, a reference type may have been loaded but not yet prepared, in which case the type will be returned but attempts to perform some operations on the returned type (e.g. fields()) will throw a ClassNotPreparedException. Use ReferenceType.isPrepared() to determine if a reference type is prepared.

Returns:
the Type of this field.
Throws:
ClassNotLoadedException - if the type has not yet been loaded or created through the appropriate class loader.
See Also:
Type

isTransient

public boolean isTransient()
Determine if this is a transient field.

Returns:
true if this field is transient; false otherwise.

isVolatile

public boolean isVolatile()
Determine if this is a volatile field.

Returns:
true if this field is volatile; false otherwise.

equals

public boolean equals(Object obj)
Compares the specified Object with this field for equality.

Returns:
true if the Object is a Field and if both mirror the same field (declared in the same class or interface, in the same VM).

hashCode

public int hashCode()
Returns the hash code value for this Field.

Returns:
the integer hash code
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


FloatType (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface FloatType

All Superinterfaces:
Mirror, PrimitiveType, Type
public interface FloatType
extends PrimitiveType

The type of all primitive float values accessed in the target VM. Calls to Value.type() will return an implementor of this interface.

Since:
1.3
See Also:
FloatValue

Methods inherited from interface com.sun.jdi.Type
name, signature
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


FloatValue (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface FloatValue

All Superinterfaces:
Comparable, Mirror, PrimitiveValue, Value
public interface FloatValue
extends PrimitiveValue, Comparable

Provides access to a primitive float value in the target VM.

Since:
1.3

Method Summary
boolean | equals(Object obj) Compares the specified Object with this FloatValue for equality.
int | hashCode() Returns the hash code value for this FloatValue.
float | value() Returns this FloatValue as a float.
Methods inherited from interface com.sun.jdi.PrimitiveValue
booleanValue, byteValue, charValue, doubleValue, floatValue, intValue, longValue, shortValue
Methods inherited from interface com.sun.jdi.Value
type
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine
Methods inherited from interface java.lang.Comparable
compareTo

Method Detail

value

public float value()
Returns this FloatValue as a float.

Returns:
the float mirrored by this object.

equals

public boolean equals(Object obj)
Compares the specified Object with this FloatValue for equality.

Returns:
true if the Object is a FloatValue and if applying "==" to the two mirrored primitives would evaluate to true; false otherwise.

hashCode

public int hashCode()
Returns the hash code value for this FloatValue.

Returns:
the integer hash code
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


IncompatibleThreadStateException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Class IncompatibleThreadStateException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by com.sun.jdi.IncompatibleThreadStateException
All Implemented Interfaces:
Serializable
public class IncompatibleThreadStateException
extends Exception

Thrown to indicate that the requested operation cannot be completed while the specified thread is in its current state.

Since:
1.3
See Also:
Serialized Form

Constructor Summary
IncompatibleThreadStateException()
IncompatibleThreadStateException(String s)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

IncompatibleThreadStateException

public IncompatibleThreadStateException()

IncompatibleThreadStateException

public IncompatibleThreadStateException(String s)
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


InconsistentDebugInfoException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Class InconsistentDebugInfoException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by com.sun.jdi.InconsistentDebugInfoException
All Implemented Interfaces:
Serializable
public class InconsistentDebugInfoException
extends RuntimeException

Thrown to indicate that there is an inconistency in the debug information provided by the target VM. For example, this exception is thrown if there is a type mismatch between a retrieved value's runtime type and its declared type as reported by the target VM.

Since:
1.3
See Also:
Serialized Form

Constructor Summary
InconsistentDebugInfoException()
InconsistentDebugInfoException(String s)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

InconsistentDebugInfoException

public InconsistentDebugInfoException()

InconsistentDebugInfoException

public InconsistentDebugInfoException(String s)
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


IntegerType (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface IntegerType

All Superinterfaces:
Mirror, PrimitiveType, Type
public interface IntegerType
extends PrimitiveType

The type of all primitive int values accessed in the target VM. Calls to Value.type() will return an implementor of this interface.

Since:
1.3
See Also:
IntegerValue

Methods inherited from interface com.sun.jdi.Type
name, signature
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


IntegerValue (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface IntegerValue

All Superinterfaces:
Comparable, Mirror, PrimitiveValue, Value
public interface IntegerValue
extends PrimitiveValue, Comparable

Provides access to a primitive int value in the target VM.

Since:
1.3

Method Summary
boolean | equals(Object obj) Compares the specified Object with this IntegerValue for equality.
int | hashCode() Returns the hash code value for this IntegerValue.
int | value() Returns this IntegerValue as an int.
Methods inherited from interface com.sun.jdi.PrimitiveValue
booleanValue, byteValue, charValue, doubleValue, floatValue, intValue, longValue, shortValue
Methods inherited from interface com.sun.jdi.Value
type
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine
Methods inherited from interface java.lang.Comparable
compareTo

Method Detail

value

public int value()
Returns this IntegerValue as an int.

Returns:
the int mirrored by this object.

equals

public boolean equals(Object obj)
Compares the specified Object with this IntegerValue for equality.

Returns:
true if the Object is an IntegerValue and if applying "==" to the two mirrored primitives would evaluate to true; false otherwise.

hashCode

public int hashCode()
Returns the hash code value for this IntegerValue.

Returns:
the integer hash code
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


InterfaceType (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface InterfaceType

All Superinterfaces:
Accessible, Comparable, Mirror, ReferenceType, Type
public interface InterfaceType
extends ReferenceType

A mirror of an interface in the target VM. An InterfaceType is a refinement of ReferenceType that applies to true interfaces in the JLS sense of the definition (not a class, not an array type). An interface type will never be returned by ObjectReference.referenceType(), but it may be in the list of implemented interfaces for a ClassType that is returned by that method.

Since:
1.3
See Also:
ObjectReference

Method Summary
List | implementors() Gets the currently prepared classes which directly implement this interface.
List | subinterfaces() Gets the currently prepared interfaces which directly extend this interface.
List | superinterfaces() Gets the interfaces directly extended by this interface.
Methods inherited from interface com.sun.jdi.ReferenceType
allFields, allLineLocations, allLineLocations, allMethods, availableStrata, classLoader, classObject, defaultStratum, equals, failedToInitialize, fieldByName, fields, getValue, getValues, hashCode, isAbstract, isFinal, isInitialized, isPrepared, isStatic, isVerified, locationsOfLine, locationsOfLine, methods, methodsByName, methodsByName, name, nestedTypes, sourceDebugExtension, sourceName, sourceNames, sourcePaths, visibleFields, visibleMethods
Methods inherited from interface com.sun.jdi.Type
signature
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine
Methods inherited from interface java.lang.Comparable
compareTo
Methods inherited from interface com.sun.jdi.Accessible
isPackagePrivate, isPrivate, isProtected, isPublic, modifiers

Method Detail

superinterfaces

public List superinterfaces()
Gets the interfaces directly extended by this interface. The returned list contains only those interfaces this interface has declared to be extended.

Returns:
a List of InterfaceType objects each mirroring an interface extended by this interface. If none exist, returns a zero length List.
Throws:
ClassNotPreparedException - if this class not yet been prepared.

subinterfaces

public List subinterfaces()
Gets the currently prepared interfaces which directly extend this interface. The returned list contains only those interfaces that declared this interface in their "extends" clause.

Returns:
a List of InterfaceType objects each mirroring an interface extending this interface. If none exist, returns a zero length List.

implementors

public List implementors()
Gets the currently prepared classes which directly implement this interface. The returned list contains only those classes that declared this interface in their "implements" clause.

Returns:
a List of ClassType objects each mirroring a class implementing this interface. If none exist, returns a zero length List.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


InternalException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Class InternalException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by com.sun.jdi.InternalException
All Implemented Interfaces:
Serializable
public class InternalException
extends RuntimeException

Thrown to indicate that an unexpected internal error has occurred.

Since:
1.3
See Also:
Serialized Form

Constructor Summary
InternalException()
InternalException(int errorCode)
InternalException(String s)
InternalException(String s, int errorCode)
Method Summary
 int errorCode()
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

InternalException

public InternalException()

InternalException

public InternalException(String s)

InternalException

public InternalException(int errorCode)

InternalException

public InternalException(String s,
                         int errorCode)
Method Detail

errorCode

public int errorCode()
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


InvalidCodeIndexException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Class InvalidCodeIndexException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by com.sun.jdi.InvalidCodeIndexException
All Implemented Interfaces:
Serializable
Deprecated. This exception is no longer thrown

public class InvalidCodeIndexException
extends RuntimeException

Thrown to indicate that the requested operation cannot be completed because the specified code index is not valid.

Since:
1.3
See Also:
Serialized Form

Constructor Summary
InvalidCodeIndexException()
Deprecated.
InvalidCodeIndexException(String s)
Deprecated.
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

InvalidCodeIndexException

public InvalidCodeIndexException()
Deprecated.

InvalidCodeIndexException

public InvalidCodeIndexException(String s)
Deprecated.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


InvalidLineNumberException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Class InvalidLineNumberException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by com.sun.jdi.InvalidLineNumberException
All Implemented Interfaces:
Serializable
Deprecated. This exception is no longer thrown

public class InvalidLineNumberException
extends RuntimeException

Thrown to indicate that the requested operation cannot be completed because the specified line number is not valid.

Since:
1.3
See Also:
Serialized Form

Constructor Summary
InvalidLineNumberException()
Deprecated.
InvalidLineNumberException(String s)
Deprecated.
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

InvalidLineNumberException

public InvalidLineNumberException()
Deprecated.

InvalidLineNumberException

public InvalidLineNumberException(String s)
Deprecated.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


InvalidStackFrameException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Class InvalidStackFrameException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by com.sun.jdi.InvalidStackFrameException
All Implemented Interfaces:
Serializable
public class InvalidStackFrameException
extends RuntimeException

Thrown to indicate that the requested operation cannot be completed because the specified stack frame is no longer valid.

Since:
1.3
See Also:
Serialized Form

Constructor Summary
InvalidStackFrameException()
InvalidStackFrameException(String s)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

InvalidStackFrameException

public InvalidStackFrameException()

InvalidStackFrameException

public InvalidStackFrameException(String s)
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


InvalidTypeException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Class InvalidTypeException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by com.sun.jdi.InvalidTypeException
All Implemented Interfaces:
Serializable
public class InvalidTypeException
extends Exception

Thrown to indicate a type mismatch in setting the value of a field or variable.

Since:
1.3
See Also:
Serialized Form

Constructor Summary
InvalidTypeException()
InvalidTypeException(String s)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

InvalidTypeException

public InvalidTypeException()

InvalidTypeException

public InvalidTypeException(String s)
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


InvocationException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Class InvocationException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by com.sun.jdi.InvocationException
All Implemented Interfaces:
Serializable
public class InvocationException
extends Exception

Thrown to indicate an exception occurred in an invoked method within the target VM.

Since:
1.3
See Also:
Serialized Form

Constructor Summary
InvocationException(ObjectReference exception)
Method Summary
 ObjectReference exception()
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

InvocationException

public InvocationException(ObjectReference exception)
Method Detail

exception

public ObjectReference exception()
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


LocalVariable (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface LocalVariable

All Superinterfaces:
Comparable, Mirror
public interface LocalVariable
extends Mirror, Comparable

A local variable in the target VM. Each variable declared within a Method has its own LocalVariable object. Variables of the same name declared in different scopes have different LocalVariable objects. LocalVariables can be used alone to retrieve static information about their declaration, or can be used in conjunction with a StackFrame to set and get values.

Since:
1.3
See Also:
StackFrame, Method

Method Summary
boolean | equals(Object obj) Compares the specified Object with this LocalVariable for equality.
int | hashCode() Returns the hash code value for this LocalVariable.
boolean | isArgument() Determines if this variable is an argument to its method.
boolean | isVisible(StackFrame frame) Determines whether this variable can be accessed from the given StackFrame.
String | name() Gets the name of the local variable.
String | signature() Gets the JNI signature of the local variable.
Type | type() Returns the type of this variable.
String | typeName() Returns a text representation of the type of this variable.
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine
Methods inherited from interface java.lang.Comparable
compareTo

Method Detail

name

public String name()
Gets the name of the local variable.

Returns:
a string containing the name.

typeName

public String typeName()
Returns a text representation of the type of this variable. Where the type is the type specified in the declaration of this local variable.

This type name is always available even if the type has not yet been created or loaded.

Returns:
a String representing the type of this local variable.

type

public Type type()
          throws ClassNotLoadedException
Returns the type of this variable. Where the type is the type specified in the declaration of this local variable.

Note: if the type of this variable is a reference type (class, interface, or array) and it has not been created or loaded by the class loader of the enclosing class, then ClassNotLoadedException will be thrown. Also, a reference type may have been loaded but not yet prepared, in which case the type will be returned but attempts to perform some operations on the returned type (e.g. fields()) will throw a ClassNotPreparedException. Use ReferenceType.isPrepared() to determine if a reference type is prepared.

Returns:
the Type of this local variable.
Throws:
ClassNotLoadedException - if the type has not yet been loaded through the appropriate class loader.
See Also:
Type, Field.type() - for usage examples

signature

public String signature()
Gets the JNI signature of the local variable.

Returns:
a string containing the signature.
See Also:
Type Signatures

isVisible

public boolean isVisible(StackFrame frame)
Determines whether this variable can be accessed from the given StackFrame. See StackFrame.visibleVariables() for a complete description variable visibility in this interface.

Parameters:
frame - the StackFrame querying visibility
Returns:
true if this variable is visible; false otherwise.
Throws:
IllegalArgumentException - if the stack frame's method does not match this variable's method.

isArgument

public boolean isArgument()
Determines if this variable is an argument to its method.

Returns:
true if this variable is an argument; false otherwise.

equals

public boolean equals(Object obj)
Compares the specified Object with this LocalVariable for equality.

Returns:
true if the Object is a LocalVariable, if both LocalVariables are contained in the same method (as determined by Method.equals(java.lang.Object)), and if both LocalVariables mirror the same declaration within that method

hashCode

public int hashCode()
Returns the hash code value for this LocalVariable.

Returns:
the integer hash code
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Locatable (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface Locatable

All Known Subinterfaces:
AccessWatchpointEvent, BreakpointEvent, BreakpointRequest, ExceptionEvent, LocatableEvent, Method, MethodEntryEvent, MethodExitEvent, ModificationWatchpointEvent, StackFrame, StepEvent, WatchpointEvent
public interface Locatable

A mirror that has a Location.

Since:
1.3

Method Summary
 Location location()
Returns the Location of this mirror, if there is executable code associated with it.

Method Detail

location

public Location location()
Returns the Location of this mirror, if there is executable code associated with it. Note that both JavaTM programming language methods and native methods have executable code. Returns null for abstract methods, since abstract methods have no executable code.

Returns:
the Location of this mirror, or null if there is no executable code associated with it.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Location (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface Location

All Superinterfaces:
Comparable, Mirror
public interface Location
extends Mirror, Comparable

A point within the executing code of the target VM. Locations are used to identify the current position of a suspended thread (analogous to an instruction pointer or program counter register in native programs). They are also used to identify the position at which to set a breakpoint.

The availability of a line number for a location will depend on the level of debugging information available from the target VM.

Several mirror interfaces have locations. Each such mirror extends a Locatable interface.

Strata

The source information for a Location is dependent on the stratum which is used. A stratum is a source code level within a sequence of translations. For example, say the baz program is written in the programming language "Foo" then translated to the language "Bar" and finally translated into the Java programming language. The Java programming language stratum is named "Java", let's say the other strata are named "Foo" and "Bar". A given location (as viewed by the sourceName() and lineNumber() methods) might be at line 14 of "baz.foo" in the "Foo" stratum, line 23 of "baz.bar" in the "Bar" stratum and line 71 of the "Java" stratum. Note that while the Java programming language may have only one source file for a reference type, this restriction does not apply to other strata - thus each Location should be consulted to determine its source path. Queries which do not specify a stratum (sourceName(), sourcePath() and lineNumber()) use the VM's default stratum (VirtualMachine.getDefaultStratum()). If the specified stratum (whether explicitly specified by a method parameter or implicitly as the VM's default) is null or is not available in the declaring type, the declaring type's default stratum is used (declaringType().defaultStratum()). Note that in the normal case, of code that originates as Java programming language source, there will be only one stratum ("Java") and it will be returned as the default. To determine the available strata use ReferenceType.availableStrata().

Since:
1.3
See Also:
EventRequestManager, StackFrame, BreakpointEvent, ExceptionEvent, Locatable

Method Summary
long | codeIndex() Gets the code position within this location's method.
ReferenceType | declaringType() Gets the type to which this Location belongs.
boolean | equals(Object obj) Compares the specified Object with this Location for equality.
int | hashCode() Returns the hash code value for this Location.
int | lineNumber() Gets the line number of this Location.
int | lineNumber(String stratum) The line number of this Location.
Method | method() Gets the method containing this Location.
String | sourceName() Gets an identifing name for the source corresponding to this location.
String | sourceName(String stratum) Gets an identifing name for the source corresponding to this location.
String | sourcePath() Gets the path to the source corresponding to this location.
String | sourcePath(String stratum) Gets the path to the source corresponding to this location.
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine
Methods inherited from interface java.lang.Comparable
compareTo

Method Detail

declaringType

public ReferenceType declaringType()
Gets the type to which this Location belongs. Normally the declaring type is a ClassType, but executable locations also may exist within the static initializer of an InterfaceType.

Returns:
the ReferenceType containing this Location.

method

public Method method()
Gets the method containing this Location.

Returns:
the location's Method.

codeIndex

public long codeIndex()
Gets the code position within this location's method.

Returns:
the long representing the position within the method or -1 if location is within a native method.

sourceName

public String sourceName()
                  throws AbsentInformationException
Gets an identifing name for the source corresponding to this location.

This method is equivalent to sourceName(vm.getDefaultStratum()) - see sourceName(String) for more information.

Returns:
a string specifying the source
Throws:
AbsentInformationException - if the source name is not known

sourceName

public String sourceName(String stratum)
                  throws AbsentInformationException
Gets an identifing name for the source corresponding to this location. Interpretation of this string is the responsibility of the source repository mechanism.

Returned name is for the specified stratum (see the class comment for a description of strata).

The returned string is the unqualified name of the source file for this Location. For example, java.lang.Thread would return "Thread.java".

Parameters:
stratum - The stratum to retrieve information from or null for the declaring type's default stratum.
Returns:
a string specifying the source
Throws:
AbsentInformationException - if the source name is not known
Since:
1.4

sourcePath

public String sourcePath()
                  throws AbsentInformationException
Gets the path to the source corresponding to this location.

This method is equivalent to sourcePath(vm.getDefaultStratum()) - see sourcePath(String) for more information.

Returns:
a string specifying the source
Throws:
AbsentInformationException - if the source name is not known

sourcePath

public String sourcePath(String stratum)
                  throws AbsentInformationException
Gets the path to the source corresponding to this location. Interpretation of this string is the responsibility of the source repository mechanism.

Returned path is for the specified stratum (see the class comment for a description of strata).

In the reference implementation, for strata which do not explicitly specify source path (the Java programming language stratum never does), the returned string is the package name of declaringType() converted to a platform dependent path followed by the unqualified name of the source file for this Location (sourceName(stratum)). For example, on a Windows platform, java.lang.Thread would return "java\lang\Thread.java".

Parameters:
stratum - The stratum to retrieve information from or null for the declaring type's default stratum.
Returns:
a string specifying the source
Throws:
AbsentInformationException - if the source name is not known
Since:
1.4

lineNumber

public int lineNumber()
Gets the line number of this Location.

This method is equivalent to lineNumber(vm.getDefaultStratum()) - see lineNumber(String) for more information.

Returns:
an int specifying the line in the source, returns -1 if the information is not available; specifically, always returns -1 for native methods.

lineNumber

public int lineNumber(String stratum)
The line number of this Location. The line number is relative to the source specified by sourceName(stratum).

Returned line number is for the specified stratum (see the class comment for a description of strata).

Parameters:
stratum - The stratum to retrieve information from or null for the declaring type's default stratum.
Returns:
an int specifying the line in the source, returns -1 if the information is not available; specifically, always returns -1 for native methods.
Since:
1.4

equals

public boolean equals(Object obj)
Compares the specified Object with this Location for equality.

Returns:
true if the Object is a Location and if it refers to the same point in the same VM as this Location.

hashCode

public int hashCode()
Returns the hash code value for this Location.

Returns:
the integer hash code
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


LongType (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface LongType

All Superinterfaces:
Mirror, PrimitiveType, Type
public interface LongType
extends PrimitiveType

The type of all primitive long values accessed in the target VM. Calls to Value.type() will return an implementor of this interface.

Since:
1.3
See Also:
LongValue

Methods inherited from interface com.sun.jdi.Type
name, signature
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


LongValue (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface LongValue

All Superinterfaces:
Comparable, Mirror, PrimitiveValue, Value
public interface LongValue
extends PrimitiveValue, Comparable

Provides access to a primitive long value in the target VM.

Since:
1.3

Method Summary
boolean | equals(Object obj) Compares the specified Object with this LongValue for equality.
int | hashCode() Returns the hash code value for this LongValue.
long | value() Returns this LongValue as a long.
Methods inherited from interface com.sun.jdi.PrimitiveValue
booleanValue, byteValue, charValue, doubleValue, floatValue, intValue, longValue, shortValue
Methods inherited from interface com.sun.jdi.Value
type
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine
Methods inherited from interface java.lang.Comparable
compareTo

Method Detail

value

public long value()
Returns this LongValue as a long.

Returns:
the long mirrored by this object.

equals

public boolean equals(Object obj)
Compares the specified Object with this LongValue for equality.

Returns:
true if the Object is a LongValue and if applying "==" to the two mirrored primitives would evaluate to true; false otherwise.

hashCode

public int hashCode()
Returns the hash code value for this LongValue.

Returns:
the integer hash code
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Method (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface Method

All Superinterfaces:
Accessible, Comparable, Locatable, Mirror, TypeComponent
public interface Method
extends TypeComponent, Locatable, Comparable

A static or instance method in the target VM. See TypeComponent for general information about Field and Method mirrors.

Since:
1.3
See Also:
ObjectReference, ReferenceType

Method Summary
List | allLineLocations() Returns a list containing a Location object for each executable source line in this method.
List | allLineLocations(String stratum, String sourceName) Returns a list containing a Location object for each executable source line in this method.
List | arguments() Returns a list containing each LocalVariable that is declared as an argument of this method.
List | argumentTypeNames() Returns a list containing a text representation of the type of each formal parameter of this method.
List | argumentTypes() Returns a list containing the type of each formal parameter of this method.
byte[] | bytecodes() Returns an array containing the bytecodes for this method.
boolean | equals(Object obj) Compares the specified Object with this method for equality.
int | hashCode() Returns the hash code value for this Method.
boolean | isAbstract() Determine if this method is abstract.
boolean | isConstructor() Determine if this method is a constructor.
boolean | isNative() Determine if this method is native.
boolean | isObsolete() Determine if this method is obsolete.
boolean | isStaticInitializer() Determine if this method is a static initializer.
boolean | isSynchronized() Determine if this method is synchronized.
Location | location() Returns the Location of this method, if there is executable code associated with it.
Location | locationOfCodeIndex(long codeIndex) Returns a Location for the given code index.
List | locationsOfLine(int lineNumber) Returns a List containing all Location objects that map to the given line number.
List | locationsOfLine(String stratum, String sourceName, int lineNumber) Returns a List containing all Location objects that map to the given line number and source name.
Type | returnType() Returns the return type, as specified in the declaration of this method.
String | returnTypeName() Returns a text representation of the return type, as specified in the declaration of this method.
List | variables() Returns a list containing each LocalVariable declared in this method.
List | variablesByName(String name) Returns a list containing each LocalVariable of a given name in this method.
Methods inherited from interface com.sun.jdi.TypeComponent
declaringType, isFinal, isStatic, isSynthetic, name, signature
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine
Methods inherited from interface com.sun.jdi.Accessible
isPackagePrivate, isPrivate, isProtected, isPublic, modifiers
Methods inherited from interface java.lang.Comparable
compareTo

Method Detail

returnTypeName

public String returnTypeName()
Returns a text representation of the return type, as specified in the declaration of this method.

This type name is always available even if the type has not yet been created or loaded.

Returns:
a String containing the return type name.

returnType

public Type returnType()
                throws ClassNotLoadedException
Returns the return type, as specified in the declaration of this method.

Note: if the return type of this method is a reference type (class, interface, or array) and it has not been created or loaded by the declaring type's class loader - that is, declaringType() .classLoader(), then ClassNotLoadedException will be thrown. Also, a reference type may have been loaded but not yet prepared, in which case the type will be returned but attempts to perform some operations on the returned type (e.g. fields()) will throw a ClassNotPreparedException. Use ReferenceType.isPrepared() to determine if a reference type is prepared.

Returns:
the return Type of this method.
Throws:
ClassNotLoadedException - if the type has not yet been created or loaded through the appropriate class loader.
See Also:
Type, Field.type() - for usage examples

argumentTypeNames

public List argumentTypeNames()
Returns a list containing a text representation of the type of each formal parameter of this method.

This list is always available even if the types have not yet been created or loaded.

Returns:
a List of String, one List element for each parameter of this method. Each element represents the type of a formal parameter as specified at compile-time.

argumentTypes

public List argumentTypes()
                   throws ClassNotLoadedException
Returns a list containing the type of each formal parameter of this method.

Note: if there is any parameter whose type is a reference type (class, interface, or array) and it has not been created or loaded by the declaring type's class loader - that is, declaringType() .classLoader(), then ClassNotLoadedException will be thrown. Also, a reference type may have been loaded but not yet prepared, in which case the list will be returned but attempts to perform some operations on the type (e.g. fields()) will throw a ClassNotPreparedException. Use ReferenceType.isPrepared() to determine if a reference type is prepared.

Returns:
return a List of Type, one List element for each parameter of this method. Each element represents the type of a formal parameter as specified at compile-time.
Throws:
ClassNotLoadedException - if the type has not yet been loaded through the appropriate class loader.
See Also:
Type

isAbstract

public boolean isAbstract()
Determine if this method is abstract.

Returns:
true if the method is declared abstract; false otherwise.

isSynchronized

public boolean isSynchronized()
Determine if this method is synchronized.

Returns:
true if the method is declared synchronized; false otherwise.

isNative

public boolean isNative()
Determine if this method is native.

Returns:
true if the method is declared native; false otherwise.

isConstructor

public boolean isConstructor()
Determine if this method is a constructor.

Returns:
true if the method is a constructor; false otherwise.

isStaticInitializer

public boolean isStaticInitializer()
Determine if this method is a static initializer.

Returns:
true if the method is a static initializer; false otherwise.

isObsolete

public boolean isObsolete()
Determine if this method is obsolete.

Returns:
true if this method has been replaced by a non-equivalent method using VirtualMachine.redefineClasses(java.util.Map).
Since:
1.4

allLineLocations

public List allLineLocations()
                      throws AbsentInformationException
Returns a list containing a Location object for each executable source line in this method.

This method is equivalent to allLineLocations(vm.getDefaultStratum(),null) - see allLineLocations(String,String) for more information.

Returns:
a List of all source line Location objects.
Throws:
AbsentInformationException - if there is no line number information for this (non-native, non-abstract) method.

allLineLocations

public List allLineLocations(String stratum,
                             String sourceName)
                      throws AbsentInformationException
Returns a list containing a Location object for each executable source line in this method.

Each location maps a source line to a range of code indices. The beginning of the range can be determined through Location.codeIndex(). The returned list is ordered by code index (from low to high).

The returned list may contain multiple locations for a particular line number, if the compiler and/or VM has mapped that line to two or more disjoint code index ranges.

If the method is native or abstract, an empty list is returned.

Returned list is for the specified stratum (see Location for a description of strata).

Parameters:
stratum - The stratum to retrieve information from or null for the ReferenceType.defaultStratum()
sourceName - Return locations only within this source file or null to return locations.
Returns:
a List of all source line Location objects.
Throws:
AbsentInformationException - if there is no line number information for this (non-native, non-abstract) method. Or if sourceName is non-null and source name information is not present.
Since:
1.4

locationsOfLine

public List locationsOfLine(int lineNumber)
                     throws AbsentInformationException
Returns a List containing all Location objects that map to the given line number.

This method is equivalent to locationsOfLine(vm.getDefaultStratum(), null, lineNumber) - see locationsOfLine(java.lang.String,java.lang.String,int) for more information.

Parameters:
lineNumber - the line number
Returns:
a List of Location objects that map to the given line number.
Throws:
AbsentInformationException - if there is no line number information for this method.

locationsOfLine

public List locationsOfLine(String stratum,
                            String sourceName,
                            int lineNumber)
                     throws AbsentInformationException
Returns a List containing all Location objects that map to the given line number and source name.

Returns a list containing each Location that maps to the given line. The returned list will contain a location for each disjoint range of code indices that have been assigned to the given line by the compiler and/or VM. Each returned location corresponds to the beginning of this range. An empty list will be returned if there is no executable code at the specified line number; specifically, native and abstract methods will always return an empty list.

Returned list is for the specified stratum (see Location for a description of strata).

Parameters:
stratum - the stratum to use for comparing line number and source name, or null to use the default stratum
sourceName - the source name containing the line number, or null to match all source names
lineNumber - the line number
Returns:
a List of Location objects that map to the given line number.
Throws:
AbsentInformationException - if there is no line number information for this method. Or if sourceName is non-null and source name information is not present.
Since:
1.4

locationOfCodeIndex

public Location locationOfCodeIndex(long codeIndex)
Returns a Location for the given code index.

Returns:
the Location corresponding to the given code index or null if the specified code index is not a valid code index for this method (native and abstract methods will always return null).

variables

public List variables()
               throws AbsentInformationException
Returns a list containing each LocalVariable declared in this method. The list includes any variable declared in any scope within the method. It may contain multiple variables of the same name declared within disjoint scopes. Arguments are considered local variables and will be present in the returned list.

Returns:
the list of LocalVariable objects which mirror local variables declared in this method in the target VM. If there are no local variables, a zero-length list is returned.
Throws:
AbsentInformationException - if there is no variable information for this method. Generally, local variable information is not available for native or abstract methods (that is, their argument name information is not available), thus they will throw this exception.

variablesByName

public List variablesByName(String name)
                     throws AbsentInformationException
Returns a list containing each LocalVariable of a given name in this method. Multiple variables can be returned if the same variable name is used in disjoint scopes within the method.

Returns:
the list of LocalVariable objects of the given name. If there are no matching local variables, a zero-length list is returned.
Throws:
AbsentInformationException - if there is no variable information for this method. Generally, local variable information is not available for native or abstract methods (that is, their argument name information is not available), thus they will throw this exception.

arguments

public List arguments()
               throws AbsentInformationException
Returns a list containing each LocalVariable that is declared as an argument of this method.

Returns:
the list of LocalVariable arguments. If there are no arguments, a zero-length list is returned.
Throws:
AbsentInformationException - if there is no variable information for this method. Generally, local variable information is not available for native or abstract methods (that is, their argument name information is not available), thus they will throw this exception.

bytecodes

public byte[] bytecodes()
Returns an array containing the bytecodes for this method.

Not all target virtual machines support this operation. Use VirtualMachine.canGetBytecodes() to determine if the operation is supported.

Returns:
the array of bytecodes; abstract and native methods will return a zero-length array.
Throws:
UnsupportedOperationException - if the target virtual machine does not support the retrieval of bytecodes.

location

public Location location()
Returns the Location of this method, if there is executable code associated with it.

Specified by:
location in interface Locatable
Returns:
the Location of this mirror, or null if this is an abstract method; native methods will return a Location object whose codeIndex is -1.

equals

public boolean equals(Object obj)
Compares the specified Object with this method for equality.

Returns:
true if the Object is a method and if both mirror the same method (declared in the same class or interface, in the same VM).

hashCode

public int hashCode()
Returns the hash code value for this Method.

Returns:
the integer hash code
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Mirror (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface Mirror

All Known Subinterfaces:
AccessWatchpointEvent, AccessWatchpointRequest, ArrayReference, ArrayType, BooleanType, BooleanValue, BreakpointEvent, BreakpointRequest, ByteType, ByteValue, CharType, CharValue, ClassLoaderReference, ClassObjectReference, ClassPrepareEvent, ClassPrepareRequest, ClassType, ClassUnloadEvent, ClassUnloadRequest, DoubleType, DoubleValue, Event, EventQueue, EventRequest, EventRequestManager, EventSet, ExceptionEvent, ExceptionRequest, Field, FloatType, FloatValue, IntegerType, IntegerValue, InterfaceType, LocalVariable, LocatableEvent, Location, LongType, LongValue, Method, MethodEntryEvent, MethodEntryRequest, MethodExitEvent, MethodExitRequest, ModificationWatchpointEvent, ModificationWatchpointRequest, ObjectReference, PathSearchingVirtualMachine, PrimitiveType, PrimitiveValue, ReferenceType, ShortType, ShortValue, StackFrame, StepEvent, StepRequest, StringReference, ThreadDeathEvent, ThreadDeathRequest, ThreadGroupReference, ThreadReference, ThreadStartEvent, ThreadStartRequest, Type, TypeComponent, Value, VirtualMachine, VMDeathEvent, VMDeathRequest, VMDisconnectEvent, VMStartEvent, VoidType, VoidValue, WatchpointEvent, WatchpointRequest
public interface Mirror

A proxy used by a debugger to examine or manipulate some entity in another virtual machine. Mirror is the root of the interface hierarchy for this package. Mirrors can be proxies for objects in the target VM (ObjectReference), primitive values (for example, IntegerValue), types (for example, ReferenceType), dynamic application state (for example, StackFrame), and even debugger-specific constructs (for example, BreakpointRequest). The VirtualMachine itself is also considered a mirror, representing the composite state of the target VM.

There is no guarantee that a particular entity in the target VM will map to a single instance of Mirror. Implementors are free to decide whether a single mirror will be used for some or all mirrors. Clients of this interface should always use equals to compare two mirrors for equality.

Any method on a Mirror that takes a Mirror as an parameter directly or indirectly (e.g., as a element in a List) will throw VMMismatchException if the mirrors are from different virtual machines.

Since:
1.3
See Also:
VirtualMachine

Method Summary
String | toString() Returns a String describing this mirror
VirtualMachine | virtualMachine() Gets the VirtualMachine to which this Mirror belongs.

Method Detail

virtualMachine

public VirtualMachine virtualMachine()
Gets the VirtualMachine to which this Mirror belongs. A Mirror must be associated with a VirtualMachine to have any meaning.

Returns:
the VirtualMachine for which this mirror is a proxy.

toString

public String toString()
Returns a String describing this mirror

Returns:
a string describing this mirror.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NativeMethodException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Class NativeMethodException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by com.sun.jdi.NativeMethodException
All Implemented Interfaces:
Serializable
public class NativeMethodException
extends RuntimeException

Thrown to indicate an operation cannot be completed because it is not valid for a native method.

Since:
1.3
See Also:
Serialized Form

Constructor Summary
NativeMethodException()
NativeMethodException(String message)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

NativeMethodException

public NativeMethodException()

NativeMethodException

public NativeMethodException(String message)
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ObjectCollectedException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Class ObjectCollectedException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by com.sun.jdi.ObjectCollectedException
All Implemented Interfaces:
Serializable
public class ObjectCollectedException
extends RuntimeException

Thrown to indicate that the requested operation cannot be completed because the specified object has been garbage collected.

Since:
1.3
See Also:
Serialized Form

Constructor Summary
ObjectCollectedException()
ObjectCollectedException(String s)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

ObjectCollectedException

public ObjectCollectedException()

ObjectCollectedException

public ObjectCollectedException(String s)
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ObjectReference (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface ObjectReference

All Superinterfaces:
Mirror, Value
All Known Subinterfaces:
ArrayReference, ClassLoaderReference, ClassObjectReference, StringReference, ThreadGroupReference, ThreadReference
public interface ObjectReference
extends Value

An object that currently exists in the target VM. An ObjectReference mirrors only the object itself and is not specific to any Field or LocalVariable to which it is currently assigned. An ObjectReference can have 0 or more references from field(s) and/or variable(s).

Any method on ObjectReference which directly or indirectly takes ObjectReference as an parameter may throw VMDisconnectedException if the target VM is disconnected and the VMDisconnectEvent has been or is available to be read from the EventQueue.

Any method on ObjectReference which directly or indirectly takes ObjectReference as an parameter may throw VMOutOfMemoryException if the target VM has run out of memory.

Any method on ObjectReference or which directly or indirectly takes ObjectReference as parameter may throw ObjectCollectedException if the mirrored object has been garbage collected.

Since:
1.3

Field Summary
static int | INVOKE_NONVIRTUAL Perform non-virtual method invocation
static int | INVOKE_SINGLE_THREADED Perform method invocation with only the invoking thread resumed
Method Summary
void | disableCollection() Prevents garbage collection for this object.
void | enableCollection() Permits garbage collection for this object.
int | entryCount() Returns the number times this object's monitor has been entered by the current owning thread.
boolean | equals(Object obj) Compares the specified Object with this ObjectReference for equality.
Value | getValue(Field sig) Gets the value of a given instance or static field in this object.
Map | getValues(List fields) Gets the value of multiple instance and/or static fields in this object.
int | hashCode() Returns the hash code value for this ObjectReference.
Value | invokeMethod(ThreadReference thread, Method method, List arguments, int options) Invokes the specified Method on this object in the target VM.
boolean | isCollected() Determines if this object has been garbage collected in the target VM.
ThreadReference | owningThread() Returns an ThreadReference for the thread, if any, which currently owns this object's monitor.
ReferenceType | referenceType() Gets the ReferenceType that mirrors the type of this object.
void | setValue(Field field, Value value) Sets the value of a given instance or static field in this object.
long | uniqueID() Returns a unique identifier for this ObjectReference.
List | waitingThreads() Returns a List containing a ThreadReference for each thread currently waiting for this object's monitor.
Methods inherited from interface com.sun.jdi.Value
type
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Field Detail

INVOKE_SINGLE_THREADED

public static final int INVOKE_SINGLE_THREADED
Perform method invocation with only the invoking thread resumed

See Also:
Constant Field Values

INVOKE_NONVIRTUAL

public static final int INVOKE_NONVIRTUAL
Perform non-virtual method invocation

See Also:
Constant Field Values
Method Detail

referenceType

public ReferenceType referenceType()
Gets the ReferenceType that mirrors the type of this object. The type may be a subclass or implementor of the declared type of any field or variable which currently holds it. For example, right after the following statement.

Object obj = new String("Hello, world!");

The ReferenceType of obj will mirror java.lang.String and not java.lang.Object.

The type of an object never changes, so this method will always return the same ReferenceType over the lifetime of the mirrored object.

The returned ReferenceType will be a ClassType or ArrayType and never an InterfaceType.

Returns:
the ReferenceType for this object.

getValue

public Value getValue(Field sig)
Gets the value of a given instance or static field in this object. The Field must be valid for this ObjectReference; that is, it must be from the mirrored object's class or a superclass of that class.

Parameters:
sig - the field containing the requested value
Returns:
the Value of the instance field.
Throws:
IllegalArgumentException - if the field is not valid for this object's class.

getValues

public Map getValues(List fields)
Gets the value of multiple instance and/or static fields in this object. The Fields must be valid for this ObjectReference; that is, they must be from the mirrored object's class or a superclass of that class.

Parameters:
fields - a list of Field objects containing the requested values.
Returns:
a Map of the requested Field objects with their Value.
Throws:
IllegalArgumentException - if any field is not valid for this object's class.

setValue

public void setValue(Field field,
                     Value value)
              throws InvalidTypeException,
                     ClassNotLoadedException
Sets the value of a given instance or static field in this object. The Field must be valid for this ObjectReference; that is, it must be from the mirrored object's class or a superclass of that class. If static, the field must not be final.

Object values must be assignment compatible with the field type (This implies that the field type must be loaded through the enclosing class's class loader). Primitive values must be either assignment compatible with the field type or must be convertible to the field type without loss of information. See the JavaTM Language Specification. section 5.2 for more information on assignment compatibility.

Parameters:
field - the field containing the requested value
value - the new value to assign
Throws:
IllegalArgumentException - if the field is not valid for this object's class.
InvalidTypeException - if the value's type does not match the field's type.
ClassNotLoadedException - if 'value' is not null, and the field type has not yet been loaded through the appropriate class loader.

invokeMethod

public Value invokeMethod(ThreadReference thread,
                          Method method,
                          List arguments,
                          int options)
                   throws InvalidTypeException,
                          ClassNotLoadedException,
                          IncompatibleThreadStateException,
                          InvocationException
Invokes the specified Method on this object in the target VM. The specified method can be defined in this object's class, in a superclass of this object's class, or in an interface implemented by this object. The method may be a static method or an instance method, but not a static initializer or constructor. Use ClassType.newInstance(com.sun.jdi.ThreadReference, com.sun.jdi.Method, java.util.List, int) to create a new object and run its constructor.

The method invocation will occur in the specified thread. Method invocation can occur only if the specified thread has been suspended by an event which occurred in that thread. Method invocation is not supported when the target VM has been suspended through VirtualMachine.suspend() or when the specified thread is suspended through ThreadReference.suspend().

The specified method is invoked with the arguments in the specified argument list. The method invocation is synchronous; this method does not return until the invoked method returns in the target VM. If the invoked method throws an exception, this method will throw an InvocationException which contains a mirror to the exception object thrown.

Object arguments must be assignment compatible with the argument type (This implies that the argument type must be loaded through the enclosing class's class loader). Primitive arguments must be either assignment compatible with the argument type or must be convertible to the argument type without loss of information. See the Java Language Specification. section 5.2 for more information on assignment compatibility.

By default, the method is invoked using dynamic lookup as documented in the Java Language Specification second edition, section 15.12.4.4; in particular, overriding based on the runtime type of the object mirrored by this ObjectReference will occur. This behavior can be changed by specifying the INVOKE_NONVIRTUAL bit flag in the options argument. If this flag is set, the specified method is invoked whether or not it is overridden for this object's runtime type. The method, in this case, must not belong to an interface and must not be abstract. This option is useful for performing method invocations like those done with the super keyword in the Java programming language.

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 VirtualMachine.suspend() or ThreadReference.suspend(). 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 ThreadReference.resume(), 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 invocation can be prevented by specifying the INVOKE_SINGLE_THREADED bit flag in the options argument; 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 VirtualMachine.dispose()) the method invocation continues.

Parameters:
thread - the thread in which to invoke.
method - the Method to invoke.
arguments - the list of Value arguments bound to the invoked method. Values from the list are assigned to arguments in the order they appear in the method signature.
options - the integer bit flag options.
Returns:
a Value mirror of the invoked method's return value.
Throws:
IllegalArgumentException - if the method is not a member of this object's class, if the size of the argument list does not match the number of declared arguemnts for the method, if the method is a constructor or static intializer, or if INVOKE_NONVIRTUAL is specified and the method is either abstract or an interface member.
{@link - InvalidTypeException} if any argument in the argument list is not assignable to the corresponding method argument type.
ClassNotLoadedException - if any argument type has not yet been loaded through the appropriate class loader.
IncompatibleThreadStateException - if the specified thread has not been suspended by an event.
InvocationException - if the method invocation resulted in an exception in the target VM.
InvalidTypeException - If the arguments do not meet this requirement -- Object arguments must be assignment compatible with the argument type. This implies that the argument type must be loaded through the enclosing class's class loader. Primitive arguments must be either assignment compatible with the argument type or must be convertible to the argument type without loss of information. See JLS section 5.2 for more information on assignment compatibility.

disableCollection

public void disableCollection()
Prevents garbage collection for this object. By default all ObjectReference values returned by JDI may be collected at any time the target VM is running. A call to this method guarantees that the object will not be collected. enableCollection() can be used to allow collection once again.

Calls to this method are counted. Every call to this method requires a corresponding call to enableCollection() before garbage collection is re-enabled.

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.

enableCollection

public void enableCollection()
Permits garbage collection for this object. By default all ObjectReference values returned by JDI may be collected at any time the target VM is running. A call to this method is necessary only if garbage collection was previously disabled with disableCollection().

isCollected

public boolean isCollected()
Determines if this object has been garbage collected in the target VM.

Returns:
true if this ObjectReference has been collected; false otherwise.

uniqueID

public long uniqueID()
Returns a unique identifier for this ObjectReference. It is guaranteed to be unique among all ObjectReferences from the same VM that have not yet been disposed. The guarantee applies as long as this ObjectReference has not yet been disposed.

Returns:
a long unique ID

waitingThreads

public List waitingThreads()
                    throws IncompatibleThreadStateException
Returns a List containing a ThreadReference for each thread currently waiting for this object's monitor. See ThreadReference.currentContendedMonitor() for information about when a thread is considered to be waiting for a monitor.

Not all target VMs support this operation. See VirtualMachine#canGetMonitorInfo to determine if the operation is supported.

Returns:
a List of ThreadReference objects. The list has zero length if no threads are waiting for the monitor.
Throws:
UnsupportedOperationException - if the target VM does not support this operation.
IncompatibleThreadStateException - if any waiting thread is not suspended in the target VM

owningThread

public ThreadReference owningThread()
                             throws IncompatibleThreadStateException
Returns an ThreadReference for the thread, if any, which currently owns this object's monitor. See ThreadReference.ownedMonitors() for a definition of ownership.

Not all target VMs support this operation. See VirtualMachine#canGetMonitorInfo to determine if the operation is supported.

Returns:
the ThreadReference which currently owns the monitor, or null if it is unowned.
Throws:
UnsupportedOperationException - if the target VM does not support this operation.
IncompatibleThreadStateException - if the owning thread is not suspended in the target VM

entryCount

public int entryCount()
               throws IncompatibleThreadStateException
Returns the number times this object's monitor has been entered by the current owning thread. See ThreadReference.ownedMonitors() for a definition of ownership.

Not all target VMs support this operation. See VirtualMachine#canGetMonitorInfo to determine if the operation is supported.

Returns:
the integer count of the number of entries.
Throws:
UnsupportedOperationException - if the target VM does not support this operation.
IncompatibleThreadStateException - if the owning thread is not suspended in the target VM
See Also:
owningThread()

equals

public boolean equals(Object obj)
Compares the specified Object with this ObjectReference for equality.

Returns:
true if the Object is an ObjectReference, if the ObjectReferences belong to the same VM, and if applying the "==" operator on the mirrored objects in that VM evaluates to true.

hashCode

public int hashCode()
Returns the hash code value for this ObjectReference.

Returns:
the integer hash code
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


com.sun.jdi (Java Debug Interface)

 com.sun.jdi
Interfaces
Accessible
ArrayReference
ArrayType
BooleanType
BooleanValue
ByteType
ByteValue
CharType
CharValue
ClassLoaderReference
ClassObjectReference
ClassType
DoubleType
DoubleValue
Field
FloatType
FloatValue
IntegerType
IntegerValue
InterfaceType
LocalVariable
Locatable
Location
LongType
LongValue
Method
Mirror
ObjectReference
PathSearchingVirtualMachine
PrimitiveType
PrimitiveValue
ReferenceType
ShortType
ShortValue
StackFrame
StringReference
ThreadGroupReference
ThreadReference
Type
TypeComponent
Value
VirtualMachine
VirtualMachineManager
VoidType
VoidValue
Classes
Bootstrap
Exceptions
AbsentInformationException
ClassNotLoadedException
ClassNotPreparedException
IncompatibleThreadStateException
InconsistentDebugInfoException
InternalException
InvalidCodeIndexException
InvalidLineNumberException
InvalidStackFrameException
InvalidTypeException
InvocationException
NativeMethodException
ObjectCollectedException
VMDisconnectedException
VMMismatchException
VMOutOfMemoryException


com.sun.jdi (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package 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.

See:
Description

Interface Summary
Accessible | Provides information on the accessibility of a type or type component.
ArrayReference | Provides access to an array object and its components in the target VM.
ArrayType | Provides access to the class of an array and the type of its components in the target VM.
BooleanType | The type of all primitive boolean values accessed in the target VM.
BooleanValue | Provides access to a primitive boolean value in the target VM.
ByteType | The type of all primitive byte values accessed in the target VM.
ByteValue | Provides access to a primitive byte value in the target VM.
CharType | The type of all primitive char values accessed in the target VM.
CharValue | Provides access to a primitive char value in the target VM.
ClassLoaderReference | A class loader object from the target VM.
ClassObjectReference | An instance of java.lang.Class from the target VM.
ClassType | A mirror of a class in the target VM.
DoubleType | The type of all primitive double values accessed in the target VM.
DoubleValue | Provides access to a primitive double value in the target VM.
Field | A class or instance variable in the target VM.
FloatType | The type of all primitive float values accessed in the target VM.
FloatValue | Provides access to a primitive float value in the target VM.
IntegerType | The type of all primitive int values accessed in the target VM.
IntegerValue | Provides access to a primitive int value in the target VM.
InterfaceType | A mirror of an interface in the target VM.
LocalVariable | A local variable in the target VM.
Locatable | A mirror that has a Location.
Location | A point within the executing code of the target VM.
LongType | The type of all primitive long values accessed in the target VM.
LongValue | Provides access to a primitive long value in the target VM.
Method | A static or instance method in the target VM.
Mirror | A proxy used by a debugger to examine or manipulate some entity in another virtual machine.
ObjectReference | An object that currently exists in the target VM.
PathSearchingVirtualMachine | A virtual machine which searches for classes through paths
PrimitiveType | The type associated with non-object values in a target VM.
PrimitiveValue | The value assigned to a field or variable of primitive type in a target VM.
ReferenceType | The type of an object in a target VM.
ShortType | The type of all primitive short values accessed in the target VM.
ShortValue | Provides access to a primitive short value in the target VM.
StackFrame | The state of one method invocation on a thread's call stack.
StringReference | A string object from the target VM.
ThreadGroupReference | A thread group object from the target VM.
ThreadReference | A thread object from the target VM.
Type | The mirror for a type in the target VM.
TypeComponent | An entity declared within a user defined type (class or interface).
Value | The mirror for a value in the target VM.
VirtualMachine | A virtual machine targeted for debugging.
VirtualMachineManager | A manager of connections to target virtual machines.
VoidType | The type of all primitive void values accessed in the target VM.
VoidValue | Provides access to a primitive void value in the target VM.

Class Summary
Bootstrap Initial class that provides access to the default implementation of JDI interfaces.

Exception Summary
AbsentInformationException | Thrown to indicate line number or variable information is not available.
ClassNotLoadedException | Thrown to indicate that the requested class has not yet been loaded through the appropriate class loader.
ClassNotPreparedException | Thrown to indicate that the requested operation cannot be completed because the specified class has not yet been prepared.
IncompatibleThreadStateException | Thrown to indicate that the requested operation cannot be completed while the specified thread is in its current state.
InconsistentDebugInfoException | Thrown to indicate that there is an inconistency in the debug information provided by the target VM.
InternalException | Thrown to indicate that an unexpected internal error has occurred.
InvalidCodeIndexException | Deprecated. This exception is no longer thrown
InvalidLineNumberException | Deprecated. This exception is no longer thrown
InvalidStackFrameException | Thrown to indicate that the requested operation cannot be completed because the specified stack frame is no longer valid.
InvalidTypeException | Thrown to indicate a type mismatch in setting the value of a field or variable.
InvocationException | Thrown to indicate an exception occurred in an invoked method within the target VM.
NativeMethodException | Thrown to indicate an operation cannot be completed because it is not valid for a native method.
ObjectCollectedException | Thrown to indicate that the requested operation cannot be completed because the specified object has been garbage collected.
VMDisconnectedException | Unchecked exception thrown to indicate that the requested operation cannot be completed because there is no longer a connection to the target VM.
VMMismatchException | Thrown to indicate that the requested operation cannot be completed because the a mirror from one target VM is being combined with a mirror from another target VM.
VMOutOfMemoryException | Thrown to indicate that the requested operation cannot be completed because the target VM has run out of memory.

Package com.sun.jdi Description

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. VirtualMachine mirrors the target virtual machine and is the origin of all information provided by the JDI. A VirtualMachine is typically created by using the VirtualMachineManager to create a connection to the target virtual machine (see the com.sun.jdi.connect package). In turn the VirtualMachineManager is typically created by calling Bootstrap.virtualMachineManager().

Most of the methods within this package can throw the unchecked exception VMDisconnectedException.

Methods may be added to the interfaces in the JDI packages in future releases. Existing packages may be renamed if the JDI becomes a standard extension.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


com.sun.jdi Class Hierarchy (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Hierarchy For Package com.sun.jdi

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class com.sun.jdi.Bootstrap
    • class java.lang.Throwable (implements java.io.Serializable)
      • class java.lang.Exception
        • class com.sun.jdi.AbsentInformationException
        • class com.sun.jdi.ClassNotLoadedException
        • class com.sun.jdi.IncompatibleThreadStateException
        • class com.sun.jdi.InvalidTypeException
        • class com.sun.jdi.InvocationException
        • class java.lang.RuntimeException
          • class com.sun.jdi.ClassNotPreparedException
          • class com.sun.jdi.InconsistentDebugInfoException
          • class com.sun.jdi.InternalException
          • class com.sun.jdi.InvalidCodeIndexException
          • class com.sun.jdi.InvalidLineNumberException
          • class com.sun.jdi.InvalidStackFrameException
          • class com.sun.jdi.NativeMethodException
          • class com.sun.jdi.ObjectCollectedException
          • class com.sun.jdi.VMDisconnectedException
          • class com.sun.jdi.VMMismatchException
          • class com.sun.jdi.VMOutOfMemoryException

Interface Hierarchy

  • interface com.sun.jdi.Accessible
    • interface com.sun.jdi.ReferenceType (also extends java.lang.Comparable, com.sun.jdi.Type)
      • interface com.sun.jdi.ArrayType
      • interface com.sun.jdi.ClassType
      • interface com.sun.jdi.InterfaceType
    • interface com.sun.jdi.TypeComponent (also extends com.sun.jdi.Mirror)
      • interface com.sun.jdi.Field (also extends java.lang.Comparable)
      • interface com.sun.jdi.Method (also extends java.lang.Comparable, com.sun.jdi.Locatable)
  • interface java.lang.Comparable
    • interface com.sun.jdi.ByteValue (also extends com.sun.jdi.PrimitiveValue)
    • interface com.sun.jdi.CharValue (also extends com.sun.jdi.PrimitiveValue)
    • interface com.sun.jdi.DoubleValue (also extends com.sun.jdi.PrimitiveValue)
    • interface com.sun.jdi.Field (also extends com.sun.jdi.TypeComponent)
    • interface com.sun.jdi.FloatValue (also extends com.sun.jdi.PrimitiveValue)
    • interface com.sun.jdi.IntegerValue (also extends com.sun.jdi.PrimitiveValue)
    • interface com.sun.jdi.LocalVariable (also extends com.sun.jdi.Mirror)
    • interface com.sun.jdi.Location (also extends com.sun.jdi.Mirror)
    • interface com.sun.jdi.LongValue (also extends com.sun.jdi.PrimitiveValue)
    • interface com.sun.jdi.Method (also extends com.sun.jdi.Locatable, com.sun.jdi.TypeComponent)
    • interface com.sun.jdi.ReferenceType (also extends com.sun.jdi.Accessible, com.sun.jdi.Type)
      • interface com.sun.jdi.ArrayType
      • interface com.sun.jdi.ClassType
      • interface com.sun.jdi.InterfaceType
    • interface com.sun.jdi.ShortValue (also extends com.sun.jdi.PrimitiveValue)
  • interface com.sun.jdi.Locatable
    • interface com.sun.jdi.Method (also extends java.lang.Comparable, com.sun.jdi.TypeComponent)
    • interface com.sun.jdi.StackFrame (also extends com.sun.jdi.Mirror)
  • interface com.sun.jdi.Mirror
    • interface com.sun.jdi.LocalVariable (also extends java.lang.Comparable)
    • interface com.sun.jdi.Location (also extends java.lang.Comparable)
    • interface com.sun.jdi.StackFrame (also extends com.sun.jdi.Locatable)
    • interface com.sun.jdi.Type
      • interface com.sun.jdi.PrimitiveType
        • interface com.sun.jdi.BooleanType
        • interface com.sun.jdi.ByteType
        • interface com.sun.jdi.CharType
        • interface com.sun.jdi.DoubleType
        • interface com.sun.jdi.FloatType
        • interface com.sun.jdi.IntegerType
        • interface com.sun.jdi.LongType
        • interface com.sun.jdi.ShortType
      • interface com.sun.jdi.ReferenceType (also extends com.sun.jdi.Accessible, java.lang.Comparable)
        • interface com.sun.jdi.ArrayType
        • interface com.sun.jdi.ClassType
        • interface com.sun.jdi.InterfaceType
      • interface com.sun.jdi.VoidType
    • interface com.sun.jdi.TypeComponent (also extends com.sun.jdi.Accessible)
      • interface com.sun.jdi.Field (also extends java.lang.Comparable)
      • interface com.sun.jdi.Method (also extends java.lang.Comparable, com.sun.jdi.Locatable)
    • interface com.sun.jdi.Value
      • interface com.sun.jdi.ObjectReference
        • interface com.sun.jdi.ArrayReference
        • interface com.sun.jdi.ClassLoaderReference
        • interface com.sun.jdi.ClassObjectReference
        • interface com.sun.jdi.StringReference
        • interface com.sun.jdi.ThreadGroupReference
        • interface com.sun.jdi.ThreadReference
      • interface com.sun.jdi.PrimitiveValue
        • interface com.sun.jdi.BooleanValue
        • interface com.sun.jdi.ByteValue (also extends java.lang.Comparable)
        • interface com.sun.jdi.CharValue (also extends java.lang.Comparable)
        • interface com.sun.jdi.DoubleValue (also extends java.lang.Comparable)
        • interface com.sun.jdi.FloatValue (also extends java.lang.Comparable)
        • interface com.sun.jdi.IntegerValue (also extends java.lang.Comparable)
        • interface com.sun.jdi.LongValue (also extends java.lang.Comparable)
        • interface com.sun.jdi.ShortValue (also extends java.lang.Comparable)
      • interface com.sun.jdi.VoidValue
    • interface com.sun.jdi.VirtualMachine
      • interface com.sun.jdi.PathSearchingVirtualMachine
  • interface com.sun.jdi.VirtualMachineManager
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Package com.sun.jdi (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Package
com.sun.jdi

Packages that use com.sun.jdi
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.
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.

Classes in com.sun.jdi used by com.sun.jdi
AbsentInformationException
Thrown to indicate line number or variable information is not available.
Accessible
Provides information on the accessibility of a type or type component.
ArrayReference
Provides access to an array object and its components in the target VM.
BooleanValue
Provides access to a primitive boolean value in the target VM.
ByteValue
Provides access to a primitive byte value in the target VM.
CharValue
Provides access to a primitive char value in the target VM.
ClassLoaderReference
A class loader object from the target VM.
ClassNotLoadedException
Thrown to indicate that the requested class has not yet been loaded through the appropriate class loader.
ClassObjectReference
An instance of java.lang.Class from the target VM.
ClassType
A mirror of a class in the target VM.
DoubleValue
Provides access to a primitive double value in the target VM.
Field
A class or instance variable in the target VM.
FloatValue
Provides access to a primitive float value in the target VM.
IncompatibleThreadStateException
Thrown to indicate that the requested operation cannot be completed while the specified thread is in its current state.
IntegerValue
Provides access to a primitive int value in the target VM.
InvalidTypeException
Thrown to indicate a type mismatch in setting the value of a field or variable.
InvocationException
Thrown to indicate an exception occurred in an invoked method within the target VM.
LocalVariable
A local variable in the target VM.
Locatable
A mirror that has a Location.
Location
A point within the executing code of the target VM.
LongValue
Provides access to a primitive long value in the target VM.
Method
A static or instance method in the target VM.
Mirror
A proxy used by a debugger to examine or manipulate some entity in another virtual machine.
ObjectReference
An object that currently exists in the target VM.
PrimitiveType
The type associated with non-object values in a target VM.
PrimitiveValue
The value assigned to a field or variable of primitive type in a target VM.
ReferenceType
The type of an object in a target VM.
ShortValue
Provides access to a primitive short value in the target VM.
StackFrame
The state of one method invocation on a thread's call stack.
StringReference
A string object from the target VM.
ThreadGroupReference
A thread group object from the target VM.
ThreadReference
A thread object from the target VM.
Type
The mirror for a type in the target VM.
TypeComponent
An entity declared within a user defined type (class or interface).
Value
The mirror for a value in the target VM.
VirtualMachine
A virtual machine targeted for debugging.
VirtualMachineManager
A manager of connections to target virtual machines.

Classes in com.sun.jdi used by com.sun.jdi.connect
VirtualMachine
A virtual machine targeted for debugging.

Classes in com.sun.jdi used by com.sun.jdi.event
Field
A class or instance variable in the target VM.
Locatable
A mirror that has a Location.
Location
A point within the executing code of the target VM.
Method
A static or instance method in the target VM.
Mirror
A proxy used by a debugger to examine or manipulate some entity in another virtual machine.
ObjectReference
An object that currently exists in the target VM.
ReferenceType
The type of an object in a target VM.
ThreadReference
A thread object from the target VM.
Value
The mirror for a value in the target VM.

Classes in com.sun.jdi used by com.sun.jdi.request
Field
A class or instance variable in the target VM.
Locatable
A mirror that has a Location.
Location
A point within the executing code of the target VM.
Mirror
A proxy used by a debugger to examine or manipulate some entity in another virtual machine.
ObjectReference
An object that currently exists in the target VM.
ReferenceType
The type of an object in a target VM.
ThreadReference
A thread object from the target VM.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


PathSearchingVirtualMachine (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface PathSearchingVirtualMachine

All Superinterfaces:
Mirror, VirtualMachine
public interface PathSearchingVirtualMachine
extends VirtualMachine

A virtual machine which searches for classes through paths

Since:
1.3

Field Summary
Fields inherited from interface com.sun.jdi.VirtualMachine
TRACE_ALL, TRACE_EVENTS, TRACE_NONE, TRACE_OBJREFS, TRACE_RECEIVES, TRACE_REFTYPES, TRACE_SENDS
Method Summary
String | baseDirectory() Get the base directory used for path searching.
List | bootClassPath() Get the boot class path for this virtual machine.
List | classPath() Get the class path for this virtual machine.
Methods inherited from interface com.sun.jdi.VirtualMachine
allClasses, allThreads, canAddMethod, canGetBytecodes, canGetCurrentContendedMonitor, canGetMonitorInfo, canGetOwnedMonitorInfo, canGetSourceDebugExtension, canGetSyntheticAttribute, canPopFrames, canRedefineClasses, canRequestVMDeathEvent, canUnrestrictedlyRedefineClasses, canUseInstanceFilters, canWatchFieldAccess, canWatchFieldModification, classesByName, description, dispose, eventQueue, eventRequestManager, exit, getDefaultStratum, mirrorOf, mirrorOf, mirrorOf, mirrorOf, mirrorOf, mirrorOf, mirrorOf, mirrorOf, mirrorOf, name, process, redefineClasses, resume, setDebugTraceMode, setDefaultStratum, suspend, topLevelThreadGroups, version
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Method Detail

classPath

public List classPath()
Get the class path for this virtual machine.

Returns:
List of components of the classpath, each represented by a String.

bootClassPath

public List bootClassPath()
Get the boot class path for this virtual machine.

Returns:
List of components of the boot class path, each represented by a String.

baseDirectory

public String baseDirectory()
Get the base directory used for path searching. Relative directories in the class path and boot class path can be resolved through this directory name.

Returns:
the base directory.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


PrimitiveType (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface PrimitiveType

All Superinterfaces:
Mirror, Type
All Known Subinterfaces:
BooleanType, ByteType, CharType, DoubleType, FloatType, IntegerType, LongType, ShortType
public interface PrimitiveType
extends Type

The type associated with non-object values in a target VM. Instances of one of the sub-interfaces of this interface will be returned from Value.type() for all PrimitiveValue objects.

Since:
1.3
See Also:
PrimitiveValue

Methods inherited from interface com.sun.jdi.Type
name, signature
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


PrimitiveValue (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface PrimitiveValue

All Superinterfaces:
Mirror, Value
All Known Subinterfaces:
BooleanValue, ByteValue, CharValue, DoubleValue, FloatValue, IntegerValue, LongValue, ShortValue
public interface PrimitiveValue
extends Value

The value assigned to a field or variable of primitive type in a target VM. Each primitive values is accessed through a subinterface of this interface.

Since:
1.3

Method Summary
boolean | booleanValue() Converts this value to a BooleanValue and returns the result as a boolean.
byte | byteValue() Converts this value to a ByteValue and returns the result as a byte.
char | charValue() Converts this value to a CharValue and returns the result as a char.
double | doubleValue() Converts this value to a DoubleValue and returns the result as a double.
float | floatValue() Converts this value to a FloatValue and returns the result as a float.
int | intValue() Converts this value to an IntegerValue and returns the result as an int.
long | longValue() Converts this value to a LongValue and returns the result as a long.
short | shortValue() Converts this value to a ShortValue and returns the result as a short.
Methods inherited from interface com.sun.jdi.Value
type
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Method Detail

booleanValue

public boolean booleanValue()
Converts this value to a BooleanValue and returns the result as a boolean.

Returns:
true if this value is non-zero (or true if already a BooleanValue); false otherwise.

byteValue

public byte byteValue()
Converts this value to a ByteValue and returns the result as a byte. The value will be narrowed as necessary, and magnitude or precision information may be lost (as if the primitive had been cast to a byte).

Returns:
the value, converted to byte

charValue

public char charValue()
Converts this value to a CharValue and returns the result as a char. The value will be narrowed or widened as necessary, and magnitude or precision information may be lost (as if the primitive had been cast to a char, in the narrowing case).

Returns:
the value, converted to char

shortValue

public short shortValue()
Converts this value to a ShortValue and returns the result as a short. The value will be narrowed or widened as necessary, and magnitude or precision information may be lost (as if the primitive had been cast to a short, in the narrowing case).

Returns:
the value, converted to short

intValue

public int intValue()
Converts this value to an IntegerValue and returns the result as an int. The value will be narrowed or widened as necessary, and magnitude or precision information may be lost (as if the primitive had been cast to an int, in the narrowing case).

Returns:
the value, converted to int

longValue

public long longValue()
Converts this value to a LongValue and returns the result as a long. The value will be narrowed or widened as necessary, and magnitude or precision information may be lost (as if the primitive had been cast to a long, in the narrowing case).

Returns:
the value, converted to long

floatValue

public float floatValue()
Converts this value to a FloatValue and returns the result as a float. The value will be narrowed or widened as necessary, and magnitude or precision information may be lost (as if the primitive had been cast to a float, in the narrowing case).

Returns:
the value, converted to float

doubleValue

public double doubleValue()
Converts this value to a DoubleValue and returns the result as a double. The value will be widened as necessary, and precision information may be lost.

Returns:
the value, converted to double
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ReferenceType (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface ReferenceType

All Superinterfaces:
Accessible, Comparable, Mirror, Type
All Known Subinterfaces:
ArrayType, ClassType, InterfaceType
public interface ReferenceType
extends Type, Comparable, Accessible

The type of an object in a target VM. ReferenceType encompasses classes, interfaces, and array types as defined in the JavaTM Language Specification. All ReferenceType objects belong to one of the following subinterfaces: ClassType for classes, InterfaceType for interfaces, and ArrayType for arrays. Note that primitive classes (for example, the reflected type of Integer.TYPE) are represented as ClassType. The VM creates Class objects for all three, so from the VM perspective, each ReferenceType maps to a distinct Class object.

ReferenceTypes can be obtained by querying a particular ObjectReference for its type or by getting a list of all reference types from the VirtualMachine.

ReferenceType provides access to static type information such as methods and fields and provides access to dynamic type information such as the corresponding Class object and the classloader.

Any method on ReferenceType which directly or indirectly takes ReferenceType as an parameter may throw VMDisconnectedException if the target VM is disconnected and the VMDisconnectEvent has been or is available to be read from the EventQueue.

Any method on ReferenceType which directly or indirectly takes ReferenceType as an parameter may throw VMOutOfMemoryException if the target VM has run out of memory.

Any method on ReferenceType or which directly or indirectly takes ReferenceType as parameter may throw ObjectCollectedException if the mirrored type has been unloaded.

Since:
1.3
See Also:
ObjectReference, ObjectReference.referenceType(), VirtualMachine, VirtualMachine.allClasses()

Method Summary
List | allFields() Returns a list containing each Field declared in this type, and its superclasses, implemented interfaces, and/or superinterfaces.
List | allLineLocations() Returns a list containing a Location object for each executable source line in this reference type.
List | allLineLocations(String stratum, String sourceName) Returns a list containing a Location object for each executable source line in this reference type.
List | allMethods() Returns a list containing each Method declared in this type, and its superclasses, implemented interfaces, and/or superinterfaces.
List | availableStrata() Return the available strata for this reference type.
ClassLoaderReference | classLoader() Gets the classloader object which loaded the class corresponding to this type.
ClassObjectReference | classObject() Returns the class object that corresponds to this type in the target VM.
String | defaultStratum() Returns the default stratum for this reference type.
boolean | equals(Object obj) Compares the specified Object with this ReferenceType for equality.
boolean | failedToInitialize() Determines if initialization failed for this class.
Field | fieldByName(String fieldName) Finds the visible Field with the given non-ambiguous name.
List | fields() Returns a list containing each Field declared in this type.
Value | getValue(Field field) Gets the Value of a given static Field in this type.
Map | getValues(List fields) Returns a map containing the Value of each static Field in the given list.
int | hashCode() Returns the hash code value for this ObjectReference.
boolean | isAbstract() Determines if this type was declared abstract.
boolean | isFinal() Determines if this type was declared final.
boolean | isInitialized() Determines if this type has been initialized.
boolean | isPrepared() Determines if this type has been prepared.
boolean | isStatic() Determines if this type was declared static.
boolean | isVerified() Determines if this type has been verified.
List | locationsOfLine(int lineNumber) Returns a List containing all Location objects that map to the given line number.
List | locationsOfLine(String stratum, String sourceName, int lineNumber) Returns a List containing all Location objects that map to the given line number.
List | methods() Returns a list containing each Method declared directly in this type.
List | methodsByName(String name) Returns a List containing each visible Method that has the given name.
List | methodsByName(String name, String signature) Returns a List containing each visible Method that has the given name and signature.
String | name() Gets the fully qualified name of this type.
List | nestedTypes() Returns a List containing ReferenceType objects that are declared within this type and are currently loaded into the Virtual Machine.
String | sourceDebugExtension() Get the source debug extension of this type.
String | sourceName() Gets an identifying name for the source corresponding to the declaration of this type.
List | sourceNames(String stratum) Gets the identifying names for all the source corresponding to the declaration of this type.
List | sourcePaths(String stratum) Gets the paths to the source corresponding to the declaration of this type.
List | visibleFields() Returns a list containing each unhidden and unambiguous Field in this type.
List | visibleMethods() Returns a list containing each Method declared or inherited by this type.
Methods inherited from interface com.sun.jdi.Type
signature
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine
Methods inherited from interface java.lang.Comparable
compareTo
Methods inherited from interface com.sun.jdi.Accessible
isPackagePrivate, isPrivate, isProtected, isPublic, modifiers

Method Detail

name

public String name()
Gets the fully qualified name of this type. The returned name is formatted as it might appear in a Java programming langauge declaration for objects of this type.

For primitive classes the returned name is the name of the corresponding primitive type; for example, "int" is returned as the name of the class represented by Integer.TYPE.

Specified by:
name in interface Type
Returns:
a string containing the type name.

classLoader

public ClassLoaderReference classLoader()
Gets the classloader object which loaded the class corresponding to this type.

Returns:
a ClassLoaderReference which mirrors the classloader, or null if the class was loaded through the bootstrap class loader.

sourceName

public String sourceName()
                  throws AbsentInformationException
Gets an identifying name for the source corresponding to the declaration of this type. Interpretation of this string is the responsibility of the source repository mechanism.

The returned name is dependent on VM's default stratum (VirtualMachine.getDefaultStratum()). In the reference implementation, when using the base stratum, the returned string is the unqualified name of the source file containing the declaration of this type. In other strata the returned source name is the first source name for that stratum. Since other languages may have more than one source name for a reference type, the use of Location.sourceName() or sourceNames(String) is preferred.

For arrays (ArrayType) and primitive classes, AbsentInformationException is always thrown.

Returns:
the string source file name
Throws:
AbsentInformationException - if the source name is not known

sourceNames

public List sourceNames(String stratum)
                 throws AbsentInformationException
Gets the identifying names for all the source corresponding to the declaration of this type. Interpretation of these names is the responsibility of the source repository mechanism.

The returned names are for the specified stratum (see Location for a description of strata). In the reference implementation, when using the Java programming language stratum, the returned List contains one element: a String which is the unqualified name of the source file containing the declaration of this type. In other strata the returned source names are all the source names defined for that stratum.

Parameters:
stratum - The stratum to retrieve information from or null for the declaring type's default stratum.
Returns:
a List of String objects each representing a source name
Throws:
AbsentInformationException - if the source names are not known.

For arrays (ArrayType) and primitive classes, AbsentInformationException is always thrown.

Since:
1.4

sourcePaths

public List sourcePaths(String stratum)
                 throws AbsentInformationException
Gets the paths to the source corresponding to the declaration of this type. Interpretation of these paths is the responsibility of the source repository mechanism.

The returned paths are for the specified stratum (see Location for a description of strata). In the reference implementation, for strata which do not explicitly specify source path (the Java programming language stratum never does), the returned strings are the sourceNames(String) prefixed by the package name of this ReferenceType converted to a platform dependent path. For example, on a Windows platform, java.lang.Thread would return a List containing one element: "java\lang\Thread.java".

Parameters:
stratum - The stratum to retrieve information from or null for the declaring type's default stratum.
Returns:
a List of String objects each representing a source path
Throws:
AbsentInformationException - if the source names are not known.

For arrays (ArrayType) and primitive classes, AbsentInformationException is always thrown.

Since:
1.4

sourceDebugExtension

public String sourceDebugExtension()
                            throws AbsentInformationException
Get the source debug extension of this type.

Not all target virtual machines support this operation. Use canGetSourceDebugExtension() to determine if the operation is supported.

Returns:
as a string the source debug extension attribute
Throws:
AbsentInformationException - if the extension is not specified
UnsupportedOperationException - if the target virtual machine does not support this operation - see canGetSourceDebugExtension(),

isStatic

public boolean isStatic()
Determines if this type was declared static. Only nested types, can be declared static, so false is returned for any package-level type, array type, or primitive class.

Returns:
true if this type is static; false otherwise.

isAbstract

public boolean isAbstract()
Determines if this type was declared abstract.

For arrays (ArrayType) and primitive classes, the return value is undefined.

Returns:
true if this type is abstract; false otherwise.

isFinal

public boolean isFinal()
Determines if this type was declared final.

For arrays (ArrayType) and primitive classes, the return value is always true.

Returns:
true if this type is final; false otherwise.

isPrepared

public boolean isPrepared()
Determines if this type has been prepared. See the JVM specification for a definition of class preparation.

For arrays (ArrayType) and primitive classes, the return value is undefined.

Returns:
true if this type is prepared; false otherwise.

isVerified

public boolean isVerified()
Determines if this type has been verified. See the JVM specification for a definition of class verification.

For arrays (ArrayType) and primitive classes, the return value is undefined.

Returns:
true if this type is verified; false otherwise.

isInitialized

public boolean isInitialized()
Determines if this type has been initialized. See the JVM specification for a definition of class verification. For InterfaceType, this method always returns the same value as isPrepared().

For arrays (ArrayType) and primitive classes, the return value is undefined.

Returns:
true if this type is initialized; false otherwise.

failedToInitialize

public boolean failedToInitialize()
Determines if initialization failed for this class. See the JVM specification for details on class initialization.

For arrays (ArrayType) and primitive classes, the return value is undefined.

Returns:
true if initialization was attempted and failed; false otherwise.

fields

public List fields()
Returns a list containing each Field declared in this type. Inherited fields are not included. Any synthetic fields created by the compiler are included in the list.

For arrays (ArrayType) and primitive classes, the returned list is always empty.

Returns:
a list Field objects; the list has length 0 if no fields exist.
Throws:
ClassNotPreparedException - if this class not yet been prepared.

visibleFields

public List visibleFields()
Returns a list containing each unhidden and unambiguous Field in this type. Each field that can be accessed from the class or its instances with its simple name is included. Fields that are ambiguously multiply inherited or fields that are hidden by fields with the same name in a more recently inherited class cannot be accessed by their simple names and are not included in the returned list. All other inherited fields are included. See JLS section 8.3 for details.

For arrays (ArrayType) and primitive classes, the returned list is always empty.

Returns:
a List of Field objects; the list has length 0 if no visible fields exist.
Throws:
ClassNotPreparedException - if this class not yet been prepared.

allFields

public List allFields()
Returns a list containing each Field declared in this type, and its superclasses, implemented interfaces, and/or superinterfaces. All declared and inherited fields are included, regardless of whether they are hidden or multiply inherited.

For arrays (ArrayType) and primitive classes, the returned list is always empty.

Returns:
a List of Field objects; the list has length 0 if no fields exist.
Throws:
ClassNotPreparedException - if this class not yet been prepared.

fieldByName

public Field fieldByName(String fieldName)
Finds the visible Field with the given non-ambiguous name. This method follows the inheritance rules specified in the JLS (8.3.3) to determine visibility.

For arrays (ArrayType) and primitive classes, the returned value is always null.

Parameters:
fieldName - a String containing the name of desired field.
Returns:
a Field object which mirrors the found field, or null if there is no field with the given name or if the given name is ambiguous.
Throws:
ClassNotPreparedException - if this class not yet been prepared.

methods

public List methods()
Returns a list containing each Method declared directly in this type. Inherited methods are not included. Constructors, the initialization method if any, and any synthetic methods created by the compiler are included in the list.

For arrays (ArrayType) and primitive classes, the returned list is always empty.

Returns:
a list Method objects; the list has length 0 if no methods exist.
Throws:
ClassNotPreparedException - if this class not yet been prepared.

visibleMethods

public List visibleMethods()
Returns a list containing each Method declared or inherited by this type. Methods from superclasses or superinterfaces that that have been hidden or overridden are not included.

Note that despite this exclusion, multiple inherited methods with the same signature can be present in the returned list, but at most one can be a member of a ClassType. See JLS section 8.4.6 for details.

For arrays (ArrayType) and primitive classes, the returned list is always empty.

Returns:
a List of Method objects; the list has length 0 if no visible methods exist.
Throws:
ClassNotPreparedException - if this class not yet been prepared.

allMethods

public List allMethods()
Returns a list containing each Method declared in this type, and its superclasses, implemented interfaces, and/or superinterfaces. All declared and inherited methods are included, regardless of whether they are hidden or overridden.

For arrays (ArrayType) and primitive classes, the returned list is always empty.

Returns:
a List of Method objects; the list has length 0 if no methods exist.
Throws:
ClassNotPreparedException - if this class not yet been prepared.

methodsByName

public List methodsByName(String name)
Returns a List containing each visible Method that has the given name. This is most commonly used to find overloaded methods.

Overridden and hidden methods are not included. See JLS (8.4.6) for details.

For arrays (ArrayType) and primitive classes, the returned list is always empty.

Parameters:
name - the name of the method to find.
Returns:
a List of Method objects that match the given name; the list has length 0 if no matching methods are found.
Throws:
ClassNotPreparedException - if this class not yet been prepared.

methodsByName

public List methodsByName(String name,
                          String signature)
Returns a List containing each visible Method that has the given name and signature. The signature string is the JNI signature for the target method:
  • ()V
  • ([Ljava/lang/String;)V
  • (IIII)Z
This method follows the inheritance rules specified in the JLS (8.4.6) to determine visibility.

At most one method in the list is a concrete method and a component of ClassType; any other methods in the list are abstract. Use ClassType.concreteMethodByName(java.lang.String, java.lang.String) to retrieve only the matching concrete method.

For arrays (ArrayType) and primitive classes, the returned list is always empty.

Parameters:
name - the name of the method to find.
signature - the signature of the method to find
Returns:
a List of Method objects that match the given name and signature; the list has length 0 if no matching methods are found.
Throws:
ClassNotPreparedException - if this class not yet been prepared.

nestedTypes

public List nestedTypes()
Returns a List containing ReferenceType objects that are declared within this type and are currently loaded into the Virtual Machine. Both static nested types and non-static nested types (that is, inner types) are included. Local inner types (declared within a code block somewhere in this reference type) are also included in the returned list.

For arrays (ArrayType) and primitive classes, the returned list is always empty.

Returns:
a List of nested ReferenceType objects; the list has 0 length if there are no nested types.

getValue

public Value getValue(Field field)
Gets the Value of a given static Field in this type. The Field must be valid for this type; that is, it must be declared in this type, a superclass, a superinterface, or an implemented interface.

Parameters:
field - the field containing the requested value
Returns:
the Value of the instance field.
Throws:
IllegalArgumentException - if the field is not valid for this object's class.

getValues

public Map getValues(List fields)
Returns a map containing the Value of each static Field in the given list. The Fields must be valid for this type; that is, they must be declared in this type, a superclass, a superinterface, or an implemented interface.

Parameters:
fields - a list of Field objects containing the requested values.
Returns:
a Map of the requested Field objects with their Value.
Throws:
IllegalArgumentException - if any field is not valid for this object's class.
VMMismatchException - if a Mirror argument and this mirror do not belong to the same VirtualMachine.

classObject

public ClassObjectReference classObject()
Returns the class object that corresponds to this type in the target VM. The VM creates class objects for every kind of ReferenceType: classes, interfaces, and array types.

Returns:
the ClassObjectReference for this reference type in the target VM.

allLineLocations

public List allLineLocations()
                      throws AbsentInformationException
Returns a list containing a Location object for each executable source line in this reference type.

This method is equivalent to allLineLocations(vm.getDefaultStratum(),null) - see allLineLocations(String,String) for more information.

Throws:
AbsentInformationException - if there is no line number information for this class and there are non-native, non-abstract executable members of this class.
ClassNotPreparedException - if this class not yet been prepared.

allLineLocations

public List allLineLocations(String stratum,
                             String sourceName)
                      throws AbsentInformationException
Returns a list containing a Location object for each executable source line in this reference type. Each location maps a source line to a range of code indices. The beginning of the range can be determined through Location.codeIndex(). The returned list may contain multiple locations for a particular line number, if the compiler and/or VM has mapped that line to two or more disjoint code index ranges. Note that it is possible for the same source line to represent different code index ranges in different methods.

For arrays (ArrayType) and primitive classes, the returned list is always empty. For interfaces (InterfaceType), the returned list will be non-empty only if the interface has executable code in its class initialization.

Returned list is for the specified stratum (see Location for a description of strata).

Parameters:
stratum - The stratum to retrieve information from or null for the defaultStratum().
sourceName - Return locations only within this source file or null to return locations.
Returns:
a List of all source line Location objects.
Throws:
AbsentInformationException - if there is no line number information for this class and there are non-native, non-abstract executable members of this class. Or if sourceName is non-null and source name information is not present.
ClassNotPreparedException - if this class not yet been prepared.
Since:
1.4

locationsOfLine

public List locationsOfLine(int lineNumber)
                     throws AbsentInformationException
Returns a List containing all Location objects that map to the given line number.

This method is equivalent to locationsOfLine(vm.getDefaultStratum(), null, lineNumber) - see locationsOfLine(java.lang.String,java.lang.String,int) for more information.

Parameters:
lineNumber - the line number
Returns:
a List of all Location objects that map to the given line.
Throws:
AbsentInformationException - if there is no line number information for this class.
ClassNotPreparedException - if this class not yet been prepared.
See Also:
VirtualMachine.getDefaultStratum()

locationsOfLine

public List locationsOfLine(String stratum,
                            String sourceName,
                            int lineNumber)
                     throws AbsentInformationException
Returns a List containing all Location objects that map to the given line number.

For arrays (ArrayType) and primitive classes, the returned list is always empty. For interfaces (InterfaceType), the returned list will be non-empty only if the interface has executable code in its class initialization at the specified line number. An empty list will be returned if there is no executable code at the specified line number.

Returned list is for the specified stratum (see Location for a description of strata).

Parameters:
stratum - the stratum to use for comparing line number and source name, or null to use the defaultStratum().
sourceName - the source name containing the line number, or null to match all source names
lineNumber - the line number
Returns:
a List of all Location objects that map to the given line.
Throws:
AbsentInformationException - if there is no line number information for this class. Or if sourceName is non-null and source name information is not present.
ClassNotPreparedException - if this class not yet been prepared.
Since:
1.4

availableStrata

public List availableStrata()
Return the available strata for this reference type.

See the Location for a description of strata.

Returns:
List of java.lang.String, each representing a stratum
Since:
1.4

defaultStratum

public String defaultStratum()
Returns the default stratum for this reference type. This value is specified in the class file and cannot be set by the user. If the class file does not specify a default stratum the base stratum ("Java") will be returned.

See the Location for a description of strata.

Since:
1.4

equals

public boolean equals(Object obj)
Compares the specified Object with this ReferenceType for equality.

Returns:
true if the Object is a ReferenceType, if the ReferenceTypes belong to the same VM, and if they mirror classes which correspond to the same instance of java.lang.Class in that VM.

hashCode

public int hashCode()
Returns the hash code value for this ObjectReference.

Returns:
the integer hash code
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ShortType (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface ShortType

All Superinterfaces:
Mirror, PrimitiveType, Type
public interface ShortType
extends PrimitiveType

The type of all primitive short values accessed in the target VM. Calls to Value.type() will return an implementor of this interface.

Since:
1.3
See Also:
LongValue

Methods inherited from interface com.sun.jdi.Type
name, signature
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ShortValue (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface ShortValue

All Superinterfaces:
Comparable, Mirror, PrimitiveValue, Value
public interface ShortValue
extends PrimitiveValue, Comparable

Provides access to a primitive short value in the target VM.

Since:
1.3

Method Summary
boolean | equals(Object obj) Compares the specified Object with this ShortValue for equality.
int | hashCode() Returns the hash code value for this ShortValue.
short | value() Returns this ShortValue as a short.
Methods inherited from interface com.sun.jdi.PrimitiveValue
booleanValue, byteValue, charValue, doubleValue, floatValue, intValue, longValue, shortValue
Methods inherited from interface com.sun.jdi.Value
type
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine
Methods inherited from interface java.lang.Comparable
compareTo

Method Detail

value

public short value()
Returns this ShortValue as a short.

Returns:
the short mirrored by this object.

equals

public boolean equals(Object obj)
Compares the specified Object with this ShortValue for equality.

Returns:
true if the Object is a ShortValue and if applying "==" to the two mirrored primitives would evaluate to true; false otherwise.

hashCode

public int hashCode()
Returns the hash code value for this ShortValue.

Returns:
the integer hash code
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


StackFrame (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface StackFrame

All Superinterfaces:
Locatable, Mirror
public interface StackFrame
extends Mirror, Locatable

The state of one method invocation on a thread's call stack. As a thread executes, stack frames are pushed and popped from its call stack as methods are invoked and then return. A StackFrame mirrors one such frame from a target VM at some point in its thread's execution. The call stack is, then, simply a List of StackFrame objects. The call stack can be obtained any time a thread is suspended through a call to ThreadReference.frames()

StackFrames provide access to a method's local variables and their current values.

The lifetime of a StackFrame is very limited. It is available only for suspended threads and becomes invalid once its thread is resumed.

Any method on StackFrame which takes StackFrame as an parameter may throw VMDisconnectedException if the target VM is disconnected and the VMDisconnectEvent has been or is available to be read from the EventQueue.

Any method on StackFrame which takes StackFrame as an parameter may throw VMOutOfMemoryException if the target VM has run out of memory.

Since:
1.3

Method Summary
Value | getValue(LocalVariable variable) Gets the Value of a LocalVariable in this frame.
Map | getValues(List variables) Returns the values of multiple local variables in this frame.
Location | location() Returns the Location of the current instruction in the frame.
void | setValue(LocalVariable variable, Value value) Sets the Value of a LocalVariable in this frame.
ObjectReference | thisObject() Returns the value of 'this' for the current frame.
ThreadReference | thread() Returns the thread under which this frame's method is running.
LocalVariable | visibleVariableByName(String name) Finds a LocalVariable that matches the given name and is visible at the current frame location.
List | visibleVariables() Returns a list containing each LocalVariable that can be accessed from this frame's location.
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Method Detail

location

public Location location()
Returns the Location of the current instruction in the frame. The method for which this frame was created can also be accessed through the returned location. For the top frame in the stack, this location identifies the next instruction to be executed. For all other frames, this location identifies the instruction that caused the next frame's method to be invoked. If the frame represents a native method invocation, the returned location indicates the class and method, but the code index will not be valid (-1).

Specified by:
location in interface Locatable
Returns:
the Location of the current instruction.
Throws:
InvalidStackFrameException - if this stack frame has become invalid. Once the frame's thread is resumed, the stack frame is no longer valid.

thread

public ThreadReference thread()
Returns the thread under which this frame's method is running.

Returns:
a ThreadReference which mirrors the frame's thread.
Throws:
InvalidStackFrameException - if this stack frame has become invalid. Once the frame's thread is resumed, the stack frame is no longer valid.

thisObject

public ObjectReference thisObject()
Returns the value of 'this' for the current frame. The ObjectReference for 'this' is only available for non-native instance methods.

Returns:
an ObjectReference, or null if the frame represents a native or static method.
Throws:
InvalidStackFrameException - if this stack frame has become invalid. Once the frame's thread is resumed, the stack frame is no longer valid.

visibleVariables

public List visibleVariables()
                      throws AbsentInformationException
Returns a list containing each LocalVariable that can be accessed from this frame's location.

Visibility is based on the code index of the current instruction of this StackFrame. Each variable has a range of byte code indices in which it is accessible. If this stack frame's method matches this variable's method and if the code index of this StackFrame is within the variable's byte code range, the variable is visible.

A variable's byte code range is at least as large as the scope of that variable, but can continue beyond the end of the scope under certain circumstances:

  • the compiler/VM does not immediately reuse the variable's slot.
  • the compiler/VM is implemented to report the extended range that would result from the item above.
The advantage of an extended range is that variables from recently exited scopes may remain available for examination (this is especially useful for loop indices). If, as a result of the extensions above, the current frame location is contained within the range of multiple local variables of the same name, the variable with the highest-starting range is chosen for the returned list.

Returns:
the list of LocalVariable objects currently visible; the list will be empty if there are no visible variables; specifically, frames in native methods will always return a zero-length list.
Throws:
AbsentInformationException - if there is no local variable information for this method.
InvalidStackFrameException - if this stack frame has become invalid. Once the frame's thread is resumed, the stack frame is no longer valid.
NativeMethodException - if the current method is native.

visibleVariableByName

public LocalVariable visibleVariableByName(String name)
                                    throws AbsentInformationException
Finds a LocalVariable that matches the given name and is visible at the current frame location. See visibleVariables() for more information on visibility.

Parameters:
name - the variable name to find
Returns:
the matching LocalVariable, or null if there is no visible variable with the given name; frames in native methods will always return null.
Throws:
AbsentInformationException - if there is no local variable information for this method.
InvalidStackFrameException - if this stack frame has become invalid. Once the frame's thread is resumed, the stack frame is no longer valid.
NativeMethodException - if the current method is native.

getValue

public Value getValue(LocalVariable variable)
Gets the Value of a LocalVariable in this frame. The variable must be valid for this frame's method and visible according to the rules described in visibleVariables().

Parameters:
variable - the LocalVariable to be accessed
Returns:
the Value of the instance field.
Throws:
IllegalArgumentException - if the variable is either invalid for this frame's method or not visible.
InvalidStackFrameException - if this stack frame has become invalid. Once the frame's thread is resumed, the stack frame is no longer valid.

getValues

public Map getValues(List variables)
Returns the values of multiple local variables in this frame. Each variable must be valid for this frame's method and visible according to the rules described in visibleVariables().

Parameters:
variables - a list of LocalVariable objects to be accessed
Returns:
a map associating each LocalVariable with its Value
Throws:
IllegalArgumentException - if any variable is either invalid for this frame's method or not visible.
InvalidStackFrameException - if this stack frame has become invalid. Once the frame's thread is resumed, the stack frame is no longer valid.

setValue

public void setValue(LocalVariable variable,
                     Value value)
              throws InvalidTypeException,
                     ClassNotLoadedException
Sets the Value of a LocalVariable in this frame. The variable must be valid for this frame's method and visible according to the rules described in visibleVariables().

Object values must be assignment compatible with the variable type (This implies that the variable type must be loaded through the enclosing class's class loader). Primitive values must be either assignment compatible with the variable type or must be convertible to the variable type without loss of information. See JLS section 5.2 for more information on assignment compatibility.

Parameters:
variable - the field containing the requested value
value - the new value to assign
Throws:
IllegalArgumentException - if the field is not valid for this object's class.
InvalidTypeException - if the value's type does not match the variable's type.
ClassNotLoadedException - if the variable type has not yet been loaded through the appropriate class loader.
InvalidStackFrameException - if this stack frame has become invalid. Once the frame's thread is resumed, the stack frame is no longer valid.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


StringReference (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface StringReference

All Superinterfaces:
Mirror, ObjectReference, Value
public interface StringReference
extends ObjectReference

A string object from the target VM. A StringReference is an ObjectReference with additional access to string-specific information from the target VM.

Since:
1.3

Field Summary
Fields inherited from interface com.sun.jdi.ObjectReference
INVOKE_NONVIRTUAL, INVOKE_SINGLE_THREADED
Method Summary
 String value()
Returns the StringReference as a String.
Methods inherited from interface com.sun.jdi.ObjectReference
disableCollection, enableCollection, entryCount, equals, getValue, getValues, hashCode, invokeMethod, isCollected, owningThread, referenceType, setValue, uniqueID, waitingThreads
Methods inherited from interface com.sun.jdi.Value
type
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Method Detail

value

public String value()
Returns the StringReference as a String. The returned string is the equivalent of the mirrored string, but is an entity in the client VM and can be manipulated like any other string.

Returns:
the string value.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ThreadGroupReference (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface ThreadGroupReference

All Superinterfaces:
Mirror, ObjectReference, Value
public interface ThreadGroupReference
extends ObjectReference

A thread group object from the target VM. A ThreadGroupReference is an ObjectReference with additional access to threadgroup-specific information from the target VM.

Since:
1.3

Field Summary
Fields inherited from interface com.sun.jdi.ObjectReference
INVOKE_NONVIRTUAL, INVOKE_SINGLE_THREADED
Method Summary
String | name() Returns the name of this thread group.
ThreadGroupReference | parent() Returns the parent of this thread group.
void | resume() Resumes all threads in this thread group.
void | suspend() Suspends all threads in this thread group.
List | threadGroups() Returns a List containing each ThreadGroupReference in this thread group.
List | threads() Returns a List containing each ThreadReference in this thread group.
Methods inherited from interface com.sun.jdi.ObjectReference
disableCollection, enableCollection, entryCount, equals, getValue, getValues, hashCode, invokeMethod, isCollected, owningThread, referenceType, setValue, uniqueID, waitingThreads
Methods inherited from interface com.sun.jdi.Value
type
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Method Detail

name

public String name()
Returns the name of this thread group.

Returns:
the string containing the thread group name.

parent

public ThreadGroupReference parent()
Returns the parent of this thread group.

Returns:
a ThreadGroupReference mirroring the parent of this thread group in the target VM, or null if this is a top-level thread group.

suspend

public void suspend()
Suspends all threads in this thread group. Each thread in this group and in all of its subgroups will be suspended as described in ThreadReference.suspend(). This is not guaranteed to be an atomic operation; if the target VM is not interrupted at the time this method is called, it is possible that new threads will be created between the time that threads are enumerated and all of them have been suspended.

resume

public void resume()
Resumes all threads in this thread group. Each thread in this group and in all of its subgroups will be resumed as described in ThreadReference.resume().

threads

public List threads()
Returns a List containing each ThreadReference in this thread group. Only the threads in this immediate thread group (and not its subgroups) are returned.

Returns:
a List of ThreadReference objects mirroring the threads from this thread group in the target VM.

threadGroups

public List threadGroups()
Returns a List containing each ThreadGroupReference in this thread group. Only the thread groups in this immediate thread group (and not its subgroups) are returned.

Returns:
a List of ThreadGroupReference objects mirroring the threads from this thread group in the target VM.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ThreadReference (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface ThreadReference

All Superinterfaces:
Mirror, ObjectReference, Value
public interface ThreadReference
extends ObjectReference

A thread object from the target VM. A ThreadReference is an ObjectReference with additional access to thread-specific information from the target VM.

Since:
1.3

Field Summary
static int | THREAD_STATUS_MONITOR Thread is waiting on a java monitor
static int | THREAD_STATUS_NOT_STARTED Thread has not yet been started
static int | THREAD_STATUS_RUNNING Thread is runnable
static int | THREAD_STATUS_SLEEPING Thread is sleeping - Thread.sleep() or JVM_Sleep() was called
static int | THREAD_STATUS_UNKNOWN Thread status is unknown
static int | THREAD_STATUS_WAIT Thread is waiting - Thread.wait() or JVM_MonitorWait() was called
static int | THREAD_STATUS_ZOMBIE Thread has completed execution
Fields inherited from interface com.sun.jdi.ObjectReference
INVOKE_NONVIRTUAL, INVOKE_SINGLE_THREADED
Method Summary
ObjectReference | currentContendedMonitor() Returns an ObjectReference for the monitor, if any, for which this thread is currently waiting.
StackFrame | frame(int index) Returns the StackFrame at the given index in the thread's current call stack.
int | frameCount() Returns the number of stack frames in the thread's current call stack.
List | frames() Returns a List containing each StackFrame in the thread's current call stack.
List | frames(int start, int length) Returns a List containing a range of StackFrame mirrors from the thread's current call stack.
void | interrupt() Interrupts this thread unless the thread has been suspended by the debugger.
boolean | isAtBreakpoint() Determines whether the thread is suspended at a breakpoint.
boolean | isSuspended() Determines whether the thread has been suspended by the the debugger.
String | name() Returns the name of this thread.
List | ownedMonitors() Returns a List containing an ObjectReference for each monitor owned by the thread.
void | popFrames(StackFrame frame) Pop stack frames.
void | resume() Resumes this thread.
int | status() Returns the thread's status.
void | stop(ObjectReference throwable) Stops this thread with an asynchronous exception.
void | suspend() Suspends this thread.
int | suspendCount() Returns the number of pending suspends for this thread.
ThreadGroupReference | threadGroup() Returns this thread's thread group.
Methods inherited from interface com.sun.jdi.ObjectReference
disableCollection, enableCollection, entryCount, equals, getValue, getValues, hashCode, invokeMethod, isCollected, owningThread, referenceType, setValue, uniqueID, waitingThreads
Methods inherited from interface com.sun.jdi.Value
type
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Field Detail

THREAD_STATUS_UNKNOWN

public static final int THREAD_STATUS_UNKNOWN
Thread status is unknown

See Also:
Constant Field Values

THREAD_STATUS_ZOMBIE

public static final int THREAD_STATUS_ZOMBIE
Thread has completed execution

See Also:
Constant Field Values

THREAD_STATUS_RUNNING

public static final int THREAD_STATUS_RUNNING
Thread is runnable

See Also:
Constant Field Values

THREAD_STATUS_SLEEPING

public static final int THREAD_STATUS_SLEEPING
Thread is sleeping - Thread.sleep() or JVM_Sleep() was called

See Also:
Constant Field Values

THREAD_STATUS_MONITOR

public static final int THREAD_STATUS_MONITOR
Thread is waiting on a java monitor

See Also:
Constant Field Values

THREAD_STATUS_WAIT

public static final int THREAD_STATUS_WAIT
Thread is waiting - Thread.wait() or JVM_MonitorWait() was called

See Also:
Constant Field Values

THREAD_STATUS_NOT_STARTED

public static final int THREAD_STATUS_NOT_STARTED
Thread has not yet been started

See Also:
Constant Field Values
Method Detail

name

public String name()
Returns the name of this thread.

Returns:
the string containing the thread name.

suspend

public void suspend()
Suspends this thread. The thread can be resumed through resume() or resumed with other threads through VirtualMachine.resume().

Unlike Thread.suspend(), suspends of both the virtual machine and individual threads are counted. Before a thread will run again, it must be resumed (through resume() or resume()) the same number of times it has been suspended.

Suspending single threads with this method has the same dangers as 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 Thread.resume().

resume

public void resume()
Resumes this thread. If this thread was not previously suspended through suspend() or through VirtualMachine.suspend(), or because of a SUSPEND_ALL or SUSPEND_EVENT_THREAD event, then invoking this method 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. Note: the normal way to resume from an event related suspension is via EventSet.resume().

suspendCount

public int suspendCount()
Returns the number of pending suspends for this thread. See suspend() for an explanation of counted suspends.

Returns:
pending suspend count as an integer

stop

public void stop(ObjectReference throwable)
          throws InvalidTypeException
Stops this thread with an asynchronous exception. A debugger thread in the target VM will stop this thread with the given Throwable object.

Parameters:
throwable - the asynchronous exception to throw.
Throws:
InvalidTypeException - if throwable is not an instance of java.lang.Throwable in the target VM.
See Also:
Thread.stop(Throwable)

interrupt

public void interrupt()
Interrupts this thread unless the thread has been suspended by the debugger.

See Also:
Thread.interrupt()

status

public int status()
Returns the thread's status. If the thread is not suspended the thread's current status is returned. If the thread is suspended, the thread's status before the suspension is returned (or THREAD_STATUS_UNKNOWN if this information is not available. isSuspended() can be used to determine if the thread has been suspended.

Returns:
one of THREAD_STATUS_UNKNOWN, THREAD_STATUS_ZOMBIE, THREAD_STATUS_RUNNING, THREAD_STATUS_SLEEPING, THREAD_STATUS_MONITOR, THREAD_STATUS_WAIT, THREAD_STATUS_NOT_STARTED,

isSuspended

public boolean isSuspended()
Determines whether the thread has been suspended by the the debugger.

Returns:
true if the thread is currently suspended; false otherwise.

isAtBreakpoint

public boolean isAtBreakpoint()
Determines whether the thread is suspended at a breakpoint.

Returns:
true if the thread is currently stopped at a breakpoint; false otherwise.

threadGroup

public ThreadGroupReference threadGroup()
Returns this thread's thread group.

Returns:
a ThreadGroupReference that mirrors this thread's thread group in the target VM.

frameCount

public int frameCount()
               throws IncompatibleThreadStateException
Returns the number of stack frames in the thread's current call stack. The thread must be suspended (normally through an interruption to the VM) to get this information, and it is only valid until the thread is resumed again.

Returns:
an integer frame count
Throws:
IncompatibleThreadStateException - if the thread is not suspended in the target VM

frames

public List frames()
            throws IncompatibleThreadStateException
Returns a List containing each StackFrame in the thread's current call stack. The thread must be suspended (normally through an interruption to the VM) to get this information, and it is only valid until the thread is resumed again.

Returns:
a List of StackFrame with the current frame first followed by each caller's frame.
Throws:
IncompatibleThreadStateException - if the thread is not suspended in the target VM

frame

public StackFrame frame(int index)
                 throws IncompatibleThreadStateException
Returns the StackFrame at the given index in the thread's current call stack. Index 0 retrieves the current frame; higher indices retrieve caller frames. The thread must be suspended (normally through an interruption to the VM) to get this information, and it is only valid until the thread is resumed again.

Parameters:
index - the desired frame
Returns:
the requested StackFrame
Throws:
IncompatibleThreadStateException - if the thread is not suspended in the target VM
IndexOutOfBoundsException - if the index is greater than or equal to frameCount() or is negative.

frames

public List frames(int start,
                   int length)
            throws IncompatibleThreadStateException
Returns a List containing a range of StackFrame mirrors from the thread's current call stack. The thread must be suspended (normally through an interruption to the VM) to get this information, and it is only valid until the thread is resumed again.

Parameters:
start - the index of the first frame to retrieve. Index 0 represents the current frame.
length - the number of frames to retrieve
Returns:
a List of StackFrame with the current frame first followed by each caller's frame.
Throws:
IncompatibleThreadStateException - if the thread is not suspended in the target VM
IndexOutOfBoundsException - if the specified range is not within the range of stack frame indicies. That is, the exception is thrown if any of the following are true:
    start < 0
    start >= frameCount()
    length < 0
    (start+length) > frameCount()

ownedMonitors

public List ownedMonitors()
                   throws IncompatibleThreadStateException
Returns a List containing an ObjectReference for each monitor owned by the thread. A monitor is owned by a thread if it has been entered (via the synchronized statement or entry into a synchronized method) and has not been relinquished through Object.wait(long).

Not all target virtual machines support this operation. Use VirtualMachine.canGetOwnedMonitorInfo() to determine if the operation is supported.

Returns:
a List of ObjectReference objects. The list has zero length if no monitors are owned by this thread.
Throws:
UnsupportedOperationException - if the target virtual machine does not support this operation.
IncompatibleThreadStateException - if the thread is not suspended in the target VM

currentContendedMonitor

public ObjectReference currentContendedMonitor()
                                        throws IncompatibleThreadStateException
Returns an ObjectReference for the monitor, if any, for which this thread is currently waiting. The thread can be waiting for a monitor through entry into a synchronized method, the synchronized statement, or Object.wait(long). The status() method can be used to differentiate between the first two cases and the third.

Not all target virtual machines support this operation. Use VirtualMachine.canGetCurrentContendedMonitor() to determine if the operation is supported.

Returns:
the ObjectReference corresponding to the contended monitor, or null if it is not waiting for a monitor.
Throws:
UnsupportedOperationException - if the target virtual machine does not support this operation.
IncompatibleThreadStateException - if the thread is not suspended in the target VM

popFrames

public void popFrames(StackFrame frame)
               throws IncompatibleThreadStateException
Pop stack frames.

All frames up to and including the frame are popped off the stack. The frame previous to the parameter frame will become the current frame.

After this operation, this thread will be suspended at the invoke instruction of the target method that created frame. The frame's method can be reentered with a step into the instruction.

The operand stack is restored, however, any changes to the arguments that occurred in the called method, remain. For example, if the method foo:

    void foo(int x) {
        System.out.println("Foo: " + x);
        x = 4;
        System.out.println("pop here");
    }
was called with foo(7) and foo is popped at the second println and resumed, it will print: Foo: 4.

Locks acquired by a popped frame are released when it is popped. This applies to synchronized methods that are popped, and to any synchronized blocks within them.

Finally blocks are not executed.

No aspect of state, other than this thread's execution point and locks, is affected by this call. Specifically, the values of fields are unchanged, as are external resources such as I/O streams. Additionally, the target program might be placed in a state that is impossible with normal program flow; for example, order of lock acquisition might be perturbed. Thus the target program may proceed differently than the user would expect.

The specified thread must be suspended.

All StackFrame objects for this thread are invalidated.

No events are generated by this method.

None of the frames through and including the frame for the caller of frame may be native.

Not all target virtual machines support this operation. Use VirtualMachine.canPopFrames() to determine if the operation is supported.

Parameters:
frame - Stack frame to pop. frame is on this thread's call stack.
Throws:
UnsupportedOperationException - if the target virtual machine does not support this operation - see VirtualMachine.canPopFrames().
IncompatibleThreadStateException - if this thread is not suspended.
IllegalArgumentException - if frame is not on this thread's call stack.
NativeMethodException - if one of the frames that would be popped is that of a native method or if the frame previous to frame is native.
InvalidStackFrameException - if frame has become invalid. Once this thread is resumed, the stack frame is no longer valid. This exception is also thrown if there are no more frames.
Since:
1.4
Overview  Package   Class  Use  Tree  Index  Help
Java Debug Interface
 PREV CLASS   NEXT CLASS FRAMES    NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Type (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface Type

All Superinterfaces:
Mirror
All Known Subinterfaces:
ArrayType, BooleanType, ByteType, CharType, ClassType, DoubleType, FloatType, IntegerType, InterfaceType, LongType, PrimitiveType, ReferenceType, ShortType, VoidType
public interface Type
extends Mirror

The mirror for a type in the target VM. This interface is the root of a type hierarchy encompassing primitive types and reference types.

A Type may be used to represent a run-time type:

Value.type()
or a compile-time type:
Field.type()
Method.returnType()
Method.argumentTypes()
LocalVariable.type()
ArrayType.componentType()

The following table illustrates which subinterfaces of Type are used to mirror types in the target VM --

Subinterfaces of PrimitiveType
Type declared in target as |  | Is mirrored as an instance of
boolean |  | BooleanType
byte |  | ByteType
char |  | CharType
double |  | DoubleType
float |  | FloatType
int |  | IntegerType
long |  | LongType
short |  | ShortType
void |  | VoidType
Subinterfaces of ReferenceType
Type declared in target as | For example | Is mirrored as an instance of
a class | Date | ClassType
an interface | Runnable | InterfaceType
an array |  | ArrayType
an array | int[] | ArrayType whose componentType() is IntegerType
an array | Date[] | ArrayType whose componentType() is ClassType
an array | Runnable[] | ArrayType whose componentType() is InterfaceType

Since:
1.3
See Also:
Subinterface PrimitiveType, Subinterface ReferenceType, Value - for relationship between Type and Value, Field.type() - for usage examples

Method Summary
String | name()
String | signature() Returns the JNI-style signature for this type.
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Method Detail

signature

public String signature()
Returns the JNI-style signature for this type.

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 Integer.TYPE.

Returns:
the string containing the type signature.
See Also:
Type Signatures

name

public String name()
Returns:
a text representation of this type.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


TypeComponent (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface TypeComponent

All Superinterfaces:
Accessible, Mirror
All Known Subinterfaces:
Field, Method
public interface TypeComponent
extends Mirror, Accessible

An entity declared within a user defined type (class or interface). This interface is the root of the type component hierarchy which includes Field and Method. Type components of the same name declared in different classes (including those related by inheritance) have different TypeComponent objects. TypeComponents can be used alone to retrieve static information about their declaration, or can be used in conjunction with a ReferenceType or ObjectReference to access values or invoke, as applicable.

Since:
1.3

Method Summary
ReferenceType | declaringType() Returns the type in which this component was declared.
boolean | isFinal() Determines if this TypeComponent is final.
boolean | isStatic() Determines if this TypeComponent is static.
boolean | isSynthetic() Determines if this TypeComponent is synthetic.
String | name() Gets the name of this type component.
String | signature() Gets the JNI-style signature for this type component.
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine
Methods inherited from interface com.sun.jdi.Accessible
isPackagePrivate, isPrivate, isProtected, isPublic, modifiers

Method Detail

name

public String name()
Gets the name of this type component.

Note: for fields, this is the field name; for methods, this is the method name; for constructors, this is <init>; for static initializers, this is <clinit>.

Returns:
a string containing the name.

signature

public String signature()
Gets the JNI-style signature for this type component. The signature is encoded type information as defined in the JNI documentation. It is a convenient, compact format for for manipulating type information internally, not necessarily for display to an end user. See Field.typeName() and Method.returnTypeName() for ways to help get a more readable representation of the type.

Returns:
a string containing the signature
See Also:
Type Signatures

declaringType

public ReferenceType declaringType()
Returns the type in which this component was declared. The returned ReferenceType mirrors either a class or an interface in the target VM.

Returns:
a ReferenceType for the type that declared this type component.

isStatic

public boolean isStatic()
Determines if this TypeComponent is static. Return value is undefined for constructors and static initializers.

Returns:
true if this type component was declared static; false otherwise.

isFinal

public boolean isFinal()
Determines if this TypeComponent is final. Return value is undefined for constructors and static initializers.

Returns:
true if this type component was declared final; false otherwise.

isSynthetic

public boolean isSynthetic()
Determines if this TypeComponent is synthetic. Synthetic members are generated by the compiler and are not present in the source code for the containing class.

Not all target VMs support this query. See VirtualMachine.canGetSyntheticAttribute() to determine if the operation is supported.

Returns:
true if this type component is synthetic; false otherwise.
Throws:
UnsupportedOperationException - if the target VM cannot provide information on synthetic attributes.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Value (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface Value

All Superinterfaces:
Mirror
All Known Subinterfaces:
ArrayReference, BooleanValue, ByteValue, CharValue, ClassLoaderReference, ClassObjectReference, DoubleValue, FloatValue, IntegerValue, LongValue, ObjectReference, PrimitiveValue, ShortValue, StringReference, ThreadGroupReference, ThreadReference, VoidValue
public interface Value
extends Mirror

The mirror for a value in the target VM. This interface is the root of a value hierarchy encompassing primitive values and object values.

Some examples of where values may be accessed:

ObjectReference.getValue(Field) | - value of a field
StackFrame.getValue(LocalVariable) | - value of a variable
VirtualMachine.mirrorOf(double) | - created in the target VM by the JDI client
ModificationWatchpointEvent.valueToBe() | - returned with an event

The following table illustrates which subinterfaces of Value are used to mirror values in the target VM --

Subinterfaces of PrimitiveValue
Kind of value For example -
expression in target 		Is mirrored as an
instance of 		Type of value
Value.type()
a boolean | true | BooleanValue | BooleanType
a byte | (byte)4 | ByteValue | ByteType
a char | 'a' | CharValue | CharType
a double | 3.1415926 | DoubleValue | DoubleType
a float | 2.5f | FloatValue | FloatType
an int | 22 | IntegerValue | IntegerType
a long | 1024L | LongValue | LongType
a short | (short)12 | ShortValue | ShortType
a void   | VoidValue | VoidType
Subinterfaces of ObjectReference
Kind of value For example -
expression in target 		Is mirrored as an
instance of 		Type of value
Value.type()
a class instance | this | ObjectReference | ClassType
an array | new int[5] | ArrayReference | ArrayType
a string | "hello" | StringReference | ClassType
a thread | Thread.currentThread() | ThreadReference | ClassType
a thread group Thread.currentThread()
  .getThreadGroup() 		ThreadGroupReference ClassType
a java.lang.Class
instance 		this.getClass() ClassObjectReference ClassType
a class loader this.getClass()
  .getClassLoader() 		ClassLoaderReference ClassType
Other
Kind of value For example -
expression in target 		Is mirrored as Type of value
null | null | null | n/a

Since:
1.3

Method Summary
 Type type()
Returns the run-time type of this value.
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Method Detail

type

public Type type()
Returns the run-time type of this value.

Returns:
a Type which mirrors the value's type in the target VM.
See Also:
Type
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


VirtualMachine (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface VirtualMachine

All Superinterfaces:
Mirror
All Known Subinterfaces:
PathSearchingVirtualMachine
public interface VirtualMachine
extends Mirror

A virtual machine targeted for debugging. More precisely, a mirror representing the composite state of the target VM. All other mirrors are associated with an instance of this interface. Access to all other mirrors is achieved directly or indirectly through an instance of this interface. Access to global VM properties and control of VM execution are supported directly by this interface.

Instances of this interface are created by instances of Connector. Note that a target VM launched by a launching connector is not guaranteed to be stable until after the VMStartEvent has been received.

Any method on VirtualMachine which takes VirtualMachine as an parameter may throw VMDisconnectedException if the target VM is disconnected and the VMDisconnectEvent has been or is available to be read from the EventQueue.

Any method on VirtualMachine which takes VirtualMachine as an parameter may throw VMOutOfMemoryException if the target VM has run out of memory.

Since:
1.3

Field Summary
static int | TRACE_ALL All tracing is enabled.
static int | TRACE_EVENTS Tracing enabled for internal event handling.
static int | TRACE_NONE All tracing is disabled.
static int | TRACE_OBJREFS Tracing enabled for internal management of object references.
static int | TRACE_RECEIVES Tracing enabled for JDWP packets received from target VM.
static int | TRACE_REFTYPES Tracing enabled for internal managment of reference types.
static int | TRACE_SENDS Tracing enabled for JDWP packets sent to target VM.
Method Summary
List | allClasses() Returns all loaded types.
List | allThreads() Returns a list of the currently running threads.
boolean | canAddMethod() Determines if the target VM supports the addition of methods when performing class redefinition.
boolean | canGetBytecodes() Determines if the target VM supports the retrieval of a method's bytecodes.
boolean | canGetCurrentContendedMonitor() Determines if the target VM supports the retrieval of the monitor for which a thread is currently waiting.
boolean | canGetMonitorInfo() Determines if the target VM supports the retrieval of the monitor information for an object.
boolean | canGetOwnedMonitorInfo() Determines if the target VM supports the retrieval of the monitors owned by a thread.
boolean | canGetSourceDebugExtension() Determines if the target VM supports getting the source debug extension.
boolean | canGetSyntheticAttribute() Determines if the target VM supports the query of the synthetic attribute of a method or field.
boolean | canPopFrames() Determines if the target VM supports popping frames of a threads stack.
boolean | canRedefineClasses() Determines if the target VM supports any level of class redefinition.
boolean | canRequestVMDeathEvent() Determines if the target VM supports the creation of VMDeathRequests.
boolean | canUnrestrictedlyRedefineClasses() Determines if the target VM supports unrestricted changes when performing class redefinition.
boolean | canUseInstanceFilters() Determines if the target VM supports filtering events by specific instance object.
boolean | canWatchFieldAccess() Determines if the target VM supports watchpoints for field access.
boolean | canWatchFieldModification() Determines if the target VM supports watchpoints for field modification.
List | classesByName(String className) Returns the loaded reference types that match a given name.
String | description() Returns text information on the target VM and the debugger support that mirrors it.
void | dispose() Invalidates this virtual machine mirror.
EventQueue | eventQueue() Returns the event queue for this virtual machine.
EventRequestManager | eventRequestManager() Returns the event request manager for this virtual machine.
void | exit(int exitCode) Causes the mirrored VM to terminate with the given error code.
String | getDefaultStratum() Return this VM's default stratum.
BooleanValue | mirrorOf(boolean value) Creates a BooleanValue for the given value.
ByteValue | mirrorOf(byte value) Creates a ByteValue for the given value.
CharValue | mirrorOf(char value) Creates a CharValue for the given value.
DoubleValue | mirrorOf(double value) Creates a DoubleValue for the given value.
FloatValue | mirrorOf(float value) Creates a FloatValue for the given value.
IntegerValue | mirrorOf(int value) Creates an IntegerValue for the given value.
LongValue | mirrorOf(long value) Creates a LongValue for the given value.
ShortValue | mirrorOf(short value) Creates a ShortValue for the given value.
StringReference | mirrorOf(String value) Creates a string in this virtual machine.
String | name() Returns the name of the target VM as reported by the property java.vm.name.
Process | process() Returns the Process object for this virtual machine if launched by a LaunchingConnector
void | redefineClasses(Map classToBytes) All classes given are redefined according to the definitions supplied.
void | resume() Continues the execution of the application running in this virtual machine.
void | setDebugTraceMode(int traceFlags) Traces the activities performed by the com.sun.jdi implementation.
void | setDefaultStratum(String stratum) Set this VM's default stratum (see Location for a discussion of strata).
void | suspend() Suspends the execution of the application running in this virtual machine.
List | topLevelThreadGroups() Returns each thread group which does not have a parent.
String | version() Returns the version of the Java Runtime Environment in the target VM as reported by the property java.version.
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Field Detail

TRACE_NONE

public static final int TRACE_NONE
All tracing is disabled.

See Also:
Constant Field Values

TRACE_SENDS

public static final int TRACE_SENDS
Tracing enabled for JDWP packets sent to target VM.

See Also:
Constant Field Values

TRACE_RECEIVES

public static final int TRACE_RECEIVES
Tracing enabled for JDWP packets received from target VM.

See Also:
Constant Field Values

TRACE_EVENTS

public static final int TRACE_EVENTS
Tracing enabled for internal event handling.

See Also:
Constant Field Values

TRACE_REFTYPES

public static final int TRACE_REFTYPES
Tracing enabled for internal managment of reference types.

See Also:
Constant Field Values

TRACE_OBJREFS

public static final int TRACE_OBJREFS
Tracing enabled for internal management of object references.

See Also:
Constant Field Values

TRACE_ALL

public static final int TRACE_ALL
All tracing is enabled.

See Also:
Constant Field Values
Method Detail

classesByName

public List classesByName(String className)
Returns the loaded reference types that match a given name. The name must be fully qualified (for example, java.lang.String). The returned list will contain a ReferenceType for each class or interface found with the given name. The search is confined to loaded classes only; no attempt is made to load a class of the given name.

The returned list will include reference types loaded at least to the point of preparation and types (like array) for which preparation is not defined.

Parameters:
className - the class/interface name to search for
Returns:
a list of ReferenceType objects, each mirroring a type in the target VM with the given name.

allClasses

public List allClasses()
Returns all loaded types. For each loaded type in the target VM a ReferenceType will be placed in the returned list. The list will include ReferenceTypes which mirror classes, interfaces, and array types.

The returned list will include reference types loaded at least to the point of preparation and types (like array) for which preparation is not defined.

Returns:
a list of ReferenceType objects, each mirroring a loaded type in the target VM.

redefineClasses

public void redefineClasses(Map classToBytes)
All classes given are redefined according to the definitions supplied. If any redefined methods have active stack frames, those active frames continue to run the bytecodes of the previous method. The redefined methods will be used on new invokes. If resetting these frames is desired, use ThreadReference.popFrames(StackFrame) with Method.isObsolete().

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 preexisting static variables will remain as they were prior to the call. However, completely uninitialized (new) static variables will be assigned their default value.

If a redefined class has instances then all those instances will have the fields defined by the redefined class at the completion of the call. Preexisting fields will retain their previous values. Any new fields will have their default values; no instance initializers or constructors are run.

Threads need not be suspended.

No events are generated by this function.

All breakpoints in the redefined classes are deleted.

Not all target virtual machines support this operation. Use canRedefineClasses() to determine if the operation is supported. Use canAddMethod() to determine if the redefinition can add methods. Use canUnrestrictedlyRedefineClasses() to determine if the redefinition can change the schema, delete methods, change the class hierarchy, etc.

Parameters:
classToBytes - A map from ReferenceType to array of byte. The bytes represent the new class definition and are in Java Virtual Machine class file format.
Throws:
UnsupportedOperationException - if the target virtual machine does not support this operation.
  • If canRedefineClasses() is false any call of this method will throw this exception.
  • If canAddMethod() is false attempting to add a method will throw this exception.
  • If canUnrestrictedlyRedefineClasses() is false, attempting any of the following will throw this exception
    • changing the schema (the fields)
    • changing the hierarchy (subclasses, interfaces)
    • deleting a method
    • changing class modifiers
    • changing method modifiers
NoClassDefFoundError - if the bytes don't correspond to the reference type (the names don't match).
VerifyError - if a "verifier" detects that a class, though well formed, contains an internal inconsistency or security problem.
ClassFormatError - if the bytes do not represent a valid class.
ClassCircularityError - if a circularity has been detected while initializing a class.
UnsupportedClassVersionError - if the major and minor version numbers in bytes are not supported by the VM.
Since:
1.4
See Also:
Method.isObsolete(),
ThreadReference.popFrames(com.sun.jdi.StackFrame),
canRedefineClasses(),
canAddMethod(),
canUnrestrictedlyRedefineClasses()

allThreads

public List allThreads()
Returns a list of the currently running threads. For each running thread in the target VM, a ThreadReference that mirrors it is placed in the list. 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. Thread objects that have not yet been started (see Thread.start()) and thread objects that have completed their execution are not included in the returned list.

Returns:
a list of ThreadReference objects, one for each running thread in the mirrored VM.

suspend

public void suspend()
Suspends the execution of the application running in this virtual machine. All threads currently running will be suspended.

Unlike Thread.suspend(), suspends of both the virtual machine and individual threads are counted. Before a thread will run again, it must be resumed (through resume() or ThreadReference.resume()) the same number of times it has been suspended.

resume

public void resume()
Continues the execution of the application running in this virtual machine. All threads are resumed as documented in ThreadReference.resume().

See Also:
suspend()

topLevelThreadGroups

public List topLevelThreadGroups()
Returns each thread group which does not have a parent. For each top level thread group a ThreadGroupReference is placed in the returned list.

This command may be used as the first step in building a tree (or trees) of the existing thread groups.

Returns:
a list of ThreadGroupReference objects, one for each top level thread group.

eventQueue

public EventQueue eventQueue()
Returns the event queue for this virtual machine. A virtual machine has only one EventQueue object, this method will return the same instance each time it is invoked.

Returns:
the EventQueue for this virtual machine.

eventRequestManager

public EventRequestManager eventRequestManager()
Returns the event request manager for this virtual machine. The EventRequestManager controls user settable events such as breakpoints. A virtual machine has only one EventRequestManager object, this method will return the same instance each time it is invoked.

Returns:
the EventRequestManager for this virtual machine.

mirrorOf

public BooleanValue mirrorOf(boolean value)
Creates a BooleanValue for the given value. This value can be used for setting and comparing against a value retrieved from a variable or field in this virtual machine.

Parameters:
value - a boolean for which to create the value
Returns:
the BooleanValue for the given boolean.

mirrorOf

public ByteValue mirrorOf(byte value)
Creates a ByteValue for the given value. This value can be used for setting and comparing against a value retrieved from a variable or field in this virtual machine.

Parameters:
value - a byte for which to create the value
Returns:
the ByteValue for the given byte.

mirrorOf

public CharValue mirrorOf(char value)
Creates a CharValue for the given value. This value can be used for setting and comparing against a value retrieved from a variable or field in this virtual machine.

Parameters:
value - a char for which to create the value
Returns:
the CharValue for the given char.

mirrorOf

public ShortValue mirrorOf(short value)
Creates a ShortValue for the given value. This value can be used for setting and comparing against a value retrieved from a variable or field in this virtual machine.

Parameters:
value - a short for which to create the value
Returns:
the ShortValue for the given short.

mirrorOf

public IntegerValue mirrorOf(int value)
Creates an IntegerValue for the given value. This value can be used for setting and comparing against a value retrieved from a variable or field in this virtual machine.

Parameters:
value - an int for which to create the value
Returns:
the IntegerValue for the given int.

mirrorOf

public LongValue mirrorOf(long value)
Creates a LongValue for the given value. This value can be used for setting and comparing against a value retrieved from a variable or field in this virtual machine.

Parameters:
value - a long for which to create the value
Returns:
the LongValue for the given long.

mirrorOf

public FloatValue mirrorOf(float value)
Creates a FloatValue for the given value. This value can be used for setting and comparing against a value retrieved from a variable or field in this virtual machine.

Parameters:
value - a float for which to create the value
Returns:
the FloatValue for the given float.

mirrorOf

public DoubleValue mirrorOf(double value)
Creates a DoubleValue for the given value. This value can be used for setting and comparing against a value retrieved from a variable or field in this virtual machine.

Parameters:
value - a double for which to create the value
Returns:
the DoubleValue for the given double.

mirrorOf

public StringReference mirrorOf(String value)
Creates a string in this virtual machine. The created string can be used for setting and comparing against a string value retrieved from a variable or field in this virtual machine.

Parameters:
value - the string to be created
Returns:
a StringReference that mirrors the newly created string in the target VM.

process

public Process process()
Returns the Process object for this virtual machine if launched by a LaunchingConnector

Returns:
the Process object for this virtual machine, or null if it was not launched by a LaunchingConnector.

dispose

public void dispose()
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 suspend() or by ThreadReference.suspend() are resumed as many times as necessary for them to run.
  • Garbage collection is re-enabled in all cases where it was disabled through ObjectReference.disableCollection().
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.

exit

public void exit(int exitCode)
Causes the mirrored VM to terminate with the given error code. All resources associated with this VirtualMachine are freed. If the mirrored VM is remote, the communication channel to it will be closed. Resources originating in this VirtualMachine (ObjectReferences, ReferenceTypes, etc.) will become invalid.

Threads running in the mirrored VM are abruptly terminated. A thread death exception is not thrown and finally blocks are not run.

Parameters:
exitCode - the exit code for the target VM. On some platforms, the exit code might be truncated, for example, to the lower order 8 bits.

canWatchFieldModification

public boolean canWatchFieldModification()
Determines if the target VM supports watchpoints for field modification.

Returns:
true if the feature is supported, false otherwise.

canWatchFieldAccess

public boolean canWatchFieldAccess()
Determines if the target VM supports watchpoints for field access.

Returns:
true if the feature is supported, false otherwise.

canGetBytecodes

public boolean canGetBytecodes()
Determines if the target VM supports the retrieval of a method's bytecodes.

Returns:
true if the feature is supported, false otherwise.

canGetSyntheticAttribute

public boolean canGetSyntheticAttribute()
Determines if the target VM supports the query of the synthetic attribute of a method or field.

Returns:
true if the feature is supported, false otherwise.

canGetOwnedMonitorInfo

public boolean canGetOwnedMonitorInfo()
Determines if the target VM supports the retrieval of the monitors owned by a thread.

Returns:
true if the feature is supported, false otherwise.

canGetCurrentContendedMonitor

public boolean canGetCurrentContendedMonitor()
Determines if the target VM supports the retrieval of the monitor for which a thread is currently waiting.

Returns:
true if the feature is supported, false otherwise.

canGetMonitorInfo

public boolean canGetMonitorInfo()
Determines if the target VM supports the retrieval of the monitor information for an object.

Returns:
true if the feature is supported, false otherwise.

canUseInstanceFilters

public boolean canUseInstanceFilters()
Determines if the target VM supports filtering events by specific instance object. For example, see BreakpointRequest.addInstanceFilter(com.sun.jdi.ObjectReference).

Returns:
true if the feature is supported, false otherwise.

canRedefineClasses

public boolean canRedefineClasses()
Determines if the target VM supports any level of class redefinition.

Returns:
true if the feature is supported, false otherwise.
Since:
1.4
See Also:
redefineClasses(java.util.Map)

canAddMethod

public boolean canAddMethod()
Determines if the target VM supports the addition of methods when performing class redefinition.

Returns:
true if the feature is supported, false otherwise.
Since:
1.4
See Also:
redefineClasses(java.util.Map)

canUnrestrictedlyRedefineClasses

public boolean canUnrestrictedlyRedefineClasses()
Determines if the target VM supports unrestricted changes when performing class redefinition.

Returns:
true if the feature is supported, false otherwise.
Since:
1.4
See Also:
redefineClasses(java.util.Map)

canPopFrames

public boolean canPopFrames()
Determines if the target VM supports popping frames of a threads stack.

Returns:
true if the feature is supported, false otherwise.
Since:
1.4
See Also:
ThreadReference.popFrames(com.sun.jdi.StackFrame)

canGetSourceDebugExtension

public boolean canGetSourceDebugExtension()
Determines if the target VM supports getting the source debug extension.

Returns:
true if the feature is supported, false otherwise.
Since:
1.4
See Also:
ReferenceType.sourceDebugExtension()

canRequestVMDeathEvent

public boolean canRequestVMDeathEvent()
Determines if the target VM supports the creation of VMDeathRequests.

Returns:
true if the feature is supported, false otherwise.
Since:
1.4
See Also:
EventRequestManager.createVMDeathRequest()

setDefaultStratum

public void setDefaultStratum(String stratum)
Set this VM's default stratum (see Location for a discussion of strata). Overrides the per-class default set in the class file.

Affects location queries (such as, Location.sourceName()) and the line boundaries used in single stepping.

Parameters:
stratum - the stratum to set as VM default, or null to use per-class defaults.
Throws:
UnsupportedOperationException - if the target virtual machine does not support this operation.
Since:
1.4

getDefaultStratum

public String getDefaultStratum()
Return this VM's default stratum.

Returns:
null (meaning that the per-class default - ReferenceType.defaultStratum() - should be used) unless the default stratum has been set with setDefaultStratum(String).
Since:
1.4
See Also:
setDefaultStratum(String), ReferenceType.defaultStratum()

description

public String description()
Returns text information on the target VM and the debugger support that mirrors it. No specific format for this information is guaranteed. Typically, this string contains version information for the target VM and debugger interfaces. More precise information on VM and JDI versions is available through version(), VirtualMachineManager.majorInterfaceVersion(), and VirtualMachineManager.minorInterfaceVersion()

Returns:
the description.

version

public String version()
Returns the version of the Java Runtime Environment in the target VM as reported by the property java.version. For obtaining the JDI interface version, use VirtualMachineManager.majorInterfaceVersion() and VirtualMachineManager.minorInterfaceVersion()

Returns:
the target VM version.

name

public String name()
Returns the name of the target VM as reported by the property java.vm.name.

Returns:
the target VM name.

setDebugTraceMode

public void setDebugTraceMode(int traceFlags)
Traces the activities performed by the com.sun.jdi implementation. All trace information is output to System.err. The given trace flags are used to limit the output to only the information desired. The given flags are in effect and the corresponding trace will continue until the next call to this method.

Output is implementation dependent and trace mode may be ignored.

Parameters:
traceFlags - identifies which kinds of tracing to enable.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


VirtualMachineManager (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface VirtualMachineManager

public interface VirtualMachineManager

A manager of connections to target virtual machines. The VirtualMachineManager allows one application to debug multiple target VMs. (Note that the converse is not supported; a target VM can be debugged by only one debugger application.) This interface contains methods to manage connections to remote target VMs and to obtain the VirtualMachine mirror for available target VMs.

Connections can be made using one of several different Connector objects. Each connector encapsulates a different way of connecting the debugger with a target VM.

The VirtualMachineManager supports many different scenarios for connecting a debugger to a virtual machine. Four examples are presented in the table below. The examples use the command line syntax in Sun's classic VM. Some Connector implementations may require slightly different handling than presented below.

Scenario Description
Debugger launches target VM (simplest, most-common scenario) Debugger calls the LaunchingConnector.launch(java.util.Map) method of the default connector, obtained with defaultConnector(). The target VM is launched, and a connection between that VM and the debugger is established. A VirtualMachine mirror is returned.

Or, for more control

  • Debugger selects a connector from the list returned by launchingConnectors() with desired characteristics (for example, transport type, etc.).
  • Debugger calls the LaunchingConnector.launch(java.util.Map) method of the selected connector. The target VM is launched, and a connection between that VM and the debugger is established. A VirtualMachine mirror is returned.
Debugger attaches to previously-running VM
  • Target VM is launched using the options -Xrunjdwp:transport=xxx,server=y -Xdebug -Xnoagent -Djava.compiler=NONE
  • Target VM generates and outputs the tranport-specific address at which it will listen for a connection.
  • Debugger is launched. Debugger selects a connector in the list returned by attachingConnectors() matching the transport with the name "xxx".
  • Debugger presents the default connector parameters (obtained through Connector.defaultArguments()) to the end user, allowing the user to fill in the transport-specific address generated by the target VM.
  • Debugger calls the AttachingConnector.attach(java.util.Map) method of the selected to attach to the target VM. A VirtualMachine mirror is returned.
Target VM attaches to previously-running debugger
  • At startup, debugger selects one or more connectors from the list returned by listeningConnectors() for one or more transports.
  • Debugger calls the ListeningConnector.startListening(java.util.Map) method for each selected connector. For each call, a transport-specific address string is generated and returned. The debugger makes the transport names and corresponding address strings available to the end user.
  • Debugger calls ListeningConnector.accept(java.util.Map) for each selected connector to wait for a target VM to connect.
  • Later, target VM is launched by end user with the options -Xrunjdwp:transport=xxx,address=yyy -Xdebug -Xnoagent -Djava.compiler=NONE where "xxx" the transport for one of the connectors selected by the the debugger and "yyy" is the address generated by ListeningConnector.accept(java.util.Map) for that transport.
  • Debugger's call to ListeningConnector.accept(java.util.Map) returns a VirtualMachine mirror.
            •
    Target VM launches debugger (sometimes called "Just-In-Time" debugging)
  • Target VM is launched with the options -Xrunjdwp:launch=cmdline,onuncaught=y,transport=xxx,server=y
  • Later, an uncaught exception is thrown in the target VM. The target VM generates the tranport-specific address at which it will listen for a connection.
  • Target VM launches the debugger with the following items concatenated together (separated by spaces) to form the command line:
    • The launch= value
    • The transport= value
    • The generated transport-specific address at which VM is listening for debugger connection.
  • Upon launch, debugger selects a connector in the list returned by attachingConnectors() matching the transport with the name "xxx".
  • Debugger changes the default connector parameters (obtained through Connector.defaultArguments()) to specify the transport specific address at which the VM is listenig. Optionally, other connector arguments can be presented to the user.
  • Debugger calls the AttachingConnector.attach(java.util.Map) method of the selected to attach to the target VM. A VirtualMachine mirror is returned.

    • Since:
    1.3

    Method Summary
List | allConnectors() Returns the list of all known Connector objects.
List | attachingConnectors() Returns the list of known AttachingConnector objects.
List | connectedVirtualMachines() Lists all target VMs which are connected to the debugger.
LaunchingConnector | defaultConnector() Identifies the default connector.
List | launchingConnectors() Returns the list of known LaunchingConnector objects.
List | listeningConnectors() Returns the list of known ListeningConnector objects.
int | majorInterfaceVersion() Returns the major version number of the JDI interface.
int | minorInterfaceVersion() Returns the minor version number of the JDI interface.

    Method Detail

    defaultConnector

    public LaunchingConnector defaultConnector()
    Identifies the default connector. This connector should be used as the launching connector when selection of a connector with specific characteristics is unnecessary.

    Returns:
    the default LaunchingConnector

    launchingConnectors

    public List launchingConnectors()
    Returns the list of known LaunchingConnector objects. Any of the returned objects can be used to launch a new target VM and immediately create a VirtualMachine mirror for it. Note that a target VM launched by a launching connector is not guaranteed to be stable until after the VMStartEvent has been received.

    Returns:
    a list of LaunchingConnector objects.

    attachingConnectors

    public List attachingConnectors()
    Returns the list of known AttachingConnector objects. Any of the returned objects can be used to attach to an existing target VM and create a VirtualMachine mirror for it.

    Returns:
    a list of AttachingConnector objects.

    listeningConnectors

    public List listeningConnectors()
    Returns the list of known ListeningConnector objects. Any of the returned objects can be used to listen for a connection initiated by a target VM and create a VirtualMachine mirror for it.

    Returns:
    a list of ListeningConnector objects.

    allConnectors

    public List allConnectors()
    Returns the list of all known Connector objects.

    Returns:
    a list of Connector objects.

    connectedVirtualMachines

    public List connectedVirtualMachines()
    Lists all target VMs which are connected to the debugger. The list includes VirtualMachine instances for any target VMs which initiated a connection and any target VMs to which this manager has initiated a connection. A target VM will remain in this list until the VM is disconnected. VMDisconnectEvent is placed in the event queue after the VM is removed from the list.

    Returns:
    a list of VirtualMachine objects, each mirroring a target VM.

    majorInterfaceVersion

    public int majorInterfaceVersion()
    Returns the major version number of the JDI interface. See VirtualMachine.version() target VM version and information and VirtualMachine.description() more version information.

    Returns:
    the integer major version number.

    minorInterfaceVersion

    public int minorInterfaceVersion()
    Returns the minor version number of the JDI interface. See VirtualMachine.version() target VM version and information and VirtualMachine.description() more version information.

    Returns:
    the integer minor version number
    Overview Package Class Use Tree Index Help
            Java Debug Interface
    PREV CLASS NEXT CLASS FRAMES NO FRAMES
    SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


VMDisconnectedException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Class VMDisconnectedException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by com.sun.jdi.VMDisconnectedException
All Implemented Interfaces:
Serializable
public class VMDisconnectedException
extends RuntimeException

Unchecked exception thrown to indicate that the requested operation cannot be completed because there is no longer a connection to the target VM.

Since:
1.3
See Also:
Serialized Form

Constructor Summary
VMDisconnectedException()
VMDisconnectedException(String message)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

VMDisconnectedException

public VMDisconnectedException()

VMDisconnectedException

public VMDisconnectedException(String message)
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


VMMismatchException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Class VMMismatchException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by com.sun.jdi.VMMismatchException
All Implemented Interfaces:
Serializable
public class VMMismatchException
extends RuntimeException

Thrown to indicate that the requested operation cannot be completed because the a mirror from one target VM is being combined with a mirror from another target VM.

Since:
1.3
See Also:
Serialized Form

Constructor Summary
VMMismatchException()
VMMismatchException(String s)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

VMMismatchException

public VMMismatchException()

VMMismatchException

public VMMismatchException(String s)
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


VMOutOfMemoryException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Class VMOutOfMemoryException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by com.sun.jdi.VMOutOfMemoryException
All Implemented Interfaces:
Serializable
public class VMOutOfMemoryException
extends RuntimeException

Thrown to indicate that the requested operation cannot be completed because the target VM has run out of memory.

Since:
1.3
See Also:
Serialized Form

Constructor Summary
VMOutOfMemoryException()
VMOutOfMemoryException(String s)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

VMOutOfMemoryException

public VMOutOfMemoryException()

VMOutOfMemoryException

public VMOutOfMemoryException(String s)
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


VoidType (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface VoidType

All Superinterfaces:
Mirror, Type
public interface VoidType
extends Type

The type of all primitive void values accessed in the target VM. Calls to Value.type() will return an implementor of this interface.

Since:
1.3
See Also:
VoidValue

Methods inherited from interface com.sun.jdi.Type
name, signature
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


VoidValue (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi
Interface VoidValue

All Superinterfaces:
Mirror, Value
public interface VoidValue
extends Value

Provides access to a primitive void value in the target VM.

Since:
1.3

Method Summary
boolean | equals(Object obj) Compares the specified Object with this VoidValue for equality.
int | hashCode() Returns the hash code value for this VoidValue.
Methods inherited from interface com.sun.jdi.Value
type
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Method Detail

equals

public boolean equals(Object obj)
Compares the specified Object with this VoidValue for equality.

Returns:
true if the Object is a VoidValue; false otherwise.

hashCode

public int hashCode()
Returns the hash code value for this VoidValue.

Returns:
the hash code
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Uses of Class com.sun.jdi.AbsentInformationException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.jdi.AbsentInformationException

Packages that use AbsentInformationException
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
String | Location.sourceName() Gets an identifing name for the source corresponding to this location.
String | Location.sourceName(String stratum) Gets an identifing name for the source corresponding to this location.
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 | StackFrame.visibleVariables() Returns a list containing each LocalVariable that can be accessed from this frame's location.
LocalVariable | StackFrame.visibleVariableByName(String name) Finds a LocalVariable that matches the given name and is visible at the current frame location.
List | Method.allLineLocations() Returns a list containing a Location object for each executable source line in this method.
List | Method.allLineLocations(String stratum, String sourceName) Returns a list containing a Location object for each executable source line in this method.
List | Method.locationsOfLine(int lineNumber) Returns a List containing all Location objects that map to the given line number.
List | 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 | Method.variables() Returns a list containing each LocalVariable declared in this method.
List | Method.variablesByName(String name) Returns a list containing each LocalVariable of a given name in this method.
List | Method.arguments() Returns a list containing each LocalVariable that is declared as an argument of this method.
String | ReferenceType.sourceName() Gets an identifying name for the source corresponding to the declaration of this type.
List | ReferenceType.sourceNames(String stratum) Gets the identifying names for all the source corresponding to the declaration of this type.
List | ReferenceType.sourcePaths(String stratum) Gets the paths to the source corresponding to the declaration of this type.
String | ReferenceType.sourceDebugExtension() Get the source debug extension of this type.
List | ReferenceType.allLineLocations() Returns a list containing a Location object for each executable source line in this reference type.
List | ReferenceType.allLineLocations(String stratum, String sourceName) Returns a list containing a Location object for each executable source line in this reference type.
List | ReferenceType.locationsOfLine(int lineNumber) Returns a List containing all Location objects that map to the given line number.
List | ReferenceType.locationsOfLine(String stratum, String sourceName, int lineNumber) Returns a List containing all Location objects that map to the given line number.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.Accessible (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.Accessible

Packages that use Accessible
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
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 Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.ArrayReference (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.ArrayReference

Packages that use ArrayReference
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
 ArrayReference ArrayType.newInstance(int length)
Creates a new instance of this array class in the target VM.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.ArrayType (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.ArrayType

No usage of com.sun.jdi.ArrayType

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.BooleanType (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.BooleanType

No usage of com.sun.jdi.BooleanType

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.BooleanValue (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.BooleanValue

Packages that use BooleanValue
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
 BooleanValue VirtualMachine.mirrorOf(boolean value)
Creates a BooleanValue for the given value.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.jdi.Bootstrap (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.jdi.Bootstrap

No usage of com.sun.jdi.Bootstrap

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.ByteType (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.ByteType

No usage of com.sun.jdi.ByteType

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.ByteValue (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.ByteValue

Packages that use ByteValue
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
 ByteValue VirtualMachine.mirrorOf(byte value)
Creates a ByteValue for the given value.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.CharType (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.CharType

No usage of com.sun.jdi.CharType

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.CharValue (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.CharValue

Packages that use CharValue
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
 CharValue VirtualMachine.mirrorOf(char value)
Creates a CharValue for the given value.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.ClassLoaderReference (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.ClassLoaderReference

Packages that use ClassLoaderReference
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
 ClassLoaderReference ReferenceType.classLoader()
Gets the classloader object which loaded the class corresponding to this type.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.jdi.ClassNotLoadedException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.jdi.ClassNotLoadedException

Packages that use ClassNotLoadedException
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
void | ClassType.setValue(Field field, Value value) Assigns a value to a static field.
Value | ClassType.invokeMethod(ThreadReference thread, Method method, List arguments, int options) Invokes the specified static Method in the target VM.
ObjectReference | ClassType.newInstance(ThreadReference thread, Method method, List arguments, int options) Constructs a new instance of this type, using the given constructor Method in the target VM.
Type | ArrayType.componentType() Returns the component type of this array, as specified in the array declaration.
Type | LocalVariable.type() Returns the type of this variable.
void | StackFrame.setValue(LocalVariable variable, Value value) Sets the Value of a LocalVariable in this frame.
Type | Method.returnType() Returns the return type, as specified in the declaration of this method.
List | Method.argumentTypes() Returns a list containing the type of each formal parameter of this method.
Type | Field.type() Returns the type of this field.
void | ObjectReference.setValue(Field field, Value value) Sets the value of a given instance or static field in this object.
Value | ObjectReference.invokeMethod(ThreadReference thread, Method method, List arguments, int options) Invokes the specified Method on this object in the target VM.
void | ArrayReference.setValue(int index, Value value) Replaces an array component with another value.
void | ArrayReference.setValues(List values) Replaces all array components with other values.
void | ArrayReference.setValues(int index, List values, int srcIndex, int length) Replaces a range of array components with other values.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.jdi.ClassNotPreparedException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.jdi.ClassNotPreparedException

No usage of com.sun.jdi.ClassNotPreparedException

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.ClassObjectReference (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.ClassObjectReference

Packages that use ClassObjectReference
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
 ClassObjectReference ReferenceType.classObject()
Returns the class object that corresponds to this type in the target VM.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.ClassType (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.ClassType

Packages that use ClassType
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 ClassType in com.sun.jdi

Methods in com.sun.jdi that return ClassType
 ClassType ClassType.superclass()
Gets the superclass of this class.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.DoubleType (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.DoubleType

No usage of com.sun.jdi.DoubleType

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.DoubleValue (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.DoubleValue

Packages that use DoubleValue
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
 DoubleValue VirtualMachine.mirrorOf(double value)
Creates a DoubleValue for the given value.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.Field (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.Field

Packages that use Field
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
 Field ReferenceType.fieldByName(String fieldName)
Finds the visible Field with the given non-ambiguous name.

Methods in com.sun.jdi with parameters of type Field
void | ClassType.setValue(Field field, Value value) Assigns a value to a static field.
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 | ObjectReference.setValue(Field field, Value value) Sets the value of a given instance or static field in this object.

Uses of Field in com.sun.jdi.event

Methods in com.sun.jdi.event that return Field
 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
 Field WatchpointRequest.field()
Gets the Field being watched by this WatchpointRequest.

Methods in com.sun.jdi.request with parameters of type Field
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 Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.FloatType (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.FloatType

No usage of com.sun.jdi.FloatType

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.FloatValue (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.FloatValue

Packages that use FloatValue
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
 FloatValue VirtualMachine.mirrorOf(float value)
Creates a FloatValue for the given value.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.jdi.IncompatibleThreadStateException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.jdi.IncompatibleThreadStateException

Packages that use IncompatibleThreadStateException
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
Value | ClassType.invokeMethod(ThreadReference thread, Method method, List arguments, int options) Invokes the specified static Method in the target VM.
ObjectReference | ClassType.newInstance(ThreadReference thread, Method method, List arguments, int options) Constructs a new instance of this type, using the given constructor Method in the target VM.
int | ThreadReference.frameCount() Returns the number of stack frames in the thread's current call stack.
List | ThreadReference.frames() Returns a List containing each StackFrame in the thread's current call stack.
StackFrame | ThreadReference.frame(int index) Returns the StackFrame at the given index in the thread's current call stack.
List | ThreadReference.frames(int start, int length) Returns a List containing a range of StackFrame mirrors from the thread's current call stack.
List | ThreadReference.ownedMonitors() Returns a List containing an ObjectReference for each monitor owned by the thread.
ObjectReference | ThreadReference.currentContendedMonitor() Returns an ObjectReference for the monitor, if any, for which this thread is currently waiting.
void | ThreadReference.popFrames(StackFrame frame) Pop stack frames.
Value | ObjectReference.invokeMethod(ThreadReference thread, Method method, List arguments, int options) Invokes the specified Method on this object in the target VM.
List | ObjectReference.waitingThreads() Returns a List containing a ThreadReference for each thread currently waiting for this object's monitor.
ThreadReference | ObjectReference.owningThread() Returns an ThreadReference for the thread, if any, which currently owns this object's monitor.
int | ObjectReference.entryCount() Returns the number times this object's monitor has been entered by the current owning thread.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.jdi.InconsistentDebugInfoException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.jdi.InconsistentDebugInfoException

No usage of com.sun.jdi.InconsistentDebugInfoException

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.IntegerType (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.IntegerType

No usage of com.sun.jdi.IntegerType

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.IntegerValue (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.IntegerValue

Packages that use IntegerValue
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
 IntegerValue VirtualMachine.mirrorOf(int value)
Creates an IntegerValue for the given value.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.InterfaceType (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.InterfaceType

No usage of com.sun.jdi.InterfaceType

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.jdi.InternalException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.jdi.InternalException

No usage of com.sun.jdi.InternalException

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.jdi.InvalidCodeIndexException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.jdi.InvalidCodeIndexException

No usage of com.sun.jdi.InvalidCodeIndexException

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.jdi.InvalidLineNumberException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.jdi.InvalidLineNumberException

No usage of com.sun.jdi.InvalidLineNumberException

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.jdi.InvalidStackFrameException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.jdi.InvalidStackFrameException

No usage of com.sun.jdi.InvalidStackFrameException

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.jdi.InvalidTypeException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.jdi.InvalidTypeException

Packages that use InvalidTypeException
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
void | ClassType.setValue(Field field, Value value) Assigns a value to a static field.
Value | ClassType.invokeMethod(ThreadReference thread, Method method, List arguments, int options) Invokes the specified static Method in the target VM.
ObjectReference | ClassType.newInstance(ThreadReference thread, Method method, List arguments, int options) Constructs a new instance of this type, using the given constructor Method in the target VM.
void | StackFrame.setValue(LocalVariable variable, Value value) Sets the Value of a LocalVariable in this frame.
void | ThreadReference.stop(ObjectReference throwable) Stops this thread with an asynchronous exception.
void | ObjectReference.setValue(Field field, Value value) Sets the value of a given instance or static field in this object.
Value | ObjectReference.invokeMethod(ThreadReference thread, Method method, List arguments, int options) Invokes the specified Method on this object in the target VM.
void | ArrayReference.setValue(int index, Value value) Replaces an array component with another value.
void | ArrayReference.setValues(List values) Replaces all array components with other values.
void | ArrayReference.setValues(int index, List values, int srcIndex, int length) Replaces a range of array components with other values.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.jdi.InvocationException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.jdi.InvocationException

Packages that use InvocationException
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
Value | ClassType.invokeMethod(ThreadReference thread, Method method, List arguments, int options) Invokes the specified static Method in the target VM.
ObjectReference | ClassType.newInstance(ThreadReference thread, Method method, List arguments, int options) Constructs a new instance of this type, using the given constructor Method in the target VM.
Value | ObjectReference.invokeMethod(ThreadReference thread, Method method, List arguments, int options) Invokes the specified Method on this object in the target VM.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.LocalVariable (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.LocalVariable

Packages that use LocalVariable
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
 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 with parameters of type LocalVariable
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.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.Locatable (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.Locatable

Packages that use Locatable
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
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
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 | 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
 interface BreakpointRequest
Identifies a Location in the target VM at which execution should be stopped.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.Location (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.Location

Packages that use Location
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
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.locationOfCodeIndex(long codeIndex) Returns a Location for the given code index.
Location | Method.location() Returns the Location of this method, if there is executable code associated with it.

Uses of Location in com.sun.jdi.event

Methods in com.sun.jdi.event that return Location
 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
 Location BreakpointRequest.location()
Returns the location of the requested breakpoint.

Methods in com.sun.jdi.request with parameters of type Location
 BreakpointRequest EventRequestManager.createBreakpointRequest(Location location)
Creates a new disabled BreakpointRequest.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.LongType (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.LongType

No usage of com.sun.jdi.LongType

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.LongValue (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.LongValue

Packages that use LongValue
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
 LongValue VirtualMachine.mirrorOf(long value)
Creates a LongValue for the given value.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.Method (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.Method

Packages that use Method
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
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 with parameters of type Method
Value | ClassType.invokeMethod(ThreadReference thread, Method method, List arguments, int options) Invokes the specified static Method in the target VM.
ObjectReference | ClassType.newInstance(ThreadReference thread, Method method, List arguments, int options) Constructs a new instance of this type, using the given constructor Method in the target VM.
Value | ObjectReference.invokeMethod(ThreadReference thread, Method method, List arguments, int options) Invokes the specified Method on this object in the target VM.

Uses of Method in com.sun.jdi.event

Methods in com.sun.jdi.event that return Method
Method | MethodExitEvent.method() Returns the method that was exited.
Method | MethodEntryEvent.method() Returns the method that was entered.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.Mirror (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.Mirror

Packages that use Mirror
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
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 | 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
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 | 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
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 | 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 Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.jdi.NativeMethodException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.jdi.NativeMethodException

No usage of com.sun.jdi.NativeMethodException

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.jdi.ObjectCollectedException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.jdi.ObjectCollectedException

No usage of com.sun.jdi.ObjectCollectedException

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.ObjectReference (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.ObjectReference

Packages that use ObjectReference
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
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
ObjectReference | ClassType.newInstance(ThreadReference thread, Method method, List 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.
ObjectReference | InvocationException.exception()
ObjectReference | ThreadReference.currentContendedMonitor() Returns an ObjectReference for the monitor, if any, for which this thread is currently waiting.

Methods in com.sun.jdi with parameters of type ObjectReference
 void ThreadReference.stop(ObjectReference throwable)
Stops this thread with an asynchronous exception.

Constructors in com.sun.jdi with parameters of type ObjectReference
InvocationException(ObjectReference exception)

Uses of ObjectReference in com.sun.jdi.event

Methods in com.sun.jdi.event that return ObjectReference
ObjectReference | ExceptionEvent.exception() Gets the thrown exception object.
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
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 | 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 Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.PathSearchingVirtualMachine (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.PathSearchingVirtualMachine

No usage of com.sun.jdi.PathSearchingVirtualMachine

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.PrimitiveType (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.PrimitiveType

Packages that use PrimitiveType
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 PrimitiveType in com.sun.jdi

Subinterfaces of PrimitiveType in com.sun.jdi
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 | 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 | LongType The type of all primitive long values accessed in the target VM.
interface | ShortType The type of all primitive short values accessed in the target VM.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.PrimitiveValue (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.PrimitiveValue

Packages that use PrimitiveValue
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
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 Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.ReferenceType (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.ReferenceType

Packages that use ReferenceType
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 ReferenceType in com.sun.jdi

Subinterfaces of ReferenceType in com.sun.jdi
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 | InterfaceType A mirror of an interface in the target VM.

Methods in com.sun.jdi that return ReferenceType
ReferenceType | Location.declaringType() Gets the type to which this Location belongs.
ReferenceType | ClassObjectReference.reflectedType() Returns the ReferenceType corresponding to this class object.
ReferenceType | TypeComponent.declaringType() Returns the type in which this component was declared.
ReferenceType | ObjectReference.referenceType() Gets the ReferenceType that mirrors the type of this object.

Uses of ReferenceType in com.sun.jdi.event

Methods in com.sun.jdi.event that return ReferenceType
 ReferenceType ClassPrepareEvent.referenceType()
Returns the reference type for which this event was generated.

Uses of ReferenceType in com.sun.jdi.request

Methods in com.sun.jdi.request that return ReferenceType
 ReferenceType ExceptionRequest.exception()
Returns exception type for which exception events are requested.

Methods in com.sun.jdi.request with parameters of type ReferenceType
void | WatchpointRequest.addClassFilter(ReferenceType refType) Restricts the events generated by this request to those whose location is in the given reference type or any of its subtypes.
void | StepRequest.addClassFilter(ReferenceType refType) Restricts the events generated by this request to those whose location is in the given reference type or any of its subtypes.
void | MethodExitRequest.addClassFilter(ReferenceType refType) Restricts the events generated by this request to those whose method is in the given reference type or any of its subtypes.
void | MethodEntryRequest.addClassFilter(ReferenceType refType) Restricts the events generated by this request to those whose method is in the given reference type or any of its subtypes.
void | ExceptionRequest.addClassFilter(ReferenceType refType) Restricts the events generated by this request to those whose location is in the given reference type or any of its subtypes.
void | ClassPrepareRequest.addClassFilter(ReferenceType refType) Restricts the events generated by this request to be the preparation of the given reference type and any subtypes.
ExceptionRequest | EventRequestManager.createExceptionRequest(ReferenceType refType, boolean notifyCaught, boolean notifyUncaught) Creates a new disabled ExceptionRequest.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.ShortType (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.ShortType

No usage of com.sun.jdi.ShortType

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.ShortValue (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.ShortValue

Packages that use ShortValue
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
 ShortValue VirtualMachine.mirrorOf(short value)
Creates a ShortValue for the given value.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.StackFrame (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.StackFrame

Packages that use StackFrame
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
 StackFrame ThreadReference.frame(int index)
Returns the StackFrame at the given index in the thread's current call stack.

Methods in com.sun.jdi with parameters of type StackFrame
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 Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.StringReference (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.StringReference

Packages that use StringReference
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
 StringReference VirtualMachine.mirrorOf(String value)
Creates a string in this virtual machine.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.ThreadGroupReference (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.ThreadGroupReference

Packages that use ThreadGroupReference
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
ThreadGroupReference | ThreadGroupReference.parent() Returns the parent of this thread group.
ThreadGroupReference | ThreadReference.threadGroup() Returns this thread's thread group.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.ThreadReference (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.ThreadReference

Packages that use ThreadReference
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
ThreadReference | StackFrame.thread() Returns the thread under which this frame's method is running.
ThreadReference | ObjectReference.owningThread() Returns an ThreadReference for the thread, if any, which currently owns this object's monitor.

Methods in com.sun.jdi with parameters of type ThreadReference
Value | ClassType.invokeMethod(ThreadReference thread, Method method, List arguments, int options) Invokes the specified static Method in the target VM.
ObjectReference | ClassType.newInstance(ThreadReference thread, Method method, List arguments, int options) Constructs a new instance of this type, using the given constructor Method in the target VM.
Value | ObjectReference.invokeMethod(ThreadReference thread, Method method, List arguments, int options) Invokes the specified Method on this object in the target VM.

Uses of ThreadReference in com.sun.jdi.event

Methods in com.sun.jdi.event that return ThreadReference
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 | 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
 ThreadReference StepRequest.thread()

Methods in com.sun.jdi.request with parameters of type ThreadReference
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 | 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 Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.Type (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.Type

Packages that use Type
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
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
Type | ArrayType.componentType() Returns the component type of this array, as specified in the array declaration.
Type | LocalVariable.type() Returns the type of this variable.
Type | Method.returnType() Returns the return type, as specified in the declaration of this method.
Type | Field.type() Returns the type of this field.
Type | Value.type() Returns the run-time type of this value.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.TypeComponent (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.TypeComponent

Packages that use TypeComponent
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
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 Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.Value (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.Value

Packages that use Value
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
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
Value | ClassType.invokeMethod(ThreadReference thread, Method method, List arguments, int options) Invokes the specified static Method in the target VM.
Value | StackFrame.getValue(LocalVariable variable) Gets the Value of a LocalVariable in this frame.
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 | ObjectReference.invokeMethod(ThreadReference thread, Method method, List arguments, int options) Invokes the specified Method on this object in the target VM.
Value | ArrayReference.getValue(int index) Returns an array component value.

Methods in com.sun.jdi with parameters of type Value
void | ClassType.setValue(Field field, Value value) Assigns a value to a static field.
void | StackFrame.setValue(LocalVariable variable, Value value) Sets the Value of a LocalVariable in this frame.
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.

Uses of Value in com.sun.jdi.event

Methods in com.sun.jdi.event that return Value
Value | ModificationWatchpointEvent.valueToBe() Value that will be assigned to the field when the instruction completes.
Value | WatchpointEvent.valueCurrent() Current value of the field.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.VirtualMachine (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.VirtualMachine

Packages that use VirtualMachine
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 VirtualMachine in com.sun.jdi

Subinterfaces of VirtualMachine in com.sun.jdi
 interface PathSearchingVirtualMachine
A virtual machine which searches for classes through paths

Methods in com.sun.jdi that return VirtualMachine
 VirtualMachine Mirror.virtualMachine()
Gets the VirtualMachine to which this Mirror belongs.

Uses of VirtualMachine in com.sun.jdi.connect

Methods in com.sun.jdi.connect that return VirtualMachine
VirtualMachine | ListeningConnector.accept(Map arguments) Waits for a target VM to attach to this connector.
VirtualMachine | AttachingConnector.attach(Map arguments) Attaches to a running application and and returns a mirror of its VM.
VirtualMachine | LaunchingConnector.launch(Map arguments) Launches an application and connects to its VM.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.VirtualMachineManager (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.VirtualMachineManager

Packages that use VirtualMachineManager
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
static VirtualMachineManager Bootstrap.virtualMachineManager()

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.jdi.VMDisconnectedException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.jdi.VMDisconnectedException

No usage of com.sun.jdi.VMDisconnectedException

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.jdi.VMMismatchException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.jdi.VMMismatchException

No usage of com.sun.jdi.VMMismatchException

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.jdi.VMOutOfMemoryException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.jdi.VMOutOfMemoryException

No usage of com.sun.jdi.VMOutOfMemoryException

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.VoidType (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.VoidType

No usage of com.sun.jdi.VoidType

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.VoidValue (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.VoidValue

No usage of com.sun.jdi.VoidValue

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


AttachingConnector (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.connect
Interface AttachingConnector

All Superinterfaces:
Connector
public interface AttachingConnector
extends Connector

A connector which attaches to a previously running target VM.

Since:
1.3

Nested Class Summary
Nested classes inherited from class com.sun.jdi.connect.Connector
Connector.Argument, Connector.BooleanArgument, Connector.IntegerArgument, Connector.SelectedArgument, Connector.StringArgument
Method Summary
 VirtualMachine attach(Map arguments)
Attaches to a running application and and returns a mirror of its VM.
Methods inherited from interface com.sun.jdi.connect.Connector
defaultArguments, description, name, transport

Method Detail

attach

public VirtualMachine attach(Map arguments)
                      throws IOException,
                             IllegalConnectorArgumentsException
Attaches to a running application and and returns a mirror of its VM.

The connector uses the given argument map in attaching the application. These arguments will include addressing information that identifies the VM. The argument map associates argument name strings to instances of Connector.Argument. The default argument map for a connector can be obtained through Connector.defaultArguments(). Argument map values can be changed, but map entries should not be added or deleted.

Parameters:
arguments - the argument map to be used in launching the VM.
Returns:
the VirtualMachine mirror of the target VM.
Throws:
IOException - when unable to attach. Specific exceptions are dependent on the Connector implementation in use.
IllegalConnectorArgumentsException - when one of the connector arguments is invalid.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Connector (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.connect
Interface Connector

All Known Subinterfaces:
AttachingConnector, LaunchingConnector, ListeningConnector
public interface Connector

A method of connection between a debugger and a target VM. A connector encapsulates exactly one Transport. used to establish the connection. Each connector has a set of arguments which controls its operation. The arguments are stored as a map, keyed by a string. Each implementation defines the string argument keys it accepts.

Since:
1.3
See Also:
LaunchingConnector, AttachingConnector, ListeningConnector, Connector.Argument

Nested Class Summary
static interface | Connector.Argument Specification for and value of a Connector argument.
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.
Method Summary
Map | defaultArguments() Returns the arguments accepted by this Connector and their default values.
String | description() Returns a human-readable description of this connector and its purpose.
String | name() Returns a short identifier for the connector.
Transport | transport() Returns the transport mechanism used by this connector to establish connections with a target VM.

Method Detail

name

public String name()
Returns a short identifier for the connector. Connector implementors should follow similar naming conventions as are used with packages to avoid name collisions. For example, the Sun connector implementations have names prefixed with "com.sun.jdi.". Not intended for exposure to end-user.

Returns:
the name of this connector.

description

public String description()
Returns a human-readable description of this connector and its purpose.

Returns:
the description of this connector

transport

public Transport transport()
Returns the transport mechanism used by this connector to establish connections with a target VM.

Returns:
the Transport used by this connector.

defaultArguments

public Map defaultArguments()
Returns the arguments accepted by this Connector and their default values. The keys of the returned map are string argument names. The values are Connector.Argument containing information about the argument and its default value.

Returns:
the map associating argument names with argument information and default value.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Connector.Argument (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.connect
Interface Connector.Argument

All Superinterfaces:
Serializable
All Known Subinterfaces:
Connector.BooleanArgument, Connector.IntegerArgument, Connector.SelectedArgument, Connector.StringArgument
Enclosing interface:
Connector
public static interface Connector.Argument
extends Serializable

Specification for and value of a Connector argument. Will always implement a subinterface of Argument: Connector.StringArgument, Connector.BooleanArgument, Connector.IntegerArgument, or Connector.SelectedArgument.

Method Summary
String | description() Returns a human-readable description of this argument and its purpose.
boolean | isValid(String value) Performs basic sanity check of argument.
String | label() Returns a short human-readable label for this argument.
boolean | mustSpecify() Indicates whether the argument must be specified.
String | name() Returns a short, unique identifier for the argument.
void | setValue(String value) Sets the value of the argument.
String | value() Returns the current value of the argument.

Method Detail

name

public String name()
Returns a short, unique identifier for the argument. Not intended for exposure to end-user.

Returns:
the name of this argument.

label

public String label()
Returns a short human-readable label for this argument.

Returns:
a label for this argument

description

public String description()
Returns a human-readable description of this argument and its purpose.

Returns:
the description of this argument

value

public String value()
Returns the current value of the argument. Initially, the default value is returned. If the value is currently unspecified, null is returned.

Returns:
the current value of the argument.

setValue

public void setValue(String value)
Sets the value of the argument. The value should be checked with isValid(String) before setting it; invalid values will throw an exception when the connection is established - for example, on LaunchingConnector.launch(java.util.Map)

isValid

public boolean isValid(String value)
Performs basic sanity check of argument.

Returns:
true if the value is valid to be used in setValue(String)

mustSpecify

public boolean mustSpecify()
Indicates whether the argument must be specified. If true, setValue(java.lang.String) must be used to set a non-null value before using this argument in establishing a connection.

Returns:
true if the argument must be specified; false otherwise.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Connector.BooleanArgument (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.connect
Interface Connector.BooleanArgument

All Superinterfaces:
Connector.Argument, Serializable
Enclosing interface:
Connector
public static interface Connector.BooleanArgument
extends Connector.Argument

Specification for and value of a Connector argument, whose value is Boolean. Boolean values are represented by the localized versions of the strings "true" and "false".

Method Summary
boolean | booleanValue() Return the value of the argument as a boolean.
boolean | isValid(String value) Performs basic sanity check of argument.
void | setValue(boolean value) Sets the value of the argument.
String | stringValueOf(boolean value) Return the string representation of the value parameter.
Methods inherited from interface com.sun.jdi.connect.Connector.Argument
description, label, mustSpecify, name, setValue, value

Method Detail

setValue

public void setValue(boolean value)
Sets the value of the argument.

isValid

public boolean isValid(String value)
Performs basic sanity check of argument.

Specified by:
isValid in interface Connector.Argument
Returns:
true if value is a string representation of a boolean value.
See Also:
stringValueOf(boolean)

stringValueOf

public String stringValueOf(boolean value)
Return the string representation of the value parameter. Does not set or examine the current value of this instance.

Returns:
the localized String representation of the boolean value.

booleanValue

public boolean booleanValue()
Return the value of the argument as a boolean. Since the argument may not have been set or may have an invalid value isValid(String) should be called on Connector.Argument.value() to check its validity. If it is invalid the boolean returned by this method is undefined.

Returns:
the value of the argument as a boolean.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Connector.IntegerArgument (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.connect
Interface Connector.IntegerArgument

All Superinterfaces:
Connector.Argument, Serializable
Enclosing interface:
Connector
public static interface Connector.IntegerArgument
extends Connector.Argument

Specification for and value of a Connector argument, whose value is an integer. Integer values are represented by their corresponding strings.

Method Summary
int | intValue() Return the value of the argument as a int.
boolean | isValid(int value) Performs basic sanity check of argument.
boolean | isValid(String value) Performs basic sanity check of argument.
int | max() The upper bound for the value.
int | min() The lower bound for the value.
void | setValue(int value) Sets the value of the argument.
String | stringValueOf(int value) Return the string representation of the value parameter.
Methods inherited from interface com.sun.jdi.connect.Connector.Argument
description, label, mustSpecify, name, setValue, value

Method Detail

setValue

public void setValue(int value)
Sets the value of the argument. The value should be checked with isValid(int) before setting it; invalid values will throw an exception when the connection is established - for example, on LaunchingConnector.launch(java.util.Map)

isValid

public boolean isValid(String value)
Performs basic sanity check of argument.

Specified by:
isValid in interface Connector.Argument
Returns:
true if value represents an int that is min() <= value <= max()

isValid

public boolean isValid(int value)
Performs basic sanity check of argument.

Returns:
true if min() <= value <= max()

stringValueOf

public String stringValueOf(int value)
Return the string representation of the value parameter. Does not set or examine the current value of this instance.

Returns:
the String representation of the int value.

intValue

public int intValue()
Return the value of the argument as a int. Since the argument may not have been set or may have an invalid value isValid(String) should be called on Connector.Argument.value() to check its validity. If it is invalid the int returned by this method is undefined.

Returns:
the value of the argument as a int.

max

public int max()
The upper bound for the value.

Returns:
the maximum allowed value for this argument.

min

public int min()
The lower bound for the value.

Returns:
the minimum allowed value for this argument.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Connector.SelectedArgument (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.connect
Interface Connector.SelectedArgument

All Superinterfaces:
Connector.Argument, Serializable
Enclosing interface:
Connector
public static interface Connector.SelectedArgument
extends Connector.Argument

Specification for and value of a Connector argument, whose value is a String selected from a list of choices.

Method Summary
List | choices() Return the possible values for the argument
boolean | isValid(String value) Performs basic sanity check of argument.
Methods inherited from interface com.sun.jdi.connect.Connector.Argument
description, label, mustSpecify, name, setValue, value

Method Detail

choices

public List choices()
Return the possible values for the argument

Returns:
List of String

isValid

public boolean isValid(String value)
Performs basic sanity check of argument.

Specified by:
isValid in interface Connector.Argument
Returns:
true if value is one of choices().
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Connector.StringArgument (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.connect
Interface Connector.StringArgument

All Superinterfaces:
Connector.Argument, Serializable
Enclosing interface:
Connector
public static interface Connector.StringArgument
extends Connector.Argument

Specification for and value of a Connector argument, whose value is a String.

Method Summary
 boolean isValid(String value)
Performs basic sanity check of argument.
Methods inherited from interface com.sun.jdi.connect.Connector.Argument
description, label, mustSpecify, name, setValue, value

Method Detail

isValid

public boolean isValid(String value)
Performs basic sanity check of argument.

Specified by:
isValid in interface Connector.Argument
Returns:
true always
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


IllegalConnectorArgumentsException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.connect
Class IllegalConnectorArgumentsException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by com.sun.jdi.connect.IllegalConnectorArgumentsException
All Implemented Interfaces:
Serializable
public class IllegalConnectorArgumentsException
extends Exception

Thrown to indicate an invalid argument or inconsistent passed to a Connector.

Since:
1.3
See Also:
Serialized Form

Constructor Summary
IllegalConnectorArgumentsException(String s, List names)
Construct an IllegalConnectorArgumentsException with the specified detail message and a List of names of arguments which are invalid or inconsistent.
IllegalConnectorArgumentsException(String s, String name)
Construct an IllegalConnectorArgumentsException with the specified detail message and the name of the argument which is invalid or inconsistent.
Method Summary
 List argumentNames()
Return a List containing the names of the invalid or inconsistent arguments.
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

IllegalConnectorArgumentsException

public IllegalConnectorArgumentsException(String s,
                                          String name)
Construct an IllegalConnectorArgumentsException with the specified detail message and the name of the argument which is invalid or inconsistent.

Parameters:
s - the detailed message.
name - the name of the invalid or inconsistent argument.

IllegalConnectorArgumentsException

public IllegalConnectorArgumentsException(String s,
                                          List names)
Construct an IllegalConnectorArgumentsException with the specified detail message and a List of names of arguments which are invalid or inconsistent.

Parameters:
s - the detailed message.
names - a List containing the names of the invalid or inconsistent argument.
Method Detail

argumentNames

public List argumentNames()
Return a List containing the names of the invalid or inconsistent arguments.

Returns:
a List of argument names.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


LaunchingConnector (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.connect
Interface LaunchingConnector

All Superinterfaces:
Connector
public interface LaunchingConnector
extends Connector

A connector which can launch a target VM before connecting to it.

Since:
1.3

Nested Class Summary
Nested classes inherited from class com.sun.jdi.connect.Connector
Connector.Argument, Connector.BooleanArgument, Connector.IntegerArgument, Connector.SelectedArgument, Connector.StringArgument
Method Summary
 VirtualMachine launch(Map arguments)
Launches an application and connects to its VM.
Methods inherited from interface com.sun.jdi.connect.Connector
defaultArguments, description, name, transport

Method Detail

launch

public VirtualMachine launch(Map arguments)
                      throws IOException,
                             IllegalConnectorArgumentsException,
                             VMStartException
Launches an application and connects to its VM. Properties of the launch (possibly including options, main class, and arguments) are specified in arguments. The argument map associates argument name strings to instances of Connector.Argument. The default argument map for a connector can be obtained through Connector.defaultArguments(). Argument map values can be changed, but map entries should not be added or deleted.

A target VM launched by a launching connector is not guaranteed to be stable until after the VMStartEvent has been received.

Important note: If a target VM is launched through this funcctions, its output and error streams must be read as it executes. These streams are available through the Process object returned by VirtualMachine.process(). If the streams are not periodically read, the target VM will stop executing when the buffers for these streams are filled.

Parameters:
arguments - the argument map to be used in launching the VM.
Returns:
the VirtualMachine mirror of the target VM.
Throws:
IOException - when unable to launch. Specific exceptions are dependent on the Connector implementation in use.
IllegalConnectorArgumentsException - when one of the connector arguments is invalid.
VMStartException - when the VM was successfully launched, but terminated with an error before a connection could be established.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ListeningConnector (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.connect
Interface ListeningConnector

All Superinterfaces:
Connector
public interface ListeningConnector
extends Connector

A connector which listens for a connection initiated by a target VM.

Since:
1.3

Nested Class Summary
Nested classes inherited from class com.sun.jdi.connect.Connector
Connector.Argument, Connector.BooleanArgument, Connector.IntegerArgument, Connector.SelectedArgument, Connector.StringArgument
Method Summary
VirtualMachine | accept(Map arguments) Waits for a target VM to attach to this connector.
String | startListening(Map arguments) Listens for one or more connections initiated by target VMs.
void | stopListening(Map arguments) Cancels listening for connections.
boolean | supportsMultipleConnections() Indicates whether this listening connector supports multiple connections for a single argument map.
Methods inherited from interface com.sun.jdi.connect.Connector
defaultArguments, description, name, transport

Method Detail

supportsMultipleConnections

public boolean supportsMultipleConnections()
Indicates whether this listening connector supports multiple connections for a single argument map. If so, a call to startListening(java.util.Map) may allow multiple target VM to become connected.

Returns:
true if multiple connections are supported; false otherwise.

startListening

public String startListening(Map arguments)
                      throws IOException,
                             IllegalConnectorArgumentsException
Listens for one or more connections initiated by target VMs. The connector uses the given argument map in determining the address at which to listen or else it generates an appropriate listen address. In either case, an address string is returned from this method which can be used in starting target VMs to identify this connector. The format of the address string is connector, transport, and, possibly, platform dependent.

The argument map associates argument name strings to instances of Connector.Argument. The default argument map for a connector can be obtained through Connector.defaultArguments(). Argument map values can be changed, but map entries should not be added or deleted.

This method does not return a VirtualMachine, and, normally, returns before any target VM initiates a connection. The connected target is obtained through accept(java.util.Map) (using the same argument map as is passed to this method).

If arguments contains addressing information. and only one conection will be accepted, the accept method can be called immediately without calling this method.

Returns:
the address at which the connector is listening for a connection.
Throws:
IOException - when unable to start listening. Specific exceptions are dependent on the Connector implementation in use.
IllegalConnectorArgumentsException - when one of the connector arguments is invalid.

stopListening

public void stopListening(Map arguments)
                   throws IOException,
                          IllegalConnectorArgumentsException
Cancels listening for connections. The given argument map should match the argument map given for a previous startListening(java.util.Map) invocation.

Throws:
IOException - when unable to stop listening. Specific exceptions are dependent on the Connector implementation in use.
IllegalConnectorArgumentsException - when one of the connector arguments is invalid.

accept

public VirtualMachine accept(Map arguments)
                      throws IOException,
                             IllegalConnectorArgumentsException
Waits for a target VM to attach to this connector.

Throws:
IOException - when unable to accept. Specific exceptions are dependent on the Connector implementation in use.
IllegalConnectorArgumentsException - when one of the connector arguments is invalid.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


com.sun.jdi.connect (Java Debug Interface)

 com.sun.jdi.connect
Interfaces
AttachingConnector
Connector
Connector.Argument
Connector.BooleanArgument
Connector.IntegerArgument
Connector.SelectedArgument
Connector.StringArgument
LaunchingConnector
ListeningConnector
Transport
Exceptions
IllegalConnectorArgumentsException
VMStartException


com.sun.jdi.connect (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package com.sun.jdi.connect

This package defines connections between the virtual machine using the JDI and the target virtual machine.

See:
Description

Interface Summary
AttachingConnector | A connector which attaches to a previously running target VM.
Connector | A method of connection between a debugger and a target VM.
Connector.Argument | Specification for and value of a Connector argument.
Connector.BooleanArgument | Specification for and value of a Connector argument, whose value is Boolean.
Connector.IntegerArgument | Specification for and value of a Connector argument, whose value is an integer.
Connector.SelectedArgument | Specification for and value of a Connector argument, whose value is a String selected from a list of choices.
Connector.StringArgument | Specification for and value of a Connector argument, whose value is a String.
LaunchingConnector | A connector which can launch a target VM before connecting to it.
ListeningConnector | A connector which listens for a connection initiated by a target VM.
Transport | A method of communication between a debugger and a target VM.

Exception Summary
IllegalConnectorArgumentsException | Thrown to indicate an invalid argument or inconsistent passed to a Connector.
VMStartException | A target VM was successfully launched, but terminated with an error before a connection could be established.

Package com.sun.jdi.connect Description

This package defines connections between the virtual machine using the JDI and the target virtual machine. In concert with VirtualMachineManager it is the mechanism for launching, attaching, etc to target virtual machines.

Methods may be added to the interfaces in the JDI packages in future releases. Existing packages may be renamed if the JDI becomes a standard extension.

Overview Package Class Use Tree Index Help
Java Debug Interface


com.sun.jdi.connect Class Hierarchy (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Hierarchy For Package com.sun.jdi.connect

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class java.lang.Throwable (implements java.io.Serializable)
      • class java.lang.Exception
        • class com.sun.jdi.connect.IllegalConnectorArgumentsException
        • class com.sun.jdi.connect.VMStartException

Interface Hierarchy

  • interface com.sun.jdi.connect.Connector
    • interface com.sun.jdi.connect.AttachingConnector
    • interface com.sun.jdi.connect.LaunchingConnector
    • interface com.sun.jdi.connect.ListeningConnector
  • interface java.io.Serializable
    • interface com.sun.jdi.connect.Connector.Argument
      • interface com.sun.jdi.connect.Connector.BooleanArgument
      • interface com.sun.jdi.connect.Connector.IntegerArgument
      • interface com.sun.jdi.connect.Connector.SelectedArgument
      • interface com.sun.jdi.connect.Connector.StringArgument
  • interface com.sun.jdi.connect.Transport
Overview Package Class Use Tree Index Help
Java Debug Interface


Uses of Package com.sun.jdi.connect (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Package
com.sun.jdi.connect

Packages that use com.sun.jdi.connect
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.

Classes in com.sun.jdi.connect used by com.sun.jdi
LaunchingConnector
A connector which can launch a target VM before connecting to it.

Classes in com.sun.jdi.connect used by com.sun.jdi.connect
Connector
A method of connection between a debugger and a target VM.
Connector.Argument
Specification for and value of a Connector argument.
IllegalConnectorArgumentsException
Thrown to indicate an invalid argument or inconsistent passed to a Connector.
Transport
A method of communication between a debugger and a target VM.
VMStartException
A target VM was successfully launched, but terminated with an error before a connection could be established.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Transport (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.connect
Interface Transport

public interface Transport

A method of communication between a debugger and a target VM.

Since:
1.3

Method Summary
 String name()
Returns a short identifier for the transport.

Method Detail

name

public String name()
Returns a short identifier for the transport.

Returns:
the name of this transport.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


VMStartException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.connect
Class VMStartException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by com.sun.jdi.connect.VMStartException
All Implemented Interfaces:
Serializable
public class VMStartException
extends Exception

A target VM was successfully launched, but terminated with an error before a connection could be established. This exception provides the Process object for the launched target to help in diagnosing the problem.

Since:
1.3
See Also:
Serialized Form

Constructor Summary
VMStartException(Process process)
VMStartException(String message, Process process)
Method Summary
 Process process()
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

VMStartException

public VMStartException(Process process)

VMStartException

public VMStartException(String message,
                        Process process)
Method Detail

process

public Process process()
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Uses of Interface com.sun.jdi.connect.AttachingConnector (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.connect.AttachingConnector

No usage of com.sun.jdi.connect.AttachingConnector

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.connect.Connector (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.connect.Connector

Packages that use Connector
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.connect

Subinterfaces of Connector in com.sun.jdi.connect
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 Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.connect.Connector.Argument (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.connect.Connector.Argument

Packages that use Connector.Argument
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
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.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.connect.Connector.BooleanArgument (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.connect.Connector.BooleanArgument

No usage of com.sun.jdi.connect.Connector.BooleanArgument

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.connect.Connector.IntegerArgument (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.connect.Connector.IntegerArgument

No usage of com.sun.jdi.connect.Connector.IntegerArgument

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.connect.Connector.SelectedArgument (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.connect.Connector.SelectedArgument

No usage of com.sun.jdi.connect.Connector.SelectedArgument

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.connect.Connector.StringArgument (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.connect.Connector.StringArgument

No usage of com.sun.jdi.connect.Connector.StringArgument

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.jdi.connect.IllegalConnectorArgumentsException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.jdi.connect.IllegalConnectorArgumentsException

Packages that use IllegalConnectorArgumentsException
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
String | ListeningConnector.startListening(Map arguments) Listens for one or more connections initiated by target VMs.
void | ListeningConnector.stopListening(Map arguments) Cancels listening for connections.
VirtualMachine | ListeningConnector.accept(Map arguments) Waits for a target VM to attach to this connector.
VirtualMachine | AttachingConnector.attach(Map arguments) Attaches to a running application and and returns a mirror of its VM.
VirtualMachine | LaunchingConnector.launch(Map arguments) Launches an application and connects to its VM.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.connect.LaunchingConnector (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.connect.LaunchingConnector

Packages that use LaunchingConnector
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
 LaunchingConnector VirtualMachineManager.defaultConnector()
Identifies the default connector.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.connect.ListeningConnector (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.connect.ListeningConnector

No usage of com.sun.jdi.connect.ListeningConnector

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.connect.Transport (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.connect.Transport

Packages that use Transport
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
 Transport Connector.transport()
Returns the transport mechanism used by this connector to establish connections with a target VM.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.jdi.connect.VMStartException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.jdi.connect.VMStartException

Packages that use VMStartException
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
 VirtualMachine LaunchingConnector.launch(Map arguments)
Launches an application and connects to its VM.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


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


AccessWatchpointEvent (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.event
Interface AccessWatchpointEvent

All Superinterfaces:
Event, Locatable, LocatableEvent, Mirror, WatchpointEvent
public interface AccessWatchpointEvent
extends WatchpointEvent

Notification of a field access in the target VM. Field modifications are not considered field accesses.

Since:
1.3
See Also:
EventQueue, VirtualMachine

Methods inherited from interface com.sun.jdi.event.WatchpointEvent
field, object, valueCurrent
Methods inherited from interface com.sun.jdi.event.LocatableEvent
thread
Methods inherited from interface com.sun.jdi.event.Event
request
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine
Methods inherited from interface com.sun.jdi.Locatable
location

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


BreakpointEvent (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.event
Interface BreakpointEvent

All Superinterfaces:
Event, Locatable, LocatableEvent, Mirror
public interface BreakpointEvent
extends LocatableEvent

Notification of a breakpoint in the target VM. The breakpoint event is generated before the code at its location is executed. When a location is reached which satisfies a currently enabled breakpoint request, an event set containing an instance of this class will be added to the VM's event queue.

Since:
1.3
See Also:
EventQueue, VirtualMachine, BreakpointRequest

Methods inherited from interface com.sun.jdi.event.LocatableEvent
thread
Methods inherited from interface com.sun.jdi.event.Event
request
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine
Methods inherited from interface com.sun.jdi.Locatable
location

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ClassPrepareEvent (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.event
Interface ClassPrepareEvent

All Superinterfaces:
Event, Mirror
public interface ClassPrepareEvent
extends Event

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).

Since:
1.3
See Also:
EventQueue, VirtualMachine

Method Summary
ReferenceType | referenceType() Returns the reference type for which this event was generated.
ThreadReference | thread() Returns the thread in which this event has occurred.
Methods inherited from interface com.sun.jdi.event.Event
request
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Method Detail

thread

public ThreadReference thread()
Returns the thread in which this event has occurred.

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 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 EventRequest.SUSPEND_EVENT_THREAD, all threads will be suspended instead, and the EventSet.suspendPolicy() 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.

Returns:
a ThreadReference which mirrors the event's thread in the target VM, or null in the rare cases described above.

referenceType

public ReferenceType referenceType()
Returns the reference type for which this event was generated.

Returns:
a ReferenceType which mirrors the class, interface, or array which has been linked.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ClassUnloadEvent (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.event
Interface ClassUnloadEvent

All Superinterfaces:
Event, Mirror
public interface ClassUnloadEvent
extends Event

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.

Since:
1.3
See Also:
EventQueue, VirtualMachine

Method Summary
String | className() Returns the name of the class that has been unloaded.
String | classSignature() Returns the JNI-style signature of the class that has been unloaded.
Methods inherited from interface com.sun.jdi.event.Event
request
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Method Detail

className

public String className()
Returns the name of the class that has been unloaded.

classSignature

public String classSignature()
Returns the JNI-style signature of the class that has been unloaded.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Event (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.event
Interface Event

All Superinterfaces:
Mirror
All Known Subinterfaces:
AccessWatchpointEvent, BreakpointEvent, ClassPrepareEvent, ClassUnloadEvent, ExceptionEvent, LocatableEvent, MethodEntryEvent, MethodExitEvent, ModificationWatchpointEvent, StepEvent, ThreadDeathEvent, ThreadStartEvent, VMDeathEvent, VMDisconnectEvent, VMStartEvent, WatchpointEvent
public interface Event
extends Mirror

An occurrence in a target VM that is of interest to a debugger. Event is the common superinterface for all events (examples include BreakpointEvent, ExceptionEvent, ClassPrepareEvent). When an event occurs, an instance of Event as a component of an EventSet is enqueued in the VirtualMachine's EventQueue.

Since:
1.3
See Also:
EventSet, EventQueue

Method Summary
 EventRequest request()
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Method Detail

request

public EventRequest request()
Returns:
The EventRequest that requested this event. Some events (eg. VMDeathEvent) may not have a cooresponding request and thus will return null.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


EventIterator (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.event
Interface EventIterator

All Superinterfaces:
Iterator
public interface EventIterator
extends Iterator

EventIterators are unmodifiable.

Since:
1.3
See Also:
Event, EventSet, Set.iterator()

Method Summary
 Event nextEvent()
Methods inherited from interface java.util.Iterator
hasNext, next, remove

Method Detail

nextEvent

public Event nextEvent()
Returns:
The next Event in an EventSet.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


EventQueue (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.event
Interface EventQueue

All Superinterfaces:
Mirror
public interface EventQueue
extends Mirror

Manager of incoming debugger events for a target VM. Events are always grouped in EventSets. EventSets generated by the debugger back end can be read here. There is one instance of EventQueue assigned to a particular VirtualMachine.

Some events cause the suspension of the target VM - event requests (com.sun.jdi.request) with a suspend policy of SUSPEND_ALL or SUSPEND_EVENT_THREAD and sometimes VMStartEvent. If these suspensions are not resumed the target VM will hang. Thus, it is always good policy to remove() every EventSet from the event queue until an EventSet containing a VMDisconnectEvent is read. Unless resume is being handled in another way, each EventSet should invoke EventSet.resume().

Since:
1.3
See Also:
EventSet, VirtualMachine

Method Summary
EventSet | remove() Waits forever for the next available event.
EventSet | remove(long timeout) Waits a specified time for the next available event.
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Method Detail

remove

public EventSet remove()
                throws InterruptedException
Waits forever for the next available event.

Returns:
the next EventSet.
Throws:
InterruptedException - if another thread has interrupted this thread.
VMDisconnectedException - if the connection to the target VM is no longer available. Note this will always be preceded by a VMDisconnectEvent.

remove

public EventSet remove(long timeout)
                throws InterruptedException
Waits a specified time for the next available event.

Parameters:
timeout - Time in milliseconds to wait for the next event
Returns:
the next EventSet, or null if there is a timeout.
Throws:
InterruptedException - if another thread has interrupted this thread.
VMDisconnectedException - if the connection to the target VM is no longer available. Note this will always be preceded by a VMDisconnectEvent.
IllegalArgumentException - if the timeout argument contains an illegal value.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


EventSet (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.event
Interface EventSet

All Superinterfaces:
Collection, Mirror, Set
public interface EventSet
extends Mirror, Set

Several Event objects may be created at a given time by the target VirtualMachine. For example, there may be more than one BreakpointRequest for a given Location or you might single step to the same location as a BreakpointRequest. These Event objects are delivered together as an EventSet. For uniformity, an EventSet is always used to deliver Event objects. EventSets are delivered by the EventQueue. EventSets are unmodifiable.

Associated with the issuance of an event set, suspensions may have occurred in the target VM. These suspensions correspond with the suspend policy. To assure matching resumes occur, it is recommended, where possible, to complete the processing of an event set with EventSet.resume().

The events that are grouped in an EventSet are restricted in the following ways:

  • Always singleton sets:
    • VMStartEvent
    • VMDisconnectEvent
  • Only with other VMDeathEvents:
    • VMDeathEvent
  • Only with other ThreadStartEvents for the same thread:
    • ThreadStartEvent
  • Only with other ThreadDeathEvents for the same thread:
    • ThreadDeathEvent
  • Only with other ClassPrepareEvents for the same class:
    • ClassPrepareEvent
  • Only with other ClassUnloadEvents for the same class:
    • ClassUnloadEvent
  • Only with other AccessWatchpointEvents for the same field access:
    • AccessWatchpointEvent
  • Only with other ModificationWatchpointEvents for the same field modification:
    • ModificationWatchpointEvent
  • Only with other ExceptionEvents for the same exception occurrance:
    • ExceptionEvent
  • Only with other MethodExitEvents for the same method exit:
    • MethodExitEvent
  • Only with other members of this group, at the same location and in the same thread:
    • BreakpointEvent
    • StepEvent
    • MethodEntryEvent

Since:
1.3
See Also:
Event, EventQueue

Method Summary
EventIterator | eventIterator() Return an iterator specific to Event objects.
void | resume() Resumes threads suspended by this event set.
int | suspendPolicy() Returns the policy used to suspend threads in the target VM for this event set.
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine
Methods inherited from interface java.util.Set
add, addAll, clear, contains, containsAll, equals, hashCode, isEmpty, iterator, remove, removeAll, retainAll, size, toArray, toArray

Method Detail

suspendPolicy

public int suspendPolicy()
Returns the policy used to suspend threads in the target VM for this event set. This policy is selected from the suspend policies for each event's request; the target VM chooses the policy which suspends the most threads. The target VM suspends threads according to that policy and that policy is returned here. See EventRequest for the possible policy values.

In rare cases, the suspend policy may differ from the requested value if a ClassPrepareEvent has occurred in a debugger system thread. See ClassPrepareEvent.thread() for details.

Returns:
the suspendPolicy which is either SUSPEND_ALL, SUSPEND_EVENT_THREAD or SUSPEND_NONE.

eventIterator

public EventIterator eventIterator()
Return an iterator specific to Event objects.

resume

public void resume()
Resumes threads suspended by this event set. If the suspendPolicy() is EventRequest.SUSPEND_ALL, a call to this method is equivalent to VirtualMachine.resume(). If the suspend policy is EventRequest.SUSPEND_EVENT_THREAD, a call to this method is equivalent to ThreadReference.resume() for the event thread. Otherwise, a call to this method is a no-op.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ExceptionEvent (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.event
Interface ExceptionEvent

All Superinterfaces:
Event, Locatable, LocatableEvent, Mirror
public interface ExceptionEvent
extends LocatableEvent

Notification of an exception in the target VM. When an exception is thrown which satisfies a currently enabled exception request, an event set containing an instance of this class will be added to the VM's event queue. 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.

Since:
1.3

Method Summary
Location | catchLocation() Gets the location where the exception will be caught.
ObjectReference | exception() Gets the thrown exception object.
Methods inherited from interface com.sun.jdi.event.LocatableEvent
thread
Methods inherited from interface com.sun.jdi.event.Event
request
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine
Methods inherited from interface com.sun.jdi.Locatable
location

Method Detail

exception

public ObjectReference exception()
Gets the thrown exception object. The exception object is an instance of Throwable or a subclass in the target VM.

Returns:
an ObjectReference which mirrors the thrown object in the target VM.

catchLocation

public Location catchLocation()
Gets the location where the exception will be 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 code index of 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 the compiler 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.

Returns:
the Location where the exception will be caught or null if the exception is uncaught.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


LocatableEvent (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.event
Interface LocatableEvent

All Superinterfaces:
Event, Locatable, Mirror
All Known Subinterfaces:
AccessWatchpointEvent, BreakpointEvent, ExceptionEvent, MethodEntryEvent, MethodExitEvent, ModificationWatchpointEvent, StepEvent, WatchpointEvent
public interface LocatableEvent
extends Event, Locatable

Abstract superinterface of events which have both location and thread.

Since:
1.3

Method Summary
 ThreadReference thread()
Returns the thread in which this event has occurred.
Methods inherited from interface com.sun.jdi.event.Event
request
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine
Methods inherited from interface com.sun.jdi.Locatable
location

Method Detail

thread

public ThreadReference thread()
Returns the thread in which this event has occurred.

Returns:
a ThreadReference which mirrors the event's thread in the target VM.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MethodEntryEvent (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.event
Interface MethodEntryEvent

All Superinterfaces:
Event, Locatable, LocatableEvent, Mirror
public interface MethodEntryEvent
extends LocatableEvent

Notification of a method invocation in the target VM. This event occurs after entry into the invoked method and before any code 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 ThreadStartEvent occurs if methods are called as part of the thread's initialization.

Since:
1.3
See Also:
EventQueue

Method Summary
 Method method()
Returns the method that was entered.
Methods inherited from interface com.sun.jdi.event.LocatableEvent
thread
Methods inherited from interface com.sun.jdi.event.Event
request
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine
Methods inherited from interface com.sun.jdi.Locatable
location

Method Detail

method

public Method method()
Returns the method that was entered.

Returns:
a Method which mirrors the method that was entered.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MethodExitEvent (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.event
Interface MethodExitEvent

All Superinterfaces:
Event, Locatable, LocatableEvent, Mirror
public interface MethodExitEvent
extends LocatableEvent

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:
1.3
See Also:
EventQueue

Method Summary
 Method method()
Returns the method that was exited.
Methods inherited from interface com.sun.jdi.event.LocatableEvent
thread
Methods inherited from interface com.sun.jdi.event.Event
request
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine
Methods inherited from interface com.sun.jdi.Locatable
location

Method Detail

method

public Method method()
Returns the method that was exited.

Returns:
a Method which mirrors the method that was exited.
Throws:
ObjectCollectedException - may be thrown if class has been garbage collected.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ModificationWatchpointEvent (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.event
Interface ModificationWatchpointEvent

All Superinterfaces:
Event, Locatable, LocatableEvent, Mirror, WatchpointEvent
public interface ModificationWatchpointEvent
extends WatchpointEvent

Notification of a field modification in the target VM.

Since:
1.3
See Also:
EventQueue, VirtualMachine, ModificationWatchpointRequest

Method Summary
 Value valueToBe()
Value that will be assigned to the field when the instruction completes.
Methods inherited from interface com.sun.jdi.event.WatchpointEvent
field, object, valueCurrent
Methods inherited from interface com.sun.jdi.event.LocatableEvent
thread
Methods inherited from interface com.sun.jdi.event.Event
request
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine
Methods inherited from interface com.sun.jdi.Locatable
location

Method Detail

valueToBe

public Value valueToBe()
Value that will be assigned to the field when the instruction completes.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


com.sun.jdi.event (Java Debug Interface)

 com.sun.jdi.event
Interfaces
AccessWatchpointEvent
BreakpointEvent
ClassPrepareEvent
ClassUnloadEvent
Event
EventIterator
EventQueue
EventSet
ExceptionEvent
LocatableEvent
MethodEntryEvent
MethodExitEvent
ModificationWatchpointEvent
StepEvent
ThreadDeathEvent
ThreadStartEvent
VMDeathEvent
VMDisconnectEvent
VMStartEvent
WatchpointEvent


com.sun.jdi.event (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package com.sun.jdi.event

This package defines JDI events and event processing.

See:
Description

Interface Summary
AccessWatchpointEvent | Notification of a field access in the target VM.
BreakpointEvent | Notification of a breakpoint in the target VM.
ClassPrepareEvent | Notification of a class prepare in the target VM.
ClassUnloadEvent | Notification of a class unload in the target VM.
Event | An occurrence in a target VM that is of interest to a debugger.
EventIterator | EventIterators are unmodifiable.
EventQueue | Manager of incoming debugger events for a target VM.
EventSet | Several Event objects may be created at a given time by the target VirtualMachine.
ExceptionEvent | Notification of an exception in the target VM.
LocatableEvent | Abstract superinterface of events which have both location and thread.
MethodEntryEvent | Notification of a method invocation in the target VM.
MethodExitEvent | Notification of a method return in the target VM.
ModificationWatchpointEvent | Notification of a field modification in the target VM.
StepEvent | Notification of step completion in the target VM.
ThreadDeathEvent | Notification of a completed thread in the target VM.
ThreadStartEvent | Notification of a new running thread in the target VM.
VMDeathEvent | Notification of target VM termination.
VMDisconnectEvent | Notification of disconnection from target VM.
VMStartEvent | Notification of initialization of a target VM.
WatchpointEvent | Notification of a field triggered event encountered by a thread in the target VM.

Package com.sun.jdi.event Description

This package defines JDI events and event processing. An Event is always a member of an EventSet, which is retrieved from the EventQueue. Examples of Events include "breakpoints events", "thread creation events" and "virtual machine death event". With the exception of termination events, all events received must be requested with an "EventRequest". The com.sun.jdi.request package defines event requests and event request management.

Methods may be added to the interfaces in the JDI packages in future releases. Existing packages may be renamed if the JDI becomes a standard extension.

Overview Package Class Use Tree Index Help
Java Debug Interface


com.sun.jdi.event Class Hierarchy (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Hierarchy For Package com.sun.jdi.event

Package Hierarchies:
All Packages

Interface Hierarchy

  • interface java.util.Collection
    • interface java.util.Set
      • interface com.sun.jdi.event.EventSet (also extends com.sun.jdi.Mirror)
  • interface java.util.Iterator
    • interface com.sun.jdi.event.EventIterator
  • interface com.sun.jdi.Locatable
    • interface com.sun.jdi.event.LocatableEvent (also extends com.sun.jdi.event.Event)
      • interface com.sun.jdi.event.BreakpointEvent
      • interface com.sun.jdi.event.ExceptionEvent
      • interface com.sun.jdi.event.MethodEntryEvent
      • interface com.sun.jdi.event.MethodExitEvent
      • interface com.sun.jdi.event.StepEvent
      • interface com.sun.jdi.event.WatchpointEvent
        • interface com.sun.jdi.event.AccessWatchpointEvent
        • interface com.sun.jdi.event.ModificationWatchpointEvent
  • interface com.sun.jdi.Mirror
    • interface com.sun.jdi.event.Event
      • interface com.sun.jdi.event.ClassPrepareEvent
      • interface com.sun.jdi.event.ClassUnloadEvent
      • interface com.sun.jdi.event.LocatableEvent (also extends com.sun.jdi.Locatable)
        • interface com.sun.jdi.event.BreakpointEvent
        • interface com.sun.jdi.event.ExceptionEvent
        • interface com.sun.jdi.event.MethodEntryEvent
        • interface com.sun.jdi.event.MethodExitEvent
        • interface com.sun.jdi.event.StepEvent
        • interface com.sun.jdi.event.WatchpointEvent
          • interface com.sun.jdi.event.AccessWatchpointEvent
          • interface com.sun.jdi.event.ModificationWatchpointEvent
      • interface com.sun.jdi.event.ThreadDeathEvent
      • interface com.sun.jdi.event.ThreadStartEvent
      • interface com.sun.jdi.event.VMDeathEvent
      • interface com.sun.jdi.event.VMDisconnectEvent
      • interface com.sun.jdi.event.VMStartEvent
    • interface com.sun.jdi.event.EventQueue
    • interface com.sun.jdi.event.EventSet (also extends java.util.Set)
Overview Package Class Use Tree Index Help
Java Debug Interface


Uses of Package com.sun.jdi.event (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Package
com.sun.jdi.event

Packages that use com.sun.jdi.event
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.

Classes in com.sun.jdi.event used by com.sun.jdi
EventQueue
Manager of incoming debugger events for a target VM.

Classes in com.sun.jdi.event used by com.sun.jdi.event
Event
An occurrence in a target VM that is of interest to a debugger.
EventIterator
EventIterators are unmodifiable.
EventSet
Several Event objects may be created at a given time by the target VirtualMachine.
LocatableEvent
Abstract superinterface of events which have both location and thread.
WatchpointEvent
Notification of a field triggered event encountered by a thread in the target VM.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


StepEvent (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.event
Interface StepEvent

All Superinterfaces:
Event, Locatable, LocatableEvent, Mirror
public interface StepEvent
extends LocatableEvent

Notification of step completion in the target VM. The step event is generated immediately before the code at its location is executed; thus, if the step is entering a new method (as might occur with StepRequest.STEP_INTO) the location of the event is the first instruction of the method. When a step leaves a method, the location of the event will be the first instruction after the call in the calling method; note that this location may not be at a line boundary, even if StepRequest.STEP_LINE was used.

Since:
1.3
See Also:
StepRequest, EventQueue

Methods inherited from interface com.sun.jdi.event.LocatableEvent
thread
Methods inherited from interface com.sun.jdi.event.Event
request
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine
Methods inherited from interface com.sun.jdi.Locatable
location

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ThreadDeathEvent (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.event
Interface ThreadDeathEvent

All Superinterfaces:
Event, Mirror
public interface ThreadDeathEvent
extends Event

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 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.

Since:
1.3
See Also:
EventQueue, VirtualMachine, ThreadReference

Method Summary
 ThreadReference thread()
Returns the thread which is terminating.
Methods inherited from interface com.sun.jdi.event.Event
request
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Method Detail

thread

public ThreadReference thread()
Returns the thread which is terminating.

Returns:
a ThreadReference which mirrors the event's thread in the target VM.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ThreadStartEvent (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.event
Interface ThreadStartEvent

All Superinterfaces:
Event, Mirror
public interface ThreadStartEvent
extends Event

Notification of a new running thread in the target VM. The new thread can be the result of a call to 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, MethodEntryEvents and MethodExitEvents might occur during thread initialization.) It is also possible for VirtualMachine.allThreads() to return a new started thread before this 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.

Since:
1.3
See Also:
EventQueue, VirtualMachine, ThreadReference

Method Summary
 ThreadReference thread()
Returns the thread which has started.
Methods inherited from interface com.sun.jdi.event.Event
request
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Method Detail

thread

public ThreadReference thread()
Returns the thread which has started.

Returns:
a ThreadReference which mirrors the event's thread in the target VM.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


VMDeathEvent (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.event
Interface VMDeathEvent

All Superinterfaces:
Event, Mirror
public interface VMDeathEvent
extends Event

Notification of target VM termination. This event occurs if the target VM terminates before the VM disconnects (VMDisconnectEvent). Thus, this event will NOT occur if external forces terminate the connection (e.g. a crash) or if the connection is intentionally terminated with VirtualMachine.dispose()

On VM termination, a single unsolicited VMDeathEvent will always be sent with a suspend policy of SUSPEND_NONE. Additional VMDeathEvents will be sent in the same event set if they are requested with a VMDeathRequest.

The VM is still intact and can be queried at the point this event was initiated but immediately thereafter it is not considered intact and cannot be queried. Note: If the enclosing EventSet has a suspend policy other than SUSPEND_ALL the initiating point may be long past.

All VMDeathEvents will be in a single EventSet, no other events will be in the event set. A resume must occur to continue execution after any event set which performs suspensions - in this case to allow proper shutdown.

Since:
1.3
See Also:
VMDisconnectEvent, EventRequestManager.createVMDeathRequest(), VMDeathRequest, EventQueue, VirtualMachine

Methods inherited from interface com.sun.jdi.event.Event
request
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


VMDisconnectEvent (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.event
Interface VMDisconnectEvent

All Superinterfaces:
Event, Mirror
public interface VMDisconnectEvent
extends Event

Notification of disconnection from target VM. May be caused by normal termination of a VM, VM termination by uncaught exception or other error, debugger action ( VirtualMachine.dispose() or VirtualMachine.exit(int)) or by external events (for example, target process termination by the operating system, transport termination, etc).

If the target VM terminates before the disconnection, this event will be preceded by a VMDeathEvent.

This event is always sent. There is no corresponding EventRequest. The enclosing singleton EventSet always has a suspend policy of EventRequest.SUSPEND_NONE.

Since:
1.3
See Also:
VMDeathEvent, EventQueue, VirtualMachine

Methods inherited from interface com.sun.jdi.event.Event
request
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


VMStartEvent (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.event
Interface VMStartEvent

All Superinterfaces:
Event, Mirror
public interface VMStartEvent
extends Event

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.

Since:
1.3
See Also:
VMDeathEvent, EventQueue, VirtualMachine

Method Summary
 ThreadReference thread()
Returns the initial thread of the VM which has started.
Methods inherited from interface com.sun.jdi.event.Event
request
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Method Detail

thread

public ThreadReference thread()
Returns the initial thread of the VM which has started.

Returns:
a ThreadReference which mirrors the event's thread in the target VM.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


WatchpointEvent (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.event
Interface WatchpointEvent

All Superinterfaces:
Event, Locatable, LocatableEvent, Mirror
All Known Subinterfaces:
AccessWatchpointEvent, ModificationWatchpointEvent
public interface WatchpointEvent
extends LocatableEvent

Notification of a field triggered event encountered by a thread in the target VM.

Since:
1.3
See Also:
EventQueue, VirtualMachine

Method Summary
Field | field() Returns the field that is about to be accessed/modified.
ObjectReference | object() Returns the object whose field is about to be accessed/modified.
Value | valueCurrent() Current value of the field.
Methods inherited from interface com.sun.jdi.event.LocatableEvent
thread
Methods inherited from interface com.sun.jdi.event.Event
request
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine
Methods inherited from interface com.sun.jdi.Locatable
location

Method Detail

field

public Field field()
Returns the field that is about to be accessed/modified.

Returns:
a Field which mirrors the field in the target VM.
Throws:
ObjectCollectedException - may be thrown if class has been garbage collected.

object

public ObjectReference object()
Returns the object whose field is about to be accessed/modified. Return null is the access is to a static field.

Returns:
a ObjectReference which mirrors the event's object in the target VM.

valueCurrent

public Value valueCurrent()
Current value of the field.

Throws:
ObjectCollectedException - if object or class have been garbage collected.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Uses of Interface com.sun.jdi.event.AccessWatchpointEvent (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.event.AccessWatchpointEvent

No usage of com.sun.jdi.event.AccessWatchpointEvent

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.event.BreakpointEvent (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.event.BreakpointEvent

No usage of com.sun.jdi.event.BreakpointEvent

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.event.ClassPrepareEvent (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.event.ClassPrepareEvent

No usage of com.sun.jdi.event.ClassPrepareEvent

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.event.ClassUnloadEvent (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.event.ClassUnloadEvent

No usage of com.sun.jdi.event.ClassUnloadEvent

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.event.Event (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.event.Event

Packages that use Event
com.sun.jdi.event This package defines JDI events and event processing.

Uses of Event in com.sun.jdi.event

Subinterfaces of Event in com.sun.jdi.event
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 | 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 | 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.

Methods in com.sun.jdi.event that return Event
 Event EventIterator.nextEvent()

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.event.EventIterator (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.event.EventIterator

Packages that use EventIterator
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
 EventIterator EventSet.eventIterator()
Return an iterator specific to Event objects.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.event.EventQueue (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.event.EventQueue

Packages that use EventQueue
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
 EventQueue VirtualMachine.eventQueue()
Returns the event queue for this virtual machine.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.event.EventSet (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.event.EventSet

Packages that use EventSet
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
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 Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.event.ExceptionEvent (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.event.ExceptionEvent

No usage of com.sun.jdi.event.ExceptionEvent

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.event.LocatableEvent (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.event.LocatableEvent

Packages that use LocatableEvent
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
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 | 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 Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.event.MethodEntryEvent (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.event.MethodEntryEvent

No usage of com.sun.jdi.event.MethodEntryEvent

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.event.MethodExitEvent (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.event.MethodExitEvent

No usage of com.sun.jdi.event.MethodExitEvent

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.event.ModificationWatchpointEvent (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.event.ModificationWatchpointEvent

No usage of com.sun.jdi.event.ModificationWatchpointEvent

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.event.StepEvent (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.event.StepEvent

No usage of com.sun.jdi.event.StepEvent

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.event.ThreadDeathEvent (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.event.ThreadDeathEvent

No usage of com.sun.jdi.event.ThreadDeathEvent

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.event.ThreadStartEvent (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.event.ThreadStartEvent

No usage of com.sun.jdi.event.ThreadStartEvent

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.event.VMDeathEvent (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.event.VMDeathEvent

No usage of com.sun.jdi.event.VMDeathEvent

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.event.VMDisconnectEvent (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.event.VMDisconnectEvent

No usage of com.sun.jdi.event.VMDisconnectEvent

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.event.VMStartEvent (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.event.VMStartEvent

No usage of com.sun.jdi.event.VMStartEvent

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.event.WatchpointEvent (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.event.WatchpointEvent

Packages that use WatchpointEvent
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
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 Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


AccessWatchpointRequest (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.request
Interface AccessWatchpointRequest

All Superinterfaces:
EventRequest, Mirror, WatchpointRequest
public interface AccessWatchpointRequest
extends WatchpointRequest

Request for notification when the contents of a field are accessed in the target VM. This event will be triggered when the specified field is accessed by JavaTM programming language code or by a Java Native Interface (JNI) get function (Get<Type>Field, GetStatic<Type>Field). Access by JDI does not trigger this event. When an enabled AccessWatchpointRequest is satisfied, an event set containing an AccessWatchpointEvent will be placed on the EventQueue. The collection of existing ExceptionRequests is managed by the EventRequestManager The collection of existing watchpoints is managed by the EventRequestManager.

Note that the modification of a Field is not considered an access.

Since:
1.3
See Also:
ModificationWatchpointRequest, EventQueue, EventRequestManager

Field Summary
Fields inherited from interface com.sun.jdi.request.EventRequest
SUSPEND_ALL, SUSPEND_EVENT_THREAD, SUSPEND_NONE
Methods inherited from interface com.sun.jdi.request.WatchpointRequest
addClassExclusionFilter, addClassFilter, addClassFilter, addInstanceFilter, addThreadFilter, field
Methods inherited from interface com.sun.jdi.request.EventRequest
addCountFilter, disable, enable, getProperty, isEnabled, putProperty, setEnabled, setSuspendPolicy, suspendPolicy
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


BreakpointRequest (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.request
Interface BreakpointRequest

All Superinterfaces:
EventRequest, Locatable, Mirror
public interface BreakpointRequest
extends EventRequest, Locatable

Identifies a Location in the target VM at which execution should be stopped. When an enabled BreakpointRequest is satisfied, an event set containing an BreakpointEvent will be placed on the EventQueue and the application is interrupted. The collection of existing breakpoints is managed by the EventRequestManager

Since:
1.3
See Also:
Location, BreakpointEvent, EventQueue, EventRequestManager

Field Summary
Fields inherited from interface com.sun.jdi.request.EventRequest
SUSPEND_ALL, SUSPEND_EVENT_THREAD, SUSPEND_NONE
Method Summary
void | addInstanceFilter(ObjectReference instance) Restricts the events generated by this request to those in which the currently executing instance is the object specified.
void | addThreadFilter(ThreadReference thread) Restricts the events generated by this request to those in the given thread.
Location | location() Returns the location of the requested breakpoint.
Methods inherited from interface com.sun.jdi.request.EventRequest
addCountFilter, disable, enable, getProperty, isEnabled, putProperty, setEnabled, setSuspendPolicy, suspendPolicy
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Method Detail

location

public Location location()
Returns the location of the requested breakpoint.

Specified by:
location in interface Locatable
Returns:
the Location where this breakpoint has been set.

addThreadFilter

public void addThreadFilter(ThreadReference thread)
Restricts the events generated by this request to those in the given thread.

Parameters:
thread - the thread to filter on.
Throws:
InvalidRequestStateException - if this request is currently enabled or has been deleted. Filters may be added only to disabled requests.

addInstanceFilter

public void addInstanceFilter(ObjectReference instance)
Restricts the events generated by this request to those in which the currently executing instance is the object specified.

Not all targets support this operation. Use VirtualMachine.canUseInstanceFilters() to determine if the operation is supported.

Parameters:
instance - the object which must be the current instance in order to pass this filter.
Throws:
UnsupportedOperationException - if the target virtual machine does not support this operation.
InvalidRequestStateException - if this request is currently enabled or has been deleted. Filters may be added only to disabled requests.
Since:
1.4
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ClassPrepareRequest (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.request
Interface ClassPrepareRequest

All Superinterfaces:
EventRequest, Mirror
public interface ClassPrepareRequest
extends EventRequest

Request for notification when a class is prepared in the target VM. When an enabled ClassPrepareRequest is satisfied, an event set containing a ClassPrepareEvent will be placed on the EventQueue. The collection of existing ClassPrepareRequests is managed by the EventRequestManager

Class preparation is defined in the Java Virtual Machine Specification.

Since:
1.3
See Also:
ClassPrepareEvent, EventQueue, EventRequestManager

Field Summary
Fields inherited from interface com.sun.jdi.request.EventRequest
SUSPEND_ALL, SUSPEND_EVENT_THREAD, SUSPEND_NONE
Method Summary
void | addClassExclusionFilter(String classPattern) Restricts the events generated by this request to the preparation of reference types whose name does not match this restricted regular expression.
void | addClassFilter(ReferenceType refType) Restricts the events generated by this request to be the preparation of the given reference type and any subtypes.
void | addClassFilter(String classPattern) Restricts the events generated by this request to the preparation of reference types whose name matches this restricted regular expression.
Methods inherited from interface com.sun.jdi.request.EventRequest
addCountFilter, disable, enable, getProperty, isEnabled, putProperty, setEnabled, setSuspendPolicy, suspendPolicy
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Method Detail

addClassFilter

public void addClassFilter(ReferenceType refType)
Restricts the events generated by this request to be the preparation of the given reference type and any subtypes. An event will be generated for any prepared reference type that can be safely cast to the given reference type.

Parameters:
refType - the reference type to filter on.
Throws:
InvalidRequestStateException - if this request is currently enabled or has been deleted. Filters may be added only to disabled requests.

addClassFilter

public void addClassFilter(String classPattern)
Restricts the events generated by this request to the preparation of reference types whose name matches this restricted regular expression. Regular expressions are limited to exact matches and patterns that begin with '*' or end with '*'; for example, "*.Foo" or "java.*".

Parameters:
classPattern - the pattern String to filter for.
Throws:
InvalidRequestStateException - if this request is currently enabled or has been deleted. Filters may be added only to disabled requests.

addClassExclusionFilter

public void addClassExclusionFilter(String classPattern)
Restricts the events generated by this request to the preparation of reference types whose name does not match this restricted regular expression. Regular expressions are limited to exact matches and patterns that begin with '*' or end with '*'; for example, "*.Foo" or "java.*".

Parameters:
classPattern - the pattern String to filter against.
Throws:
InvalidRequestStateException - if this request is currently enabled or has been deleted. Filters may be added only to disabled requests.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ClassUnloadRequest (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.request
Interface ClassUnloadRequest

All Superinterfaces:
EventRequest, Mirror
public interface ClassUnloadRequest
extends EventRequest

Request for notification when a class is unloaded in the target VM. When an enabled ClassUnloadRequest is satisfied, a event set containing an ClassUnloadEvent will be placed on the EventQueue. The collection of existing ClassUnloadRequests is managed by the EventRequestManager

Refer to the Java Virtual Machine Specification for more information on class unloading.

Since:
1.3
See Also:
ClassUnloadEvent, EventQueue, EventRequestManager

Field Summary
Fields inherited from interface com.sun.jdi.request.EventRequest
SUSPEND_ALL, SUSPEND_EVENT_THREAD, SUSPEND_NONE
Method Summary
void | addClassExclusionFilter(String classPattern) Restricts the events generated by this request to the unloading of reference types whose name does not match a restricted regular expression.
void | addClassFilter(String classPattern) Restricts the events generated by this request to the unloading of reference types whose name matches a restricted regular expression.
Methods inherited from interface com.sun.jdi.request.EventRequest
addCountFilter, disable, enable, getProperty, isEnabled, putProperty, setEnabled, setSuspendPolicy, suspendPolicy
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Method Detail

addClassFilter

public void addClassFilter(String classPattern)
Restricts the events generated by this request to the unloading of reference types whose name matches a restricted regular expression. Regular expressions are limited to exact matches and patterns that begin with '*' or end with '*'; for example, "*.Foo" or "java.*".

Parameters:
classPattern - the pattern String to filter for.
Throws:
InvalidRequestStateException - if this request is currently enabled or has been deleted. Filters may be added only to disabled requests.

addClassExclusionFilter

public void addClassExclusionFilter(String classPattern)
Restricts the events generated by this request to the unloading of reference types whose name does not match a restricted regular expression. Regular expressions are limited to exact matches and patterns that begin with '*' or end with '*'; for example, "*.Foo" or "java.*".

Parameters:
classPattern - the pattern String to filter against.
Throws:
InvalidRequestStateException - if this request is currently enabled or has been deleted. Filters may be added only to disabled requests.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


DuplicateRequestException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.request
Class DuplicateRequestException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by com.sun.jdi.request.DuplicateRequestException
All Implemented Interfaces:
Serializable
public class DuplicateRequestException
extends RuntimeException

Thrown to indicate a duplicate event request.

Since:
1.3
See Also:
Serialized Form

Constructor Summary
DuplicateRequestException()
DuplicateRequestException(String s)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

DuplicateRequestException

public DuplicateRequestException()

DuplicateRequestException

public DuplicateRequestException(String s)
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


EventRequest (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.request
Interface EventRequest

All Superinterfaces:
Mirror
All Known Subinterfaces:
AccessWatchpointRequest, BreakpointRequest, ClassPrepareRequest, ClassUnloadRequest, ExceptionRequest, MethodEntryRequest, MethodExitRequest, ModificationWatchpointRequest, StepRequest, ThreadDeathRequest, ThreadStartRequest, VMDeathRequest, WatchpointRequest
public interface EventRequest
extends Mirror

Represents a request for notification of an event. Examples include BreakpointRequest and ExceptionRequest. When an event occurs for which an enabled request is present, an EventSet will be placed on the EventQueue. The collection of existing event requests is managed by the EventRequestManager.

The number of events generated for an event request can be controlled through filters. Filters provide additional constraints that an event must satisfy before it is placed on the event queue. Multiple filters can be used by making multiple calls to filter addition methods such as ExceptionRequest.addClassFilter(java.lang.String classPattern). Filters are added to an event one at a time only while the event is disabled. Multiple filters are applied with CUT-OFF AND, in the order it was added to the request. Only events that satisfy all filters are placed in the event queue.

The set of available filters is dependent on the event request, some examples of filters are:

  • Thread filters allow control over the thread for which events are generated.
  • Class filters allow control over the class in which the event occurs.
  • Instance filters allow control over the instance in which the event occurs.
  • Count filters allow control over the number of times an event is reported.
Filters can dramatically improve debugger performance by reducing the amount of event traffic sent from the target VM to the debugger VM.

Any method on EventRequest which takes EventRequest as an parameter may throw VMDisconnectedException if the target VM is disconnected and the VMDisconnectEvent has been or is available to be read from the EventQueue.

Any method on EventRequest which takes EventRequest as an parameter may throw VMOutOfMemoryException if the target VM has run out of memory.

Since:
1.3
See Also:
BreakpointEvent, EventQueue, EventRequestManager

Field Summary
static int | SUSPEND_ALL Suspend all threads when the event occurs
static int | SUSPEND_EVENT_THREAD Suspend only the thread which generated the event when the event occurs
static int | SUSPEND_NONE Suspend no threads when the event occurs
Method Summary
void | addCountFilter(int count) Limit the requested event to be reported at most once after a given number of occurrences.
void | disable() Same as setEnabled(false).
void | enable() Same as setEnabled(true).
Object | getProperty(Object key) Returns the value of the property with the specified key.
boolean | isEnabled() Determines if this event request is currently enabled.
void | putProperty(Object key, Object value) Add an arbitrary key/value "property" to this request.
void | setEnabled(boolean val) Enables or disables this event request.
void | setSuspendPolicy(int policy) Determines the threads to suspend when the requested event occurs in the target VM.
int | suspendPolicy() Returns a value which describes the threads to suspend when the requested event occurs in the target VM.
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Field Detail

SUSPEND_NONE

public static final int SUSPEND_NONE
Suspend no threads when the event occurs

See Also:
Constant Field Values

SUSPEND_EVENT_THREAD

public static final int SUSPEND_EVENT_THREAD
Suspend only the thread which generated the event when the event occurs

See Also:
Constant Field Values

SUSPEND_ALL

public static final int SUSPEND_ALL
Suspend all threads when the event occurs

See Also:
Constant Field Values
Method Detail

isEnabled

public boolean isEnabled()
Determines if this event request is currently enabled.

Returns:
true if enabled; false otherwise.

setEnabled

public void setEnabled(boolean val)
Enables or disables this event request. While this event request is disabled, the event request will be ignored and the target VM will not be stopped if any of its threads reaches the event request. Disabled event requests still exist, and are included in event request lists such as EventRequestManager.breakpointRequests().

Parameters:
val - true if the event request is to be enabled; false otherwise.
Throws:
InvalidRequestStateException - if this request has been deleted.
IllegalThreadStateException - if this is a StepRequest, val is true, and the thread named in the request has died.

enable

public void enable()
Same as setEnabled(true).

Throws:
InvalidRequestStateException - if this request has been deleted.
IllegalThreadStateException - if this is a StepRequest and the thread named in the request has died.

disable

public void disable()
Same as setEnabled(false).

Throws:
InvalidRequestStateException - if this request has been deleted.

addCountFilter

public void addCountFilter(int count)
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.

Parameters:
count - the number of ocurrences before generating an event.
Throws:
InvalidRequestStateException - if this request is currently enabled or has been deleted. Filters may be added only to disabled requests.
IllegalArgumentException - if count is less than one.

setSuspendPolicy

public void setSuspendPolicy(int policy)
Determines the threads to suspend when the requested event occurs in the target VM. Use SUSPEND_ALL to suspend all threads in the target VM (the default). Use SUSPEND_EVENT_THREAD to suspend only the thread which generated the event. Use SUSPEND_NONE to suspend no threads.

Thread suspensions through events have the same functionality as explicitly requested suspensions. See ThreadReference.suspend() and VirtualMachine.suspend() for details.

Parameters:
policy - the selected suspend policy.
Throws:
InvalidRequestStateException - if this request is currently enabled or has been deleted. Suspend policy may only be set in disabled requests.
IllegalArgumentException - if the policy argument contains an illegal value.

suspendPolicy

public int suspendPolicy()
Returns a value which describes the threads to suspend when the requested event occurs in the target VM. The returned value is SUSPEND_ALL, SUSPEND_EVENT_THREAD, or SUSPEND_NONE.

Returns:
the current suspend mode for this request

putProperty

public void putProperty(Object key,
                        Object value)
Add an arbitrary key/value "property" to this request. The property can be used by a client of the JDI to associate application information with the request; These client-set properties are not used internally by the JDI.

The get/putProperty methods provide access to a small per-instance map. This is not to be confused with Properties.

If value is null this method will remove the property.

See Also:
getProperty(java.lang.Object)

getProperty

public Object getProperty(Object key)
Returns the value of the property with the specified key. Only properties added with putProperty(java.lang.Object, java.lang.Object) will return a non-null value.

Returns:
the value of this property or null
See Also:
putProperty(java.lang.Object, java.lang.Object)
Overview  Package   Class  Use  Tree  Index  Help
Java Debug Interface
 PREV CLASS   NEXT CLASS FRAMES    NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


EventRequestManager (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.request
Interface EventRequestManager

All Superinterfaces:
Mirror
public interface EventRequestManager
extends Mirror

Manages the creation and deletion of EventRequests. A single implementor of this interface exists in a particuar VM and is accessed through VirtualMachine.eventRequestManager()

Since:
1.3
See Also:
EventRequest, Event, BreakpointRequest, BreakpointEvent, VirtualMachine

Method Summary
List | accessWatchpointRequests() Return an unmodifiable list of the enabled and disabled access watchpoint requests.
List | breakpointRequests() Return an unmodifiable list of the enabled and disabled breakpoint requests.
List | classPrepareRequests() Return an unmodifiable list of the enabled and disabled class prepare requests.
List | classUnloadRequests() Return an unmodifiable list of the enabled and disabled class unload requests.
AccessWatchpointRequest | createAccessWatchpointRequest(Field field) Creates a new disabled watchpoint which watches accesses to the specified field.
BreakpointRequest | createBreakpointRequest(Location location) Creates a new disabled BreakpointRequest.
ClassPrepareRequest | createClassPrepareRequest() Creates a new disabled ClassPrepareRequest.
ClassUnloadRequest | createClassUnloadRequest() Creates a new disabled ClassUnloadRequest.
ExceptionRequest | createExceptionRequest(ReferenceType refType, boolean notifyCaught, boolean notifyUncaught) Creates a new disabled ExceptionRequest.
MethodEntryRequest | createMethodEntryRequest() Creates a new disabled MethodEntryRequest.
MethodExitRequest | createMethodExitRequest() Creates a new disabled MethodExitRequest.
ModificationWatchpointRequest | createModificationWatchpointRequest(Field field) Creates a new disabled watchpoint which watches accesses to the specified field.
StepRequest | createStepRequest(ThreadReference thread, int size, int depth) Creates a new disabled StepRequest.
ThreadDeathRequest | createThreadDeathRequest() Creates a new disabled ThreadDeathRequest.
ThreadStartRequest | createThreadStartRequest() Creates a new disabled ThreadStartRequest.
VMDeathRequest | createVMDeathRequest() Creates a new disabled VMDeathRequest.
void | deleteAllBreakpoints() Remove all breakpoints managed by this EventRequestManager.
void | deleteEventRequest(EventRequest eventRequest) Removes an eventRequest.
void | deleteEventRequests(List eventRequests) Removes a list of EventRequests.
List | exceptionRequests() Return an unmodifiable list of the enabled and disabled exception requests.
List | methodEntryRequests() Return an unmodifiable list of the enabled and disabled method entry requests.
List | methodExitRequests() Return an unmodifiable list of the enabled and disabled method exit requests.
List | modificationWatchpointRequests() Return an unmodifiable list of the enabled and disabled modification watchpoint requests.
List | stepRequests() Return an unmodifiable list of the enabled and disabled step requests.
List | threadDeathRequests() Return an unmodifiable list of the enabled and disabled thread death requests.
List | threadStartRequests() Return an unmodifiable list of the enabled and disabled thread start requests.
List | vmDeathRequests() Return an unmodifiable list of the enabled and disabled VM death requests.
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Method Detail

createClassPrepareRequest

public ClassPrepareRequest createClassPrepareRequest()
Creates a new disabled ClassPrepareRequest. The new event request is added to the list managed by this EventRequestManager. Use EventRequest.enable() to activate this event request.

Returns:
the created ClassPrepareRequest

createClassUnloadRequest

public ClassUnloadRequest createClassUnloadRequest()
Creates a new disabled ClassUnloadRequest. The new event request is added to the list managed by this EventRequestManager. Use EventRequest.enable() to activate this event request.

Returns:
the created ClassUnloadRequest

createThreadStartRequest

public ThreadStartRequest createThreadStartRequest()
Creates a new disabled ThreadStartRequest. The new event request is added to the list managed by this EventRequestManager. Use EventRequest.enable() to activate this event request.

Returns:
the created ThreadStartRequest

createThreadDeathRequest

public ThreadDeathRequest createThreadDeathRequest()
Creates a new disabled ThreadDeathRequest. The new event request is added to the list managed by this EventRequestManager. Use EventRequest.enable() to activate this event request.

Returns:
the created ThreadDeathRequest

createExceptionRequest

public ExceptionRequest createExceptionRequest(ReferenceType refType,
                                               boolean notifyCaught,
                                               boolean notifyUncaught)
Creates a new disabled ExceptionRequest. The new event request is added to the list managed by this EventRequestManager. Use EventRequest.enable() to activate this event request.

A specific exception type and its subclasses can be selected for exception events. Caught exceptions, uncaught exceptions, or both can be selected. Note, however, that at the time an exception is thrown, it is not always possible to determine whether it is truly caught. See ExceptionEvent.catchLocation() for details.

Parameters:
refType - If non-null, specifies that exceptions which are instances of refType will be reported. Note: this will include instances of sub-types. If null, all instances will be reported
notifyCaught - If true, caught exceptions will be reported.
notifyUncaught - If true, uncaught exceptions will be reported.
Returns:
the created ExceptionRequest

createMethodEntryRequest

public MethodEntryRequest createMethodEntryRequest()
Creates a new disabled MethodEntryRequest. The new event request is added to the list managed by this EventRequestManager. Use EventRequest.enable() to activate this event request.

Returns:
the created MethodEntryRequest

createMethodExitRequest

public MethodExitRequest createMethodExitRequest()
Creates a new disabled MethodExitRequest. The new event request is added to the list managed by this EventRequestManager. Use EventRequest.enable() to activate this event request.

Returns:
the created MethodExitRequest

createStepRequest

public StepRequest createStepRequest(ThreadReference thread,
                                     int size,
                                     int depth)
Creates a new disabled StepRequest. The new event request is added to the list managed by this EventRequestManager. Use EventRequest.enable() to activate this event request.

The returned request will control stepping only in the specified thread; all other threads will be unaffected. A sizevalue of StepRequest.STEP_MIN will generate a step event each time the code index changes. It represents the smallest step size available and often maps to the instruction level. A size value of StepRequest.STEP_LINE will generate a step event each time the source line changes unless line number information is not available, in which case a STEP_MIN will be done instead. For example, no line number information is available during the execution of a method that has been rendered obsolete by by a VirtualMachine.redefineClasses(java.util.Map) operation. A depth value of StepRequest.STEP_INTO will generate step events in any called methods. A depth value of StepRequest.STEP_OVER restricts step events to the current frame or caller frames. A depth value of StepRequest.STEP_OUT restricts step events to caller frames only. All depth restrictions are relative to the call stack immediately before the step takes place.

Only one pending step request is allowed per thread.

Note that a typical debugger will want to cancel stepping after the first step is detected. Thus a next line method would do the following:

     EventRequestManager mgr = myVM.eventRequestManager();
     StepRequest request = mgr.createStepRequest(myThread,
                                                 StepRequest.STEP_LINE,
                                                 StepRequest.STEP_OVER);
     request.addCountFilter(1);  // next step only
     request.enable();
     myVM.resume();

Parameters:
thread - the thread in which to step
depth - the step depth
size - the step size
Returns:
the created StepRequest
Throws:
DuplicateRequestException - if there is already a pending step request for the specified thread.
IllegalArgumentException - if the size or depth arguments contain illegal values.

createBreakpointRequest

public BreakpointRequest createBreakpointRequest(Location location)
Creates a new disabled BreakpointRequest. The given Location must have a valid (that is, non-negative) code index. The new breakpoint is added to the list managed by this EventRequestManager. Multiple breakpoints at the same location are permitted. Use EventRequest.enable() to activate this event request.

Parameters:
location - the location of the new breakpoint.
Returns:
the created BreakpointRequest
Throws:
NativeMethodException - if location is within a native method.

createAccessWatchpointRequest

public AccessWatchpointRequest createAccessWatchpointRequest(Field field)
Creates a new disabled watchpoint which watches accesses to the specified field. The new watchpoint is added to the list managed by this EventRequestManager. Multiple watchpoints on the same field are permitted. Use EventRequest.enable() to activate this event request.

Not all target virtual machines support this operation. Use VirtualMachine.canWatchFieldAccess() to determine if the operation is supported.

Parameters:
field - the field to watch
Returns:
the created watchpoint
Throws:
UnsupportedOperationException - if the target virtual machine does not support this operation.

createModificationWatchpointRequest

public ModificationWatchpointRequest createModificationWatchpointRequest(Field field)
Creates a new disabled watchpoint which watches accesses to the specified field. The new watchpoint is added to the list managed by this EventRequestManager. Multiple watchpoints on the same field are permitted. Use EventRequest.enable() to activate this event request.

Not all target virtual machines support this operation. Use VirtualMachine.canWatchFieldModification() to determine if the operation is supported.

Parameters:
field - the field to watch
Returns:
the created watchpoint
Throws:
UnsupportedOperationException - if the target virtual machine does not support this operation.

createVMDeathRequest

public VMDeathRequest createVMDeathRequest()
Creates a new disabled VMDeathRequest. The new request is added to the list managed by this EventRequestManager. Use EventRequest.enable() to activate this event request.

This request (if enabled) will cause a VMDeathEvent to be sent on termination of the target VM.

A VMDeathRequest with a suspend policy of SUSPEND_ALL can be used to assure processing of incoming SUSPEND_NONE or SUSPEND_EVENT_THREAD events before VM death. If all event processing is being done in the same thread as event sets are being read, enabling the request is all that is needed since the VM will be suspended until the EventSet containing the VMDeathEvent is resumed.

Not all target virtual machines support this operation. Use VirtualMachine.canRequestVMDeathEvent() to determine if the operation is supported.

Returns:
the created request
Throws:
UnsupportedOperationException - if the target VM does not support this operation.
Since:
1.4

deleteEventRequest

public void deleteEventRequest(EventRequest eventRequest)
Removes an eventRequest. The eventRequest is disabled and the removed from the requests managed by this EventRequestManager. Once the eventRequest is deleted, no operations (for example, EventRequest.setEnabled(boolean)) are permitted - attempts to do so will generally cause an InvalidRequestStateException. No other eventRequests are effected.

Because this method changes the underlying lists of event requests, attempting to directly delete from a list returned by a request accessor (e.g. below):

   Iterator iter = requestManager.stepRequests().iterator();
   while (iter.hasNext()) {
      requestManager.deleteEventRequest(iter.next());
  }
may cause a ConcurrentModificationException. Instead use deleteEventRequests(List) or copy the list before iterating.

Parameters:
eventRequest - the eventRequest to remove

deleteEventRequests

public void deleteEventRequests(List eventRequests)
Removes a list of EventRequests.

Parameters:
eventRequests - the list of eventRequests to remove
See Also:
deleteEventRequest(EventRequest)

deleteAllBreakpoints

public void deleteAllBreakpoints()
Remove all breakpoints managed by this EventRequestManager.

See Also:
deleteEventRequest(EventRequest)

stepRequests

public List stepRequests()
Return an unmodifiable list of the enabled and disabled step requests. This list is a live view of these requests and thus changes as requests are added and deleted.

Returns:
the all StepRequest objects.

classPrepareRequests

public List classPrepareRequests()
Return an unmodifiable list of the enabled and disabled class prepare requests. This list is a live view of these requests and thus changes as requests are added and deleted.

Returns:
the all ClassPrepareRequest objects.

classUnloadRequests

public List classUnloadRequests()
Return an unmodifiable list of the enabled and disabled class unload requests. This list is a live view of these requests and thus changes as requests are added and deleted.

Returns:
the all ClassUnloadRequest objects.

threadStartRequests

public List threadStartRequests()
Return an unmodifiable list of the enabled and disabled thread start requests. This list is a live view of these requests and thus changes as requests are added and deleted.

Returns:
the all ThreadStartRequest objects.

threadDeathRequests

public List threadDeathRequests()
Return an unmodifiable list of the enabled and disabled thread death requests. This list is a live view of these requests and thus changes as requests are added and deleted.

Returns:
the all ThreadDeathRequest objects.

exceptionRequests

public List exceptionRequests()
Return an unmodifiable list of the enabled and disabled exception requests. This list is a live view of these requests and thus changes as requests are added and deleted.

Returns:
the all ExceptionRequest objects.

breakpointRequests

public List breakpointRequests()
Return an unmodifiable list of the enabled and disabled breakpoint requests. This list is a live view of these requests and thus changes as requests are added and deleted.

Returns:
the list of all BreakpointRequest objects.

accessWatchpointRequests

public List accessWatchpointRequests()
Return an unmodifiable list of the enabled and disabled access watchpoint requests. This list is a live view of these requests and thus changes as requests are added and deleted.

Returns:
the all AccessWatchpointRequest objects.

modificationWatchpointRequests

public List modificationWatchpointRequests()
Return an unmodifiable list of the enabled and disabled modification watchpoint requests. This list is a live view of these requests and thus changes as requests are added and deleted.

Returns:
the all ModificationWatchpointRequest objects.

methodEntryRequests

public List methodEntryRequests()
Return an unmodifiable list of the enabled and disabled method entry requests. This list is a live view of these requests and thus changes as requests are added and deleted.

Returns:
the list of all MethodEntryRequest objects.

methodExitRequests

public List methodExitRequests()
Return an unmodifiable list of the enabled and disabled method exit requests. This list is a live view of these requests and thus changes as requests are added and deleted.

Returns:
the list of all MethodExitRequest objects.

vmDeathRequests

public List vmDeathRequests()
Return an unmodifiable list of the enabled and disabled VM death requests. This list is a live view of these requests and thus changes as requests are added and deleted. Note: the unsolicited VMDeathEvent does not have a corresponding request.

Returns:
the list of all VMDeathRequest objects.
Since:
1.4
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ExceptionRequest (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.request
Interface ExceptionRequest

All Superinterfaces:
EventRequest, Mirror
public interface ExceptionRequest
extends EventRequest

Request for notification when an exception occurs in the target VM. When an enabled ExceptionRequest is satisfied, an event set containing an ExceptionEvent will be placed on the EventQueue. The collection of existing ExceptionRequests is managed by the EventRequestManager

Since:
1.3
See Also:
ExceptionEvent, EventQueue, EventRequestManager

Field Summary
Fields inherited from interface com.sun.jdi.request.EventRequest
SUSPEND_ALL, SUSPEND_EVENT_THREAD, SUSPEND_NONE
Method Summary
void | addClassExclusionFilter(String classPattern) Restricts the events generated by this request to those whose location is in a class whose name does not match a restricted regular expression.
void | addClassFilter(ReferenceType refType) Restricts the events generated by this request to those whose location is in the given reference type or any of its subtypes.
void | addClassFilter(String classPattern) Restricts the events generated by this request to those whose location is in a class whose name matches a restricted regular expression.
void | addInstanceFilter(ObjectReference instance) Restricts the events generated by this request to those in which the currently executing instance ("this") is the object specified.
void | addThreadFilter(ThreadReference thread) Restricts the events generated by this request to those in the given thread.
ReferenceType | exception() Returns exception type for which exception events are requested.
boolean | notifyCaught() Returns whether caught exceptions of the requested type will generate events when they are thrown.
boolean | notifyUncaught() Returns whether uncaught exceptions of the requested type will generate events when they are thrown.
Methods inherited from interface com.sun.jdi.request.EventRequest
addCountFilter, disable, enable, getProperty, isEnabled, putProperty, setEnabled, setSuspendPolicy, suspendPolicy
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Method Detail

exception

public ReferenceType exception()
Returns exception type for which exception events are requested.

Returns:
The exception (and its subclasses) requested with EventRequestManager.createExceptionRequest(com.sun.jdi.ReferenceType, boolean, boolean), or null if, as by default, all exceptions are requested.

notifyCaught

public boolean notifyCaught()
Returns whether caught exceptions of the requested type will generate events when they are thrown.

Note that at the time an exception is thrown, it is not always possible to determine whether it is truly caught. See ExceptionEvent.catchLocation() for details.

Returns:
boolean true if caught exceptions will be reported, false otherwise.

notifyUncaught

public boolean notifyUncaught()
Returns whether uncaught exceptions of the requested type will generate events when they are thrown.

Note that at the time an exception is thrown, it is not always possible to determine whether it is truly uncaught. See ExceptionEvent.catchLocation() for details.

Returns:
boolean true if caught exceptions will be reported, false otherwise.

addThreadFilter

public void addThreadFilter(ThreadReference thread)
Restricts the events generated by this request to those in the given thread.

Parameters:
thread - the thread to filter on.
Throws:
InvalidRequestStateException - if this request is currently enabled or has been deleted. Filters may be added only to disabled requests.

addClassFilter

public void addClassFilter(ReferenceType refType)
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.

Parameters:
refType - the reference type to filter on.
Throws:
InvalidRequestStateException - if this request is currently enabled or has been deleted. Filters may be added only to disabled requests.

addClassFilter

public void addClassFilter(String classPattern)
Restricts the events generated by this request to those whose location is in a class whose name matches a restricted regular expression. Regular expressions are limited to exact matches and patterns that begin with '*' or end with '*'; for example, "*.Foo" or "java.*".

Parameters:
classPattern - the pattern String to filter for.
Throws:
InvalidRequestStateException - if this request is currently enabled or has been deleted. Filters may be added only to disabled requests.

addClassExclusionFilter

public void addClassExclusionFilter(String classPattern)
Restricts the events generated by this request to those whose location is in a class whose name does not match a restricted regular expression. Regular expressions are limited to exact matches and patterns that begin with '*' or end with '*'; for example, "*.Foo" or "java.*".

Parameters:
classPattern - the pattern String to filter against.
Throws:
InvalidRequestStateException - if this request is currently enabled or has been deleted. Filters may be added only to disabled requests.

addInstanceFilter

public void addInstanceFilter(ObjectReference instance)
Restricts the events generated by this request to those in which the currently executing instance ("this") is the object specified.

Not all targets support this operation. Use VirtualMachine.canUseInstanceFilters() to determine if the operation is supported.

Parameters:
instance - the object which must be the current instance in order to pass this filter.
Throws:
UnsupportedOperationException - if the target virtual machine does not support this operation.
InvalidRequestStateException - if this request is currently enabled or has been deleted. Filters may be added only to disabled requests.
Since:
1.4
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


InvalidRequestStateException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.request
Class InvalidRequestStateException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by com.sun.jdi.request.InvalidRequestStateException
All Implemented Interfaces:
Serializable
public class InvalidRequestStateException
extends RuntimeException

Thrown to indicate that the requested event cannot be modified because it is enabled. Filters can be added only to disabled event requests. Also thrown if an operation is attempted on a deleted request. See EventRequestManager.deleteEventRequest(EventRequest)

Since:
1.3
See Also:
Serialized Form

Constructor Summary
InvalidRequestStateException()
InvalidRequestStateException(String s)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, 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

InvalidRequestStateException

public InvalidRequestStateException()

InvalidRequestStateException

public InvalidRequestStateException(String s)
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


MethodEntryRequest (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.request
Interface MethodEntryRequest

All Superinterfaces:
EventRequest, Mirror
public interface MethodEntryRequest
extends EventRequest

Request for notification when a method is invoked in the target VM. When an enabled MethodEntryRequest is satisfied, an event set containing a MethodEntryEvent will be placed on the EventQueue. The collection of existing MethodEntryRequests is managed by the EventRequestManager

Since:
1.3
See Also:
MethodEntryEvent, EventQueue, EventRequestManager

Field Summary
Fields inherited from interface com.sun.jdi.request.EventRequest
SUSPEND_ALL, SUSPEND_EVENT_THREAD, SUSPEND_NONE
Method Summary
void | addClassExclusionFilter(String classPattern) Restricts the events generated by this request to those whose method is in a class whose name does not match this restricted regular expression, e.g.
void | addClassFilter(ReferenceType refType) Restricts the events generated by this request to those whose method is in the given reference type or any of its subtypes.
void | addClassFilter(String classPattern) Restricts the events generated by this request to those whose method is in a class whose name matches this restricted regular expression.
void | addInstanceFilter(ObjectReference instance) Restricts the events generated by this request to those in which the currently executing instance ("this") is the object specified.
void | addThreadFilter(ThreadReference thread) Restricts the events generated by this request to those in the given thread.
Methods inherited from interface com.sun.jdi.request.EventRequest
addCountFilter, disable, enable, getProperty, isEnabled, putProperty, setEnabled, setSuspendPolicy, suspendPolicy
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Method Detail

addThreadFilter

public void addThreadFilter(ThreadReference thread)
Restricts the events generated by this request to those in the given thread.

Parameters:
thread - the thread to filter on.
Throws:
InvalidRequestStateException - if this request is currently enabled or has been deleted. Filters may be added only to disabled requests.

addClassFilter

public void addClassFilter(ReferenceType refType)
Restricts the events generated by this request to those whose method 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.

Parameters:
refType - the reference type to filter on.
Throws:
InvalidRequestStateException - if this request is currently enabled or has been deleted. Filters may be added only to disabled requests.

addClassFilter

public void addClassFilter(String classPattern)
Restricts the events generated by this request to those whose method is in a class whose name matches this restricted regular expression. Regular expressions are limited to exact matches and patterns that begin with '*' or end with '*'; for example, "*.Foo" or "java.*".

Parameters:
classPattern - the pattern String to filter for.
Throws:
InvalidRequestStateException - if this request is currently enabled or has been deleted. Filters may be added only to disabled requests.

addClassExclusionFilter

public void addClassExclusionFilter(String classPattern)
Restricts the events generated by this request to those whose method is in a class whose name does not match this restricted regular expression, e.g. "java.*" or "*.Foo".

Parameters:
classPattern - the pattern String to filter against.
Throws:
InvalidRequestStateException - if this request is currently enabled or has been deleted. Filters may be added only to disabled requests.

addInstanceFilter

public void addInstanceFilter(ObjectReference instance)
Restricts the events generated by this request to those in which the currently executing instance ("this") is the object specified.

Not all targets support this operation. Use VirtualMachine.canUseInstanceFilters() to determine if the operation is supported.

Parameters:
instance - the object which must be the current instance in order to pass this filter.
Throws:
UnsupportedOperationException - if the target virtual machine does not support this operation.
InvalidRequestStateException - if this request is currently enabled or has been deleted. Filters may be added only to disabled requests.
Since:
1.4
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


MethodExitRequest (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.request
Interface MethodExitRequest

All Superinterfaces:
EventRequest, Mirror
public interface MethodExitRequest
extends EventRequest

Request for notification when a method returns in the target VM. When an enabled MethodExitRequest is hit, an event set containing a MethodExitEvent will be placed on the EventQueue. The collection of existing MethodExitRequests is managed by the EventRequestManager

Since:
1.3
See Also:
MethodExitEvent, EventQueue, EventRequestManager

Field Summary
Fields inherited from interface com.sun.jdi.request.EventRequest
SUSPEND_ALL, SUSPEND_EVENT_THREAD, SUSPEND_NONE
Method Summary
void | addClassExclusionFilter(String classPattern) Restricts the events generated by this request to those whose method is in a class whose name does not match this restricted regular expression.
void | addClassFilter(ReferenceType refType) Restricts the events generated by this request to those whose method is in the given reference type or any of its subtypes.
void | addClassFilter(String classPattern) Restricts the events generated by this request to those whose method is in a class whose name matches a restricted regular expression.
void | addInstanceFilter(ObjectReference instance) Restricts the events generated by this request to those in which the currently executing instance ("this") is the object specified.
void | addThreadFilter(ThreadReference thread) Restricts the events generated by this request to those in the given thread.
Methods inherited from interface com.sun.jdi.request.EventRequest
addCountFilter, disable, enable, getProperty, isEnabled, putProperty, setEnabled, setSuspendPolicy, suspendPolicy
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Method Detail

addThreadFilter

public void addThreadFilter(ThreadReference thread)
Restricts the events generated by this request to those in the given thread.

Parameters:
thread - the thread to filter on.
Throws:
InvalidRequestStateException - if this request is currently enabled or has been deleted. Filters may be added only to disabled requests.

addClassFilter

public void addClassFilter(ReferenceType refType)
Restricts the events generated by this request to those whose method 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.

Parameters:
refType - the reference type to filter on.
Throws:
InvalidRequestStateException - if this request is currently enabled or has been deleted. Filters may be added only to disabled requests.

addClassFilter

public void addClassFilter(String classPattern)
Restricts the events generated by this request to those whose method is in a class whose name matches a restricted regular expression. Regular expressions are limited to exact matches and patterns that begin with '*' or end with '*'; for example, "*.Foo" or "java.*".

Parameters:
classPattern - the pattern String to filter for.
Throws:
InvalidRequestStateException - if this request is currently enabled or has been deleted. Filters may be added only to disabled requests.

addClassExclusionFilter

public void addClassExclusionFilter(String classPattern)
Restricts the events generated by this request to those whose method is in a class whose name does not match this restricted regular expression. Regular expressions are limited to exact matches and patterns that begin with '*' or end with '*'; for example, "*.Foo" or "java.*".

Parameters:
classPattern - the pattern String to filter against.
Throws:
InvalidRequestStateException - if this request is currently enabled or has been deleted. Filters may be added only to disabled requests.

addInstanceFilter

public void addInstanceFilter(ObjectReference instance)
Restricts the events generated by this request to those in which the currently executing instance ("this") is the object specified.

Not all targets support this operation. Use VirtualMachine.canUseInstanceFilters() to determine if the operation is supported.

Parameters:
instance - the object which must be the current instance in order to pass this filter.
Throws:
UnsupportedOperationException - if the target virtual machine does not support this operation.
InvalidRequestStateException - if this request is currently enabled or has been deleted. Filters may be added only to disabled requests.
Since:
1.4
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ModificationWatchpointRequest (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.request
Interface ModificationWatchpointRequest

All Superinterfaces:
EventRequest, Mirror, WatchpointRequest
public interface ModificationWatchpointRequest
extends WatchpointRequest

Request for notification when a field is set. This event will be triggered when a value is assigned to the specified field with a JavaTM programming language statement (assignment, increment, etc) or by a Java Native Interface (JNI) set function (Set<Type>Field, SetStatic<Type>Field). Setting a field to a value which is the same as the previous value still triggers this event. Modification by JDI does not trigger this event. When an enabled ModificationWatchpointRequest is satisfied, an event set containing a ModificationWatchpointEvent will be placed on the EventQueue. The collection of existing watchpoints is managed by the EventRequestManager.

Since:
1.3
See Also:
ModificationWatchpointEvent, AccessWatchpointRequest, EventQueue, EventRequestManager

Field Summary
Fields inherited from interface com.sun.jdi.request.EventRequest
SUSPEND_ALL, SUSPEND_EVENT_THREAD, SUSPEND_NONE
Methods inherited from interface com.sun.jdi.request.WatchpointRequest
addClassExclusionFilter, addClassFilter, addClassFilter, addInstanceFilter, addThreadFilter, field
Methods inherited from interface com.sun.jdi.request.EventRequest
addCountFilter, disable, enable, getProperty, isEnabled, putProperty, setEnabled, setSuspendPolicy, suspendPolicy
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


com.sun.jdi.request (Java Debug Interface)

 com.sun.jdi.request
Interfaces
AccessWatchpointRequest
BreakpointRequest
ClassPrepareRequest
ClassUnloadRequest
EventRequest
EventRequestManager
ExceptionRequest
MethodEntryRequest
MethodExitRequest
ModificationWatchpointRequest
StepRequest
ThreadDeathRequest
ThreadStartRequest
VMDeathRequest
WatchpointRequest
Exceptions
DuplicateRequestException
InvalidRequestStateException


com.sun.jdi.request (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package com.sun.jdi.request

This package is used to request that a JDI event be sent under specified conditions.

See:
Description

Interface Summary
AccessWatchpointRequest | Request for notification when the contents of a field are accessed in the target VM.
BreakpointRequest | Identifies a Location in the target VM at which execution should be stopped.
ClassPrepareRequest | Request for notification when a class is prepared in the target VM.
ClassUnloadRequest | Request for notification when a class is unloaded in the target VM.
EventRequest | Represents a request for notification of an event.
EventRequestManager | Manages the creation and deletion of EventRequests.
ExceptionRequest | Request for notification when an exception occurs in the target VM.
MethodEntryRequest | Request for notification when a method is invoked in the target VM.
MethodExitRequest | Request for notification when a method returns in the target VM.
ModificationWatchpointRequest | Request for notification when a field is set.
StepRequest | Request for notification when a step occurs in the target VM.
ThreadDeathRequest | Request for notification when a thread terminates in the target VM.
ThreadStartRequest | Request for notification when a thread starts execution in the target VM.
VMDeathRequest | Request for notification when the target VM terminates.
WatchpointRequest | Identifies a Field in the target VM being watched.

Exception Summary
DuplicateRequestException | Thrown to indicate a duplicate event request.
InvalidRequestStateException | Thrown to indicate that the requested event cannot be modified because it is enabled.

Package com.sun.jdi.request Description

This package is used to request that a JDI event be sent under specified conditions. With the exception of termination events, which are always sent, there is one kind of EventRequest for each kind of Event - for example, BreakpointRequest is used to request a BreakpointEvent. Event requests are created by the EventRequestManager. Events and event processing are defined in the com.sun.jdi.event package.

Methods may be added to the interfaces in the JDI packages in future releases. Existing packages may be renamed if the JDI becomes a standard extension.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


com.sun.jdi.request Class Hierarchy (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Hierarchy For Package com.sun.jdi.request

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class java.lang.Throwable (implements java.io.Serializable)
      • class java.lang.Exception
        • class java.lang.RuntimeException
          • class com.sun.jdi.request.DuplicateRequestException
          • class com.sun.jdi.request.InvalidRequestStateException

Interface Hierarchy

  • interface com.sun.jdi.Locatable
    • interface com.sun.jdi.request.BreakpointRequest (also extends com.sun.jdi.request.EventRequest)
  • interface com.sun.jdi.Mirror
    • interface com.sun.jdi.request.EventRequest
      • interface com.sun.jdi.request.BreakpointRequest (also extends com.sun.jdi.Locatable)
      • interface com.sun.jdi.request.ClassPrepareRequest
      • interface com.sun.jdi.request.ClassUnloadRequest
      • interface com.sun.jdi.request.ExceptionRequest
      • interface com.sun.jdi.request.MethodEntryRequest
      • interface com.sun.jdi.request.MethodExitRequest
      • interface com.sun.jdi.request.StepRequest
      • interface com.sun.jdi.request.ThreadDeathRequest
      • interface com.sun.jdi.request.ThreadStartRequest
      • interface com.sun.jdi.request.VMDeathRequest
      • interface com.sun.jdi.request.WatchpointRequest
        • interface com.sun.jdi.request.AccessWatchpointRequest
        • interface com.sun.jdi.request.ModificationWatchpointRequest
    • interface com.sun.jdi.request.EventRequestManager
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Package com.sun.jdi.request (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Package
com.sun.jdi.request

Packages that use com.sun.jdi.request
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.

Classes in com.sun.jdi.request used by com.sun.jdi
EventRequestManager
Manages the creation and deletion of EventRequests.

Classes in com.sun.jdi.request used by com.sun.jdi.event
EventRequest
Represents a request for notification of an event.

Classes in com.sun.jdi.request used by com.sun.jdi.request
AccessWatchpointRequest
Request for notification when the contents of a field are accessed in the target VM.
BreakpointRequest
Identifies a Location in the target VM at which execution should be stopped.
ClassPrepareRequest
Request for notification when a class is prepared in the target VM.
ClassUnloadRequest
Request for notification when a class is unloaded in the target VM.
EventRequest
Represents a request for notification of an event.
ExceptionRequest
Request for notification when an exception occurs in the target VM.
MethodEntryRequest
Request for notification when a method is invoked in the target VM.
MethodExitRequest
Request for notification when a method returns in the target VM.
ModificationWatchpointRequest
Request for notification when a field is set.
StepRequest
Request for notification when a step occurs in the target VM.
ThreadDeathRequest
Request for notification when a thread terminates in the target VM.
ThreadStartRequest
Request for notification when a thread starts execution in the target VM.
VMDeathRequest
Request for notification when the target VM terminates.
WatchpointRequest
Identifies a Field in the target VM being watched.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


StepRequest (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.request
Interface StepRequest

All Superinterfaces:
EventRequest, Mirror
public interface StepRequest
extends EventRequest

Request for notification when a step occurs in the target VM. When an enabled StepRequest is satisfied, an event set containing a StepEvent will be placed on the EventQueue. The collection of existing StepRequests is managed by the EventRequestManager

Since:
1.3
See Also:
StepEvent, EventQueue, EventRequestManager

Field Summary
static int | STEP_INTO Step into any newly pushed frames
static int | STEP_LINE Step to the next location on a different line
static int | STEP_MIN Step to the next available location
static int | STEP_OUT Step out of the current frame
static int | STEP_OVER Step over any newly pushed frames
Fields inherited from interface com.sun.jdi.request.EventRequest
SUSPEND_ALL, SUSPEND_EVENT_THREAD, SUSPEND_NONE
Method Summary
void | addClassExclusionFilter(String classPattern) Restricts the events generated by this request to those whose location is in a class whose name does not match a restricted regular expression.
void | addClassFilter(ReferenceType refType) Restricts the events generated by this request to those whose location is in the given reference type or any of its subtypes.
void | addClassFilter(String classPattern) Restricts the events generated by this request to those whose location is in a class whose name matches a restricted regular expression.
void | addInstanceFilter(ObjectReference instance) Restricts the events generated by this request to those in which the currently executing instance ("this") is the object specified.
int | depth()
int | size()
ThreadReference | thread()
Methods inherited from interface com.sun.jdi.request.EventRequest
addCountFilter, disable, enable, getProperty, isEnabled, putProperty, setEnabled, setSuspendPolicy, suspendPolicy
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Field Detail

STEP_INTO

public static final int STEP_INTO
Step into any newly pushed frames

See Also:
Constant Field Values

STEP_OVER

public static final int STEP_OVER
Step over any newly pushed frames

See Also:
Constant Field Values

STEP_OUT

public static final int STEP_OUT
Step out of the current frame

See Also:
Constant Field Values

STEP_MIN

public static final int STEP_MIN
Step to the next available location

See Also:
Constant Field Values

STEP_LINE

public static final int STEP_LINE
Step to the next location on a different line

See Also:
Constant Field Values
Method Detail

thread

public ThreadReference thread()
Returns:
the thread on which the step event is being requested.

size

public int size()
Returns:
the step size

depth

public int depth()
Returns:
the step depth

addClassFilter

public void addClassFilter(ReferenceType refType)
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.

Parameters:
refType - the reference type to filter on.
Throws:
InvalidRequestStateException - if this request is currently enabled or has been deleted. Filters may be added only to disabled requests.

addClassFilter

public void addClassFilter(String classPattern)
Restricts the events generated by this request to those whose location is in a class whose name matches a restricted regular expression. Regular expressions are limited to exact matches and patterns that begin with '*' or end with '*'; for example, "*.Foo" or "java.*".

Parameters:
classPattern - the pattern String to filter for.
Throws:
InvalidRequestStateException - if this request is currently enabled or has been deleted. Filters may be added only to disabled requests.

addClassExclusionFilter

public void addClassExclusionFilter(String classPattern)
Restricts the events generated by this request to those whose location is in a class whose name does not match a restricted regular expression. Regular expressions are limited to exact matches and patterns that begin with '*' or end with '*'; for example, "*.Foo" or "java.*".

Parameters:
classPattern - the pattern String to filter against.
Throws:
InvalidRequestStateException - if this request is currently enabled or has been deleted. Filters may be added only to disabled requests.

addInstanceFilter

public void addInstanceFilter(ObjectReference instance)
Restricts the events generated by this request to those in which the currently executing instance ("this") is the object specified.

Not all targets support this operation. Use VirtualMachine.canUseInstanceFilters() to determine if the operation is supported.

Parameters:
instance - the object which must be the current instance in order to pass this filter.
Throws:
UnsupportedOperationException - if the target virtual machine does not support this operation.
InvalidRequestStateException - if this request is currently enabled or has been deleted. Filters may be added only to disabled requests.
Since:
1.4
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ThreadDeathRequest (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.request
Interface ThreadDeathRequest

All Superinterfaces:
EventRequest, Mirror
public interface ThreadDeathRequest
extends EventRequest

Request for notification when a thread terminates in the target VM. When an enabled ThreadDeathRequest is satisfied, an event set containing a ThreadDeathEvent will be placed on the EventQueue. The collection of existing ThreadDeathRequests is managed by the EventRequestManager

Since:
1.3
See Also:
ThreadDeathEvent, EventQueue, EventRequestManager

Field Summary
Fields inherited from interface com.sun.jdi.request.EventRequest
SUSPEND_ALL, SUSPEND_EVENT_THREAD, SUSPEND_NONE
Method Summary
 void addThreadFilter(ThreadReference thread)
Restricts the events generated by this request to those in the given thread.
Methods inherited from interface com.sun.jdi.request.EventRequest
addCountFilter, disable, enable, getProperty, isEnabled, putProperty, setEnabled, setSuspendPolicy, suspendPolicy
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Method Detail

addThreadFilter

public void addThreadFilter(ThreadReference thread)
Restricts the events generated by this request to those in the given thread.

Parameters:
thread - the thread to filter on.
Throws:
InvalidRequestStateException - if this request is currently enabled or has been deleted. Filters may be added only to disabled requests.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


ThreadStartRequest (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.request
Interface ThreadStartRequest

All Superinterfaces:
EventRequest, Mirror
public interface ThreadStartRequest
extends EventRequest

Request for notification when a thread starts execution in the target VM. When an enabled ThreadStartRequest is hit, an event set containing a ThreadStartEvent will be placed on the EventQueue. The collection of existing ThreadStartRequests is managed by the EventRequestManager

Since:
1.3
See Also:
ThreadStartEvent, EventQueue, EventRequestManager

Field Summary
Fields inherited from interface com.sun.jdi.request.EventRequest
SUSPEND_ALL, SUSPEND_EVENT_THREAD, SUSPEND_NONE
Method Summary
 void addThreadFilter(ThreadReference thread)
Restricts the events generated by this request to those in the given thread.
Methods inherited from interface com.sun.jdi.request.EventRequest
addCountFilter, disable, enable, getProperty, isEnabled, putProperty, setEnabled, setSuspendPolicy, suspendPolicy
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Method Detail

addThreadFilter

public void addThreadFilter(ThreadReference thread)
Restricts the events generated by this request to those in the given thread.

Parameters:
thread - the thread to filter on.
Throws:
InvalidRequestStateException - if this request is currently enabled or has been deleted. Filters may be added only to disabled requests.
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


VMDeathRequest (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.request
Interface VMDeathRequest

All Superinterfaces:
EventRequest, Mirror
public interface VMDeathRequest
extends EventRequest

Request for notification when the target VM terminates. When an enabled VMDeathRequest is satisfied, an event set containing a VMDeathEvent will be placed on the EventQueue. The collection of existing VMDeathRequests is managed by the EventRequestManager

Even without creating a VMDeathRequest, a single unsolicited VMDeathEvent will be sent with a suspend policy of SUSPEND_NONE. This request would typically be created so that a VMDeathEvent with a suspend policy of SUSPEND_ALL will be sent. This event can be used to assure completion of any processing which requires the VM to be alive (e.g. event processing). Note: the unsolicited VMDeathEvent will still be sent.

Since:
1.4
See Also:
VMDeathEvent, EventQueue, EventRequestManager

Field Summary
Fields inherited from interface com.sun.jdi.request.EventRequest
SUSPEND_ALL, SUSPEND_EVENT_THREAD, SUSPEND_NONE
Methods inherited from interface com.sun.jdi.request.EventRequest
addCountFilter, disable, enable, getProperty, isEnabled, putProperty, setEnabled, setSuspendPolicy, suspendPolicy
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


WatchpointRequest (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

com.sun.jdi.request
Interface WatchpointRequest

All Superinterfaces:
EventRequest, Mirror
All Known Subinterfaces:
AccessWatchpointRequest, ModificationWatchpointRequest
public interface WatchpointRequest
extends EventRequest

Identifies a Field in the target VM being watched.

Since:
1.3
See Also:
AccessWatchpointRequest, ModificationWatchpointRequest, EventQueue, EventRequestManager

Field Summary
Fields inherited from interface com.sun.jdi.request.EventRequest
SUSPEND_ALL, SUSPEND_EVENT_THREAD, SUSPEND_NONE
Method Summary
void | addClassExclusionFilter(String classPattern) Restricts the events generated by this request to those whose location is in a class whose name does not match this restricted regular expression.
void | addClassFilter(ReferenceType refType) Restricts the events generated by this request to those whose location is in the given reference type or any of its subtypes.
void | addClassFilter(String classPattern) Restricts the events generated by this request to those whose location is in a class whose name matches a restricted regular expression.
void | addInstanceFilter(ObjectReference instance) Restricts the events generated by this request to those in which the currently executing instance ("this") is the object specified.
void | addThreadFilter(ThreadReference thread) Restricts the events generated by this request to those in the given thread.
Field | field() Gets the Field being watched by this WatchpointRequest.
Methods inherited from interface com.sun.jdi.request.EventRequest
addCountFilter, disable, enable, getProperty, isEnabled, putProperty, setEnabled, setSuspendPolicy, suspendPolicy
Methods inherited from interface com.sun.jdi.Mirror
toString, virtualMachine

Method Detail

field

public Field field()
Gets the Field being watched by this WatchpointRequest.

Returns:
the Field this Watchpoint is monitoring.

addThreadFilter

public void addThreadFilter(ThreadReference thread)
Restricts the events generated by this request to those in the given thread.

Parameters:
thread - the thread to filter on.
Throws:
InvalidRequestStateException - if this request is currently enabled or has been deleted. Filters may be added only to disabled requests.

addClassFilter

public void addClassFilter(ReferenceType refType)
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.

Parameters:
refType - the reference type to filter on.
Throws:
InvalidRequestStateException - if this request is currently enabled or has been deleted. Filters may be added only to disabled requests.

addClassFilter

public void addClassFilter(String classPattern)
Restricts the events generated by this request to those whose location is in a class whose name matches a restricted regular expression. Regular expressions are limited to exact matches and patterns that begin with '*' or end with '*'; for example, "*.Foo" or "java.*".

Parameters:
classPattern - the pattern String to filter for.
Throws:
InvalidRequestStateException - if this request is currently enabled or has been deleted. Filters may be added only to disabled requests.

addClassExclusionFilter

public void addClassExclusionFilter(String classPattern)
Restricts the events generated by this request to those whose location is in a class whose name does not match this restricted regular expression. Regular expressions are limited to exact matches and patterns that begin with '*' or end with '*'; for example, "*.Foo" or "java.*".

Parameters:
classPattern - the pattern String to filter against.
Throws:
InvalidRequestStateException - if this request is currently enabled or has been deleted. Filters may be added only to disabled requests.

addInstanceFilter

public void addInstanceFilter(ObjectReference instance)
Restricts the events generated by this request to those in which the currently executing instance ("this") is the object specified.

Not all targets support this operation. Use VirtualMachine.canUseInstanceFilters() to determine if the operation is supported.

Parameters:
instance - the object which must be the current instance in order to pass this filter.
Throws:
UnsupportedOperationException - if the target virtual machine does not support this operation.
InvalidRequestStateException - if this request is currently enabled or has been deleted. Filters may be added only to disabled requests.
Since:
1.4
Overview Package Class Use Tree Index Help
Java Debug Interface
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Uses of Interface com.sun.jdi.request.AccessWatchpointRequest (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.request.AccessWatchpointRequest

Packages that use AccessWatchpointRequest
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
 AccessWatchpointRequest EventRequestManager.createAccessWatchpointRequest(Field field)
Creates a new disabled watchpoint which watches accesses to the specified field.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.request.BreakpointRequest (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.request.BreakpointRequest

Packages that use BreakpointRequest
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
 BreakpointRequest EventRequestManager.createBreakpointRequest(Location location)
Creates a new disabled BreakpointRequest.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.request.ClassPrepareRequest (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.request.ClassPrepareRequest

Packages that use ClassPrepareRequest
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
 ClassPrepareRequest EventRequestManager.createClassPrepareRequest()
Creates a new disabled ClassPrepareRequest.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.request.ClassUnloadRequest (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.request.ClassUnloadRequest

Packages that use ClassUnloadRequest
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
 ClassUnloadRequest EventRequestManager.createClassUnloadRequest()
Creates a new disabled ClassUnloadRequest.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.jdi.request.DuplicateRequestException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.jdi.request.DuplicateRequestException

No usage of com.sun.jdi.request.DuplicateRequestException

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.request.EventRequest (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.request.EventRequest

Packages that use EventRequest
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
 EventRequest Event.request()

Uses of EventRequest in com.sun.jdi.request

Subinterfaces of EventRequest in com.sun.jdi.request
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 | 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
 void EventRequestManager.deleteEventRequest(EventRequest eventRequest)
Removes an eventRequest.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.request.EventRequestManager (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.request.EventRequestManager

Packages that use EventRequestManager
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
 EventRequestManager VirtualMachine.eventRequestManager()
Returns the event request manager for this virtual machine.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.request.ExceptionRequest (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.request.ExceptionRequest

Packages that use ExceptionRequest
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
 ExceptionRequest EventRequestManager.createExceptionRequest(ReferenceType refType, boolean notifyCaught, boolean notifyUncaught)
Creates a new disabled ExceptionRequest.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.jdi.request.InvalidRequestStateException (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.jdi.request.InvalidRequestStateException

No usage of com.sun.jdi.request.InvalidRequestStateException

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.request.MethodEntryRequest (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.request.MethodEntryRequest

Packages that use MethodEntryRequest
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
 MethodEntryRequest EventRequestManager.createMethodEntryRequest()
Creates a new disabled MethodEntryRequest.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.request.MethodExitRequest (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.request.MethodExitRequest

Packages that use MethodExitRequest
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
 MethodExitRequest EventRequestManager.createMethodExitRequest()
Creates a new disabled MethodExitRequest.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.request.ModificationWatchpointRequest (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.request.ModificationWatchpointRequest

Packages that use ModificationWatchpointRequest
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
 ModificationWatchpointRequest EventRequestManager.createModificationWatchpointRequest(Field field)
Creates a new disabled watchpoint which watches accesses to the specified field.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.request.StepRequest (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.request.StepRequest

Packages that use StepRequest
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
 StepRequest EventRequestManager.createStepRequest(ThreadReference thread, int size, int depth)
Creates a new disabled StepRequest.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.request.ThreadDeathRequest (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.request.ThreadDeathRequest

Packages that use ThreadDeathRequest
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
 ThreadDeathRequest EventRequestManager.createThreadDeathRequest()
Creates a new disabled ThreadDeathRequest.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.request.ThreadStartRequest (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.request.ThreadStartRequest

Packages that use ThreadStartRequest
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
 ThreadStartRequest EventRequestManager.createThreadStartRequest()
Creates a new disabled ThreadStartRequest.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.request.VMDeathRequest (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.request.VMDeathRequest

Packages that use VMDeathRequest
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
 VMDeathRequest EventRequestManager.createVMDeathRequest()
Creates a new disabled VMDeathRequest.

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.jdi.request.WatchpointRequest (Java Debug Interface)

Overview Package Class Use Tree Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.jdi.request.WatchpointRequest

Packages that use WatchpointRequest
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
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 Index Help
Java Debug Interface
PREV NEXT FRAMES NO FRAMES


Java(tm) Debug Wire Protocol

Java

JavaTM Debug Wire Protocol
Specification Details

 JDWP

  • 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)
  • 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)
  • 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)
  • Field Command Set (8)
  • ObjectReference Command Set (9)
    • ReferenceType (1)
    • GetValues (2)
    • SetValues (3)
    • MonitorInfo (5)
    • InvokeMethod (6)
    • DisableCollection (7)
    • EnableCollection (8)
    • IsCollected (9)
  • 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)
  • 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 | reserved16 | Reserved for future capability
    boolean | reserved17 | Reserved for future capability
    boolean | reserved18 | Reserved for future capability
    boolean | reserved19 | Reserved for future capability
    boolean | reserved20 | Reserved for future capability
    boolean | reserved21 | Reserved for future capability
    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.
    Out Data
    int | classes | Number of reference types that follow.
    Repeated classes times:
    referenceTypeID | refType | The reference type.
    int | classfile
    Repeated classfile times:
    byte | classbyte | byte in JVM class file format.
    Reply Data
    (None)
    Error Data
    INVALID_CLASS | One of the refType is not the ID of a reference type.
    INVALID_OBJECT | One of the refType 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.
    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.

    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 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.
    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
    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.
    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. 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.
    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.

    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. 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).
    Out Data
    referenceTypeID | refType | The class.
    methodID | methodID | The method.
    Reply Data
    long | start | Lowest valid code index for the method.
    long | end | Highest valid code index for the method.
    int | lines | The number of lines.
    Repeated lines times:
    long | lineCodeIndex | Initial code index of the line (unsigned).
    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.
    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.
    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.

    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
    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.
    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 the JDWP may be collected at any time the target VM is running. 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.

    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 The value of the String.
    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.
    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 for monitor entry or with java.lang.Object.wait. The thread must be suspended, and the returned information is relevant only while the thread is suspended.
    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.

    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 threads and thread groups directly contained in this thread group. Threads and thread groups in child thread groups are not included.
    Out Data
    threadGroupID group The thread group object ID.
    Reply Data
    int | childThreads | The number of child threads.
    Repeated childThreads times:
    threadID | childThread | A direct child thread ID.
    int | childGroups | The number of 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.
    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.

    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 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 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 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
    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.
    Out Data
    byte | event | Event type to clear
    int | requestID | ID of request to clear
    Reply Data
    (None)
    Error Data
    VM_DEAD The virtual machine is not running.
    ClearAllBreakpoints Command (3)
    Removes all set breakpoints.
    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.
    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.
    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 stack frames, thru and including 'frame'.Since JDWP version 1.4.
    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:

    • Always singleton composite events:
      • VM Start Event
      • VM Death Event
    • 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 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
    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 | Location of entry
    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 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.
    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.
    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.
    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. JVMDI 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

    VM_DISCONNECTED | 100 | Never sent across JDWP
    VM_START | JDWP.EventKind.VM_INIT
    THREAD_DEATH | JDWP.EventKind.THREAD_END
    SINGLE_STEP | 1
    BREAKPOINT | 2
    FRAME_POP | 3
    EXCEPTION | 4
    USER_DEFINED | 5
    THREAD_START | 6
    THREAD_END | 7
    CLASS_PREPARE | 8
    CLASS_UNLOAD | 9
    CLASS_LOAD | 10
    FIELD_ACCESS | 20
    FIELD_MODIFICATION | 21
    EXCEPTION_CATCH | 30
    METHOD_ENTRY | 40
    METHOD_EXIT | 41
    VM_INIT | 90
    VM_DEATH | 99

    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

    INVOKE_SINGLE_THREADED | 0x01 | otherwise, all threads started.
    INVOKE_NONVIRTUAL | 0x02 | otherwise, normal virtual invoke (instance methods only)

    Copyright © 2003 Sun Microsystems, Inc. All Rights Reserved.

    Please send comments to: java-debugger@java.sun.com

            Sun


Java Print Service

Java

JavaTM Print Service

 Documentation Contents
The JavaTM Print Service is a new Java Print API that allows printing on all Java platforms, including platforms requiring a small footprint, such as a J2ME profile, but still supports the current Java 2 Print API. Thie Java Print Service API includes an extensible print attribute set based on the standard attributes specified in the Internet Printing Protocol (IPP) 1.1 from the IETF. 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 data to different formats, a third party can dynamically install their own print services through the Service Provider Interface.

Java Print Service User Guide

The Java Print Service User Guide ( HTML | PDF ) describes the Java Print Service in more detail and demonstrates how to use the Java Print Service API to:
  • Discover and select print services based on their capabilities
  • Specify the format of print data
  • Submit print jobs to services that support the document type to be printed.

Java Print Service API Specification

The Java Print Service API consists of these four packages:

javax.print:
Provides the principal classes and interfaces for the Java Print Service API.

javax.print.attribute:
Provides classes and interfaces that describe the types of Java Print Service attributes and how they can be collected into attribute sets.

javax.print.attribute.standard:
Contains classes defining specific printing attributes.

javax.print.event:
Contains event classes and listener interfaces for monitoring print services and the progress of a specific print job.

For More Information

See the Java Software websites:
  • Printing on the Java Platform
  • JSR-006: Unified Printing API
  • The Java 2D Home Page
  • The JFC Home Page

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-print@sun.com 		Sun Microsystems, Inc
Java Software


Java Print Service API User Guide: - Example: Print2DGraphics.java

CONTENTS | PREV | NEXT JavaTM Print Service API User Guide

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Print Service API User Guide: - Example: Print2DPrinterJob.java

CONTENTS | PREV | NEXT JavaTM Print Service API User Guide

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Print Service API User Guide: - Example: Print2DtoStream.java

CONTENTS | PREV | NEXT JavaTM Print Service API User Guide

APPENDIX E

Example: Print2DtoStream.java

/*
 * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
 *
 * This software is the proprietary information of Sun Microsystems, Inc.
 * 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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Print Service API User Guide: - Example: PrintGIF.java

CONTENTS | PREV | NEXT JavaTM Print Service API User Guide

APPENDIX F

Example: PrintGIF.java

/*
* Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
*
* This software is the proprietary information of Sun Microsystems, Inc.
* 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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Print Service API User Guide: - Example: PrintGIFtoStream.java

CONTENTS | PREV | NEXT JavaTM Print Service API User Guide

APPENDIX B

Example: PrintGIFtoStream.java

/*
* Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
*
* This software is the proprietary information of Sun Microsystems, Inc.
* 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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Print Service API User Guide: - Example: PrintPS.java

CONTENTS | PREV | NEXT JavaTM Print Service API User Guide

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Print Service API User Guide: 2 - Attributes

CONTENTS | PREV | NEXT JavaTM Print Service API User Guide

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 JavaTM 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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Print Service API User Guide: 2 - Attributes

CONTENTS | PREV | NEXT JavaTM Print Service API User Guide

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Print Service API User Guide: 2 - Attributes

CONTENTS | PREV | NEXT JavaTM Print Service API User Guide

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Print Service API User Guide: 2 - Attributes

CONTENTS | PREV | NEXT JavaTM Print Service API User Guide

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Print Service API User Guide: 2 - Attributes

CONTENTS | PREV | NEXT JavaTM Print Service API User Guide

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Print Service API User Guide: 2 - Attributes

CONTENTS | PREV | NEXT JavaTM Print Service API User Guide

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Print Service API User Guide: 2 - Attributes

CONTENTS | PREV | NEXT JavaTM Print Service API User Guide

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 SDK 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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Print Service API User Guide: 3 - Specifying Document Types

CONTENTS | PREV | NEXT JavaTM Print Service API User Guide

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 PostScriptTM printers can directly print a PostScriptTM 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 JavaTM 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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Print Service API User Guide: 3 - Specifying Document Types

CONTENTS | PREV | NEXT JavaTM Print Service API User Guide

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 PostScriptTM, 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"

PostScriptTM 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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Print Service API User Guide: 3 - Specifying Document Types

CONTENTS | PREV | NEXT JavaTM Print Service API User Guide

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 JavaTM 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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Print Service API User Guide: 3 - Specifying Document Types

CONTENTS | PREV | NEXT JavaTM Print Service API User Guide

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 PostScriptTM document. Instead of the client explicitly describing the document as PostScriptTM 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 PostScriptTM. 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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Print Service API User Guide: 3 - Specifying Document Types

CONTENTS | PREV | NEXT JavaTM Print Service API User Guide

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Print Service API User Guide: - JavaTM Print Service Glossary

CONTENTS | PREV | NEXT JavaTM Print Service API User Guide

APPENDIX G

JavaTM 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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Print Service API User Guide: 1 - Introduction

CONTENTS | PREV | NEXT JavaTM Print Service API User Guide

CHAPTER 1

Introduction

The JavaTM 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 JavaTM 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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Print Service API User Guide: 1 - Introduction

CONTENTS | PREV | NEXT JavaTM Print Service API User Guide

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 SDK 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 SDK 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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Print Service API User Guide: 1 - Introduction

CONTENTS | PREV | NEXT JavaTM Print Service API User Guide

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Print Service API User Guide: 1 - Introduction

CONTENTS | PREV | NEXT JavaTM Print Service API User Guide

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 Java 2 SDK 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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Print Service API User Guide: 1 - Introduction

CONTENTS | PREV | NEXT JavaTM Print Service API User Guide

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 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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Print Service API User Guide: Contents

CONTENTS | PREV | NEXT

JavaTM Print Service API User Guide

CONTENTS | PREV | NEXT
Copyright © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Print Service API User Guide: -

CONTENTS | PREV | NEXT JavaTM Print Service API User Guide

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Print Service API User Guide: 5 - Printing and Streaming 2D Graphics

CONTENTS | PREV | NEXT JavaTM Print Service API User Guide

CHAPTER 5

Printing and Streaming 2D Graphics

The Java 2DTM printing API is the java.awt.print package that is part of the JavaTM 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 JavaTM 2 SE to allow access to the JavaTM 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 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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Print Service API User Guide: 5 - Printing and Streaming 2D Graphics

CONTENTS | PREV | NEXT JavaTM Print Service API User Guide

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Print Service API User Guide: 5 - Printing and Streaming 2D Graphics

CONTENTS | PREV | NEXT JavaTM Print Service API User Guide

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Print Service API User Guide: 4 - Printing and Streaming Documents

CONTENTS | PREV | NEXT JavaTM Print Service API User Guide

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Print Service API User Guide: 4 - Printing and Streaming Documents

CONTENTS | PREV | NEXT JavaTM Print Service API User Guide

StreamPrintService Versus PrintService

The JavaTM 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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Print Service API User Guide: 4 - Printing and Streaming Documents

CONTENTS | PREV | NEXT JavaTM Print Service API User Guide

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 Java 2 SE SDK 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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Print Service API User Guide: 4 - Printing and Streaming Documents

CONTENTS | PREV | NEXT JavaTM Print Service API User Guide

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Print Service API User Guide: 4 - Printing and Streaming Documents

CONTENTS | PREV | NEXT JavaTM Print Service API User Guide

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Print Service API User Guide: 4 - Printing and Streaming Documents

CONTENTS | PREV | NEXT JavaTM Print Service API User Guide

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Print Service API User Guide: 4 - Printing and Streaming Documents

CONTENTS | PREV | NEXT JavaTM Print Service API User Guide

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Print Service API User Guide: 4 - Printing and Streaming Documents

CONTENTS | PREV | NEXT JavaTM Print Service API User Guide

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 © 2001 Sun Microsystems, Inc. All Rights Reserved.


Java Virtual Machine Profiler Interface

Java (tm)

JavaTM Virtual Machine Profiler Interface (JVMPI)

 Documentation Contents
The JavaTM Virtual Machine* Profiling Interface (JVMPI) is an experimental interface for profiling. The JVMPI is not yet a standard profiling interface. This feature is provided for the benefit of tools vendors who have an immediate need for profiling hooks in the Java virtual machine. The JVMPI will continue to evolve, based on feedback from customers and tools vendors.

JVMPI is a two-way function call interface between the Java virtual machine and an in-process profiler agent. On the one hand, the virtual machine notifies the profiler agent of various events, corresponding to, for example, heap allocation, method calls, etc. On the other hand, the profiler agent issues control requests through the JVMPI. For example, the profiler agent can turn on/off a specific event notification, based on the needs of the profiler front-end.

JVMPI Reference

  • JVMPI Reference

*As used on this web site, the terms "Java Virtual Machine" or "JVM" mean a virtual machine for the Java platform.

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: jvmpi@eng.sun.com 		Sun

Java Software


The Java Virtual Machine Profiler Interface (JVMPI)

JavaTM Virtual Machine Profiler Interface (JVMPI)

This document describes the Java Virtual Machine Profiler Interface (JVMPI) in the Java 2 SDK, Standard Edition. It is intended for tools vendors to develop profilers that work in conjunction with Sun's Java virtual machine* implementation.

Note: This interface is an experimental feature in the Java 2 SDK. The JVMPI is not yet a standard profiling interface. We provide the documentation for the benefit of tools vendors who have an immediate need for profiling hooks in the Java virtual machine. The JVMPI will continue to evolve, based on the feedback from customers and tools vendors. Please send comments to jvmpi@eng.sun.com.

Note: VERSION_1 of this interface is implemented in the Classic VM. The Java HotSpot Client VM and the Java HotSpot Server VM both implement VERSION_1_1 (as of Java 2 SDK 1.2.2) or VERSION_1_2 (as of Java 2 SDK 1.4.2) of this interface with Java HotSpot technology. Notes specific to Java Hotspot technology are marked as such.

Contents

  • Overview
    • Start-up
    • Function Call Interface
    • Event Notification
    • JVMPI IDs
    • Threading and Locking Issues
    • Data Communication between the Profiler Agent a nd Front-End
  • Interface Functions
  • Events
  • Dump Formats
  • Data Types
  • Notes on Changes Since Java 2 SDK, v1.2
    • What's new?
    • Limitations
    • Changes in VERSION_1_1
    • Changes in VERSION_1_2
  • The HPROF Profiler Agent
    • Overview
    • Heap Allocation Profiles
    • CPU Usage Profiles
  • Code Examples
    • A Simple Class Load Tracer
    • The HPROF Profiling Agent

1. Overview

The JVMPI is a two-way function call interface between the Java virtual machine and an in-process profiler agent. On one hand, the virtual machine notifies the profiler agent of various events, corresponding to, for example, heap allocation, thread start, etc. On the other hand, the profiler agent issues controls and requests for more information through the JVMPI. For example, the profiler agent can turn on/off a specific event notification, based on the needs of the profiler front-end.

See long description [D]

The profiler front-end may or may not run in the same process as the profiler agent. It may reside in a different process on the same machine, or on a remote machine connected via the network. The JVMPI does not specify a standard wire protocol. Tools vendors may design wire protocols suitable for the needs of different profiler front-ends.

A profiling tool based on JVMPI can obtain a variety of information such as heavy memory allocation sites, CPU usage hot-spots, unnecessary object retention, and monitor contention, for a comprehensive performance analysis.

JVMPI supports partial profiling, i.e a user can selectively profile an application for certain subsets of the time the virtual machine is up and can also choose to obtain only certain types of profiling information.

In the current version of JVMPI, only one agent per virtual machine can be supported.

1.1. Start-up

The user can specify the name of the profiler agent and the options to the profiler agent through a command line option to the Java virtual machine. For example, suppose the user specifies:
     java -Xrunmyprofiler:heapdump=on,file=log.txt ToBeProfiledClass
The VM attempts to locate a profiler agent library called myprofiler in Java's library directory:
  • On Microsoft Windows, it is [value of java.home property]\bin\myprofiler.dll
  • On SPARC/Solaris, it is [value of java.home property]/lib/sparc/libmyprofiler.so
If the library is not found in the Java library directory, the VM continues to search for the library following the normal library search mechanism of the given platform:
  • On Microsoft Windows, the VM searches the current directory, Windows system directories, and the directories in the PATH environment variable.
  • On Solaris, the VM searches the directories in LD_LIBRARY_PATH.
The VM loads the profiler agent library and looks for the entry point:
jint JNICALL JVM_OnLoad(JavaVM *jvm, char *options, void *reserved);
The VM calls the JVM_OnLoad function, passing a pointer to the JavaVM instance as the first argument, and string "heapdump=on,file=log.txt" as the second argument. The third argument to JVM_OnLoad is reserved and set to NULL.

On success, the JVM_OnLoad function must return JNI_OK. If for some reason the JVM_OnLoad function fails, it must return JNI_ERR.

1.2. Function Call Interface

The profiler agent can obtain a function call interface by issuing a GetEnv call on the JavaVM pointer. For example, the following code retrieves the version of JVMPI interface that is implemented in the Java 2 SDK:
JVMPI_Interface *jvmpi_interface;

JNIEXPORT jint JNICALL JVM_OnLoad(JavaVM *jvm, char *options, void *reserved)
{
    int res = (*jvm)->GetEnv(jvm, (void **)&jvmpi_interface, JVMPI_VERSION_1);
    if (res < 0) {
        return JNI_ERR;
    }
    ... /* use entries in jvmpi_interface */
}
The JVMPI_Interface structure defines the function call interface between the profiler agent and the VM:
/* interface functions */
typedef struct {
    jint version;   /* JVMPI version */

    /* ------interface implemented by the profiler------ */

    void (*NotifyEvent)(JVMPI_Event *event);

    /* ------interface implemented by the JVM------ */

    jint (*EnableEvent)(jint event_type, void *arg);
    jint (*DisableEvent)(jint event_type, void *arg);
    jint (*RequestEvent)(jint event_type, void *arg);

    void (*GetCallTrace)(JVMPI_CallTrace *trace, jint depth);

    void (*ProfilerExit)(jint);

    JVMPI_RawMonitor (*RawMonitorCreate)(char *lock_name);
    void (*RawMonitorEnter)(JVMPI_RawMonitor lock_id);
    void (*RawMonitorExit)(JVMPI_RawMonitor lock_id);
    void (*RawMonitorWait)(JVMPI_RawMonitor lock_id, jlong ms);
    void (*RawMonitorNotifyAll)(JVMPI_RawMonitor lock_id);
    void (*RawMonitorDestroy)(JVMPI_RawMonitor lock_id);

    jlong (*GetCurrentThreadCpuTime)(void);
    void (*SuspendThread)(JNIEnv *env);
    void (*ResumeThread)(JNIEnv *env);
    jint (*GetThreadStatus)(JNIEnv *env);
    jboolean (*ThreadHasRun)(JNIEnv *env);
    jint (*CreateSystemThread)(char *name, jint priority, void (*f)(void *));
    void (*SetThreadLocalStorage)(JNIEnv *env_id, void *ptr);
    void * (*GetThreadLocalStorage)(JNIEnv *env_id);

    void (*DisableGC)(void);
    void (*EnableGC)(void);
    void (*RunGC)(void);

    jobjectID (*GetThreadObject)(JNIEnv *env);
    jobjectID (*GetMethodClass)(jmethodID mid);

    /* JNI handle <-> object ID conversions; VERSION_1_1 and newer */

    jobject   (*jobjectID2jobject)(jobjectID jid);
    jobjectID (*jobject2jobjectID)(jobject   j);

    /* VERSION_1_2 and newer: */

    void (*SuspendThreadList)(jint reqCount, JNIEnv **reqList, jint *results);
    void (*ResumeThreadList)(jint reqCount, JNIEnv **reqList, jint *results);

} JVMPI_Interface;
The GetEnv function returns a pointer to a JVMPI_Interface whose version field indicates a JVMPI version that is compatible to the version number argument passed in the GetEnv call. Note that the value of the version field is not necessarily identical to the version argument passed in the GetEnv call.

The JVMPI_Interface returned by GetEnv has all the functions set up except for NotifyEvent. The profiler agent must set up the NotifyEvent function pointer before returning from JVM_OnLoad.

1.3. Event Notification

The VM sends an event by calling NotifyEvent with a JVMPI_Event data structure as the argument. The following events are supported:
  • method enter and exit
  • object alloc, move, and free
  • heap arena create and delete
  • GC start and finish
  • JNI global reference alloc and free
  • JNI weak global reference alloc and free
  • compiled method load and unload
  • thread start and end
  • class file data ready for instrumentation
  • class load and unload
  • contended Java monitor wait to enter , entered, and exit
  • contended raw monitor wait to enter, entered, and exit
  • Java monitor wait and waited
  • monitor dump
  • heap dump
  • object dump
  • request to dump or reset profiling data
  • Java virtual machine initialization and shutdown

The JVMPI_Event structure contains the event type, the JNIEnv pointer of the current thread, and other event-specific information. The event specific information is represented as a union of event-specific structures. The JVMPI Events section provides a complete description of all event-specific structures. For now, we show the event-specific structures for class load and class unload below.

typedef struct {
    jint event_type;                  /* event_type */
    JNIEnv *env_id;                   /* env where this event occurred */

    union {
        struct {
        char *class_name;         /* class name */
        char *source_name;        /* name of source file */
        jint num_interfaces;      /* number of interfaces implemented */
          jint num_methods;         /* number of methods in the class */
        JVMPI_Method *methods;    /* methods */
        jint num_static_fields;   /* number of static fields */
        JVMPI_Field *statics;     /* static fields */
        jint num_instance_fields; /* number of instance fields */
        JVMPI_Field *instances;   /* instance fields */
        jobjectID class_id;       /* id of the class object */
    } class_load;

        struct {
        jobjectID class_id;       /* id of the class object */
    } class_unload;

        ... /* Refer to the section on JVMPI events for a full listing */
    } u;
} JVMPI_Event;

1.4. JVMPI IDs

The JVMPI refers to entities in the Java virtual machine as various kinds of IDs. Threads, classes, methods, objects, heap arenas and JNI global references all have unique IDs.

Each ID has a defining event and an undefining event. A defining event provides the information related to an ID. For example, the defining event for a thread ID contains, among other entries, the name of the thread.

An ID is valid until its undefining event arrives. An undefining event invalidates the ID, whose value may be reused later as a different kind of ID. The value of a thread ID, for example, may be redefined as a method ID after the thread ends.

ID | data type | defining event | undefining event
thread ID | JNIEnv * | thread start | thread end
object ID | jobjectID | object alloc | object free, object move, and arena delete
class ID | jobjectID | class load | class unload and object move
method ID | jmethodID | defining class load | defining class unload
arena ID | jint | arena new | arena delete
JNI global ref ID | jobject | global ref alloc | global ref free

Assuming the defining events are enabled during the profiler initialization, the profiler agent is guaranteed to be notified of an entity's creation through a defining event, before the entity appears in other JVMPI events.

If the defining events are not enabled, the profiler agent may receive an unknown ID. In that case the profiler agent may request the corresponding defining event to be sent on demand by issuing a RequestEvent call.

IDs representing objects have type jobjectID. A class is represented by the object ID of the corresponding java.lang.Class object. Therefore, class IDs are also of type jobjectID.

A jobjectID is defined by an object alloc event, and remains valid in the arena in which the object is allocated until one of its undefining events arrive:

  • An object free event invalidates an object ID.
  • An object move event is a special type of undefining events. Unlike other undefining events which signal the end-of-life of the corresponding entities, the object still exists, but its ID changes, and it may have been moved to a new arena.
  • An arena delete event invalidates all remaining object IDs in the arena.

When an object free or arena delete event invalidates an object ID, the object is known as being garbage collected.

Typically, the profiler agent maintains a mapping between jobjectIDs and its internal representation of object identities, and updates the mapping in response to the defining and undefining events for JVMPI object IDs.

Since object IDs may be invalidated during GC, the VM issues all events that contain jobjectID entries with GC disabled. In addition, the profiling agent must disable GC when it is directly manipulating any jobjectID data types. Otherwise the GC may invalidate a jobjectID while it is being manipulated in the agent code. The profiler agent must make sure that GC is disabled when it calls a JVMPI function that either takes a jobjectID argument or returns a jobjectID result. If the function call is inside an event handler where GC is already disabled, then the profiler agent need not explicitly disable the GC again.

A thread may be identified either by its JNIEnv interface pointer or by the object ID of the corresponding java.lang.Thread object. The JNIEnv pointer is valid between thread start and thread end events, and remains constant during the lifetime of a thread. The java.lang.Thread object ID, on the other hand, could remain valid after the thread ends, until it is garbage collected. The profiler agent can convert a JNIEnv pointer to the corresponding thread object ID by calling the GetThreadObject function.

1.5. Threading and Locking Issues

The JVMPI is used by the profiler agent that runs in the same process as the Java virtual machine. Programmers who write the agent must be careful in dealing with threading and locking issues in order to prevent data corruption and deadlocks.

Events are sent in the same thread where they are generated. For example, a class loading event is sent in the same thread in which the class is loaded. Multiple events may arrive concurrently in different threads. The agent program must therefore provide the necessary synchronization in order to avoid data corruption caused by multiple threads updating the same data structure at the same time.

In some cases, synchronizing on certain frequent events (such as method entry and method exit) may impose unacceptable overhead to program execution. Agents may utilize the thread-local storage support provided by the JVMPI to record profiling data without having to contend for global locks, and only merge the thread-local data into global profiles at selected intervals. The JVMPI supplies the agent with a pointer-size thread-local storage. Following is a simple example that illustrates how a profiler agent may take advantage of this feature. Suppose we need to write a profiler agent that counts the number of methods executed in each thread. The agent installs event handlers for thread start, method entry, and thread end events:

/* thread start event handler
 * sets up the storage for thread-local method invocation counter
 */
void ThreadStartHandler(JNIEnv *thread_id)
{
    int *p_ctr = (int *)malloc(sizeof(int));
    CALL(SetThreadLocalStorage)(thread_id, p_ctr);
}

/* method enter event handler
 * increments thread local method invocation counter
 */
void MethodEntryHandler(jmethodID method_id, JNIEnv *thread_id)
{
    int *p_ctr = (int *)CALL(GetThreadLocalStorage)(thread_id);
    (*p_ctr)++;
}

/* thread end handler
 * prints the number of methods executed
 */
void ThreadEndHandler(JNIEnv *thread_id)
{
    int *p_ctr = (int *)CALL(GetThreadLocalStorage)(thread_id);
    fprintf(stdout, "Thread %x executed %d methods\n",
        thread_id, (*p_ctr));
    free(p_ctr);
}

The following JVMPI functions can cause event notification to be sent synchronously in the same thread during the function execution:

  • RequestEvent
  • CreateSystemThread
  • RunGC

The RequestEvent function supplies the JVMPI event explicitly requested by the profiler agent. The CreateSystemThread function causes thread object allocation and thread start events to be issued. The RunGC function causes GC-related events to be generated.

When a profiling agent is loaded into the Java virtual machine, the process can either be in one of three modes: multi-threaded mode with GC enabled, multi-threaded mode with GC disabled, and the thread suspended mode. Different JVMPI events are issued in different modes. Certain JVMPI functions change the process from one mode to another.

The profiler agent must obey the following guidelines to avoid deadlocks:

  • In the multi-threaded mode with GC enabled, the agent code has a great deal of freedom in acquiring locks and calling JVMPI functions. Of course the normal rules of deadlock avoidance apply. Different threads must not enter the same set of locks in different orders.

  • When the GC is disabled the agent program must not call any JVMPI function that could require new Java objects to be created or cause the garbage collector to run. Currently, such functions include CreateSystemThread and RunGC. In addition, programmers need to be aware that disabling the GC creates an implicit locking dependency among threads. When the GC is disabled, the current thread may not be able to safely acquire certain locks. Deadlocks may happen, for example, if one thread disables GC and tries to acquire a lock, while another thread already acquired that lock but is triggering a GC.

  • In the thread suspended mode, one or more of the threads have been suspended. In this case, the agent program must not perform any operations that may cause the current thread to block. Such operations include, for example, the malloc and fprintf functions provided by the standard C library. These functions typically acquire internal C library locks that may be held by one of the suspended threads.

1.6 Data Communication between the Profiler Agent and Front-End

The JVMPI provides a low-level mechanism for a profiler agent to communicate with the virtual machine. The goal is to provide maximum flexiblity for the profiler agent to present the data depending on the needs of the front-end, and also to keep the processing work done by the virtual machine at a minimum. Therefore, the JVMPI does not specify a wire protocol between the profiling agent and the front-end. Instead, tools vendors design their own profiling agents that suit the needs of their front-ends.

The following issues need to be considered when designing the wire protocol in order to allow the profiler agent and front-end to reside on different machines:

  • Pointer size (e.g., 32 or 64 bit) - all of the JVMPI IDs are of pointer type (see Data Types).
  • Byte order (little endian or big endian).
  • Bit order (most significant bit first or least significant bit first).
  • String encoding - the JVMPI uses the UTF-8 encoding as documented in the Java virtual machine specification.

For example, the HPROF profiler agent shipped with the Java 2 SDK sends the size of all IDs as the first record, and uses the standard network byte order for integer and floating-point data.

2. Interface Functions

  • CreateSystemThread
  • DisableEvent
  • DisableGC
  • EnableEvent
  • EnableGC
  • GetCallTrace
  • GetCurrentThreadCpuTime
  • GetMethodClass
  • GetThreadLocalStorage
  • GetThreadObject
  • GetThreadStatus
  • NotifyEvent
  • ProfilerExit
  • RawMonitorCreate
  • RawMonitorDestroy
  • RawMonitorEnter
  • RawMonitorExit
  • RawMonitorNotifyAll
  • RawMonitorWait
  • RequestEvent
  • ResumeThread
  • ResumeThreadList
  • RunGC
  • SetThreadLocalStorage
  • SuspendThread
  • SuspendThreadList
  • ThreadHasRun
  • jobjectID2jobject
  • jobject2jobjectID

jint (*CreateSystemThread)(char *name, jint priority, void (*f)(void *));

Called by the profiler agent to create a daemon thread in the Java virtual machine.

It is safe for the profiler agent to make this call only after the JVM notifies a JVMPI_EVENT_INIT_DONE and when the system is in a multi-threaded mode with GC enabled.

Arguments:

name | - name of the thread.
priority | - thread priority; the values can be:
JVMPI_NORMAL_PRIORITY
JVMPI_MAXIMUM_PRIORITY
JVMPI_MINIMUM_PRIORITY
f | - function to be run by the thread.

Returns:

JNI_OK | - success.
JNI_ERR | - failure.

jint (*DisableEvent)(jint event_type, void *arg);

Called by the profiler agent to disable the notification of a particular type of event. Apart from event_type, the profiler agent may also pass an argument that provides additional information specific to the given event type.

All events are disabled when the VM starts up. Once enabled, an event stays enabled until it is explicitly disabled.

This function returns JVMPI_NOT_AVAILABLE if event_type is JVMPI_EVENT_HEAP_DUMP, JVMPI_EVENT_MONITOR_DUMP or JVMPI_EVENT_OBJECT_DUMP.

Arguments:

event_type | - type of event, JVMPI_EVENT_CLASS_LOAD etc.
arg | - event specific information.

Returns:

JVMPI_SUCCESS | disable succeeded.
JVMPI_FAIL | disable failed.
JVMPI_NOT_AVAILABLE | support for disabling the given event_type is not available.

void (*DisableGC)(void);

Called by the profiler to disable garbage collection, until EnabledGC is called. DisableGC and EnableGC calls may be nested.

jint (*EnableEvent)(jint event_type, void *arg);

Called by the profiler agent to enable notification of a particular type of event. Apart from event_type, the profiler may also pass an argument that provides additional information specific to the given event type.

All events are disabled when the VM starts up. Once enabled, an event stays enabled until it is explicitly disabled.

This function returns JVMPI_NOT_AVAILABLE if event_type is JVMPI_EVENT_HEAP_DUMP, JVMPI_EVENT_MONITOR_DUMP or JVMPI_EVENT_OBJECT_DUMP. The profiler agent must use the RequestEvent function to request these events.

Arguments:

event_type | - type of event, JVMPI_EVENT_CLASS_LOAD etc.
arg | - event specific argument.

Returns:

JVMPI_SUCCESS | enable succeeded.
JVMPI_FAIL | enable failed.
JVMPI_NOT_AVAILABLE | support for enabling the given event_type is not available.

void (*EnableGC)(void);

Enables garbage collections. DisableGC and EnableGC calls may be nested.

void (*GetCallTrace)(JVMPI_CallTrace *trace, jint depth);

Called by the profiler to obtain the current method call stack trace for a given thread. The thread is identified by the env_id field in the JVMPI_CallTrace structure. The profiler agent should allocate a JVMPI_CallTrace structure with enough memory for the requested stack depth. The VM fills in the frames buffer and the num_frames field.

Arguments:

trace | - trace data structure to be filled by the VM.
depth | - depth of the call stack trace.

jlong (*GetCurrentThreadCpuTime)(void);

Called by the profiler agent to obtain the accumulated CPU time consumed by the current thread.

Returns:

time in nanoseconds

jobjectID (*GetMethodClass)(jmethodID mid);

Called by the profiler agent to obtain the object ID of the class that defines a method.

The profiler must disable GC before calling this function.

Arguments:

mid - a method ID.

Returns:

object ID of the defining class.

void * (*GetThreadLocalStorage)(JNIEnv *env_id);

Called by the profiler to get the value of the JVMPI thread-local storage. The JVMPI supplies to the agent a pointer-size thread-local storage that can be used to record per-thread profiling information.

Arguments:

env_id - the JNIEnv * of the thread.

Returns:

the value of the thread local storage

jobjectID (*GetThreadObject)(JNIEnv *env);

Called by the profiler agent to obtain the thread object ID that corresponds to a JNIEnv pointer.

The profiler must disable GC before calling this function.

Arguments:

env - JNIEnv pointer of the thread.

Returns:

the thread object ID.

jint (*GetThreadStatus)(JNIEnv *env);

Called by the profiler agent to obtain the status of a thread.

Arguments:

env - the JNIEnv * of the thread.

Returns:

JVMPI_THREAD_RUNNABLE | - thread is runnable.
JVMPI_THREAD_MONITOR_WAIT | - thread is waiting on a monitor.
JVMPI_THREAD_CONDVAR_WAIT | - thread is waiting on a condition variable.

When a thread is suspended (by java.lang.Thread.suspend, SuspendThread or SuspendThreadList) or interrupted in any of the above states the JVMPI_THREAD_SUSPENDED or the JVMPI_THREAD_INTERRUPTED bit is set.

void (*NotifyEvent)(JVMPI_Event *event);

Called by the VM to send an event to the profiling agent. The profiler agent registers the types of events it is interested in by calling EnableEvent, or requests a specific type of event by calling RequestEvent.

When an event is enabled by EnableEvent, the thread that generates the event is the thread in which the event is sent. When an event is requested by RequestEvent, the thread that requests the event is the thread in which the event is sent. Multiple threads may send multiple events concurrently.

If the event specific information contains a jobjectID, this function is called with GC disabled. GC is enabled after the function returns.

The space allocated for the JVMPI_Event structure and any event specific information is freed by the virtual machine once this function returns. The profiler agent must copy any necessary data it needs to retain into its internal buffers.

Arguments:

event - the JVMPI event sent from the VM to the profiling agent.

void (*ProfilerExit)(jint err_code);

Called by the profiler agent to inform the VM that the profiler wants to exit with error code set to err_code. This function causes the VM to also exit with the same err_code.

Arguments:

err_code - exit code

JVMPI_RawMonitor (*RawMonitorCreate)(char *lock_name);

Called by the profiler to create a raw monitor.

Raw monitors are similar to Java monitors. The difference is that raw monitors are not associated with Java objects.

It is not safe for the profiler agent to call this function in the thread suspended mode because this function may call arbitrary system functions such as malloc and block on an internal system library lock.

If the raw monitor is created with a name beginning with an underscore ('_'), then its monitor contention events are not sent to the profiler agent.

Arguments:

lock_name - name of raw monitor.

Returns:

a raw monitor

void (*RawMonitorDestroy)(JVMPI_RawMonitor lock_id);

Called by the profiler agent to destroy a raw monitor and free all system resources associated with the monitor.

Raw monitors are similar to Java monitors. The difference is that raw monitors are not associated with Java objects.

It is not safe for the profiler agent to call this function in the thread suspended mode because this function may call arbitrary system functions such as free and block on a internal system library lock.

Arguments:

lock_id - the raw monitor to be destroyed

void (*RawMonitorEnter)(JVMPI_RawMonitor lock_id);

Called by the profiler agent to enter a raw monitor.

Raw monitors are similar to Java monitors. The difference is that raw monitors are not associated with Java objects.

It is not safe for the profiler agent to call this function in the thread suspended mode because the current thread may block on the raw monitor already acquired by one of the suspended threads.

Arguments:

lock_id - the raw monitor to be entered

void (*RawMonitorExit)(JVMPI_RawMonitor lock_id);

Called by the profiler agent to exit a raw monitor.

Raw monitors are similar to Java monitors. The difference is that raw monitors are not associated with Java objects.

Arguments:

lock_id - the raw monitor to exit

void (*RawMonitorNotifyAll)(JVMPI_RawMonitor lock_id);

Called by the profiler to notify all the threads that are waiting on a raw monitor.

Raw monitors are similar to Java monitors. The difference is that raw monitors are not associated with Java objects.

Arguments:

lock_id - the raw monitor to notify

void (*RawMonitorWait)(JVMPI_RawMonitor lock_id, jlong ms);

Called by the profiler agent to wait on a raw monitor for a specified timeout period. Passing 0 as the timeout period causes the thread to wait forever.

Raw monitors are similar to Java monitors. The difference is that raw monitors are not associated with Java objects.

Hotspot note: if the raw monitor is not owned by the thread executing RawMonitorWait, waiting will not occur.

Arguments:

lock_id | - the raw monitor to wait on
ms | - time to wait (in milliseconds).

jint (*RequestEvent)(jint event_type, void *arg);

Called by the profiler agent to request a particular type of event to be notified. Apart from event_type, the profiler agent may also pass an argument that provides additional information specific to the given event type.

This function can be called to request one-time events such as JVMPI_EVENT_HEAP_DUMP, JVMPI_EVENT_MONITOR_DUMP and JVMPI_EVENT_OBJECT_DUMP. Notification for these events cannot be controlled by the EnableEvent and DisableEvent functions.

In addition, this function can be called to request the defining events for a specific class, thread, or object. This is useful when the profiler agent needs to resolve an unknown class, method, thread, or object ID received in an event, but the corresponding defining event was disabled earlier.

  • The profiler agent may receive information about an unknown class ID by requesting a JVMPI_EVENT_CLASS_LOAD event and setting the event-specific argument to the class object ID.
  • The profiler agent may receive information about an unknown thread ID by requesting a JVMPI_EVENT_THREAD_START event and setting the event-specific argument to the thread object ID.
  • The profiler agent may receive information about an unknown object ID by requesting a JVMPI_EVENT_OBJECT_ALLOC event and setting the event-specific argument to the object ID.

Thus the profiler agent can either enable the above three events asynchronously by calling EnableEvent, or request these events synchronously by calling RequestEvent. The requested event is sent in the same thread that issued the RequestEvent call, and is sent before the RequestEvent function returns.

The RequestEvent function cannot be used to request other events not listed above.

Events requested through RequestEvent will arrive with the JVMPI_REQUESTED_EVENT bit set in its event_type.

Arguments:

event_type | - type of event, JVMPI_EVENT_CLASS_LOAD etc.
arg | - event specific argument.

Returns:

JVMPI_SUCCESS | request succeeded.
JVMPI_FAIL | request failed.
JVMPI_NOT_AVAILABLE | support for issuing the requested event_type is not available.

void (*ResumeThread)(JNIEnv *env);

Called by the profiler agent to resume a thread.

Note that a thread suspended by the java.lang.Thread.suspend method can be resumed by the JVMPI ResumeThread function.

Arguments:

env - the JNIEnv * of the thread.

void (*ResumeThreadList)(jint reqCount, JNIEnv **reqList, jint *results);

Called by the profiler agent to resume reqCount threads specified in the reqList array.

Arguments:

reqCount - the number of threads to resume
reqList - the list of threads to resume
results - the list of per-thread resume results

Returns:

The results array element for a specific thread contains zero (0) if the resume was successful and non-zero otherwise.

void (*RunGC)(void);

Called by the profiler to force a complete garbage collection. This function must not be called when GC is disabled.

void (*SetThreadLocalStorage)(JNIEnv *env_id, void *ptr);

Called by the profiler agent to set the value of the JVMPI thread-local storage. The JVMPI supplies to the agent a pointer-size thread-local storage that can be used to record per-thread profiling information.

Arguments:

env_id | - the JNIEnv * of the thread.
ptr | - the value to be entered into the thread-local storage.

void (*SuspendThread)(JNIEnv *env);

Called by the profiler agent to suspend a thread. The system enters the thread suspended mode after this function is called.

Note that a thread suspended by the JVMPI SuspendThread function can be resumed by the java.lang.Thread.resume method.

In the Java 2 SDK implementation, this function must be called when the GC is disabled. GC must remain disabled until all threads have been resumed.

Arguments:

env - the JNIEnv * of the thread.

void (*SuspendThreadList)(jint reqCount, JNIEnv **reqList, jint *results);

Called by the profiler agent to suspend reqCount threads specified in the reqList array. The system enters the thread suspended mode after this function is called.

In the Java 2 SDK implementation, this function must be called when the GC is disabled. GC must remain disabled until all threads have been resumed.

Arguments:

reqCount - the number of threads to suspend
reqList - the list of threads to suspend
results - the list of per-thread suspend results

Returns:

The results array element for a specific thread contains zero (0) if the suspend was successful and non-zero otherwise.

jboolean (*ThreadHasRun)(JNIEnv *env);

Called by the profiler to determine if a thread identified by the given JNIEnv pointer has consumed CPU time since the last time the thread was suspended by SuspendThread or SuspendThreadList. This function must be called when the thread has been resumed by ResumeThread or ResumeThreadList and then suspended again by the SuspendThread or SuspendThreadList function.

Arguments:

env - the JNIEnv * of the thread.

Returns:

JNI_TRUE | - thread got a chance to run.
JNI_FALSE | - thread did not get a chance to run.

jobject (*jobjectID2jobject)(jobjectID jid);

Called by the profiler agent to convert an object ID to JNI Handle.

This function is experimental and may be removed from the final JVMPI specification, as its usage is very unsafe and can lead to unreliable profilers. See also note.

Arguments:

jid - the object ID to be converted.

Returns:

JNI handle

jobjectID (*jobject2jobjectID)(jobject j);

Called by the profiler agent to convert a JNI Handle to an object ID.

This function is experimental and may be removed from the final JVMPI specification, as its usage is very unsafe and can lead to unreliable profilers.

Arguments:

j - JNI handle.

Returns:

object ID

Usage Note:

It is not safe to invoke JNI functions in arbirtrary JVMPI event handlers. JVMPI events may be issued in virtual machine states that are not suitable for executing JNI functions. The profiler agent may only invoke JNI functions in multithreaded mode (as defined by the JVMPI specification) and must take extremely care under these circumstances to avoid race conditions, dead locks, and infinite recursions.

Note that jobjectID2jobject and jobject2jobjectID may only be invoked in GC-disabled mode (as defined by the JVMPI specification) and under this mode it not safe to call JNI functions. Thus you should never call jobjectID2jobject and then use a JNI function to process the resulting jobject in an event handler running in GC-disabled mode.

3. Events

  • JVMPI_EVENT_ARENA_DELETE
  • JVMPI_EVENT_ARENA_NEW
  • JVMPI_EVENT_CLASS_LOAD
  • JVMPI_EVENT_CLASS_LOAD_HOOK
  • JVMPI_EVENT_CLASS_UNLOAD
  • JVMPI_EVENT_COMPILED_METHOD_LOAD
  • JVMPI_EVENT_COMPILED_METHOD_UNLOAD
  • JVMPI_EVENT_DATA_DUMP_REQUEST
  • JVMPI_EVENT_DATA_RESET_REQUEST
  • JVMPI_EVENT_GC_FINISH
  • JVMPI_EVENT_GC_START
  • JVMPI_EVENT_HEAP_DUMP
  • JVMPI_EVENT_JNI_GLOBALREF_ALLOC
  • JVMPI_EVENT_JNI_GLOBALREF_FREE
  • JVMPI_EVENT_JNI_WEAK_GLOBALREF_ALLOC
  • JVMPI_EVENT_JNI_WEAK_GLOBALREF_FREE
  • JVMPI_EVENT_JVM_INIT_DONE
  • JVMPI_EVENT_JVM_SHUT_DOWN
  • JVMPI_EVENT_METHOD_ENTRY
  • JVMPI_EVENT_METHOD_ENTRY2
  • JVMPI_EVENT_METHOD_EXIT
  • JVMPI_EVENT_MONITOR_CONTENDED_ENTER
  • JVMPI_EVENT_MONITOR_CONTENDED_ENTERED
  • JVMPI_EVENT_MONITOR_CONTENDED_EXIT
  • JVMPI_EVENT_MONITOR_DUMP
  • JVMPI_EVENT_MONITOR_WAIT
  • JVMPI_EVENT_MONITOR_WAITED
  • JVMPI_EVENT_OBJECT_ALLOC
  • JVMPI_EVENT_OBJECT_DUMP
  • JVMPI_EVENT_OBJECT_FREE
  • JVMPI_EVENT_OBJECT_MOVE
  • JVMPI_EVENT_RAW_MONITOR_CONTENDED_ENTER
  • JVMPI_EVENT_RAW_MONITOR_CONTENDED_ENTERED
  • JVMPI_EVENT_RAW_MONITOR_CONTENDED_EXIT
  • JVMPI_EVENT_THREAD_END
  • JVMPI_EVENT_THREAD_START
  • JVMPI_EVENT_INSTRUCTION_START

JVMPI_EVENT_ARENA_DELETE

Sent when a heap arena is deleted.

All objects residing in this arena are freed. An explicit JVMPI_EVENT_OBJECT_FREE is not sent for those objects. The profiler agent can infer all the objects currently residing in that arena by keeping track of the object allocations in the arena and all the objects moved in and out of the arena.

This event is issued in the thread suspended mode. The profiler must not make any blocking calls such as entering a monitor or allocating from the C heap (for example, via malloc).

This event is always sent between a pair of JVMPI_EVENT_GC_START and JVMPI_EVENT_GC_FINISH events. The profiler agent should acquire all the locks need for processing this event in the event handler for JVMPI_EVENT_GC_START.

struct {
    jint arena_id;
} delete_arena;
Contents:
arena_id - ID of the arena being deleted.

JVMPI_EVENT_ARENA_NEW

Sent when a new arena for allocating objects is created.
struct {
    jint arena_id;
    char *arena_name;
} new_arena;
Contents:
arena_id | - ID given to the arena.
arena_name | - name of the arena.

JVMPI_EVENT_CLASS_LOAD

Sent when a class is loaded in the VM, or when the profiler agent requests a JVMPI_EVENT_CLASS_LOAD event by issuing a RequestEvent call. In the latter case, the JVMPI_REQUESTED_EVENT bit in the event type is set.

This event is issued with GC disabled. GC is re-enabled after NotifyEvent returns.

struct {
    char *class_name;
    char *source_name;
    jint num_interfaces;
    jint num_methods;
    JVMPI_Method *methods;
    jint num_static_fields;
    JVMPI_Field *statics;
    jint num_instance_fields;
    JVMPI_Field *instances;
    jobjectID class_id;
} class_load;

Contents:

class_name | - name of class being loaded.
source_name | - name of source file that defines the class.
num_interfaces | - number of interfaces implemented by this class.
methods | - methods defined in the class.
num_static_fields | - number of static fields defined in this class.
statics | - static fields defined in the class.
num_instance_fields | - number of instance fields defined in this class.
instances | - instance fields defined in the class.
class_id | - class object ID.

Note: class IDs are IDs of the class objects and are subject to change when JVMPI_EVENT_OBJECT_MOVE arrives.

JVMPI_EVENT_CLASS_LOAD_HOOK

Sent when the VM obtains a class file data, but before it constructs the in-memory representation for that class. The profiler agent can instrument the existing class file data sent by the VM to include profiling hooks.

The profiler must allocate the space for the modified class file data buffer using the memory allocation function pointer sent in this event, because the VM is responsible for freeing the new class file data buffer.

struct {
    unsigned char *class_data;
    jint class_data_len;
    unsigned char *new_class_data;
    jint new_class_data_len;
    void * (*malloc_f)(unsigned int);
} class_load_hook;

Contents:

class_data | - pointer to the current class file data buffer.
class_data_len | - length of current class file data buffer.
new_class_data | - pointer to the instrumented class file data buffer.
new_class_data_len | - length of the new class file data buffer.
malloc_f | - pointer to a memory allocation function.

The profiler agent 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 NotifyEvent. It must set both new_class_data and new_class_data_len to the old values if it chooses not to instrument this class.

JVMPI_EVENT_CLASS_UNLOAD

Sent when a class is unloaded.

This event is issued with GC disabled. GC is re-enabled after NotifyEvent returns.

struct {
    jobjectID class_id;
} class_unload;

Contents:

class_id - class being unloaded.

JVMPI_EVENT_COMPILED_METHOD_LOAD

Sent when a method is compiled and loaded into memory.
struct {
    jmethodID method_id;
    void *code_addr;
    jint code_size;
    jint lineno_table_size;
    JVMPI_Lineno *lineno_table;
} compiled_method_load;

Contents:

method_id | - method being compiled and loaded.
code_addr | - address where compiled method code is loaded.
code_size | - size of compiled code.
lineno_table_size | - size of line number table.
lineno_table | - table mapping offset from beginning of method to the src file line number.

JVMPI_EVENT_COMPILED_METHOD_UNLOAD

Sent when a compiled method is unloaded from memory.
struct {
    jmethodID method_id;
} compiled_method_unload;

Contents:

method_id - compiled method being unloaded.

JVMPI_EVENT_DATA_DUMP_REQUEST

Sent by the VM to request the profiler agent to dump its data. This is just a hint and the profiler 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 Microsoft Windows or a CTRL-\ on Solaris causes the VM to send this event to the profiler agent.

There is no event specific information.

JVMPI_EVENT_DATA_RESET_REQUEST

Sent by the VM to request the profiler agent to reset its data. This is just a hint and the profiler 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 Microsoft Windows or a CTRL-\ on Solaris causes the VM to send this event to the profiler agent.

There is no event specific information.

JVMPI_EVENT_GC_FINISH

Sent when GC finishes. The profiler agent can release any locks, grabbed during GC start notification for handling object free, object move, and arena delete events. The system gets back into the multi-threaded mode after this event.

The event-specific data contains Java heap statistics.

struct {
    jlong used_objects;
    jlong used_object_space;
    jlong total_object_space;
} gc_info;
Contents:
used_objects | - number of used objects on the heap.
used_object_space | - amount of space used by the objects (in bytes).
total_object_space | - total amount of object space (in bytes).

JVMPI_EVENT_GC_START

Sent when GC is about to start. The system goes into thread suspended mode after this event. To avoid deadlocks, the profiler agent should grab any locks that are needed for handling object free, object move, and arena delete events in the event handler for this event.

There is no event specific information.

JVMPI_EVENT_HEAP_DUMP

Sent when requested by the RequestEvent function. The profiler agent can specify the level of information to be dumped by passing an JVMPI_HeapDumpArg structure to RequestEvent as the second argument, with the heap_dump_level field set to the desired dump level.

The dump level values can be one of the following:

  • JVMPI_DUMP_LEVEL_0
  • JVMPI_DUMP_LEVEL_1
  • JVMPI_DUMP_LEVEL_2

If a NULL value is passed, then the dump level is set to JVMPI_DUMP_LEVEL_2.

This event is issued with GC disabled. GC is re-enabled after NotifyEvent returns.

The event-specific data contains a snapshot of all live objects in the Java heap.

struct {
    int dump_level;
    char *begin;
    char *end;
    jint num_traces;
    JVMPI_CallTrace *traces;
} heap_dump;
Contents:
dump_level | - the dump level specified in RequestEvent
begin | - beginning of the heap dump
end | - end of the heap dump
num_traces | - number of stack traces in which the GC roots reside, 0 for JVMPI_DUMP_LEVEL_0
traces | - the stack traces in which the GC roots reside

The format of the heap dump between begin and end depends on the level of information requested. The formats are described in detail in the JVMPI Dump Formats section.

JVMPI_EVENT_JNI_GLOBALREF_ALLOC

Sent when a JNI global reference is created. The event-specific data contains the JNI global reference as well as the corresponding object ID.

This event is issued with GC disabled. GC is re-enabled after NotifyEvent returns.

struct {
    jobjectID obj_id;
    jobject ref_id;
} jni_globalref_alloc;
Contents:
obj_id | - object ID referred to by the global reference.
ref_id | - JNI global reference.

JVMPI_EVENT_JNI_GLOBALREF_FREE

Sent when a JNI global reference is deleted. The event-specific data contains the JNI global reference that is being deleted.
struct {
    jobject ref_id;
} jni_globalref_free;
Contents:
ref_id - JNI global reference.

JVMPI_EVENT_JNI_WEAK_GLOBALREF_ALLOC

Sent when a JNI weak global reference is created. The event-specific data contains the JNI weak global reference as well as the corresponding object ID.

This event is issued with GC disabled. GC is re-enabled after NotifyEvent returns.

struct {
    jobjectID obj_id;
    jobject ref_id;
} jni_globalref_alloc;
Contents:
obj_id | - object ID referred to by the weak global reference.
ref_id | - JNI weak global reference.

JVMPI_EVENT_JNI_WEAK_GLOBALREF_FREE

Sent when a JNI weak global reference is deleted. The event-specific data contains the JNI weak global reference that is being deleted.
struct {
    jobject ref_id;
} jni_globalref_free;
Contents:
ref_id - JNI weak global reference.

JVMPI_EVENT_JVM_INIT_DONE

Sent by the VM when its initialization is done. It is safe to call CreateSystemThread only after this event is notified.

There is no event specific data.

JVMPI_EVENT_JVM_SHUT_DOWN

Sent by the VM when it is shutting down. The profiler typically responds by saving the profiling data.

There is no event specific data.

JVMPI_EVENT_METHOD_ENTRY

Sent when a method is entered. Compared with JVMPI_EVENT_METHOD_ENTRY2, this event does not send the jobjectID of the target object on which the method is invoked.
struct {
    jmethodID method_id;
} method;

Contents:

method_id - the method being entered.

JVMPI_EVENT_METHOD_ENTRY2

Sent when a method is entered. If the method is an instance method, the jobjectID of the target object is sent with the event. If the method is a static method, the obj_id field in the event is set to NULL.

This event is issued with GC disabled. GC is re-enabled after NotifyEvent returns.

struct {
    jmethodID method_id;
    jobjectID obj_id;
} method_entry2;

Contents:

method_id | - the method being entered.
obj_id | - the target object, NULL for static methods.

JVMPI_EVENT_METHOD_EXIT

Sent when a method is exited. The method exit may be a normal exit, or caused by an unhandled exception.
struct {
    jmethodID method_id;
} method;

Contents:

method_id - the method being entered.

JVMPI_EVENT_MONITOR_CONTENDED_ENTER

Sent when a thread is attempting to enter a Java monitor already acquired by another thread.

This event is issued with GC disabled. GC is re-enabled after NotifyEvent returns.

struct {
    jobjectID object;
} monitor;
Contents:
object - object ID associated with the monitor

JVMPI_EVENT_MONITOR_CONTENDED_ENTERED

Sent when a thread enters a Java monitor after waiting for it to be released by another thread.

This event is issued with GC disabled. GC is re-enabled after NotifyEvent returns.

struct {
    jobjectID object;
} monitor;
Contents:
object - object ID associated with the monitor

JVMPI_EVENT_MONITOR_CONTENDED_EXIT

Sent when a thread exits a Java monitor, and another thread is waiting to acquire the same monitor.

This event is issued with GC disabled. GC is re-enabled after NotifyEvent returns.

struct {
    jobjectID object;
} monitor;
Contents:
object - object ID associated with the monitor

JVMPI_EVENT_MONITOR_DUMP

Sent when requested by the RequestEvent function.

The event-specific data contains a snapshot of all the threads and monitors in the VM.

This event is issued with GC disabled. GC is re-enabled after NotifyEvent returns.

struct {
    char *begin;
    char *end;
    jint num_traces;
    JVMPI_CallTrace *traces;
    jint *threads_status;
} monitor_dump;
Contents:
begin | - start of the monitor dump buffer.
end | - end of the dump buffer
num_traces | - number of thread traces.
traces | - traces of all threads.
thread_status | - status of all threads.

The format of the monitor dump buffer is described in detail in the JVMPI Dump Formats section.

JVMPI_EVENT_MONITOR_WAIT

Sent when a thread is about to wait on an object.

This event is issued with GC disabled. GC is re-enabled after NotifyEvent returns.

struct {
    jobjectID object;
    jlong timeout;
} monitor_wait;
Contents:
object | - ID of object on which the current thread is going to wait.
(NULL indicates the thread is in Thread.sleep.)
timeout | - the number of milliseconds the thread will wait. (0 indicates waiting forever.)

JVMPI_EVENT_MONITOR_WAITED

Sent when a thread finishes waiting on an object.

This event is issued with GC disabled. GC is re-enabled after NotifyEvent returns.

struct {
    jobjectID object;
    jlong timeout;
} monitor_wait;
Contents:
object | - ID of object on which the current thread waited.
(NULL indicates the thread is in Thread.sleep.)
timeout | - the number of milliseconds the thread waited.

JVMPI_EVENT_OBJECT_ALLOC

Sent when an object is allocated, or when the profiler agent requests a JVMPI_EVENT_OBJECT_ALLOC event by issuing a RequestEvent call. In the latter case, the JVMPI_REQUESTED_EVENT bit in the event type is set.

This event is issued with GC disabled. GC is re-enabled after NotifyEvent returns.

struct {
    jint arena_id;
    jobjectID class_id;
    jint is_array;
    jint size;
    jobjectID obj_id;
} obj_alloc;

Contents:

arena_id | - arena where allocated.
class_id | - class to which this object belongs, or the array element class if is_array is JVMPI_CLASS.
is_array | - values can be:
JVMPI_NORMAL_OBJECT | normal object
JVMPI_CLASS | array of objects
JVMPI_BOOLEAN | array of booleans
JVMPI_BYTE | array of bytes
JVMPI_CHAR | array of chars
JVMPI_SHORT | array of shorts
JVMPI_INT | array of ints
JVMPI_LONG | array of longs
JVMPI_FLOAT | array of floats
JVMPI_DOUBLE | array of doubles
size | - size in number of bytes.
obj_id | - unique object ID.

JVMPI_EVENT_OBJECT_DUMP

Sent when requested by the RequestEvent function. The jobjectID of the object for which a dump is being requested should be passed as the second argument to RequestEvent.

The profiler agent should request this event with GC disabled.

The event-specific data contains a snapshot of the object.

struct {
    jint data_len;
    char *data;
} object_dump;
Contents:
data_len | - length of the object dump buffer
data | - beginning of the object dump

The format of the object dump buffer is described in detail in the JVMPI Dump Formats section.

JVMPI_EVENT_OBJECT_FREE

Sent when an object is freed.

This event is issued in the thread suspended mode. The profiler must not make any blocking calls such as entering a monitor or allocating from the C heap (for example, via malloc).

This event is always sent between a pair of JVMPI_EVENT_GC_START and JVMPI_EVENT_GC_FINISH events. The profiler agent should acquire all the locks need for processing this event in the event handler for JVMPI_EVENT_GC_START.

struct {
    jobjectID obj_id;
} obj_free;

Contents:

obj_id - object being freed.

JVMPI_EVENT_OBJECT_MOVE

Sent when an object is moved in the heap.

This event is issued in the thread suspended mode. The profiler must not make any blocking calls such as entering a monitor or allocating from the C heap (for example, via malloc).

This event is always sent between a pair of JVMPI_EVENT_GC_START and JVMPI_EVENT_GC_FINISH events. The profiler agent should acquire all the locks need for processing this event in the event handler for JVMPI_EVENT_GC_START.

 struct {
     jint arena_id;
     jobjectID obj_id;
     jint new_arena_id;
     jobjectID new_obj_id;
} obj_move;

Contents:

arena_id | - current arena.
obj_id | - current object ID.
new_arena_id | - new arena.
new_obj_id | - new object ID.

JVMPI_EVENT_RAW_MONITOR_CONTENDED_ENTER

Sent when a thread is attempting to enter a raw monitor already acquired by another thread.
struct {
    char *name;
    JVMPI_RawMonitor id;
} raw_monitor;
Contents:
name | - name of the raw monitor
id | - ID of the raw monitor

JVMPI_EVENT_RAW_MONITOR_CONTENDED_ENTERED

Sent when a thread enters a raw monitor after waiting for it to be released by another thread.
struct {
    char *name;
    JVMPI_RawMonitor id;
} raw_monitor;
Contents:
name | - name of the raw monitor
id | - ID of the raw monitor

JVMPI_EVENT_RAW_MONITOR_CONTENDED_EXIT

Sent when a thread exits a raw monitor, and another thread is waiting to acquire the same monitor.
struct {
    char *name;
    JVMPI_RawMonitor id;
} raw_monitor;
Contents:
name | - name of the raw monitor
id | - ID of the raw monitor

JVMPI_EVENT_THREAD_END

Sent when a thread ends in the VM.

The env_id field of the JVMPI_Event received in this event notification is the JNIEnv interface pointer of the thread that ended.

JVMPI_EVENT_THREAD_START

Sent when a thread is started in the VM, or when the profiler agent requests a JVMPI_EVENT_THREAD_START event by issuing a RequestEvent call. In the latter case, the JVMPI_REQUESTED_EVENT bit in the event type is set.

This event is issued with GC disabled. GC is re-enabled after NotifyEvent returns.

struct {
    char *thread_name;
    char *group_name;
    char *parent_name;
    jobjectID thread_id;
    JNIEnv *thread_env_id;
} thread_start;

Contents:

thread_name | - name of thread being started.
group_name | - group to which the thread belongs.
parent_name | - name of parent.
thread_id | - thread object ID.
thread_env_id | - JNIEnv * of the thread.
Threads are associated with a JNIEnv pointer and a thread object ID. The JVMPI uses the JNIEnv pointer as the thread ID.

JVMPI_EVENT_INSTRUCTION_START

Sent when each instruction (i.e., bytecode operation) is issued by the interpreter.

This thread is issued only by interpreter, and not by compiled code.

struct {
    jmethodID method_id;
    jint      offset;
    union {
        struct {
            jboolean is_true;
        } if_info;
        struct {
            jint key;
            jint low;
            jint hi;
        } tableswitch_info;
        struct {
            jint     chosen_pair_index; /* actually chosen pair index (0-based) */
            jboolean is_default;        /* whether default branch is taken      */
        } lookupswitch_info;
    } u;
} instruction;

Contents:

method_id | - id of method that executes the instruction
offset | - instruction offset in the method's bytecode
is_true | - whether true or false branch is taken in an if-bytecode
key | - top stack value used as an index in tableswitch
low | - min value of the index in tableswitch
hi | - max value of the index in tableswitch
chosen_pair_index | - actually chosen pair index (0-based) in lookupswitch
is_default | - whether default branch is taken in lookupswitch

Hotspot note: must run with flag -XX:+EnableJVMPIInstructionStartEvent, otherwise no events will be sent.

4. Dump Formats

  • Sizes and Types Used in Dump Format Descriptions
  • Heap Dump Format
  • Object Dump Format
  • Monitor Dump Format

4.1 Sizes and Types Used in Dump Format Descriptions

u1: 1 byte
u2: 2 bytes
u4: 4 bytes
u8: 8 bytes
ty: u1 where:
JVMPI_NORMAL_OBJECT | normal object
JVMPI_CLASS | array of objects
JVMPI_BOOLEAN | array of booleans
JVMPI_BYTE | array of bytes
JVMPI_CHAR | array of chars
JVMPI_SHORT | array of shorts
JVMPI_INT | array of ints
JVMPI_LONG | array of longs
JVMPI_FLOAT | array of floats
JVMPI_DOUBLE | array of doubles
vl: values, exact size depends on the type of value:
boolean, byte | u1
short, char | u2
int, float | u4
long, double | u8
JNIEnv *, jobjectID, and JVMPI_RawMonitor | sizeof(void *)

4.2 Heap Dump Format

The heap dump format depends on the level of information requested.

JVMPI_DUMP_LEVEL_0:
The dump consists of a sequence of records of the following format:

ty | type of object
jobjectID | object

JVMPI_DUMP_LEVEL_1:
The dump format is the same as that of JVMPI_DUMP_LEVEL_2, except that the following values are excluded from the dump: primitive fields in object instance dumps, primitive static fields in class dumps, and primitive array elements.

JVMPI_DUMP_LEVEL_2:
The dump consists of a sequence of records, where each record includes an 8-bit record type followed by data whose format is specific to each record type.

Record type Record data
JVMPI_GC_ROOT_UNKNOWN
(unknown root)
jobjectID object
JVMPI_GC_ROOT_JNI_GLOBAL
(JNI global ref root)
jobjectID | object
jobject | JNI global reference
JVMPI_GC_ROOT_JNI_LOCAL
(JNI local ref)
jobjectID | object
JNIEnv * | thread
u4 | frame # in stack trace (-1 for empty)
JVMPI_GC_ROOT_JAVA_FRAME
(Java stack frame)
jobjectID | object
JNIEnv * | thread
u4 | frame # in stack trace (-1 for empty)
JVMPI_GC_ROOT_NATIVE_STACK
(native stack)
jobjectID | object
JNIEnv * | thread
JVMPI_GC_ROOT_STICKY_CLASS
(system class)
jobjectID class object
JVMPI_GC_ROOT_THREAD_BLOCK
(reference from thread block)
jobjectID | thread object
JNIEnv * | thread
JVMPI_GC_ROOT_MONITOR_USED
(entered monitor)
jobjectID object
JVMPI_GC_CLASS_DUMP
(dump of a class object)
jobjectID | class
jobjectID | super
jobjectID | class loader
jobjectID | signers
jobjectID | protection domain
jobjectID | class name (a String object, may be NULL)
void * | reserved
u4 | instance size (in bytes)
[jobjectID]* | interfaces
u2 | size of constant pool
[u2, | constant pool index,
 ty, | type,
 vl]* | value
[vl]* | static field values
JVMPI_GC_INSTANCE_DUMP
(dump of a normal object)
jobjectID | object
jobjectID | class
u4 | number of bytes that follow
[vl]* | instance field values (class, followed by super, super's super ...)
JVMPI_GC_OBJ_ARRAY_DUMP
(dump of an object array)
jobjectID | array object
u4 | number of elements
jobjectID | element class ID (may be NULL in the Java 2 SDK)
[jobjectID]* | elements
JVMPI_GC_PRIM_ARRAY_DUMP
(dump of a primitive array)
jobjectID | array object
u4 | number of elements
ty | element type
[vl]* | elements

4.3 Object Dump Format

The dump buffer consists of a single record which includes an 8-bit record type, followed by data specific to the record type. The record type can be one of the following:
  • JVMPI_GC_CLASS_DUMP
  • JVMPI_GC_INSTANCE_DUMP
  • JVMPI_GC_OBJ_ARRAY_DUMP
  • JVMPI_GC_PRIM_ARRAY_DUMP
The format of the data for each record type is the same as described above in the heap dump format section. The level of information is the same as JVMPI_DUMP_LEVEL_2, with all of the following values included: primitive fields in object instance dumps, primitive static fields in class dumps, and primitive arrays elements.

4.4 Monitor Dump Format

The dump buffer consists of a sequence of records, where each record includes an 8-bit record type followed by data whose format is specific to each record type.
Record type Record data
JVMPI_MONITOR_JAVA
(Java monitor)
jobjectID | object ID
JNIEnv * | owner thread
u4 | entry count
u4 | number of threads waiting to enter
[JNIEnv *]* | threads waiting to enter
u4 | number of threads waiting to be notified
[JNIEnv *]* | threads waiting to be notified
JVMPI_MONITOR_RAW
(Raw monitor)
char * | raw monitor name
JVMPI_RawMonitor | raw monitor ID
JNIEnv * | owner thread
u4 | entry count
u4 | number of threads waiting to enter
[JNIEnv *]* | threads waiting to enter
u4 | number of threads waiting to be notified
[JNIEnv *]* | threads waiting to be notified

5. Data Types

  • jobjectID
  • JVMPI_CallFrame
  • JVMPI_CallTrace
  • JVMPI_Field
  • JVMPI_HeapDumpArg
  • JVMPI_Lineno
  • JVMPI_Method
  • JVMPI_RawMonitor

Characters are encoded using the UTF-8 encoding as documented in the Java virtual machine specification.

jobjectID

An opaque pointer representing an object ID.

struct _jobjectID;
typedef struct _jobjectID * jobjectID;

JVMPI_CallFrame

A method being executed.

typedef struct {
    jint lineno;
    jmethodID method_id;
} JVMPI_CallFrame;
Fields:
line number | - line number in the source file.
method_id | - method being executed.

JVMPI_CallTrace

A call trace of method execution.
typedef struct {
    JNIEnv *env_id;
    jint num_frames;
    JVMPI_CallFrame *frames;
} JVMPI_CallTrace;
Fields:
env_id | - ID of thread which executed this trace.
num_frames | - number of frames in the trace.
frames | -the JVMPI_CallFrames that make up this trace. Callee followed by callers.

JVMPI_Field

A field defined in a class.
typedef struct {
    char *field_name;
    char *field_signature;
} JVMPI_Field;
Fields:
field_name | - name of field
field_signature | - signature of field

JVMPI_HeapDumpArg

Additional info for requesting heap dumps.

typedef struct {
    jint heap_dump_level;
} JVMPI_HeapDumpArg;
Fields:
heap_dump_level - level of heap dump information, values can be:
JVMPI_DUMP_LEVEL_0
JVMPI_DUMP_LEVEL_1
JVMPI_DUMP_LEVEL_2

JVMPI_Lineno

A mapping between source line number and offset from the beginning of a compiled method.
typedef struct {
    jint offset;
    jint lineno;
} JVMPI_Lineno;
Fields:
offset | - offset from beginning of method
lineno | - lineno from beginning of source file

JVMPI_Method

A method defined in a class.
typedef struct {
    char *method_name;
    char *method_signature;
    jint start_lineno;
    jint end_lineno;
    jmethodID method_id;
} JVMPI_Method;
Fields:
method_name | - name of method
method_signature | - signature of method
start_lineno | - start line number in the source file
end_lineno | - end line number in the source file
method_id | - ID given to this method

JVMPI_RawMonitor

An opaque pointer representing a raw monitor.

struct _JVMPI_RawMonitor;
typedef struct _JVMPI_RawMonitor * JVMPI_RawMonitor;

6. Notes on Changes Since Java 2 SDK, v1.2

6.1 What's new?

  • On Microsoft Windows, the following events are now supported in the presence of the JIT compiler:
    JVMPI_EVENT_METHOD_ENTRY,
    JVMPI_EVENT_METHOD_ENTRY2,
    JVMPI_EVENT_METHOD_EXIT,
    JVMPI_EVENT_COMPILED_METHOD_LOAD, and
    JVMPI_EVENT_COMPILED_METHOD_UNLOAD
  • The JVMPI_GC_CLASS_DUMP dump record now includes a jobjectID denoting the class name string object. This field was reserved in version 1.2 of the Java 2 SDK. The field is maintained by the VM as a class name cache, and thus may or may not be set for a given class.

6.2 Limitations

  • JVMPI_EVENT_OBJECT_ALLOC events for object arrays are issued with unknown element class IDs (i.e., the class_id field is always NULL).

  • SuspendThread or SuspendThreadList must be called with the GC is disabled. GC must remain disabled until all threads have been resumed.

  • The thread start event for the main thread (first thread the VM creates) may arrive after some other events that refer to its JNIEnv interface pointer.

  • JVMPI_EVENT_ARENA_NEW and JVMPI_EVENT_ARENA_DELETE events are never issued. Arena IDs in other events are always set to 1.

6.3 Changes in VERSION_1_1

  • The changes in this section are applicable when the JVMPI_Interface.version field is JVMPI_VERSION_1_1 or newer.
  • New event JVMPI_EVENT_INSTRUCTION_START which is issued in interpreter mode only.
  • Added two functions to JVMPI_Interface: jobjectID2jobject and jobject2jobjectID. Their usage is very restricted (see note).

6.4 Changes in VERSION_1_2

  • The changes in this section are applicable when the JVMPI_Interface.version field is JVMPI_VERSION_1_2 or newer.
  • Added two functions to JVMPI_Interface: SuspendThreadList and ResumeThreadList.

7. The HPROF Profiler Agent

7.1 Overview

HPROF is a simple profiler agent shipped with the Java 2 SDK. It is a dynamically-linked library that interacts with the JVMPI and writes out profiling information either to a file or to a socket in ascii or binary format. This information can be further processed by a profiler front-end tool.

It is capable of presenting CPU usage, heap allocation statistics and monitor contention profiles. In addition it can also report complete heap dumps and states of all the monitors and threads in the Java virtual machine.

HPROF can be invoked by:

java -Xrunhprof ToBeProfiledClass
Depending on the type of profiling requested, HPROF instructs the virtual machine to send it the relevant JVMPI events and processes the event data into profiling information. For example, the following command obtains the heap allocation profile:
java -Xrunhprof:heap=sites ToBeProfiledClass
Following is the complete list of options that can passed to hprof :
Hprof usage: -Xrunhprof[:help]|[:

Note: format=b cannot be used with cpu=old|times

By default, heap profiling information (sites and dump) is written out to java.hprof.txt (ascii).

7.2 Heap Allocation Profiles

Following is the heap allocation profile generated by running the Java compiler (javac) on a set of input files. Only parts of the profiler output are shown here.

Command used: javac -J-Xrunhprof:heap=sites foo.java ...
SITES BEGIN (ordered by live bytes) Wed Oct  7 11:38:10 1998
        percent        live       alloc'ed    stack class
rank  self  accum   bytes objs   bytes   objs trace name
   1 9.18%  9.18%  149224 5916 1984600 129884  1073 char []
   2 7.28% 16.45%  118320 5916  118320   5916  1090 sun/tools/java/Identifier
   3 7.28% 23.73%  118320 5916  118320   5916  1091 java/util/Hashtable$Entry
   ...
   7 3.39% 41.42%   55180 2759   55180   2759  1264 java/util/Hashtable$Entry
   ...
SITES END
A crucial piece of information in heap profile is the amount of allocation that occurs in various parts of the program. The SITES record above tells us that 9.18% of live objects are character arrays. Note that the amount of live data is only a fraction of the total allocation that has occurred at a given site; the rest has been garbage collected.

A good way to relate allocation sites to the source code is to record the dynamic stack traces that led to the heap allocation. Following is another part of the profiler output that illustrates the stack traces referred to by the four allocation sites in output shown above.

THREAD START (obj=1d6b20, id = 1, name="main", group="main")
...
TRACE 1073: (thread=1)
        java/lang/String.(String.java:244)
        sun/tools/java/Scanner.bufferString(Scanner.java:143)
        sun/tools/java/Scanner.scanIdentifier(Scanner.java:942)
        sun/tools/java/Scanner.xscan(Scanner.java:1281)

TRACE 1090: (thread=1)
        sun/tools/java/Identifier.lookup(Identifier.java:106)
        sun/tools/java/Scanner.scanIdentifier(Scanner.java:942)
        sun/tools/java/Scanner.xscan(Scanner.java:1281)
        sun/tools/java/Scanner.scan(Scanner.java:971)

TRACE 1091: (thread=1)
        java/util/Hashtable.put(Hashtable.java:405)
        sun/tools/java/Identifier.lookup(Identifier.java:106)
        sun/tools/java/Scanner.scanIdentifier(Scanner.java:942)
        sun/tools/java/Scanner.xscan(Scanner.java:1281)

TRACE 1264: (thread=1)
        java/util/Hashtable.put(Hashtable.java:405)
        sun/tools/java/Type.(Type.java:90)
        sun/tools/java/MethodType.(MethodType.java:42)
        sun/tools/java/Type.tMethod(Type.java:274)

Each frame in the stack trace contains class name, method name, source file name, and the line number. The user can set the maximum number of frames collected by the HPROF agent. The default limit is 4. Stack traces reveal not only which methods performed heap allocation, but also which methods were ultimately responsible for making calls that resulted in memory allocation. For example, in the heap profile above, instances of the same java/util/Hashtable$Entry class are allocated in traces 1091 and 1264, each originated from different methods.

7.3 CPU Usage Profiles

HPROF collects CPU usage information by sampling-based CPU time profiling. Following is part of the output collected from a run of the javac compiler.

Command used: javac -J-Xrunhprof:cpu=samples foo.java ...

CPU SAMPLES BEGIN (total = 252378) Wed Oct 07 13:30:10 1998
rank   self  accum   count trace method
   1  4.96%  4.96%   12514   303 sun/io/ByteToCharSingleByte.convert
   2  3.18%  8.14%    8022   306 java/lang/String.charAt
   3  1.91% 10.05%    4828   301 sun/tools/java/ScannerInputReader.
   4  1.80% 11.85%    4545   305 sun/io/ByteToCharSingleByte.getUnicode
   5  1.50% 13.35%    3783   304 sun/io/ByteToCharSingleByte.getUnicode
   6  1.30% 14.65%    3280   336 sun/tools/java/ScannerInputReader.read
   7  1.13% 15.78%    2864   404 sun/io/ByteToCharSingleByte.convert
   8  1.11% 16.89%    2800   307 java/lang/String.length
   9  1.00% 17.89%    2516  4028 java/lang/Integer.toString
  10  0.95% 18.84%    2403   162 java/lang/System.arraycopy
...
CPU SAMPLES END

The HPROF agent periodically samples the stack of all running threads to record the most frequently active stack traces. The count field above indicates how many times a particular stack trace was found to be active. These stack traces correspond to the CPU usage hot spots in the application.

8. Code Examples

8.1 A Simple Class Load Tracer

The jvmpi_example.zip file contains an example profiler agent for tracing all the classes loaded by a Java program. Both Solaris and Microsoft Windows versions are included.

8.2 The HPROF Profiling Agent

The hprof.zip file contains the implementation of the HPROF profiling agent in the Java 2 SDK. Both Solaris and Microsoft Windows versions are included.

*As used on this web site, the terms "Java Virtual Machine" or "JVM" mean a virtual machine for the Java platform.

Last modified: Mon Nov 4 15:24:04 PST


Packaging JNLP Applications in a Web Archive

Java TM Web Start 1.4.2

Please send comments and feedback to Java Web Start feedback.

Table of Contents

Introduction
Examples
Servlet Configuration
Specifying Resources
Mapping Requests to Resources
Processing of JNLP Files

Introduction

Java Web Start includes a servlet in the developer's pack that can be used to package a JNLP file and its associated resources in a Web Archive (.war) file. The purpose of the servlet is to provide a simple and convenient packaging format for JNLP applications, so they can be easily deployed in a Web Container, such as Tomcat or a J2EE-compliant Application Server.

The download servlet supports the following features:

  • Automatic installation of the codebase URL into JNLP files, thus eliminating manual management of hard-coded URLs into JNLP files.
  • Explicit specification of the timestamp for a JNLP file, independent of the file-system timestamp.
  • Supports all download protocols defined in the JNLP specification v1.0.1. These include basic download protocol, version-based download protocol, and extension download protocol.
  • Version-based information is specified per file or per directory in the Web archive. Thus, no centralized file needs to be managed for the entire archive.
  • Automatic generation of JARDiff files

The packaging support consists of one servlet: JnlpDownloadServlet. The servlet is packaged into the jnlp-servlet.jar file.

Below are two examples of how to use the servlet followed by a detailed description of the functionality of the servlet.

Examples

The first example shows how an application can be packaged into a WAR file without using the version-based download. The JnlpDownloadServlet is used to insert the exact URL into the JNLP file at request time. The second example shows how to add support for version-based download as well.

WAR file without use of version-download protocol

The example1.war contains:
   /index.html
   /app/launch.jnlp
   /app/application.jar
   /app/images/icon.gif
   /WEB-INF/web.xml
   /WEB-INF/lib/jnlp-servlet.jar
   /WEB-INF/lib/<jar files for XML parser> (not needed if the servlet container is running J2SE 1.4+)
The JNLP file for the application would look like this:
   TS: 2002-04-23 19:21:05
   <?xml version="1.0" encoding="UTF-8"?>
   <jnlp codebase="$$codebase">
     <information>
         <title>Example 1</title>
         <vendor>Myself</vendor>
         <description>just an example</description>
         <icon href="images/icon.gif"/>
     </information>
     <resources>
       <j2se version="1.2+"/>
       <jar href="application.jar"/>
     </resources>
     <application-desc/>
   </jnlp>
The first line with the TS tag contains the timestamp that the servlet will return for the JNLP file. The format of the timestamp is in ISO 8601 format. If the line is omitted, the timestamp of the file in the WAR file is used. The $$codebase string is modified by the JnlpDownloadServlet to be the actual URL for the request.

The web.xml file instructs the Web container to invoke the JNLPDownloadServlet for all requests to a JNLP file.

  <web-app>
     <servlet>
        <servlet-name>JnlpDownloadServlet</servlet-name>
        <servlet-class>com.sun.javaws.servlet.JnlpDownloadServlet</servlet-class>
     </servlet>
     <servlet-mapping>
        <servlet-name>JnlpDownloadServlet</servlet-name>
        <url-pattern>*.jnlp</url-pattern>
     </servlet-mapping>
  </web-app>
The JnlpDownloadServlet requires an XML parser in order to work. If your servlet container is running J2SE 1.4+, there is already a XML parser integrated in it. Otherwise please add jar files that implement a Java XML parser to the WEB-INF/lib directory. The reference implementation of the parser can be downloaded from http://java.sun.com/xml.

WAR file with use of version-download protocol

The example2.war contains:
   /index.html
   /app/version.xml
   /app/launch.jnlp
   /app/application.jar
   /app/lib__V2.1.jar
   /app/images/icon.gif
   /WEB-INF/web.xml
   /WEB-INF/lib/jnlp-servlet.jar
   /WEB-INF/lib/<jar files for XML parser> (not needed if the servlet container is running J2SE 1.4+)
The /app directory contains two JAR resources: application.jar and lib.jar. The lib.jar uses a naming convention to associate the version-id 2.1, i.e., the version information is associated on a per-file basis. The version of the application.jar file is described in the version.xml file, i.e., on a per-directory basis. The version.xml file looks like this:
   <jnlp-versions>
      <resource>
         <pattern>
           <name>application.jar</name>
            <version-id>1.1</version-id>
         </pattern>
         <file>application.jar</file>
      </resource>
   </jnlp-versions>
The JNLP file for the application looks like this:
   TS: 2002-04-23 19:21:05
   <?xml version="1.0" encoding="UTF-8"?>
   <jnlp codebase="$$codebase" href="$$name">
     <information>
         <title>Example 2</title>
         <vendor>Myself</vendor>
         <description>just an example</description>
         <icon href="images/icon.gif"/>
     </information>
     <resources>
       <j2se version="1.2+"/>
       <jar href="application.jar" version="1.1"/>
       <jar href="lib.jar" version="2.1"/>
     </resources>
     <application-desc/>
   </jnlp>
Finally, the web.xml file configures the JnlpDownloadServlet to be invoked for all requests into the /app directory.
  <web-app>
     <servlet>
        <servlet-name>JnlpDownloadServlet</servlet-name>
        <servlet-class>com.sun.javaws.servlet.JnlpDownloadServlet</servlet-class>
     </servlet>
     <servlet-mapping>
        <servlet-name>JnlpDownloadServlet</servlet-name>
        <url-pattern>/app/*</url-pattern>
     </servlet-mapping>
  </web-app>

Servlet Configuration

This section shows how to configure a WAR file to include the JnlpDownloadServlet and also how the servlet can be configured.

Adding the Servlet to a WAR archive

First the necessary servlet code must be made available to the servlet container. This is done by populating the WEB-INF/lib directory. The servlet is added to a WAR archive by including the jnlp-servlet.jar file in the WEB-INF/lib/ directory. The servlet needs access to an XML parser. If your servlet container is running J2SE 1.4+, there is already a XML parser integrated in it. Otherwise JAR files implementing a Java XML parser must also be added. They can be downloaded from http://java.sun.com/xml.

Once the servlet code is available, the Web container must be told to invoke the servlet on the right set of JNLP and JAR files, or on a given subdirectory. This is all configured in the WEB-INF/web.xml file inside the <web-app> tag:

   <web-app>
      ...
   </web-app>
The first thing to do is to tell the Web container how to invoke the servlet. This is done by using the <servlet> tag:
   <servlet>
      <servlet-name>JnlpDownloadServlet</servlet-name>
      <servlet-class>com.sun.javaws.servlet.JnlpDownloadServlet</servlet-class>
   </servlet>
Secondly, the Web container must be told when to invoke the servlet. This can be done in several ways. It can be invoked for certain directories or for files with certain extensions. For example, to invoke it for JNLP files, add the following to the web.xml file:
   <servlet-mapping>
     <servlet-name>JnlpDownloadServlet</servlet-name>
     <url-pattern>*.jnlp</url-pattern>
   </servlet-mapping>
Or for a given subdirectory:
   <servlet-mapping>
     <servlet-name>JnlpDownloadServlet</servlet-name>
     <url-pattern>/app/*</url-pattern>
   </servlet-mapping>

See also example1 and example2 for examples on how to configure the servlet.

Logging

The servlet has built-in logging capabilities to monitor its behavior. Logging messages are generated in 4 different categories:
FATAL
A malfunction or internal error happened inside the servlet.
WARNING
An error processing some of the information in the WAR file, e.g., parsing the version.xml file.
INFORMATIONAL
Logging all requests and replies, re-scanning of directories, etc.
DEBUG
Detailed internal information about how a request is processed.
The 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 will be written to. If no path is specified, logging is done to the standard log for servlets (using the ServletContext.log method). For example:
 <servlet>
    <servlet-name>
      JnlpDownloadServlet
    </servlet-name>
    <servlet-class>
      com.sun.javaws.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>

Configuring file extensions and MIME types

The servlet treats JNLP and JAR files specially. JNLP files will be macro-expanded as described in a section below. A version-based request for a JAR file might result in the generation for 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. For 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 shown below:
     Extension      Default MIME type
     -------------------------------------------
       .jnlp        application/x-java-jnlp-file
       .jar         application/x-java-archive
       .jardiff     application/x-java-archive-diff
A mapping can be overwritten by using the <mime-type> element in the web.xml file. For example:
  <web-app>
     ...
     <mime-mapping>
        <extension>jnlp</extension>
        <mime-type>text/ascii</mime-type>
     </mime-mapping>
     ...
  </web-app>

Specifying Resources

Application resources such as images, JAR files, and JNLP files are stored in the WAR file. The WAR file itself is a hierarchical directory structure, and the location of a resource inside the WAR file determines what URL will be used to look it up.

Assume that the WAR file (or servlet) has been configured so it handles all URL requests that starts with http://www.mytool.com/tool/. If the following requests is made: http://www.mytool.com/tool/app/launch.jnlp. Then the JnlpDownloadServlet will look for the launch.jnlp resource in the app/ directory in the WAR file.

No version information

A resource that has no associated version information, such as a JNLP file for an application, is simply just added to the WAR file. For example, given the above example, then the WAR file should included the following file:
    /app/launch.jnlp
In general, the timestamp that will be returned for the file is the last-modified timestamp that the file has in the WAR file. The only exception is for JNLP files where it can be explicitly specified in the JNLP file (see below).

Version information and more

The version-based and extension-based download protocols in the JNLP specification allows a resource to be looked up based on version-id, operating system, system architecture, and locale. The JnlpDownloadServlet provides two mechanisms for associating this information with a resource. It can be done on a per-file basis, using a naming convention, or by a per-directory basis, using a configuration file. Both methods can be used for the same directory.

The following information can be associated with a resource:

  • A path to the resource, e.g., /app
  • A name for the resource, e.g., launch.jnlp
  • A version-id, e.g., 1.1.0
  • A list of supported operations systems, e.g., SunOS Linux
  • A list of supported architectures, e.g., x86
  • A list of supported locales, e.g., da da_DK
  • A flag indicating if the version-id is a product version or a platform version (only used for JRE downloading)

The path is specified by the location of the resource in the WAR archive. The rest of the information is either specified by the use of a naming convention or in the version.xml file.

Resource Naming

The file naming convention is used if a double underscore (__) marker is found in the filename. The filename is parsed according to the BNF notation shown below:
    file    ::= name __ options . ext
    options ::= option ( __ options ) *
    option  ::= V version-id |
                O os |
                    A arch |
                    L locale
Only one version-id can be specified per file. However, multiple os, arch, and locale fields can be specified. For example:
    application__V1.2__Len_US__Len.jar
will mean that the resource application.jar has a version-id of 1.2, and the following associated locales: en_US and en.

The version.xml file

In each directory, a version.xml file can be placed to describe the additional properties, such as a version-id, for files in that particular directory. This is an alternative to the file naming convention.

For example, placing the file application-1_2-us.jar in a directory, along with a version.xml with the following content:

       <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>
will be the same as having placed the file application__V1.2__Len_US__Len.jar in the directory.

A resource can also be specified with a platform version-id in the version.xml file. Such a resource is used to match a particular platform request for a JRE. A resource with a platform version-id is specified using the <platform> element. For example:

      <platform>
             <pattern>
                <name>J2RE</name>
                <version-id>1.3</version-id>
                <locale>en_US</locale>
                <locale>en</locale>
             </pattern>
             <file>j2re-1_3.0-us.jnlp</file>
             <product-version-id>1.3.0</product-version-id>
         </platform>
Platform version requests are generated internally by Java Web Start, when an application has requested a version of the Java 2 platform that is currently not installed on the local system.

The complete document type definition (DTD) for the version.xml is shown in the following:

   <!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)>

Mapping Requests to Resources

The JNLP specification defines four different kinds of download requests that Java Web Start (or more generally, a JNLP Client) can make to a server when requesting a resource:
  • Basic Download Request: This is an ordinary URL request to a specific file. The Last-Modified field of the response is used to determine if an update is available on the server. The basic download request can be used for all resource types.
  • Version-based Download Request: This request type can be used for JAR files and images, i.e., the following elements will generate a version-based download request: <jar>, <nativelib>, and <icon>, when the version attribute is included.
  • Extension Download Request: This request type is an extension of the version-based request type and is generated by either the <j2se> or <extension> elements. In addition to the version information, it also contains information about operating system, system architecture, and locale.
  • Platform-version Download Request: This is simliar to the extension download request, but used to request a particular version of the Java 2 SE Runtime Environment (J2RE). This request is generated by Java Web Start, when a JNLP file has requested a particular version of the J2RE that is not currently installed on the client system.

A request is initially processed by the JNLPDownloadServlet, and it extracts the following information from the request:

  • Path in WAR file,
  • Name of requested file
  • Version string (version-id parameter or platform-version-id parameter)
  • Current version-id (current-version-id parameter)
  • List of operation systems (os parameter)
  • List of architectures (arch parameter)
  • List of locales (locale parameter)

Consider example2, and assume that it is being hosted at http://www.mytool.com/tool2/. If the following requests is made: http://www.mytool.com/tool2/app/lib.jar&version-id=2.1. Then the path of the resource would be, app/, the name would be lib.jar, the version string would be 2.1, and the lists for os, architecture, and locales would be empty.

A request to a directory, e.g., http://www.mytool.com/tool2/app/, will get appended the default filename: launch.jnlp. Thus, it would be the same as http://www.mytool.com/tool2/app/launch.jnlp.

Handling a basic download request

A request for which no version-id is specified (neither version-id parameter or platform-version-id parameter is specified in the request) is handled as a basic download request.

The request is first checked to see if it contains a double underscore (__) or is a request to the version.xml file. If so, the request is rejected and a HTTP 404 error code is returned.

The JnlpDownloadServlet will then try to locate the resource with the given path and name in the WAR file, and if found return it. If the resource is not found, a HTTP 404 error code is returned for the request.

If a match is found and it is a JNLP file, then it is preprocessed as described below before returned.

Handling a version-based download request

The resource lookup for resources with a version-id is uniform across the version-based download protocol, the extension download protocol, and the platform-version download request.

First, the JnlpDownloadServlet will build a database of all the resources that are located in the WAR file directory that the URL request is accessing (based on the path in the request). The database is built by scanning the version.xml file (if present), and the list of files in the directory that is using the naming convention described above. The servlet caches the information internally. It only does a re-scan if the timestamp of the version.xml file is more recent than at the last scan. Thus, if you add a file using the naming convention, make sure to touch the version.xml file to force the servlet to do a re-scan.

Secondly, the servlet will scan through the entries in the database to find a match for the given request (the match rules are described below). For a non-platform request, first the resource entries in the version.xml file are scanned in the order they are specified, and then secondly the entries that are specified using the naming convention. For a platform-version request, the platform entries in the version.xml file is scanned in the order they are specified. If several entries matches the request, then the entry with the highest version-id is returned. If multiple matches is found with the same highest version-id, then the first one specified is returned.

The matching rules are as follows:

  1. The name of the resource must match the request
  2. The version-id of the resource must match the version string in the request
  3. For the os, arch, and locale lists the following rules are used:
    1. If an empty list is specified for the resource, then it is a match
    2. If a non-empty list is specified for the resource, then it is a match, if at least one of the values specified for the resource is a prefix of at least one of the values specified in the request.
The x-java-jnlp-version-id returned in the response is the version-id for the matching resource, except for a platform request where it is taken from the <product-version-id> field in the version.xml file.

If a match is found and it is a JNLP file, then it is preprocessed as described below before returned.

Automatic JARDiff generation

The servlet will automatically generate and return 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 (given the above matching rules) and the request is for a JAR file (e.g., the target resource has the .jar extension), then a JARDiff file will be generated by the servlet. The JARDiff file is returned as long as 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 given Web container. The servlet locates the temporary working directory using the javax.servlet.context.tempdir context attribute.

Processing of JNLP files

The JnlpDownloadServlet will automatically macro-expand certain template values in a JNLP file and replace them with URLs that are specific to the current request. This will enable JNLP files to be written and deployed without containing hard-coded URLs.

Macro expansions

The servlet will automatically substitute certain fixed keys in the JNLP file (prefixed with $$) with URLs that are based on the current request. The keys are designed so location-independent WAR files can be created and deployed into a Web container.

The table below shows the 3 keys that the servlet will look for and substitute:

         Pattern       Value
         ----------------------------------------------------------------
         $$codebase    Complete URL for request, except name of JNLP file
     $$name        Name of the JNLP file
         $$context     Base URL for the Web Archive.
For example: Consider the example1 WAR file. Lets assume that it has been deployed at the following location: http://www.mytool.com/tool. Thus, a request to http://www.mytool.com/tool/app/launch.jnlp will return the JNLP file. The values of the macro-expanded keys would be:
      $$codebase = http://www.mytool.com/tool/app/
      $$name     = launch.jnlp
      $$context  = http://www.mytool.com/tool/

The servlet does not validate the format of the JNLP file nor that the XML is well-formed. The value substitution is purely textual.

Explicit Timestamps

An explicit timestamp can be included in a JNLP file to ensure that a consistent timestamp will be returned from the Web Server. This is especially useful if a JNLP file is replicated onto multiple Web servers that are serving the same URL in a round-robin or load-balancing fashion. Note that a similar method is not provided for JAR files. The version-based download protocol should be used instead.

An explicit timestamp is included in the JNLP if the first-line starts with TS:. If so, it is parsed accordingly to the ISO 8601 formatting of timestamps (see below). The first line is also removed from the contents.

See example1 and example2 above for sample JNLP files using the TS: element.

ISO 8601 Formatting

The general format of a timestamp is:
   YYYY-MM-DD hh:mm:ss
The dashes, colons, and seconds are optional:
   YYYYMMDDhhmm
The hh is in 24h notation. By default, the local time zone is used. A Universal Time (UTC) (also know as GMT time) can be specified by appending the capital letter Z to a time as in:
     23:59:59Z or 235959Z
The strings
     +hh:mm, +hhmm, or +hh
can be added to the time to indicate that the used 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 of time:
     12:00Z = 13:00+01:00 = 0700-0500

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.


Java(TM) Web Start

Java

JavaTM Web Start 1.4.2

 Documentation Contents
The JavaTM Web Start product version 1.4.2 is bundled with the Java 2 SDK and Java Runtime Environment (Java RE).

It is installed silently during the installation of the Java 2 SDK and Java RE. On Microsoft Windows, look for a Java Web Start icon on your desktop. There will also be an entry for Java Web Start in the Start --> Programs menu. On Solaris/Linux, you can launch Java Web Start by running <jre_home>/javaws/javaws.

Overview

Java Web Start is an application-deployment technology that gives you the power to launch full-featured applications with a single click from your Web browser. You can now download and launch applications, such as a complete spreadsheet program or an Internet chat client, without going through complicated installation procedures.

Java Web Start includes the security features of the JavaTM 2 platform, so the integrity of your data and files is never compromised. In addition, Java Web Start technology enables you to use the latest Java 2 technology—with any browser.

With Java Web Start, you launch applications simply by clicking on a Web page link. If the application is not present on your computer, Java Web Start automatically downloads all necessary files. It then caches the files on your computer so the application is always ready to be relaunched anytime you want—either from an icon on your desktop or from the browser link. And no matter which method you use to launch the application, the most current version of the application is always presented to you.

Developer's Pack

The Java Web Start product for network launching of applications is part of the Java 2 SDK. A Java Web Start Developer's Pack is available as a separate download. See the Developer's Section of the Java Web Start web site.

The Developer's Pack contains class libraries and documentation for use by developers in writing and deploying their applications using Java Web Start technology. In particular, the Developer's Pack contains the specification and implementation of the Java Network Launching Protocol (JNLP) API. This API enables applications to take advantage of services not ordinarily available to applications running on the Java 2 Platform.

In addition, the Developer's Pack contains documentation describing how developers can package their applications in a web archive file for efficient deployment over the net using Java Web Start technology.

Some of the documentation available in the Developer's Pack is also accessible from the links in the Documentation section below.

Documentation

  • README
  • Release Notes
  • Architecture (available on java.sun.com)
  • Developer's Guide (also available in PDF)
  • FAQ (available on java.sun.com)
  • Packaging JNLP Applications in a Web Archive
  • JNLP API Specification

Localized Documentation (ja | zh | zh_TW | ko | fr | it | de | es | sv)

Some documentation has been translated to Japanese, Chinese, Korean, French, Italian, German, Spanish, and Swedish. See Localized Documents.

For More Information

  • Empower Your Applications with JavaTM Web Start

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please submit comments at our feedback form. 		Sun
Java Software


Java(TM) Web Start Technology README

Java

README

JavaTM Web Start Technology

Version 1.4.2

Table of Contents

Introduction
Installation Instructions
Using Java Web Start Software
Release Notes

Introduction

JavaTM Web Start is a deployment solution for Java-technology-based applications. It is the plumbing between the computer and the Internet that allows the user to launch and manage applications right off the Web. Java Web Start provides easy, one-click activation of applications, and guarantees that you are always running the latest version of the application, eliminating complicated installation or upgrade procedures.

Distributing software across the Web in the tradition manner requires the user to find the installer on the Web, download the installer, locate the installer on the system, and then execute the installer. Once the installer is executed, it prompts for installation directories and installation options such as full, typical, or minimum. This is a time-consuming and complicated task, and one that must be repeated for each new version of the software.

By contrast, Web-deployed applications, such as your favorite HTML-based email client and calendar, auction sites, and so on, are a breeze to install and use. The Web browser has automated the entire process. There is no complicated download, setup, and configuration steps, and you are guaranteed to always be running the latest version.

Java Web Start technology provides the same benefits to full-featured applications as described above for HTML-based applications. Java Web Start technology is an application deployment solution for the Web. Using a full-featured application instead of an HTML-based client can have many benefits:

  • A highly-interactive user interface, comparable to traditional applications, such as word processors and spreadsheets.
  • Lower bandwidth requirements. An application does not necessarily have to connect back to the Web server on each click, and it can cache already-downloaded information. Thus, it can provide better interactivity on slow connections.
  • Support for off-line use.
Or course, you still have to download the application the first time you use it. An HTML-based application, thus has a first-time activation cost. Typically, a Web page is brought up in a matter of seconds. A Java TM-technology-based application will require download times in the order of minutes on a typical modem connection. The Java Web Start caches all downloaded files locally on the computer. Thus, although the first-time activation cost is higher for applications than for HTML pages, subsequent launches will be almost instantaneous because all the required resources are already available locally.

On each launch, Java Web Start checks the Web server to see if a new version of the application is available, and if so, automatically downloads and launches it. Thus, applications are automatically brought up to date. There is no complicated upgrade procedure.

Security

Java Web Start is built on top of the Java 2 platform, which provides a comprehensive security architecture. Applications launched with Java Web Start will, by default, run in a restricted environment ("sandbox") with limited access to files and network. Thus, launching applications using Java Web Start maintains system security and integrity.

An application can request unrestricted access to your system. In this case, Java Web Start will display a Security Warning dialog when the application is launched for the first time. The security warning will show information about the vendor who developed the application. If you choose to trust the vendor, then the application will be launched. The information about the origin of the application is based on digital code signing.

Installation Instructions

Java Web Start is installed with the SDK/JRE. For installation instructions, follow the standard installation instructions for the SDK/JRE you are installing.

Using Java Web Start Software

Java Web Start allows you to launch Java-technology-based applications directly from the Web. An application can be launched in three different ways:
  • From a Web browser by clicking on a link.
  • From Java Web Start's built-in Application Manager, which tracks recently used applications and provides quick access to your favorite applications.
  • From desktop icons or the Start Menu (Microsoft Windows only).
Regardless of which way is used, Java Web Start will connect back to the Web server each time an application is launched to check whether an updated version of the application is available.

Launching from a Web browser

On the Java Web Start demos page (http://java.sun.com/products/javawebstart/demos.html), there are links to a number of applications that can be launched with a single click of a mouse. Try launching the different applications by clicking on the Launch buttons. The Web browser will launch Java Web Start, which will then download, cache, and execute the given application. You will notice that the second time you launch an application, it starts much more quickly since it is already present locally and does not need to be downloaded again.

Most of the demos on the page are just downloaded and executed without any user intervention. These applications run in a restricted environment in which they are prevented from accessing the local disk and network, and can be guaranteed not to install any viruses on your computer.

Some demos require extra privileges, such as access to your local hard disk. For these applications, a security dialog will pop up with information about the origin of the application based on who digitally signed the code. The application will run only if you decide to trust the vendor.

That is really all there is to using Java Web Start, but how does it work? The HTML links that launch the applications are, in fact, standard HTML links. However, instead of pointing to another Web page, they link to a special configuration file called a JNLP file. The Web browser examines the file extension and/or the MIME type of the file, and sees that it belongs to Java Web Start. It then launches Java Web Start with the downloaded JNLP file as an argument. Java Web Start proceeds with downloading, caching, and running the application as directed by the JNLP file.

Launching from the built-in Application Manager

The Application Manager is a built-in part of the Java Web Start product. It lets you quickly and easily launch applications that have previously been launched by Java Web Start. It is a combination of a History menu and a Start/Programs menu for your Web deployed Java-technology-based applications. The Application Manager also allows you to see additional information about the applications, with links the applications' home pages.

You launch an application from the Application Manager by double clicking on the application icon or by clicking the launch button.

Another important feature of the Application Manager is the Preferences dialog which lets you examine and modify settings used by Java Web Start. For example, this includes tabs which allow you to:

  • Specify an HTTP Proxy (or tell Java Web Start to use the default browser settings).
  • Clear the cache of downloaded applications.
  • Specify the location of the different versions of Java runtime environments.
  • Select whether a Java console is to be displayed.
  • View the set of root security certificates.
The Application Manager is launched by either clicking on the Java Web Start icon on the desktop or in the Start Menu on Microsoft Windows. On the SolarisTM Operating Environment and Linux, it is launched by invoking the javaws command in the Java Web Start installation directory. The Application Manager can also be launched from a Web browser; see, for example, the demos page (http://java.sun.com/products/javawebstart/demos.html).

Launching from desktop icons and the Start Menu (Microsoft Windows only)

Java Web Start technology can automatically create shortcuts on the Microsoft Windows desktop and in the Start Menu for Web deployed Java-technology-based applications. By default, Java Web Start asks the second time an application is launched, if a shortcut should be created. This can be changed using the Preference panel.

Shortcuts can also be added and removed by using the Application Manager, using the Application/Create Shortcut, and using Application/Remove Shortcut menu item.

Using Java Web Start Software Behind a Proxy Server/Firewall

Java Web Start software must be configured with the correct proxy settings in order to launch applications from outside your firewall. Java Web Start software will automatically try to detect the proxy settings from the default browser on your system (Internet Explorer or NetscapeTM browsers on Microsoft Windows, and Netscape browsers on the Solaris Operating Environment and Linux). Java Web Start technology supports most web proxy auto-configuration scripts. It can detect proxy settings in almost all environments.

If the proxy setting cannot be automatically detected, then you will be prompted to specify the proxy settings the first time you use Java Web Start. Java Web Start will also prompt you for a user name and password required to access an authenticating proxy server. This user name and password will be stored for the current invocation of Java Web Start. However, at the time a newly invoked Java Virtual Machine, if accessing a secure web site, will prompt you for the user name and password since this information is stored within a Java Virtual Machine instance.

You can also use the Java Web Start Preferences panel to view or edit the proxy configuration. Launch the Application Manager, either by clicking on the icon on the desktop (Microsoft Windows), or type ./javaws in the Java Web Start installation directory (Solaris Operating Environment and Linux), and then select Edit/Preferences. If you are in an environment where access to the Web is through a proxy server, you are encouraged to use the Java Web Start Preferences panel to check that these are set-up correctly.

Release Notes

For a list of bug fixes, and changes and enhancements made for this release of Java Web Start, refer to Release Notes and Enhancements and Changes.
This product includes code from Nullsoft, Inc. Copyright © 2003, Sun Microsystems, Inc.
All rights reserved.


Java Web Start 1.4.2 Release Notes

Java

JavaTM Web Start 1.4.2 Release Notes

 Documentation Contents

These release notes include the following sections:

  • Enhancements
    • Improved JNLP URL Support In Application Manager
    • Dynamic Download of HTTPS Certificates
    • Automatic Detection of JREs
    • Combined Control Panel Infrastructure
    • Security Audit of Java Web Start
    • First-Time Prompt for Shortcut
    • Integration with InstallShield 7
  • Bug Fixes

Enhancements

Improved JNLP URL Support In Application Manager

JNLP URLs are now directly openable from the JAWS Application Manager and can be bookmarked. Moreover, they may be .html or .jnlp files. (This is RFE 4531885.)

Dynamic Download of HTTPS Certificates

Java Web Start now dynamically imports certificates in much the same way as browsers do, making use of https much easier for users. (This is RFE 4696477.) For more information, see Dynamic Download of HTTPS Certificates in the Java Web Start 1.4.2 Developer Guide.

Automatic Detection of JREs

Every time JAWS is run, it automatically detects all "registered" JREs on the computer.

There are two types of JREs recognized by JAWS: registered and unregistered. A registered JRE is one that is recorded in the system or package registry, i.e., the system registry on Windows, the package database on Solaris, and the RPM database on Linux. An unregistered JRE is not recorded in a registry; e.g., a JRE mounted on a network drive in an unregistered JRE. (This is RFE 4474876.)

Combined Control Panel Infrastructure

There is now a combined control panel infrastructure used for the Java deployment products, including Java Plug-in and Java Web Start. If you have taken advantage of knowing certain undocumented information, such as the Java Web Start cache location or the configuration file format and location, you could be affected. (This is RFE 4723794.)

Security Audit of Java Web Start

A security audit of Java Web Start has been completed. (This is RFE 4645808.)

First-Time Prompt for Shortcut

Users are now asked if they want a desktop shorcut the first time an application is downloaded and cached. (This is RFE 4737538.)

Integration with InstallShield 7

Java Web Start is now installed via InstallShield 7 as part of the JRE. There is no longer a separate installer for Java Web Start. (This is RFE 4718282.)

Bug Fixes

Bug ID | Synopsis
4791532 | Dialogs are layed out wrong in javawebstart
4778185 | JNLPClassLoader can still return unencoded URL
4780676 | Java Web Start sometimes fails to launch applications while offline
4757170 | Typo in Jaws Pop-up window <Rename HTML Entry> "You must enter and entry name"
4777238 | Cache Location JTextField should handle enter properly
4685501 | De - Word "Console" is not translated in the titlebar of jaws Console dialog
4688776 | JaWS, JAWS 1.2 b08, Translation errors
4785128 | Exception coming if you use mantis-beta jaws with jre1.2.2 on Windows
4772298 | Proxy authentication dialog pops up twice even if username/password is correct
4772381 | System.exit not working with shutdownhook and JWS console
4784292 | Java Web Start should use cached jnlp file if possible to improve startup time
4782008 | Review webstart ActiveX control
4782000 | Need to update webstart autoinstall version tags
4785581 | JAWS on linux cannot be invoked via symbolic link
4789162 | JAWS on solaris/sparc cannot be invoked via symbolic link
4792033 | Need javaws link in /usr/bin on Solaris
4792949 | autoupdate of javaws file is not getting staged in RE area
4791695 | Help Menu Item, "Check For Update" doesn't notify of the latest 1.2 JWS version
4735750 | Fix Certificate-chain Validation
4711515 | Wrong AppContext used in RMI threads
4757168 | Jaws application not properly cached if PATH to the application contains letter N
4759001 | Exception coming (getText()),when trying to Clear Folder with the Downloaded vie
4759005 | Exception coming (synchron),when trying to Clear Folder with the Downloaded vie
4665132 | Webstart not returning ContextClassLoader consistently under jre 1.4.0
4696315 | Splash screen is not showing with large image
4699299 | Splash Screen is wierd on Linux machine
4734410 | JAVAWS is passing the property set in extension installer to main program
4739089 | Java Web Wtart does not handle signed jars correctly
4743169 | Root Certificates panel in Java WS app mgr is blank if cacerts is missing
4754648 | Advanced Preference Panel miss a key shortcut
4754763 | getResourceAsStream() fails with JNLPClassLoader
4772558 | Implement new Icons from UE group.
4772559 | Reduce access scope (phase II)
4772563 | New default splash screen, and modified customized ones
4772926 | Extra ; char on the window title
4773110 | Apps are run with the wrong JRE
4775373 | Problem checking for updates on https codebase
4379831 | Please launch new VM for -Dsun.java2d.noddraw=true
4474875 | Incremental updates fail if going from basic proto to version based.
4485537 | 'Read -1 of 2k (0%)' message still displayed in DL window
4653074 | JWS: Update Shortcuts and programs folder when app name changed in jnlp file.
4666303 | Cannot delete java.sun.com cache directory structure in Application Manager
4687256 | Jaws App_mgr did not prompt shortcut options on the second launch with j2re1.2.2
4688193 | Reduce access scope
4691541 | JWS should handle the version control of splash screen icons
4708051 | Exception coming when you try to "Clear Folder" with View/Download_App enabled
4718813 | Application Manager lost focus after first startup
4729230 | Loging to "TEMP" file does not work
4761563 | Can't set property to "" in jnlp file
4625826 | Unexpected exit when lazy-loading unsigned jar file
4775823 | Unnecessary . (dot) in Appman Shortcuts tab after "When to Create" instruction.
4685497 | De - Overlapping text in the certificates tab
4723717 | JRE1.4.0_x - JaWS component cannot be installed in non-default location.
4777764 | Cancelling import certificate will cause ca chain completely broken
4694453 | Customize splash screen would not work if no href
4720897 | Jar Diff'ing does not work if jars are packaged in a war file.
4724977 | The application panel size it too small to show the string.
4726525 | Certificate detail panel should have focus on OK button
4751780 | JWS Hanging on Jar update (Scanning entries at 100% for a LONG time)
4759104 | Clear cache function could not remove certificate
4759298 | "details" button not showing on app_mgr root certicates tab
4480656 | View Source in IE won't work after creating shortcut for Notepad Demo
4498419 | WebStart won't start if the default browser is deinstalled
4623207 | jaxp.jar
4626733 | Multi-platform support
4653036 | JarDiffHandler() should use javax.servlet.context.
4654173 | JWS litters $WINUSERHOME\Local Settings\Temp and d:\TMP
4667701 | JWS should give the name of the resource that fails
4668473 | Cannot create shortcut if title is too long
4676386 | Better user-agent value in http request header
4685505 | De - Broken border around " Choose Log File Name"
4687857 | Focus is back to wrong window after closing dialog
4699771 | JWS login prompt for secure resources is not robust.
4744945 | JWS 1.2 application cannot delete after upgrade
4775777 | "Invalid Cache Location" window incorrect behavior
4492987 | Java Web Start Installation documentation for Linux
4768914 | Javaws unsigned extension installer can call setJREInfo
4773602 | Auto proxy detection is failing when using Netscape 4.79 and 7.0
4777392 | Mantis b06:file type description for jnlp is not set to NS/IE on Win98 ja
4665251 | Preferences: Shortcut Options: When To Create := "Always" fails (always:)
4692415 | Jaws application freezing if you launching it as a root, through browser on Sol
4723790 | Web start install should use pack instead of crunch
4739415 | Jaws j2re1.4.0 installer problem
4772158 | Make web start part of J2RE image on Unix platform
4776098 | Javaws JRE autodownload not working
4431364 | JRE should always be installed
4459559 | J2SE Installer can't finish the work if Installed
4463745 | WebStart can't handle Netscape automatic proxy configuration
4469455 | Proxy autoconfig script parsing has problems
4514686 | Installer can't handle adding >100th mime type to Netscape on Windows
4615288 | Build fails under Windows due to install directory not existing
4653566 | JWS is not compatible with the centralization of home directories under NT
4685474 | Message on Japanese Installer/Uninstaller does not fall within a view area
4730185 | javaws.cfg file in $USERPROFILE is not uninstalled
4763779 | Need to check javaws bootdir during control build
4764601 | Unsigned extension installer throws exception when Main.systemExit is called
4765164 | Singleton api service classes can be re-initialized
4765165 | com.sun.jnlp package needs to be protected from package addition
4775492 | Javaws app with no href in JNLP causing nonfatal exception on netscape/unix
4768903 | Javaws dev target doesn't work during dev build
4741507 | Missing signed entry JNLPException is not explicit

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please submit comments at our feedback form. 		Sun
Java Software


Java Web Start 1.4.2 Developer Guide

Note: There are two ways to navigate this guide:

  • Search the guide
  • Select from the contents below:

Overview

Java Web Start Technology
Where to Find Java Web Start Technology
Desktop and Server Requirements

Setting up the Web Site

Introduction
 Basic Steps

Creating the Web Page That Launches the Application

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

Application Development Considerations

Introduction
Retrieving Resources from JAR files
 Security and Code Signing
 Signing JAR Files with a Test Certificate
 How to Encode JNLP Files
 Dynamic Download of HTTPS Certificates

Packaging an Application for Easy Deployment

JNLP File Syntax

Introduction
 The jnlp Element
The security Element
The resources Element
The application-desc Element
The applet-desc Element

JNLP API Examples

Introduction
 Using a BasicService Service
Using a ClipboardService Service
Using a DownloadService Service
Using a FileOpenService Service
Using a FileSaveService Service
Using a PrintService Service
Using a PersistenceService Service
Using FileContents
Using a JNLPRandomAccessFile

Appendices:

Converting JNLP Files to Work With This Release
FAQ
JNLP API (JavaDoc)


Converting JNLP Files to Work With This Release

The JNLP file format has not changed between the 1.0 and this release.

If your JNLP file is compatible with a version of Java Web Start that is lower than 1.0, please note that the JNLP file format has changed significantly. Below is a list of the most common modifications that needs to be applied to a 0.4 JNLP file to make it compatible with Java Web Start 1.0 or higher:

  • Set spec attribute to 1.0.
  • Rename the unrestricted element to all-permissions.
  • Rename the jre element to j2se and move this element inside the resources element (i.e., make j2se a subelement of resources).

Converting JNLP files used with the 1.0-beta or 1.0-rc release only requires updating the spec attribute to "1.0".


Application Development Considerations

This chapter includes the following topics:

  • Introduction
  • Retrieving Resources from JAR files
  • 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 2 platform. 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 2 platform (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.
  • 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

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 2 Platform. 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 2 SE SDK. The documentation for the jarsigner tool provides examples of how to sign code and create test certificates, and it discusses other issues related to signing.

Java Web Start also supports use of the Netscape signtool used with SDK/JRE 1.4.2. See the Netscape Web site for details: http://developer.netscape.com/software/signedobj/

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 J2SE platform. (See the J2SE 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.


JNLP API Examples

This chapter includes the following topics:

  • Introduction
  • Using a BasicService Service
  • Using a ClipboardService Service
  • Using a DownloadService Service
  • Using a FileOpenService Service
  • Using a FileSaveService Service
  • Using a PrintService Service
  • Using a PersistenceService Service
  • Using FileContents
  • Using a JNLPRandomAccessFile

Introduction

The JNLP API is designed to provide additional information to the application that would otherwise not be available using the standard Java 2 SE API. The following code examples show how the following services can be used: BasicService, ClipboardService, DownloadService, FileOpenService, FileSaveService, PrintService, and PersistenceService.

The public classes and interfaces in the JNLP API are included in the jnlp.jar file. This JAR file must be included in the classpath when compiling source files that use the JNLP API. For example on Windows:

javac -classpath .;jnlp.jar *.java

The jnlp.jar file is included in the JNLP Developers Pack.

Using a BasicService Service

The javax.jnlp.BasicService service provides a set of methods for querying and interacting with the environment similar to what the AppletContext provides for a Java Applet.

The showURL method uses the JNLP API to direct the default browser on the platform to show the given URL. The method returns true if the request succeeds, otherwise false.

import javax.jnlp.*;
   ...

   // Method to show a URL
boolean showURL(URL url) {
try {
// Lookup the javax.jnlp.BasicService object
BasicService
  bs = (BasicService)ServiceManager.lookup("javax.jnlp.BasicService");
// Invoke the showDocument method
return bs.showDocument(url);
} catch(UnavailableServiceException
  ue) {
// Service is not supported
return false;
}
}

Using a ClipboardService Service

The javax.jnlp.ClipboardService service provides methods for accessing the shared system-wide clipboard, even for applications that are running in the restricted execution environment.

Java Web Start will warn the user of the potential security risk of letting an untrusted application access potentially confidential information stored in the clipboard, or overwriting contents stored in the clipboard.

import javax.jnlp;
    ...

    private ClipboardService cs;

    try {
        cs = (ClipboardService)ServiceManager.lookup
                 ("javax.jnlp.ClipboardService");
    } catch (UnavailableServiceException e) {
        cs = null;
    }

    if (cs != null) {
// set
  the system clipboard contents to a string selection
StringSelection ss = new StringSelection("Java
  Web Start!");
cs.setContents(ss);
// get
  the contents of the system clipboard and print them
Transferable tr = cs.getContents();
if (tr.isDataFlavorSupported(DataFlavor.stringFlavor))
  {
try
  {
String s = (String)tr.getTransferData(DataFlavor.stringFlavor);
System.out.println("Clipboard contents: " + s);
} catch
  (Exception e) {
e.printStackTrace();
}
}
}

Using a DownloadService Service

The javax.jnlp.DownloadService service allows an application to control how its own resources are cached.

The service allows an application to determine which of its resources are cached, to force resources to be cached, and to remove resources from the cache.

import javax.jnlp.*;
    ...

    DownloadService ds;

    try {
        ds = (DownloadService)ServiceManager.lookup("javax.jnlp.DownloadService");
    } catch (UnavailableServiceException e) {
        ds = null;
    }

    if (ds != null) {

        try {
            // determine if a particular resource is cached
            URL url =
                    new URL("http://java.sun.com/products/javawebstart/lib/draw.jar");
            boolean cached = ds.isResourceCached(url, "1.0");
            // remove the resource from the cache
            if (cached) {
                ds.removeResource(url, "1.0");
            }
            // reload the resource into the cache
            DownloadServiceListener dsl = ds.getDefaultProgressWindow();
            ds.loadResource(url, "1.0", dsl);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Using a FileOpenService Service

The javax.jnlp.FileOpenService service provides methods for importing files from the local disk, even for applications that are running in the restricted execution environment.

This interface is designed to provide the same kind of of disk access to potentially untrusted Web-deployed applications that a Web developer has when using HTML. HTML forms support the inclusion of files by displaying a file open dialog.

import javax.jnlp.*;
    ...

    FileOpenService fos;

    try {
        fos = (FileOpenService)ServiceManager.lookup("javax.jnlp.FileOpenService");
    } catch (UnavailableServiceException e) {
        fos = null;
    }

    if (fos != null) {
        try {
            // ask user to select a file through this service
            FileContents fc = fos.openFileDialog(null, null);
            // ask user to select multiple files through this service
            FileContents[] fcs = fos.openMultiFileDialog(null, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Using a FileSaveService Service

The javax.jnlp.FileSaveService service provides methods for exporting files to the local disk, even for applications that are running in the restricted execution environment.

This interface is designed to provide the same level of disk access to potentially untrusted Web-deployed applications that a Web browser provides for contents that it is displaying. Most browsers provide a Save As... dialog as part of their user interface.

import javax.jnlp.*;
    ...

    FileSaveService fss;
    FileOpenService fos;

    try {
        fos = (FileOpenService)ServiceManager.lookup("javax.jnlp.FileOpenService");
        fss = (FileSaveService)ServiceManager.lookup
                                   ("javax.jnlp.FileSaveService");
    } catch (UnavailableServiceException e) {
        fss = null;
        fos = null;
    }

    if (fss != null && fos != null) {
        try {
            // get a file with FileOpenService
            FileContents fc = fos.openFileDialog(null, null);
            // one way to save a file
            FileContents newfc = fss.saveFileDialog(null, null,
            fc.getInputStream(), "newFileName.txt");
            // another way to save a file
            FileContents newfc2 = fss.saveAsFileDialog(null, null, fc);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Also see Using FileContents.

Using a PrintService Service

The javax.jnlp.PrintService service provides methods for access to printing, even for applications that are running in the restricted execution environment.

Using this service, an application can submit a print job. Java Web Start will then show this request to the user and, if accepted, queue the request to the printer.

import javax.jnlp.*;
    ...

    PrintService ps;

    try {
        ps = (PrintService)ServiceManager.lookup("javax.jnlp.PrintService");
    } catch (UnavailableServiceException e) {
        ps = null;
    }

    if (ps != null) {
        try {

            // get the default PageFormat
            PageFormat pf = ps.getDefaultPage();

            // ask the user to customize the PageFormat
            PageFormat newPf = ps.showPageFormatDialog(pf);

            // print the document with the PageFormat above
            ps.print(new DocToPrint());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // Code to construct the Printable Document
    class DocToPrint implements Printable {
        public int print(Graphics g, PageFormat pageformat, int PageIndex){
            // code to generate what you want to print
        }
    }

Using a PersistenceService Service

The javax.jnlp.PersistenceService service provides methods for storing data locally on the client system, even for applications that are running in the restricted execution environment.

The service is designed to be somewhat similar to that which the cookie mechanism provides to HTML-based applications. Cookies allow a small amount of data to be stored locally on the client system. That data can be securely managed by the browser and can only be retrieved by HTML pages which originate from the same URL as the page that stored the data.

import javax.jnlp.*;
    ...

    PersistenceService ps;
    BasicService bs;

    try {
        ps = (PersistenceService)ServiceManager.lookup("javax.jnlp.PersistenceService");
        bs = (BasicService)ServiceManager.lookup("javax.jnlp.BasicService");
    } catch (UnavailableServiceException e) {
        ps = null;
        bs = null;
    }

    if (ps != null && bs != null) {

        try {
            // find all the muffins for our URL
            URL codebase = bs.getCodeBase();
            String [] muffins = ps.getNames(url);

            // get the attributes (tags) for each of these muffins.
            // update the server's copy of the data if any muffins
            // are dirty
            int [] tags = new int[muffins.length];
            URL [] muffinURLs = new URL[muffins.length];
            for (int i = 0; i < muffins.length; i++) {
                muffinURLs[i] = new URL(codebase.toString() + muffins[i]);
                tags[i] = ps.getTag(muffinURLs[i]);
                // update the server if anything is tagged DIRTY
                if (tags[i] == PersistenceService.DIRTY) {
                    doUpdateServer(muffinURLs[i]);
                }
            }

            // read in the contents of a muffin and then delete it
            FileContents fc = ps.get(muffinURLs[0]);
            long maxsize = fc.getMaxLength();
            byte [] buf = new byte[fc.getLength()];
            InputStream is = fc.getInputStream();
            long pos = 0;
            while((pos = is.read(buf, pos, buf.length - pos)) > 0) {
                // just loop
            }
            is.close();

            ps.delete(muffinURLs[0]);

            // re-create the muffin and repopulate its data
            ps.create(muffinURLs[0], maxsize);
            fc = ps.get(muffinURLs[0]);
            // don't append
            OutputStream os = fc.getOutputStream(false);
            os.write(buf);
            os.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

   void doUpdateServer(URL url) {
        // update the server's copy of the persistent data
        // represented by the given URL
        ...
        ps.setTag(url, PersistenceService.CACHED);
   }

Using FileContents

javax.jnlp.FileContents objects encapsulate the name and contents of a file. An object of this class is used by the FileOpenService, FileSaveService and PersistenceService. Here is an example of how an instance of a FileContents can be used to read from and write to a file:

import javax.jnlp.*;
    ...

    FileOpenService fos;

    //Initialize fos (see Using a FileOpenService Service example)
    ...

    if (fos != null) {

        try {

            // get a FileContents object to work with from the
            // FileOpenService
            FileContents fc = fos.openFileDialog(null, null);

            // get the InputStream from the file and read a few bytes
            byte [] buf = new byte[fc.getLength()];
            InputStream is = fc.getInputStream();
            int pos = 0;
            while ((pos = is.read(buf, pos, buf.length - pos)) > 0) {
                // just loop
            }
            is.close();

            // get the OutputStream and write the file back out
            if (fc.canWrite()) {
               // don't append
               OutputStream os = fc.getOutputStream(false);
               os.write(buf);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Using a JNLPRandomAccessFile

Instances of javax.jnlp.JNLPRandomAccessFile 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. Here is an example of how an instance of a JNLPRandomAccessFile can be used to write to a random access file:

import javax.jnlp.*;
    ...

    FileOpenService fos;

    //Initialize fos (see Using a FileOpenService Service example)
    ...

    if (fos != null) {
        try {
           // ask the user to choose a file to open
           FileContents fc = fos.openFileDialog(null, null);

           // attempt to increase the maximum file length
           long grantedLength = fc.getLength();
           if (grantedLength + 1024 > fc.getMaxLength()) {
               // attempt to increase the maximum file size defined by
               // the client
               grantedLength = fc.setMaxLength(grantedLength + 1024);
           }

           // if we were able to increase the maximum allowable file size,
           // get a JNLPRandomAccessFile representation of the file, and
           // write to it
           if (fc.getMaxSize() > fc.getLength() && fc.canWrite()) {
               JNLPRandomAccessFile raf = fc.getRandomAccessFile("rw");
               raf.seek(raf.length() - 1);
               raf.writeUTF("Java Web Start!");
               raf.close();
           }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


Creating the Web Page That Lauches the Application

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

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.yyy.zzz, the page needs to include the following link:

<a href=http://www.yyy.zzz/app.jnlp>Launch the application</a>

It may be the case, however, that JAWS 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 (JAWS) 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 SDK/JRE.

The scripts, and the HTML for the auto-install page, are discussed below.

Detecting if JAWS 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 javaws12Installed = 0;
var javaws142Installed=0;
isIE = "false";
if (navigator.mimeTypes && navigator.mimeTypes.length) {
   x = navigator.mimeTypes['application/x-java-jnlp-file'];
   if (x) {
      javawsInstalled = 1;
      javaws12Installed=1;
      javaws142Installed=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, javaws12Installed, and javaws142Installed are all set to 1. With Netscape it is not possible to determine which particular version of JAWS is installed, so all three 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.2"))) Then
     javaws12Installed = 0
  Else
     javaws12Installed = 1
  End If
  If Not(IsObject(CreateObject("JavaWebStart.isInstalled.1.4.2.0"))) Then
     javaws142Installed = 0
  Else
     javaws142Installed = 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 two things:

  • whether the client machine has any version of JAWS installed;
  • whether the client machine has version 1.2 of JAWS installed;
  • whether the client machine has versions 1.4.2 of JAWS installed.

After the above two scripts have been executed, the variables javawsInstalled, javaws12Installed, and javaws142Installed will be set to either 1 or 0, as follows:

Browser
javawsInstalled javaws12Installed javaws142Installed
Internet Explorer | 1 if any version of JAWS is installed; 0 otherwise. | 1 if JAWS 1.2 is installed; 0 otherwise. | 1 if JAWS 1.4.2 is installed; 0 otherwise.
Netscape Navigator | 1 if any version of JAWS is installed; 0 otherwise. | 1 if any version of JAWS is installed; 0 otherwise. | 1 if any version of JAWS is installed; 0 otherwise.

Launching the application if JAWS 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., JAWS is installed);
  • initiate auto-download of JRE 1.4.2, which includes JAWS (i.e., JAWS is not installed and the user is running IE on Windows);
  • or provide a link to the general download page for the 1.4.2 SDK/JRE (i.e., JAWS 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.yyy.zzz/app.jnlp>Launch
        the application</a>");
} else {
    document.write("Click ");
    document.write("<a href=http://java.sun.com/PluginBrowserCheck?
        pass=http://www.yyy.zzz/download.html&
        fail=http://java.sun.com/j2se/1.4.2/download.html>here</a> ");
    document.write("to download and install JRE 1.4.2 and
        the application.");
}
</SCRIPT>

Notes:

  1. The script only uses javawsInstalled, not javaws12Installed or javaws142Installed.
  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 JAWS is already available on the client, then the script provides a link to the application's jnlp file. If JAWS 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.yyy.zzz/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 1.4.2 JRE general download page on java.sun.com.

Creating an auto-install page

Note:

For a complete list of JRE releases that can be autodownloaded via a .cab file, as mentioned below, see Autodownload Files (Windows Only).

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 J2RE 1.4.2. Along with JAWS, an ActiveX control will be downloaded to the client. The ActiveX control will launch the application using the newly installed JAWS. Here is a sample download.html file:

<HTML>
<BODY>
<OBJECT CODEBASE="http://java.sun.com/products/plugin/autodl/jinstall-1_4_2-windows-i586.cab"
CLASSID="clsid:5852F5ED-8BF4-11D4-A245-0080C6F74284" HEIGHT=0 WIDTH=0>
<PARAM NAME="app" VALUE="http://www.yyy.zzz/app.jnlp">
<PARAM NAME="back" VALUE="true">
<!-- Alternate HTML for browsers which cannot instantiate the object -->
<A HREF="http://java.sun.com/j2se/1.4.2/download.html">
Download Java Web Start</A>
</OBJECT>
</BODY>
</HTML>

This OBJECT tag fetches a .cab file that contains an auto-installer for JRE 1.4.2. (Note that this .cab file will not be available until the GA release of the 1.4.2 SDK/JRE.) 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.


Overview

Java Web Start Technology

Java Web Start is a helper application that gets associated with a Web browser. When a user clicks on a link that points to a special launch file (JNLP file), it causes the browser to launch Java Web Start, which then automatically downloads, caches, and runs the given Java Technology-based application. The entire process is typically completed without requiring any user interaction, except for the initial single click.

JNLP URLs are also directly openable from the JAWS Application Manager and can be bookmarked. Moreover, they may be .html or .jnlp files.

From a technology standpoint, Java Web Start has a number of key benefits that make it an attractive platform to use for deploying applications:

  • Java Web Start is built exclusively to launch applications written to the Java 2 SE platform. Thus, a single application can be made available on a Web server and then deployed on a wide variety of platforms, including Windows 98/NT/2000/ME/XP, Linux, and the SolarisTM Operating Environment. The Java platform has proven to be a very robust, productive, and expressive development platform, leading to a significant cost savings due to minimized development and testing costs.
  • Java Web Start supports multiple revisions of the Java 2 platform, Standard Edition. Thus, an application can request a particular version of the platform it requires, such as J2SETM 1.4.0. Several applications can run at the same time on different platform revisions without causing conflicts, and Java Web Start can automatically download and install a revision of the platform if an application requests a version that is not installed on the client system.
  • Java Web Start allows applications to be launched independently of a Web browser. This can be used for off-line operation of an application, where launching through the browser is often inconvenient or impossible. The application can also be launched through desktop shortcuts, making launching the Web-deployed application similar to launching a native application.
  • Java Web Start takes advantage of the inherent security of the Java Platform. Applications are by default run in a protective environment (sandbox) with restricted access to local disk and network resources. It allows the user to safely run applications from sources that are not trusted.
  • Applications launched with Java Web Start are cached locally. Thus, an already-downloaded application is launched on par with a traditionally installed application.

The technology underlying Java Web Start is the Java TM Network Launching Protocol & API (JNLP). This technology is currently under development via the Java Community Process (JCP). Java Web Start is the reference implementation (RI) for the JNLP specification. The JNLP technology defines, among other things, a standard file format that describes how to launch an application called a JNLP file.

Where to find Java Web Start

See the Java Web Start web site, http://java.sun.com/products/javawebstart/, for availability of Java Web Start downloads. The JNLP specification can be found at http://java.sun.com/aboutJava/communityprocess/final-draft/jsr056.

Requirements

Desktop/Client requirements:

The client machine requires support for the Java Runtime Environment (JRE), version 1.2.2 or later. Java Web Start is available for Windows 98/NT/2000/ME/XP, the Solaris Operating Environment, and Linux.

See the README document for details.

Server requirements:

Applications can be deployed from any standard Web server. In order to use Java Web Start, the Web server must be configured with support for a new MIME type as explained below.


Packaging an Application for Easy Deployment

The Developer's Pack contains a servlet that can be used to bundle a JNLP-deployed application in a Web Archive (WAR) file. See Packaging JNLP Applications in a Web Archive


Setting Up the Web Site

Introduction

Java Web Start leverages existing Internet technology, such as the HTTP protocol and Web servers, so existing infrastructure for deploying HTML-based contents can be reused to deploy Java Technology-based applications using Java Web Start.

In order to deploy your application to client machines, you must make sure that all files containing your application are accessible through a Web server. This typically amounts to copying one or more JAR files, along with a JNLP file, into the Web server's directories. The set-up required for enabling the Web site to support Java Web Start is very similar to deploying HTML-based contents. The only caveat is that a new MIME type needs to be configured for the Web server.

Basic Steps

1. Configure the Web server to use the Java Web Start MIME type

Configure the Web server so that all files with the .jnlp file extension are set to the application/x-java-jnlp-file MIME type.

Most Web browsers use the MIME type returned with the contents from the Web server to determine how to handle the particular content. The server must return application/x-java-jnlp-file MIME type for JNLP files in order for Java Web Start to be invoked.

Each Web server has a specific way in which to add MIME types. For example, for the Apache Web server you must add the following line to the .mime.types configuration file:

application/x-java-jnlp-file JNLP

Check the documentation for the specifics of your Web server.

2. Create a JNLP file for the application

The easiest way to create this file is to modify an existing JNLP file to your requirements.

The syntax and format for the JNLP file is described in a later section.

3. Make the application accessible on the Web server

Ensure your application's JAR files and the JNLP file are accessible at the URLs listed in the JNLP file.

4. Create the web page that launches the application

See the next chapter, Creating the Web Page that launches the Application, for details on step 4.


JNLP File Syntax

This chapter covers the following topics:

  • Introduction
  • Example
  • JNLP Elements
    • jnlp Element
    • information Element
    • security Element
    • resources Element
    • application-desc Element
    • applet-desc Element

Introduction

The format used in this release is that specified in the Java Network Launching Protocol and API (JNLP) Specification v1.0.1. This document describes the most commonly used elements of a JNLP file. For a complete description of the format, refer to the specification.

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="1.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/>
  </information>
  <security>
      <all-permissions/>
  </security>
  <resources>
    <j2se version="1.4.2"/>
    <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.

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. Java Web Start requires this attribute to be set in order for the application to be included in the Application Manager.

information Element

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 Application Manager 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 Application Manager;
  • in desktop shortcuts.

A 64x64 icon is shown during download; in the Application Manager 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 a kind="splash" attribute, but does contain another icon tag, Java Web Start will display a splash screen consisting of the image specified by the icon element on the left and the application's title and vendor on the right.

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.

A splash image will be surrounded by a border defined by Java Web Start.

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.

Applications not marked offline in the JNLP file will not be launched by the Application Manager. By default Application Manager only launches an application if the client system is online.

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 reasonable fast server connection, the lastest version of the application will usually be run, but it is not guaranteed. The application, however, can be run offline.

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.

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 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 and API (JNLP) Specification v1.0.1 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"/>
    </resource>

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 or lazily. For example:

    <jar href="sound.jar" download="lazy"/>
<nativelib href="native-sound.jar"
    download="eager"/>

The j2se element specifies what Java 2 SE Runtime Environment (JRE) versions an application is supported on, as well as standard parameters to the Java Virtual Machine. If several JREs can 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"/>
<j2se version="1.4+"/>

The version attribute refers, by default, to a platform (specification) version of the Java 2 platform. Currently defined platform version are 1.2, 1.3, and 1.4. (A platform version may optionally contain a micro version number; e.g., 1.4.2.)

Exact product versions (implementation versions) may also be specified—e.g., 1.3.1_01 or 1.4.2-beta by Sun Microsystems, Inc.—by including the href attribute. E.g.,

<j2se version="1.3.1_01" href="http://java.sun.com/products/autodl/j2se"/

or

<j2se version="1.4.2-beta" 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 property element defines a system property that will be available through the System.getProperty and System.getProperties methods. It has two required attributes: name and value. For example:

<property name="key" value="overwritten"/>

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>

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.

Note: Applets must be packaged in JAR files in order to work with Java Web Start.


Deva Search - Help Page

Enter multiple terms with a space between them. The search engine searches for any instance of each term in the list.

Search terms are not case sensitive. You can enter terms in any combination of upper and lower case.

Terms may include any of the following characters: A-Z a-z 0-9 _ - . ' , $ %.

Place a plus sign (+) in front of each word that must appear in the results. For example, if you enter +printer +cartridge +maintenance, the search engine will find all pages that have all three words in them. Note that the three words may not necessarily be adjacent to each other, but they will be in the same page.

Place a minus sign (-) in front of words that you do not want to appear in the results. For example, if you enter +printer +cartridge -maintenance, the search engine will find all pages that have the words "printer" and "cartridge" but not "maintenance."

Common words (a, an, the, etc.) are excluded from the search index.


Deva Search

This page is designed to be viewed by a browser which supports frames.


Deva Search

Java Web Start Search Page
Tips


 All Classes
BasicService
ClipboardService
DownloadService
DownloadServiceListener
ExtensionInstallerService
FileContents
FileOpenService
FileSaveService
JNLPRandomAccessFile
PersistenceService
PrintService
ServiceManager
ServiceManagerStub
UnavailableServiceException


JNLP API Reference 1.0

Frame Alert

This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client.
Link to Non-frame version.


JNLP API Reference 1.0: Index

Package Class Tree Index
PREV NEXT FRAMES NO FRAMES
B C D E F G H I J L O P R S T U V W

B

BasicService - interface javax.jnlp.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.

C

CACHED - Static variable in interface javax.jnlp.PersistenceService
canRead() - Method in interface javax.jnlp.FileContents
Returns whether the file can be read.
canWrite() - Method in interface javax.jnlp.FileContents
Returns whether the file can be written to.
ClipboardService - interface javax.jnlp.ClipboardService.
ClipboardService provides methods for accessing the shared system-wide clipboard, even for applications that are running in the untrusted execution environment.
close() - Method in interface javax.jnlp.JNLPRandomAccessFile
Closes this random access file stream and releases any system resources associated with the stream.
create(URL, long) - Method in interface javax.jnlp.PersistenceService
Creates a new persistent storage entry on the client side named with the given URL.

D

delete(URL) - Method in interface javax.jnlp.PersistenceService
Removes the stream associated with the given URL from the client-side date persistence store.
DIRTY - Static variable in interface javax.jnlp.PersistenceService
downloadFailed(URL, String) - Method in interface javax.jnlp.DownloadServiceListener
A JNLP client's DownloadService implementation should call this method if a download fails or aborts unexpectedly.
DownloadService - interface javax.jnlp.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.
DownloadServiceListener - interface javax.jnlp.DownloadServiceListener.
The DownloadServiceListener provides an interface for a callback object implementation, which may be used by a DownloadService implementation.

E

ExtensionInstallerService - interface javax.jnlp.ExtensionInstallerService.
The ExtensionInstallerService is used by an extension installer to communicate with the JNLP Client.

F

FileContents - interface javax.jnlp.FileContents.
FileContents objects encapsulate the name and contents of a file.
FileOpenService - interface javax.jnlp.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.
FileSaveService - interface javax.jnlp.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.

G

get(URL) - Method in interface javax.jnlp.PersistenceService
Returns a FileContents object representing the contents of this file.
getCodeBase() - Method in interface javax.jnlp.BasicService
Returns the codebase for the application.
getContents() - Method in interface javax.jnlp.ClipboardService
Returns a Transferable object representing the current contents of the clipboard.
getDefaultPage() - Method in interface javax.jnlp.PrintService
Creates a new PageFormat instance and sets it to the default size and orientation.
getDefaultProgressWindow() - Method in interface javax.jnlp.DownloadService
Return a default DownloadServiceListener implementation which, when passed to a load method, should pop up and update a progress window as the load progresses.
getExtensionLocation() - Method in interface javax.jnlp.ExtensionInstallerService
Returns the location of the extension being installed
getExtensionVersion() - Method in interface javax.jnlp.ExtensionInstallerService
Returns the version of the extension being installed
getFilePointer() - Method in interface javax.jnlp.JNLPRandomAccessFile
Returns the current offset in this file.
getInputStream() - Method in interface javax.jnlp.FileContents
Gets an InputStream from the file.
getInstalledJRE(URL, String) - Method in interface javax.jnlp.ExtensionInstallerService
Returns the path to the executable for the given JRE.
getInstallPath() - Method in interface javax.jnlp.ExtensionInstallerService
Returns the directory where the installer is recommended to install the extension in.
getLength() - Method in interface javax.jnlp.FileContents
Gets the length of the file.
getMaxLength() - Method in interface javax.jnlp.FileContents
Gets the maximum file length for the file, as set by the creator of this object.
getName() - Method in interface javax.jnlp.FileContents
Gets the file name as a String.
getNames(URL) - Method in interface javax.jnlp.PersistenceService
Returns an array of Strings containing the names of all the entries for a given URL.
getOutputStream(boolean) - Method in interface javax.jnlp.FileContents
Gets an OutputStream to the file.
getRandomAccessFile(String) - Method in interface javax.jnlp.FileContents
Returns a JNLPRandomAccessFile representing a random access interface to the file's contents.
getServiceNames() - Method in interface javax.jnlp.ServiceManagerStub
See description for ServiceManager.getServiceNames()
getServiceNames() - Static method in class javax.jnlp.ServiceManager
Returns the names of all services implemented by the JNLP Client.
getTag(URL) - Method in interface javax.jnlp.PersistenceService
Returns an int corresponding to the current value of the tag for the persistent data store entry associated with the given URL.

H

hideProgressBar() - Method in interface javax.jnlp.ExtensionInstallerService
Hides the progress bar.
hideStatusWindow() - Method in interface javax.jnlp.ExtensionInstallerService
Hides the status window.

I

installFailed() - Method in interface javax.jnlp.ExtensionInstallerService
This should be invoked if the install fails.
installSucceeded(boolean) - Method in interface javax.jnlp.ExtensionInstallerService
Installers should invoke this upon a succesful installation of the extension.
isExtensionPartCached(URL, String, String) - Method in interface javax.jnlp.DownloadService
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.
isExtensionPartCached(URL, String, String[]) - Method in interface javax.jnlp.DownloadService
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.
isOffline() - Method in interface javax.jnlp.BasicService
Determines if the system is offline.
isPartCached(String) - Method in interface javax.jnlp.DownloadService
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.
isPartCached(String[]) - Method in interface javax.jnlp.DownloadService
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.
isResourceCached(URL, String) - Method in interface javax.jnlp.DownloadService
Returns true if the resource referred to by the given URL and version is cached, and that resource is mentioned in the JNLP file for the application.
isWebBrowserSupported() - Method in interface javax.jnlp.BasicService
Checks if a Web browser is supported on the current platform and by the given JNLP Client.

J

javax.jnlp - package javax.jnlp
JNLPRandomAccessFile - interface javax.jnlp.JNLPRandomAccessFile.
Instances of this class support both reading and writing to a random access file.

L

length() - Method in interface javax.jnlp.JNLPRandomAccessFile
Returns the length of this file.
loadExtensionPart(URL, String, String[], DownloadServiceListener) - Method in interface javax.jnlp.DownloadService
Downloads the given parts of the given extension, if the parts and the extension are mentioned in the JNLP file for the application.
loadExtensionPart(URL, String, String, DownloadServiceListener) - Method in interface javax.jnlp.DownloadService
Downloads the given part of the given extension, if the part and the extension are mentioned in the JNLP file for the application.
loadPart(String[], DownloadServiceListener) - Method in interface javax.jnlp.DownloadService
Downloads the given parts, if the parts are mentioned in the JNLP file for the application.
loadPart(String, DownloadServiceListener) - Method in interface javax.jnlp.DownloadService
Downloads the given part, if the part is mentioned in the JNLP file for the application.
loadResource(URL, String, DownloadServiceListener) - Method in interface javax.jnlp.DownloadService
Downloads the given resource, if the resource is mentioned in the JNLP file for the application.
lookup(String) - Method in interface javax.jnlp.ServiceManagerStub
See description for ServiceManager.lookup(java.lang.String)
lookup(String) - Static method in class javax.jnlp.ServiceManager
Asks the JNLP Client for a service with a given name.

O

openFileDialog(String, String[]) - Method in interface javax.jnlp.FileOpenService
Asks the user to choose a single file.
openMultiFileDialog(String, String[]) - Method in interface javax.jnlp.FileOpenService
Asks the user to choose one or more files.

P

PersistenceService - interface javax.jnlp.PersistenceService.
PersistenceService provides methods for storing data locally on the client system, even for applications that are running in the untrusted execution environment.
print(Pageable) - Method in interface javax.jnlp.PrintService
Prints a document using the given Pageable object
print(Printable) - Method in interface javax.jnlp.PrintService
Prints a document using the given Printable object
PrintService - interface javax.jnlp.PrintService.
PrintService provides methods for access to printing functions, even for applications that are running in the untrusted execution environment.
progress(URL, String, long, long, int) - Method in interface javax.jnlp.DownloadServiceListener
A JNLP client's DownloadService implementation should call this method several times during a download.

R

read() - Method in interface javax.jnlp.JNLPRandomAccessFile
Reads a byte of data from this file.
read(byte[]) - Method in interface javax.jnlp.JNLPRandomAccessFile
Reads up to b.length bytes of data from this file into an array of bytes.
read(byte[], int, int) - Method in interface javax.jnlp.JNLPRandomAccessFile
Reads up to len bytes of data from this file into an array of bytes.
readBoolean() - Method in interface javax.jnlp.JNLPRandomAccessFile
Reads a boolean from this file.
readByte() - Method in interface javax.jnlp.JNLPRandomAccessFile
Reads a signed eight-bit value from this file.
readChar() - Method in interface javax.jnlp.JNLPRandomAccessFile
Reads a Unicode character from this file.
readDouble() - Method in interface javax.jnlp.JNLPRandomAccessFile
Reads a double from this file.
readFloat() - Method in interface javax.jnlp.JNLPRandomAccessFile
Reads a float from this file.
readFully(byte[]) - Method in interface javax.jnlp.JNLPRandomAccessFile
Reads b.length bytes from this file into the byte array, starting at the current file pointer.
readFully(byte[], int, int) - Method in interface javax.jnlp.JNLPRandomAccessFile
Reads exactly len bytes from this file into the byte array, starting at the current file pointer.
readInt() - Method in interface javax.jnlp.JNLPRandomAccessFile
Reads a signed 32-bit integer from this file.
readLine() - Method in interface javax.jnlp.JNLPRandomAccessFile
Reads the next line of text from this file.
readLong() - Method in interface javax.jnlp.JNLPRandomAccessFile
Reads a signed 64-bit integer from this file.
readShort() - Method in interface javax.jnlp.JNLPRandomAccessFile
Reads a signed 16-bit number from this file.
readUnsignedByte() - Method in interface javax.jnlp.JNLPRandomAccessFile
Reads an unsigned eight-bit number from this file.
readUnsignedShort() - Method in interface javax.jnlp.JNLPRandomAccessFile
Reads an unsigned 16-bit number from this file.
readUTF() - Method in interface javax.jnlp.JNLPRandomAccessFile
Reads in a string from this file.
removeExtensionPart(URL, String, String) - Method in interface javax.jnlp.DownloadService
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.
removeExtensionPart(URL, String, String[]) - Method in interface javax.jnlp.DownloadService
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.
removePart(String) - Method in interface javax.jnlp.DownloadService
Removes the given part from the cache, if the part is mentioned in the JNLP file for the application.
removePart(String[]) - Method in interface javax.jnlp.DownloadService
Removes the given parts from the cache, if the parts are mentioned in the JNLP file for the application.
removeResource(URL, String) - Method in interface javax.jnlp.DownloadService
Removes the given resource from the cache, if the resource is mentioned in the JNLP file for the application.

S

saveAsFileDialog(String, String[], FileContents) - Method in interface javax.jnlp.FileSaveService
Asks the users to save a file.
saveFileDialog(String, String[], InputStream, String) - Method in interface javax.jnlp.FileSaveService
Asks the users to save a file.
seek(long) - Method in interface javax.jnlp.JNLPRandomAccessFile
Sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs.
ServiceManager - class javax.jnlp.ServiceManager.
The ServiceManager provides static methods to lookup JNLP services.
ServiceManagerStub - interface javax.jnlp.ServiceManagerStub.
A ServiceManagerStub object implements the particular lookup of JNLP services by the JNLP Client.
setContents(Transferable) - Method in interface javax.jnlp.ClipboardService
Sets the current contents of the clipboard to the specified Transferable object.
setHeading(String) - Method in interface javax.jnlp.ExtensionInstallerService
Updates the status of the installer process.
setJREInfo(String, String) - Method in interface javax.jnlp.ExtensionInstallerService
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.
setLength(long) - Method in interface javax.jnlp.JNLPRandomAccessFile
Sets the length of this file.
setMaxLength(long) - Method in interface javax.jnlp.FileContents
Sets the maximum file length for the file.
setNativeLibraryInfo(String) - Method in interface javax.jnlp.ExtensionInstallerService
Informs the JNLP Client of a directory where it should search for native libraries.
setServiceManagerStub(ServiceManagerStub) - Static method in class javax.jnlp.ServiceManager
Sets the object that all lookup and getServiceNames requests are delegated to.
setStatus(String) - Method in interface javax.jnlp.ExtensionInstallerService
Updates the status of the installer process.
setTag(URL, int) - Method in interface javax.jnlp.PersistenceService
Tags the persistent data store entry associated with the given URL with the given tag value.
showDocument(URL) - Method in interface javax.jnlp.BasicService
Directs a browser on the client to show the given URL.
showPageFormatDialog(PageFormat) - Method in interface javax.jnlp.PrintService
Displays a dialog that allows modification of a PageFormat instance.
skipBytes(int) - Method in interface javax.jnlp.JNLPRandomAccessFile
Attempts to skip over n bytes of input discarding the skipped bytes.

T

TEMPORARY - Static variable in interface javax.jnlp.PersistenceService

U

UnavailableServiceException - exception javax.jnlp.UnavailableServiceException.
The UnavailableServiceException is thrown by the ServiceManager when a non-existing or unavailable service is looked up.
UnavailableServiceException() - Constructor for class javax.jnlp.UnavailableServiceException
Constructs an UnavailableServiceException with null as its error detail message.
UnavailableServiceException(String) - Constructor for class javax.jnlp.UnavailableServiceException
Constructs an UnavailableServiceException with the specified detail message.
updateProgress(int) - Method in interface javax.jnlp.ExtensionInstallerService
Updates the progress bar.
upgradingArchive(URL, String, int, int) - Method in interface javax.jnlp.DownloadServiceListener
A JNLP client's DownloadService implementation should call this method at least several times when applying an incremental update to an in-cache resource.

V

validating(URL, String, long, long, int) - Method in interface javax.jnlp.DownloadServiceListener
A JNLP client's DownloadService implementation should call this method at least several times during validation of a download.

W

write(byte[]) - Method in interface javax.jnlp.JNLPRandomAccessFile
Writes b.length bytes from the specified byte array to this file, starting at the current file pointer.
write(byte[], int, int) - Method in interface javax.jnlp.JNLPRandomAccessFile
Writes len bytes from the specified byte array starting at offset off to this file.
write(int) - Method in interface javax.jnlp.JNLPRandomAccessFile
Writes the specified byte to this file.
writeBoolean(boolean) - Method in interface javax.jnlp.JNLPRandomAccessFile
Writes a boolean to the file as a one-byte value.
writeByte(int) - Method in interface javax.jnlp.JNLPRandomAccessFile
Writes a byte to the file as a one-byte value.
writeBytes(String) - Method in interface javax.jnlp.JNLPRandomAccessFile
Writes the string to the file as a sequence of bytes.
writeChar(int) - Method in interface javax.jnlp.JNLPRandomAccessFile
Writes a char to the file as a two-byte value, high byte first.
writeChars(String) - Method in interface javax.jnlp.JNLPRandomAccessFile
Writes a string to the file as a sequence of characters.
writeDouble(double) - Method in interface javax.jnlp.JNLPRandomAccessFile
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.
writeFloat(float) - Method in interface javax.jnlp.JNLPRandomAccessFile
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.
writeInt(int) - Method in interface javax.jnlp.JNLPRandomAccessFile
Writes an int to the file as four bytes, high byte first.
writeLong(long) - Method in interface javax.jnlp.JNLPRandomAccessFile
Writes a long to the file as eight bytes, high byte first.
writeShort(int) - Method in interface javax.jnlp.JNLPRandomAccessFile
Writes a short to the file as two bytes, high byte first.
writeUTF(String) - Method in interface javax.jnlp.JNLPRandomAccessFile
Writes a string to the file using UTF-8 encoding in a machine-independent manner.
B C D E F G H I J L O P R S T U V W
Package Class Tree Index
PREV NEXT FRAMES NO FRAMES
Copyright (c) 2001-2002 Sun Microsystems, Inc. All Rights Reserved


Serialized Form

Package javax.jnlp

Class javax.jnlp.UnavailableServiceException implements Serializable

Package Class Tree Index
PREV NEXT FRAMES NO FRAMES
Copyright (c) 2001-2002 Sun Microsystems, Inc. All Rights Reserved


JNLP API Reference 1.0: Interface BasicService

Package Class Tree Index
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: INNER | 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.

Version:
1.0

Method Summary
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

public 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

public 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

public 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

public 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
SUMMARY: INNER | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD
Copyright (c) 2001-2002 Sun Microsystems, Inc. All Rights Reserved


JNLP API Reference 1.0: Interface ClipboardService

Package Class Tree Index
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: INNER | 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.

Version:
1.0

Method Summary
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

public 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

public 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
SUMMARY: INNER | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Copyright (c) 2001-2002 Sun Microsystems, Inc. All Rights Reserved


JNLP API Reference 1.0: Interface DownloadService

Package Class Tree Index
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: INNER | 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.

Version:
1.0

Method Summary
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 mentioned in the JNLP file for the application.
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 mentioned in the JNLP file for the application.
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 mentioned in the JNLP file for the application.

Method Detail

isResourceCached

public 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 mentioned in the JNLP file for the application.
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

public 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

public 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

public 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

public 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

public void loadResource(java.net.URL ref,
                         java.lang.String version,
                         DownloadServiceListener progress)
                  throws java.io.IOException
Downloads the given resource, if the resource is 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.
progress - Download progress callback object.

loadPart

public 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.

loadPart

public 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.

loadExtensionPart

public 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.

loadExtensionPart

public 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.

removeResource

public 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 mentioned in the JNLP file for the application.
Parameters:
ref - The URL for the resource.
version - The version string, or null for no version.

removePart

public 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.

removePart

public 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.

removeExtensionPart

public 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.

removeExtensionPart

public 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.

getDefaultProgressWindow

public 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.
Package Class Tree Index
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: INNER | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Copyright (c) 2001-2002 Sun Microsystems, Inc. All Rights Reserved


JNLP API Reference 1.0: Interface DownloadServiceListener

Package Class Tree Index
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: INNER | 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.

Version:
1.0
See Also:
DownloadService

Method Summary
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

public 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

public 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

public 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

public 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
SUMMARY:  INNER | FIELD | CONSTR | METHOD DETAIL:  FIELD | CONSTR | METHOD
Copyright (c) 2001-2002 Sun Microsystems, Inc. All Rights Reserved


JNLP API Reference 1.0: Interface ExtensionInstallerService

Package Class Tree Index
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: INNER | 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.

Version:
1.0

Method Summary
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

public 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

public java.lang.String getExtensionVersion()
Returns the version of the extension being installed

getExtensionLocation

public java.net.URL getExtensionLocation()
Returns the location of the extension being installed

hideProgressBar

public void hideProgressBar()
Hides the progress bar. Any subsequent calls to updateProgress will force it to be visible.

hideStatusWindow

public 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

public void setHeading(java.lang.String heading)
Updates the status of the installer process.

setStatus

public void setStatus(java.lang.String status)
Updates the status of the installer process.

updateProgress

public void updateProgress(int value)
Updates the progress bar.
Parameters:
value - progress bar value - should be between 0 and 100.

installSucceeded

public 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

public 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

public 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

public void setNativeLibraryInfo(java.lang.String path)
Informs the JNLP Client of a directory where it should search for native libraries.

getInstalledJRE

public 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
SUMMARY: INNER | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Copyright (c) 2001-2002 Sun Microsystems, Inc. All Rights Reserved


JNLP API Reference 1.0: Interface FileContents

Package Class Tree Index
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: INNER | 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.

Version:
1.0
See Also:
FileOpenService, FileSaveService

Method Summary
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

public 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

public 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

public 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

public 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

public 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

public 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

public 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

public 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

public 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
SUMMARY: INNER | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Copyright (c) 2001-2002 Sun Microsystems, Inc. All Rights Reserved


JNLP API Reference 1.0: Interface FileOpenService

Package Class Tree Index
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: INNER | 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.

Version:
1.0
See Also:
FileSaveService, FileContents

Method Summary
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

public 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.

openMultiFileDialog

public 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[])
Package Class Tree Index
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: INNER | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Copyright (c) 2001-2002 Sun Microsystems, Inc. All Rights Reserved


JNLP API Reference 1.0: Interface FileSaveService

Package Class Tree Index
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: INNER | 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.

Version:
1.0
See Also:
FileOpenService, FileContents

Method Summary
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

public 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

saveAsFileDialog

public 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.
filecontents - 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
Package Class Tree Index
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: INNER | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Copyright (c) 2001-2002 Sun Microsystems, Inc. All Rights Reserved


JNLP API Reference 1.0: Interface JNLPRandomAccessFile

Package Class Tree Index
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: INNER | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

javax.jnlp
Interface JNLPRandomAccessFile

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.

Version:
1.0

Method Summary
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

public 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

public 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

public 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

public 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

public 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

public 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

public 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

public 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

public 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

public 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

public 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

public 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

public 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

public 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

public 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

public 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

public 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

public 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

public 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

public 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

public 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

public 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

public 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

public 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

public 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

public 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

public 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

public 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

public 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

public 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

public 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

public 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

public 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

public 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

public 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

public 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

public 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
SUMMARY: INNER | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Copyright (c) 2001-2002 Sun Microsystems, Inc. All Rights Reserved


JNLP API Reference 1.0: Package javax.jnlp

Package Class Tree Index
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package javax.jnlp

Interface Summary
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.
ClipboardService | ClipboardService provides methods for accessing the shared system-wide clipboard, even for applications that are running in the untrusted execution environment.
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.
DownloadServiceListener | The DownloadServiceListener provides an interface for a callback object implementation, which may be used by a DownloadService implementation.
ExtensionInstallerService | The ExtensionInstallerService is used by an extension installer to communicate with the JNLP Client.
FileContents | FileContents objects encapsulate the name and contents of a file.
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.
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.
JNLPRandomAccessFile | Instances of this class support both reading and writing to a random access file.
PersistenceService | PersistenceService provides methods for storing data locally on the client system, even for applications that are running in the untrusted execution environment.
PrintService | PrintService provides methods for access to printing functions, even for applications that are running in the untrusted execution environment.
ServiceManagerStub | A ServiceManagerStub object implements the particular lookup of JNLP services by the JNLP Client.

Class Summary
ServiceManager The ServiceManager provides static methods to lookup JNLP services.

Exception Summary
UnavailableServiceException The UnavailableServiceException is thrown by the ServiceManager when a non-existing or unavailable service is looked up.

Package Class Tree Index
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES
Copyright (c) 2001-2002 Sun Microsystems, Inc. All Rights Reserved


JNLP API Reference 1.0: javax.jnlp Class Hierarchy

Package Class Tree Index
PREV NEXT FRAMES NO FRAMES

Hierarchy For Package javax.jnlp

Class Hierarchy

  • class java.lang.Object
    • class javax.jnlp.ServiceManager
    • class java.lang.Throwable (implements java.io.Serializable)
      • class java.lang.Exception
        • class javax.jnlp.UnavailableServiceException

Interface Hierarchy

  • interface javax.jnlp.BasicService
  • interface javax.jnlp.ClipboardService
  • interface java.io.DataInput
    • interface javax.jnlp.JNLPRandomAccessFile(also extends java.io.DataOutput)
  • interface java.io.DataOutput
    • interface javax.jnlp.JNLPRandomAccessFile(also extends java.io.DataInput)
  • interface javax.jnlp.DownloadService
  • interface javax.jnlp.DownloadServiceListener
  • interface javax.jnlp.ExtensionInstallerService
  • interface javax.jnlp.FileContents
  • interface javax.jnlp.FileOpenService
  • interface javax.jnlp.FileSaveService
  • interface javax.jnlp.PersistenceService
  • interface javax.jnlp.PrintService
  • interface javax.jnlp.ServiceManagerStub
Package Class Tree Index
PREV NEXT FRAMES NO FRAMES
Copyright (c) 2001-2002 Sun Microsystems, Inc. All Rights Reserved


JNLP API Reference 1.0: Interface PersistenceService

Package Class Tree Index
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: INNER | 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.

Version:
1.0

Field Summary
static int | CACHED
static int | DIRTY
static int | TEMPORARY
Method Summary
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

public static final int CACHED

TEMPORARY

public static final int TEMPORARY

DIRTY

public static final int DIRTY
Method Detail

create

public 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

public 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

public 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

public 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

public 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

public 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
SUMMARY: INNER | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Copyright (c) 2001-2002 Sun Microsystems, Inc. All Rights Reserved


JNLP API Reference 1.0: Interface PrintService

Package Class Tree Index
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: INNER | 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.

Version:
1.0

Method Summary
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

public 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

public 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

public 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

public 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
SUMMARY: INNER | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Copyright (c) 2001-2002 Sun Microsystems, Inc. All Rights Reserved


JNLP API Reference 1.0: Class ServiceManager

Package Class Tree Index
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: INNER | 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.

Version:
1.0
See Also:
ServiceManagerStub

Method Summary
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.

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
SUMMARY: INNER | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD
Copyright (c) 2001-2002 Sun Microsystems, Inc. All Rights Reserved


JNLP API Reference 1.0: Interface ServiceManagerStub

Package Class Tree Index
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: INNER | 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.

Version:
1.0
See Also:
ServiceManager

Method Summary
 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

public java.lang.Object lookup(java.lang.String name)
                        throws UnavailableServiceException
See description for ServiceManager.lookup(java.lang.String)

getServiceNames

public java.lang.String[] getServiceNames()
See description for ServiceManager.getServiceNames()
Package Class Tree Index
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: INNER | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD
Copyright (c) 2001-2002 Sun Microsystems, Inc. All Rights Reserved


JNLP API Reference 1.0: Class UnavailableServiceException

Package Class Tree Index
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: INNER | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

javax.jnlp
Class UnavailableServiceException

java.lang.Object
  |
  +--java.lang.Throwable
        |
        +--java.lang.Exception
              |
              +--javax.jnlp.UnavailableServiceException
public class UnavailableServiceException
extends java.lang.Exception

The UnavailableServiceException is thrown by the ServiceManager when a non-existing or unavailable service is looked up.

Version:
1.0
See Also:
ServiceManager, Serialized Form

Constructor Summary
UnavailableServiceException()
Constructs an UnavailableServiceException with null as its error detail message.
UnavailableServiceException(java.lang.String msg)
Constructs an UnavailableServiceException with the specified detail message.
Methods inherited from class java.lang.Throwable
fillInStackTrace, getLocalizedMessage, getMessage, printStackTrace, printStackTrace, printStackTrace, 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
SUMMARY: INNER | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD
Copyright (c) 2001-2002 Sun Microsystems, Inc. All Rights Reserved


Programming With Assertions

 Documentation Contents

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. This section covers some of them:

  • Internal Invariants
  • Control-Flow Invariants
  • Preconditions, Postconditions, and Class Invariants

There are also a few 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 ( JLS 14.20), 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 invariants 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 JLS 14.20, 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.

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 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

  1. 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.

  2. 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.

  3. 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.

  4. 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

  1. 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.

  2. 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

  1. 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

  1. 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.

  2. 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.

  3. 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 just assertion errors. We enhanced Throwable with the getStackTrace method to provide this functionality.

  4. Why is AssertionError a subclass of Error rather than RuntimeException?

    This issue was controversial. The expert group discussed it at 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

  1. 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 JLS 14.20 can be used to achieve this effect for developers who really want it.

  2. 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.

  3. 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.

  4. 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.

  5. 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.

  6. 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).

  7. 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
  8. Why does an assert statement that executes before its class is initialized behave as if assertions were enabled in the class?

    9. 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.

Sun
Java Software

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.


Chained Exception Facility

 Documentation Contents
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).

The bugtraq report that corresponds to this change is 4209652.

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software


Enhancements in java.lang and java.util.*

Java

Enhancements to java.lang.* and java.util.*
in Java 2 SDK v1.3

 Documentation Contents
Version 1.3 of the Java 2 SDK included the following enhancements:
Classes java.lang.Math and java.lang.StrictMath
New Timer API
Enhanced Collections Framework
Virtual Machine Shutdown Hooks
New URL JAR File Caching
Classes java.lang.Math and java.lang.StrictMath
The Java 2 Platform now contains two clases which provide API for performing general numeric operations.
  • java.lang.StrictMath - Class java.lang.StrictMath has the same API as old class java.lang.Math, which was present previous versions of the Java platform. Unlike class Math, however, StrictMath 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 permits better-performing implementations where strict reproducibility is not required.

New Timer API

Two new classes have been added to the Java 2 Platform to provide an API for a timer facility which can be used for purposes such as animations, human interaction timeouts, on-screen clocks and calendars, work-scheduling routines, reminder facilities, and more.
  • java.util.Timer
  • java.util.TimerTask
Countdown.java is a simple demo application that uses the new Timer API.

Enhanced Collections Framework

The Collections Framework has these new convenience APIs:
  • Added java.util.Collections.singletonList and java.util.Collections.singletonMap. Previously, there was a convenience implementation for singleton Set, but no corresponding implementation for List and Map. Both of these implementations proved desirable in practice.
  • Added java.util.Collections.EMPTY_MAP. Previously, there were constant convenience implementations for the empty Set and List, but no corresponding implementation for Map.
The following special-purpose implementation has also been added:
  • Added Map constuctor for WeakHashMap. The Map interface dictates that most Map implementations should have a "copy constructor" that takes a Map argument. WeakHashMap lacked such a constructor in the 1.2 release.

Virtual Machine Shutdown Hooks

Sophisticated applications often require the ability to perform specific actions when the virtual machine shuts down, whether due to voluntary exit or involuntary termination. Typical actions include cleanly closing down network connections, saving session state, and deleting temporary files. Every major operating system provides the means for native applications to do this, though of course the details vary from platform to platform. Three methods have been added to java.lang.Runtime to provide a simple and portable interface to these facitilies. The new methods are:
  • addShutdownHook
  • removeShutdownHook
  • halt
In addition, the Runtime.exit method has been revised. For more information, see Design of the Shutdown Hooks API.

New URL JAR File Caching

The API of classes java.util.zip and java.util.jar have been enhanced with the addition of the following:
  • java.util.zip.OPEN_READ
  • java.util.zip.OPEN_DELETE
  • java.util.zip.ZipFile(File file, int mode)
  • java.util.jar.JarFile(File file, boolean verify, int mode)
The previous implementation of caching downloaded Jar files created problems for long-running server application and for RMI. Each open JarURLConnection creates a temporary local file that holds Jar-file date, and a JarFile object is created on top of the temporary file. Because the open file handle/descriptor on each temporary file was never closed, the files could quickly take up disk space for long-running server applications. The new API provides a solution for this problem by supporting a new "delete-on-close" mode for opening Zip and Jar files.

Copyright © 1999 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: jdk-comments@java.sun.com 		Sun


Design of Shutdown Hooks API

Java

Design of the Shutdown Hooks API

 Documentation Contents
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 © 1999 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software


The java.lang.* and java.util.* Packages

 Documentation Contents
The java.lang package provides classes that are fundamental to the design of the JavaTM programming language. The java.lang.refs and java.lang.reflect packages provide, respectively, reference-object classes and APIs for obtaining reflective information about classes.

The java.util.* packages provide support for the event model, collections framework, date and time facilities, and contains various utility classes. The java.util.zip and java.util.jar packages provide support for ZIP file format and Java Archive (JAR) file formats respectively, and the java.util.prefs package implements the Preferences API.

Enhancements

Java 2 SDK v1.4 offers several significant enhancements to the functionality in the java.lang.* and java.util.* packages, including
  • Assertion Factility - Assertions are boolean expressions that the programmer believes to be true concerning the state of a computer program. For example, after sorting a list, the programmer might assert that the list is in ascending order. Evaluating assertions at runtime to confirm their validity is one of the most powerful tools for improving code quality, as it quickly uncovers the programmer's misconceptions concerning a program's behavior.
  • Preferences API - The preferences API, implemented by package java.util.prefs, allows applications to store and retrieve user and system preference and configuration data. This data is stored persistently in an implementation-dependent backing store. The Preferences API is intended to replace most common uses of class java.util.Properties, rectifying many of its deficiencies, while retaining its light weight.
  • Logging API - The Java Logging API facilitates software servicing and maintenance at customer sites by producing log reports suitable for analysis by end users, system administrators, field service engineers, and software development teams. The Logging APIs capture information such as security failures, configuration errors, performance bottlenecks, and/or bugs in the application or platform. The core package includes support for delivering plain text or XML formatted log records to memory, output streams, consoles, files, and sockets. In addition, the logging APIs are capable of interacting with logging services that already exist on the host operating system.
  • Regular Expressions - New package java.util.regex contains classes for matching character sequences against patterns specified by regular expressions.
  • Chained Exception Facility - This is a new facility that provides a common API to record the fact that one exception caused another, to access causative exceptions, and to acess the 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.
Enhancements in Java 2 SDK v1.3
Version 1.3 of the Java 2 SDK offered several enhancements in the java.lang and java.util.* packages. See Enhancements in 1.3 for details.

API Specifications

  • Package java.lang
  • Package java.lang.ref
  • Package java.lang.reflect
  • Package java.util
  • Package java.util.prefs
  • Package java.util.logging
  • Package java.util.regex
  • Package java.util.jar
  • Package java.util.zip

Related Documentation

  • The Collections Framework
  • Package Java Archive (JAR) Features
  • Supported Encodings

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software


Preferences API
Java

Preferences API

 Documentation Contents

Overview

Applications require preference and configuration data to adapt to the needs of different users and environments. The java.util.prefs package provides a way for applications to store and retrieve user and system preference and configuration data. The data is stored persistently in an implementation-dependent backing store. There are two separate trees of preference nodes, one for user preferences and one for system preferences.

All of the methods that modify preference data are permitted to operate asynchronously. They may return immediately, and changes will eventually propagate to the persistent backing store. The flush method can be used to force updates to the backing store.

The methods in the Preferences class may be invoked concurrently by multiple threads in a single JVM without the need for external synchronization, and the results will be equivalent to some serial execution. If this class is used concurrently by multiple JVMs that store their preference data in the same backing store, the data store will not be corrupted, but no other guarantees are made concerning the consistency of the preference data.

For more details, choose from the following links:

  • Comparing Preferences API to Other Mechanisms
  • Usage Notes
  • Design FAQ

Comparing Preferences API to Other Mechanisms

Prior to the introduction of the Preferences API, developers could choose to manage preference and configuration data in an ad hoc fashion, by using the Properties API or the JNDI API as described below.

Often, preference and configuration data was stored in properties files, accessed through the java.util.Properties API. However, there are no standards as to where such files should reside on disk, or what they should be called. Using this mechanism, it is extremely difficult to backup a user's preference data, or transfer it from one machine to another. As the number of applications increases, the possibility of file name conflicts increases. Also, this mechanism is of no help on platforms that lack a local disk, or where it is desirable that the data be stored in an external data store (such as an enterprise-wide LDAP directory service).

Less frequently, developers stored user preference and configuration data in a directory service, accessed through the Java Naming and Directory Interface (JNDI) API. Unlike the Properties API, JNDI allows the use of arbitrary data stores (back-end neutrality). While JNDI is extremely powerful, it is also rather large, consisting of 5 packages and 83 classes. JNDI provides no policy as to where in the directory name space the preference data should be stored, or in which name space.

Neither Properties nor JNDI provide a simple, ubiquitous, back-end neutral preferences management facility. The Preferences API does provide such a facility, combining the simplicity of Properties with the back-end neutrality of JNDI. It provides sufficient built-in policy to prevent name clashes, foster consistency, and encourage robustness in the face of inaccessibility of the backing data store.

  • See Also: Design FAQ

Usage Notes

The material contained in this section is not part of the Preferences API specification, instead it is intended to provide some examples of how the Preferences API might be used.
  • Obtaining Preferences Objects for an Enclosing Class
  • Obtaining Preferences Objects for a Static Method
  • Atomic Updates
  • Determining Backing Store Status

Obtaining Preferences Objects for an Enclosing Class

The following examples illustrate how you might obtain the Preferences objects (system and user) pertaining to the enclosing class. These examples would work only inside instance methods.

Note that static final fields, rather than inline String literals, are used for the key names (NUM_ROWS and NUM_COLS). This reduces the likelihood of runtime bugs from typographical errors in key names.

Note also that reasonable defaults are provided for each of the preference values obtained. These defaults will be returned if no preference value has been set, or if the backing store is inaccessible.

package com.acme.widget;
import  java.util.prefs.*;

public class Gadget {
    // Preference keys for this package
    private static final String NUM_ROWS = "num_rows";
    private static final String NUM_COLS = "num_cols";

    void foo() {
        Preferences prefs = Preferences.userNodeForPackage(this);

        int numRows = prefs.getInt(NUM_ROWS, 40);
        int numCols = prefs.getInt(NUM_COLS, 80);

        ...
    }
}
The above example obtains per-user preferences. If a single, per-system value were desired, the first line in foo would be replaced by:
        Preferences prefs = Preferences.systemNodeForPackage(this);

Obtaining Preferences Objects for a Static Method

The examples in the prior section illustrate obtaining Preferences objects pertaining to the enclosing class, and work inside instance methods. In a static method (or static initializer), you need to explicitly provide the name of the package :
    Static String ourNodeName = "/com/acme/widget";

    static void foo() {
        Preferences prefs = Preferences.userRoot().node(ourNodeName);

        ...
    }
It is always acceptable to obtain a system preferences object once, in a static initializer, and use it whenever system preferences are required:
    static Preferences prefs =  Preferences.systemRoot().node(ourNodeName);
In general, it is acceptable to do the same thing for a user preferences object, but not if the code in question is to be used in a server, wherein multiple users will be running concurrently or serially. In such a system, userNodeForPackage and userRoot will return the appropriate node for the calling user, thus it's critical that calls to userNodeForPackage or userRoot be made from the appropriate thread at the appropriate time. If a piece of code may eventually be used in such a server environment, it is good, conservative practice to obtain user preferences objects immediately before they are used, as in the prior example.

Atomic Updates

The preferences API does not provide database like "transactions" wherein multiple preferences are modified atomically. Occasionally, it is necessary to modify two or more preferences as a unit. For example, suppose you are storing the x and y coordinates where a window is to be placed. The only way to achieve atomicity is to store both values in a single preference. Many encodings are possible. Here's a simple one:
    int x, y;
    ...
    prefs.put(POSITION, x + "," + y);
When such a "compound preference" is read, it must be decoded. For robustness, allowances should be made for a corrupt (unparseable) value:
    static int X_DEFAULT = 50, Y_DEFAULT = 25;
    void baz() {
        String position = prefs.get(POSITION, X_DEFAULT + "," + Y_DEFAULT);
        int x, y;
        try {
            int i = position.indexOf(',');
            x = Integer.parseInt(coordinates.substring(0, i));
            y = Integer.parseInt(position.substring(i + 1));
        } catch(Exception e) {
            // Value was corrupt, just use defaults
            x = X_DEFAULT;
            y = Y_DEFAULT;
        }
        ...
    }

Determining Backing Store Status

Typical application code has no need to know whether the backing store is available. It should almost always be available, but if it isn't, the code should continue to execute using default values in place of preference values from the backing store. Very rarely, some advanced program might want to vary its behavior (or simply refuse to run) if the backing store were unavailable. Following is a method that determines whether the backing store is available by attempting to modify a preference value and flush the result to the backing store.
    private static final String BACKING_STORE_AVAIL = "BackingStoreAvail";

    private static boolean backingStoreAvailable() {
        Preferences prefs = Preferences.userRoot().node("");
        try {
            boolean oldValue = prefs.getBoolean(BACKING_STORE_AVAIL, false);
            prefs.putBoolean(BACKING_STORE_AVAIL, !oldValue);
            prefs.flush();
        } catch(BackingStoreException e) {
            return false;
        }
        return true;
    }

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 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 © 2002 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software


Enhancements to java.math

 Documentation Contents
The following enhancements were made to the java.math package in version 1.3 of the JavaTM 2 SDK.

Performance enhancements in BigIntenger

Class java.math.BigInteger has been reimplemented in pure Java programming-language code. Previously, BigInteger's implementation was based on an underlying C library. On a high-quality VM, the new implementation performs all operations faster than the old implementation. The speed-up can be as much as 5x or more, depending on the operation being performed and the length of the operands.
More robust BigDecimal(String) constructor
The BigDecimal(String) constructor has been enhanced to allow signed strings (for example, "+2.71828") and exponential notation (for example, "1.23E-23") as input.

Copyright © 1999 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: jdk-comments@java.sun.com 		Sun


Enhancements to java.math

 Documentation Contents
The following enhancement has been made to the java.math package in version 1.4 of the JavaTM 2 SDK.

Performance enhancements for prime generation in BigIntenger

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).

Copyright © 2001 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: j2se-comments@java.sun.com 		Sun


Arbitrary Precision Math

Java

Arbitrary-Precision Math

 Documentation Contents
The java.math package supports arbitrary-precision math. The package consists of two classes:
  • BigInteger numbers are immutable, arbitrary-precision integers. The BigInteger class provides analogs for all Java language primitive integer operators. The class also supports modular arithmetic, GCD calculation, prime number generation and testing, single-bit manipulation, and various other operations.
  • BigDecimal numbers are immutable, arbitrary-precision signed decimal numbers, suitable for monetary calculations. The BigDecimal class provides operations for basic arithmetic, scale manipulation, comparison, format conversion, and hashing.
Enhancements
  • Enhancements to java.math in version 1.4 of the JavaTM 2 SDK.
  • Enhancements to java.math in version 1.3 of the Java 2 SDK.
API Specification
  • java.math Package
Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: j2se-comments@sun.com

Sun Microsystems, Inc
Java Software


The APPLET Tag

 Documentation Contents

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/jdk/1.4/demo/applets/NervousText/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.)
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 © 1995-98 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: jdk-comments@java.sun.com 		Sun

Java Software


Miscellaneous Features

 Documentation Contents
  • The @deprecated Tag
    Used within documentation comments to mark classes and members as "no-longer-preferred", and directs the developer to replacement classes and members.
  • APPLET Tag
    Enhancements to the <APPLET> tag defined in HTML. Loads applets in the applet viewer or a web browser.

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: jdk-comments@java.sun.com 		Sun

Java Software


Java Thread Primitive Deprecation

Java

Why Are Thread.stop, Thread.suspend,
Thread.resume and Runtime.runFinalizersOnExit Deprecated?

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. (This is the approach that JavaSoft's Tutorial has always recommended.) 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() {
        Thread thisThread = Thread.currentThread();
        while (true) {
            try {
                thisThread.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 {
                thisThread.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 the thread is "resumed." The resulting run method follows:
    public void run() {
        while (true) {
            try {
                Thread.currentThread().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 boolean volatile threadSuspended;

    public void run() {
        while (true) {
            try {
                Thread.currentThread().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 {
                thisThread.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 has never been implemented. 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.) We are not implementing it at this time, but neither are we deprecating it (forestalling its implementation in future). While it would certainly be deadlock prone, it has been argued that there may be circumstances where a program is willing to risk a deadlock rather than exit outright.

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 © 1995-99 Sun Microsystems, Inc. All Rights Reserved.

Suggest a feature or make comments

Java Software


The @deprecated Tag

"@deprecated": Mechanical Help for Abandoning Old APIs

John R. Rose
Oct 4, 1996

Problem:

Java 1.1 introduces many new APIs, some of which supersede older ones. The new and old APIs co-exist in the same packages. The superseded ones add various difficulties to the programmer's job, the chief being the need to ignore and avoid them in most cases.

Partial Solution: If we mark superseded classes, methods, and fields clearly and unambiguously as "deprecated", the programmers will know where to concentrate their attention. Also, the compiler will be able to help with this process, by bringing unintentional uses of deprecated APIs to the programmer's attention.

Details:

Within documentation comments, we define the new paragraph tag "@deprecated". (See JLS, $$184.) It can appear in both class and member documentation comments, and will apply specifically the construct its comment introduces.

The tagged paragraph can be empty. If it is not, it should tell the programmer how to avoid using the deprecated feature.

There should be "@see" tagged paragraphs which refer to the new versions of the same functionality.

As far as the compiler is concerned, the presence of the string "@deprecated" at the beginning of a documentation comment line (except for whitespace) causes it to place a "Deprecated" attribute in the output classfile for the corresponding class, field, or method.

Moreover, in parallel with the access checking logic for classes and members, the compiler looks for "Deprecated" attributes of classes and members being accessed, and issues warnings when the deprecated classes or members are used.

Note that deprecation applies to classes and to individual members, 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 member to hide or override a deprecated one, which removes deprecation. It is the responsibility of the programmer to deprecate overrides of a deprecated method, if in fact they should be deprecated.

A deprecation warning is suppressed if the compilation unit containing the deprecation is being compiled at the same time as the compilation unit using the deprecated class or member. This allows legacy APIs to be built without warnings. There currently is no other way to suppress the deprecation warnings.

A hypothetical "-strict" option to the compiler could promote all warnings, including deprecation warnings, to hard errors. This is not in 1.1.

Javadoc should somehow highlight deprecation paragraphs, and perhaps should place a characteristic glyph next to references to deprecated names.

Practice:

Here is an example of the most common form of a deprecated method:

    /**
     * @deprecated
     * @see #getPreferredSize
     */
    public Dimension preferredSize() {
    return getPreferredSize();
    }
(Notes: The "@deprecated" tag must be followed by a space or newline. The "@see" tag must be at the beginning of the line. See the JLS, chapter 18.)

If the deprecation is a simple renaming, there is no need to say something like "this method is replaced by getPreferredSize"; the "@see"-tagged paragraph points the user to the replacement.

The deprecation may be more complex if the API was reorganized by other than a renaming of features. Here is an example of a method that is being retracted:

    /**
     * Delete multiple items from the list.
     *
     * @deprecated  Not for public use in the future.
     * This method is expected to be retained only as a package
     * private method.
     * @see #remove(int)
     * @see #removeAll()
     */
    public synchronized void delItems(int start, int end) {
    ...
    }
Designers of new 1.1 APIs should carefully consider whether they are superseding old APIs. For each such API, if they wish to encourage users of the old previous API to migrate to the new API, they should add a deprecation paragraph to the documentation comment. Empty deprecation paragraphs are bad form, because they do not help the user fix the warnings that arise from the deprecation.

Valid reasons for wishing one's users to migrate to the new API include:

  • the old API is insecure, buggy, or highly inefficient
  • the old API is going away in a future release
  • the old API encourages very bad coding practices

Not all of these reasons are of equal weight, yet deprecation is a reasonable (though not mandatory) choice in all these cases. Therefore, the use of deprecated APIs can never be made a hard error by default. Also, the deprecation comments need to help the user decide when to move to the new API, and so should briefly mention the technical reasons for deprecation.

(It is probably not good to specifically mention a timetable for phase-out of the deprecated API; this is a business decision that needs to be communicated other ways.)

It is not necessary to deprecate individual members of a deprecated class, unless of course the programmer wants to explain some specific point about one member.

When a feature is deprecated, it is a good idea to notify the engineering organization of this fact, so that other engineers can respond to the change (pro or con) in a timely manner.

Other Design Options:

This is the first time the compiler is in any way cognizant of document comment contents. (Once, it made sure that they were at the right place in the parse tree, but this is no longer true.) We did not lightly choose to make the compiler's behavior dependent on the contents of a comment.

One precedent for looking into comments is "lint", which uses comments like /*PRINTFLIKE2*/ to annotate C APIs.

Note that Java documentation comments are structured, and the structure is specified in the Java Language Specification. This means that we "own" the format of this particular sort of comment, so our design is somewhat more reasonable than the less-differentiated conventions used by lint.

We considered introducing pragmas, and using them for deprecation (e.g., <*deprecated*>) but this would open the door very wide to many sorts of incompatible extensions and, possibly, to serious abuses.

However, @deprecated does work like a pragma: It belongs in the source, expresses information about it, but does not modify its semantics. Unlike many pragmas, @deprecated is intended for a human audience.

The compiler emits warnings as a friendly and helpful reminder, but does not enforce any rules. It's up to the programmer to use the contents of the deprecation paragraph. Since the human is the primary user of the data, it belongs in comments.

We considered introducing a new keyword, something like "transient". This would solve the mechanical problem, but at the cost of modifying the language itself. In particular, we would have to take away an identifier from coders that we had not previously reserved (like "var"). Moreover, since the primary audience of deprecations is humans, a keyword-based approach is insufficient, and must be augmented by comment conventions, preferably ones which integrate with javadoc. Thus, the keyword approach does not pay.

Still, the compiler has heretofore ignored and should generally ignore documentation comments. This is an admittedly irregular exception to that practice. But the other design options for deprecation involve worse sorts of irregularity.

Sun logo Copyright © 1996 Sun Microsystems, Inc., 2550 Garcia Ave., Mtn. View, CA 94043-1100 USA. All rights reserved.

Please send comments to: jdk-comments@java.sun.com


How and When to Deprecate APIs

Sun Microsystems, Inc

How and When
To Deprecate APIs

(based on a writeup by John Rose)

Maintained by doug.kramer@sun.com

Deprecation
Home Page

Contents

  • What "Deprecated" means
  • When to Deprecate
  • What happens when an API is Deprecated
  • How to Deprecate

What "Deprecated" means

You may have heard the term, "self-deprecating humor". That is humor that minimizes your importance. A deprecated class or method is like that. It is no longer important. It is so unimportant, in fact, that it should no longer be used at all, as it will probably cease to exist in the future.

The need for deprecation comes about because, as a class evolves, its API changes. Methods are renamed for consistency. New and better methods are added. Attributes change. But making such changes introduces a problem. You need to keep the old API around until people make the transition to the new one, but you don't want developers to continue programming to the old API.

The ability to mark a class or method as "deprecated" solves the problem. Existing classes that use the old API continue to work, but the compiler can issue a warning when it finds references to deprecated items. Meanwhile, the API comments can warn the user against using the deprecated item and tell the user how to avoid doing so. The @deprecated tag achieves these goals.

Note: "Deprecated" and "depreciated" are not same. "Depreciated" is a financial term that means "lowered value". Although the meanings are similar, classes and methods are deprecated, not depreciated.

When to Deprecate

Designers of new APIs should carefully consider whether they are superseding old APIs. For each such API, if they wish to encourage users of the old previous API to migrate to the new API, they should add a deprecation paragraph to the documentation comment. Empty deprecation paragraphs are bad form, because they do not help the user fix the warnings that arise from the deprecation.

Valid reasons for wishing one's users to migrate to the new API include: - the old API is insecure, buggy, or highly inefficient - the old API is going away in a future release - the old API encourages very bad coding practices Not all of these reasons are of equal weight, yet deprecation is a reasonable (though not mandatory) choice in all these cases. Therefore, the use of deprecated APIs can never be made a hard error by default. Also, the deprecation comments need to help the user decide when to move to the new API, and so should briefly mention the technical reasons for deprecation.

What happens when an API is Deprecated

In parallel with the access-checking logic for classes and members, the compiler looks for deprecated attributes of classes and members being accessed, and issues warnings when the deprecated classes or members are used.
Note: A deprecation warning is suppressed if the compilation unit containing the deprecation is being compiled at the same time as the compilation unit using the deprecated class or member. This allows legacy APIs to be built without warnings. There currently is no other way to suppress the deprecation warnings.
JavaDoc also pays special attention to @deprecated tags when generating html files. Javadoc parses the entire paragraph following the @deprecated tag and moves it 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.

How to Deprecate

To deprecate a class or method, use the @deprecated tag, as explained in How to Write Doc Comments for JavaDoc. The paragraph following the @deprecated tag should explain why the item has been deprecated and suggest how the user can avoid using it.

It is not necessary to deprecate individual members of a deprecated class, unless of course the programmer wants to explain some specific point about one member.

Note: Deprecation applies to classes and to individual members, 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 member to hide or override a deprecated one, which removes deprecation. It is the responsibility of the programmer to deprecate overrides of a deprecated method, if in fact they should be deprecated.
It is probably not good to specifically mention a timetable for phase-out of the deprecated API; this is a business decision that needs to be communicated other ways.

When a feature is deprecated, it is a good idea to notify the engineering organization of this fact, so that other engineers can respond to the change (pro or con) in a timely manner.


Deprecation of APIs

 Documentation Contents
A deprecated API is an API that we recommend you no longer use, due to improvements in Java. While deprecated APIs are currently still implemented, they may be removed in future implementations, and we recommend using other APIs. The @deprecated tag denotes a deprecated API.
Deprecated Guide
  • How and When to Deprecate APIs

Deprecated Design Notes
  • The @deprecated Tag
Copyright © 1995-97 Sun Microsystems, Inc. All Rights Reserved.

Please send comments on deprecation to: jdk-comments@java.sun.com 		Sun

Java Software


Networking Features

Java

Networking

 Documentation Contents
Networking Enhancements for JavaTM 2 SDK, Standard Edition, v 1.3

New Classes/Interfaces

  • java.net.DatagramSocketImplFactory

    New interface java.net.DatagramSocketImplFactory is used by DatagramSocket to create actual socket implementations. This addition makes DatagramSocket consistent with the other socket types, by allowing the user to set the DatagramSocketImplFactory through a public API.

Modified Classes/Interfaces

  • java.net.HttpURLConnection

    The following constants were added to java.net.HttpURLConnection to make the HTTP status codes match the HTTP 1.1 RFC:

    • public static final int HTTP_INTERNAL_ERROR = 500;
    • public static final int HTTP_NOT_IMPLEMENTED = 501;

    Two new methods were added to support following HTTP redirects (requests with response code 3xx) on a per-instance basis. The default is to use the class setting.

    • public boolean getInstanceFollowRedirects()
    • public void setInstanceFollowRedirects(boolean followRedirects)

  • java.net.Socket and java.net.SocketImpl

    Two new methods have been added to java.net.Socket. Java sockets now support the keepalive option.

    • public boolean getKeepAlive(boolean)
    • public void setKeepAlive(boolean on)

    Two new methods have been added to java.net.Socket and java.net.SocketImpl. This change is to support TCP half-closed sockets:

    • public void shutdownInput()
    • public void shutdownOutput()

  • java.net.URL,java.net.URLConnection, and java.net.ContentHandler

    Several access methods have been added to make java.net.URL consistent with the fields of a URL as described in the latest IETF specification, RFC2396.

    • public String getAuthority()
    • public String getPath()
    • public String getQuery()
    • public String getUserInfo()
    • public set(String protocol, String host, int port, String authority, String userInfo, String path, String query, String ref)

    An overloaded getContent() method was added to java.net.URL, java.net.URLConnection, and java.net.ContentHandler to allow requesting that the returned content object support one of an ordered list of Java types. This allows mapping of MIME types to more than one possible Java type, and improves system flexibility.

    • varied implementation, see javadocs for each class.

    Static methods java.net.URLConnection.setDefaultRequestProperty() and java.net.URLConnection.getDefaultRequestProperty() are now deprecated.

  • java.net.URLDecoder

    The method java.net.URLDecoder.decode(String) no longer throws an exception.

  • java.net.URLStreamHandler

    Several new methods have been added to java.net.URLStreamHandler.

    These additions expose the concept of a handler's default port number and allow URL handlers to override aspects of URL equality and hashcode comparisons in URL protocol-specific ways. These changes enable cleaner access to the parsed component parts of a URL and enhance the ability of the various URL handlers to share common parsing code.

    • protected boolean equals(URL u1, URL u2)
    • protected getDefaultPort()
    • protected InetAddress getHostAddress(URL u)
    • protected int hashCode(URL u)
    • protected boolean hostsEqual(URL u1, URL u2)
    • protected boolean sameFile(URL u1, URL u2)
    • protected void setURL(URL u, String protocol, String host, int port, String authority, String userInfo, String path, String query, String ref)

  • java.util.jar.JarFile and java.util.zip.ZipFile

    There is a new open mode for java.util.zip.ZipFile and java.util.jar.JarFile, which automatically deletes temporary (cached) files associated with each JarURLConnection when the Zip/Jar file opened in this mode is closed and the process exits. This is useful when downloading temporary jar files onto a local disk.

Miscellaneous Information

  • Added HTTP 1.1 client-side support and enhancements, such as http keepalives.
  • The SDK now does a better job of URL parsing by following RFC 2396 much more closely.

Copyright © 1996-99 Sun Microsystems, Inc. All Rights Reserved.

 Sun Microsystems, Inc
Java Software


Networking Features

Java

Networking
New Features and Enhancements

 Documentation Contents

IPv6 (Internet Protocol version 6)

J2SETM 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 © 2001 Sun Microsystems, Inc. All Rights Reserved.

 Sun Microsystems, Inc
Java Software


Extending Sockets in JDK 1.1

Duke icon 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();
    ...
    }
    ...
}

Last Modified: 21 August, 1996
David Brownell
David Brown


Networking Features

 Documentation Contents

New Features and Enhancements

  • Changes and Enhancements in version 1.4.2.

  • New Features and Enhancements in version 1.4.

  • Networking Release Notes for version 1.4.2.

  • Previous changes and enhancements made in version 1.3.

Guides

For completeness, this section includes documentation related to changes to the java.net package made previously in the Java 1.1 platform:

  • Networking Overview (also available in PDF)
    Overview of networking facilities in java.net, including Addressing, Making TCP Connections, Sending/Receiving Datagram Packets via UDP, Locating/Identifying Network Resources, and Security.

  • IPv6 Support (also available in PDF)
    IPv6 support, including special IPv6 address types and dual-stack node.

  • Networking Properties
    Descriptions of properties used by networking

  • Extendable Socket and ServerSocket
    The design, rationale, and how to do it

  • Socket Options
    Support for popular BSD-style options in the java base classes

  • Socket Exceptions
    Subclasses of SocketException for finer granularity of handling network errors

  • Miscellaneous
    Important bug fixes, new constructors, new methods, and more

Networking API Reference

  • java.net Package
  • javax.net Package
  • javax.net.ssl Package

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

 Sun Microsystems, Inc
Java Software


Miscellaneous changes to java.net

Miscellaneous changes to java.net worth mentioning:

Noteworthy bug fixes:

  • InetAddress
    A bug existed in JDK1.0.2 where one could not create an InetAddress out of a IP address String (e.g., "206.26.48.100") if a corresponding host name (e.g., "java.sun.com") could not be found. This resulted in an UnknownHostException. The bug is fixed in JDK1.1. Additionally, when an InetAddress is created from an IP address, the corresponding hostname is not looked up until specifically requested (via InetAddress.getHostName()), as a performance enhancement.
  • ServerSocket/DatagramSocket close()
    A bug existed in JDK1.0.2 where the close() method of ServerSocket and DatagramSocket were synchronized. The result was that if one thread were blocked indefinitely in DatagramSocket.receive() or ServerSocket.accept(), another thread couldn't break the blocking thread out by calling close(). This is fixed in JDK1.1 by making the close() methods unsynchronized.
  • URLConnection
    There was a bug in JDK1.0.2 where the methods on URLConnection:
    • setRequestProperty()
    • getRequestProperty()
    • getHeaderField()
    • getHeaderFieldInt()
    • getContentLength()
    • getDate()
    etc, did not work. These are fixed in JDK1.1.

Binding to local port/address:

  • Socket, ServerSocket, DatagramSocket
    These classes has overloaded constructors for binding to a specific local address and port. This is useful and necessary for applications like proxy servers that operate on multi-homed machines, and need particular control over which network interfaces are used.

MulticastSocket:

  • The MulticastSocket class was moved from package sun.net into the core API of java.net.

HttpURLConnection:

  • JDK1.1 introduces a new class, HttpURLConnection which extends URLConnection, and provides additional functionality specific to HTTP:
  • Ability to use all of the request methods with HTTP/1.1, like:
    • GET
    • POST
    • PUT
    • HEAD
    • TRACE
    • DELETE
    • OPTIONS
  • Control over whether to follow HTTP redirects.
David Brown
Last modified: Thu Dec 5 15:09:54 PST


Networking Properties

 Documentation Contents

Java Properties

java.net.preferIPv4Stack (default: false)
If IPv6 is available on the operating system the underlying native socket will be an IPv6 socket. This allows Java(tm) applications to connect too, and accept connections from, both IPv4 and IPv6 hosts.

If an application has a preference to only use IPv4 sockets then this property can be set to true. The implication is that the application will not be able to communicate with IPv6 hosts.

java.net.preferIPv6Addresses (default: false)
If IPv6 is available on the operating system the default preference is to prefer an IPv4-mapped address over an IPv6 address. This is for backward compatibility reasons - for example applications that depend on access to an IPv4 only service or applications that depend on the %d.%d.%d.%d representation of an IP address. This property can be set to try to change the preferences to use IPv6 addresses over IPv4 addresses. This allows applications to be tested and deployed in environments where the application is expected to connect to IPv6 services.

networkaddress.cache.ttl (default: -1)
Specified in java.security to indicate the caching policy for successful name lookups from the name service.. The value is specified as as integer to indicate the number of seconds to cache the successful lookup.

A value of -1 indicates "cache forever".

networkaddress.cache.negative.ttl (default: 10)
Specified in java.security to indicate the caching policy for un-successful name lookups from the name service.. The value is specified as as integer to indicate the number of seconds to cache the failure for un-successful lookups.

A value of 0 indicates "never cache". A value of -1 indicates "cache forever".

http.proxyHost (default: <none>)
http.proxyPort (default: 80 if http.proxyHost specified)
http.nonProxyHosts (default: <none>

ftp.proxyHost (default: <none>)
ftp.proxyPort (default: 80 if ftp.proxyHost specified)
ftp.nonProxyHosts (default: <none>)

http.proxyHost and http.proxyPort indicate the proxy server and port that the http protocol handler will use.

http.nonProxyHosts indicates the hosts which should be connected too directly and not through the proxy server. The value can be a list of hosts, each seperated by a |, and in addition a wildcard character (*) can be used for matching. For example: -Dhttp.nonProxyHosts="*.foo.com|localhost".

ftp.proxyHost and ftp.proxyPort indicate the proxy server and port that the ftp protocol handler will use. ftp.nonProxyHosts is similiar to http.nonProxyHosts and indicates the hosts that should be connected too directly and not through the proxy server.

http.agent (default: Java1.4.0)

Indicates the User-Agent request header sent in http requests.

http.auth.digest.validateServer (default: false)
http.auth.digest.validateProxy (default: false)
http.auth.digest.cnonceRepeat (default: 5)
These system properties modify the behavior of the HTTP digest authentication mechanism. Digest authentication provides a limited ability for the server to authenticate itself to the client (ie. by proving that it knows the users password). However, not all servers support this capability and by default the check is switched off. The first two properties above can be set to true, to enforce this check, for either authentication with an origin, or a proxy server respectively.

It is not normally necessary to set the third property (http.auth.digest.cnonceRepeat). This determines how many times a cnonce value is reused. This can be useful when the MD5-sess algorithm is being used. Increasing the value reduces the computational overhead on both the client and the server by reducing the amount of material that has to be hashed for each HTTP request.

http.auth.ntlm.domain:
NTLM authentication is supported on Windows platforms only (due to licensing restrictions). Similar to other HTTP authentication schemes, NTLM uses the java.net.Authenticator class to acquire usernames and passwords when they are needed. However, NTLM also needs the NT domain name. 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.keepAlive (default: true)
Indicates if keep alive (persistent) connections should be supported. Persistent connections improve performance by allowing the underlying socket connection be reused for multiple http requests.

The default is true and thus persistent connections will be used with http 1.1 servers. Set to 'false' to disable the use of persistent connections.

http.maxConnections (default: 5)
If HTTP keep-alive is enabled, this value is the number of idle connections that will be simultaneously kept alive, per-destination.

SOCKS protocol support settings
The SOCKS username and password are acquired in the following way. First, if the application has registered a java.net.Authenticator default instance, then this will be queried with the protocol set to the string "SOCKS5", and the prompt set to to the string "SOCKS authentication". If the authenticator does not return a username/password or if no authenticator is registered then the system checks for the user preferences "java.net.socks.username" and "java.net.socks.password". If these preferences do not exist, then the system property "user.name" is checked for a username. In this case, no password is supplied.
socksProxyHost
socksProxyPort (default: 1080)
Indicates the name of the SOCKS proxy server and the port number that will be used by the SOCKS protocol layer. If socksProxyHost is specified then all TCP sockets will use the SOCKS proxy server to establish a connection or accept one. The SOCKS proxy server can either be a SOCKS v4 or v5 server and it has to allow for unauthenticated connections.

Sun implementation-specific properties

These properties may not be supported in future releases.
sun.net.inetaddr.ttl
This is a sun private system property which corresponds to networkaddress.cache.ttl. It takes the same value and has the same meaning, but can be set as a command-line option. However, the preferred way is to use the security property mentioned above.

sun.net.inetaddr.negative.ttl
This is a sun private system property which corresponds to networkaddress.cache.negative.ttl. It takes the same value and has the same meaning, but can be set as a command-line option. However, the preferred way is to use the security property mentioned above.

sun.net.client.defaultConnectTimeout (default: -1)
sun.net.client.defaultReadTimeout (default: -1)
These properties specify the default connect and read timeout (resp.) for the protocol handler used by java.net.URLConnection.

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 connection it is the timeout when establishing the connection to ftp servers.

sun.net.client.defaultReadTimeout specifies the timeout (in milliseconds) when reading from input stream when a connection is established to a resource.

JNDI DNS service provider settings
These properties may not be supported in future releases.
sun.net.spi.nameservice.provider.<n>=<default|dns,sun|...>
Specifies the name service provider that you can use. By default, Java will use the system configured name lookup mechanism, such as file, nis, etc. You can specify your own by setting this option. takes the value of a positive number, it indicates the precedence order with a small number takes higher precendence over a bigger number. In J2SETM 1.4, we have provided one DNS name service provider through JNDI, which is called "dns,sun".

sun.net.spi.nameservice.nameservers=<server1_ipaddr,server2_ipaddr ...>
You can specify a comma separated list of IP addresses that point to the DNS servers you want to use. If the sun.net.spi.nameservice.nameservers property is not defined, then the provider will use any name servers already configured in the platform DNS configuration.

sun.net.spi.nameservice.domain=<domainname>
This property specifies the default DNS domain name, for instance, eng.sun.com. If the sun.net.spi.nameservice.domain property is not defined then the provider will use any domain or domain search list configured in the platform DNS configuration.

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

 Sun Microsystems, Inc


Networking Release Notes
The following are known bugs and other networking issues for JavaTM 2 SDK, Standard Edition, v1.4.2.
  • In releases prior to 1.4.2, it was possible to create an invalid URL instance such as the following: new URL ("http://www.foo.com:-1/index.html"). Specifying a port number of -1 is not valid. However, in previous releases the -1 was stripped off when sending such URLS with HTTP commands. In 1.4.2, the -1 is left in the URL and this may cause problems for some HTTP servers or proxies. Applications should not create URL instances with a -1 port number. Assuming the -1 refers to the default port in this example, the correct way to create this URL is new URL ("http://www.foo.com/index.html"). This note only applies to the single argument URL constructor.
  • On Microsoft Windows 98/ME, a read timeout set using Socket.setSoTimeout or an accept timeout set using ServerSocket.setSoTimeout may result in a timeout that is 500ms later than expected. This issue is observable with all J2SE releases and stems from a Microsoft Windows 98/ME bug. A patch for Microsoft Windows 98/ME is obtainable through the following page on the Microsoft website: http://support.microsoft.com/default.aspx?scid=KB;EN-US;Q257821&
  • Prior to J2SE 1.4.1 the java.net.InetAddress.getLocalHost() would cache the lookup of the IP address of the local machine for the entire session of the application. This behaviour poses a problem for applications running on machines that are connected to the internet via a dial-up connection or machines that acquired their addresses through DHCP. This has been corrected in 1.4.1 so that the local IP address is no longer cached. InetAddress.getLocalHost() will return the correct IP address for dial-up connections as well as for DHCP. See bug 4211819.
  • Prior to J2SE 1.4.1, the http/https protocol handlers would not redirect correctly from a http URL to a https URL (and vice versa). In particular, the redirect was attempted using the original URL scheme. This has been fixed in 1.4.1. by returning the server responses for such redirects (from http to https or https to http) to the application. Therefore, it is the applications responsibility 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. See bug 4620571.
  • Prior to J2SE 1.4 the java.net.URLConnection class would handle errors from http servers inconsistently. In particular the getInputStream or other methods would throw a FileNotFoundException if the http server returned a response code >= 400 and the request was for a resource of a known file type.

    This has been corrected in 1.4 so that an IOException is thrown for any http error from the server and a specific exception of FileNotFoundExeption when the resource is not found (ie: 404 or 410 response codes). The exception is thrown irrespective of the file type.

    Applications that assumed an exception would not be thrown when an http error is returned from the server need to be aware of this change in 1.4 - see 4160499.

    Related to this issue is that HttpURLConnection.getErrorStream() method can now been used to read the error page from the http server when a http error is returned from the server. Previously getErrorStream() always returned null.

  • Prior to J2SE 1.4 the InetAddress.toString() would perform a lookup via the name service if the hostname wasn't previously resolved. This is no longer the case in 1.4 and toString will return immediately. If the hostname is not resolved the returned string will contain the dotted IP address only.

    Applications that depend on toString() returning a string with the resolved hostname should be aware of this correction in 1.4 - see 4239141.

  • Prior to J2SE 1.4 if InetAddress.getByName if a lookup to the name service failed then all subsequent lookups of that hostname would fail for the lifetime of the virtual machine. This arose because negative lookups were always cached. This has changed in 1.4 so that by default if a lookup fails it's possible for a subsequent lookup to succeed. This is particularly important in dial-up environments or environments where the name service is not reliable.

    Applications that depend on behaviour where subsequent lookups always failed need to be aware of this issue - see 4256129. In addition the caching of negative lookups can be controlled by the networkaddress.cache.negative.ttl property in the java.security file.

  • Java 2 Platform, Standard Edition, v1.4 introduces a new exception java.net.PortUnreachableException. This exception may be thrown by DatagramSocket.send or DatagramSocket.receive if the DatagramSocket is connected (via the connect method) and an ICMP port unreachable is received to indicate that the remote application is not running. The PortUnreachableException serves as a useful indication for some UDP based protocols.

    The following lists the known issues with PortUnreachableException :-

    1. On Solaris 8 if IPv6 is enabled then ICMP port unreachable packets from IPv4 hosts will appear to be discarded. This is a Solaris 8 bug and is tracked as bug 4422658.
    2. On some Microsoft Windows releases (specifically Windows 98 and Windows NT) ICMP port unreachable packets are incorrectly discarded by the operating system and thus the PortUnreachableException is not thrown. As this time we are not aware of any Windows Sockets updates from Microsoft to fix this issue.
    3. On Linux if UDP packets are sent to the loopback address and no UDP applicatiob to bound to the destination port no ICMP port unreachable indication is received and thus no PortUnreachableException is thrown. This is a Linux kernel issue and we are not aware of a patch at this time.
  • On many Linux installations InetAddress.getLocalHost() may return an InetAddress representing the loopback address (127.0.0.1). This stems from many Linux installations configuring /etc/hosts to map the hostname to the loopback address. If the host has a static IP address then the /etc/hosts file should be corrected to map the hostname to the host address.

    If DHCP is used in conjunction with dynamic DNS then there are two options (i) change the name service search order in /etc/nsswitch.conf to use dns before the hosts file (ie: "hosts: dns files"), or (ii) configure InetAddress to use the DNS name service provider instead of the default provider (-Dsun.net.spi.nameservice.provider.1=dns,sun). This issue is being tracked in 4665037.

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

 Sun


New SocketExceptions in JDK1.1

Duke icon 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
    }

    David Brown


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.


Networking IPv6 User Guide

Networking IPv6 User Guide for J2SDK/JRE 1.4

This document covers the following topics:

  • Overview
  • Supported Operating Systems
  • Special IPv6 Address Types
  • IPv6-Related System Properties
  • Dual-Stack Node
  • Java Application Impact
  • IPv6 Networking Properties

Overview

With the J2SDK/JRE 1.4 release, IPv6 support has been added to Java Networking. This will make J2SE compliant with the following standards (RFCs):

  • RFC2373: IPv6 Addressing Architecture;
  • RFC 2553: BasicSocket Interface Extensions for IPv6;
  • RFC 2732: Format for Literal IPv6 Addresses in URLs.

Since the J2SDK does not support raw sockets, RFC 2292 (: Advanced Sockets API for IPv6) is not supported in this release.

Other interesting features of IPv6, such as tunneling, autoconfiguration of addresses, mobile IP, etc., are not supported at the Java API level, as they are handled automatically by the underlying OS or system support.

Supported Operating Systems

The following operating systems are supported in this release:

  • Solaris 8 and up
  • Linux kernel 2.1.2 and up (RedHat 6.1 and up)

Notes on Linux

  1. It is recommended to use Linux kernel 2.4.0 and higher releases, as IPv6 support is better in those releases.
  2. With Linux, you need to install an IPv6-enabled kernel or rebuild the kernel with IPv6 options enabled. (Up until Kernel 2.4.2, the IPv6 implementation is marked as "experimental.") In addition, you will need to install several network utilities. For detailed information, refer to http://www.bieringer.de/linux/IPv6/IPv6-HOWTO/IPv6-HOWTO.html

Notes on Windows

J2SETM 1.4 does not support IPv6 on Microsoft Windows. Microsoft has released an IPv6 Technology Previous for Windows 2000 but this is a limited seperate stack implementation. A complete dual IPv4/IPv6 stack implementation for Microsoft Windows is not expected to be released until 2002 or later.

Special IPv6 Address Types

Unspecified address (:: corresponding to 0.0.0.0 in IPv4)

This is also called anylocal or wildcard address. If a socket is bound to an IPv6 anylocal address on a dual-stack machine, it can accept both IPv6 and IPv4 traffic; if it is bound to an IPv4 (IPv4-mapped) anylocal address, it can only accept IPv4 traffic. We always try to bind to IPv6 anylocal address on a dual-stack machine unless a related system property is set to use IPv4 Stack.

When bound to ::, method ServerSocket.accept will accept connections from both IPv6 or IPv4 hosts. The Java platform API currently has no way to specify to accept connections only from IPv6 hosts.

Applications can enumerate the interfaces using NetworkInterface and bind a ServerSocketChannel to each IPv6 address, and then use a selector from the New I/O API to accept connections from these sockets.

Note: The option discussed below is introduced in Draft-ietf-ipngwg-rfc2553bis-03.txt. It will be supported in the Java 2 platform when it becomes a standard.

However, there is a new socket option that changes the above behaviour. Draft-ietf-ipngwg-rfc2553bis-03.txt has introduced a new IP level socket option, IPV6_V6ONLY. This socket option restricts AF_INET6 sockets to IPv6 communications only. Normally, AF_INET6 sockets may be used for both IPv4 and IPv6 communications. Some applications may want to restrict their use of an AF_INET6 socket to IPv6 communications only. For these applications the IPV6_V6ONLY socket option is defined. When this option is turned on, the socket can be used to send and receive IPv6 packets only. By default this option is turned off.

Loopback address (::1 corresponding to 127.0.0.1 in IPv4)

Packets with the loopback address must never be sent on a link or forwarded by an IPv6 router. There are two separate loopback addresses for IPv4 and IPv6 and they are treated as such.

IPv4 and IPv6 addresses are separate address spaces except when it comes to "::".

Compatibility address ::w.x.y.z

This is used for hosts and routers to dynamically tunnel IPv6 packets over IPv4 routing infrastructure. It is meaningful for OS kernel and routers. Java provides a utility method to test it.

IPv4-mapped address ::ffff:w.x.y.z

This is an IPv6 address that is used to represent an IPv4 address. It allows the native program to use the same address data structure and also the same socket when communicating with both IPv4 and IPv6 nodes. Thus, on a dual-stack node with IPv4-mapped address support, an IPv6 application can talk to both IPv4 and IPv6 peer. The OS will do the underlying plumbing required to send or receive an IPv4 datagram and to hand it to an IPv6 destination socket, and it will synthesize an IPv4-mapped IPv6 address when needed.

For Java, it is used for internal representation; it has no functional role. Java will never return an IPv4-mapped address. It understands IPv4-mapped address syntax, both in byte array and text representation. However, it will be converted into an IPv4 address.

IPv6-Related System Properties

On dual stack machines, system properties are provided for setting the preferred protocol stack—IPv4 or IPv6—as well as the preferred
address family types—inet4 or inet6.

IPv6 stack is preferred by default, since on a dual-stack machine IPv6 socket can talk to both IPv4 and IPv6 peers.

This setting can be changed through the java.net.preferIPv4Stack=<true|false> system property.

By default, we would prefer IPv4 addresses over IPv6 addresses, i.e., when querying the name service (e.g., DNS service), we would return Ipv4 addresses ahead of IPv6 addresses. There are two reasons for this choice:

  1. There are some applications that expect an IPv4 address textual format, i.e. "%d.%d.%d.%d". Using an IPv4 address minimizes the surprises;
  2. Using IPv4 address, we can use one call (with an IPv6 socket) to reach either a legacy IPv4-only service, or an IPv6 service (unless the IPv6 service is on a Ipv6 only node).

This setting can be changed through the system property java.net.preferIPv6Addresses=<true|false>

Dual-Stack Node

For many years, if not forever, there will be a mix of IPv6 and IPv4 nodes on the Internet. Thus compatibility with the large installed base of IPv4 nodes is crucial for the success of the transition from IPv4 to IPv6. Dual stack, defined in RFC 1933, is one of the main mechanisms for guaranteeing a smooth transition. The other mechanism is IPv6 packet tunneling, which is relevant to the J2SDK only through the IPv4-compatible address. The former is the most relevant piece to the J2SDK. A dual stack includes implementations of both versions of the Internet Protocol, IPv4 and IPv6.

A general property of a dual-stack node is that an IPv6 socket can communicate both with an IPv4 and IPv6 peer at the transport layer (TCP or UDP) . At the native level, the IPv6 socket communicates with an IPv4 peer through an IPv4-mapped IPv6 address. However, unless a socket checks for the peers address type, it won't know whether it is talking to an IPv4 or an IPv6 peer. All the internal plumbing and conversion of address types is done by the dual-protocol stack.

Note: IPv4-mapped address has significance only at the implementation of a dual-protocol stack. It is used to fake (i.e., appear in the same format as) an Ipv6 address to be handed over to an IPv6 socket. At the conceptual level it has no role; its role is limited at the Java API level. Parsing of an IPv4-mapped address is supported, but an IPv4-mapped address is never returned.

Java Application Impact

  1. There should be no change in Java application code if everything has been done appropriately. I.e., there are no direct references to IPv4 literal addresses; instead, hostnames are used.
  2. All the address or socket type information is encapsulated in the Java networking API.
  3. Through setting system properties, address type and/or socket type preferences can be set.
  4. For new applications Ipv6-specific new classes and APIs can be used.

communication scenarios:

(Nodes) | V4 Only | V4/V6 | V6 Only
V4 Only | x | x |
V4/V6 | x | x | x
V6 Only |  | x | x

Top row and left column represent various node types attempting to communicate. An x indicates that these nodes can communicate with each other.

UDP
scenario 1:

Either host1 or host2 can be a native application.

host1 is server, host2 is client

If host2 wants to talk to host1, it will create a V6 socket. It then looks up the IP address for host1. Since host1 only has a v4 protocol stack, it will only have IPv4 records in the name lookup service. So host2 will try to reach host1 using an IPv4-mapped address. An IPv4 packet will be sent by host2, and host1 will think it is communicating with a v4 client.

host1 is client, host2 is server

If host2 is the server, it will first create a v6-type socket (by default), then it will wait for connections. Since host1 supports v4 only, it creates a v4-type socket. They resolves the name for host2. It only gets v4 address for host2, since it doesn't understand IPv6 address. So it connects to host2 using v4 address. A v4 packet will be sent on the wire. On host2, the dual stack will convert the v4 packet into a v6 packet with a v4-mapped address in it and hand it over to the v6 socket. The server application will handle it as if it is a connection from a v6 node.

Class Changes

InetAddress

This class represents an IP address. It provides address storage, name-address translation methods, address conversion methods, as well as address testing methods. In J2SE 1.4, this class is extended to support both IPv4 and IPv6 addresses. Utility methods are added to check address types and scopes. The two types of addresses, IPv4 and IPv6, can be distinguished by the Java type Inet4Address and Inet6Address.

Two new subclasses of InetAddress are created: Inet4Address and Inet6Address. V4- and V6-specific state and behaviors are implemented in these two subclasses. Due to Java's object-oriented nature, an application normally only needs to deal with InetAddress class—through polymorphism it will get the correct behavior. Only when it needs to access protocol-family-specific behaviors, such as in calling an IPv6-only method, or when it cares to know the class types of the IP address, will it ever become aware of Inet4Address and Inet6Address.

The new methods introduced are:

InetAddress:
isAnyLocalAddress
isLoopbackAddress
isLinkLocalAddress
isSiteLocalAddress
isMCGlobal
isMCNodeLocal
isMCLinkLocal
isMCSiteLocal
isMCOrgLocal
getCanonicalHostName
getByAddr

Inet6Address:
isIPv4CompatibleAddress

InetAddress and Different Naming services

Prior to 1.4, InetAddress utilized the system configured name service to resolve host names. In 1.4, we have added a Java DNS provider through JNDI for alternative name lookups. You can tell the J2SDK to use this provider by setting up a few system properties. These system properties are documented in the Java system properties section. In the future, we plan to provide a generic service provider framework so that you can write your own name service providers.

A Word on Serialization

All IPv4 addresses are represented in Java as Inet4Address objects. They are serialized as InetAddress objects, and deserialized from InetAddress to Inet4Address to keep backward compatibility. IPv6 addresses are represented as Inet6Address and are serialized as such.

Socket, ServerSocket, and DatagramSocket

Due to the object-oriented nature of Java, the address types and storage structures are not exposed at the socket API level, so no new APIs are needed. The existing socket APIs handle both IPv4 and IPv6 traffic.

The selection of which stack to use depends upon the following:

  1. The underlying OS support;
  2. The user's stack preference property setting.

All supported Ipv6 socket options have a IPv4 counterparts. Thus no new APIs were added to support IPv6 socket options. Instead, the old APIs are overloaded to support both V4 and V6 socket options.

MulticastSocket

Again all the socket options APIs are overloaded to support IPv6 multicast socket options.

We have added two new APIs to set/get network interfaces in addition to the existing MulticastSocket.setInterface/MulticastSocket.getInterface that takes/returns an InetAddress instance. The two existing methods are used to set or retrieve the network interface used by the current MulticastSocket to send multicast packets (i.e., equivalent to IP_MULTICAST_IF in native socket option). For IPv4, the interface was indicated by an IP address. Thus we can use the equivalent InetAddress in Java. They will continue to work with IPv6 multicast socket. However, in IPv6, according to RFC 2553, the interface should be indicated using an interface index. To better support the concept of a network interface, we introduced a new class, NetworkInterface. It encapsulate the data representing the state of the network interface, including name and IP addresses and some basic manipulation methods. Thus we have introduced two new methods for setting the outgoing interface for multicast socket: setNetworkInterface and getNetworkInterface. They take or return a NetworkInterface object. These new methods can be used with both v4 and v6 multicast.

Methods have also been added for joining and leaving a multicast group on a network interface. This was previously unavailable in the Java API.

MulticastSocket:
NetworkInterface getNetworkInterface()
setNetworkInterface(NetworkInterface netIf)
joinGroup(SocketAddress mcastaddr,NetworkInterface netIf)
leaveGroup(SocketAddress mcastaddr,NetworkInterface netIf)

URL, URI parsers

Literal IP addresses can be used in URL/URIs. However, since colon (:) is used in existing URL/URI specifications to separate host from port, using literal IPv6 representation in URL/URIs without modification will fail in parsing. Thus for specifying literal IPv6 addresses in URL/URIs, RFC 2732 was created. The parsing of URL/URI has been updated to be compliant with RFC 2732.

SocketPermission

Since SocketPermission utilizes URLs, its implementation has been updated to be compliant with RFC 2732.

codebase, used in defining a permission, is a variant of URL. As such, it should follow URL formats and conventions. RFC 2732 format is used for URL and codebase; RFC 2373 format is used everywhere else.

IPv6 Networking Properties

java.net.preferIPv4Stack (default: false)

If IPv6 is available on the operating system, the underlying native socket will be an IPv6 socket. This allows Java(tm) applications to connect too, and accept connections from, both IPv4 andIPv6 hosts.

If an application has a preference to only use IPv4 sockets, then this property can be set to true. The implication is that the application will not be able to communicate with IPv6 hosts.

java.net.preferIPv6Addresses (default: false)

If IPv6 is available on the operating system, the default preference is to prefer an IPv4-mapped address over an IPv6 address. This is for backward compatibility reasons—for example, applications that depend on access to an IPv4-only service, or applications that depend on the %d.%d.%d.%d representation of an IP address.
This property can be set to try to change the preferences to use IPv6 addresses over IPv4 addresses. This allows applications to be tested and deployed in environments where the application is expected to connect to IPv6 services.

JNDI DNS service provider settings:

sun.net.spi.nameservice.provider.<n>=<default|dns,sun|...>

Specifies the name service provider that you can use. By default, Java will use the system-configured, name-lookup mechanism, such as file, nis, etc. You can specify your own by setting this option. <n> takes the value of a positive number and it indicates the precedence order: a small number takes higher precendence over a bigger number. In 1.4 , we have provided one DNS name service provider through JNDI, which is called dns,sun.

sun.net.spi.nameservice.nameservers=<server1_ipaddr,server2_ipaddr ...>

You can specify a comma separated list of IP addresses that point to the DNS servers you want to use.

sun.net.spi.nameservice.domain=<domainname>

This property specifies the default DNS domain name, e.g., eng.sun.com.


Networking Overview

Java Networking Overview

The Java Networking API (java.net) provides the interfaces/classes for the following functions:

  • Addressing
  • Making TCP connections
  • Sending/Receiving Datagram Packets via UDP
  • Locating/Identifying Network Resources
  • Security
    • Authentication
    • Permissions

The goal of this document is to provide a high-level overview of the facilities the java.net package provides. For details about interfaces, classes, or factories, see the networking API. For basic networking concepts, see Trail: Custom Networking in the Java Tutorial.

Addressing

java.net provides the following addressing-related classes:

  • InetAddress
  • Inet4Address
  • Inet6Address
  • SocketAddress
  • InetSocketAddress

For IP addressing, three classes are provided: InetAddress, Inet4Address, and Inet6Address. InetAddress represents an IP address, which is either a 32- or 128-bit unsigned number used by IP, the lower-level protocol on which protocols like TCP and UDP are built. To represent 32-bit IPv4 address, Inet4Address is provided. (An IPv4 address has the familiar form nnn.nnn.nnn.nnn, where n is an integer; e.g., 129.250.35.250). It is a subclass of InetAddress. To represent 128-bit IPv6 addresses, Inet6Address is provided. It is also a subclass of InetAddress.

Flow chart showing the logic flows from InetAddress to Inet4Address and Inet6Address

For socket addressing, two classes are provided: SocketAddress and InetSocketAddress. SocketAddress is an abstract socket address, independent of a specific protocol. It is intended for subclassing for a specific protocol. InetSocketAddress below is an example. InetSocketAddress is a subclass of SocketAddress; it represents an IP socket address. It can include an IP address (e.g., 129.250.35.250) and port (e.g., 80); a hostname (e.g., coastnews.com) and port (e.g., 1000); or port only (e.g., 1010). In the latter case, a wildcard IP address is assumed.

Diagram showing the logic flows between SocketAddress and InetSocketAddress

Making TCP Connections

These classes are related to making normal TCP connections:

  • ServerSocket
  • Socket

For simple connections between a client and a server, ServerSocket and Socket are all that you will probably need.

ServerSocket represents the socket on a server that waits and listens for requests for service from a client. Socket represents the endpoints for communication between a server and a client. When a server gets a request for service, it creates a Socket for communication with the client and continues to listen for other requests on the ServerSocket. The client also creates a Socket for communication with the server. The sequence is shown below:

See long description [D]

Once the connection is established, getInputStream() and getOutputSteam() may be used in communication between the sockets

Sending/Receiving Datagram Packets via UDP

The following are related to sending and receiving datagram packets via UDP.

  • DatagramPacket
  • DatagramSocket

DatagramPacket represents a datagram packet. Datagram packets are used for connectionless delivery and normally include destination address and port information. DatagramSocket is a socket used for sending and receiving datagram packets over a network via UDP. A DatagramPacket is sent from a DatagramSocket by calling the send(...) method of DatagramSocket with DatagramPacket as the argument: send(DatagramPacket dp). receive(DatagramPacket dp) is use for receiving a DatagramPacket. (The MulticastSocket class may be used for sending/receiving a DatagramPacket to a mulitcast group. It is a subclass of DatagramSocket that adds functionality for multicasting.)

See long description [D]

Locating/Identifying Network Resources

These classes are related to locating or identifying network resources:

  • URI
  • URL
  • URLClassLoader
  • URLConnection
  • URLStreamHandler
  • HttpURLConnection
  • JarURLConnection

The most commonly used classes are URI, URL, URLConnection, and HttpURLConnection.

URI represents a Uniform Resource Identifier for a resource; it is an identifier for a resource but not necessarily a locator for that resource. URL represents a Uniform Resource Locator for a resource. URLs are a subset of URIs, though the class URL is not a subclass of the URI class. In short, a URL tells how to access the resource, while a URI may or may not. The Uniform Resource Name (URN) is another subset of URI. No Java class exists for it.

Diagram showing URL and URN as subclasses of URI.

URLConnection is the abstract superclass of all classes that represent a connection between an application and a network resource identified by a URL. Given a URL and hence a protocol, URL.openConnection() returns an instance of the appropriate implementation of URLConnection for the protocol. (The protocol is known from the URL.) The instance provides the means—URLConnection.connect()—to actually open the connection and access the URL.

See long description [D]

HttpURLConnection is the most commonly used implementation of URLConnection. It is for http protocol, the protocol used for accessing content on web servers. In the above diagram, if the access protocol for the URL were http, then an instance of HttpURLConnection would be returned by the openConnection() method.

Security

Security includes authentication- and permissions-related classes. Authentication relates to user authentication and involves username and password checking. Authentication of a user may be required in a number of situations, such as when a user tries to access a URL. Permissions relate to what actions may be performed; e.g., unless the NetPermission object "setDefaultAuthenticator" exists, then invoking the method Authenticator.setDefault(Authenticator a) will cause a security exception.

Authentication

Some proxies and origin servers require authentication information, using authentication schemes such as BASIC and DIGEST. For instance, when connecting with http via a proxy and the proxy requires authentication, we call the Authenticator class to obtain usernames, passwords, and other items needed to authenticate. The following classes relate to authentication:

  • Authenticator
  • PasswordAuthentication

In addition to methods for user authentication, the abstract class Authenticator also has methods for querying about the authentication being requested (see getRequestingXXX()). It is typically subclassed and an instance of the subclass is registered with the system by calling setDefault(Authenticator a). (Note that if there is a security manager, it checks to see that the security policy permits the NetPermission "setDefaultAthenticator".) Then, when the system requires authentication, it will call a method such as requestPasswordAuthentication().

PasswordAuthentication is simply a data holder for a user name and a password.

Permissions

  • SocketPermission
  • NetPermission

A SocketPermission consists of a host, with optional port range, and a set of actions that may be performed on that host—connect, accept, listen and/or resolve. It includes methods to determine if one SocketPermission is equal to another or implies another Permission. A SocketPermission may be included in a PermissionCollection for easy checking if a permission exists.

NetPermission is a class for various named network permissions. Currently there are three: setDefaultAuthenticator, as mentioned above; requestPasswordAuthentication; and specifyStreamHandler. A NetPermission may be included in a PermissionCollection for easy checking if a permission exists.

For more information about permissions, see http://java.sun.com/j2se/1.4/docs/guide/security/permissions.html.


New I/O APIs

 Documentation Contents
The new I/O (NIO) APIs introduced in v 1.4 provide new features and improved performance in the areas of buffer management, scalable network and file I/O, character-set support, and regular-expression matching. The NIO APIs supplement the I/O facilities in the java.io package.

Features

The NIO APIs include the following features:
  • Buffers for data of primitive types
  • Character-set encoders and decoders
  • A pattern-matching facility based on Perl-style regular expressions
  • Channels, a new primitive I/O abstraction
  • A file interface that supports locks and memory mapping
  • A multiplexed, non-blocking I/O facility for writing scalable servers

Examples

  • NIO Examples

API References

New packages, classes, and interfaces:
  • java.nio package: Buffers, which are used throughout the NIO APIs.
  • java.nio.channels package: Channels and selectors.
  • java.nio.charset package: Character encodings.
  • java.nio.channels.spi package: Service-provider classes for channels.
  • java.nio.charset.spi package: Service-provider classes for charsets.
  • java.util.regex package: Classes for matching character sequences against patterns specified by regular expressions.
  • java.lang.CharSequence interface: The interface implemented by objects that can be passed as arguments to methods in the java.util.regex package. The String, StringBuffer, and java.nio.CharBuffer classes implement this interface.

Note: The new InetSocketAddress and SocketAddress classes, while not strictly part of the NIO APIs, are used by them.

Revised classes and interfaces:

  • In the FileInputStream and FileOutputStream classes, getChannel methods have been added to return the underlying FileChannel object, and the close methods have been revised to close the underlying channel.
  • Similarly, in the RandomAccessFile class, a getChannel method has been added and the close method has been revised to close the underlying channel. The RandomAccessFile constructors now support the mode characters "s" and "d" to allow the specification, at file-open time, of synchronous writes or synchronous-data writes.
  • In the InputStreamReader and OutputStreamWriter classes, constructors have been added that take a stream and a Charset object, and the getEncoding methods have been revised to return the historical name of the encoding being used. Constructors to InputStreamReader and OutputStreamWriter have been added that take existing CharsetDecoder and CharsetEncoder objects, respectively.
  • In the String class, two split methods are new. The subSequence method has been added, as required by the CharSequence interface that String now implements. Three additional methods have been added: matches, replaceAll, and replaceFirst.
  • In the StringBuffer class, the subSequence method has been added, as required by the CharSequence interface that StringBuffer now implements.
  • In the Thread class, the interrupt method has been revised to interrupt threads blocked in channel-I/O operations.
  • In the DatagramSocket class, the receive and send methods have been revised to throw a java.nio.channels.IllegalBlockingModeException if the socket has a channel and the channel is in non-blocking mode. The close method now closes the socket's channel, if it has one, and the new getChannel method returns the underlying channel, if any.
  • In the ServerSocket class, the accept and implAccept methods have been revised to throw a java.nio.IllegalBlockingModeException if the socket has a channel and the channel is in non-blocking mode. The getChannel method has been added and close revised, for the same reasons as in DatagramSocket.
  • In the Socket class, the getInputStream and getOutputStream methods have been revised to delegate all I/O operations to the socket's channel, if it has one. The connect methods have been revised to throw a java.nio.IllegalBlockingModeException if the socket has a channel and the channel is in non-blocking mode. The getChannel method has been added and close revised, for the same reasons as in DatagramSocket.

Three new functions have been added to the Java Native Interface (JNI) to support direct buffers. For information, see JNI Enhancements in v 1.4.

For More Information

  • New I/O: Additional Documentation
  • Supported Encodings
  • JSR-51: New I/O APIs for the Java Platform (Note: v 1.4 has a subset of the changes proposed in this specification request.)

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-io@java.sun.com 		Sun
Java Software


NIO Examples

 Documentation Contents
NIO
The examples in the following table show how to use the NIO APIs.

Source File | Description
Grep.java | Searches a list of files for lines that match a given regular-expression pattern. Demonstrates NIO mapped byte buffers, charsets, and regular expressions.
Sum.java | Computes 16-bit checksums for a list of files. Uses NIO mapped byte buffers for speed.
TimeQuery.java | Asks a list of hosts what time it is. Is a simple, blocking program that demonstrates NIO socket channels (connection and reading), buffer handling, charsets, and regular expressions.
TimeServer.java | Listens for connections and tells callers what time it is. Is a simple, blocking program that demonstrates NIO socket channels (accepting and writing), buffer handling, charsets, and regular expressions.
Ping.java | Connects to each of a list of hosts and measures the time required to complete the connection. Uses a selector and two additional threads to demonstrate non-blocking connects and the multithreaded use of a selector.
NBTimeServer.java | Implements a non-blocking Internet time server.

Java logo Copyright © 2001 Sun Microsystems, Inc. All Rights Reserved.


Performance Enhancements

 Documentation Contents
Version 1.4 of the JavaTM 2 SDK and Java 2 Runtime Environment contain many performance enhancements including improvements in startup time, memory footprint, and program execution speed. The most significant performance enhancements are detailed below.
Performance Enhancements
  • Improvements to Program Execution Speed

See Also

  • Improvements to Startup Time and Memory Footprint - These improvements were made in previous release J2SDK 1.3.
  • Performance Documentation for the Java Platform (on java.sun.com web site)
  • Performance and Scalability Guide (on the java.sun.com web site)
  • Performance FAQ (on the java.sun.com web site)
  • Java HotSpot VM Options (on the java.sun.com web site)

*As used on this web site, the terms "Java Virtual Machine" or "JVM" mean a virtual machine for the Java platform.

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: j2se-comments@eng.sun.com 		Sun


Improvements to Program Execution Speed

 Documentation Contents

Enhancements in J2SDK 1.4

The following are some of the enhancements made for improved program execution speed in J2SDK 1.4.
  • J2SDK 1.4 has much improved performance in the area of Java 2DTM 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.

  • 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 New I/O APIs.

  • 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.

  • The networking functionality in J2SDK 1.4 has improved performance for Http streaming.

  • 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).

  • 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 BugParade 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 BugParade 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 BugParade 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 © 2001 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: jdk-comments@eng.sun.com 		Sun


Improvements to Startup Time and Memory Footprint

Java

Improvements to Startup Time
and Memory Footprint

 Documentation Contents
The following are some of the changes and have helped to reduce startup time and decrease the amount of memory used by the JavaTM 2 SDK and Java 2 Runtime Environment.
  • Swing Class Loading - In version 1.3, loading of some Swing classes is delayed until they are actually needed by the runtime environment. In version 1.2, Swing classes were loaded at startup regardless of whether the classes were needed immediately. This change reduces startup time.

  • JAR File Memory Usage Rection - The way JAR files are indexed in memory has been improved so that the memory cost of loading a JAR file has been greatly reduced. The class libraries in rt.jar, for example, occupied about 420 KB of memory when loaded in version 1.2, but require only about 100 KB in version 1.3.

  • JTable - In version 1.3, loading of international date and number formatting code by JTable is deferred until the internationalization code is needed by the runtime environment. In version 1.2, class JTable loaded the intenationalization code at startup, even if it was not needed immediately. This change reduces startup time.

  • Size of DLLs Reduced - In version 1.3, the size of DLL libraries have been reduced in terms of memory footprint (by about 280 KB) and download size (by about 250 KB), with no detrimental effect on execution speed.

  • Remove Dependencies on Seldom-Used DLLs - In version 1.3, DLLs that handle dialog boxes and drag-and-drop functionality are loaded only if they are actually needed. In version 1.2, some of these libraries were loaded at startup regardless of whether they would ever be used. This change reduces startup time.

  • Reduce Memory Footprint Associated with Strings - In version 1.3 of the SDK, java.lang.String has been modified to load the relatively small java.io.ObjectStreamField class for handling serialization requirements. In 1.2, String loaded the much larger java.io.ObjectStreamClass for this purpose.

  • The size of internal VM datastructures used by the client virtual machine have been reduced.

Copyright © 2001 Sun Microsystems, Inc. All Rights Reserved.

 Sun


Java(TM) Plugin Component

Java

The JavaTM Plug-in Component

 Documentation Contents
The JavaTM Plug-in component enables applets written to the Java 2 Platform 1.4 specification to be run in Netscape Navigator and Microsoft Internet Explorer web browsers.
Java Plug-in Developer Guide
The Java Plug-in Developer Guide (also available in PDF) provides documentation in the following areas:
  • Java Plug-in Basics
  • Deployment Schemes
  • Security
  • Debugging Support
  • Advanced Topics
Common DOM API
Applet developers can use the Common DOM API when writing applets that are intended to be run with the Java Plug-in. The Common DOM API enables developers to traverse Document Object Models from within their applets. The Common DOM API is supported only by the Java Plug-in, and it will not work if used in conjunction with applications as opposed to applets, nor will it work in applets that aren't run in the environment provided by the 1.4 Java Plug-in.

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-plugin-feedback@sun.com 		Sun
Java Software


Applet Caching and Installation in Java Plug-in

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

Once an applet it is cached, it no longer needs to be downloaded when referenced again. Thus performance is improved.

This release introduces an alternative form of applet caching, allowing an applet deployer to decide if an applet should be sticky, i.e., 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 new feature is activated by including the new 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 seperated 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.

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.
  • If you get the "java.io.IOException: Caching not supported for ..." exception, this is because Java Plug-in was unable to get the expiration and last-modification dates for a given JAR file from the web server. If the Java Plug-in cannot get this information, there is no point in caching since the JAR file will be downloaded every time it is used. Even with this exception, however, the applet should work fine. This exception is merely informative.


Using the Conventional APPLET Tag

This section includes the following topics:

  • Support for the APPLET Tag
  • Compatibility with the OBJECT Tag
  • Supported Platforms and Browsers
  • Updating Old Class Files
  • Other Enhancements

Support for the APPLET Tag

JavaTM Plug-in now supports the HTML APPLET tag for launching applets. Users may configure their browsers so that Sun's JRE is the default runtime environment for handling APPLET tags.

Notes

  1. Even though Java Plug-in now supports the APPLET tag, it does not support applets that make use of proprietary technologies. Examples of such technologies are:
    • CAB files
    • Authenticode signing
    • Java Moniker
  2. 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.

Compatibility with the OBJECT Tag (Internet Explorer on Windows Platform)

This release of Java Plug-in supports the use of APPLET tags for launching applets. However, it is also fully backward compatible with previous Java Plug-in releases in its support of the OBJECT tag for launching applets in Internet Explorer running on the Windows platform. As before, developers have the option of using the HTML Converter to set up their applet web pages to use the OBJECT tag.

For more information about using OBJECT tags to launch applets on Java Plug-in, see Using OBJECT, EMBED and APPLET Tags in Java Plug-in and Using the HTML Converter to Convert Applet Tags for Java Plug-in.

Supported Platforms and Browsers

The support for the APPLET tag in Java Plug-in is intended for use on the following operating systems:
  • Windows 95
  • Windows 98 (1st and 2nd editions)
  • Windows ME
  • Windows NT 4.0
  • Windows 2000
  • Windows XP
  • Unix
  • Linux

Java Plug-in provides support for the APPLET tag on the following web browsers:

  • Internet Explorer 4.0 (4.01 recommended), 5.0 (5.01 recommended), 5.5 (Service Pack 2 recommended), 6.0
  • Netscape 6.0, 6.1

Note

Applet tag support currently does not work on Netscape 4.

Updating Old Class Files

In some cases, the new Java Runtime Environment associated with this Java Plug-in release will not run class files that were generated with old compilers. The usual symptom is a java.lang.ClassFormatError that the virtual machine throws when it attempts to load such a class file. This failure has nothing specifically to do with the changes in this release. Rather, old bytecode compilers did not strictly adhere to proper class-file format in all situations when generating class files. Recent virtual machines are implemented to be strict in enforcing proper class file format, and this can lead to errors when they attempt to load old, improperly formatted class files. Some typical problems in some older class files are (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 Java 2 SDK. If you choose to use a third-party obfuscator, be sure to use one that produces class files that respect proper class-file format.

Other Enhancements

In addition to the support for the APPLET tag described above, the Java Plug-in has many performance and architecture enhancements that will make it more suitable for widespread use on consumer client machines that typically are not as powerful as client platforms in an enterprise environment. Some of these enhancements are summarized below.

Memory management

  • Dynamic maximum heap size is scaled down from 128 MB to 96MB to avoid unnecessary paging on the system.
  • Classloader implementation has been tuned to allow memory to be reclaimed more often by the garbage collector.
  • Potential memory leak issue is addressed by using JNI/COM smart pointers in implementation.

Performance

  • Applet download time is significant reduced by relying on browser caching when possible. No connection will be opened on the server side unless it is absolutely necessary.
  • Applet lifecycle is controlled asynchronously to allow very fast page switch.
  • Sped up classloader object reclaim by removing its finalize() method.
  • HTTPS read has been made significantly faster by increasing buffer size.
  • HTTPS calls are significant faster by statically linking Microsoft's Wininet instead of dynamic function lookup every time.
  • JavaScript performance is greatly enhanced by eliminating BeanInfo lookup over the network.
  • Java Console performance is enhanced by using the Console Writer thread to avoid blocking System.out and System.err when possible.

Design

  • Default JavaScript/Java interaction is changed from "not-scriptable" to "scriptable", allowing any applets running through the APPLET tag to be used from JavaScript without modification.

JDK 1.1 compatibility

  • Java Plug-in can now access the sun.audio package.
  • Some applets are compiled with compilers that don't generate proper class file format which conforms to the class-file specification. Such appletss may result in a ClassFormatError when Java Plug-in attempts to load them. To help address this problem, PluginClassLoader provides a bytecode scanner to transform bad class files to conforming on-the-fly to allow the applets to run. Currently, only bad class files with the following errors 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

See also Updating Old Class Files above.


Appendix 4: Microsoft VM and Java 2 Applet Compatibility Issues

This appendix documents the known applet compatibility issues between the Microsoft VM (Virtual Machine) and Sun's Java 2 VM.

ClassFormatError

This problem is caused by bytecode generated from old JDK 1.0.2 or 1.1 compilers, which generate bytecode that does not conform to the Java VM Specification. Since the verifiers in recent J2SE releases are much stricter about bad class format, ClassFormatError is thrown by the VM when these bad class files are loaded.

To allow some applets with bad class file format to run in Java 2, a bytecode transformer is put into the Java Plug-in 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 is not fixable by the bytecode transformer, so any class file that has any of these known problems will not run under Java 2:

  • Illegal use of nonvirtual function call
  • Arguments can't fit into locals
  • Unsorted lookup switch
  • Truncated class file

Security exception with sun.audio

The sun.audio package was accessible by applets in JDK 1.1. However, the applet sandbox was closed up in Java 2, so that applets that try to access any class libraries in the sun.audio package will result in a SecurityException.

To provide maximum applet compatibility, the applet sandbox in Java Plug-in has been opened up to allow applets to access the sun.audio package again.

Unable to find resources from AppletContext.getAudioClip() and AppletContext.getImage()

The resource-lookup sequence in AppletContext.getImage() and AppletContext.getAudioClip() is different in the Microsoft and Sun implementations.

In the Microsoft VM, resources are looked up in the following sequence:

  1. Archives specified through HTML archive or cabbase parameters
  2. codebase URL

In Sun's implementation, resources are looked up according to codebase URL.

As a result, some applets that rely on the resources-lookup sequence in the Microsoft VM may not load resources properly in Java 2.

To provide maximum applet compatibility, the resources-lookup sequence in Java Plug-in has been changed to the following:

  1. Archives specified through HTML archive parameters
  2. codebase URL

ClassLoader sharing policy

ClassLoader sharing policy is different in the Microsoft and Sun implementations.

In the Microsoft VM, the ClassLoader object is shared between applets if and only if all of the following are true:

  • codebase values are the same
  • archive values are the same
  • cabbase values are the same

In Sun's 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 in the Microsoft VM may not run properly in Java 2 because of potential class definition conflicts.

To provide maximum applet compatibility, the ClassLoader sharing policy in Java Plug-in has been changed to the following requirements:

  • codebase values are the same and
  • cache_archive values are the same and
  • java_archive values are the same and
  • archive values are the same

Security model—Java 2 Versus Microsoft

Java 2 has a new security model providing much more capability and flexibility than JDK 1.1 provides. The Microsoft VM security model is based on JDK 1.1 and its own propriety technologies.

This issue is not fixable, so applets that rely on the Microsoft's security model will not run properly in Java 2.

Applet packaging

Applet packaging in Java 2 and JDK 1.1 is through the .jar file. However, Microsoft's VM supports applet packaging through .jar file and its own propriety .cab (cabinet) file.

This issue is not fixable, so applets packaged in Microsoft's .cab file format will not load in Java 2.

Java language specification strictness (null versus 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 null as a zero-length String, while some other APIs may treat null as it is. In Java 2, the Java language specification has been tightened up to specify what the exact behavior should be.

This issue is not fixable, so applets that rely on the APIs to treat null as a zero-length String may result in an exception in Java 2.

Applet signing—RSA versus Authenticode

In Java 2, applet signing is supported through RSA and the .jar file, while Microsoft supports applet signing through its own proprietary Authenticode and .cab technologies.

This issue is not fixable, so signed applets that rely on Microsoft's Authenticode and .cab technologies may not load properly in Java 2.

Implementation changes in AWT class libraries

In JDK 1.1, AWT class libraries were used by developers as thread-safe libraries; i.e., applets may perform lots of actions through the AWT in multiple threads and assume the class libraries will take care of synchronization issues. In Java 2, the AWT class libraries implementation has been changed to guarantee thread safety only when it is called by the AWT event-dispatch thread.

This issue is not fixable, so applets in Java 2 that make calls to AWT class libraries without awareness of the thread-safety issue may result in deadlock or race conditions.

Java/JavaScript communication

In the Microsoft implementation, applet methods and properties exposed in JavaScript in an HTML page are exactly the same as the methods/fields of the applet object. In Java Plug-in, applet methods and properties exposed in JavaScript in HTML are obtained via JavaBeans Introspection, which analyzes methods and properties through naming convention in the applet object. The side effect is that applet fields are treated differently.

This problem will be fixed in future release of Java Plug-in. In the meantime, JavaScript accessing fields in the applet object may not work properly in Java 2.

Microsoft proprietary Java class libraries

Microsoft has provided lots of proprietary class libraries in its VM implementation, including J/Direct, AFC, WFC, etc.

This issue is not fixable, so applets that rely on any of the Microsoft proprietary Java class libraries will not work properly in Java 2.

Whitespace characters in string returned from Applet.getParameter()

In the Microsoft implementation, whitespace characters are stripped off before the string is returned to the applets in Applet.getParameter(). However, the Sun 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 2 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 object identity, so that each Hashtable object returns its unique value when hashCode() is called. In Java 2, implementation of Hashtable.hashCode() was changed to be value-based as part of the Java Collection Framework. Hashtable object returns its hashcode value based on the objects it contains.

This change breaks some JDK 1.1 applets if they add Hashtable object into itself, as this breaks the fundamental design of the Collection Framework and causes a StackOverflowError. It breaks the logic in the code of some applets that rely on Hashtable.hashCode() to return a constant value from the same Hashtable object.

To provide maximum applet compatibility, the implementation of Hashtable.hashCode() is changed to check for this special case and avoid stack overflow.

Accessing frame from applet

To track mouse events or for other reasons, an applet may sometimes try to access to its frame. In the Microsoft and Sun implementations, the number of containers between the frame and the applet is different.

An applets that relies on the location of its 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 2. The most common symptom is ClassCastException from the AWT Dispatch Event Thread.

This issue is not fixable; thus an applets affected by this issue may not run properly in Java 2.

MAYSCRIPT

In Netscape Navigator and Java Plug-in, an applet accessing JavaScript is required to specify the MAYSCRIPT parameter in the applet tag. However, the Microsoft implementation doesn't honor this parameter and allows applets to access JavaScript under all conditions. Since most Internet applets target the Microsoft VM, 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. Since most web sites target the Microsoft VM instead of Sun's, these web sites do not recognize Sun's HTTP User-Agent, and this may result in failure.

As a result, HTTP User-Agent used in Java Plug-in has been changed to be similar to the one in the browser; 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()/Applet.stop() is called, which may be true in Microsoft's implementation but not in Sun's.

Applets that rely on specific events during applet startup or shutdown in Microsoft's VM may not function properly in Java 2. The most common symptom is NullPointerException from the AWT Dispatch Event Thread.

This issue is not fixable.

Java class libraries compatibility

There are lots of changes in the Java class libraries in Java 2. Some APIs are clarified, some are depreciated, and some other have been altered in implementation. These following have caused some of the applets run in Microsoft's VM to fail in Java 2:

java.awt.Graphics.drawString()

drawString() treats null as an empty string in the Microsoft VM. In Java 2, drawString() treats null as it is and throws NullPointerException.

java.awt.Graphics.drawImage()

drawImage() ignores null image in the Microsoft VM. In Java 2, 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 2, 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 2, calling these methods on a dead thread will result in AccessControlException.

All of these issues are fixable but have not yet been fixed. At this time, applets affected by these issues will result in exceptions and may not run properly in Java 2.


Java Plug-in Console

This chapter includes the following topics:

  • What is Java Console?
  • Debugging Options
  • Task-Bar Integration
  • Startup Behavior

What is Java Console?

Java Console is a simple air for debugging that redirects any System.out and System.err to the console window.

Debugging Options

Java Console provides various options as shown below to make applet debugging easier.

Sample console window

An action/option is selected by typing its letter/number while the Java Console window has focus.

Key
Description
c: Clears the Java Console window.
f: Triggers finalization on the objects in the finalization queue and then displays memory information. Memory refers to the current heap size used by the JRE. Free is the available memory that is free in the heap. The percent (xx%) is the free memory as a percent of the total heap size.
g: Triggers garbage collection and displays memory information as described above.
h: Displays help message, which is being described here.
l: Displays a list of the cached ClassLoader objects in the Java Plug-in. (These are runtime objects cached in semiconductor memory, not on disk, and should not be confused with the cached JAR files mentioned in Applet Caching.) Classes are cached to avoid having to load them again when returning to previously-visited pages. When a page is visited the first time, a ClassLoader object will be created and all of the classes that are downloaded will be cached in that object. These objects are created and cached according to their codebase. To identify a ClassLoader object, the "classloader list" displays the codebase for that object. Additional information displayed with a ClassLoader object includes zombie, cache and info. zombie = true indicates that a ClassLoader object is not being used (i.e., the applet is not currently loaded on the page). cache = true indicates that the applet should be cached, while false indicates that the applet will be destroyed when the page is left. info is a value used for debugging.
m: Displays heap memory usage as described above.
o: Triggers logging, which directs output from the Java Plug-in Console to a log file.
p: Reloads the proxy configuration.
q: Causes the Java Console to disapper from the main screen.
r: Reloads the policy configuration.
s: Prints out the system properties. This is mostly for debugging.
t: Prints out all the existing thread groups. The first group shown is Group main. ac stands for active count; it is the total number of active threads in a thread group and its child thread groups. agc stands for active group count; it is the number of active child thread groups of a thread group. pri stands for priority; it is the priority of a thread group. Following Group main, other thread groups will be shown as Group <name>, where name is the URL associated with an applet. Individual listings of threads will show the thread name, the thread priority, alive if the thread is alive or destroyed if the thread is in the process of being destroyed, and daemon if the thread is a daemon thread.
x:

This removes (destroys) all ClassLoader objects in the cache.

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.
0-5: This sets the trace-level options as described in the next section, Tracing and Logging.

Task-Bar Integration

When Java Plug-in is running an icon is now displayed—in the taskbar for Windows or on the desktop for Solaris. When clicked, the Java Console opens. This allows the user to open and close the Java Console any number of times within the same browser session.

Startup Behavior

Java Console may be shown, hidden, or not started at startup time, as configured through the Java Plug-in Control Panel in the Basic tab.


Java Plug-in 1.4.2 Developer Guide Contents

Java Plug-in 1.4.2 Developer Guide

Note: There are two ways to navigate this guide:

  • Search the guide
  • Select from the contents below:

Part I: Java Plug-in Basics

Chapter 1: Overview—What Is Java Plug-in? What Does It Support?
Chapter 2: Using the Conventional Applet Tag
Chapter 3: Using OBJECT, EMBED and APPLET Tags in Java Plug-in
Chapter 4: Using the HTML Converter to Convert Applet Tags for Java Plug-in
Chapter 5: Proxy Configuration
Chapter 6: Protocol Support: HTTP, HTTPS, FTP, GOPHER, SOCKS, and NTLM
Chapter 7: Cookie Support
Chapter 8: Applet Caching
 Chapter 9: Using the Java Plug-in Control Panel to Set Plug-in Behavior/Options

Part II: Deployment Schemes

Chapter 10: Installation for Conventional Applets (Microsoft Windows Only)
 Chapter 11: Intranet With OBJECT/EMBED Tag
Chapter 12: Internet Deployment
Chapter 13: Silent Installation
Chapter 14: Jar Indexing
Chapter 15: Java Server Pages

Part III: Security

Chapter 16: Overview—Applet Security Basics
Chapter 17: How RSA Signed Applet Verification Works in Java Plug-in
Chapter 18: How to Sign Applets Using RSA-Signed Certificates
Chapter 19: How to Deploy RSA-Signed Applets in Java Plug-in

Part IV: Debugging Support

Chapter 20: Debugging Support
Chapter 21: Java Plug-in Console
Chapter 22: Tracing and Logging

Part V: Advanced Topics

Chapter 23: Supporting Multiple Versions of JRE/Java Plug-in
 Chapter 24: Java-to-JavaScript Communication
 Chapter 25: JavaScript-to-Java Communication (Scripting)
 Chapter 26: Deploying Java Extensions
Chapter 27: Applet Persistence API
Chapter 28: Special Applet Attributes

Appendices

Appendix 1: Netscape 6
 Appendix 2: Frequently Asked Questions (FAQ)

  • Basic Information FAQ
  • Developer Information FAQ
  • Troubleshooting FAQ
  • About Applet Tag Support in Java Plug-in

Appendix 3: More About HTML Converter
Appendix 4: Microsoft VM and Java 2 Applet Compatibility Issues
 Appendix 5: Complete Example—Deploying Java Media Framework as Java Extension
 Appendix 6: Sun-Supported Specification-Version and Implemenation-Version Formats


Java Plug-in Control Panel

Using the Java Plug-in Control Panel to Set Plug-in Behavior/Options

This section covers the following topics:

  • Overview
  • Starting the Java Plug-in Control Panel
  • Saving Options
  • Control Panel Help
  • Setting Control Panel Options
    • Basic Panel
    • Advanced Panel
    • Browser Panel (Window only)
    • Proxies Panel
    • Cache Panel
    • Certificates Panel
    • Update Panel (Windows only, 1.4.2_01 and higher releases)
    • About Panel

Overview

The JavaTM Plug-in Control Panel enables you to change the default settings used by the Java Plug-in at startup. All applets running in an active instance of Java Plug-in use these settings.

Starting the Java Plug-in Control Panel

Start the Java Plug-in Control Panel as follows:

On Windows: From the Windows Control Panel, double-click the Java coffee-cup icon labeled Java Plug-in to launch the Java Plug-in Control Panel.

On Solaris and Linux: You can run the Control Panel by launching the ControlPanel executable file. In the Java 2 SDK, this file is located at:

<SDK installation directory>/jre/bin/ControlPanel

It is also located at:

<SDK installation directory>/bin/ControlPanel

For example, if your Java 2 SDK is installed at /usr/j2se, launch the Control Panel with this command:

/usr/j2se/jre/bin/ControlPanel
In a Java 2 Runtime Environment installation, the file is located at:
<JRE installation directory>/bin/ControlPanel
You can also use Netscape to visit the Control Panel applet page, which was installed inside the JRE directory as the file ControlPanel.html. In the Java 2 SDK this file is located at:
<SDK installation directory>/jre/ControlPanel.html
In the JRE:
<JRE installation directory>/ControlPanel.html

Saving Options

When you have completed your changes to the Control Panel options, click Apply to save the changes. Click Reset to cancel your changes and reload the last values that were entered and applied. Note that this is not the same as the set of default values that were originally set for Java Plug-in when it was installed.

Control Panel Help

Help for Java Plug-in is available from any panel in the Control Panel. Help comes up in its own window in response to pushing the Help button and looks like this:

Setting Control Panel Options

There are eight sub-panels (tabs) in the Java Control Panel. From six of them you can set various options. The panels are labeled:

  • Basic
  • Advanced
  • Browser
  • Proxies
  • Cache
  • Certificates
  • Update Panel
  • About

Each is described separately below.

Note

The settings shown for check boxes and radial buttons in each panel below, with the exception of the Browser panel, are the default (installation) settings. The check boxes for the Browser panel are determined according to user selection during installation.

Basic Panel

The Basic panel looks like this:

Use the Basic panel to set the following options:

Show Java Console

Displays the Java Console while running applets. The console displays messages printed by System.out and System.err objects. It is useful for debugging problems.

Hide console

The console is running but hidden. This is the default setting (checked).

Do not start console

The console is not started.

Show Java in System Tray (Windows only)

The Show Java in System Tray option indicates to the user that a Java VM is running; it provides control over the Java Plug-in Control Panel and Java Console; and it provides information about the Java release. When enabled and Java Plug-in is started, the coffee-cup logo displays in the system tray. When Java Plug-in is shutdown, the icon is removed from the system tray. This option is enabled by default (checked).

Note

If Show Java in System Tray is checked, the icon will show up in the system tray even if Do not start console is selected.

When Java Plug-in is first started and the mouse is pointed at the icon, a balloon toll tip will appear saying "Java 2 Standard Edition" along with a clickable link to http://java.sun.com/getjava. Thereafter, until Java Plug-in is shut down, when the mouse is pointd at the icon, a text box will say "Java 2 Standard Edition."

When the system tray icon is left-double-clicked, the Java Plug-in Control Panel will appear. If it is already open, a second Java Plug-in Control Panel will appear. When the system tray icon is right-clicked, a popup menu will appear with following menu items:

  • Open Control Panel
  • Open/Hide Console
  • About Java Technology
  • Hide Icon

Open Control Panel opens the Java Plug-in Control Panel. If it is already open, a second Java Plug-in Control Panel will appear.

Open/Hide Console: Open Console opens the Java Console if it is closed; Hide Console hides the Java Console if it is open.

About Java Technology brings up the About - Java box.

Hide Icon removes the icon from the system tray until the user re-enables it and Java Plug-in is restarted (i.e., the browser is closed, then reopened on a page with an applet).

Note:

To re-enable the icon, start the Java Plug-in Control Panel, check Show Java in System Tray, and press Apply.

Show Exception Dialog Box

Show an exception dialog box when exceptions occur. The default setting is hide the exception dialog box (unchecked).

Advanced Panel

The Advanced panel looks like this:

Use the Advanced panel to set the following options:

Java Runtime Environment

Enables Java Plug-in to run with any Java 2 JRE or SDK, Standard Edition v 1.4 installed on your machine. Java Plug-in 1.4 is delivered with a default JRE. However, you can override the default JRE and use an older or newer version in the 1.4 family. The Control Panel automatically detects all versions of the Java 2 SDK or JRE installed on your machine, and it displays in a list box all versions which you can use. The first item in the list will always be the Java Plug-in default; the last item will always say Other. If you choose Other, you must specify the path to the Java 2 JRE or SDK, Standard Edition v 1.4 that you wish to use. Only advanced users should change this option.

Note

Only advanced users should change this option. Changing the default JRE is not recommended.

Java Runtime Parameters

You can override the Java Plug-in default startup parameters by specifying custom options in the Java Runtime Parameters field. The syntax is the same as used with parameters to the java command line invocation. See the Java 2 Standard Edition (J2SE) documentation for a full list of command line options. The URL below is subject to change:

http://java.sun.com/j2se/1.4/docs/tooldocs/<platform>/java.html

where <platform> is one of the operating systems: solaris, linux, windows.

Below are some examples of Java runtime parameters

Enabling and disabling assertion support

To enable assertion support, the following system property must be specified in the Java Runtime Parameters:

-D[ enableassertions | ea ][:<package name>"..." | : <class name> ]

To disable assertion in the Java Plug-in, specify the following in the Java Runtime Parameters:

-D[ 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:

-D[ 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 because, 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 values 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.

Browser Panel (Windows only)

This panel relates only to Microsoft Windows installations; it does not appear in other installations. Check any browser for which you want Java Plug-in to be the default Java runtime, instead of the internal JVM of that browser. This is to enable APPLET tag support in Internet Explorer and Netscape 6 via Java Plug-in.

Proxies Panel

The Proxies panel looks like this:

Use the Proxies panel to use the browser default settings or to override the proxy address and port for the different protocols.

Use browser settings

Check this to use the browser default proxy settings. This is the default setting (checked).

Proxy information table

You can override the default settings by unchecking the "Use browser settings" check box, then completing the proxy information table beneath the check box. You can enter the proxy address and port for each of the supported protocols: HTTP, Secure (HTTPS), FTP, Gopher, and Socks.

No proxy host

This is a host or list of hosts for which no proxy/proxies are to be used. No proxy host is usually used for an internal host in an intranet environment.

Automatic proxy configuration URL

This is the 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.

For additional details about proxy configuration, see the chapter called Proxy Configuration.

Cache Panel

The Cache panel looks like this:

Note

The cache referred to here is the sticky cache; i.e., the disk cache created and controlled by Java Plug-in which the browser cannot overwrite. See Applet Caching.

Enable Caching

Check this to enable caching. This is the default setting (checked). With applet caching enabled, performance is improved because once an applet is cached it no longer needs to be downloaded when referenced again.

The Java Plug-in caches files of the following types downloaded via HTTP/HTTPS:

.jar (jar file)
.zip (zip file)
.class (java class file)
.au (audio file)
.wav (audio file)
.jpg (image file)
.gif (image file)

View files in Cache

Press this to view the cached files. Another dialog (Java Plug-in Cache Viewer) will pop up and display the cached files. The Cache Viewer displays the following information about the files in cache: Name, Type, Size, Expire Date, Last Modified, Version, and URL. In the Cache Viewer you can also selectively delete files in the cache. This is an alternative to the Clear Cache option described below, which deletes all files in the cache.

Clear Cache

Press this to clear all files in the cache. You will be prompted (Erase all files in ... _cache?) before the files are removed.

Location

You can use this to specify the location of the cache. The default location of the cache is <user home>/.jpi_cache, where <user home> is the value of the system property user.home. Its value depends on the OS.

Size

You can check Unlimited to make the cache unlimited in size; or you can set the Maximum size of the cache. If the cache size exceeds the specified limit, the oldest files cached will be removed until the cache size is within the limit.

Compression

You can set the compression of the JAR cache files between None and High. While you will save memory by specifying higher compression, performance will be degraded; best performance will be achieved with no compression.

Certificates Panel

The Certificates panel looks like this:

Four types of certificates may be selected:

  • Signed applet
  • Secure site
  • Signer CA
  • Secure site CA

Signed applet

These are certificates for signed applets that are trusted by the user. The certificates that appear in the signed applet list are read from the certificate file jpicerts<version> located in the <user home>/.java directory.

Secure site

These are certificates for secure sites. The certificates that appear in the Secure site list are read from the certificate file jpihttpscerts<version> located in the <user home>/.java directory.

Signer CA

These are certificates of Certificate Authorities (CAs) for signed applets; they are the ones who issue the certificates to the signers of signed applets. The certificates that appear in the Signer CA list are read from the certificate file cacerts, located in the <jre>/lib/security directory.

Secure site CA

These are certificates of Certificate Authorities (CAs) for secure sites; they are the ones who issue the certificates for secure sites. The certificates that appear in the Secure site CA list are read from the certificate file jssecacerts, located in the <jre>/lib/security directory

For Signed applet and Secure site certificates, there are four options: Import, Export, Remove, and Detail. 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: Detail. The user can only view the details of a certificate.

Update Panel (Windows only, 1.4.2_01 and higher releases)

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 looks like this:

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 montly. For daily updates, you can select the time of the day for the udpate; for weekly updates, you can select the day of the week and the time of the day; for montly updates, you can select the day of the month and the time of the day.

You can do manual updates at any time by presseing the Update Now button. This allows you to do immediate, unscheduled upates.

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 tranparent 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.

About Panel

The About panel looks like this:


Cookie Support

This section covers the following topics:

  • Introduction
  • How Java Plug-in supports cookies
  • Cookie policy support in Java Plug-in

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 facilitates deployment of client-side Java.

Cookie support allows a Java component 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. Java Plug-in provides bidirectional cookie support.

How Java Plug-in Supports Cookies

Java Plug-in provides cookie support through the browser API. Because browsers on different platforms implement the browser's API differently, cookie support in Java Plug-in varies according to platform.

When a browser makes an HTTP/HTTPS request through a URL connection, it normally checks the cookie cache and policy to determine if a cookie should be sent along with the HTTP/HTTPS request header. If so, the browser will read the cookie from the cache and append the cookie as part of the HTTP/HTTPS request header.

When a browser processes the HTTP/HTTPS respond header through a URL connection, it will check the header to see if any cookies should be set. The browser also checks the cookie policy to determine if the action is allowed. If so, it will extract the cookie from the HTTP/HTTPS respond header and write it into the cookie cache.

When an HTTP/HTTPS request is made using Java Plug-in, Java Plug-in consults the browser to determine if a cookie should be sent along. If so, the HTTP/HTTPS request will contain the cookie as part of the header. Otherwise, the HTTP/HTTPS request will be sent with no cookie attached.

When a cookie needs to be set from the HTTP/HTTPS respond header, Java Plug-in uses the browser API to do so.

Cookie support in Java Plug-in is triggered transparently when an HTTP/HTTPS connection needs to be made.

Netscape 4 Limitation

When using Java Plug-in with Netscape 4, cookie support works only if the codebase is the same or a subdirectory of the document base. See examples in the table below:

Document Base | Codebase | Will It Work?
http://host.com/my/ | http://host.com/my/ | Yes
http://host.com/my/ | http://host.com/my/page | Yes
http://host.com/my/page/ | http://host.com/my/ | No

To ensure that cookie support in Java Plug-in always works as expected, the following is recommended:

  • Use Internet Explorer or Netscape 6
  • If you must use Netscape 4, avoid having your web server set cookies in an HTTP/HTTPS connection with an applet.

The above recommendations apply to an intranet environment, where deployment of browsers and web servers is controllable.

Cookie Policy Support in Java Plug-in

Java Plug-in supports all cookie policies that are supported in both Internet Explorer and Netscape Navigator. Cookie policy can be configured in both browsers (see your browser guide for details). There are various options, including the following:

  • Always accept cookies
  • Disable all cookie use
  • Prompt/Warn before accepting a cookie
  • Only accept cookies from a server if they get sent back to that server

When cookie policy is changed in the browser, it will take effect the next time an HTTP/HTTPS connection is made via Java Plug-in.

Java Plug-in does not provide cookie-caching support. Instead, it consults the browser every time an HTTP/HTTPS connection is made. Any change to a cookie in the browser is reflected immediately in Java Plug-in when a new HTTP/HTTPS connection is made.


Java Debugger Support

Debugging Support

This section covers the following topics:

  • How to Debug Applets in Java Plug-in
  • Java Plug-in 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

Debugging Java applets in Java Plug-in has not been simple in the past, partly because the applets use many services and facilities from the Java 2 Runtime Environment, Java Plug-in, and the browser itself. If the applet does not work, the developer needs to spend time diagnosing the problem.

The purpose of this document is to simplify the debugging process. It provides techniques and suggestions for developing applets in Java Plug-in and describes some common mistakes in applet development.

How to Debug Applets in Java Plug-in

In order to debug applets, you must have the appropriate version of the Java 2 SDK, Standard Edition, installed on your machine. Also make sure to compile your .java files with -g option with javac. To begin debugging your applet:

  1. Start the Java Plug-in Control Panel. On the Advanced tab, specify the following parameters in the Java Runtime Parameters:
    -Djava.compiler=NONE
-Xnoagent
-Xdebug
-Xrunjdwp:transport=dt_shmem,address=
    <connection-address>,server=y,suspend=n

    The <connection-address> could be any string which is used by the java debugger later to connect to the JVM. For example,

    -Djava.compiler=NONE
-Xnoagent
-Xdebug
-Xrunjdwp:transport=dt_shmem,address=2502,server=y,suspend=n

    See JPDA Connection and Invocation for the details on the possible runtime parameters for debugging.

  2. On the Advanced tab in the Java Plug-in Control Panel, select "JDK <version> in <jdk-path>" for the Java Runtime Environment, where <version> is the Java Plug-in version and <jdk-path> is the path to the Java 2 SDK installation. For example, "JDK1.4 in C:\jdk1.4" .

  3. Start Internet Explorer or Netscape Navigator and load the page which contains the applet to be debugged. Make sure the applet code has been compiled with -g option with javac.

  4. Run the command jdb -attach <connection address> in a DOS command prompt. <connection address> is the name mentioned in the step 1. For example, if <connection address> is 2502, you will run the command as
              jdb -attach 2502
    To learn more about the Java Debugger (jdb), see The Java Debugger.

  5. Once the jdb has attached to the VM, you can set up breakpoints in the applet.

  6. 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 Netscape Navigator, run either Internet Explorer or Netscape Navigator 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 Java 2 debuggers, like Inprise's JBuilder or Symantac'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 Plug-in Control Panel. For more information, consult your Java 2 debugger or IDE manuals.

Java Plug-in Console

One of the most powerful tools in Java Plug-in is the Java Plug-in Console. It 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 Plug-in 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.

Java Plug-in Trace File

Similar to the Java Plug-in Console, this is a file that records all the System.out and System.err messages. The trace file is disabled by default but is automatically enabled when the Java Plug-in Console is enabled. The trace file is normally located in user.dir, and the file is called .plugin<version>.trace. For example, in Windows NT this file is located in C:\WINNT\Profiles\<username>\.plugin<version>.trace.

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. The possible values are true or false. By default this property is false. To enable this property, set -Djavaplugin.trace=true in the Java Runtime Parameters field in the Advance Panel of the Java Plug-in Control Panel.

java.security.debug property

This property controls whether the security system of the Java 2 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, set -Djava.security.debug=access:stack in the Java Runtime Parameters field in the Advanced Panel of the Java Plug-in Control Panel.

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 Netscape Navigator, 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 Netscape Navigator 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 Netscape, 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 BugParade. Before submitting a bug, search the BugParade 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 Plug-in Console or trace file;
  • Proxy configuration information, e.g., auto proxy configuration with proxy configuration file attached;
  • Browser and platform information, e.g., Navigator 4.7 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.


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
    • Raw installation
    • Java installer
    • 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 2 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.

As implied from the above, there are three ways that extensions can be installed by Java Plug-in:

  • By raw installation
  • With a Java installer
  • With a native installer

Each method is discussed below:

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
mediaz-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_codex.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

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 2 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.

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 2 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 update, the extension will be downloaded and verified to ensure that it is correctly signed. If it is valid, the Plug-in will pop-up a security dialog providing three options:

  1. Grant always: If selected, the Implementation-URL JAR will be granted the AllPermission permission. Any sapplet or extension signed with the same certificate will be trusted automatically in the future, and no security dialog will pop up when this certificate is encountered again. This decision can be changed from the Java Plug-in Control Panel.
  2. Grant this session: If selected, the Implementation-URL JAR will be granted the AllPermission permission. Any applet or extension signed with the same certificate will be trusted automatically within the same browser session.
  3. Deny: If selected, the installation is cancelled.

Once the user selects the options 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 2 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 SDK. 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/products/plugin/autodl/jinstall-1_4-windows-i586.cab#Version=1,4,0,0"
    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.4">
    <PARAM NAME = "scriptable" VALUE = "false">
    <COMMENT>
    <EMBED
            type = "application/x-java-applet;version=1.4"
            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.


Complete Example: Java Media Framework as Java Extension

Appendix 5: 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.4 SDK in the following location on your computer: C:\j2sdk1.4.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_1a-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, 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 locations of workspace1, then we use the jar tool in the SDK as follows:

C:\plugin\extensions\workspace1>C:\j2sdk1.4.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 *.class.

In this example we use the jarsigner tool to sign the new jar file.

Assuming that we have a Thawte keystore called thawte.p12 located in C:\plugin\keystores with the same password, mypass, for both storepass and keypass, and storetype is "pkcs12" and the keystore alias is "Sun Microsystems Inc.'s Thawte Consulting cc ID", then we can sign my_jmf.jar as follows, creating a signed jar file called s_my_jmf.jar:

C:\plugin\extensions\workspace1>C:\j2sdk1.4.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:\j2sdk1.4.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 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\workspace2, we can jar the applet with the manifest with the following command:

C:\plugin\extensions\workspace2>C:\j2sdk1.4.0\bin\jar cmf applet_manifest my_SimplePlayerApplet.jar *.class

Again, we use jarsigner to sign the jar file:

C:\plugin\extensions\workspace2>C:\j2sdk1.4.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:\j2sdk1.4.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 SDK in the bin directory (<sdk_location>/bin/HtmlConverter.exe) to convert the applet to various forms. Here we have chosen to do both: SimplePlayerApplet-1.html uses the conventional applet form; SimplePlayerApplet-2.html is a converted format for both the OBJECT and EMBED tags that assumes dynamic versioning (clasdid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93") for the OBJECT tag and type="application/x-java-applet;jpi-version=1.4" for the EMBED tag for Plug-in 1.4.2).

The two forms are 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>

SimplePlayerApplet-2.html

<html>
<head>
<title>SimplePlayerApplet</title>
</head>
<body bgcolor="#FFFFFF" text="#000000">
<!--"CONVERTED_APPLET"-->
<!-- HTML CONVERTER -->
<OBJECT
     classid = "clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
     codebase = "http://java.sun.com/products/plugin/autodl/jinstall-1_4-windows-i586.cab#Version=1,4,0,0"
     WIDTH = 320 HEIGHT = 300 >
     <PARAM NAME = CODE VALUE = "SimplePlayerApplet.class" >
     <PARAM NAME = ARCHIVE VALUE = "s_my_SimplePlayerApplet.jar" >
     <PARAM NAME = "type" VALUE = "application/x-java-applet;version=1.4">
     <PARAM NAME = "scriptable" VALUE = "false">
     <PARAM NAME = "file" VALUE="0720crt1.avi">

<COMMENT>
<EMBED
     type = "application/x-java-applet;version=1.4"
     CODE = "SimplePlayerApplet.class"
     ARCHIVE = "s_my_SimplePlayerApplet.jar"
     WIDTH = 320
     HEIGHT = 300
     file ="0720crt1.avi"
     scriptable = false
     pluginspage = "http://java.sun.com/products/plugin/index.html#download">
<NOEMBED>

</NOEMBED>
</EMBED>
</COMMENT>
</OBJECT>

<!--
<APPLET CODE = "SimplePlayerApplet.class" ARCHIVE = "s_my_SimplePlayerApplet.jar"
    WIDTH = 320 HEIGHT = 300>
<PARAM NAME = "file" VALUE="0720crt1.avi">

</APPLET>
-->

<!--"END_CONVERTED_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
  • SimplePlayerApplet-2.htm

Testing the Example

You can test the setup by pushing either of the buttons below:

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 Security Warming dialog that says: 'The applet requires the installation of optional package "javax.media.s_my_jmf" from http://java.sun.com/products/plugin/extensions/examples/jmf/s_my_jmf.jar'. You will have the options to Grant this session, Deny, or Grant Always. If you grant permission for installation, the extension will be installed in <jre_location>/lib/ext and the applet will run.


HTML Converter

Using the HTML Converter to Convert Applet Tags for Java Plug-in

The Java Plug-in HTML Converter is a utility for converting an HTML page (file) containing applets to a format for Java Plug-in. The conversion process is as follows:

First, HTML that is not part of an applet is transferred from the source file to a temporary file. Then, when an <APPLET> tag is reached, the converter parses the applet to the first </APPLET> tag (not contained in quotes) and merges the applet data with the template. (See Details about templates in the section called More About HTML Converter for more information.) If this completes without error, the original HTML file is moved to the backup folder and the temporary file is then renamed as the original file's name.

The converter effectively converts the files in place. Thus, once the converter runs, files are setup for Java Plug-in.

For detailed information about installing and using the HTML Converter, see More About HTML Converter.


More About HTML Converter

This section includes the following topics:

  • Running the GUI Version of the HTML Converter
    • Choosing files within folders to convert
    • Choosing a backup folder
    • Generating a log file
    • Choosing a conversion template
    • Choosing version scheme
    • Converting
    • Exit or convert more files
    • Details about templates
  • Running the converter from the command line

Notes:

  1. Backup all files before converting them with this tool.
  2. Cancelling a conversion will not rollback the changes.
  3. Comments within the APPLET tag are ignored.

Running the GUI version of the HTML Converter

The HTML Converter is contained in the SDK, not the JRE. To run the converter, go to the lib subdirectory of your SDK installation directory. For example, if you installed the SDK on Window on the C drive, then cd to

C:\sdk1.4.2\lib\

The converter (htmlconverter.jar) is contained in that directory.

To launch the converter type:

C:\sdk1.4.2\lib>..\bin\java -jar htmlconverter.jar -gui

Launching the converter on UNIX/Linux is analogous.

Windows Alternative

To launch the converter using Window Explorer, navigate to the following directory:

C:\j2sdk1.4.2\bin

(or to <sdk_location>\bin if it is not located in the directory shown above) then double-click on the HtmlConverter.exe application.

Unix/Linux Alternative

cd to <sdk_location>/bin—for example /home/jones/j2sdk1.4.2/bin—then enter:

HtmlConverter -gui

The HTML Converter window will appear:

sample converter window

Choosing files within folders to convert:

To convert a single file withing a folder, you may specify the path to the file and include the file name; you may also browse to the file a select it. To convert all files within a folder, you may type in the path to the folder, or choose the browse button to select a folder from a dialog. Once you have chosen a path, you may supply any number of file specifiers in "Matching File Names". Each specifier must be separated by a comma. You may use * as a wildcard. Finally, if you would like all files in nested folders matching the file name to be converted, select the checkbox "Include Subfolders".

Choosing a backup folder:

Windows

The default backup folder path is the source path with an "_BAK" appended to the name; e.g., if the source path is c:/html, then the backup path would be c:/html_BAK. The backup path may be changed by entering a path in the field labeled "Backup Files to Folder:", or by browsing for a folder.

Unix (Solaris):

The default backup folder path is the source path with an "_BAK" appended to the name; e.g., if the source path is /home/user1/html, then the backup path would be /home/user1/html_BAK. The backup path may be changed by typing a path in the field labeled "Backup Files to Folder:", or by browsing for a folder.

Generating a log file:

If you would like a log file to be generated, go to the Advanced Options screen (Edit>Options) and check "Generate Log File". Enter a path in the text field, including the name of the log file; or use the browse button to set the path (including log file). The log file may be an existing one or a new one. The log file contains basic information related to the conversion process.

Choosing a conversion template:

A default template will be used if none is chosen. This template will produce converted html files that will work with IE and Netscape. If you would like to use a different template, you may choose it from the menu on the main screen. If you choose "Other Template ..." from the menu, you will be allowed to choose a file to be used as the template. If you choose a file, be sure that it is a template.

Choosing a version scheme

Note: The specified version mentioned below is the version of the JRE you use to launch the converter; e.g., 1.4.2. The first two numbers in the version indicate the family; e.g., 1.4.3_02 is in the 1.4 family. For an explanation of product version numbers, see Note on Version Numbers in the section called Using OBJECT, EMBED and APPLET Tags in Java Plug-in.

There are two choices here:

  1. You can choose to have conversion tags that will require the specified version of Java Plug-in to run your applets. If the specified version is not installed, then the client will be asked if he/she wants to install and download it.
  2. You can choose conversion tags that will allow any installed version of Java Plug-in in the family, equal to or higher than the specified version, to run your applets. If there is no installed version of Java Plug-in, or no installed version in the family equal to or higher than the specified version, then the client will be asked if he/she wants to install and run the latest version of Java Plug-in in the family.

Converting:

Click the "Convert..." button to begin the conversion process. A dialog will show the files being processed, the number of files processed, the number of applets found, and number of errors.

Exit or Convert More Files:

When the conversion is complete, the button in the process dialog will change from "Cancel" to "Done". You may choose "Done" to close the dialog. You can then exit the Java Plug-in HTML Converter program, or select another set of files to convert.

Details about templates:

The template file is the basis behind converting applets. It is simply a text file containing tags that represent parts of the original applet. By
adding/removing/moving the tags in a template file, you can alter the output of the converted file.

Supported Tags:

$OriginalApplet$ | This tag is substituted with the complete text of the original applet.
$AppletAttributes$ | This tag is substituted with all of the applets attributes (code, codebase, width, height, etc.).
$ObjectAttributes$ | This tag is substituted with all the attributes required by the object tag.
$EmbedAttributes$ | This tag is substituted with all the attributes required by the embed tag.
$AppletParams$ | This tag is substituted with all the applet's <param ...> tags
$ObjectParams$ | This tag is substituted with all the <param...> tags required by the object tag.
$EmbedParams$ | This tag is substituted with all the <param...> tags required by the embed tag in the form name=value
$AlternateHTML$ | This tag is substituted with the text in the no-support-for-applets area of the original applet
$CabFileLocation$ | This is the URL of the cab file that should be used in each template that targets IE.
$NSFileLocation$ | This is the URL of the Netscape plugin to be used in each template that targets Netscape.
$SmartUpdate$ | This is the URL of the Netscape SmartUpdate to be used in each template that targets Netscape Navigator 4.0 or later.
$MimeType$ | This is the MIME type of the Java object.

Below are four templates that come with the HTML Converter. You can make up others and put them in the template folder to use them.

default.tpl— the default template for the converter. The converted page can be used in IE and Navigator on Windows to invoke Java Plug-in. This template can also be used with Netscape on Unix (Solaris)

<!-- HTML CONVERTER -->
<OBJECT classid="clsid:E19F9330-3110-11d4-991C-005004D3B3DB"
$ObjectAttributes$ codebase="$CabFileLocation$">
$ObjectParams$
<PARAM NAME="type" VALUE="$MimeType$">
<PARAM NAME="scriptable" VALUE="false">
$AppletParams$
<COMMENT>
<EMBED type="$MimeType$" $EmbedAttributes$
$EmbedParams$ scriptable=false pluginspage="$NSFileLocation$"><NOEMBED>
</COMMENT>
$AlternateHTML$
 </NOEMBED></EMBED>
</OBJECT>

<!--
$ORIGINALAPPLET$
-->

ieonly.tpl — the converted page can be used to invoke Java Plug-in in IE on Windows only.

<!-- HTML CONVERTER -->
<OBJECT classid="clsid:E19F9330-3110-11d4-991C-005004D3B3DB"
$ObjectAttributes$ codebase="$CabFileLocation$">
$ObjectParams$
<PARAM NAME="type" VALUE="$MimeType$">
<PARAM NAME="scriptable" VALUE="false">
$AppletParams$
$AlternateHTML$
</OBJECT>

<!--
$ORIGINALAPPLET$
-->

nsonly.tpl — the converted page can be used to invoke Java Plug-in in Navigator on Windows and Solaris.

<!-- HTML CONVERTER -->
<EMBED type="$MimeType$" $EmbedAttributes$
$EmbedParams$ scriptable=false pluginspage="$NSFileLocation$"><NOEMBED>
$AlternateHTML$
</NOEMBED></EMBED>

<!--
$ORIGINALAPPLET$
-->

extend.tpl — the converted page can be used in any browser and any platform. If the browser is IE or Navigator on Windows, or Navigator on Solaris, Java(TM) Plug-in will be invoked. Otherwise, the browser's default JVM is used.

<!-- HTML CONVERTER -->
<SCRIPT LANGUAGE="JavaScript"><!--
var _info = navigator.userAgent; var _ns = false; var _ns6 = false;
var _ie = (_info.indexOf("MSIE") > 0 && _info.indexOf("Win") > 0 &&
_info.indexOf("Windows 3.1") < 0);
//--></SCRIPT>
<COMMENT><SCRIPT LANGUAGE="JavaScript1.1"><!--
var _ns = (navigator.appName.indexOf("Netscape") >= 0 &&
((_info.indexOf("Win") > 0 && _info.indexOf("Win16") < 0 &&
java.lang.System.getProperty("os.version").indexOf("3.5") < 0) ||
_info.indexOf("Sun") > 0));
var _ns6 = ((_ns == true) && (_info.indexOf("Mozilla/5") >= 0));
//--></SCRIPT></COMMENT>

<SCRIPT LANGUAGE="JavaScript"><!--
if (_ie == true) document.writeln('<OBJECT
classid="clsid:E19F9330-3110-11d4-991C-005004D3B3DB" $ObjectAttributes$
codebase="$CabFileLocation$"><NOEMBED><XMP>');
else if (_ns == true && _ns6 == false) document.writeln('<EMBED
type="$MimeType$" $EmbedAttributes$
$EmbedParams$ scriptable=false
pluginspage="$NSFileLocation$"><NOEMBED><XMP>');
//--></SCRIPT>
<APPLET $AppletAttributes$></XMP>
$ObjectParams$
<PARAM NAME="type" VALUE="$MimeType$">
<PARAM NAME="scriptable" VALUE="false">
$AppletParams$
$AlternateHTML$
</APPLET>
</NOEMBED></EMBED></OBJECT>

<!--
$ORIGINALAPPLET$
-->

Running the converter from the command line:

Format:

java -jar htmlconverter.jar [-options1 value1 [-option2 value2 [...]]] [-simulate] [filespecs]

If only "java -jar htmlconverter.jar -gui" is specified (only -gui option with no filespecs), the GUI version of the converter will be launched. Otherwise, the GUI will be suppressed.

filespecs:
space-delimited list of file specifications which may include wildcard (*), e.g. *.html, file*.html).

-simulate:
Set to preview a conversion without actually doing the conversion. Use this option if you are unsure about a conversion. You will be shown detail information about the conversion had it been done.

Options: | Description
-source | Path to files; e.g., c:\htmldocs in Windows, /home/user1/htmldocs in Unix. Default is <userdir> If the path is relative, it is assumed to be relative to the directory from which the HTMLConverter was launched.
-dest | Path to converter file location. Default: <usrdir>
-backup | Path to the directory where you want backup files to be stored. Default: <source>_BAK If the path is relative, it is assumed to be relative to the directory from which the HTMLConverter was launched.
-f | Force overwritting of backup files.
-subdirs | Sets whether files in subdirectories should be converted or not. Default: false
-template | Name of template file to use for conversion. Default: Standard (IE & Navigator) for Windows & Solaris Only. Note: Use the default if you are unsure.
-log | Path and filename for the log. If not provided, no log file is written.
-progress | Set to display standard out progress during conversion. Default: true
-latest | Use the latest JRE supporting the MIME type.
-gui | Display the graphical user interface for the converter.


Installation for Conventional Applets

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 Netscape 6 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 browsers, users also can use the Advanced tab in the Internet Options window to enable/disable Java Plug-in's APPLET tag support. (Tool>Internet Options ... and select 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
If this flag is passed to the installer, APPLET tag support will be enabled for Microsoft Internet Explorer browsers.
-netscape6

If this flag is passed to the installer, APPLET tag support will be enabled for Netscape 6 browsers.


Deployment: Internet

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 Netscape

With Netscape it is recommended that you use the APPLET tag for internet deployment.


Deployment: Intranet

Intranet With OBJECT/EMBED Tag

This section includes the following topics:

  • Introduction
  • Deploying Java Plug-in with Internet Explorer
  • Deploying Java Plug-in with Navigator

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 Netscape Navigator 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-1_4-win.exe#Version=1,4,0,0"

(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 1.4, the version number is 1,4,0,0. 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 file jre-1_4-win.exe#Version=1,4,0,0 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 Navigator

For Netscape 6 you must use the APPLET tag.

To deploy Java Plug-in in intranet environments with Navigator 4, 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.

If you are using the Java Plug-in HTML Converter, you can simply change the conversion template file to specify your download page (the NSFileLocation variable) before the conversion. For information about modifying the conversion template, see Details About Templates in the chapter called More About HTML Converter or consult the Help file in the HTML Converter itself (Help>Help).

Once you have implemented these changes, when a machine that does not have Java Plug-in installed browses an HTML page with Navigator, users will see a missing-plugin icon on the HTML page. When the user clicks on this picture, Navigator 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 Navigator

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 Netscape 4 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.


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.


Java-to-Javascript Communication

This section includes the following topics:

  • Introduction
  • JSObject
    • How JSObject Works
    • Degree of JSObject support in Java Plug-in
    • Enabling JSObject support in Java Plug-in
  • Common DOM API

Introduction

Java Plug-in offers two way 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 of differences in DOM implementations 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()

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. Currently, Java Plug-in 1.3 ships netscape.javascript in a JAR file called JAWS.JAR. To compile an applet which uses JSObject, add JAWS.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 2 platform. As a result, applets using JSObject may not run in AppletViewer or result in exceptions.

Degree of JSObject support in Java Plug-in

Internet Explorer:

By accessing the DOM through COM, Java Plug-in provides full support of JSObject in IE.

Netscape Navigator:

By accessing the DOM through Netscape's Plug-in API, Java Plug-in provides limited support of JSObject in Navigator 4 . In Navigator 4 the following JavaScript objects can be accessed through JSObject:

  • Anchor
  • Document
  • Element
  • Form
  • Frame
  • History
  • Image
  • Layer
  • Link
  • Location
  • Navigator
  • Option
  • URL
  • Window

No other JavaScript objects are supported with Netscape 4, and attempting to access them through JSObject will result in Java exceptions. These restrictions do not apply to Netscape 6; it provides full support of JSObject.

Note: Even though different browsers may support the same JavaScript object, support of an object's methods and properties may differ. Be sure to check the JavaScript developer guide for your browser.

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.

Common DOM API

Overview

This section discusses the Common DOM API in Java Plug-in for 1.4. 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 Netscape 6; 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();
}


JavaScript to Java

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

Scripting for applets is supported in Internet Explorer and Netscape 6; it is not supported in Netscape 4. It is assumed in this chapter that you understand the special HTML tags required for Java Plug-in. For information about these special 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()


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, without converting the HTML pages through the HTML Converter. 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.


Netscape 6

This section describes the primary features of the Java runtime in Netscape 6, which is enabled by Java Plug-in. It includes the following topics:

  • APPLET , EMBED AND OBJECT Tag Support
  • Java-JavaScript Bi-directional Communication
  • RSA Signed Applet Verification
  • Display of Java Console
  • Enable/Disable Java
  • Applet Lifecycle Change
  • Proxy and Cookie Support
  • HTTPS
  • Automatic Download
  • Backward Compatibility Issue

APPLET Tag Support

Applets are loaded by Java Plug-in if the conventional APPLET tag is used.

Note:

Currently the OBJECT and element does not work with Netscape 6 with Java Plug-in. You must use the APPLET or EMBED element with Netscape 6.

Java-JavaScript Bi-directional Communication

JavaScript can access the methods of applets, and applets can access the Document Object Model (DOM) through JavaScript.

See Java-to-JavaScript Communication and JavaScript-to-Java Communication. Be sure to read the sections on security.

RSA Signed Applet Verification

RSA signed applet verification is supported.

Display of Java Console

You may display the Java Console through the Netscape 6 browser menu: Tasks>Tools>Java Console.

Enable/Disable Java

You may enable/disable Java through the Netscape 6 browser menu: Edit>Preferences>Advanced. Note that to take effect, the browser must be restarted.

Applet Lifecycle Change

Whenever a page is visited, the init() and start() methods of the applet are called; and whenever the page is left, the stop() and destroy() methods may be called.

Proxy and Cookie Support

Java Plug-in previously handled proxy and cookie support alone. In Netscape 6 this support is moved to the browser.

HTTPS

HTTPS is supported through Java Secure Socket Extension (JSSE) in J2SE.

Automatic Download

Via its XPInstall mechanism, Netscape 6 will support automatic download of Java Plug-in (JRE) if it is not present.

Backward Compatibility Issue

Although Sun has tried to ensure backward compatibility as much as possible between Java 2 and the Netscape VM, it may not be 100%. Some applets may run as is; other may only need recompilation; others, however, may need to be ported to Java 2.


Overview - What Is Java Plug-in

Overview—What Is Java Plug-in? What Does It Support?

This chapter includes the following topics:

  • What Is Java Plug-in?
  • Supported Operating Systems and Browsers

What Is Java Plug-in?

Java Plug-in extends the functionality of a web browser, allowing applets or Java Beans to be run under Sun's Jave 2 runtime environment (JRE) rather than the Java runtime environment that comes with the web browser. Java Plug-in is part of Sun's JRE and is installed with it when the JRE is installed on a computer. It works with both Netscape and Internet Explorer.

This functionality can be achieved in two different ways:

  1. By using the conventional APPLET tag in a web page.
  2. By replacing the APPLET tag with the OBJECT tag for Internet Explorer; by replacing the APPLET tag with the EMBED tag for Netscape 4. Note, however, that the OBJECT and EMBED tags must conform to a special format as described in the next chapter, Using OBJECT, EMBED and APPLET Tags in Java Plug-in.

Note:

Currently the OBJECT and EMBED tags do not work with Netscape 6 with Java Plug-in. You must use the APPLET tag with Netscape 6.

OBJECT and EMBED tags may be manually updated in web pages, but to facilitate updating web pages to this special format, an HTML Converter is provided. It is describe in the section called Using the HTML Converter to Convert Applet Tags for Java Plug-in.

While the above constitutes the heart of Java Plug-in, there are many other related topics that you may want to understand. For instance, you may want to know how proxy configuration works in Java Plug-in, you may want to know what protocols Java Plug-in supports, or you may want to know about cookie support and caching. Such topics are included in Part I: Java Plug-in Basics.

You can determine some of the behavior of Java Plug-in and set options via the Java Plug-in Control Panel. How you do this is also discussed in Part I in the chapter called Using the Java Plug-in Control Panel to Set Plug-in Behavior/Options.

Java Plug-in may be deployed in various ways—on the Internet, within an intranet, via Java Server Pages, etc. The various types and methods of deployments are discussed in the Part II: Deployment Schemes.

Applets must be run in a secure environment, and various security topics are discussed in the Part III: Security, including RSA signed applet verification. As signing applets can be a difficult topic for novice applet developers, this guide provides step-by-step instructions for signing applets in the chapter called How to Sign Applets Using RSA-Signed Certificates.

Java Plug-in provides various kinds of debugging support for applets, and Part IV: Debugging Support describes them. Java Debugger support is discussed. So is the Java Plug-in Console, which includes various options that may be set for debugging, including ones for tracing and logging.

Part V: Advanced Topics discusses more esoteric matters such as supporting multiple JREs in the same environment, Java-toJavaScript communication, how to persist applets across browser sessions, special applet attributes for changing the applet window background color, etc.

Finally, there are Appendices that information about Netscape 6; a FAQ; additional information about the HTML Converter; and Microsoft VM versus Java 2 compatibility issues.

Supported Operating Systems and Browsers

Operating System Support:

Window 98 SE, ME, NT 4.0 (SP6), 2000 (SP2), and XP; Solaris 7, 8, and 9; and Linux 6.0 or later.

Browser Support:

Internet Explorer 4 (SP2), 5.01 (SP2), 5.5 (SP2), and 6; Netscape 4.5, 4.6, 4.7, and 4.77; and Netscape 6.2.1 and higher.


Applet Persistence API

Beginning with Java2 SKD, Standard Edition v 1.4, two new methods have been added to interface AppletContext.java to allow applet persistence across browser sessions. These methods are:

  • setStream(String key, InputStream stream)
  • getStream(String key)

These new methods enable the applet developer to stream data and objects from one browser session so that they can be reused in subsequent browser sessions. This provides applet persistence and makes it unnecessary to use static objects in applets for this same purpose.

setStream(key, stream) maps a key to a stream. getStream(key) returns the stream mapped to the key. If the AppletContext already has a stream mapped to the key when setStream(key, stream) is invoked, the mapping is updated.

See the API specification for more information


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 J2SE. However, J2SE supports fewer root CA certificates than does the browser. As a result, you may have problems with untrusted server certificates.
  • Client authentication: An HTTPS server may require client authentication, in which case a local client certificate is sent to the server for authentication. In JSSE, client certificates are stored in a separate file and are independent of the browser. In order for client authentication to work, developers must import client certificates into JSSE through the keytool. See the JSSE documentation for more information.
  • 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 user will be presented with a dialog requesting two items (fields) of information: username and password. If the user's domain is the same as the domain of the server to be accessed, only username and passwork need be entered. But when the domain of the user is different from that of the server, then the domain of the server must be entered as well. It should be entered in the username field with a separating backslash (\) as follows:

<domain>\<username>

password is entered as it normally is in the password field.


Proxy Configuration

This section covers the following topics:

  • Introduction
  • How Java Plug-in Obtains Proxy Information
  • Direct Connection
  • Manual Proxy Configuration
  • Automatic Proxy Configuration

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 on their intranet web pages may also set up proxy support. This support is required for Java Plug-in to work in an intranet environment and can be set up through the Java Plug-in Control Panel.

The Control Panel provides three proxy options:

  • "Use browser settings"
  • Manual configuration through the Protocol-Address-Port table
  • "Automatic proxy configuration URL"

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.

If you select manual configuration in the Control Panel, then you must enter in the table for each protocol the address and port for the proxy server. Note that you may select to exclude some hosts from requiring proxy servers by listing them in the field labeled "No proxy host".

If you select "Automatic proxy configuration URL", 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.

How Java Plug-in Obtains 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 Java Plug-in obtains proxy information for three different browser-platform combinations:

Internet Explorer on Win32: IE stores proxy information in the same set of keys in the windows registry. Java Plug-in obtains this information directly.

Netscape Navigator on Win32: Navigator 4 stores proxy information in the user preference file on the local machine. Java Plug-in reads and parses the user preference file to obtain the Navigator 4 proxy information. Netscape 6 has an API for obtaining proxy information. findProxyForURL(URL) returns proxy configuration information for the URL passed to it.

Netscape Navigator on Solaris and Linux: Navigator stores proxy information in a file in the local machine. Java Plug-in reads and parses this file to obtain the proxy information. For Netscape 6 the process is the same as described in the previous section.

Java Plug-in obtains proxy information at startup time. If you change the proxy setting after Java Plug-in has started, you may force Java Plug-in to reload the proxy information from the browser through the p option in the Java Console.

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.

Manual Proxy Configuration

Both Internet Explorer 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 the proxy server bypass list in the browser's setting.

Internet Explorer: Java Plug-in recognizes 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 supports 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 supports this option by bypassing the proxy server if the URL hostname is plain; i.e., the hostname contains no dot (.).

Netscape Navigator: Java Plug-in recognizes 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 Navigator, it bypasses the proxy whenever the URL hostname ends with ".eng" or ".sun.com". Java Plug-in fully supports this syntax in the proxy server bypass list in 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.

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 IE.

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 Navigator.

There are a number of JavaScript helper functions which can be called from the JavaScript function FindProxyForURL. Java Plug-in provides its own implementation of these functions to completely emulate the 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.

Note that executing the function FindProxyForURL always returns proxy information as a string. Java Plug-in extracts the setting in the following way :

  • If "DIRECT" is in the string, Java Plug-in assumes direct connection.
  • If "PROXY" is in the string, it uses the first proxy setting for the connection.
  • If "SOCKS" is in the string, it uses the SOCKS v4 for the connection.
  • Otherwise, the proxy information in the string is incorrect. In this cases, Java Plug-in assumes direct connection.

For more information about automatic proxy configuration in your browser, consult the user guide for your browser.


How to Deploy 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 both verify positive, 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 Plug-in 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 Plug-in 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 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.


How RSA Signed Applet Verification Works 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 RSA signed applet support 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

So that Java Plug-in can verify 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 2 SDK, Standard Edition v 1.3 introduced fine-grained access control based on "codesource" and "protection domain," as described below:

Every class that is loaded from a JAR file has a codesource, which encapsulates two pieces of information:

  1. The location (URL) where the class came from;
  2. 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.

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. This means that a protection domain encapsulates two things:

  1. A codesource;
  2. The set of permissions granted to it.

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 behaviour is common to all secure classloaders (i.e., instances of java.security.SecureClassLoader). (Note: 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 (introduced with version 1.3) allows system administrators to turn off the PluginClassLoader behaviour. 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.


How to Sign Applets Using RSA-Signed 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 applet using jarsigner
    • Signing applet 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.

To sign an applet, several things are required:

  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

For RSA signing of applets, two types of signing tools are currently supported in Java Plug-in:

  1. Jarsigner—a tool that is shipped as part of the Java 2 SDK. Command is jarsigner ...
  2. Netscape Signing Tool—a tool that is provided by Netscape for signing applets in Navigator/Communicator. The latest version of the signing tool may be download from http://developer.netscape.com/software/signedobj/jarpack.html. (Note that Netscape no longer makes older versions of the signing tool available for download.) Command is signtool ...

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:\>C:\jdk1.3\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:\>C:\jdk1.3\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:\>C:\jdk1.3\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 2 SDK, can be used for that purpose. E.g.,

C:>C:\jdk1.3\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:>C:\jdk1.3\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:\>C:\jdk1.3\bin\jarsigner C:\TestApplet.jar MyCert
Enter Passphrase for keystore: ********
  2. Use "jarsigner -verify -verbose -certs" to verify the jar files
    C:>C:\jdk1.3\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.


Overview -- Applet Security Basics

Overview—Applet Security Basics

Applet Security Basics

Below are the basic facts regarding applet security and Java Plug-in. More detail can be found in the next chapter, How RSA Signed Applet Verification Works in Java Plug-in.

  • All unsigned applets are run under the standard applet security model.
  • If usePolicy IS NOT DEFINED in the java.policy file, then a signed applet has the AllPermission permission if:
    Java Plug-in can verify the signers, and the user, when prompted, agrees to granting the AllPermission permission.
  • If usePolicy IS DEFINED, then a signed applet has only the permissions defined in java.policy and no prompting occurs.

Moreover, note that Java Plug-in now handles certificate management; i.e., the certificate verification task is no longer passed off to the browser.


Silent Installation

This section includes the following topics:

  • Introduction
  • Running InstallShield in Silent Mode: Installation
  • Running InstallShield in Silent Mode: Uninstalling
  • Creating a Log File

Notes

  1. This chapter applies to 32-bit Windows and silent installation of the Java Runtime Environment (JRE).
  2. It is intended for:
    • system administrators who want to deploy Java Plug-in and the JRE on multiple PCs in the Intranet environment without user interaction;
    • companies with products that require the JRE, which they can silently install with their product.

Introduction

JavaTM 2 Platform Runtime Environment (JRE) installations are built using InstallShield Developer 7, which is based on Microsoft Window Installer. This product contains built-in support for silent or unattended installations. This document tells how to silently install the JRE. Refer to http://support.installshield.com/ for complete information about silent installations.

Running InstallShield in Silent Mode: Installation

Here is the command line for installing in silent mode:

<jre>.exe /s /v"/qn [ADDLOCAL=jrecore[,extra][,other_US] | ALL] [IEXPLORER=1] [NETSCAPE6=1] [MOZILLA=1] [INSTALLDIR=<drive>:\<install_path>][REBOOT=Suppress]"

where

<jre>.exe is the single executable installer for the Java Runtime Environment (JRE); ADDLOCAL, if used, is either jrecore[,extra][,other_US] or ALL; IEXPLORER=1, if used, indicates that the Plug-in should be registered with the Internet Explorer browser; NETSCAPE6=1, if used, indicates that the Plug-in should be registered with Netscape 6 or later browsers; MOZILLA=1 indicates that the Plug-in should be registered with Mozilla 1.1 and later browsers; INSTALLDIR, if used, specifies the drive and path of the installation; and REBOOT=Suppress, if used, indicates that if locked files are encountered the computer should not be rebooted.

If ADDLOCAL=jrecore[,extra][,other_US] is used,

jrecore indicates the core of the JRE will be installed;

extra (optional) indicates additional Fonts, Colors, and Soundbank will be installed;

other (optional) indicates locale-specific .jar files will be installed.

If ADDLOCAL=ALL is used, then all the features will be installed.

If ADDLOCAL is not used, then only the recommended features will be installed: jrecore will be installed; extra will not be installed; other will be installed only if l10n support, other than English, is installed.

If INSTALLDIR is not specified, the installation will go into C:\Program Files\java\j2re1.4.2 (default location).

Note

The command is case sensitive and there must be no spaces in the features listed with ADDLOCAL.

Examples

Suppose the JRE installer is j2re-1_4_2-bin-b18-windows-i586-05_mar_2003.exe; you want to install the JRE core and additional Fonts, Colors and Soundbank; and you want to register the Plug-in with Netscape 7 and Mozilla 1.3. Then the command would be:

j2re-1_4_2-bin-b18-windows-i586-05_mar_2003.exe /s /v"/qn ADDLOCAL=jrecore,extra NETSCAPE=1 MOZILLA=1"

Or suppose you want all features to be installed; you only want to register the Plug-in with Internet Explorer; and you want the installation on the D drive at java\jre. Then the command line could be simply:

j2re-1_4_2-bin-b18-windows-i586-05_mar_2003.exe /s /v"/qn ADDLOCAL=ALL IEXPLORER=1 INSTALLDIR=D:\java\jre"

You may find it convenient to use the "start /w" command, as that will cause MS-DOS to wait until the install is complete. For example:

start /w j2re-1_4_2-bin-b18-windows-i586-05_mar_2003.exe /s /v"/qn ADDLOCAL=ALL IEXPLORER=1 INSTALLDIR=D:\java\jre"

Running InstallShield in Silent Mode: Uninstalling

This is the command line for uninstalling in silent mode:

<jre>.exe /s /v"/qn [REBOOT=Suppress]" /x

where <jre>.exe is the single executable installer for the JRE and REBOOT=Suppress, if used, indicates that if locked files are encountered the computer should not be rebooted.

Example

j2re-1_4_2-bin-b18-windows-i586-05_mar_2003.exe /s /v"/qn REBOOT=Suppress" /x

Creating a Log File

If you want to create a log file describing the installation, add /L C:\<path>setup.log to the command. Note that this comes within the quote marks (""). For example:

j2re-1_4_2-bin-b18-windows-i586-05_mar_2003.exe /s/v"/qn ADDLOCAL=ALL /L C:\<path>setup.log"

This will cause the log to be written to the setup.log file.

To verify if a silent installation succeeded, scroll to the end of the log file.


SimplePlayerApplet.java Source Code

/*
 * @(#)SimplePlayerApplet.java  1.2 01/03/13

 *
 * Copyright (c) 1996-2001 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.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.

    }
}


Special Applet Attributes

There are six special attributes that can be used for customizing the applet window during downloading of an applet. (Note: The same applies to a JavaBeans component.) This section discusses:

  • The default appearance of the applet window (no special attributes specified)
  • The six special attributes
    • image
    • progressbar
    • boxmessage
    • boxbgcolor
    • boxfgcolor
    • progresscolor
  • The order of attribute precedence
  • The failure scenario, i.e., what happens when an applet does not download or run cleanly

Default Appearance

When none of these tags are used, the default appearance of the applet window is as follows:

The coffee cup logo is placed in the upper left corner. Its dimensions are 24x24 pixels and it is located 6 pixels from the top and left sides of the applet window. If the entire size of the applet is less than 36x36 pixels, then it will not be displayed. The status bar of the browser will display "Loading Java Applet ..." when the mouse points at the applet window.

Special Attributes

image

The image attribute allows you to replace the default coffee cup logo 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, gray, 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.

progressbar

With the progressbar attribute you can request display of a progress bar instead of the default graphic. The progress bar will horizontally fill the applet window up to 6 pixels to the right and left. The text "Loading Java Applet ..." will appear above the progress bar and be center-aligned with it. By default the progress bar is purple. The format for turning on the progress bar with the standard APPLET element is:

<APPLET ...>
<PARAM name="progressbar" value="true">
</APPLET>

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 that is displayed. If you use this attribute, the text will be used with the progress bar and with the status bar of the browser. The format for using this with the standard APPLET element is:

<APPLET ...>
<PARAM name="boxmessage" value="<your custom message goes here>">
</APPLET>

boxbgcolor, boxfgcolor, progresscolor

These attributes can be used to customize colors in the applet window.

By default the applet window background color is gray. 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 applet window foreground color is used for messages that appear in the window and for the border of the progress bar.) 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>

By default the progress bar fill color is purple. The attribute progresscolor can be used to specify a different fill color. The color values are the same as described above. The format for use with the standard APPLET element is:

<APPLET ...>
<PARAM name="progresscolor" value="<value>">
</APPLET>

Attribute Precedence

The order of precedence for these attributes 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 a progress bar is requested via the progressbar attribute, then the progress bar is displayed with the default text and color as described above under progressbar.
4) If custom text is provided via the boxmessage attribute, then the progress bar is displayed with the custom text as described above under boxmessage.

With any combination of image, progressbar, and boxmessage attributes, custom colors can always be provided via the boxbgcolor, boxfgcolor, and progresscolor attributes.

Failure Scenario

If an applet fails to load, the applet window will display error information. The applet window will have a single pixel border using the foreground color, and a small "broken" graphic will occupy the upper left corner. The user can right-mouse click over the applet window to get a popup menu with options to:

  • open the Java Console, or
  • open a window with information about the Java VM and Java Plug-in.


Tracing and Logging

This section includes the following topics:

  • Tracing
  • Logging
  • Other Options

Tracing

Tracing is a facility to redirect any output in the JavaConsole to a trace file.

Tracing can be turned on by enabling the property javaplugin.trace. However, it turns on all tracing facilities inside Java Plug-in. To enable more fine-grained tracing, javaplugin.trace.option may be used. You can set trace-level options (0-5) in the Java Console, shown in the previous chapter, with the following meanings:

  • 0 — off
  • 1 — basic
  • 2 — network and basic
  • 3 — security, network and basic
  • 4 — extension, security, network and basic
  • 5 — LiveConnect, extension, security, network and basic

This enables tracing on the fly.

Another way to set fine-grained tracing is through the Java Plug-in Control Panel. For instance, to enable tracing for everthing (option 5 above), enter the following in the "Java Run Time Parameters" textfield:

-Djavaplugin.trace=true
-Djavaplugin.trace.option=basic|net|security|ext|liveconnect

Tracing 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 restart.

Logging

Similar to tracing, logging is a facility to redirect any output in the Java Console to a log file using the Java Logging API. Logging can be turned on by enabling the property javaplugin.logging:

-D javaplugin.logging = true

Other Options

File Names

By default the trace and log file names are, respectively:

.plugin<version>.trace and .plugin<version>.log

However, you can give them different names by setting the properties:

javaplugin.trace.filename and javaplugin.log.filename

in the Java Plug-in Control Panel.

File Location

The default location (directory) of Java Plug-in related files is:

  • /usr/home on Unix/Linux
  • \Winnt\Profiles\<user> on Window

However, the location can be set with the environment variable USER_JPI_PROFILE.

Overwrite Option

Furthermore, if you do not want to overwrite trace and log files each session, you can set the property javaplugin.outputfiles.overwrite=false. If the property is set false, then trace and log files will be uniquely named for each session. E.g., if default trace and log file names are used as shown above, then date information would be included as follows:

.plugin<username><date hash code>.trace and .plugin<username><date hash code>.log


Using OBJECT, EMBED and APPLET Tags in Java Plug-in

This chapter includes the following topics:

  • Introduction
  • JavaTM Plug-in in IE on Windows
  • Java Plug-in in NavigatorTM on Windows or SolarisTM operating environments
  • Java Plug-in in IE and Navigator
  • Java Plug-in Anywhere
  • Summary

Introduction

This document explains the tagging structure, involving OBJECT and EMBED tags, required by Java Plug-in. It is intended for web authors who want to manually insert Java Plug-in tags in their HTML pages.

Notes

  1. There is a Java Plug-in HTML Converter, available free-of-charge from Sun Microsystems, that can automatically generate the tagging structure. It is highly recommended that most web authors use it.
  2. This converter can convert pages into any of the formats described below.
  3. For a complete list of JRE releases that can be autodownloaded via .cab files, as mentioned below, see Autodownload Files (Windows Only).

Applets are normally specified in an HTML file as follows:

<APPLET code="XYZApp.class" codebase="html/" align="baseline"
    width="200" height="200">
<PARAM name="model" value="models/HyaluronicAcid.xyz">
    No Java 2 SDK, Standard Edition v 1.4.2 support for APPLET!!
</APPLET>

And normally the APPLET tag specifies information about the applet, while the <PARAM> tags, located between the <APPLET> and </APPLET> tags, store per-instance applet information.

However, an APPLET is rendered by the browser and there is no easy way to interrupt the browser and force it to use Sun's Java Runtime Environment (JRE) to run the applet. To force the browser to do so, however, you may use a special Java Plug-in tagging structure—involving the OBJECT or EMBED tag or both, as described below—in place of the usual APPLET tag in an your HTML pages. This will cause the browser to launch Java Plug-in, which will then run the applet using Sun's JRE.

For various combinations of browsers and platforms, the following sections tell you exactly what you need to do

Note on Version Numbers

Product version numbers are of the form:

n1.n2.n3_n4n5

where n1.n2 is the major version number, the n3 is the minor version number (also referred to as the maintenance version number), and n4n5 is the patch version number (also referred to as the update version number).

The version numbers used in the examples below refer to the 1.4 major release with minor release number of 2 and, at times, hypothetical patch number of mn. Do not put hypothetical values into actual HTML for web pages.

Java Plug-in in IE on Windows

To use Java Plug-in in IE on Windows, use the OBJECT tag. The following is an example of mapping an APPLET tag to a Java Plug-in tag:

Original APPLET tag:

<APPLET code="XYZApp.class" codebase="html/" align="baseline"
    width="200" height="200">
<PARAM name="model" value="models/HyaluronicAcid.xyz">
    No Java 2 SDK, Standard Edition v 1.4.2 support for APPLET!!
</APPLET>

New OBJECT tag:

<OBJECT classid="clsid:CAFEEFAC-0014-0002-0000-ABCDEFFEDCBA"
    width="200" height="200" align="baseline"
    codebase="http://java.sun.com/products/plugin/autodl/jinstall-1_4_2-windows-i586.cab#Version=1,4,2,0">
    <PARAM name="code" value="XYZApp.class">
    <PARAM name="codebase" value="html/">
    <PARAM name="type" value="application/x-java-applet;jpi-version=1.4.2">
    <PARAM name="model" value="models/HyaluronicAcid.xyz">
    <PARAM name="scriptable" value="true">
        No Java 2 SDK, Standard Edition v 1.4.2 support for APPLET!!
</OBJECT>

Note

For static versioning, set codebase equal to:

http://java.sun.com/products/plugin/autodl/<.cab file for the version you want>

For example, for static versioning for the 1.4.2 release (which uses classid of clsid:CAFEEFAC-0014-0002-0000-ABCDEFFEDCBA), set codebase to:

http://java.sun.com/products/plugin/autodl/jinstall-1_4_2-win.cab

For a complete list of JRE releases that can be autodownloaded via .cab files, see Autodownload Files (Windows Only).

For dynamic versioning (which uses classid of clsid:8AD9C840-044E-11D1-B3E9-00805F499D93), set codebase equal to:

http://java.sun.com/products/plugin/autodl/jinstall-<major version of family in underscore format>-windows-i586.cab#Version=<full version number for lowest version in family in comma-separated format>

If no version of Java is installed, or a version less than the major version of the family is installed, then this will cause automatic redirection to the latest .cab for the latest version in the family.

For example, for the 1.4.2 release you would set codebase as follows:

http://java.sun.com/products/plugin/autodl/jinstall-1_4-windows-i586.cab#Version=1,4,0,0

If the user had version 1.3.1 installed, then the latest version in the 1.4 family would be downloaded and installed. But if any version in the 1.4 family were installed, then it would be used and no download would take place.

Note that the autodownload .cab files can change as patch releases are released. See below for more about the interpretation of codebase.

Note that the OBJECT tag contains similar information to the APPLET tag. It is sufficient to launch Java Plug-in in IE. The classid in the OBJECT tag is the class identifier for Java Plug-in itself. When IE renders this class identifier in the OBJECT tag, it will try to load Java Plug-in into the browser. See classid attribute below for information about versioning.

There are several attributes in the OBJECT tag, such as width, height and align, that are mapped directly from the corresponding attributes in the APPLET tag. These contain formatting information that IE will use to position Java Plug-in. Since this information is mapped directly without changes, the position and appearance of the applets using Java Plug-in should be the same as those applets using the APPLET tag.

Not all attributes in the APPLET tag can be mapped to the OBJECT tag attributes. For example, the attributes code and codebase in the APPLET tag are not mapped into the OBJECT tag attribute. Instead, the attribute code is mapped into the PARAM code because, according to the w3c.org HTML specification, the attribute code does not exist in the OBJECT tag. There are other attributes that do not correspond in the OBJECT tag attributes. These attributes, with one exception, should be mapped to PARAM tags.

Note

Duplicate parameter names should never be used with the OBJECT tag in Java Plug-in.

The one exception is the codebase attribute. In the APPLET tag, the codebase attribute represents the location from which to download additional class and jar files. However, in the OBJECT tag, the codebase attribute represents the location from which to download Java Plug-in when it is not found on the local machine. Because the codebase attribute has two different meanings in the APPLET and OBJECT tags, the codebase attribute in the APPLET tag is mapped into a PARAM codebase in the OBJECT tag to resolve the conflict.

In the above example, the code and codebase attributes in the APPLET tag are mapped into the OBJECT tag parameters. The PARAM code identifies the applet, and its value should be the same as the code attribute in the APPLET tag. The PARAM codebase identifies the codebase of the applet. Java Plug-in knows where to download the applet or JavaBeans component because it can read this information from the parameters. The parameter type is not mapped from the APPLET tag, but it is required in the OBJECT tag. It identifies the type of the Java executable, such as an applet or a JavaBean, so that Java Plug-in knows how to initialize the Java executable. These three PARAM tags (code, codebase, and type) in the above example are specified for Java Plug-in. They do not exist in the PARAM of the original APPLET tag. Note that the model parameter within the OBJECT tag is identical to the model parameter inside the APPLET tag. Except for these first three parameters specified for Java Plug-in, the remainder of the parameters are the same as those inside the APPLET tag.

A new addition for Java Plug-in 1.3 (and valid in 1.4.x) was the PARAM scriptable. This was added to improve performance of applets that do not require the use of JavaScript or VBScript. The value should be true if the applet requires scripting support and false if it does not. The value is false by default.

Please note that PARAM scriptable is not the same as the PARAM mayscript. mayscript provides support for communication from Java applets to JavaScript only, while scriptable allows communication from JavaScript to Java applets in Internet Explorer only.

The text "No Java 2 SDK, Standard Edition v 1.4.2 support for APPLET!!" in the APPLET tag is mapped inside the <OBJECT> and </OBJECT> tags. Originally, this text is displayed only if the browser does not have Java support. By mapping it inside the OBJECT tag, this text will be displayed if the browser does not support the OBJECT tag.

The APPLET-to-OBJECT tag attributes mapping is as follows:

Attribute Name | APPLET Tag Support | OBJECT Tag Support | Attribute Mapping to OBJECT Tag
align | X | X | OBJECT attribute align
alt | X
archive | X | PARAM element archive
code | X | X | PARAM element code
codebase | X | X | PARAM element codebase
height | X | X | OBJECT attribute height
hspace | X | X | OBJECT attribute hspace
name X X

OBJECT attribute name, PARAM element name

This case is an exception. The name attribute in the orginal APPLET element must be mapped both to the name attribute in the OBJECT element and to a nested PARAM. If the original applet were as follows:

<APPLET name="clock" ...>
</APPLET>

Then the mapping would be:

<OBJECT name="clock" ...>
<PARAM name="name" value="clock">
</OBJECT>
object | X | PARAM element object
title | X | X | OBJECT attribute title
vspace | X | X | OBJECT attribute vspace
width | X | X | OBJECT attribute width
mayscript | X | PARAM element mayscript

Some OBJECT attributes and nested PARAM elements are special to the OBJECT tag. They are the following:

Attribute/PARAM | Meaning in OBJECT tag
Attribute classid

It should always have the same value for dynamic version support, i.e. clsid:8AD9C840-044E-11D1-B3E9-00805F499D93. For static version support it will have a unique value for the version, e.g., clsid:CAFEEFAC-0014-0002-0000-ABCDEFFEDCBA.

For more information about static vs. dynamic versioning, see Encountering OBJECT, EMBED, and APPLET Tags With Different Plug-in Versions and Browsers.

Note: The example above uses static versioning.

Attribute codebase

It should be a full URL pointing to a .cab file somewhere on the network. It's purpose is to allow downloading and installation of Plug-in if either no version of Plug-in is installed on a user's computer or if no appropriate version of Plug-in is installed. The URL should, by default, point to a page on the Java Software website.

Examples:

In the above example, codebase is:

codebase="http://java.sun.com/products/plugin/autodl/jinstall-1_4_2-windows-i586.cab#Version=1,4,2,0"

Note that this was for static versioning and that the version number appended to the .cab file indicates that 1.4.2 version of Plug-in needs to be installed on the user's computer, otherwise an attempt will be made to download and install it.

For dynamic versioning, codebase would be as follows:

codebase="http://java.sun.com/products/plugin/autodl/jinstall-1_4-windows-i586.cab#Version=1,4,0,0"

The appended version number indicates that if the user has version 1.4.0 or higher of the Plug-in installed on the computer, no download will occur. In other words, if the installed Plug-in is in the 1.4 family (major version 1.4), then it will run. If the installed version is lower, however, then an attempt will be made to download and install a newer version via the .cab file.
PARAM element type

The value for parameter type should be as follows:

"application/x-java-<object_type>;<version_type>=<implementation_version>"

where

object_type is applet or bean;

version_type is jpi-version for static versioning or version for dynamic versioning;

implementation_version is Implementation-Version as defined in Appendix 6: Sun-Supported Specification-Version and Implemenation-Version Formats.

For more information about static vs. dynamic versioning, see Encountering OBJECT, EMBED, and APPLET Tags With Different Plug-in Versions and Browsers.

Examples:

For an applet deployed for static versioning with Plug-in version 1.4.1 patch release 02, value for type would be as follows:

"application/x-java-applet;jpi-version=1.4.1_02"

For a bean deployed for dynamic versioning with Plug-in version 1.4.1 patch release 03, value for type would be:

"application/x-java-bean;version=1.4"

This is because for dynamic versioning only the major version number is checked; i.e., if the installed Plug-in is in the major version family, no download is required.
PARAM element codebase | Specifies the base URL of the applet. The URL can be relative or absolute but it should be in the domain of the current document. This PARAM element is required only if the applet is not located in the same directory as the document.
PARAM element code | Specifies the name of the Java applet or JavaBeans component. It cannot be used with PARAM element object nested inside the same OBJECT tag.
PARAM element scriptable | Specifies whether the applet is scriptable from the HTML page using JavaScript or VBScript. The value can be either true or false. This attribute is new in Java Plug-in 1.4.
PARAM element object | Specifies the name of the serialized Java applet or JavaBeans component. It cannot be used with PARAM element code nested inside the same OBJECT tag. This attribute is optional.
PARAM element archive | Specifies the name of the Java archive. This attribute is optional.
PARAM element mayscript | Specifies whether the applet is allowed to access netscape.javascript.JSObject. The value can be either true or false. This attribute is optional.

If the original APPLET element uses attributes type, codebase, code, object or archive, and also has nested PARAM element attributes type, codebase, code, object or archive, there will be a problem with the direct mapping of the APPELET attributes to PARAM attributes , as there will then be PARAM elements with duplicate name attributes, e.g.,

If the orginal applet were as follows:

<APPLET codebase = "a/b/c ...>
<PARAM name="codebase" value="my.jar">
</APPLET>

Then the direct mapping would be:

<OBJECT ...>
<PARAM name="codebase" value="a/b/c">
<PARAM name="codebase" value="my.jar">
</OBJECT>

To avoid this problem, any APPLET attribute that has a corresponding PARAM element in the orignal applet should be mapped as shown below.

Original attribute in the APPLET element | New PARAM attribute with OBJECT element
code | java_code
codebase | java_codebase
archive | java_archive
object | java_object
type | java_type

These new PARAM element attribute names should be used only when necessary. If both the new and original PARAM names exist in the same OBJECT tag, the values associated with the new PARAM element names are used by Java Plug-in to load the applet or JavaBean.

Example

Suppose the orginal applet was as follows:

<APPLET codebase = "a/b/c ...>
<PARAM name="codebase" value="my.jar">
</APPLET>

Then the mapping should be as shown below:

<OBJECT ...>
<PARAM name="java_codebase" value="a/b/c">
<PARAM name="codebase" value="my.jar">
</OBJECT>

Java Plug-in in Netscape Navigator on Windows or SolarisTM operating environments

To use Java Plug-in with Netscape Navigator 4.x on Windows or Solaris operating environments, you must use the EMBED tag. The following example shows the mapping of a traditional APPLET tag to a Java Plug-in EMBED tag:

Original APPLET tag:

<APPLET code="XYZApp.class" codebase="html/" align="baseline"
    width="200" height="200">
<PARAM name="model" value="models/HyaluronicAcid.xyz">
    No Java 2 SDK, Standard Edition v 1.4.1 support for APPLET!!
</APPLET>

New EMBED tag:

<EMBED type="application/x-java-applet;jpi-version=1.4.1" width="200"
   height="200" align="baseline" code="XYZApp.class"
   codebase="html/" model="models/HyaluronicAcid.xyz"
   pluginspage="http://java.sun.com/j2se/1.4.1/download.html">
<NOEMBED>
   No Java 2 SDK, Standard Edition v 1.4.1 support for APPLET!!
</NOEMBED>
</EMBED>

Note that the EMBED tag contains similar information to the APPLET tag.It is sufficient to launch Java Plug-in in Navigator. The attribute type in the EMBED tag is used to identify the type of the Java executable, such as an applet or a bean. When Navigator renders this attribute in the EMBED tag, it will try to load Java Plug-in into the browser. Note that a version number is also appended. It is used for comparing the version installed on a user's computer and deciding if another version needs to be installed. The second table below describes this in greater detail.

In the above example, several attributes in the EMBED tag, such as width, height and align, map directly from the corresponding attributes in the APPLET tag. These contain formatting information that Navigator uses to position Java Plug-in. Since this information is mapped directly without changes, the position and appearance of the applets using Java Plug-in should be the same as those applets using the APPLET tag.

Unlike the OBJECT tag, all information must be stored inside the <EMBED> tag. No PARAM elements are used with the EMBED tag. Therefore, all APPLET attributes and related PARAM elements must be mapped as attribute name="value" pairs inside the EMBED tag.

In the above example, the code and codebase attributes in the APPLET tag are mapped into the EMBED tag attributes. Attribute code identifies the applet. Its value should be the same as the code attribute in the APPLET tag. Attribute codebase identifies the codebase of the applet. Java Plug-in knows where to download the applet or JavaBeans component because it can read this information from the attributes. Also notice that the model attribute within the EMBED tag is mapped from the nested PARAM element model inside the APPLET tag.

Like the codebase attribute in the OBJECT tag, attribute pluginspage in the EMBED tag is used by Navigator if Java Plug-in is not installed on the user's computer, or if the wrong version of Java Plug-in is installed. It should point to the Java Plug-in Download Page on the Java Software website; or, for intranet deployment, to a page on the intranet from which Java Plug-in may be downloaded.

The text "No Java 2 SDK, Standard Edition v 1.4.1 support for APPLET!!" in the APPLET tag is mapped inside the <NOEMBED> and </NOEMBED> tags. With the traditional APPLET tag this text is displayed only if the browser does not have internal support for Java. By mapping it inside the NOEMBED tag, this text will be displayed if the browser does not support the EMBED tag, or if Navigator fails to start the Java Plug-in.

The APPLET-to-EMBED tag attributes mapping is as follows:

Attributes | APPLET tag support | EMBED tag support | Attribute map to EMBED tag
align | X | X | Attribute align
alt | X | X | Attribute alt
archive | X |  | Attribute archive
code | X |  | Attribute code
codebase | X |  | Attribute codebase
height | X | X | Attribute height
hspace | X | X | Attribute hspace
name | X | X | Attribute name
object | X |  | Attribute object
title | X | X | Attribute title
vspace | X | X | Attribute vspace
width | X | X | Attribute width
mayscript | X |  | Attribute mayscript

Some attributes are special to the EMBED tag. These attributes are:

Attribute
Meaning in EMBED tag
Attribute type

type should be as follows:

"application/x-java-<object_type>;<version_type>=<implementation_version>"

where

object_type is applet or bean;

version_type is jpi-version for static versioning or version for dynamic versioning;

implementation_version is Implementation-Version as defined in Appendix 6: Sun-Supported Specification-Version and Implemenation-Version Formats.

For more information about static vs. dynamic versioning, see Encountering OBJECT, EMBED, and APPLET Tags With Different Plug-in Versions and Browsers.

Examples:

For an applet deployed for static versioning with Plug-in version 1.4.1 patch release 02, type would be as follows:

"application/x-java-applet;jpi-version=1.4.1_02"

For a bean deployed for dynamic versioning with Plug-in version 1.4.1 patch release 03, type would be:

"application/x-java-bean;version=1.4"

This is because for dynamic versioning only the major version number is checked; i.e., if the installed Plug-in is in the major version family, no download is required).
Attribute codebase | Specifies the base URL of the applet or JavaBeans component. The URL can be relative or absolute but it should be in the domain of the current document. This attribute is required only if the applet is not located in the same directory as the document.
Attribute code | Specifies the name of the Java applet or JavaBeans component. It cannot be used with param object inside the same EMBED tag.
Attribute object | Specifies the name of the serialized Java applet or JavaBeans component. It cannot be used with the code attribute inside the same EMBED tag. This attribute is optional.
Attribute archive | Specifies the name of the Java archive. This attribute is optional.
Attribute pluginspage | It should be a full URL pointing to an HTML page from which Java Plug-in can be downloaded. If there is no Plug-in installed on a user's computer, or if the version of the Plug-in is not the one specified via the the type attribute, then this page will be presented to the user.
Attribute mayscript | Specifies whether the applet is allowed to access netscape.javascript.JSObject. The value can be either true or false. This attribute is optional.

Similar to the case of the OBJECT tag, if the original APPLET tag has PARAM element type, codebase, code, object, or archive, mapping it to the EMBED tag attribute will cause a problem. To avoid this, Java Plug-in also supports the same new set of attribute names for the EMBED tag, as specified below:

Similar to the case of the OBJECT element, if the original APPLET element uses attributes type, codebase, code, object or archive, and also has nested PARAM element attributes type, codebase, code, object or archive, there will be a problem with the direct mapping of the APPELET attributes to EMBED attributes. To avoid this problem, Java Plug-in also supports the same new set of attribute names for the EMBED tag, as specified below:

Original Attribute Names | New Attribute Names
code | java_code
codebase | java_codebase
archive | java_archive
object | java_object
type | java_type

These new attribute names should be used only when necessary. If both new and original attribute names exist in the same EMBED tag, the value associated with the new attribute name is used by Java Plug-in to load the applet or bean.

Java Plug-in in IE and Navigator

The new OBJECT element scheme described above allows a web page with an applet to use Java Plug-in with Internet Explorer, and the new EMBED element scheme allows a web page with an applet to use Java Plug-in with Netscape. However, changes are a web page will be browsed by both browsers. Hence, there needs to be a way to use the OBJECT scheme when a page is browser by Internet Explorer, and the EMBED scheme when the page is browsed by Netscape. Such a scheme is described below.

Original APPLET element:

<APPLET code="XYZApp.class" codebase="html/" align="baseline"
    width="200" height="200">
<PARAM NAME="model" VALUE="models/HyaluronicAcid.xyz">
    No Java 2 SDK, Standard Editoin v 1.4 support for APPLET!!
</APPLET>

New OBJECT element with nested EMBED element:

<OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
    width="200" height="200" align="baseline"
    codebase="http://java.sun.com/products/plugin/1.4/jinstall-14-win32.cab#Version=1,4,0,mn">
    <PARAM NAME="code" VALUE="XYZApp.class">
    <PARAM NAME="codebase" VALUE="html/">
    <PARAM NAME="type" VALUE="application/x-java-applet;jpi-version=1.4">
    <PARAM NAME="model" VALUE="models/HyaluronicAcid.xyz">
    <PARAM NAME="scriptable" VALUE="true">
    <COMMENT>
        <EMBED type="application/x-java-applet;jpi-version=1.4" width="200"
           height="200" align="baseline" code="XYZApp.class"
           codebase="html/" model="models/HyaluronicAcid.xyz"
           pluginspage="http://java.sun.com/products/plugin/1.4/plugin-install.html">
            <NOEMBED>
                No Java 2 SDK, Standard Edition v 1.4 support for APPLET!!
            </NOEMBED>
        </EMBED>
    </COMMENT>
</OBJECT>

Because IE understands the <OBJECT> tag, it will try to launch Java Plug-in. Notice that the <COMMENT> tag is a special HTML tag understood only by IE. IE ignores text between the <COMMENT> and </COMMENT> tags. In effect, the above tags actually become:

Note that the <COMMENT> element is unique to IE. IE ignores text between the <COMMENT> and </COMMENT> elements. For IE, then, the above structure of elements looks like this:

<OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
    width="200" height="200" align="baseline"
    codebase="http://java.sun.com/products/plugin/1.4/jinstall-14-win32.cab#Version=1,4,0,mn">
    <PARAM NAME="code" VALUE="XYZApp.class">
    <PARAM NAME="codebase" VALUE="html/">
    <PARAM NAME="type" VALUE="application/x-java-applet;jpi-version=1.4">
    <PARAM NAME="model" VALUE="models/HyaluronicAcid.xyz">
    <PARAM NAME="scriptable" VALUE="true">
</OBJECT>

This is identical to the new OBJECT tag example described above.

Now because Navigator understands neither the OBJECT nor the COMMENT elements, Navigator 4 views the above structure as follows:

<EMBED type="application/x-java-applet;jpi-version=1.4" width="200"
   height="200" align="baseline" code="XYZApp.class"
   codebase="html/" model="models/HyaluronicAcid.xyz"
   pluginspage="http://java.sun.com/products/plugin/1.4/plugin-install.html">
    <NOEMBED>
        No Java 2 SDK, Standard Edition v 1.4 support for APPLET!!
    </NOEMBED>
</EMBED>

This is identical to the new EMBED element example described above.

Thus you can use the new element structure—OBJECT element with nested EMBED element—to invoke Java Plug-in when either IE or Netcape encounters a page with an applet. The is the recommeded format to use.

Java Plug-in Anywhere

Warning!

The material in this section is out of date. It will be updated in the future. The description of the script below corresponds to the Extended option with the HtmlConverter. It is recommended that you do not use this option at this time. The Standard option is the recommended option.

In most environments, Internet or intranet, an HTML page is likely to be viewed on different browsers on different platforms. Ideally, then, you should activate Java Plug-in only on the right browser-platform combination. Otherwise, an applet should use the browser's default JVM. You can achieve this using the following Java Plug-in format:

Original APPLET element:

<APPLET code="XYZApp.class" codebase="html/" align="baseline"
    width="200" height="200">
<PARAM NAME="model" VALUE="models/HyaluronicAcid.xyz">
    No Java 2 SDK, Standard Edition v 1.4 support for APPLET!!
</APPLET>

New-style format:

The following is an example of an equivalent Java Plug-in format. (The example includes comments.)

<!-- The following code is specified at the beginning of the <BODY> tag. -->
<SCRIPT LANGUAGE="JavaScript"><!--
    var _info = navigator.userAgent;
    var _ns = false;
    var _ie = (_info.indexOf("MSIE") > 0 && _info.indexOf("Win") > 0
        && _info.indexOf("Windows 3.1") < 0);
//--></SCRIPT>
<COMMENT><SCRIPT LANGUAGE="JavaScript1.1"><!--
    var _ns = (navigator.appName.indexOf("Netscape") >= 0
        && ((_info.indexOf("Win") > 0 && _info.indexOf("Win16") < 0
        && java.lang.System.getProperty("os.version").indexOf("3.5") < 0)
        || _info.indexOf("Sun") > 0));
//--></SCRIPT></COMMENT>

<!-- The following code is repeated for each APPLET tag -->
<SCRIPT LANGUAGE="JavaScript"><!--
    if (_ie == true) document.writeln('
<OBJECT
    classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
    width="200" height="200" align="baseline"
codebase="http://java.sun.com/products/plugin/1.4/jinstall-14-win32.cab#Version=1,4,0,mn">
    <NOEMBED><XMP>');
    else if (_ns == true) document.writeln('
<EMBED
    type="application/x-java-applet;jpi-version=1.4" width="200" height="200"
    align="baseline" code="XYZApp.class" codebase="html/"
    model="models/HyaluronicAcid.xyz"
    pluginspage="http://java.sun.com/products/plugin/1.4/plugin-install.html">
    <NOEMBED><XMP>');
//--></SCRIPT>
   <APPLET code="XYZApp.class" codebase="html/" align="baseline"
        width="200" height="200">
</XMP>
    <PARAM NAME="java_code" VALUE="XYZApp.class">
    <PARAM NAME="java_codebase" VALUE="html/">
    <PARAM NAME="java_type" VALUE="application/x-java-applet;jpi-version=1.4">
    <PARAM NAME="model" VALUE="models/HyaluronicAcid.xyz">
    <PARAM NAME="scriptable" VALUE="true">
    No Java 2 SDK, Standard Edition v 1.4 support for APPLET!!
</APPLET></NOEMBED></EMBED>
</OBJECT>

<!--
    <APPLET code="XYZApp.class" codebase="html/" align="baseline"
        width="200" height="200">
    <PARAM NAME="model" VALUE="models/HyaluronicAcid.xyz">
    No Java 2 SDK, Standard Edition v 1.4 support for APPLET!!
    </APPLET>
-->

Although this tag seems complicated compared to the old APPLET tag, it is not. Most of the Java Plug-in tag is the same regardless of the applet used. For the majority of cases, a webmaster can copy and paste the Java Plug-in tag.

The first block of the script extracts the browser and platform. You must determine the browser and platform on which the applet is running. You do this by using JavaScriptTM to extract first the browser name, then the platform. This is done once per HTML document.

The second block of the script replaces the APPLET tag. You must replace each APPLET tag with a similar block of code. The script replaces the APPLET tag with either an EMBED tag or OBJECT tag, depending on the browser. You use the OBJECT tag for IE and the EMBED tag for Netscape Navigator. Finally, the original APPLET tag is included as a comment at the end. It is always a good idea to keep the original APPLET tag in case you want to remove the Java Plug-in invocation.

The first JavaScript establishes the browser and the platform on which the browser is running. You must do this because, currently, Java Plug-in supports only Windows 95, Windows 98, Windows NT 4.0, and Solaris. Note that Windows NT 3.51 is the only Win32 platform that Java Plug-in does not support. Java Plug-in should be invoked only on the supported browser and platform. The script sets the variable _ie to true if the browser is Internet Explorer. It sets the variable _ns to true if the browser is Navigator. (Note that all variable names in the JavaScript start with "_". This is done to avoid conflicting with other JavaScript variables in the same page.)

To detect the right browser, the JavaScript evaluates three strings that are within the JavaScript's Navigator object: userAgent, appVersion, and appName. These strings contain information about the browser and the platform. By looking at some examples of the string userAgent, you can see how to evaluate userAgent and use it to determine the browser. The following are some examples of the userAgent string for different platforms as it appears in Internet Explorer.

Platform and Browser | JavaScript's Navigator.userAgent string
Windows 2000 w/IE 5.0 | "Mozilla/4.0 (compatible; MSIE 5.01; Window NT5.0)
Windows NT 4.0 w/IE 4.0 | "Mozilla/4.0 (compatible; MSIE 4.0; Windows NT)"
Windows NT 4.0 w/IE 3.02 | "Mozilla/2.0 (compatible; MSIE 3.02; Windows NT)"
Windows 95 w/IE 4.0 | "Mozilla/4.0 (compatible; MSIE 4.0; Windows 95)"
Windows 95 w/IE 3.02 | "Mozilla/2.0 (compatible; MSIE 3.02; Windows 95)"
Windows NT 3.51 w/IE 4.0 | "Mozilla/4.0 (compatible; MSIE 4.0; Windows 3.1)"
Windows 3.1 w/IE 4.0 | "Mozilla/4.0 (compatible; MSIE 4.0; Windows 3.1)"
Windows NT 4.0 w/Navigator 4.04 | "Mozilla/4.04 [en] (WinNT; I)"
Windows NT 4.0 w/Navigator 3.04 | "Mozilla/3.04 (WinNT; I)"
Windows NT 3.51 w/Navigator 4.04 | "Mozilla/4.04 [en] (WinNT; I)"
Windows NT 3.51 w/Navigator 3.04 | "Mozilla/3.04 (WinNT; I)"
Windows 95 w/Navigator 4.03 | "Mozilla/4.03 [en] (Win95; I)"
Windows 95 w/Navigator 3.03 | "Mozilla/3.03 (Win95; I)"
Solaris 2.6 w/Navigator 4.02 | "Mozilla/4.02 [en] (X11; l; SunOS 5.6 sun4u)

Note that in each case the substring "MSIE" is always in the userAgent string in Internet Explorer. Also, the userAgent string in IE under Windows 3.1 and Windows 3.51 would contain the substring "Windows 3.1" because IE in these platforms is 16-bit. While IE 4 is also available on Solaris and Mac, in these versions the userAgent string does not contain the substring "Win". In addition, IE on Windows CE does not support JavaScript. This can be summarized as follows:

userAgent string / Browsers | Windows 3.1 w/ IE 3/4 | Windows NT 3.51 w/ IE 3/4 | Windows 95 w/ IE 3/4 | Windows NT 4.0 w/ IE 3/4 | Windows CE w/ IE | Mac w/ IE | UNIX w/ IE | Other browsers on any platform
contains "MSIE" | X | X | X | X |  | X | X |
contains "Win" | X | X | X | X |  |  |  |
does not contain "Windows 3.1" |  |  | X | X |  | X | X | X

The above table shows that only Windows 95 and Windows NT 4.0 with IE can pass the Java Plug-in browser and platform requirements. However, this logic makes no assumptions about future releases of IE or future releases of Windows with IE. As long as the userAgent string contains "MSIE" and "Win", the above code should work in future releases of IE on Win32.

The above logic summarizes into the following:

<SCRIPT LANGUAGE="JavaScript"><!--
    var _info = navigator.userAgent;
    var _ie = (_info.indexOf("MSIE") > 0 && _info.indexOf("Win") > 0
            && _info.indexOf("Windows 3.1") < 0);
//--></SCRIPT>

It is harder to detect Navigator on the right platform. Using just JavaScript, there is no way to determine if the browser is running on the Windows NT 3.51 or Windows NT 4.0 operating platform. (Refer to the above table and examine the userAgent string. Notice that the userAgent strings in Windows NT 3.51 and Windows NT 4.0 operating platforms are the same in Navigator.) It is important to make this distinction because Java Plug-in supports only the Windows NT 4.0 operating platform. To run Java Plug-in on the right platform, you must use LiveConnect in Navigator to determine the OS version number. This can be summarized as follows:

Testing logic / Browsers | Windows 3.1 w/ NS 3/4 | Windows NT 3.51 w/ NS 3/4 | Windows 95 w/ NS 3/4 | Windows NT 4.0 w/ NS 3/4 | NS on Solaris | IE on Solaris | NS on other platform | IE on other platform | Other browsers on any platform
appName contains "Netscape" | X | X | X | X | X |  | X |  |
userAgent contains "Win" | X | X | X | X |  |  |  | X |
userAgent does not contain "Win16" |  | X | X | X |  |  | X | X |
os.version does not contain 3.5 | X |  | X | X |  |  | Depends on OS |  |
userAgent contains "Sun" |  |  |  |  | X | X |  |  |

The above logic translates into the following code:

<SCRIPT LANGUAGE="JavaScript"><!--
    var _info = navigator.userAgent; var _ns = false;
//--></SCRIPT>
<COMMENT><SCRIPT LANGUAGE="JavaScript1.1"><!--
     var _ns = (navigator.appName.indexOf("Netscape") >= 0
            && ((_info.indexOf("Win") > 0  && _info.indexOf("Win16") < 0
            && java.lang.System.getProperty("os.version").indexOf("3.5") < 0)
            || _info.indexOf("Sun") > 0));
//--></SCRIPT></COMMENT>

Referring to the previous table, note that only Windows 95, Windows NT 4.0, and Solaris operating environments with Navigator pass all the tests. Because LiveConnect is used to get the OS version number and only Navigator supports LiveConnect, a JavaScript that accesses LiveConnect will not be understood by IE. To prevent this from causing a problem, you block out this piece of the script using the COMMENT tag since COMMENT is an IE-specific comment tag. The text between the COMMENT tag is ignored by IE but not by Navigator. In addition, you must specify the script language as JavaScript1.1 to block this out if the browser is Navigator 2.

At this point, the above logic for IE and Navigator summarizes to a script that should look as follows:

<!-- The following code is specified at the beginning of the <BODY> tag. -->
<SCRIPT LANGUAGE="JavaScript"><!--
    var _info = navigator.userAgent; var _ns = false;
    var _ie = (_info.indexOf("MSIE") > 0 && _info.indexOf("Win") > 0
            && _info.indexOf("Windows 3.1") < 0);
//--></SCRIPT>
<COMMENT><SCRIPT LANGUAGE="JavaScript1.1"><!--
    var _ns = (navigator.appName.indexOf("Netscape") >= 0
           && ((_info.indexOf("Win") > 0 && _info.indexOf("Win16") < 0
           && java.lang.System.getProperty("os.version").indexOf("3.5") < 0)
           || _info.indexOf("Sun") > 0));
//--></SCRIPT></COMMENT>

Remember that this block of JavaScript should be put at the top of the <BODY> of the HTML file. It is put at the top so that other JavaScripts can reference the variables _ie and _ns. This JavaScript is the same in all HTML files, and it is only needed once for each HTML body.

The second block of HTML tags are actually the corresponding OBJECT and EMBED tags that are mapped from the data in the APPLET tag. Note that JavaScript outputs the OBJECT tag when the browser is IE running on the Windows 95, Windows 98 or Windows NT 4.0 operating environments. If the browser is Navigator 3/4 on Windows 95, Windows 98, Windows NT 4.0, or Solaris operating environments, then JavaScript also outputs the EMBED tag, though with a slightly different syntax. Recall that the mechanism for detecting the browser and the platform has been described in the above section. (Tags <!-- and --> are used for comments in HTML.)

Original APPLET tag:

<APPLET code="XYZApp.class" codebase="html/" align="baseline"
    width="200" height="200">
<PARAM NAME="model" VALUE="models/HyaluronicAcid.xyz">
    No Java 2 SDK, Standard Edition v 1.4 support for APPLET!!
</APPLET>

New style tag:

<SCRIPT LANGUAGE="JavaScript"><!--
    if (_ie == true) document.writeln('<OBJECT
    classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
    width="200" height="200" align="baseline"
codebase="http://java.sun.com/products/plugin/1.4/jinstall-14-win32.cab#Version=1,4,0,mn">
    <NOEMBED><XMP>');
    else if (_ns == true) document.writeln('<EMBED
    type="application/x-java-applet;jpi-version=1.4" width="200" height="200"
    align="baseline" code="XYZApp.class" codebase="html/"
    model="models/HyaluronicAcid.xyz"
    pluginspage="http://java.sun.com/products/plugin/1.4/plugin-install.html">
    <NOEMBED><XMP>');
//--></SCRIPT>
    <APPLET code="XYZApp.class" codebase="html/" align="baseline"
        width="200" height="200"></XMP>
    <PARAM NAME="java_code" VALUE="XYZApp.class">
    <PARAM NAME="java_codebase" VALUE="html/">
    <PARAM NAME="java_type" VALUE="application/x-java-applet;jpi-version=1.4">
    <PARAM NAME="model" VALUE="models/HyaluronicAcid.xyz">LUE="models/HyaluronicAcid.xyz">
    <PARAM NAME="scriptable" VALUE="true">
        No Java 2 SDK, Standard Edition v 1.4 support for APPLET!!
    </APPLET></NOEMBED></EMBED></OBJECT>

Note that the original APPLET tag is also mapped in the new Java Plug-in tag. This is done because Java Plug-in is intended to be used only on supported platforms. Leaving the APPLET tag in the script ensures that browsers that do not support Java Plug-in, or browsers that do not support JavaScript can gracefully handle the applet using the default JVM. HotJava Browser, IE, and Navigator on non-Java Plug-in supported platforms, or browsers without JavaScript support, read the above tags as follows:

<APPLET code="XYZApp.class" codebase="html/" align="baseline"
    width="200" height="200"></XMP>
<PARAM NAME="java_code" VALUE="XYZApp.class">
<PARAM NAME="java_codebase" VALUE="html/">
<PARAM NAME="java_type" VALUE="application/x-java-applet;jpi-version=1.4">
<PARAM NAME="model" VALUE="models/HyaluronicAcid.xyz">
<PARAM NAME="scriptable" VALUE="true">
   No Java 2 SDK, Standard Edition v 1.4 support for APPLET!!
</APPLET></NOEMBED></EMBED></OBJECT>

These browsers ignore the tags </XMP>, </OBJECT>, </EMBED>, and </NOEMBED> as well because there is no corresponding <XMP>, <OBJECT>, <EMBED>, and <NOEMBED> tags. Because Java Plug-in is targeted for features in the Java 2 SDK, Standard Edition v 1.4 or future releases, those browsers without full Java 2 SDK 1.4 support and who do not support Java Plug-in will display the message "No Java 2 SDK, Standard Edition v 1.4 support for APPLET".

Unlike the previous examples, the mapped PARAM names contain java_code, java_codebase, and java_type instead of code, codebase, and type. This is necessary because specifying code and codebase in the <PARAM> inside the <APPLET> and </APPLET> tag causes problems in some browsers.

IE on Windows reads the tags as follows:

<OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
    width="200" height="200" align="baseline"
codebase="http://java.sun.com/products/plugin/1.4/jinstall-14-win32.cab#Version=1,4,0,mn">
    <NOEMBED><XMP>
    <APPLET code="XYZApp.class" codebase="html/" align="baseline"
        width="200" height="200"></XMP>
    <PARAM NAME="java_code" VALUE="XYZApp.class">
    <PARAM NAME="java_codebase" VALUE="html/">
    <PARAM NAME="java_type" VALUE="application/x-java-applet;jpi-version=1.4">
    <PARAM NAME="model" VALUE="models/HyaluronicAcid.xyz">
    <PARAM NAME="scriptable" VALUE="true">
        No Java 2 SDK, Standard Edition v 1.4 support for APPLET!!
    </APPLET></NOEMBED></EMBED>
</OBJECT>

Be careful when you use the <XMP> tag. Because IE renders the <OBJECT> tag, you must disable the <APPLET> tag. If not disabled, two applets will simultaneously show up in the browser—one applet will be running in Microsoft's JVM, and the other will be running in Sun's JVM using Java Plug-in. The <XMP> tag provides a solution. The <XMP> and </XMP> tags basically transform any HTML tag that occurs between them into a stream of static text. In the above example, the <XMP> and </XMP> tags cause the browser to treat the <APPLET> tag as static text instead of an HTML tag. Because the browser ignores any static text between the <OBJECT> tag and the <PARAM> tag, the above tags actually become:

<OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
    width="200" height="200" align="baseline"
codebase="http://java.sun.com/products/plugin/1.4/jinstall-14-win32.cab#Version=1,4,0,mn">
    <PARAM NAME="java_code" VALUE="XYZApp.class">
    <PARAM NAME="java_codebase" VALUE="html/">
    <PARAM NAME="java_type" VALUE="application/x-java-applet;jpi-version=1.4">
    <PARAM NAME="model" VALUE="models/HyaluronicAcid.xyz">
    <PARAM NAME="scriptable" VALUE="true">
        No Java 2 SDK, Standard Edition v 1.4 support for APPLET!!
</OBJECT>

This is identical to the OBJECT tag example outlined above. Note that the <OBJECT> tag ignores the <NOEMBED>, </NOEMBED>, and </EMBED> tags.

Navigator on Windows operating environments reads tags as follows:

<EMBED type="application/x-java-applet;jpi-version=1.4" width="200" height="200"
    align="baseline" code="XYZApp.class" codebase="html/"
    model="models/HyaluronicAcid.xyz"
    pluginspage="http://java.sun.com/products/plugin/1.4/plugin-install.html">
<NOEMBED><XMP>
    <APPLET code="XYZApp.class" codebase="html/" align="baseline"
        width="200" height="200"></XMP>
    <PARAM NAME="java_code" VALUE="XYZApp.class">
    <PARAM NAME="java_codebase" VALUE="html/">
    <PARAM NAME="java_type" VALUE="application/x-java-applet;jpi-version=1.4">
    <PARAM NAME="model" VALUE="models/HyaluronicAcid.xyz">
    <PARAM NAME="scriptable" VALUE="true">
        No Java 2 SDK, Standard Edition v 1.4 support for APPLET!!
    </APPLET></NOEMBED></EMBED></OBJECT>

Note that the <XMP> tag is used again in the <EMBED> tag to also disable the <APPLET> tag. The <EMBED> tag ignores the <PARAM> and </OBJECT> tags as well. In effect, the above tags actually become:

<EMBED type="application/x-java-applet;jpi-version=1.4" width="200" height="200"
    align="baseline" code="XYZApp.class" codebase="html/"
    model="models/HyaluronicAcid.xyz"
    pluginspage="http://java.sun.com/products/plugin/1.4/plugin-install.html">
<NOEMBED>
        No Java 2 SDK, Standard Edition v 1.4 support for APPLET!!
</NOEMBED>
</EMBED>

This is identical to the EMBED tag example outlined above.

You can use the combined OBJECT-EMBED-JavaScript tag to activate Java Plug-in in the right browser on the right platform. This combined tag is complicated and it should be used only if your HTML page is browsed by users in a heterogenous environment.

Summary

This document describes the OBJECT tag and EMBED tag styles used by Java Plug-in. It focuses on the conversion from an APPLET tag to the OBJECT and EMBED tags. Currently, HTML 4.0 suggests that the OBJECT tag is the best way to insert Java applets and JavaBeans components into a HTML page. This document will be updated in the near future should there be a need to convert the OBJECT tag to the Java Plug-in tag style. Information disclosed in this document is intended to assist ISVs for writing HTML migration tools and to assist webmasters with Java Plug-in migration. The tag style described in this document is subject to change in the future.

Note that the use of Java Plug-in is not limited to the tag styles described in this document. In fact, webmasters are encouraged to modify the tag style or mix the tag with JavaScript to fit their needs. As long as the described OBJECT tag is used in IE and EMBED tag is used in Navigator, there should be no problems running Java Plug-in. Currently, there are several conversion templates shipped with the Java Plug-in HTML converter. Webmasters may find one template better than others for their needs, and are encouraged to modify these templates themselves if necessary.


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 Plug-in Control Panel
  • Unique Registry Keys for JRE/JDK

So that multiple JRE versions may be deployed in the same environment, every new or patch release of Java Plug-in uniquely identifies registry keys, CLSID, MIME type and other resources.

Notes: (1) For an explanation of product version numbers, see the note in the section called "Using OBJECT, EMBED and APPLET Tags in Java Plug-in." In this section, a mix of version 1.3 and 1.4 examples is given. (2) While the examples below are for Windows, multi-version support also applies to Solaris and Linux.

Unique CLSID

There is a unique CLSID for every new/patch version of Java Plug-in. (CLSID is used in the OBJECT tag with Internet Explorer running on Windows.) If you want a particular 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 for the Java Plug-in/JRE release.

Examples:

For example, the CLSID for Java Plug-in 1.4 is:

CAFEEFAC-0014-0000-0000-ABCDEFFEDCBA

and you would find this in the registry:

HKEY_CLASSES_ROOT\CLSID\CAFEEFAC-0014-0000-0000-ABCDEFFEDCBA

The CLSID for 1.3.0_03 is:

CAFEEFAC-0013-0000-0003-ABCDEFFEDCBA

and you would find this in the registry:

HKEY_CLASSES_ROOT\CLSID\CAFEEFAC-0013-0000-0003-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/patch version of Java Plug-in. (MIME type is used in the EMBED tag with Netscape and as a PARM in the OBJECT tag for Internet Explorer. NP*.dll is unique to Netscape.) If you want to use a particular version of Java Plug-in with Netscape, specify the unique MIME type in the EMBED tag.

Note that this MIME type will be supported by an NP*.dll with a unique name for every new/patch version. Thus, installing different version of Java Plug-in does not overwrite other .dll files in Navigator's Plugins directory.

In general MIME type looks like this:

application/x-java-applet;jpi-version=<version>

where version includes the major, minor and patch version numbers.

Examples:

The MIME type for the 1.4 release is:

application/x-java-applet;jpi-version=1.4

The MIME type for the 1.3.0_03 release is:

application/x-java-applet;jpi-version=1.3.0_03

MIME type is supported in the file

NPJPI<modified version number>.dll

Example:

For Java Plug-in 1.4.0_01, the unique MIME type would be:

application/x-java-applet;jpi-version=1.4.0_01

and it would be supported in the file:

NPJPI140_01.dll

in Navigator's Plugins directory.

Note

Prior to release 1.4.0, the supporting .dll file was of the form NPJava<modified version number>.dll; e.g., release 1.3.0_03 would we supported by NPJava130_03.dll.

Unique Java Plug-in Registry Key

There is a unique Java Plug-in registry key for every new/patch version of Java Plug-in. The main Java Plug-in registry key is:

HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Plug-in\<version number>

where the <version number> will include the major, minor and the patch version numbers.

Example:

For Java Plug-in 1.4 you will find the following in your registry:

HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Plug-in\1.4.0

Unique Java Plug-in Property File

As in previous versions, the property file continues to be located in <user.home>\.java. However, the filename will be unique in every new/patch release and have the following form:

<user.home>\.java\properties_<modified version number>

where the <modified version number> will include the major, minor, and patch version numbers; e.g.,

C:\WINNT\Profiles\stanleyh\.java\properties140_xx

Unique Java Plug-in Trace and Log Files

A trace file has been created automatically in <user.home> when Java Console is enabled. Its purpose is to capture in a single file the same messages that are displayed in Java Console. But in order to avoid conflict, this file is now uniquely named in every new/patch release. There is also a uniquely named log file. These files have the form:

<user.home>\.plugin<modified version number>.trace
<user.home>\.plugin<modified version number>.log

where the <modified version number> includes the major, minor and the patch version numbers; e.g., .plugin140_xx.trace

Unique Java Plug-in Control Panel

There is a unique file name for the Java Plug-in Control Panel dll in every new/patch release. From the Windows Control Panel, this allows the user to launch the Control Panel for a particular version of Java Plug-in. The filename for the dll is of the form:

plugincpl<modified version number>.cpl

where the <modified version number> will include the major, minor and the patch version numbers; e.g., plugincpl130_01.cpl

Note below that the user can choose which version of the Java Plug-in Control Panel to launch.

Windows Control Panel window

Unique Registry Keys for JRE/JDK

There are unique registry keys for every new/patch release of the JRE/JDK. Prior to release 1.3 of Java Plug-in, installating multiple versions of Java Plug-in overwrote the JRE/JDK registry keys. 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.3.0_01

These keys allow Java Plug-in to locate the proper version of JRE/JDK.


Versions Formats

Appendix 6: Sun-Supported 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.


Deva Search

Java Plug-in Search Page
Tips


About Applet Tag Support in Java Plug-in

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 2 Applet Compatibility Issues.

Q: Why should I encourage people to use the Java 2 Platform?

A: The Java 2 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 2 Platform, you can write more powerful, robust, and full-featured applications and applets. And with the Java 2 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 2 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. Moreover, the JRE/Java Plug-in continues to ship with the HTML Converter for those developers who want to invoke their applets using OBJECT rather than APPLET tags.

Q: Are there compatibility issues with using the Java 2 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 2 Platform. The documentation for a given Java 2 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 2 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 2 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 2 Platform family, and it uses the new Java 2 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 2 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.


Basics

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 2 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 2 SDK, Standard Edition
  • Full Java CompatibleTM support
  • Future-ready architecture
  • Free public download and easy install
  • Free Java Plug-in Software HTML Converter

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 2 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 2 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 2 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://java.sun.com/cgi-bin/bugreport.cgi

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 2 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 2 SDK, Standard Edition?

A: Java Plug-in Software is fully compliant with the JCK test suite for Java 2 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 2 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.


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 2 SDK, Standard Edition, web page authors must modify the page's HTML to specify the use of Sun's JRE via Java Plug-in. Sun is 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 HTML Converter, free of charge; it will automatically make the changes to the HTML of a selected web page or set of web pages.

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 can I get the the Java Plug-in Software HTML Converter?

A: The Java Plug-in HTML Converter is bundled with the J2SE SDK. It is free.

Q: How do I run the HTML Converter?

A: See More About the HTML Converter.

Q: What capabilities do the supplementary templates provide with the Java Plug-in HTML Converter?

A: The HTML Converter provides both a default template (default.tpl) and three supplementary templates. The supplementary templates allow web-page authors to more explicitly target browsers and platforms in their environment when modifying pages with the HTML Converter:

  1. default.tpl: The default template used by the Java Plug-in HTML Converter. The converted page can be used in supported versions of Internet Explorer and Navigator on supported operating systems to invoke the Java Plug-in.
  2. extend.tpl: The converted page can be used with any supported browser or platform. Java Plug-in will be invoked on all supported operating systems and browsers. If operating system or browser is not supported by Java Plug-in, then the browser's default Java runtime will be used.
  3. ieonly.tpl: The converted page can be used to invoke Java Plug-in in supported versions of Internet Explorer on supported operating systems.
  4. nsonly.tpl: The converted page can be used to invoke Java Plug-in in supported versions of Navigator on supported operating systems.

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 2 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 2 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: What happens on browsers other than IE or Navigator, or on non-supported platforms?

A: The default conversion template provided with the Java Plug-in HTML Converter is designed so that an applet will not be rendered in browsers other than Internet Explorer and Netscape Navigator on unsupported platforms. However, the Java Plug-in HTML Converter provides additional templates allowing web-page authors to specify that on non-supported platforms applets will be rendered using the original <APPLET> tag with the browser's 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.


Frequently Asked Questions

Frequently Asked Questions (FAQ)

Basic Information FAQ

Questions and answers for people unfamiliar with Java Plug-in Software. Includes information about availability, versioning and supported features.

Developer Information FAQ

Information for system administrators and people developing applets or webpages that use Java Plug-in Software. Includes information about the HTML Converter.

Troubleshooting FAQ

Answers to common problems using Java Plug-in Software. Includes installation, debugging, and security information.

About Applet Tag Support in Java Plug-in

Answers questions about support for conventional applet tage support in Java Plug-in.


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 J2SE, 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 2 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 2 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 2 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 2 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.


All Classes (Common DOM API)

 All Classes
AbstractView
Attr
CDATASection
CSS2Properties
CSSCharsetRule
CSSFontFaceRule
CSSImportRule
CSSMediaRule
CSSPageRule
CSSPrimitiveValue
CSSRule
CSSRuleList
CSSStyleDeclaration
CSSStyleRule
CSSStyleSheet
CSSUnknownRule
CSSValue
CSSValueList
CharacterData
Comment
Counter
DOMAccessException
DOMAccessor
DOMAction
DOMException
DOMImplementation
DOMImplementationCSS
DOMService
DOMServiceProvider
DOMUnsupportedException
Document
DocumentCSS
DocumentEvent
DocumentFragment
DocumentStyle
DocumentType
DocumentView
Element
ElementCSSInlineStyle
Entity
EntityReference
Event
EventException
EventListener
EventTarget
HTMLAnchorElement
HTMLAppletElement
HTMLAreaElement
HTMLBRElement
HTMLBaseElement
HTMLBaseFontElement
HTMLBodyElement
HTMLButtonElement
HTMLCollection
HTMLDListElement
HTMLDOMImplementation
HTMLDirectoryElement
HTMLDivElement
HTMLDocument
HTMLElement
HTMLFieldSetElement
HTMLFontElement
HTMLFormElement
HTMLFrameElement
HTMLFrameSetElement
HTMLHRElement
HTMLHeadElement
HTMLHeadingElement
HTMLHtmlElement
HTMLIFrameElement
HTMLImageElement
HTMLInputElement
HTMLIsIndexElement
HTMLLIElement
HTMLLabelElement
HTMLLegendElement
HTMLLinkElement
HTMLMapElement
HTMLMenuElement
HTMLMetaElement
HTMLModElement
HTMLOListElement
HTMLObjectElement
HTMLOptGroupElement
HTMLOptionElement
HTMLParagraphElement
HTMLParamElement
HTMLPreElement
HTMLQuoteElement
HTMLScriptElement
HTMLSelectElement
HTMLStyleElement
HTMLTableCaptionElement
HTMLTableCellElement
HTMLTableColElement
HTMLTableElement
HTMLTableRowElement
HTMLTableSectionElement
HTMLTextAreaElement
HTMLTitleElement
HTMLUListElement
LinkStyle
MediaList
MouseEvent
MutationEvent
NamedNodeMap
Node
NodeList
Notation
ProcessingInstruction
RGBColor
Rect
StyleSheet
StyleSheetList
Text
UIEvent
ViewCSS


Constant Field Values (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Constant Field Values

Contents
  • org.w3c.*
org.w3c.*

org.w3c.dom.DOMException
public static final short | DOMSTRING_SIZE_ERR | 2
public static final short | HIERARCHY_REQUEST_ERR | 3
public static final short | INDEX_SIZE_ERR | 1
public static final short | INUSE_ATTRIBUTE_ERR | 10
public static final short | INVALID_ACCESS_ERR | 15
public static final short | INVALID_CHARACTER_ERR | 5
public static final short | INVALID_MODIFICATION_ERR | 13
public static final short | INVALID_STATE_ERR | 11
public static final short | NAMESPACE_ERR | 14
public static final short | NO_DATA_ALLOWED_ERR | 6
public static final short | NO_MODIFICATION_ALLOWED_ERR | 7
public static final short | NOT_FOUND_ERR | 8
public static final short | NOT_SUPPORTED_ERR | 9
public static final short | SYNTAX_ERR | 12
public static final short | WRONG_DOCUMENT_ERR | 4

org.w3c.dom.Node
public static final short | ATTRIBUTE_NODE | 2
public static final short | CDATA_SECTION_NODE | 4
public static final short | COMMENT_NODE | 8
public static final short | DOCUMENT_FRAGMENT_NODE | 11
public static final short | DOCUMENT_NODE | 9
public static final short | DOCUMENT_TYPE_NODE | 10
public static final short | ELEMENT_NODE | 1
public static final short | ENTITY_NODE | 6
public static final short | ENTITY_REFERENCE_NODE | 5
public static final short | NOTATION_NODE | 12
public static final short | PROCESSING_INSTRUCTION_NODE | 7
public static final short | TEXT_NODE | 3

org.w3c.dom.css.CSSPrimitiveValue
public static final short | CSS_ATTR | 22
public static final short | CSS_CM | 6
public static final short | CSS_COUNTER | 23
public static final short | CSS_DEG | 11
public static final short | CSS_DIMENSION | 18
public static final short | CSS_EMS | 3
public static final short | CSS_EXS | 4
public static final short | CSS_GRAD | 13
public static final short | CSS_HZ | 16
public static final short | CSS_IDENT | 21
public static final short | CSS_IN | 8
public static final short | CSS_KHZ | 17
public static final short | CSS_MM | 7
public static final short | CSS_MS | 14
public static final short | CSS_NUMBER | 1
public static final short | CSS_PC | 10
public static final short | CSS_PERCENTAGE | 2
public static final short | CSS_PT | 9
public static final short | CSS_PX | 5
public static final short | CSS_RAD | 12
public static final short | CSS_RECT | 24
public static final short | CSS_RGBCOLOR | 25
public static final short | CSS_S | 15
public static final short | CSS_STRING | 19
public static final short | CSS_UNKNOWN | 0
public static final short | CSS_URI | 20

org.w3c.dom.css.CSSRule
public static final short | CHARSET_RULE | 2
public static final short | FONT_FACE_RULE | 5
public static final short | IMPORT_RULE | 3
public static final short | MEDIA_RULE | 4
public static final short | PAGE_RULE | 6
public static final short | STYLE_RULE | 1
public static final short | UNKNOWN_RULE | 0

org.w3c.dom.css.CSSValue
public static final short | CSS_CUSTOM | 3
public static final short | CSS_INHERIT | 0
public static final short | CSS_PRIMITIVE_VALUE | 1
public static final short | CSS_VALUE_LIST | 2

org.w3c.dom.events.Event
public static final short | AT_TARGET | 2
public static final short | BUBBLING_PHASE | 3
public static final short | CAPTURING_PHASE | 1

org.w3c.dom.events.EventException
public static final short UNSPECIFIED_EVENT_TYPE_ERR 0

org.w3c.dom.events.MutationEvent
public static final short | ADDITION | 2
public static final short | MODIFICATION | 1
public static final short | REMOVAL | 3

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Deprecated List (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Deprecated API

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


API Help (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

How This API Document Is Organized

This API (Application Programming Interface) document has pages corresponding to the items in the navigation bar, described as follows.

Overview

The Overview page is the front page of this API document and provides a list of all packages with a summary for each. This page can also contain an overall description of the set of packages.

Package

Each package has a page that contains a list of its classes and interfaces, with a summary for each. This page can contain four categories:

  • Interfaces (italic)
  • Classes
  • Exceptions
  • Errors

Class/Interface

Each class, interface, nested class and nested interface has its own separate page. Each of these pages has three sections consisting of a class/interface description, summary tables, and detailed member descriptions:

  • Class inheritance diagram
  • Direct Subclasses
  • All Known Subinterfaces
  • All Known Implementing Classes
  • Class/interface declaration
  • Class/interface description

  • Nested Class Summary
  • Field Summary
  • Constructor Summary
  • Method Summary

  • Field Detail
  • Constructor Detail
  • Method Detail
Each summary entry contains the first sentence from the detailed description for that item. The summary entries are alphabetical, while the detailed descriptions are in the order they appear in the source code. This preserves the logical groupings established by the programmer.

Use

Each documented package, class and interface has its own Use page. This page describes what packages, classes, methods, constructors and fields use any part of the given class 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.

Tree (Class Hierarchy)

There is a Class Hierarchy page for all packages, plus a hierarchy for each package. Each hierarchy page contains a list of classes and a list of interfaces. The classes are organized by inheritance structure starting with java.lang.Object. The interfaces do not inherit from java.lang.Object.
  • When viewing the Overview page, clicking on "Tree" displays the hierarchy for all packages.
  • When viewing a particular package, class or interface page, clicking "Tree" displays the hierarchy for only that package.

Deprecated API

The Deprecated API page lists all of the API that have been deprecated. A deprecated API is not recommended for use, generally due to improvements, and a replacement API is usually given. Deprecated APIs may be removed in future implementations.

Index

The Index contains an alphabetic list of all classes, interfaces, constructors, methods, and fields.

Prev/Next

These links take you to the next or previous class, interface, package, or related page.

Frames/No Frames

These links show and hide the HTML frames. All pages are available with or without frames.

Serialized Form

Each serializable or externalizable 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 description.

This help file applies to API documentation generated using the standard doclet.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Common DOM API

Frame Alert

This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client.
Link toNon-frame version.


Overview (Common DOM API)

Common DOM API
All Classes

Packages
com.sun.java.browser.dom
org.w3c.dom
org.w3c.dom.css
org.w3c.dom.events
org.w3c.dom.html
org.w3c.dom.stylesheets
org.w3c.dom.views


Overview (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Common DOM API

Packages
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.stylesheets |
org.w3c.dom.views |

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Class Hierarchy (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Hierarchy For All Packages

Package Hierarchies:
com.sun.java.browser.dom, org.w3c.dom, org.w3c.dom.css, org.w3c.dom.events, org.w3c.dom.html, org.w3c.dom.stylesheets, org.w3c.dom.views

Class Hierarchy

  • class java.lang.Object
    • class com.sun.java.browser.dom.DOMService
    • class com.sun.java.browser.dom.DOMServiceProvider
    • class java.lang.Throwable (implements java.io.Serializable)
      • class java.lang.Exception
        • class com.sun.java.browser.dom.DOMAccessException
        • class com.sun.java.browser.dom.DOMUnsupportedException
        • class java.lang.RuntimeException
          • class org.w3c.dom.DOMException
          • class org.w3c.dom.events.EventException

Interface Hierarchy

  • interface org.w3c.dom.views.AbstractView
    • interface org.w3c.dom.css.ViewCSS
  • interface org.w3c.dom.css.Counter
  • interface org.w3c.dom.css.CSS2Properties
  • interface org.w3c.dom.css.CSSRule
    • interface org.w3c.dom.css.CSSCharsetRule
    • interface org.w3c.dom.css.CSSFontFaceRule
    • interface org.w3c.dom.css.CSSImportRule
    • interface org.w3c.dom.css.CSSMediaRule
    • interface org.w3c.dom.css.CSSPageRule
    • interface org.w3c.dom.css.CSSStyleRule
    • interface org.w3c.dom.css.CSSUnknownRule
  • interface org.w3c.dom.css.CSSRuleList
  • interface org.w3c.dom.css.CSSStyleDeclaration
  • interface org.w3c.dom.css.CSSValue
    • interface org.w3c.dom.css.CSSPrimitiveValue
    • interface org.w3c.dom.css.CSSValueList
  • interface org.w3c.dom.events.DocumentEvent
  • interface org.w3c.dom.stylesheets.DocumentStyle
    • interface org.w3c.dom.css.DocumentCSS
  • interface org.w3c.dom.views.DocumentView
  • interface com.sun.java.browser.dom.DOMAccessor
  • interface com.sun.java.browser.dom.DOMAction
  • interface org.w3c.dom.DOMImplementation
    • interface org.w3c.dom.css.DOMImplementationCSS
    • interface org.w3c.dom.html.HTMLDOMImplementation
  • interface org.w3c.dom.css.ElementCSSInlineStyle
  • interface org.w3c.dom.events.Event
    • interface org.w3c.dom.events.MouseEvent
    • interface org.w3c.dom.events.MutationEvent
    • interface org.w3c.dom.events.UIEvent
      • interface org.w3c.dom.events.MouseEvent
  • interface org.w3c.dom.events.EventListener
  • interface org.w3c.dom.events.EventTarget
  • interface org.w3c.dom.html.HTMLCollection
  • interface org.w3c.dom.stylesheets.LinkStyle
  • interface org.w3c.dom.stylesheets.MediaList
  • interface org.w3c.dom.NamedNodeMap
  • interface org.w3c.dom.Node
    • interface org.w3c.dom.Attr
    • interface org.w3c.dom.CDATASection
    • interface org.w3c.dom.CharacterData
      • interface org.w3c.dom.CDATASection
      • interface org.w3c.dom.Comment
      • interface org.w3c.dom.Text
        • interface org.w3c.dom.CDATASection
    • interface org.w3c.dom.Comment
    • interface org.w3c.dom.Document
      • interface org.w3c.dom.html.HTMLDocument
    • interface org.w3c.dom.DocumentFragment
    • interface org.w3c.dom.DocumentType
    • interface org.w3c.dom.Element
      • interface org.w3c.dom.html.HTMLAnchorElement
      • interface org.w3c.dom.html.HTMLAppletElement
      • interface org.w3c.dom.html.HTMLAreaElement
      • interface org.w3c.dom.html.HTMLBaseElement
      • interface org.w3c.dom.html.HTMLBaseFontElement
      • interface org.w3c.dom.html.HTMLBodyElement
      • interface org.w3c.dom.html.HTMLBRElement
      • interface org.w3c.dom.html.HTMLButtonElement
      • interface org.w3c.dom.html.HTMLDirectoryElement
      • interface org.w3c.dom.html.HTMLDivElement
      • interface org.w3c.dom.html.HTMLDListElement
      • interface org.w3c.dom.html.HTMLElement
        • interface org.w3c.dom.html.HTMLAnchorElement
        • interface org.w3c.dom.html.HTMLAppletElement
        • interface org.w3c.dom.html.HTMLAreaElement
        • interface org.w3c.dom.html.HTMLBaseElement
        • interface org.w3c.dom.html.HTMLBaseFontElement
        • interface org.w3c.dom.html.HTMLBodyElement
        • interface org.w3c.dom.html.HTMLBRElement
        • interface org.w3c.dom.html.HTMLButtonElement
        • interface org.w3c.dom.html.HTMLDirectoryElement
        • interface org.w3c.dom.html.HTMLDivElement
        • interface org.w3c.dom.html.HTMLDListElement
        • interface org.w3c.dom.html.HTMLFieldSetElement
        • interface org.w3c.dom.html.HTMLFontElement
        • interface org.w3c.dom.html.HTMLFormElement
        • interface org.w3c.dom.html.HTMLFrameElement
        • interface org.w3c.dom.html.HTMLFrameSetElement
        • interface org.w3c.dom.html.HTMLHeadElement
        • interface org.w3c.dom.html.HTMLHeadingElement
        • interface org.w3c.dom.html.HTMLHRElement
        • interface org.w3c.dom.html.HTMLHtmlElement
        • interface org.w3c.dom.html.HTMLIFrameElement
        • interface org.w3c.dom.html.HTMLImageElement
        • interface org.w3c.dom.html.HTMLInputElement
        • interface org.w3c.dom.html.HTMLIsIndexElement
        • interface org.w3c.dom.html.HTMLLabelElement
        • interface org.w3c.dom.html.HTMLLegendElement
        • interface org.w3c.dom.html.HTMLLIElement
        • interface org.w3c.dom.html.HTMLLinkElement
        • interface org.w3c.dom.html.HTMLMapElement
        • interface org.w3c.dom.html.HTMLMenuElement
        • interface org.w3c.dom.html.HTMLMetaElement
        • interface org.w3c.dom.html.HTMLModElement
        • interface org.w3c.dom.html.HTMLObjectElement
        • interface org.w3c.dom.html.HTMLOListElement
        • interface org.w3c.dom.html.HTMLOptGroupElement
        • interface org.w3c.dom.html.HTMLOptionElement
        • interface org.w3c.dom.html.HTMLParagraphElement
        • interface org.w3c.dom.html.HTMLParamElement
        • interface org.w3c.dom.html.HTMLPreElement
        • interface org.w3c.dom.html.HTMLQuoteElement
        • interface org.w3c.dom.html.HTMLScriptElement
        • interface org.w3c.dom.html.HTMLSelectElement
        • interface org.w3c.dom.html.HTMLStyleElement
        • interface org.w3c.dom.html.HTMLTableCaptionElement
        • interface org.w3c.dom.html.HTMLTableCellElement
        • interface org.w3c.dom.html.HTMLTableColElement
        • interface org.w3c.dom.html.HTMLTableElement
        • interface org.w3c.dom.html.HTMLTableRowElement
        • interface org.w3c.dom.html.HTMLTableSectionElement
        • interface org.w3c.dom.html.HTMLTextAreaElement
        • interface org.w3c.dom.html.HTMLTitleElement
        • interface org.w3c.dom.html.HTMLUListElement
      • interface org.w3c.dom.html.HTMLFieldSetElement
      • interface org.w3c.dom.html.HTMLFontElement
      • interface org.w3c.dom.html.HTMLFormElement
      • interface org.w3c.dom.html.HTMLFrameElement
      • interface org.w3c.dom.html.HTMLFrameSetElement
      • interface org.w3c.dom.html.HTMLHeadElement
      • interface org.w3c.dom.html.HTMLHeadingElement
      • interface org.w3c.dom.html.HTMLHRElement
      • interface org.w3c.dom.html.HTMLHtmlElement
      • interface org.w3c.dom.html.HTMLIFrameElement
      • interface org.w3c.dom.html.HTMLImageElement
      • interface org.w3c.dom.html.HTMLInputElement
      • interface org.w3c.dom.html.HTMLIsIndexElement
      • interface org.w3c.dom.html.HTMLLabelElement
      • interface org.w3c.dom.html.HTMLLegendElement
      • interface org.w3c.dom.html.HTMLLIElement
      • interface org.w3c.dom.html.HTMLLinkElement
      • interface org.w3c.dom.html.HTMLMapElement
      • interface org.w3c.dom.html.HTMLMenuElement
      • interface org.w3c.dom.html.HTMLMetaElement
      • interface org.w3c.dom.html.HTMLModElement
      • interface org.w3c.dom.html.HTMLObjectElement
      • interface org.w3c.dom.html.HTMLOListElement
      • interface org.w3c.dom.html.HTMLOptGroupElement
      • interface org.w3c.dom.html.HTMLOptionElement
      • interface org.w3c.dom.html.HTMLParagraphElement
      • interface org.w3c.dom.html.HTMLParamElement
      • interface org.w3c.dom.html.HTMLPreElement
      • interface org.w3c.dom.html.HTMLQuoteElement
      • interface org.w3c.dom.html.HTMLScriptElement
      • interface org.w3c.dom.html.HTMLSelectElement
      • interface org.w3c.dom.html.HTMLStyleElement
      • interface org.w3c.dom.html.HTMLTableCaptionElement
      • interface org.w3c.dom.html.HTMLTableCellElement
      • interface org.w3c.dom.html.HTMLTableColElement
      • interface org.w3c.dom.html.HTMLTableElement
      • interface org.w3c.dom.html.HTMLTableRowElement
      • interface org.w3c.dom.html.HTMLTableSectionElement
      • interface org.w3c.dom.html.HTMLTextAreaElement
      • interface org.w3c.dom.html.HTMLTitleElement
      • interface org.w3c.dom.html.HTMLUListElement
    • interface org.w3c.dom.Entity
    • interface org.w3c.dom.EntityReference
    • interface org.w3c.dom.html.HTMLAnchorElement
    • interface org.w3c.dom.html.HTMLAppletElement
    • interface org.w3c.dom.html.HTMLAreaElement
    • interface org.w3c.dom.html.HTMLBaseElement
    • interface org.w3c.dom.html.HTMLBaseFontElement
    • interface org.w3c.dom.html.HTMLBodyElement
    • interface org.w3c.dom.html.HTMLBRElement
    • interface org.w3c.dom.html.HTMLButtonElement
    • interface org.w3c.dom.html.HTMLDirectoryElement
    • interface org.w3c.dom.html.HTMLDivElement
    • interface org.w3c.dom.html.HTMLDListElement
    • interface org.w3c.dom.html.HTMLDocument
    • interface org.w3c.dom.html.HTMLElement
      • interface org.w3c.dom.html.HTMLAnchorElement
      • interface org.w3c.dom.html.HTMLAppletElement
      • interface org.w3c.dom.html.HTMLAreaElement
      • interface org.w3c.dom.html.HTMLBaseElement
      • interface org.w3c.dom.html.HTMLBaseFontElement
      • interface org.w3c.dom.html.HTMLBodyElement
      • interface org.w3c.dom.html.HTMLBRElement
      • interface org.w3c.dom.html.HTMLButtonElement
      • interface org.w3c.dom.html.HTMLDirectoryElement
      • interface org.w3c.dom.html.HTMLDivElement
      • interface org.w3c.dom.html.HTMLDListElement
      • interface org.w3c.dom.html.HTMLFieldSetElement
      • interface org.w3c.dom.html.HTMLFontElement
      • interface org.w3c.dom.html.HTMLFormElement
      • interface org.w3c.dom.html.HTMLFrameElement
      • interface org.w3c.dom.html.HTMLFrameSetElement
      • interface org.w3c.dom.html.HTMLHeadElement
      • interface org.w3c.dom.html.HTMLHeadingElement
      • interface org.w3c.dom.html.HTMLHRElement
      • interface org.w3c.dom.html.HTMLHtmlElement
      • interface org.w3c.dom.html.HTMLIFrameElement
      • interface org.w3c.dom.html.HTMLImageElement
      • interface org.w3c.dom.html.HTMLInputElement
      • interface org.w3c.dom.html.HTMLIsIndexElement
      • interface org.w3c.dom.html.HTMLLabelElement
      • interface org.w3c.dom.html.HTMLLegendElement
      • interface org.w3c.dom.html.HTMLLIElement
      • interface org.w3c.dom.html.HTMLLinkElement
      • interface org.w3c.dom.html.HTMLMapElement
      • interface org.w3c.dom.html.HTMLMenuElement
      • interface org.w3c.dom.html.HTMLMetaElement
      • interface org.w3c.dom.html.HTMLModElement
      • interface org.w3c.dom.html.HTMLObjectElement
      • interface org.w3c.dom.html.HTMLOListElement
      • interface org.w3c.dom.html.HTMLOptGroupElement
      • interface org.w3c.dom.html.HTMLOptionElement
      • interface org.w3c.dom.html.HTMLParagraphElement
      • interface org.w3c.dom.html.HTMLParamElement
      • interface org.w3c.dom.html.HTMLPreElement
      • interface org.w3c.dom.html.HTMLQuoteElement
      • interface org.w3c.dom.html.HTMLScriptElement
      • interface org.w3c.dom.html.HTMLSelectElement
      • interface org.w3c.dom.html.HTMLStyleElement
      • interface org.w3c.dom.html.HTMLTableCaptionElement
      • interface org.w3c.dom.html.HTMLTableCellElement
      • interface org.w3c.dom.html.HTMLTableColElement
      • interface org.w3c.dom.html.HTMLTableElement
      • interface org.w3c.dom.html.HTMLTableRowElement
      • interface org.w3c.dom.html.HTMLTableSectionElement
      • interface org.w3c.dom.html.HTMLTextAreaElement
      • interface org.w3c.dom.html.HTMLTitleElement
      • interface org.w3c.dom.html.HTMLUListElement
    • interface org.w3c.dom.html.HTMLFieldSetElement
    • interface org.w3c.dom.html.HTMLFontElement
    • interface org.w3c.dom.html.HTMLFormElement
    • interface org.w3c.dom.html.HTMLFrameElement
    • interface org.w3c.dom.html.HTMLFrameSetElement
    • interface org.w3c.dom.html.HTMLHeadElement
    • interface org.w3c.dom.html.HTMLHeadingElement
    • interface org.w3c.dom.html.HTMLHRElement
    • interface org.w3c.dom.html.HTMLHtmlElement
    • interface org.w3c.dom.html.HTMLIFrameElement
    • interface org.w3c.dom.html.HTMLImageElement
    • interface org.w3c.dom.html.HTMLInputElement
    • interface org.w3c.dom.html.HTMLIsIndexElement
    • interface org.w3c.dom.html.HTMLLabelElement
    • interface org.w3c.dom.html.HTMLLegendElement
    • interface org.w3c.dom.html.HTMLLIElement
    • interface org.w3c.dom.html.HTMLLinkElement
    • interface org.w3c.dom.html.HTMLMapElement
    • interface org.w3c.dom.html.HTMLMenuElement
    • interface org.w3c.dom.html.HTMLMetaElement
    • interface org.w3c.dom.html.HTMLModElement
    • interface org.w3c.dom.html.HTMLObjectElement
    • interface org.w3c.dom.html.HTMLOListElement
    • interface org.w3c.dom.html.HTMLOptGroupElement
    • interface org.w3c.dom.html.HTMLOptionElement
    • interface org.w3c.dom.html.HTMLParagraphElement
    • interface org.w3c.dom.html.HTMLParamElement
    • interface org.w3c.dom.html.HTMLPreElement
    • interface org.w3c.dom.html.HTMLQuoteElement
    • interface org.w3c.dom.html.HTMLScriptElement
    • interface org.w3c.dom.html.HTMLSelectElement
    • interface org.w3c.dom.html.HTMLStyleElement
    • interface org.w3c.dom.html.HTMLTableCaptionElement
    • interface org.w3c.dom.html.HTMLTableCellElement
    • interface org.w3c.dom.html.HTMLTableColElement
    • interface org.w3c.dom.html.HTMLTableElement
    • interface org.w3c.dom.html.HTMLTableRowElement
    • interface org.w3c.dom.html.HTMLTableSectionElement
    • interface org.w3c.dom.html.HTMLTextAreaElement
    • interface org.w3c.dom.html.HTMLTitleElement
    • interface org.w3c.dom.html.HTMLUListElement
    • interface org.w3c.dom.Notation
    • interface org.w3c.dom.ProcessingInstruction
    • interface org.w3c.dom.Text
      • interface org.w3c.dom.CDATASection
  • interface org.w3c.dom.NodeList
  • interface org.w3c.dom.css.Rect
  • interface org.w3c.dom.css.RGBColor
  • interface org.w3c.dom.stylesheets.StyleSheet
    • interface org.w3c.dom.css.CSSStyleSheet
  • interface org.w3c.dom.stylesheets.StyleSheetList
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Serialized Form (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Serialized Form

Package com.sun.java.browser.dom

Class com.sun.java.browser.dom.DOMAccessException extends Exception implements Serializable

Serialized Fields

ex

Throwable ex

msg

String msg

Class com.sun.java.browser.dom.DOMUnsupportedException extends Exception implements Serializable

Serialized Fields

ex

Throwable ex

msg

String msg

Package org.w3c.dom

Class org.w3c.dom.DOMException extends RuntimeException implements Serializable

Serialized Fields

code

short code

Package org.w3c.dom.events

Class org.w3c.dom.events.EventException extends RuntimeException implements Serializable

Serialized Fields

code

short code

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


DOMAccessException (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

com.sun.java.browser.dom
Class DOMAccessException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by com.sun.java.browser.dom.DOMAccessException
All Implemented Interfaces:
Serializable
public class DOMAccessException
extends Exception

See Also:
Serialized Form

Constructor Summary
DOMAccessException()
Constructs a new DOMAccessException with no detail message.
DOMAccessException(Exception e)
Constructs a new DOMAccessException with the given exception as a root clause.
DOMAccessException(Exception e, String msg)
Constructs a new DOMAccessException with the given exception as a root clause and the given detail message.
DOMAccessException(String msg)
Constructs a new DOMAccessException with the given detail message.
Method Summary
Throwable | getCause() Returns the root cause of the error or null if there is none.
String | getMessage() Returns the detail message of the error or null if there is no detail message.
Methods inherited from class java.lang.Throwable
fillInStackTrace, getLocalizedMessage, getStackTrace, 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

DOMAccessException

public DOMAccessException()
Constructs a new DOMAccessException with no detail message.

DOMAccessException

public DOMAccessException(String msg)
Constructs a new DOMAccessException with the given detail message.

Parameters:
msg - Detail message.

DOMAccessException

public DOMAccessException(Exception e)
Constructs a new DOMAccessException with the given exception as a root clause.

Parameters:
e - Exception.

DOMAccessException

public DOMAccessException(Exception e,
                          String msg)
Constructs a new DOMAccessException with the given exception as a root clause and the given detail message.

Parameters:
e - Exception.
msg - Detail message.
Method Detail

getMessage

public String getMessage()
Returns the detail message of the error or null if there is no detail message.

getCause

public Throwable getCause()
Returns the root cause of the error or null if there is none.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


DOMAccessor (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

com.sun.java.browser.dom
Interface DOMAccessor

public interface DOMAccessor

Method Summary
Document | getDocument(Object obj) Returns the Document object of the DOM.
DOMImplementation | getDOMImplementation() Returns a DOMImplementation object.

Method Detail

getDocument

public Document getDocument(Object obj)
                     throws DOMException
Returns the Document object of the DOM.

Throws:
DOMException

getDOMImplementation

public DOMImplementation getDOMImplementation()
Returns a DOMImplementation object.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


DOMAction (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

com.sun.java.browser.dom
Interface DOMAction

public interface DOMAction

Method Summary
 Object 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.

Method Detail

run

public Object 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. accessor is used for the DOMAction to access the entry point of the browser's DOM, if necessary.

Parameters:
accessor - DOMAccessor
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


DOMService (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

com.sun.java.browser.dom
Class DOMService

java.lang.Object
    extended by com.sun.java.browser.dom.DOMService
public abstract class DOMService
extends Object

Constructor Summary
DOMService()
An empty constructor is provided.
Method Summary
static DOMService | getService(Object obj) Returns new instance of a DOMService.
abstract Object | invokeAndWait(DOMAction action) Causes action.run() to be executed synchronously on the DOM action dispatching thread.
abstract void | invokeLater(DOMAction action) Causes action.run() to be executed asynchronously on the DOM action dispatching thread.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DOMService

public DOMService()
An empty constructor is provided. Implementations of this abstract class must provide a public 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.

Method Detail

getService

public static DOMService getService(Object obj)
                             throws DOMUnsupportedException
Returns new instance of a DOMService. The implementation of the DOMService returns depends on the setting of the com.sun.java.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.

Parameters:
obj - Object to leverage the DOMService
Throws:
DOMUnsupportedException

invokeAndWait

public abstract Object invokeAndWait(DOMAction action)
                              throws DOMAccessException
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. If the DOMAction.run() method throws any DOM security related exception (on the DOM action dispatching thread), it's caught and re-thrown, as an DOMSecurityException, on the caller's thread.

Parameters:
action - DOMAction.
Throws:
DOMAccessException

invokeLater

public abstract void invokeLater(DOMAction action)
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.

Parameters:
action - DOMAction.
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


DOMServiceProvider (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

com.sun.java.browser.dom
Class DOMServiceProvider

java.lang.Object
    extended by com.sun.java.browser.dom.DOMServiceProvider
public abstract class DOMServiceProvider
extends Object

Constructor Summary
DOMServiceProvider()
An empty constructor is provided.
Method Summary
abstract boolean | canHandle(Object obj) Returns true if the DOMService can determine the association between the obj and the underlying DOM in the browser.
abstract Document | getDocument(Object obj) Returns the Document object of the DOM.
abstract DOMImplementation | getDOMImplementation() Returns the DOMImplemenation object of the DOM.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DOMServiceProvider

public DOMServiceProvider()
An empty constructor is provided. Implementations should provide a public 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.

Method Detail

canHandle

public abstract boolean canHandle(Object obj)
Returns true if the DOMService can determine the association between the obj and the underlying DOM in the browser.

getDocument

public abstract Document getDocument(Object obj)
                              throws DOMUnsupportedException
Returns the Document object of the DOM.

Throws:
DOMUnsupportedException

getDOMImplementation

public abstract DOMImplementation getDOMImplementation()
Returns the DOMImplemenation object of the DOM.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


DOMUnsupportedException (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

com.sun.java.browser.dom
Class DOMUnsupportedException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by com.sun.java.browser.dom.DOMUnsupportedException
All Implemented Interfaces:
Serializable
public class DOMUnsupportedException
extends Exception

See Also:
Serialized Form

Constructor Summary
DOMUnsupportedException()
Constructs a new DOMUnsupportedException with no detail message.
DOMUnsupportedException(Exception e)
Constructs a new DOMUnsupportedException with the given exception as a root clause.
DOMUnsupportedException(Exception e, String msg)
Constructs a new DOMUnsupportedException with the given exception as a root clause and the given detail message.
DOMUnsupportedException(String msg)
Constructs a new DOMUnsupportedException with the given detail message.
Method Summary
Throwable | getCause() Returns the root cause of the error or null if there is none.
String | getMessage() Returns the detail message of the error or null if there is no detail message.
Methods inherited from class java.lang.Throwable
fillInStackTrace, getLocalizedMessage, getStackTrace, 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

DOMUnsupportedException

public DOMUnsupportedException()
Constructs a new DOMUnsupportedException with no detail message.

DOMUnsupportedException

public DOMUnsupportedException(String msg)
Constructs a new DOMUnsupportedException with the given detail message.

Parameters:
msg - Detail message.

DOMUnsupportedException

public DOMUnsupportedException(Exception e)
Constructs a new DOMUnsupportedException with the given exception as a root clause.

Parameters:
e - Exception.

DOMUnsupportedException

public DOMUnsupportedException(Exception e,
                               String msg)
Constructs a new DOMUnsupportedException with the given exception as a root clause and the given detail message.

Parameters:
e - Exception.
msg - Detail message.
Method Detail

getMessage

public String getMessage()
Returns the detail message of the error or null if there is no detail message.

getCause

public Throwable getCause()
Returns the root cause of the error or null if there is none.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


com.sun.java.browser.dom (Common DOM API)

 com.sun.java.browser.dom
Interfaces
DOMAccessor
DOMAction
Classes
DOMService
DOMServiceProvider
Exceptions
DOMAccessException
DOMUnsupportedException


com.sun.java.browser.dom (Common DOM API)

Common DOM API
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package com.sun.java.browser.dom

Interface Summary
DOMAccessor
DOMAction

Class Summary
DOMService
DOMServiceProvider

Exception Summary
DOMAccessException
DOMUnsupportedException

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


com.sun.java.browser.dom Class Hierarchy (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Hierarchy For Package com.sun.java.browser.dom

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class com.sun.java.browser.dom.DOMService
    • class com.sun.java.browser.dom.DOMServiceProvider
    • class java.lang.Throwable (implements java.io.Serializable)
      • class java.lang.Exception
        • class com.sun.java.browser.dom.DOMAccessException
        • class com.sun.java.browser.dom.DOMUnsupportedException

Interface Hierarchy

  • interface com.sun.java.browser.dom.DOMAccessor
  • interface com.sun.java.browser.dom.DOMAction
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Package com.sun.java.browser.dom (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Package
com.sun.java.browser.dom

Packages that use com.sun.java.browser.dom
com.sun.java.browser.dom

Classes in com.sun.java.browser.dom used by com.sun.java.browser.dom
DOMAccessException
DOMAccessor
DOMAction
DOMService
DOMUnsupportedException

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Class com.sun.java.browser.dom.DOMAccessException (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.java.browser.dom.DOMAccessException

Packages that use DOMAccessException
com.sun.java.browser.dom

Uses of DOMAccessException in com.sun.java.browser.dom

Methods in com.sun.java.browser.dom that throw DOMAccessException
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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface com.sun.java.browser.dom.DOMAccessor (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.java.browser.dom.DOMAccessor

Packages that use DOMAccessor
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
 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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface com.sun.java.browser.dom.DOMAction (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.java.browser.dom.DOMAction

Packages that use DOMAction
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
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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Class com.sun.java.browser.dom.DOMService (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.java.browser.dom.DOMService

Packages that use DOMService
com.sun.java.browser.dom

Uses of DOMService in com.sun.java.browser.dom

Methods in com.sun.java.browser.dom that return DOMService
static DOMService DOMService.getService(Object obj)
Returns new instance of a DOMService.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Class com.sun.java.browser.dom.DOMServiceProvider (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Class com.sun.java.browser.dom.DOMUnsupportedException (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.java.browser.dom.DOMUnsupportedException

Packages that use DOMUnsupportedException
com.sun.java.browser.dom

Uses of DOMUnsupportedException in com.sun.java.browser.dom

Methods in com.sun.java.browser.dom that throw DOMUnsupportedException
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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


A-Index (Common DOM API)

Common DOM API
PREV LETTER NEXT LETTER FRAMES NO FRAMES
A B C D E F G H I L M N O P R S T U V W

A

ADDITION - Static variable in interface org.w3c.dom.events.MutationEvent
The Attr was just added.
ATTRIBUTE_NODE - Static variable in interface org.w3c.dom.Node
The node is an Attr.
AT_TARGET - Static variable in interface org.w3c.dom.events.Event
The event is currently being evaluated at the target EventTarget.
AbstractView - interface org.w3c.dom.views.AbstractView.
A base interface that all views shall derive from.
Attr - interface org.w3c.dom.Attr.
The Attr interface represents an attribute in an Element object.
add(HTMLElement, HTMLElement) - Method in interface org.w3c.dom.html.HTMLSelectElement
Add a new element to the collection of OPTION elements for this SELECT .
addEventListener(String, EventListener, boolean) - Method in interface org.w3c.dom.events.EventTarget
This method allows the registration of event listeners on the event target.
appendChild(Node) - Method in interface org.w3c.dom.Node
Adds the node newChild to the end of the list of children of this node.
appendData(String) - Method in interface org.w3c.dom.CharacterData
Append the string to the end of the character data of the node.
appendMedium(String) - Method in interface org.w3c.dom.stylesheets.MediaList
Adds the medium newMedium to the end of the list.
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV LETTER NEXT LETTER FRAMES NO FRAMES
A B C D E F G H I L M N O P R S T U V W
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


B-Index (Common DOM API)

Common DOM API
PREV LETTER NEXT LETTER FRAMES NO FRAMES
A B C D E F G H I L M N O P R S T U V W

B

BUBBLING_PHASE - Static variable in interface org.w3c.dom.events.Event
The current event phase is the bubbling phase.
blur() - Method in interface org.w3c.dom.html.HTMLAnchorElement
Removes keyboard focus from this element.
blur() - Method in interface org.w3c.dom.html.HTMLInputElement
Removes keyboard focus from this element.
blur() - Method in interface org.w3c.dom.html.HTMLSelectElement
Removes keyboard focus from this element.
blur() - Method in interface org.w3c.dom.html.HTMLTextAreaElement
Removes keyboard focus from this element.
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
A B C D E F G H I L M N O P R S T U V W
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


C-Index (Common DOM API)

Common DOM API
PREV LETTER NEXT LETTER FRAMES NO FRAMES
A B C D E F G H I L M N O P R S T U V W

C

CAPTURING_PHASE - Static variable in interface org.w3c.dom.events.Event
The current event phase is the capturing phase.
CDATASection - interface org.w3c.dom.CDATASection.
CDATA sections are used to escape blocks of text containing characters that would otherwise be regarded as markup.
CDATA_SECTION_NODE - Static variable in interface org.w3c.dom.Node
The node is a CDATASection.
CHARSET_RULE - Static variable in interface org.w3c.dom.css.CSSRule
The rule is a CSSCharsetRule.
COMMENT_NODE - Static variable in interface org.w3c.dom.Node
The node is a Comment.
CSS2Properties - interface org.w3c.dom.css.CSS2Properties.
The CSS2Properties interface represents a convenience mechanism for retrieving and setting properties within a CSSStyleDeclaration.
CSSCharsetRule - interface org.w3c.dom.css.CSSCharsetRule.
The CSSCharsetRule interface represents a @charset rule in a CSS style sheet.
CSSFontFaceRule - interface org.w3c.dom.css.CSSFontFaceRule.
The CSSFontFaceRule interface represents a @font-face rule in a CSS style sheet.
CSSImportRule - interface org.w3c.dom.css.CSSImportRule.
The CSSImportRule interface represents a @import rule within a CSS style sheet.
CSSMediaRule - interface org.w3c.dom.css.CSSMediaRule.
The CSSMediaRule interface represents a @media rule in a CSS style sheet.
CSSPageRule - interface org.w3c.dom.css.CSSPageRule.
The CSSPageRule interface represents a @page rule within a CSS style sheet.
CSSPrimitiveValue - interface org.w3c.dom.css.CSSPrimitiveValue.
The CSSPrimitiveValue interface represents a single CSS value .
CSSRule - interface org.w3c.dom.css.CSSRule.
The CSSRule interface is the abstract base interface for any type of CSS statement.
CSSRuleList - interface org.w3c.dom.css.CSSRuleList.
The CSSRuleList interface provides the abstraction of an ordered collection of CSS rules.
CSSStyleDeclaration - interface org.w3c.dom.css.CSSStyleDeclaration.
The CSSStyleDeclaration interface represents a single CSS declaration block.
CSSStyleRule - interface org.w3c.dom.css.CSSStyleRule.
The CSSStyleRule interface represents a single rule set in a CSS style sheet.
CSSStyleSheet - interface org.w3c.dom.css.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".
CSSUnknownRule - interface org.w3c.dom.css.CSSUnknownRule.
The CSSUnknownRule interface represents an at-rule not supported by this user agent.
CSSValue - interface org.w3c.dom.css.CSSValue.
The CSSValue interface represents a simple or a complex value.
CSSValueList - interface org.w3c.dom.css.CSSValueList.
The CSSValueList interface provides the abstraction of an ordered collection of CSS values.
CSS_ATTR - Static variable in interface org.w3c.dom.css.CSSPrimitiveValue
The value is a attribute function.
CSS_CM - Static variable in interface org.w3c.dom.css.CSSPrimitiveValue
The value is a length (cm).
CSS_COUNTER - Static variable in interface org.w3c.dom.css.CSSPrimitiveValue
The value is a counter or counters function.
CSS_CUSTOM - Static variable in interface org.w3c.dom.css.CSSValue
The value is a custom value.
CSS_DEG - Static variable in interface org.w3c.dom.css.CSSPrimitiveValue
The value is an angle (deg).
CSS_DIMENSION - Static variable in interface org.w3c.dom.css.CSSPrimitiveValue
The value is a number with an unknown dimension.
CSS_EMS - Static variable in interface org.w3c.dom.css.CSSPrimitiveValue
The value is a length (ems).
CSS_EXS - Static variable in interface org.w3c.dom.css.CSSPrimitiveValue
The value is a length (exs).
CSS_GRAD - Static variable in interface org.w3c.dom.css.CSSPrimitiveValue
The value is an angle (grad).
CSS_HZ - Static variable in interface org.w3c.dom.css.CSSPrimitiveValue
The value is a frequency (Hz).
CSS_IDENT - Static variable in interface org.w3c.dom.css.CSSPrimitiveValue
The value is an identifier.
CSS_IN - Static variable in interface org.w3c.dom.css.CSSPrimitiveValue
The value is a length (in).
CSS_INHERIT - Static variable in interface org.w3c.dom.css.CSSValue
The value is inherited and the cssText contains "inherit".
CSS_KHZ - Static variable in interface org.w3c.dom.css.CSSPrimitiveValue
The value is a frequency (kHz).
CSS_MM - Static variable in interface org.w3c.dom.css.CSSPrimitiveValue
The value is a length (mm).
CSS_MS - Static variable in interface org.w3c.dom.css.CSSPrimitiveValue
The value is a time (ms).
CSS_NUMBER - Static variable in interface org.w3c.dom.css.CSSPrimitiveValue
The value is a simple number.
CSS_PC - Static variable in interface org.w3c.dom.css.CSSPrimitiveValue
The value is a length (pc).
CSS_PERCENTAGE - Static variable in interface org.w3c.dom.css.CSSPrimitiveValue
The value is a percentage.
CSS_PRIMITIVE_VALUE - Static variable in interface org.w3c.dom.css.CSSValue
The value is a primitive value and an instance of the CSSPrimitiveValue interface can be obtained by using binding-specific casting methods on this instance of the CSSValue interface.
CSS_PT - Static variable in interface org.w3c.dom.css.CSSPrimitiveValue
The value is a length (pt).
CSS_PX - Static variable in interface org.w3c.dom.css.CSSPrimitiveValue
The value is a length (px).
CSS_RAD - Static variable in interface org.w3c.dom.css.CSSPrimitiveValue
The value is an angle (rad).
CSS_RECT - Static variable in interface org.w3c.dom.css.CSSPrimitiveValue
The value is a rect function.
CSS_RGBCOLOR - Static variable in interface org.w3c.dom.css.CSSPrimitiveValue
The value is a RGB color.
CSS_S - Static variable in interface org.w3c.dom.css.CSSPrimitiveValue
The value is a time (s).
CSS_STRING - Static variable in interface org.w3c.dom.css.CSSPrimitiveValue
The value is a STRING.
CSS_UNKNOWN - Static variable in interface org.w3c.dom.css.CSSPrimitiveValue
The value is not a recognized CSS2 value.
CSS_URI - Static variable in interface org.w3c.dom.css.CSSPrimitiveValue
The value is a URI.
CSS_VALUE_LIST - Static variable in interface org.w3c.dom.css.CSSValue
The value is a CSSValue list and an instance of the CSSValueList interface can be obtained by using binding-specific casting methods on this instance of the CSSValue interface.
CharacterData - interface org.w3c.dom.CharacterData.
The CharacterData interface extends Node with a set of attributes and methods for accessing character data in the DOM.
Comment - interface org.w3c.dom.Comment.
This interface inherits from CharacterData and represents the content of a comment, i.e., all the characters between the starting ' <!--' and ending '-->'.
Counter - interface org.w3c.dom.css.Counter.
The Counter interface is used to represent any counter or counters function value.
canHandle(Object) - Method in class com.sun.java.browser.dom.DOMServiceProvider
Returns true if the DOMService can determine the association between the obj and the underlying DOM in the browser.
click() - Method in interface org.w3c.dom.html.HTMLInputElement
Simulate a mouse-click.
cloneNode(boolean) - Method in interface org.w3c.dom.Node
Returns a duplicate of this node, i.e., serves as a generic copy constructor for nodes.
close() - Method in interface org.w3c.dom.html.HTMLDocument
Closes a document stream opened by open() and forces rendering.
code - Variable in class org.w3c.dom.DOMException
code - Variable in class org.w3c.dom.events.EventException
com.sun.java.browser.dom - package com.sun.java.browser.dom
createAttribute(String) - Method in interface org.w3c.dom.Document
Creates an Attr of the given name.
createAttributeNS(String, String) - Method in interface org.w3c.dom.Document
Creates an attribute of the given qualified name and namespace URI.
createCDATASection(String) - Method in interface org.w3c.dom.Document
Creates a CDATASection node whose value is the specified string.
createCSSStyleSheet(String, String) - Method in interface org.w3c.dom.css.DOMImplementationCSS
Creates a new CSSStyleSheet.
createCaption() - Method in interface org.w3c.dom.html.HTMLTableElement
Create a new table caption object or return an existing one.
createComment(String) - Method in interface org.w3c.dom.Document
Creates a Comment node given the specified string.
createDocument(String, String, DocumentType) - Method in interface org.w3c.dom.DOMImplementation
Creates a DOM Document object of the specified type with its document element.
createDocumentFragment() - Method in interface org.w3c.dom.Document
Creates an empty DocumentFragment object.
createDocumentType(String, String, String) - Method in interface org.w3c.dom.DOMImplementation
Creates an empty DocumentType node.
createElement(String) - Method in interface org.w3c.dom.Document
Creates an element of the type specified.
createElementNS(String, String) - Method in interface org.w3c.dom.Document
Creates an element of the given qualified name and namespace URI.
createEntityReference(String) - Method in interface org.w3c.dom.Document
Creates an EntityReference object.
createEvent(String) - Method in interface org.w3c.dom.events.DocumentEvent
createHTMLDocument(String) - Method in interface org.w3c.dom.html.HTMLDOMImplementation
Creates an HTMLDocument object with the minimal tree made of the following elements: HTML , HEAD , TITLE , and BODY .
createProcessingInstruction(String, String) - Method in interface org.w3c.dom.Document
Creates a ProcessingInstruction node given the specified name and data strings.
createTFoot() - Method in interface org.w3c.dom.html.HTMLTableElement
Create a table footer row or return an existing one.
createTHead() - Method in interface org.w3c.dom.html.HTMLTableElement
Create a table header row or return an existing one.
createTextNode(String) - Method in interface org.w3c.dom.Document
Creates a Text node given the specified string.
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
A B C D E F G H I L M N O P R S T U V W
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


D-Index (Common DOM API)

Common DOM API
PREV LETTER NEXT LETTER FRAMES NO FRAMES
A B C D E F G H I L M N O P R S T U V W

D

DOCUMENT_FRAGMENT_NODE - Static variable in interface org.w3c.dom.Node
The node is a DocumentFragment.
DOCUMENT_NODE - Static variable in interface org.w3c.dom.Node
The node is a Document.
DOCUMENT_TYPE_NODE - Static variable in interface org.w3c.dom.Node
The node is a DocumentType.
DOMAccessException - exception com.sun.java.browser.dom.DOMAccessException.
DOMAccessException() - Constructor for class com.sun.java.browser.dom.DOMAccessException
Constructs a new DOMAccessException with no detail message.
DOMAccessException(String) - Constructor for class com.sun.java.browser.dom.DOMAccessException
Constructs a new DOMAccessException with the given detail message.
DOMAccessException(Exception) - Constructor for class com.sun.java.browser.dom.DOMAccessException
Constructs a new DOMAccessException with the given exception as a root clause.
DOMAccessException(Exception, String) - Constructor for class com.sun.java.browser.dom.DOMAccessException
Constructs a new DOMAccessException with the given exception as a root clause and the given detail message.
DOMAccessor - interface com.sun.java.browser.dom.DOMAccessor.
DOMAction - interface com.sun.java.browser.dom.DOMAction.
DOMException - exception org.w3c.dom.DOMException.
DOM operations only raise exceptions in "exceptional" circumstances, i.e., when an operation is impossible to perform (either for logical reasons, because data is lost, or because the implementation has become unstable).
DOMException(short, String) - Constructor for class org.w3c.dom.DOMException
DOMImplementation - interface org.w3c.dom.DOMImplementation.
The DOMImplementation interface provides a number of methods for performing operations that are independent of any particular instance of the document object model.
DOMImplementationCSS - interface org.w3c.dom.css.DOMImplementationCSS.
This interface allows the DOM user to create a CSSStyleSheet outside the context of a document.
DOMSTRING_SIZE_ERR - Static variable in class org.w3c.dom.DOMException
If the specified range of text does not fit into a DOMString
DOMService - class com.sun.java.browser.dom.DOMService.
DOMService() - Constructor for class com.sun.java.browser.dom.DOMService
An empty constructor is provided.
DOMServiceProvider - class com.sun.java.browser.dom.DOMServiceProvider.
DOMServiceProvider() - Constructor for class com.sun.java.browser.dom.DOMServiceProvider
An empty constructor is provided.
DOMUnsupportedException - exception com.sun.java.browser.dom.DOMUnsupportedException.
DOMUnsupportedException() - Constructor for class com.sun.java.browser.dom.DOMUnsupportedException
Constructs a new DOMUnsupportedException with no detail message.
DOMUnsupportedException(String) - Constructor for class com.sun.java.browser.dom.DOMUnsupportedException
Constructs a new DOMUnsupportedException with the given detail message.
DOMUnsupportedException(Exception) - Constructor for class com.sun.java.browser.dom.DOMUnsupportedException
Constructs a new DOMUnsupportedException with the given exception as a root clause.
DOMUnsupportedException(Exception, String) - Constructor for class com.sun.java.browser.dom.DOMUnsupportedException
Constructs a new DOMUnsupportedException with the given exception as a root clause and the given detail message.
Document - interface org.w3c.dom.Document.
The Document interface represents the entire HTML or XML document.
DocumentCSS - interface org.w3c.dom.css.DocumentCSS.
This interface represents a document with a CSS view.
DocumentEvent - interface org.w3c.dom.events.DocumentEvent.
The DocumentEvent interface provides a mechanism by which the user can create an Event of a type supported by the implementation.
DocumentFragment - interface org.w3c.dom.DocumentFragment.
DocumentFragment is a "lightweight" or "minimal" Document object.
DocumentStyle - interface org.w3c.dom.stylesheets.DocumentStyle.
The DocumentStyle interface provides a mechanism by which the style sheets embedded in a document can be retrieved.
DocumentType - interface org.w3c.dom.DocumentType.
Each Document has a doctype attribute whose value is either null or a DocumentType object.
DocumentView - interface org.w3c.dom.views.DocumentView.
The DocumentView interface is implemented by Document objects in DOM implementations supporting DOM Views.
deleteCaption() - Method in interface org.w3c.dom.html.HTMLTableElement
Delete the table caption, if one exists.
deleteCell(int) - Method in interface org.w3c.dom.html.HTMLTableRowElement
Delete a cell from the current row.
deleteData(int, int) - Method in interface org.w3c.dom.CharacterData
Remove a range of 16-bit units from the node.
deleteMedium(String) - Method in interface org.w3c.dom.stylesheets.MediaList
Deletes the medium indicated by oldMedium from the list.
deleteRow(int) - Method in interface org.w3c.dom.html.HTMLTableElement
Delete a table row.
deleteRow(int) - Method in interface org.w3c.dom.html.HTMLTableSectionElement
Delete a row from this section.
deleteRule(int) - Method in interface org.w3c.dom.css.CSSMediaRule
Used to delete a rule from the media block.
deleteRule(int) - Method in interface org.w3c.dom.css.CSSStyleSheet
Used to delete a rule from the style sheet.
deleteTFoot() - Method in interface org.w3c.dom.html.HTMLTableElement
Delete the footer from the table, if one exists.
deleteTHead() - Method in interface org.w3c.dom.html.HTMLTableElement
Delete the header from the table, if one exists.
dispatchEvent(Event) - Method in interface org.w3c.dom.events.EventTarget
This method allows the dispatch of events into the implementations event model.
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
A B C D E F G H I L M N O P R S T U V W
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


E-Index (Common DOM API)

Common DOM API
PREV LETTER NEXT LETTER FRAMES NO FRAMES
A B C D E F G H I L M N O P R S T U V W

E

ELEMENT_NODE - Static variable in interface org.w3c.dom.Node
The node is an Element.
ENTITY_NODE - Static variable in interface org.w3c.dom.Node
The node is an Entity.
ENTITY_REFERENCE_NODE - Static variable in interface org.w3c.dom.Node
The node is an EntityReference.
Element - interface org.w3c.dom.Element.
The Element interface represents an element in an HTML or XML document.
ElementCSSInlineStyle - interface org.w3c.dom.css.ElementCSSInlineStyle.
Inline style information attached to elements is exposed through the style attribute.
Entity - interface org.w3c.dom.Entity.
This interface represents an entity, either parsed or unparsed, in an XML document.
EntityReference - interface org.w3c.dom.EntityReference.
EntityReference objects may be inserted into the structure model when an entity reference is in the source document, or when the user wishes to insert an entity reference.
Event - interface org.w3c.dom.events.Event.
The Event interface is used to provide contextual information about an event to the handler processing the event.
EventException - exception org.w3c.dom.events.EventException.
Event operations may throw an EventException as specified in their method descriptions.
EventException(short, String) - Constructor for class org.w3c.dom.events.EventException
EventListener - interface org.w3c.dom.events.EventListener.
The EventListener interface is the primary method for handling events.
EventTarget - interface org.w3c.dom.events.EventTarget.
The EventTarget interface is implemented by all Nodes in an implementation which supports the DOM Event Model.
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
A B C D E F G H I L M N O P R S T U V W
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


F-Index (Common DOM API)

Common DOM API
PREV LETTER NEXT LETTER FRAMES NO FRAMES
A B C D E F G H I L M N O P R S T U V W

F

FONT_FACE_RULE - Static variable in interface org.w3c.dom.css.CSSRule
The rule is a CSSFontFaceRule.
focus() - Method in interface org.w3c.dom.html.HTMLAnchorElement
Gives keyboard focus to this element.
focus() - Method in interface org.w3c.dom.html.HTMLInputElement
Gives keyboard focus to this element.
focus() - Method in interface org.w3c.dom.html.HTMLSelectElement
Gives keyboard focus to this element.
focus() - Method in interface org.w3c.dom.html.HTMLTextAreaElement
Gives keyboard focus to this element.
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
A B C D E F G H I L M N O P R S T U V W
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


G-Index (Common DOM API)

Common DOM API
PREV LETTER NEXT LETTER FRAMES NO FRAMES
A B C D E F G H I L M N O P R S T U V W

G

getALink() - Method in interface org.w3c.dom.html.HTMLBodyElement
Color of active links (after mouse-button down, but before mouse-button up).
getAbbr() - Method in interface org.w3c.dom.html.HTMLTableCellElement
Abbreviation for header cells.
getAccept() - Method in interface org.w3c.dom.html.HTMLInputElement
A comma-separated list of content types that a server processing this form will handle correctly.
getAcceptCharset() - Method in interface org.w3c.dom.html.HTMLFormElement
List of character sets supported by the server.
getAccessKey() - Method in interface org.w3c.dom.html.HTMLAnchorElement
A single character access key to give access to the form control.
getAccessKey() - Method in interface org.w3c.dom.html.HTMLAreaElement
A single character access key to give access to the form control.
getAccessKey() - Method in interface org.w3c.dom.html.HTMLButtonElement
A single character access key to give access to the form control.
getAccessKey() - Method in interface org.w3c.dom.html.HTMLInputElement
A single character access key to give access to the form control.
getAccessKey() - Method in interface org.w3c.dom.html.HTMLLabelElement
A single character access key to give access to the form control.
getAccessKey() - Method in interface org.w3c.dom.html.HTMLLegendElement
A single character access key to give access to the form control.
getAccessKey() - Method in interface org.w3c.dom.html.HTMLTextAreaElement
A single character access key to give access to the form control.
getAction() - Method in interface org.w3c.dom.html.HTMLFormElement
Server-side form handler.
getAlign() - Method in interface org.w3c.dom.html.HTMLAppletElement
Aligns this object (vertically or horizontally) with respect to its surrounding text.
getAlign() - Method in interface org.w3c.dom.html.HTMLDivElement
Horizontal text alignment.
getAlign() - Method in interface org.w3c.dom.html.HTMLHRElement
Align the rule on the page.
getAlign() - Method in interface org.w3c.dom.html.HTMLHeadingElement
Horizontal text alignment.
getAlign() - Method in interface org.w3c.dom.html.HTMLIFrameElement
Aligns this object (vertically or horizontally) with respect to its surrounding text.
getAlign() - Method in interface org.w3c.dom.html.HTMLImageElement
Aligns this object (vertically or horizontally) with respect to its surrounding text.
getAlign() - Method in interface org.w3c.dom.html.HTMLInputElement
Aligns this object (vertically or horizontally) with respect to its surrounding text.
getAlign() - Method in interface org.w3c.dom.html.HTMLLegendElement
Text alignment relative to FIELDSET .
getAlign() - Method in interface org.w3c.dom.html.HTMLObjectElement
Aligns this object (vertically or horizontally) with respect to its surrounding text.
getAlign() - Method in interface org.w3c.dom.html.HTMLParagraphElement
Horizontal text alignment.
getAlign() - Method in interface org.w3c.dom.html.HTMLTableCaptionElement
Caption alignment with respect to the table.
getAlign() - Method in interface org.w3c.dom.html.HTMLTableCellElement
Horizontal alignment of data in cell.
getAlign() - Method in interface org.w3c.dom.html.HTMLTableColElement
Horizontal alignment of cell data in column.
getAlign() - Method in interface org.w3c.dom.html.HTMLTableElement
Specifies the table's position with respect to the rest of the document.
getAlign() - Method in interface org.w3c.dom.html.HTMLTableRowElement
Horizontal alignment of data within cells of this row.
getAlign() - Method in interface org.w3c.dom.html.HTMLTableSectionElement
Horizontal alignment of data in cells.
getAlt() - Method in interface org.w3c.dom.html.HTMLAppletElement
Alternate text for user agents not rendering the normal content of this element.
getAlt() - Method in interface org.w3c.dom.html.HTMLAreaElement
Alternate text for user agents not rendering the normal content of this element.
getAlt() - Method in interface org.w3c.dom.html.HTMLImageElement
Alternate text for user agents not rendering the normal content of this element.
getAlt() - Method in interface org.w3c.dom.html.HTMLInputElement
Alternate text for user agents not rendering the normal content of this element.
getAltKey() - Method in interface org.w3c.dom.events.MouseEvent
Used to indicate whether the 'alt' key was depressed during the firing of the event.
getAnchors() - Method in interface org.w3c.dom.html.HTMLDocument
A collection of all the anchor (A ) elements in a document with a value for the name attribute.
getApplets() - Method in interface org.w3c.dom.html.HTMLDocument
A collection of all the OBJECT elements that include applets and APPLET ( deprecated ) elements in a document.
getArchive() - Method in interface org.w3c.dom.html.HTMLAppletElement
Comma-separated archive list.
getArchive() - Method in interface org.w3c.dom.html.HTMLObjectElement
Space-separated list of archives.
getAreas() - Method in interface org.w3c.dom.html.HTMLMapElement
The list of areas defined for the image map.
getAttrChange() - Method in interface org.w3c.dom.events.MutationEvent
attrChange indicates the type of change which triggered the DOMAttrModified event.
getAttrName() - Method in interface org.w3c.dom.events.MutationEvent
attrName indicates the name of the changed Attr node in a DOMAttrModified event.
getAttribute(String) - Method in interface org.w3c.dom.Element
Retrieves an attribute value by name.
getAttributeNS(String, String) - Method in interface org.w3c.dom.Element
Retrieves an attribute value by local name and namespace URI.
getAttributeNode(String) - Method in interface org.w3c.dom.Element
Retrieves an attribute node by name.
getAttributeNodeNS(String, String) - Method in interface org.w3c.dom.Element
Retrieves an Attr node by local name and namespace URI.
getAttributes() - Method in interface org.w3c.dom.Node
A NamedNodeMap containing the attributes of this node (if it is an Element) or null otherwise.
getAxis() - Method in interface org.w3c.dom.html.HTMLTableCellElement
Names group of related headers.
getAzimuth() - Method in interface org.w3c.dom.css.CSS2Properties
See the azimuth property definition in CSS2.
getBackground() - Method in interface org.w3c.dom.css.CSS2Properties
See the background property definition in CSS2.
getBackground() - Method in interface org.w3c.dom.html.HTMLBodyElement
URI of the background texture tile image.
getBackgroundAttachment() - Method in interface org.w3c.dom.css.CSS2Properties
See the background-attachment property definition in CSS2.
getBackgroundColor() - Method in interface org.w3c.dom.css.CSS2Properties
See the background-color property definition in CSS2.
getBackgroundImage() - Method in interface org.w3c.dom.css.CSS2Properties
See the background-image property definition in CSS2.
getBackgroundPosition() - Method in interface org.w3c.dom.css.CSS2Properties
See the background-position property definition in CSS2.
getBackgroundRepeat() - Method in interface org.w3c.dom.css.CSS2Properties
See the background-repeat property definition in CSS2.
getBgColor() - Method in interface org.w3c.dom.html.HTMLBodyElement
Document background color.
getBgColor() - Method in interface org.w3c.dom.html.HTMLTableCellElement
Cell background color.
getBgColor() - Method in interface org.w3c.dom.html.HTMLTableElement
Cell background color.
getBgColor() - Method in interface org.w3c.dom.html.HTMLTableRowElement
Background color for rows.
getBlue() - Method in interface org.w3c.dom.css.RGBColor
This attribute is used for the blue value of the RGB color.
getBody() - Method in interface org.w3c.dom.html.HTMLDocument
The element that contains the content for the document.
getBorder() - Method in interface org.w3c.dom.css.CSS2Properties
See the border property definition in CSS2.
getBorder() - Method in interface org.w3c.dom.html.HTMLImageElement
Width of border around image.
getBorder() - Method in interface org.w3c.dom.html.HTMLObjectElement
Width of border around the object.
getBorder() - Method in interface org.w3c.dom.html.HTMLTableElement
The width of the border around the table.
getBorderBottom() - Method in interface org.w3c.dom.css.CSS2Properties
See the border-bottom property definition in CSS2.
getBorderBottomColor() - Method in interface org.w3c.dom.css.CSS2Properties
See the border-bottom-color property definition in CSS2.
getBorderBottomStyle() - Method in interface org.w3c.dom.css.CSS2Properties
See the border-bottom-style property definition in CSS2.
getBorderBottomWidth() - Method in interface org.w3c.dom.css.CSS2Properties
See the border-bottom-width property definition in CSS2.
getBorderCollapse() - Method in interface org.w3c.dom.css.CSS2Properties
See the border-collapse property definition in CSS2.
getBorderColor() - Method in interface org.w3c.dom.css.CSS2Properties
See the border-color property definition in CSS2.
getBorderLeft() - Method in interface org.w3c.dom.css.CSS2Properties
See the border-left property definition in CSS2.
getBorderLeftColor() - Method in interface org.w3c.dom.css.CSS2Properties
See the border-left-color property definition in CSS2.
getBorderLeftStyle() - Method in interface org.w3c.dom.css.CSS2Properties
See the border-left-style property definition in CSS2.
getBorderLeftWidth() - Method in interface org.w3c.dom.css.CSS2Properties
See the border-left-width property definition in CSS2.
getBorderRight() - Method in interface org.w3c.dom.css.CSS2Properties
See the border-right property definition in CSS2.
getBorderRightColor() - Method in interface org.w3c.dom.css.CSS2Properties
See the border-right-color property definition in CSS2.
getBorderRightStyle() - Method in interface org.w3c.dom.css.CSS2Properties
See the border-right-style property definition in CSS2.
getBorderRightWidth() - Method in interface org.w3c.dom.css.CSS2Properties
See the border-right-width property definition in CSS2.
getBorderSpacing() - Method in interface org.w3c.dom.css.CSS2Properties
See the border-spacing property definition in CSS2.
getBorderStyle() - Method in interface org.w3c.dom.css.CSS2Properties
See the border-style property definition in CSS2.
getBorderTop() - Method in interface org.w3c.dom.css.CSS2Properties
See the border-top property definition in CSS2.
getBorderTopColor() - Method in interface org.w3c.dom.css.CSS2Properties
See the border-top-color property definition in CSS2.
getBorderTopStyle() - Method in interface org.w3c.dom.css.CSS2Properties
See the border-top-style property definition in CSS2.
getBorderTopWidth() - Method in interface org.w3c.dom.css.CSS2Properties
See the border-top-width property definition in CSS2.
getBorderWidth() - Method in interface org.w3c.dom.css.CSS2Properties
See the border-width property definition in CSS2.
getBottom() - Method in interface org.w3c.dom.css.CSS2Properties
See the bottom property definition in CSS2.
getBottom() - Method in interface org.w3c.dom.css.Rect
This attribute is used for the bottom of the rect.
getBubbles() - Method in interface org.w3c.dom.events.Event
Used to indicate whether or not an event is a bubbling event.
getButton() - Method in interface org.w3c.dom.events.MouseEvent
During mouse events caused by the depression or release of a mouse button, button is used to indicate which mouse button changed state.
getCancelable() - Method in interface org.w3c.dom.events.Event
Used to indicate whether or not an event can have its default action prevented.
getCaption() - Method in interface org.w3c.dom.html.HTMLTableElement
Returns the table's CAPTION , or void if none exists.
getCaptionSide() - Method in interface org.w3c.dom.css.CSS2Properties
See the caption-side property definition in CSS2.
getCause() - Method in class com.sun.java.browser.dom.DOMAccessException
Returns the root cause of the error or null if there is none.
getCause() - Method in class com.sun.java.browser.dom.DOMUnsupportedException
Returns the root cause of the error or null if there is none.
getCellIndex() - Method in interface org.w3c.dom.html.HTMLTableCellElement
The index of this cell in the row, starting from 0.
getCellPadding() - Method in interface org.w3c.dom.html.HTMLTableElement
Specifies the horizontal and vertical space between cell content and cell borders.
getCellSpacing() - Method in interface org.w3c.dom.html.HTMLTableElement
Specifies the horizontal and vertical separation between cells.
getCells() - Method in interface org.w3c.dom.html.HTMLTableRowElement
The collection of cells in this row.
getCh() - Method in interface org.w3c.dom.html.HTMLTableCellElement
Alignment character for cells in a column.
getCh() - Method in interface org.w3c.dom.html.HTMLTableColElement
Alignment character for cells in a column.
getCh() - Method in interface org.w3c.dom.html.HTMLTableRowElement
Alignment character for cells in a column.
getCh() - Method in interface org.w3c.dom.html.HTMLTableSectionElement
Alignment character for cells in a column.
getChOff() - Method in interface org.w3c.dom.html.HTMLTableCellElement
Offset of alignment character.
getChOff() - Method in interface org.w3c.dom.html.HTMLTableColElement
Offset of alignment character.
getChOff() - Method in interface org.w3c.dom.html.HTMLTableRowElement
Offset of alignment character.
getChOff() - Method in interface org.w3c.dom.html.HTMLTableSectionElement
Offset of alignment character.
getCharset() - Method in interface org.w3c.dom.html.HTMLAnchorElement
The character encoding of the linked resource.
getCharset() - Method in interface org.w3c.dom.html.HTMLLinkElement
The character encoding of the resource being linked to.
getCharset() - Method in interface org.w3c.dom.html.HTMLScriptElement
The character encoding of the linked resource.
getChecked() - Method in interface org.w3c.dom.html.HTMLInputElement
When the type attribute of the element has the value "Radio" or "Checkbox", this represents the current state of the form control, in an interactive user agent.
getChildNodes() - Method in interface org.w3c.dom.Node
A NodeList that contains all children of this node.
getCite() - Method in interface org.w3c.dom.html.HTMLModElement
A URI designating a document that describes the reason for the change.
getCite() - Method in interface org.w3c.dom.html.HTMLQuoteElement
A URI designating a source document or message.
getClassName() - Method in interface org.w3c.dom.html.HTMLElement
The class attribute of the element.
getClear() - Method in interface org.w3c.dom.css.CSS2Properties
See the clear property definition in CSS2.
getClear() - Method in interface org.w3c.dom.html.HTMLBRElement
Control flow of text around floats.
getClientX() - Method in interface org.w3c.dom.events.MouseEvent
The horizontal coordinate at which the event occurred relative to the DOM implementation's client area.
getClientY() - Method in interface org.w3c.dom.events.MouseEvent
The vertical coordinate at which the event occurred relative to the DOM implementation's client area.
getClip() - Method in interface org.w3c.dom.css.CSS2Properties
See the clip property definition in CSS2.
getCode() - Method in interface org.w3c.dom.html.HTMLAppletElement
Applet class file.
getCode() - Method in interface org.w3c.dom.html.HTMLObjectElement
Applet class file.
getCodeBase() - Method in interface org.w3c.dom.html.HTMLAppletElement
Optional base URI for applet.
getCodeBase() - Method in interface org.w3c.dom.html.HTMLObjectElement
Base URI for classid , data , and archive attributes.
getCodeType() - Method in interface org.w3c.dom.html.HTMLObjectElement
Content type for data downloaded via classid attribute.
getColSpan() - Method in interface org.w3c.dom.html.HTMLTableCellElement
Number of columns spanned by cell.
getColor() - Method in interface org.w3c.dom.css.CSS2Properties
See the color property definition in CSS2.
getColor() - Method in interface org.w3c.dom.html.HTMLBaseFontElement
Font color.
getColor() - Method in interface org.w3c.dom.html.HTMLFontElement
Font color.
getCols() - Method in interface org.w3c.dom.html.HTMLFrameSetElement
The number of columns of frames in the frameset.
getCols() - Method in interface org.w3c.dom.html.HTMLTextAreaElement
Width of control (in characters).
getCompact() - Method in interface org.w3c.dom.html.HTMLDListElement
Reduce spacing between list items.
getCompact() - Method in interface org.w3c.dom.html.HTMLDirectoryElement
Reduce spacing between list items.
getCompact() - Method in interface org.w3c.dom.html.HTMLMenuElement
Reduce spacing between list items.
getCompact() - Method in interface org.w3c.dom.html.HTMLOListElement
Reduce spacing between list items.
getCompact() - Method in interface org.w3c.dom.html.HTMLUListElement
Reduce spacing between list items.
getComputedStyle(Element, String) - Method in interface org.w3c.dom.css.ViewCSS
This method is used to get the computed style as it is defined in .
getContent() - Method in interface org.w3c.dom.css.CSS2Properties
See the content property definition in CSS2.
getContent() - Method in interface org.w3c.dom.html.HTMLMetaElement
Associated information.
getContentDocument() - Method in interface org.w3c.dom.html.HTMLFrameElement
The document this frame contains, if there is any and it is available, or null otherwise.
getContentDocument() - Method in interface org.w3c.dom.html.HTMLIFrameElement
The document this frame contains, if there is any and it is available, or null otherwise.
getContentDocument() - Method in interface org.w3c.dom.html.HTMLObjectElement
The document this object contains, if there is any and it is available, or null otherwise.
getCookie() - Method in interface org.w3c.dom.html.HTMLDocument
The cookies associated with this document.
getCoords() - Method in interface org.w3c.dom.html.HTMLAnchorElement
Comma-separated list of lengths, defining an active region geometry.
getCoords() - Method in interface org.w3c.dom.html.HTMLAreaElement
Comma-separated list of lengths, defining an active region geometry.
getCounterIncrement() - Method in interface org.w3c.dom.css.CSS2Properties
See the counter-increment property definition in CSS2.
getCounterReset() - Method in interface org.w3c.dom.css.CSS2Properties
See the counter-reset property definition in CSS2.
getCounterValue() - Method in interface org.w3c.dom.css.CSSPrimitiveValue
This method is used to get the Counter value.
getCssFloat() - Method in interface org.w3c.dom.css.CSS2Properties
See the float property definition in CSS2.
getCssRules() - Method in interface org.w3c.dom.css.CSSMediaRule
A list of all CSS rules contained within the media block.
getCssRules() - Method in interface org.w3c.dom.css.CSSStyleSheet
The list of all CSS rules contained within the style sheet.
getCssText() - Method in interface org.w3c.dom.css.CSSRule
The parsable textual representation of the rule.
getCssText() - Method in interface org.w3c.dom.css.CSSStyleDeclaration
The parsable textual representation of the declaration block (excluding the surrounding curly braces).
getCssText() - Method in interface org.w3c.dom.css.CSSValue
A string representation of the current value.
getCssValueType() - Method in interface org.w3c.dom.css.CSSValue
A code defining the type of the value as defined above.
getCtrlKey() - Method in interface org.w3c.dom.events.MouseEvent
Used to indicate whether the 'ctrl' key was depressed during the firing of the event.
getCue() - Method in interface org.w3c.dom.css.CSS2Properties
See the cue property definition in CSS2.
getCueAfter() - Method in interface org.w3c.dom.css.CSS2Properties
See the cue-after property definition in CSS2.
getCueBefore() - Method in interface org.w3c.dom.css.CSS2Properties
See the cue-before property definition in CSS2.
getCurrentTarget() - Method in interface org.w3c.dom.events.Event
Used to indicate the EventTarget whose EventListeners are currently being processed.
getCursor() - Method in interface org.w3c.dom.css.CSS2Properties
See the cursor property definition in CSS2.
getDOMImplementation() - Method in interface com.sun.java.browser.dom.DOMAccessor
Returns a DOMImplementation object.
getDOMImplementation() - Method in class com.sun.java.browser.dom.DOMServiceProvider
Returns the DOMImplemenation object of the DOM.
getData() - Method in interface org.w3c.dom.CharacterData
The character data of the node that implements this interface.
getData() - Method in interface org.w3c.dom.ProcessingInstruction
The content of this processing instruction.
getData() - Method in interface org.w3c.dom.html.HTMLObjectElement
A URI specifying the location of the object's data.
getDateTime() - Method in interface org.w3c.dom.html.HTMLModElement
The date and time of the change.
getDeclare() - Method in interface org.w3c.dom.html.HTMLObjectElement
Declare (for future reference), but do not instantiate, this object.
getDefaultChecked() - Method in interface org.w3c.dom.html.HTMLInputElement
When type has the value "Radio" or "Checkbox", this represents the HTML checked attribute of the element.
getDefaultSelected() - Method in interface org.w3c.dom.html.HTMLOptionElement
Represents the value of the HTML selected attribute.
getDefaultValue() - Method in interface org.w3c.dom.html.HTMLInputElement
When the type attribute of the element has the value "Text", "File" or "Password", this represents the HTML value attribute of the element.
getDefaultValue() - Method in interface org.w3c.dom.html.HTMLTextAreaElement
Represents the contents of the element.
getDefaultView() - Method in interface org.w3c.dom.views.DocumentView
The default AbstractView for this Document, or null if none available.
getDefer() - Method in interface org.w3c.dom.html.HTMLScriptElement
Indicates that the user agent can defer processing of the script.
getDetail() - Method in interface org.w3c.dom.events.UIEvent
Specifies some detail information about the Event, depending on the type of event.
getDir() - Method in interface org.w3c.dom.html.HTMLElement
Specifies the base direction of directionally neutral text and the directionality of tables.
getDirection() - Method in interface org.w3c.dom.css.CSS2Properties
See the direction property definition in CSS2.
getDisabled() - Method in interface org.w3c.dom.html.HTMLButtonElement
The control is unavailable in this context.
getDisabled() - Method in interface org.w3c.dom.html.HTMLInputElement
The control is unavailable in this context.
getDisabled() - Method in interface org.w3c.dom.html.HTMLLinkElement
Enables/disables the link.
getDisabled() - Method in interface org.w3c.dom.html.HTMLOptGroupElement
The control is unavailable in this context.
getDisabled() - Method in interface org.w3c.dom.html.HTMLOptionElement
The control is unavailable in this context.
getDisabled() - Method in interface org.w3c.dom.html.HTMLSelectElement
The control is unavailable in this context.
getDisabled() - Method in interface org.w3c.dom.html.HTMLStyleElement
Enables/disables the style sheet.
getDisabled() - Method in interface org.w3c.dom.html.HTMLTextAreaElement
The control is unavailable in this context.
getDisabled() - Method in interface org.w3c.dom.stylesheets.StyleSheet
false if the style sheet is applied to the document.
getDisplay() - Method in interface org.w3c.dom.css.CSS2Properties
See the display property definition in CSS2.
getDoctype() - Method in interface org.w3c.dom.Document
The Document Type Declaration (see DocumentType) associated with this document.
getDocument(Object) - Method in interface com.sun.java.browser.dom.DOMAccessor
Returns the Document object of the DOM.
getDocument(Object) - Method in class com.sun.java.browser.dom.DOMServiceProvider
Returns the Document object of the DOM.
getDocument() - Method in interface org.w3c.dom.views.AbstractView
The source DocumentView of which this is an AbstractView.
getDocumentElement() - Method in interface org.w3c.dom.Document
This is a convenience attribute that allows direct access to the child node that is the root element of the document.
getDomain() - Method in interface org.w3c.dom.html.HTMLDocument
The domain name of the server that served the document, or null if the server cannot be identified by a domain name.
getElementById(String) - Method in interface org.w3c.dom.Document
Returns the Element whose ID is given by elementId.
getElements() - Method in interface org.w3c.dom.html.HTMLFormElement
Returns a collection of all control elements in the form.
getElementsByName(String) - Method in interface org.w3c.dom.html.HTMLDocument
Returns the (possibly empty) collection of elements whose name value is given by elementName .
getElementsByTagName(String) - Method in interface org.w3c.dom.Document
Returns a NodeList of all the Elements with a given tag name in the order in which they are encountered in a preorder traversal of the Document tree.
getElementsByTagName(String) - Method in interface org.w3c.dom.Element
Returns a NodeList of all descendant Elements with a given tag name, in the order in which they are encountered in a preorder traversal of this Element tree.
getElementsByTagNameNS(String, String) - Method in interface org.w3c.dom.Document
Returns a NodeList of all the Elements with a given local name and namespace URI in the order in which they are encountered in a preorder traversal of the Document tree.
getElementsByTagNameNS(String, String) - Method in interface org.w3c.dom.Element
Returns a NodeList of all the descendant Elements with a given local name and namespace URI in the order in which they are encountered in a preorder traversal of this Element tree.
getElevation() - Method in interface org.w3c.dom.css.CSS2Properties
See the elevation property definition in CSS2.
getEmptyCells() - Method in interface org.w3c.dom.css.CSS2Properties
See the empty-cells property definition in CSS2.
getEncoding() - Method in interface org.w3c.dom.css.CSSCharsetRule
The encoding information used in this @charset rule.
getEnctype() - Method in interface org.w3c.dom.html.HTMLFormElement
The content type of the submitted form, generally "application/x-www-form-urlencoded".
getEntities() - Method in interface org.w3c.dom.DocumentType
A NamedNodeMap containing the general entities, both external and internal, declared in the DTD.
getEvent() - Method in interface org.w3c.dom.html.HTMLScriptElement
Reserved for future use.
getEventPhase() - Method in interface org.w3c.dom.events.Event
Used to indicate which phase of event flow is currently being evaluated.
getFace() - Method in interface org.w3c.dom.html.HTMLBaseFontElement
Font face identifier.
getFace() - Method in interface org.w3c.dom.html.HTMLFontElement
Font face identifier.
getFirstChild() - Method in interface org.w3c.dom.Node
The first child of this node.
getFloatValue(short) - Method in interface org.w3c.dom.css.CSSPrimitiveValue
This method is used to get a float value in a specified unit.
getFont() - Method in interface org.w3c.dom.css.CSS2Properties
See the font property definition in CSS2.
getFontFamily() - Method in interface org.w3c.dom.css.CSS2Properties
See the font-family property definition in CSS2.
getFontSize() - Method in interface org.w3c.dom.css.CSS2Properties
See the font-size property definition in CSS2.
getFontSizeAdjust() - Method in interface org.w3c.dom.css.CSS2Properties
See the font-size-adjust property definition in CSS2.
getFontStretch() - Method in interface org.w3c.dom.css.CSS2Properties
See the font-stretch property definition in CSS2.
getFontStyle() - Method in interface org.w3c.dom.css.CSS2Properties
See the font-style property definition in CSS2.
getFontVariant() - Method in interface org.w3c.dom.css.CSS2Properties
See the font-variant property definition in CSS2.
getFontWeight() - Method in interface org.w3c.dom.css.CSS2Properties
See the font-weight property definition in CSS2.
getForm() - Method in interface org.w3c.dom.html.HTMLButtonElement
Returns the FORM element containing this control.
getForm() - Method in interface org.w3c.dom.html.HTMLFieldSetElement
Returns the FORM element containing this control.
getForm() - Method in interface org.w3c.dom.html.HTMLInputElement
Returns the FORM element containing this control.
getForm() - Method in interface org.w3c.dom.html.HTMLIsIndexElement
Returns the FORM element containing this control.
getForm() - Method in interface org.w3c.dom.html.HTMLLabelElement
Returns the FORM element containing this control.
getForm() - Method in interface org.w3c.dom.html.HTMLLegendElement
Returns the FORM element containing this control.
getForm() - Method in interface org.w3c.dom.html.HTMLObjectElement
Returns the FORM element containing this control.
getForm() - Method in interface org.w3c.dom.html.HTMLOptionElement
Returns the FORM element containing this control.
getForm() - Method in interface org.w3c.dom.html.HTMLSelectElement
Returns the FORM element containing this control.
getForm() - Method in interface org.w3c.dom.html.HTMLTextAreaElement
Returns the FORM element containing this control.
getForms() - Method in interface org.w3c.dom.html.HTMLDocument
A collection of all the forms of a document.
getFrame() - Method in interface org.w3c.dom.html.HTMLTableElement
Specifies which external table borders to render.
getFrameBorder() - Method in interface org.w3c.dom.html.HTMLFrameElement
Request frame borders.
getFrameBorder() - Method in interface org.w3c.dom.html.HTMLIFrameElement
Request frame borders.
getGreen() - Method in interface org.w3c.dom.css.RGBColor
This attribute is used for the green value of the RGB color.
getHeaders() - Method in interface org.w3c.dom.html.HTMLTableCellElement
List of id attribute values for header cells.
getHeight() - Method in interface org.w3c.dom.css.CSS2Properties
See the height property definition in CSS2.
getHeight() - Method in interface org.w3c.dom.html.HTMLAppletElement
Override height.
getHeight() - Method in interface org.w3c.dom.html.HTMLIFrameElement
Frame height.
getHeight() - Method in interface org.w3c.dom.html.HTMLImageElement
Override height.
getHeight() - Method in interface org.w3c.dom.html.HTMLObjectElement
Override height.
getHeight() - Method in interface org.w3c.dom.html.HTMLTableCellElement
Cell height.
getHref() - Method in interface org.w3c.dom.css.CSSImportRule
The location of the style sheet to be imported.
getHref() - Method in interface org.w3c.dom.html.HTMLAnchorElement
The URI of the linked resource.
getHref() - Method in interface org.w3c.dom.html.HTMLAreaElement
The URI of the linked resource.
getHref() - Method in interface org.w3c.dom.html.HTMLBaseElement
The base URI.
getHref() - Method in interface org.w3c.dom.html.HTMLLinkElement
The URI of the linked resource.
getHref() - Method in interface org.w3c.dom.stylesheets.StyleSheet
If the style sheet is a linked style sheet, the value of its attribute is its location.
getHreflang() - Method in interface org.w3c.dom.html.HTMLAnchorElement
Language code of the linked resource.
getHreflang() - Method in interface org.w3c.dom.html.HTMLLinkElement
Language code of the linked resource.
getHspace() - Method in interface org.w3c.dom.html.HTMLAppletElement
Horizontal space to the left and right of this image, applet, or object.
getHspace() - Method in interface org.w3c.dom.html.HTMLImageElement
Horizontal space to the left and right of this image.
getHspace() - Method in interface org.w3c.dom.html.HTMLObjectElement
Horizontal space to the left and right of this image, applet, or object.
getHtmlFor() - Method in interface org.w3c.dom.html.HTMLLabelElement
This attribute links this label with another form control by id attribute.
getHtmlFor() - Method in interface org.w3c.dom.html.HTMLScriptElement
Reserved for future use.
getHttpEquiv() - Method in interface org.w3c.dom.html.HTMLMetaElement
HTTP response header name.
getId() - Method in interface org.w3c.dom.html.HTMLElement
The element's identifier.
getIdentifier() - Method in interface org.w3c.dom.css.Counter
This attribute is used for the identifier of the counter.
getImages() - Method in interface org.w3c.dom.html.HTMLDocument
A collection of all the IMG elements in a document.
getImplementation() - Method in interface org.w3c.dom.Document
The DOMImplementation object that handles this document.
getIndex() - Method in interface org.w3c.dom.html.HTMLOptionElement
The index of this OPTION in its parent SELECT , starting from 0.
getInternalSubset() - Method in interface org.w3c.dom.DocumentType
The internal subset as a string, or null if there is none.
getIsMap() - Method in interface org.w3c.dom.html.HTMLImageElement
Use server-side image map.
getLabel() - Method in interface org.w3c.dom.html.HTMLOptGroupElement
Assigns a label to this option group.
getLabel() - Method in interface org.w3c.dom.html.HTMLOptionElement
Option label for use in hierarchical menus.
getLang() - Method in interface org.w3c.dom.html.HTMLElement
Language code defined in RFC 1766.
getLastChild() - Method in interface org.w3c.dom.Node
The last child of this node.
getLeft() - Method in interface org.w3c.dom.css.CSS2Properties
See the left property definition in CSS2.
getLeft() - Method in interface org.w3c.dom.css.Rect
This attribute is used for the left of the rect.
getLength() - Method in interface org.w3c.dom.CharacterData
The number of 16-bit units that are available through data and the substringData method below.
getLength() - Method in interface org.w3c.dom.NamedNodeMap
The number of nodes in this map.
getLength() - Method in interface org.w3c.dom.NodeList
The number of nodes in the list.
getLength() - Method in interface org.w3c.dom.css.CSSRuleList
The number of CSSRules in the list.
getLength() - Method in interface org.w3c.dom.css.CSSStyleDeclaration
The number of properties that have been explicitly set in this declaration block.
getLength() - Method in interface org.w3c.dom.css.CSSValueList
The number of CSSValues in the list.
getLength() - Method in interface org.w3c.dom.html.HTMLCollection
This attribute specifies the length or size of the list.
getLength() - Method in interface org.w3c.dom.html.HTMLFormElement
The number of form controls in the form.
getLength() - Method in interface org.w3c.dom.html.HTMLSelectElement
The number of options in this SELECT .
getLength() - Method in interface org.w3c.dom.stylesheets.MediaList
The number of media in the list.
getLength() - Method in interface org.w3c.dom.stylesheets.StyleSheetList
The number of StyleSheets in the list.
getLetterSpacing() - Method in interface org.w3c.dom.css.CSS2Properties
See the letter-spacing property definition in CSS2.
getLineHeight() - Method in interface org.w3c.dom.css.CSS2Properties
See the line-height property definition in CSS2.
getLink() - Method in interface org.w3c.dom.html.HTMLBodyElement
Color of links that are not active and unvisited.
getLinks() - Method in interface org.w3c.dom.html.HTMLDocument
A collection of all AREA elements and anchor ( A ) elements in a document with a value for the href attribute.
getListStyle() - Method in interface org.w3c.dom.css.CSS2Properties
See the list-style property definition in CSS2.
getListStyle() - Method in interface org.w3c.dom.css.Counter
This attribute is used for the style of the list.
getListStyleImage() - Method in interface org.w3c.dom.css.CSS2Properties
See the list-style-image property definition in CSS2.
getListStylePosition() - Method in interface org.w3c.dom.css.CSS2Properties
See the list-style-position property definition in CSS2.
getListStyleType() - Method in interface org.w3c.dom.css.CSS2Properties
See the list-style-type property definition in CSS2.
getLocalName() - Method in interface org.w3c.dom.Node
Returns the local part of the qualified name of this node.
getLongDesc() - Method in interface org.w3c.dom.html.HTMLFrameElement
URI designating a long description of this image or frame.
getLongDesc() - Method in interface org.w3c.dom.html.HTMLIFrameElement
URI designating a long description of this image or frame.
getLongDesc() - Method in interface org.w3c.dom.html.HTMLImageElement
URI designating a long description of this image or frame.
getLowSrc() - Method in interface org.w3c.dom.html.HTMLImageElement
URI designating the source of this image, for low-resolution output.
getMargin() - Method in interface org.w3c.dom.css.CSS2Properties
See the margin property definition in CSS2.
getMarginBottom() - Method in interface org.w3c.dom.css.CSS2Properties
See the margin-bottom property definition in CSS2.
getMarginHeight() - Method in interface org.w3c.dom.html.HTMLFrameElement
Frame margin height, in pixels.
getMarginHeight() - Method in interface org.w3c.dom.html.HTMLIFrameElement
Frame margin height, in pixels.
getMarginLeft() - Method in interface org.w3c.dom.css.CSS2Properties
See the margin-left property definition in CSS2.
getMarginRight() - Method in interface org.w3c.dom.css.CSS2Properties
See the margin-right property definition in CSS2.
getMarginTop() - Method in interface org.w3c.dom.css.CSS2Properties
See the margin-top property definition in CSS2.
getMarginWidth() - Method in interface org.w3c.dom.html.HTMLFrameElement
Frame margin width, in pixels.
getMarginWidth() - Method in interface org.w3c.dom.html.HTMLIFrameElement
Frame margin width, in pixels.
getMarkerOffset() - Method in interface org.w3c.dom.css.CSS2Properties
See the marker-offset property definition in CSS2.
getMarks() - Method in interface org.w3c.dom.css.CSS2Properties
See the marks property definition in CSS2.
getMaxHeight() - Method in interface org.w3c.dom.css.CSS2Properties
See the max-height property definition in CSS2.
getMaxLength() - Method in interface org.w3c.dom.html.HTMLInputElement
Maximum number of characters for text fields, when type has the value "Text" or "Password".
getMaxWidth() - Method in interface org.w3c.dom.css.CSS2Properties
See the max-width property definition in CSS2.
getMedia() - Method in interface org.w3c.dom.css.CSSImportRule
A list of media types for which this style sheet may be used.
getMedia() - Method in interface org.w3c.dom.css.CSSMediaRule
A list of media types for this rule.
getMedia() - Method in interface org.w3c.dom.html.HTMLLinkElement
Designed for use with one or more target media.
getMedia() - Method in interface org.w3c.dom.html.HTMLStyleElement
Designed for use with one or more target media.
getMedia() - Method in interface org.w3c.dom.stylesheets.StyleSheet
The intended destination media for style information.
getMediaText() - Method in interface org.w3c.dom.stylesheets.MediaList
The parsable textual representation of the media list.
getMessage() - Method in class com.sun.java.browser.dom.DOMAccessException
Returns the detail message of the error or null if there is no detail message.
getMessage() - Method in class com.sun.java.browser.dom.DOMUnsupportedException
Returns the detail message of the error or null if there is no detail message.
getMetaKey() - Method in interface org.w3c.dom.events.MouseEvent
Used to indicate whether the 'meta' key was depressed during the firing of the event.
getMethod() - Method in interface org.w3c.dom.html.HTMLFormElement
HTTP method used to submit form.
getMinHeight() - Method in interface org.w3c.dom.css.CSS2Properties
See the min-height property definition in CSS2.
getMinWidth() - Method in interface org.w3c.dom.css.CSS2Properties
See the min-width property definition in CSS2.
getMultiple() - Method in interface org.w3c.dom.html.HTMLSelectElement
If true, multiple OPTION elements may be selected in this SELECT .
getName() - Method in interface org.w3c.dom.Attr
Returns the name of this attribute.
getName() - Method in interface org.w3c.dom.DocumentType
The name of DTD; i.e., the name immediately following the DOCTYPE keyword.
getName() - Method in interface org.w3c.dom.html.HTMLAnchorElement
Anchor name.
getName() - Method in interface org.w3c.dom.html.HTMLAppletElement
The name of the applet.
getName() - Method in interface org.w3c.dom.html.HTMLButtonElement
Form control or object name when submitted with a form.
getName() - Method in interface org.w3c.dom.html.HTMLFormElement
Names the form.
getName() - Method in interface org.w3c.dom.html.HTMLFrameElement
The frame name (object of the target attribute).
getName() - Method in interface org.w3c.dom.html.HTMLIFrameElement
The frame name (object of the target attribute).
getName() - Method in interface org.w3c.dom.html.HTMLImageElement
The name of the element (for backwards compatibility).
getName() - Method in interface org.w3c.dom.html.HTMLInputElement
Form control or object name when submitted with a form.
getName() - Method in interface org.w3c.dom.html.HTMLMapElement
Names the map (for use with usemap ).
getName() - Method in interface org.w3c.dom.html.HTMLMetaElement
Meta information name.
getName() - Method in interface org.w3c.dom.html.HTMLObjectElement
Form control or object name when submitted with a form.
getName() - Method in interface org.w3c.dom.html.HTMLParamElement
The name of a run-time parameter.
getName() - Method in interface org.w3c.dom.html.HTMLSelectElement
Form control or object name when submitted with a form.
getName() - Method in interface org.w3c.dom.html.HTMLTextAreaElement
Form control or object name when submitted with a form.
getNamedItem(String) - Method in interface org.w3c.dom.NamedNodeMap
Retrieves a node specified by name.
getNamedItemNS(String, String) - Method in interface org.w3c.dom.NamedNodeMap
Retrieves a node specified by local name and namespace URI.
getNamespaceURI() - Method in interface org.w3c.dom.Node
The namespace URI of this node, or null if it is unspecified.
getNewValue() - Method in interface org.w3c.dom.events.MutationEvent
newValue indicates the new value of the Attr node in DOMAttrModified events, and of the CharacterData node in DOMCharDataModified events.
getNextSibling() - Method in interface org.w3c.dom.Node
The node immediately following this node.
getNoHref() - Method in interface org.w3c.dom.html.HTMLAreaElement
Specifies that this area is inactive, i.e., has no associated action.
getNoResize() - Method in interface org.w3c.dom.html.HTMLFrameElement
When true, forbid user from resizing frame.
getNoShade() - Method in interface org.w3c.dom.html.HTMLHRElement
Indicates to the user agent that there should be no shading in the rendering of this element.
getNoWrap() - Method in interface org.w3c.dom.html.HTMLTableCellElement
Suppress word wrapping.
getNodeName() - Method in interface org.w3c.dom.Node
The name of this node, depending on its type; see the table above.
getNodeType() - Method in interface org.w3c.dom.Node
A code representing the type of the underlying object, as defined above.
getNodeValue() - Method in interface org.w3c.dom.Node
The value of this node, depending on its type; see the table above.
getNotationName() - Method in interface org.w3c.dom.Entity
For unparsed entities, the name of the notation for the entity.
getNotations() - Method in interface org.w3c.dom.DocumentType
A NamedNodeMap containing the notations declared in the DTD.
getObject() - Method in interface org.w3c.dom.html.HTMLAppletElement
Serialized applet file.
getOptions() - Method in interface org.w3c.dom.html.HTMLSelectElement
The collection of OPTION elements contained by this element.
getOrphans() - Method in interface org.w3c.dom.css.CSS2Properties
See the orphans property definition in CSS2.
getOutline() - Method in interface org.w3c.dom.css.CSS2Properties
See the outline property definition in CSS2.
getOutlineColor() - Method in interface org.w3c.dom.css.CSS2Properties
See the outline-color property definition in CSS2.
getOutlineStyle() - Method in interface org.w3c.dom.css.CSS2Properties
See the outline-style property definition in CSS2.
getOutlineWidth() - Method in interface org.w3c.dom.css.CSS2Properties
See the outline-width property definition in CSS2.
getOverflow() - Method in interface org.w3c.dom.css.CSS2Properties
See the overflow property definition in CSS2.
getOverrideStyle(Element, String) - Method in interface org.w3c.dom.css.DocumentCSS
This method is used to retrieve the override style declaration for a specified element and a specified pseudo-element.
getOwnerDocument() - Method in interface org.w3c.dom.Node
The Document object associated with this node.
getOwnerElement() - Method in interface org.w3c.dom.Attr
The Element node this attribute is attached to or null if this attribute is not in use.
getOwnerNode() - Method in interface org.w3c.dom.stylesheets.StyleSheet
The node that associates this style sheet with the document.
getOwnerRule() - Method in interface org.w3c.dom.css.CSSStyleSheet
If this style sheet comes from an @import rule, the ownerRule attribute will contain the CSSImportRule.
getPadding() - Method in interface org.w3c.dom.css.CSS2Properties
See the padding property definition in CSS2.
getPaddingBottom() - Method in interface org.w3c.dom.css.CSS2Properties
See the padding-bottom property definition in CSS2.
getPaddingLeft() - Method in interface org.w3c.dom.css.CSS2Properties
See the padding-left property definition in CSS2.
getPaddingRight() - Method in interface org.w3c.dom.css.CSS2Properties
See the padding-right property definition in CSS2.
getPaddingTop() - Method in interface org.w3c.dom.css.CSS2Properties
See the padding-top property definition in CSS2.
getPage() - Method in interface org.w3c.dom.css.CSS2Properties
See the page property definition in CSS2.
getPageBreakAfter() - Method in interface org.w3c.dom.css.CSS2Properties
See the page-break-after property definition in CSS2.
getPageBreakBefore() - Method in interface org.w3c.dom.css.CSS2Properties
See the page-break-before property definition in CSS2.
getPageBreakInside() - Method in interface org.w3c.dom.css.CSS2Properties
See the page-break-inside property definition in CSS2.
getParentNode() - Method in interface org.w3c.dom.Node
The parent of this node.
getParentRule() - Method in interface org.w3c.dom.css.CSSRule
If this rule is contained inside another rule (e.g.
getParentRule() - Method in interface org.w3c.dom.css.CSSStyleDeclaration
The CSS rule that contains this declaration block or null if this CSSStyleDeclaration is not attached to a CSSRule.
getParentStyleSheet() - Method in interface org.w3c.dom.css.CSSRule
The style sheet that contains this rule.
getParentStyleSheet() - Method in interface org.w3c.dom.stylesheets.StyleSheet
For style sheet languages that support the concept of style sheet inclusion, this attribute represents the including style sheet, if one exists.
getPause() - Method in interface org.w3c.dom.css.CSS2Properties
See the pause property definition in CSS2.
getPauseAfter() - Method in interface org.w3c.dom.css.CSS2Properties
See the pause-after property definition in CSS2.
getPauseBefore() - Method in interface org.w3c.dom.css.CSS2Properties
See the pause-before property definition in CSS2.
getPitch() - Method in interface org.w3c.dom.css.CSS2Properties
See the pitch property definition in CSS2.
getPitchRange() - Method in interface org.w3c.dom.css.CSS2Properties
See the pitch-range property definition in CSS2.
getPlayDuring() - Method in interface org.w3c.dom.css.CSS2Properties
See the play-during property definition in CSS2.
getPosition() - Method in interface org.w3c.dom.css.CSS2Properties
See the position property definition in CSS2.
getPrefix() - Method in interface org.w3c.dom.Node
The namespace prefix of this node, or null if it is unspecified.
getPrevValue() - Method in interface org.w3c.dom.events.MutationEvent
prevValue indicates the previous value of the Attr node in DOMAttrModified events, and of the CharacterData node in DOMCharDataModified events.
getPreviousSibling() - Method in interface org.w3c.dom.Node
The node immediately preceding this node.
getPrimitiveType() - Method in interface org.w3c.dom.css.CSSPrimitiveValue
The type of the value as defined by the constants specified above.
getProfile() - Method in interface org.w3c.dom.html.HTMLHeadElement
URI designating a metadata profile.
getPrompt() - Method in interface org.w3c.dom.html.HTMLIsIndexElement
The prompt message.
getPropertyCSSValue(String) - Method in interface org.w3c.dom.css.CSSStyleDeclaration
Used to retrieve the object representation of the value of a CSS property if it has been explicitly set within this declaration block.
getPropertyPriority(String) - Method in interface org.w3c.dom.css.CSSStyleDeclaration
Used to retrieve the priority of a CSS property (e.g.
getPropertyValue(String) - Method in interface org.w3c.dom.css.CSSStyleDeclaration
Used to retrieve the value of a CSS property if it has been explicitly set within this declaration block.
getPublicId() - Method in interface org.w3c.dom.DocumentType
The public identifier of the external subset.
getPublicId() - Method in interface org.w3c.dom.Entity
The public identifier associated with the entity, if specified.
getPublicId() - Method in interface org.w3c.dom.Notation
The public identifier of this notation.
getQuotes() - Method in interface org.w3c.dom.css.CSS2Properties
See the quotes property definition in CSS2.
getRGBColorValue() - Method in interface org.w3c.dom.css.CSSPrimitiveValue
This method is used to get the RGB color.
getReadOnly() - Method in interface org.w3c.dom.html.HTMLInputElement
This control is read-only.
getReadOnly() - Method in interface org.w3c.dom.html.HTMLTextAreaElement
This control is read-only.
getRectValue() - Method in interface org.w3c.dom.css.CSSPrimitiveValue
This method is used to get the Rect value.
getRed() - Method in interface org.w3c.dom.css.RGBColor
This attribute is used for the red value of the RGB color.
getReferrer() - Method in interface org.w3c.dom.html.HTMLDocument
Returns the URI of the page that linked to this page.
getRel() - Method in interface org.w3c.dom.html.HTMLAnchorElement
Forward link type.
getRel() - Method in interface org.w3c.dom.html.HTMLLinkElement
Forward link type.
getRelatedNode() - Method in interface org.w3c.dom.events.MutationEvent
relatedNode is used to identify a secondary node related to a mutation event.
getRelatedTarget() - Method in interface org.w3c.dom.events.MouseEvent
Used to identify a secondary EventTarget related to a UI event.
getRev() - Method in interface org.w3c.dom.html.HTMLAnchorElement
Reverse link type.
getRev() - Method in interface org.w3c.dom.html.HTMLLinkElement
Reverse link type.
getRichness() - Method in interface org.w3c.dom.css.CSS2Properties
See the richness property definition in CSS2.
getRight() - Method in interface org.w3c.dom.css.CSS2Properties
See the right property definition in CSS2.
getRight() - Method in interface org.w3c.dom.css.Rect
This attribute is used for the right of the rect.
getRowIndex() - Method in interface org.w3c.dom.html.HTMLTableRowElement
The index of this row, relative to the entire table, starting from 0.
getRowSpan() - Method in interface org.w3c.dom.html.HTMLTableCellElement
Number of rows spanned by cell.
getRows() - Method in interface org.w3c.dom.html.HTMLFrameSetElement
The number of rows of frames in the frameset.
getRows() - Method in interface org.w3c.dom.html.HTMLTableElement
Returns a collection of all the rows in the table, including all in THEAD , TFOOT , all TBODY elements.
getRows() - Method in interface org.w3c.dom.html.HTMLTableSectionElement
The collection of rows in this table section.
getRows() - Method in interface org.w3c.dom.html.HTMLTextAreaElement
Number of text rows.
getRules() - Method in interface org.w3c.dom.html.HTMLTableElement
Specifies which internal table borders to render.
getScheme() - Method in interface org.w3c.dom.html.HTMLMetaElement
Select form of content.
getScope() - Method in interface org.w3c.dom.html.HTMLTableCellElement
Scope covered by header cells.
getScreenX() - Method in interface org.w3c.dom.events.MouseEvent
The horizontal coordinate at which the event occurred relative to the origin of the screen coordinate system.
getScreenY() - Method in interface org.w3c.dom.events.MouseEvent
The vertical coordinate at which the event occurred relative to the origin of the screen coordinate system.
getScrolling() - Method in interface org.w3c.dom.html.HTMLFrameElement
Specify whether or not the frame should have scrollbars.
getScrolling() - Method in interface org.w3c.dom.html.HTMLIFrameElement
Specify whether or not the frame should have scrollbars.
getSectionRowIndex() - Method in interface org.w3c.dom.html.HTMLTableRowElement
The index of this row, relative to the current section ( THEAD , TFOOT , or TBODY ), starting from 0.
getSelected() - Method in interface org.w3c.dom.html.HTMLOptionElement
Represents the current state of the corresponding form control, in an interactive user agent.
getSelectedIndex() - Method in interface org.w3c.dom.html.HTMLSelectElement
The ordinal index of the selected option, starting from 0.
getSelectorText() - Method in interface org.w3c.dom.css.CSSPageRule
The parsable textual representation of the page selector for the rule.
getSelectorText() - Method in interface org.w3c.dom.css.CSSStyleRule
The textual representation of the selector for the rule set.
getSeparator() - Method in interface org.w3c.dom.css.Counter
This attribute is used for the separator of the nested counters.
getService(Object) - Static method in class com.sun.java.browser.dom.DOMService
Returns new instance of a DOMService.
getShape() - Method in interface org.w3c.dom.html.HTMLAnchorElement
The shape of the active area.
getShape() - Method in interface org.w3c.dom.html.HTMLAreaElement
The shape of the active area.
getSheet() - Method in interface org.w3c.dom.stylesheets.LinkStyle
The style sheet.
getShiftKey() - Method in interface org.w3c.dom.events.MouseEvent
Used to indicate whether the 'shift' key was depressed during the firing of the event.
getSize() - Method in interface org.w3c.dom.css.CSS2Properties
See the size property definition in CSS2.
getSize() - Method in interface org.w3c.dom.html.HTMLBaseFontElement
Font size.
getSize() - Method in interface org.w3c.dom.html.HTMLFontElement
Font size.
getSize() - Method in interface org.w3c.dom.html.HTMLHRElement
The height of the rule.
getSize() - Method in interface org.w3c.dom.html.HTMLInputElement
Size information.
getSize() - Method in interface org.w3c.dom.html.HTMLSelectElement
Number of visible rows.
getSpan() - Method in interface org.w3c.dom.html.HTMLTableColElement
Indicates the number of columns in a group or affected by a grouping.
getSpeak() - Method in interface org.w3c.dom.css.CSS2Properties
See the speak property definition in CSS2.
getSpeakHeader() - Method in interface org.w3c.dom.css.CSS2Properties
See the speak-header property definition in CSS2.
getSpeakNumeral() - Method in interface org.w3c.dom.css.CSS2Properties
See the speak-numeral property definition in CSS2.
getSpeakPunctuation() - Method in interface org.w3c.dom.css.CSS2Properties
See the speak-punctuation property definition in CSS2.
getSpecified() - Method in interface org.w3c.dom.Attr
If this attribute was explicitly given a value in the original document, this is true; otherwise, it is false.
getSpeechRate() - Method in interface org.w3c.dom.css.CSS2Properties
See the speech-rate property definition in CSS2.
getSrc() - Method in interface org.w3c.dom.html.HTMLFrameElement
A URI designating the initial frame contents.
getSrc() - Method in interface org.w3c.dom.html.HTMLIFrameElement
A URI designating the initial frame contents.
getSrc() - Method in interface org.w3c.dom.html.HTMLImageElement
URI designating the source of this image.
getSrc() - Method in interface org.w3c.dom.html.HTMLInputElement
When the type attribute has the value "Image", this attribute specifies the location of the image to be used to decorate the graphical submit button.
getSrc() - Method in interface org.w3c.dom.html.HTMLScriptElement
URI designating an external script.
getStandby() - Method in interface org.w3c.dom.html.HTMLObjectElement
Message to render while loading the object.
getStart() - Method in interface org.w3c.dom.html.HTMLOListElement
Starting sequence number.
getStress() - Method in interface org.w3c.dom.css.CSS2Properties
See the stress property definition in CSS2.
getStringValue() - Method in interface org.w3c.dom.css.CSSPrimitiveValue
This method is used to get the string value.
getStyle() - Method in interface org.w3c.dom.css.CSSFontFaceRule
The declaration-block of this rule.
getStyle() - Method in interface org.w3c.dom.css.CSSPageRule
The declaration-block of this rule.
getStyle() - Method in interface org.w3c.dom.css.CSSStyleRule
The declaration-block of this rule set.
getStyle() - Method in interface org.w3c.dom.css.ElementCSSInlineStyle
The style attribute.
getStyleSheet() - Method in interface org.w3c.dom.css.CSSImportRule
The style sheet referred to by this rule, if it has been loaded.
getStyleSheets() - Method in interface org.w3c.dom.stylesheets.DocumentStyle
A list containing all the style sheets explicitly linked into or embedded in a document.
getSummary() - Method in interface org.w3c.dom.html.HTMLTableElement
Description about the purpose or structure of a table.
getSystemId() - Method in interface org.w3c.dom.DocumentType
The system identifier of the external subset.
getSystemId() - Method in interface org.w3c.dom.Entity
The system identifier associated with the entity, if specified.
getSystemId() - Method in interface org.w3c.dom.Notation
The system identifier of this notation.
getTBodies() - Method in interface org.w3c.dom.html.HTMLTableElement
Returns a collection of the defined table bodies.
getTFoot() - Method in interface org.w3c.dom.html.HTMLTableElement
Returns the table's TFOOT , or null if none exists.
getTHead() - Method in interface org.w3c.dom.html.HTMLTableElement
Returns the table's THEAD , or null if none exists.
getTabIndex() - Method in interface org.w3c.dom.html.HTMLAnchorElement
Index that represents the element's position in the tabbing order.
getTabIndex() - Method in interface org.w3c.dom.html.HTMLAreaElement
Index that represents the element's position in the tabbing order.
getTabIndex() - Method in interface org.w3c.dom.html.HTMLButtonElement
Index that represents the element's position in the tabbing order.
getTabIndex() - Method in interface org.w3c.dom.html.HTMLInputElement
Index that represents the element's position in the tabbing order.
getTabIndex() - Method in interface org.w3c.dom.html.HTMLObjectElement
Index that represents the element's position in the tabbing order.
getTabIndex() - Method in interface org.w3c.dom.html.HTMLSelectElement
Index that represents the element's position in the tabbing order.
getTabIndex() - Method in interface org.w3c.dom.html.HTMLTextAreaElement
Index that represents the element's position in the tabbing order.
getTableLayout() - Method in interface org.w3c.dom.css.CSS2Properties
See the table-layout property definition in CSS2.
getTagName() - Method in interface org.w3c.dom.Element
The name of the element.
getTarget() - Method in interface org.w3c.dom.ProcessingInstruction
The target of this processing instruction.
getTarget() - Method in interface org.w3c.dom.events.Event
Used to indicate the EventTarget to which the event was originally dispatched.
getTarget() - Method in interface org.w3c.dom.html.HTMLAnchorElement
Frame to render the resource in.
getTarget() - Method in interface org.w3c.dom.html.HTMLAreaElement
Frame to render the resource in.
getTarget() - Method in interface org.w3c.dom.html.HTMLBaseElement
The default target frame.
getTarget() - Method in interface org.w3c.dom.html.HTMLFormElement
Frame to render the resource in.
getTarget() - Method in interface org.w3c.dom.html.HTMLLinkElement
Frame to render the resource in.
getText() - Method in interface org.w3c.dom.html.HTMLBodyElement
Document text color.
getText() - Method in interface org.w3c.dom.html.HTMLOptionElement
The text contained within the option element.
getText() - Method in interface org.w3c.dom.html.HTMLScriptElement
The script content of the element.
getText() - Method in interface org.w3c.dom.html.HTMLTitleElement
The specified title as a string.
getTextAlign() - Method in interface org.w3c.dom.css.CSS2Properties
See the text-align property definition in CSS2.
getTextDecoration() - Method in interface org.w3c.dom.css.CSS2Properties
See the text-decoration property definition in CSS2.
getTextIndent() - Method in interface org.w3c.dom.css.CSS2Properties
See the text-indent property definition in CSS2.
getTextShadow() - Method in interface org.w3c.dom.css.CSS2Properties
See the text-shadow property definition in CSS2.
getTextTransform() - Method in interface org.w3c.dom.css.CSS2Properties
See the text-transform property definition in CSS2.
getTimeStamp() - Method in interface org.w3c.dom.events.Event
Used to specify the time (in milliseconds relative to the epoch) at which the event was created.
getTitle() - Method in interface org.w3c.dom.html.HTMLDocument
The title of a document as specified by the TITLE element in the head of the document.
getTitle() - Method in interface org.w3c.dom.html.HTMLElement
The element's advisory title.
getTitle() - Method in interface org.w3c.dom.stylesheets.StyleSheet
The advisory title.
getTop() - Method in interface org.w3c.dom.css.CSS2Properties
See the top property definition in CSS2.
getTop() - Method in interface org.w3c.dom.css.Rect
This attribute is used for the top of the rect.
getType() - Method in interface org.w3c.dom.css.CSSRule
The type of the rule, as defined above.
getType() - Method in interface org.w3c.dom.events.Event
The name of the event (case-insensitive).
getType() - Method in interface org.w3c.dom.html.HTMLAnchorElement
Advisory content type.
getType() - Method in interface org.w3c.dom.html.HTMLButtonElement
The type of button.
getType() - Method in interface org.w3c.dom.html.HTMLInputElement
The type of control created.
getType() - Method in interface org.w3c.dom.html.HTMLLIElement
List item bullet style.
getType() - Method in interface org.w3c.dom.html.HTMLLinkElement
Advisory content type.
getType() - Method in interface org.w3c.dom.html.HTMLOListElement
Numbering style.
getType() - Method in interface org.w3c.dom.html.HTMLObjectElement
Content type for data downloaded via data attribute.
getType() - Method in interface org.w3c.dom.html.HTMLParamElement
Content type for the value attribute when valuetype has the value "ref".
getType() - Method in interface org.w3c.dom.html.HTMLScriptElement
The content type of the script language.
getType() - Method in interface org.w3c.dom.html.HTMLSelectElement
The type of this form control.
getType() - Method in interface org.w3c.dom.html.HTMLStyleElement
The content type pf the style sheet language.
getType() - Method in interface org.w3c.dom.html.HTMLTextAreaElement
The type of this form control.
getType() - Method in interface org.w3c.dom.html.HTMLUListElement
Bullet style.
getType() - Method in interface org.w3c.dom.stylesheets.StyleSheet
This specifies the style sheet language for this style sheet.
getURL() - Method in interface org.w3c.dom.html.HTMLDocument
The complete URI of the document.
getUnicodeBidi() - Method in interface org.w3c.dom.css.CSS2Properties
See the unicode-bidi property definition in CSS2.
getUseMap() - Method in interface org.w3c.dom.html.HTMLImageElement
Use client-side image map.
getUseMap() - Method in interface org.w3c.dom.html.HTMLInputElement
Use client-side image map.
getUseMap() - Method in interface org.w3c.dom.html.HTMLObjectElement
Use client-side image map.
getVAlign() - Method in interface org.w3c.dom.html.HTMLTableCellElement
Vertical alignment of data in cell.
getVAlign() - Method in interface org.w3c.dom.html.HTMLTableColElement
Vertical alignment of cell data in column.
getVAlign() - Method in interface org.w3c.dom.html.HTMLTableRowElement
Vertical alignment of data within cells of this row.
getVAlign() - Method in interface org.w3c.dom.html.HTMLTableSectionElement
Vertical alignment of data in cells.
getVLink() - Method in interface org.w3c.dom.html.HTMLBodyElement
Color of links that have been visited by the user.
getValue() - Method in interface org.w3c.dom.Attr
On retrieval, the value of the attribute is returned as a string.
getValue() - Method in interface org.w3c.dom.html.HTMLButtonElement
The current form control value.
getValue() - Method in interface org.w3c.dom.html.HTMLInputElement
When the type attribute of the element has the value "Text", "File" or "Password", this represents the current contents of the corresponding form control, in an interactive user agent.
getValue() - Method in interface org.w3c.dom.html.HTMLLIElement
Reset sequence number when used in OL .
getValue() - Method in interface org.w3c.dom.html.HTMLOptionElement
The current form control value.
getValue() - Method in interface org.w3c.dom.html.HTMLParamElement
The value of a run-time parameter.
getValue() - Method in interface org.w3c.dom.html.HTMLSelectElement
The current form control value.
getValue() - Method in interface org.w3c.dom.html.HTMLTextAreaElement
Represents the current contents of the corresponding form control, in an interactive user agent.
getValueType() - Method in interface org.w3c.dom.html.HTMLParamElement
Information about the meaning of the value attribute value.
getVersion() - Method in interface org.w3c.dom.html.HTMLHtmlElement
Version information about the document's DTD.
getVerticalAlign() - Method in interface org.w3c.dom.css.CSS2Properties
See the vertical-align property definition in CSS2.
getView() - Method in interface org.w3c.dom.events.UIEvent
The view attribute identifies the AbstractView from which the event was generated.
getVisibility() - Method in interface org.w3c.dom.css.CSS2Properties
See the visibility property definition in CSS2.
getVoiceFamily() - Method in interface org.w3c.dom.css.CSS2Properties
See the voice-family property definition in CSS2.
getVolume() - Method in interface org.w3c.dom.css.CSS2Properties
See the volume property definition in CSS2.
getVspace() - Method in interface org.w3c.dom.html.HTMLAppletElement
Vertical space above and below this image, applet, or object.
getVspace() - Method in interface org.w3c.dom.html.HTMLImageElement
Vertical space above and below this image.
getVspace() - Method in interface org.w3c.dom.html.HTMLObjectElement
Vertical space above and below this image, applet, or object.
getWhiteSpace() - Method in interface org.w3c.dom.css.CSS2Properties
See the white-space property definition in CSS2.
getWidows() - Method in interface org.w3c.dom.css.CSS2Properties
See the widows property definition in CSS2.
getWidth() - Method in interface org.w3c.dom.css.CSS2Properties
See the width property definition in CSS2.
getWidth() - Method in interface org.w3c.dom.html.HTMLAppletElement
Override width.
getWidth() - Method in interface org.w3c.dom.html.HTMLHRElement
The width of the rule.
getWidth() - Method in interface org.w3c.dom.html.HTMLIFrameElement
Frame width.
getWidth() - Method in interface org.w3c.dom.html.HTMLImageElement
Override width.
getWidth() - Method in interface org.w3c.dom.html.HTMLObjectElement
Override width.
getWidth() - Method in interface org.w3c.dom.html.HTMLPreElement
Fixed width for content.
getWidth() - Method in interface org.w3c.dom.html.HTMLTableCellElement
Cell width.
getWidth() - Method in interface org.w3c.dom.html.HTMLTableColElement
Default column width.
getWidth() - Method in interface org.w3c.dom.html.HTMLTableElement
Specifies the desired table width.
getWordSpacing() - Method in interface org.w3c.dom.css.CSS2Properties
See the word-spacing property definition in CSS2.
getZIndex() - Method in interface org.w3c.dom.css.CSS2Properties
See the z-index property definition in CSS2.
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
A B C D E F G H I L M N O P R S T U V W
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


H-Index (Common DOM API)

Common DOM API
PREV LETTER NEXT LETTER FRAMES NO FRAMES
A B C D E F G H I L M N O P R S T U V W

H

HIERARCHY_REQUEST_ERR - Static variable in class org.w3c.dom.DOMException
If any node is inserted somewhere it doesn't belong
HTMLAnchorElement - interface org.w3c.dom.html.HTMLAnchorElement.
The anchor element.
HTMLAppletElement - interface org.w3c.dom.html.HTMLAppletElement.
An embedded Java applet.
HTMLAreaElement - interface org.w3c.dom.html.HTMLAreaElement.
Client-side image map area definition.
HTMLBRElement - interface org.w3c.dom.html.HTMLBRElement.
Force a line break.
HTMLBaseElement - interface org.w3c.dom.html.HTMLBaseElement.
Document base URI.
HTMLBaseFontElement - interface org.w3c.dom.html.HTMLBaseFontElement.
Base font.
HTMLBodyElement - interface org.w3c.dom.html.HTMLBodyElement.
The HTML document body.
HTMLButtonElement - interface org.w3c.dom.html.HTMLButtonElement.
Push button.
HTMLCollection - interface org.w3c.dom.html.HTMLCollection.
An HTMLCollection is a list of nodes.
HTMLDListElement - interface org.w3c.dom.html.HTMLDListElement.
Definition list.
HTMLDOMImplementation - interface org.w3c.dom.html.HTMLDOMImplementation.
The HTMLDOMImplementation interface extends the DOMImplementation interface with a method for creating an HTML document instance.
HTMLDirectoryElement - interface org.w3c.dom.html.HTMLDirectoryElement.
Directory list.
HTMLDivElement - interface org.w3c.dom.html.HTMLDivElement.
Generic block container.
HTMLDocument - interface org.w3c.dom.html.HTMLDocument.
An HTMLDocument is the root of the HTML hierarchy and holds the entire content.
HTMLElement - interface org.w3c.dom.html.HTMLElement.
All HTML element interfaces derive from this class.
HTMLFieldSetElement - interface org.w3c.dom.html.HTMLFieldSetElement.
Organizes form controls into logical groups.
HTMLFontElement - interface org.w3c.dom.html.HTMLFontElement.
Local change to font.
HTMLFormElement - interface org.w3c.dom.html.HTMLFormElement.
The FORM element encompasses behavior similar to a collection and an element.
HTMLFrameElement - interface org.w3c.dom.html.HTMLFrameElement.
Create a frame.
HTMLFrameSetElement - interface org.w3c.dom.html.HTMLFrameSetElement.
Create a grid of frames.
HTMLHRElement - interface org.w3c.dom.html.HTMLHRElement.
Create a horizontal rule.
HTMLHeadElement - interface org.w3c.dom.html.HTMLHeadElement.
Document head information.
HTMLHeadingElement - interface org.w3c.dom.html.HTMLHeadingElement.
For the H1 to H6 elements.
HTMLHtmlElement - interface org.w3c.dom.html.HTMLHtmlElement.
Root of an HTML document.
HTMLIFrameElement - interface org.w3c.dom.html.HTMLIFrameElement.
Inline subwindows.
HTMLImageElement - interface org.w3c.dom.html.HTMLImageElement.
Embedded image.
HTMLInputElement - interface org.w3c.dom.html.HTMLInputElement.
Form control.
HTMLIsIndexElement - interface org.w3c.dom.html.HTMLIsIndexElement.
This element is used for single-line text input.
HTMLLIElement - interface org.w3c.dom.html.HTMLLIElement.
List item.
HTMLLabelElement - interface org.w3c.dom.html.HTMLLabelElement.
Form field label text.
HTMLLegendElement - interface org.w3c.dom.html.HTMLLegendElement.
Provides a caption for a FIELDSET grouping.
HTMLLinkElement - interface org.w3c.dom.html.HTMLLinkElement.
The LINK element specifies a link to an external resource, and defines this document's relationship to that resource (or vice versa).
HTMLMapElement - interface org.w3c.dom.html.HTMLMapElement.
Client-side image map.
HTMLMenuElement - interface org.w3c.dom.html.HTMLMenuElement.
Menu list.
HTMLMetaElement - interface org.w3c.dom.html.HTMLMetaElement.
This contains generic meta-information about the document.
HTMLModElement - interface org.w3c.dom.html.HTMLModElement.
Notice of modification to part of a document.
HTMLOListElement - interface org.w3c.dom.html.HTMLOListElement.
Ordered list.
HTMLObjectElement - interface org.w3c.dom.html.HTMLObjectElement.
Generic embedded object.
HTMLOptGroupElement - interface org.w3c.dom.html.HTMLOptGroupElement.
Group options together in logical subdivisions.
HTMLOptionElement - interface org.w3c.dom.html.HTMLOptionElement.
A selectable choice.
HTMLParagraphElement - interface org.w3c.dom.html.HTMLParagraphElement.
Paragraphs.
HTMLParamElement - interface org.w3c.dom.html.HTMLParamElement.
Parameters fed to the OBJECT element.
HTMLPreElement - interface org.w3c.dom.html.HTMLPreElement.
Preformatted text.
HTMLQuoteElement - interface org.w3c.dom.html.HTMLQuoteElement.
For the Q and BLOCKQUOTE elements.
HTMLScriptElement - interface org.w3c.dom.html.HTMLScriptElement.
Script statements.
HTMLSelectElement - interface org.w3c.dom.html.HTMLSelectElement.
The select element allows the selection of an option.
HTMLStyleElement - interface org.w3c.dom.html.HTMLStyleElement.
Style information.
HTMLTableCaptionElement - interface org.w3c.dom.html.HTMLTableCaptionElement.
Table caption See the CAPTION element definition in HTML 4.0.
HTMLTableCellElement - interface org.w3c.dom.html.HTMLTableCellElement.
The object used to represent the TH and TD elements.
HTMLTableColElement - interface org.w3c.dom.html.HTMLTableColElement.
Regroups the COL and COLGROUP elements.
HTMLTableElement - interface org.w3c.dom.html.HTMLTableElement.
The create* and delete* methods on the table allow authors to construct and modify tables.
HTMLTableRowElement - interface org.w3c.dom.html.HTMLTableRowElement.
A row in a table.
HTMLTableSectionElement - interface org.w3c.dom.html.HTMLTableSectionElement.
The THEAD , TFOOT , and TBODY elements.
HTMLTextAreaElement - interface org.w3c.dom.html.HTMLTextAreaElement.
Multi-line text field.
HTMLTitleElement - interface org.w3c.dom.html.HTMLTitleElement.
The document title.
HTMLUListElement - interface org.w3c.dom.html.HTMLUListElement.
Unordered list.
handleEvent(Event) - Method in interface org.w3c.dom.events.EventListener
This method is called whenever an event occurs of the type for which the EventListener interface was registered.
hasAttribute(String) - Method in interface org.w3c.dom.Element
Returns true when an attribute with a given name is specified on this element or has a default value, false otherwise.
hasAttributeNS(String, String) - Method in interface org.w3c.dom.Element
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.
hasAttributes() - Method in interface org.w3c.dom.Node
Returns whether this node (if it is an element) has any attributes.
hasChildNodes() - Method in interface org.w3c.dom.Node
Returns whether this node has any children.
hasFeature(String, String) - Method in interface org.w3c.dom.DOMImplementation
Test if the DOM implementation implements a specific feature.
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
A B C D E F G H I L M N O P R S T U V W
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


I-Index (Common DOM API)

Common DOM API
PREV LETTER NEXT LETTER FRAMES NO FRAMES
A B C D E F G H I L M N O P R S T U V W

I

IMPORT_RULE - Static variable in interface org.w3c.dom.css.CSSRule
The rule is a CSSImportRule.
INDEX_SIZE_ERR - Static variable in class org.w3c.dom.DOMException
If index or size is negative, or greater than the allowed value
INUSE_ATTRIBUTE_ERR - Static variable in class org.w3c.dom.DOMException
If an attempt is made to add an attribute that is already in use elsewhere
INVALID_ACCESS_ERR - Static variable in class org.w3c.dom.DOMException
If a parameter or an operation is not supported by the underlying object.
INVALID_CHARACTER_ERR - Static variable in class org.w3c.dom.DOMException
If an invalid or illegal character is specified, such as in a name.
INVALID_MODIFICATION_ERR - Static variable in class org.w3c.dom.DOMException
If an attempt is made to modify the type of the underlying object.
INVALID_STATE_ERR - Static variable in class org.w3c.dom.DOMException
If an attempt is made to use an object that is not, or is no longer, usable.
importNode(Node, boolean) - Method in interface org.w3c.dom.Document
Imports a node from another document to this document.
initEvent(String, boolean, boolean) - Method in interface org.w3c.dom.events.Event
The initEvent method is used to initialize the value of an Event created through the DocumentEvent interface.
initMouseEvent(String, boolean, boolean, AbstractView, int, int, int, int, int, boolean, boolean, boolean, boolean, short, EventTarget) - Method in interface org.w3c.dom.events.MouseEvent
The initMouseEvent method is used to initialize the value of a MouseEvent created through the DocumentEvent interface.
initMutationEvent(String, boolean, boolean, Node, String, String, String, short) - Method in interface org.w3c.dom.events.MutationEvent
The initMutationEvent method is used to initialize the value of a MutationEvent created through the DocumentEvent interface.
initUIEvent(String, boolean, boolean, AbstractView, int) - Method in interface org.w3c.dom.events.UIEvent
The initUIEvent method is used to initialize the value of a UIEvent created through the DocumentEvent interface.
insertBefore(Node, Node) - Method in interface org.w3c.dom.Node
Inserts the node newChild before the existing child node refChild.
insertCell(int) - Method in interface org.w3c.dom.html.HTMLTableRowElement
Insert an empty TD cell into this row.
insertData(int, String) - Method in interface org.w3c.dom.CharacterData
Insert a string at the specified 16-bit unit offset.
insertRow(int) - Method in interface org.w3c.dom.html.HTMLTableElement
Insert a new empty row in the table.
insertRow(int) - Method in interface org.w3c.dom.html.HTMLTableSectionElement
Insert a row into this section.
insertRule(String, int) - Method in interface org.w3c.dom.css.CSSMediaRule
Used to insert a new rule into the media block.
insertRule(String, int) - Method in interface org.w3c.dom.css.CSSStyleSheet
Used to insert a new rule into the style sheet.
invokeAndWait(DOMAction) - Method in class com.sun.java.browser.dom.DOMService
Causes action.run() to be executed synchronously on the DOM action dispatching thread.
invokeLater(DOMAction) - Method in class com.sun.java.browser.dom.DOMService
Causes action.run() to be executed asynchronously on the DOM action dispatching thread.
isSupported(String, String) - Method in interface org.w3c.dom.Node
Tests whether the DOM implementation implements a specific feature and that feature is supported by this node.
item(int) - Method in interface org.w3c.dom.NamedNodeMap
Returns the indexth item in the map.
item(int) - Method in interface org.w3c.dom.NodeList
Returns the indexth item in the collection.
item(int) - Method in interface org.w3c.dom.css.CSSRuleList
Used to retrieve a CSS rule by ordinal index.
item(int) - Method in interface org.w3c.dom.css.CSSStyleDeclaration
Used to retrieve the properties that have been explicitly set in this declaration block.
item(int) - Method in interface org.w3c.dom.css.CSSValueList
Used to retrieve a CSSValue by ordinal index.
item(int) - Method in interface org.w3c.dom.html.HTMLCollection
This method retrieves a node specified by ordinal index.
item(int) - Method in interface org.w3c.dom.stylesheets.MediaList
Returns the indexth in the list.
item(int) - Method in interface org.w3c.dom.stylesheets.StyleSheetList
Used to retrieve a style sheet by ordinal index.
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
A B C D E F G H I L M N O P R S T U V W
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


L-Index (Common DOM API)

Common DOM API
PREV LETTER NEXT LETTER FRAMES NO FRAMES
A B C D E F G H I L M N O P R S T U V W

L

LinkStyle - interface org.w3c.dom.stylesheets.LinkStyle.
The LinkStyle interface provides a mechanism by which a style sheet can be retrieved from the node responsible for linking it into a document.
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
A B C D E F G H I L M N O P R S T U V W
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


M-Index (Common DOM API)

Common DOM API
PREV LETTER NEXT LETTER FRAMES NO FRAMES
A B C D E F G H I L M N O P R S T U V W

M

MEDIA_RULE - Static variable in interface org.w3c.dom.css.CSSRule
The rule is a CSSMediaRule.
MODIFICATION - Static variable in interface org.w3c.dom.events.MutationEvent
The Attr was modified in place.
MediaList - interface org.w3c.dom.stylesheets.MediaList.
The MediaList interface provides the abstraction of an ordered collection of media, without defining or constraining how this collection is implemented.
MouseEvent - interface org.w3c.dom.events.MouseEvent.
The MouseEvent interface provides specific contextual information associated with Mouse events.
MutationEvent - interface org.w3c.dom.events.MutationEvent.
The MutationEvent interface provides specific contextual information associated with Mutation events.
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
A B C D E F G H I L M N O P R S T U V W
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


N-Index (Common DOM API)

Common DOM API
PREV LETTER NEXT LETTER FRAMES NO FRAMES
A B C D E F G H I L M N O P R S T U V W

N

NAMESPACE_ERR - Static variable in class 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.
NOTATION_NODE - Static variable in interface org.w3c.dom.Node
The node is a Notation.
NOT_FOUND_ERR - Static variable in class org.w3c.dom.DOMException
If an attempt is made to reference a node in a context where it does not exist
NOT_SUPPORTED_ERR - Static variable in class org.w3c.dom.DOMException
If the implementation does not support the requested type of object or operation.
NO_DATA_ALLOWED_ERR - Static variable in class org.w3c.dom.DOMException
If data is specified for a node which does not support data
NO_MODIFICATION_ALLOWED_ERR - Static variable in class org.w3c.dom.DOMException
If an attempt is made to modify an object where modifications are not allowed
NamedNodeMap - interface org.w3c.dom.NamedNodeMap.
Objects implementing the NamedNodeMap interface are used to represent collections of nodes that can be accessed by name.
Node - interface org.w3c.dom.Node.
The Node interface is the primary datatype for the entire Document Object Model.
NodeList - interface org.w3c.dom.NodeList.
The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented.
Notation - interface org.w3c.dom.Notation.
This interface represents a notation declared in the DTD.
namedItem(String) - Method in interface org.w3c.dom.html.HTMLCollection
This method retrieves a Node using a name.
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.
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
A B C D E F G H I L M N O P R S T U V W
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


O-Index (Common DOM API)

Common DOM API
PREV LETTER NEXT LETTER FRAMES NO FRAMES
A B C D E F G H I L M N O P R S T U V W

O

open() - Method in interface org.w3c.dom.html.HTMLDocument
Note.
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.css - package org.w3c.dom.css
org.w3c.dom.events - package org.w3c.dom.events
org.w3c.dom.html - package org.w3c.dom.html
org.w3c.dom.stylesheets - package org.w3c.dom.stylesheets
org.w3c.dom.views - package org.w3c.dom.views
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
A B C D E F G H I L M N O P R S T U V W
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


P-Index (Common DOM API)

Common DOM API
PREV LETTER NEXT LETTER FRAMES NO FRAMES
A B C D E F G H I L M N O P R S T U V W

P

PAGE_RULE - Static variable in interface org.w3c.dom.css.CSSRule
The rule is a CSSPageRule.
PROCESSING_INSTRUCTION_NODE - Static variable in interface org.w3c.dom.Node
The node is a ProcessingInstruction.
ProcessingInstruction - interface org.w3c.dom.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.
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.
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
A B C D E F G H I L M N O P R S T U V W
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


R-Index (Common DOM API)

Common DOM API
PREV LETTER NEXT LETTER FRAMES NO FRAMES
A B C D E F G H I L M N O P R S T U V W

R

REMOVAL - Static variable in interface org.w3c.dom.events.MutationEvent
The Attr was just removed.
RGBColor - interface org.w3c.dom.css.RGBColor.
The RGBColor interface is used to represent any RGB color value.
Rect - interface org.w3c.dom.css.Rect.
The Rect interface is used to represent any rect value.
remove(int) - Method in interface org.w3c.dom.html.HTMLSelectElement
Remove an element from the collection of OPTION elements for this SELECT .
removeAttribute(String) - Method in interface org.w3c.dom.Element
Removes an attribute by name.
removeAttributeNS(String, String) - Method in interface org.w3c.dom.Element
Removes an attribute by local name and namespace URI.
removeAttributeNode(Attr) - Method in interface org.w3c.dom.Element
Removes the specified attribute node.
removeChild(Node) - Method in interface org.w3c.dom.Node
Removes the child node indicated by oldChild from the list of children, and returns it.
removeEventListener(String, EventListener, boolean) - Method in interface org.w3c.dom.events.EventTarget
This method allows the removal of event listeners from the event target.
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.
removeProperty(String) - Method in interface org.w3c.dom.css.CSSStyleDeclaration
Used to remove a CSS property if it has been explicitly set within this declaration block.
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.
reset() - Method in interface org.w3c.dom.html.HTMLFormElement
Restores a form element's default values.
run(DOMAccessor) - Method in interface com.sun.java.browser.dom.DOMAction
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
A B C D E F G H I L M N O P R S T U V W
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


S-Index (Common DOM API)

Common DOM API
PREV LETTER NEXT LETTER FRAMES NO FRAMES
A B C D E F G H I L M N O P R S T U V W

S

STYLE_RULE - Static variable in interface org.w3c.dom.css.CSSRule
The rule is a CSSStyleRule.
SYNTAX_ERR - Static variable in class org.w3c.dom.DOMException
If an invalid or illegal string is specified.
StyleSheet - interface org.w3c.dom.stylesheets.StyleSheet.
The StyleSheet interface is the abstract base interface for any type of style sheet.
StyleSheetList - interface org.w3c.dom.stylesheets.StyleSheetList.
The StyleSheetList interface provides the abstraction of an ordered collection of style sheets.
select() - Method in interface org.w3c.dom.html.HTMLInputElement
Select the contents of the text area.
select() - Method in interface org.w3c.dom.html.HTMLTextAreaElement
Select the contents of the TEXTAREA .
setALink(String) - Method in interface org.w3c.dom.html.HTMLBodyElement
setAbbr(String) - Method in interface org.w3c.dom.html.HTMLTableCellElement
setAccept(String) - Method in interface org.w3c.dom.html.HTMLInputElement
setAcceptCharset(String) - Method in interface org.w3c.dom.html.HTMLFormElement
setAccessKey(String) - Method in interface org.w3c.dom.html.HTMLAnchorElement
setAccessKey(String) - Method in interface org.w3c.dom.html.HTMLAreaElement
setAccessKey(String) - Method in interface org.w3c.dom.html.HTMLButtonElement
setAccessKey(String) - Method in interface org.w3c.dom.html.HTMLInputElement
setAccessKey(String) - Method in interface org.w3c.dom.html.HTMLLabelElement
setAccessKey(String) - Method in interface org.w3c.dom.html.HTMLLegendElement
setAccessKey(String) - Method in interface org.w3c.dom.html.HTMLTextAreaElement
setAction(String) - Method in interface org.w3c.dom.html.HTMLFormElement
setAlign(String) - Method in interface org.w3c.dom.html.HTMLAppletElement
setAlign(String) - Method in interface org.w3c.dom.html.HTMLDivElement
setAlign(String) - Method in interface org.w3c.dom.html.HTMLHRElement
setAlign(String) - Method in interface org.w3c.dom.html.HTMLHeadingElement
setAlign(String) - Method in interface org.w3c.dom.html.HTMLIFrameElement
setAlign(String) - Method in interface org.w3c.dom.html.HTMLImageElement
setAlign(String) - Method in interface org.w3c.dom.html.HTMLInputElement
setAlign(String) - Method in interface org.w3c.dom.html.HTMLLegendElement
setAlign(String) - Method in interface org.w3c.dom.html.HTMLObjectElement
setAlign(String) - Method in interface org.w3c.dom.html.HTMLParagraphElement
setAlign(String) - Method in interface org.w3c.dom.html.HTMLTableCaptionElement
setAlign(String) - Method in interface org.w3c.dom.html.HTMLTableCellElement
setAlign(String) - Method in interface org.w3c.dom.html.HTMLTableColElement
setAlign(String) - Method in interface org.w3c.dom.html.HTMLTableElement
setAlign(String) - Method in interface org.w3c.dom.html.HTMLTableRowElement
setAlign(String) - Method in interface org.w3c.dom.html.HTMLTableSectionElement
setAlt(String) - Method in interface org.w3c.dom.html.HTMLAppletElement
setAlt(String) - Method in interface org.w3c.dom.html.HTMLAreaElement
setAlt(String) - Method in interface org.w3c.dom.html.HTMLImageElement
setAlt(String) - Method in interface org.w3c.dom.html.HTMLInputElement
setArchive(String) - Method in interface org.w3c.dom.html.HTMLAppletElement
setArchive(String) - Method in interface org.w3c.dom.html.HTMLObjectElement
setAttribute(String, String) - Method in interface org.w3c.dom.Element
Adds a new attribute.
setAttributeNS(String, String, String) - Method in interface org.w3c.dom.Element
Adds a new attribute.
setAttributeNode(Attr) - Method in interface org.w3c.dom.Element
Adds a new attribute node.
setAttributeNodeNS(Attr) - Method in interface org.w3c.dom.Element
Adds a new attribute.
setAxis(String) - Method in interface org.w3c.dom.html.HTMLTableCellElement
setAzimuth(String) - Method in interface org.w3c.dom.css.CSS2Properties
setBackground(String) - Method in interface org.w3c.dom.css.CSS2Properties
setBackground(String) - Method in interface org.w3c.dom.html.HTMLBodyElement
setBackgroundAttachment(String) - Method in interface org.w3c.dom.css.CSS2Properties
setBackgroundColor(String) - Method in interface org.w3c.dom.css.CSS2Properties
setBackgroundImage(String) - Method in interface org.w3c.dom.css.CSS2Properties
setBackgroundPosition(String) - Method in interface org.w3c.dom.css.CSS2Properties
setBackgroundRepeat(String) - Method in interface org.w3c.dom.css.CSS2Properties
setBgColor(String) - Method in interface org.w3c.dom.html.HTMLBodyElement
setBgColor(String) - Method in interface org.w3c.dom.html.HTMLTableCellElement
setBgColor(String) - Method in interface org.w3c.dom.html.HTMLTableElement
setBgColor(String) - Method in interface org.w3c.dom.html.HTMLTableRowElement
setBody(HTMLElement) - Method in interface org.w3c.dom.html.HTMLDocument
setBorder(String) - Method in interface org.w3c.dom.css.CSS2Properties
setBorder(String) - Method in interface org.w3c.dom.html.HTMLImageElement
setBorder(String) - Method in interface org.w3c.dom.html.HTMLObjectElement
setBorder(String) - Method in interface org.w3c.dom.html.HTMLTableElement
setBorderBottom(String) - Method in interface org.w3c.dom.css.CSS2Properties
setBorderBottomColor(String) - Method in interface org.w3c.dom.css.CSS2Properties
setBorderBottomStyle(String) - Method in interface org.w3c.dom.css.CSS2Properties
setBorderBottomWidth(String) - Method in interface org.w3c.dom.css.CSS2Properties
setBorderCollapse(String) - Method in interface org.w3c.dom.css.CSS2Properties
setBorderColor(String) - Method in interface org.w3c.dom.css.CSS2Properties
setBorderLeft(String) - Method in interface org.w3c.dom.css.CSS2Properties
setBorderLeftColor(String) - Method in interface org.w3c.dom.css.CSS2Properties
setBorderLeftStyle(String) - Method in interface org.w3c.dom.css.CSS2Properties
setBorderLeftWidth(String) - Method in interface org.w3c.dom.css.CSS2Properties
setBorderRight(String) - Method in interface org.w3c.dom.css.CSS2Properties
setBorderRightColor(String) - Method in interface org.w3c.dom.css.CSS2Properties
setBorderRightStyle(String) - Method in interface org.w3c.dom.css.CSS2Properties
setBorderRightWidth(String) - Method in interface org.w3c.dom.css.CSS2Properties
setBorderSpacing(String) - Method in interface org.w3c.dom.css.CSS2Properties
setBorderStyle(String) - Method in interface org.w3c.dom.css.CSS2Properties
setBorderTop(String) - Method in interface org.w3c.dom.css.CSS2Properties
setBorderTopColor(String) - Method in interface org.w3c.dom.css.CSS2Properties
setBorderTopStyle(String) - Method in interface org.w3c.dom.css.CSS2Properties
setBorderTopWidth(String) - Method in interface org.w3c.dom.css.CSS2Properties
setBorderWidth(String) - Method in interface org.w3c.dom.css.CSS2Properties
setBottom(String) - Method in interface org.w3c.dom.css.CSS2Properties
setCaption(HTMLTableCaptionElement) - Method in interface org.w3c.dom.html.HTMLTableElement
setCaptionSide(String) - Method in interface org.w3c.dom.css.CSS2Properties
setCellPadding(String) - Method in interface org.w3c.dom.html.HTMLTableElement
setCellSpacing(String) - Method in interface org.w3c.dom.html.HTMLTableElement
setCh(String) - Method in interface org.w3c.dom.html.HTMLTableCellElement
setCh(String) - Method in interface org.w3c.dom.html.HTMLTableColElement
setCh(String) - Method in interface org.w3c.dom.html.HTMLTableRowElement
setCh(String) - Method in interface org.w3c.dom.html.HTMLTableSectionElement
setChOff(String) - Method in interface org.w3c.dom.html.HTMLTableCellElement
setChOff(String) - Method in interface org.w3c.dom.html.HTMLTableColElement
setChOff(String) - Method in interface org.w3c.dom.html.HTMLTableRowElement
setChOff(String) - Method in interface org.w3c.dom.html.HTMLTableSectionElement
setCharset(String) - Method in interface org.w3c.dom.html.HTMLAnchorElement
setCharset(String) - Method in interface org.w3c.dom.html.HTMLLinkElement
setCharset(String) - Method in interface org.w3c.dom.html.HTMLScriptElement
setChecked(boolean) - Method in interface org.w3c.dom.html.HTMLInputElement
setCite(String) - Method in interface org.w3c.dom.html.HTMLModElement
setCite(String) - Method in interface org.w3c.dom.html.HTMLQuoteElement
setClassName(String) - Method in interface org.w3c.dom.html.HTMLElement
setClear(String) - Method in interface org.w3c.dom.css.CSS2Properties
setClear(String) - Method in interface org.w3c.dom.html.HTMLBRElement
setClip(String) - Method in interface org.w3c.dom.css.CSS2Properties
setCode(String) - Method in interface org.w3c.dom.html.HTMLAppletElement
setCode(String) - Method in interface org.w3c.dom.html.HTMLObjectElement
setCodeBase(String) - Method in interface org.w3c.dom.html.HTMLAppletElement
setCodeBase(String) - Method in interface org.w3c.dom.html.HTMLObjectElement
setCodeType(String) - Method in interface org.w3c.dom.html.HTMLObjectElement
setColSpan(int) - Method in interface org.w3c.dom.html.HTMLTableCellElement
setColor(String) - Method in interface org.w3c.dom.css.CSS2Properties
setColor(String) - Method in interface org.w3c.dom.html.HTMLBaseFontElement
setColor(String) - Method in interface org.w3c.dom.html.HTMLFontElement
setCols(String) - Method in interface org.w3c.dom.html.HTMLFrameSetElement
setCols(int) - Method in interface org.w3c.dom.html.HTMLTextAreaElement
setCompact(boolean) - Method in interface org.w3c.dom.html.HTMLDListElement
setCompact(boolean) - Method in interface org.w3c.dom.html.HTMLDirectoryElement
setCompact(boolean) - Method in interface org.w3c.dom.html.HTMLMenuElement
setCompact(boolean) - Method in interface org.w3c.dom.html.HTMLOListElement
setCompact(boolean) - Method in interface org.w3c.dom.html.HTMLUListElement
setContent(String) - Method in interface org.w3c.dom.css.CSS2Properties
setContent(String) - Method in interface org.w3c.dom.html.HTMLMetaElement
setCookie(String) - Method in interface org.w3c.dom.html.HTMLDocument
setCoords(String) - Method in interface org.w3c.dom.html.HTMLAnchorElement
setCoords(String) - Method in interface org.w3c.dom.html.HTMLAreaElement
setCounterIncrement(String) - Method in interface org.w3c.dom.css.CSS2Properties
setCounterReset(String) - Method in interface org.w3c.dom.css.CSS2Properties
setCssFloat(String) - Method in interface org.w3c.dom.css.CSS2Properties
setCssText(String) - Method in interface org.w3c.dom.css.CSSRule
setCssText(String) - Method in interface org.w3c.dom.css.CSSStyleDeclaration
setCssText(String) - Method in interface org.w3c.dom.css.CSSValue
setCue(String) - Method in interface org.w3c.dom.css.CSS2Properties
setCueAfter(String) - Method in interface org.w3c.dom.css.CSS2Properties
setCueBefore(String) - Method in interface org.w3c.dom.css.CSS2Properties
setCursor(String) - Method in interface org.w3c.dom.css.CSS2Properties
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.
setData(String) - Method in interface org.w3c.dom.html.HTMLObjectElement
setDateTime(String) - Method in interface org.w3c.dom.html.HTMLModElement
setDeclare(boolean) - Method in interface org.w3c.dom.html.HTMLObjectElement
setDefaultChecked(boolean) - Method in interface org.w3c.dom.html.HTMLInputElement
setDefaultSelected(boolean) - Method in interface org.w3c.dom.html.HTMLOptionElement
setDefaultValue(String) - Method in interface org.w3c.dom.html.HTMLInputElement
setDefaultValue(String) - Method in interface org.w3c.dom.html.HTMLTextAreaElement
setDefer(boolean) - Method in interface org.w3c.dom.html.HTMLScriptElement
setDir(String) - Method in interface org.w3c.dom.html.HTMLElement
setDirection(String) - Method in interface org.w3c.dom.css.CSS2Properties
setDisabled(boolean) - Method in interface org.w3c.dom.html.HTMLButtonElement
setDisabled(boolean) - Method in interface org.w3c.dom.html.HTMLInputElement
setDisabled(boolean) - Method in interface org.w3c.dom.html.HTMLLinkElement
setDisabled(boolean) - Method in interface org.w3c.dom.html.HTMLOptGroupElement
setDisabled(boolean) - Method in interface org.w3c.dom.html.HTMLOptionElement
setDisabled(boolean) - Method in interface org.w3c.dom.html.HTMLSelectElement
setDisabled(boolean) - Method in interface org.w3c.dom.html.HTMLStyleElement
setDisabled(boolean) - Method in interface org.w3c.dom.html.HTMLTextAreaElement
setDisabled(boolean) - Method in interface org.w3c.dom.stylesheets.StyleSheet
setDisplay(String) - Method in interface org.w3c.dom.css.CSS2Properties
setElevation(String) - Method in interface org.w3c.dom.css.CSS2Properties
setEmptyCells(String) - Method in interface org.w3c.dom.css.CSS2Properties
setEncoding(String) - Method in interface org.w3c.dom.css.CSSCharsetRule
setEnctype(String) - Method in interface org.w3c.dom.html.HTMLFormElement
setEvent(String) - Method in interface org.w3c.dom.html.HTMLScriptElement
setFace(String) - Method in interface org.w3c.dom.html.HTMLBaseFontElement
setFace(String) - Method in interface org.w3c.dom.html.HTMLFontElement
setFloatValue(short, float) - Method in interface org.w3c.dom.css.CSSPrimitiveValue
A method to set the float value with a specified unit.
setFont(String) - Method in interface org.w3c.dom.css.CSS2Properties
setFontFamily(String) - Method in interface org.w3c.dom.css.CSS2Properties
setFontSize(String) - Method in interface org.w3c.dom.css.CSS2Properties
setFontSizeAdjust(String) - Method in interface org.w3c.dom.css.CSS2Properties
setFontStretch(String) - Method in interface org.w3c.dom.css.CSS2Properties
setFontStyle(String) - Method in interface org.w3c.dom.css.CSS2Properties
setFontVariant(String) - Method in interface org.w3c.dom.css.CSS2Properties
setFontWeight(String) - Method in interface org.w3c.dom.css.CSS2Properties
setFrame(String) - Method in interface org.w3c.dom.html.HTMLTableElement
setFrameBorder(String) - Method in interface org.w3c.dom.html.HTMLFrameElement
setFrameBorder(String) - Method in interface org.w3c.dom.html.HTMLIFrameElement
setHeaders(String) - Method in interface org.w3c.dom.html.HTMLTableCellElement
setHeight(String) - Method in interface org.w3c.dom.css.CSS2Properties
setHeight(String) - Method in interface org.w3c.dom.html.HTMLAppletElement
setHeight(String) - Method in interface org.w3c.dom.html.HTMLIFrameElement
setHeight(String) - Method in interface org.w3c.dom.html.HTMLImageElement
setHeight(String) - Method in interface org.w3c.dom.html.HTMLObjectElement
setHeight(String) - Method in interface org.w3c.dom.html.HTMLTableCellElement
setHref(String) - Method in interface org.w3c.dom.html.HTMLAnchorElement
setHref(String) - Method in interface org.w3c.dom.html.HTMLAreaElement
setHref(String) - Method in interface org.w3c.dom.html.HTMLBaseElement
setHref(String) - Method in interface org.w3c.dom.html.HTMLLinkElement
setHreflang(String) - Method in interface org.w3c.dom.html.HTMLAnchorElement
setHreflang(String) - Method in interface org.w3c.dom.html.HTMLLinkElement
setHspace(String) - Method in interface org.w3c.dom.html.HTMLAppletElement
setHspace(String) - Method in interface org.w3c.dom.html.HTMLImageElement
setHspace(String) - Method in interface org.w3c.dom.html.HTMLObjectElement
setHtmlFor(String) - Method in interface org.w3c.dom.html.HTMLLabelElement
setHtmlFor(String) - Method in interface org.w3c.dom.html.HTMLScriptElement
setHttpEquiv(String) - Method in interface org.w3c.dom.html.HTMLMetaElement
setId(String) - Method in interface org.w3c.dom.html.HTMLElement
setIsMap(boolean) - Method in interface org.w3c.dom.html.HTMLImageElement
setLabel(String) - Method in interface org.w3c.dom.html.HTMLOptGroupElement
setLabel(String) - Method in interface org.w3c.dom.html.HTMLOptionElement
setLang(String) - Method in interface org.w3c.dom.html.HTMLElement
setLeft(String) - Method in interface org.w3c.dom.css.CSS2Properties
setLetterSpacing(String) - Method in interface org.w3c.dom.css.CSS2Properties
setLineHeight(String) - Method in interface org.w3c.dom.css.CSS2Properties
setLink(String) - Method in interface org.w3c.dom.html.HTMLBodyElement
setListStyle(String) - Method in interface org.w3c.dom.css.CSS2Properties
setListStyleImage(String) - Method in interface org.w3c.dom.css.CSS2Properties
setListStylePosition(String) - Method in interface org.w3c.dom.css.CSS2Properties
setListStyleType(String) - Method in interface org.w3c.dom.css.CSS2Properties
setLongDesc(String) - Method in interface org.w3c.dom.html.HTMLFrameElement
setLongDesc(String) - Method in interface org.w3c.dom.html.HTMLIFrameElement
setLongDesc(String) - Method in interface org.w3c.dom.html.HTMLImageElement
setLowSrc(String) - Method in interface org.w3c.dom.html.HTMLImageElement
setMargin(String) - Method in interface org.w3c.dom.css.CSS2Properties
setMarginBottom(String) - Method in interface org.w3c.dom.css.CSS2Properties
setMarginHeight(String) - Method in interface org.w3c.dom.html.HTMLFrameElement
setMarginHeight(String) - Method in interface org.w3c.dom.html.HTMLIFrameElement
setMarginLeft(String) - Method in interface org.w3c.dom.css.CSS2Properties
setMarginRight(String) - Method in interface org.w3c.dom.css.CSS2Properties
setMarginTop(String) - Method in interface org.w3c.dom.css.CSS2Properties
setMarginWidth(String) - Method in interface org.w3c.dom.html.HTMLFrameElement
setMarginWidth(String) - Method in interface org.w3c.dom.html.HTMLIFrameElement
setMarkerOffset(String) - Method in interface org.w3c.dom.css.CSS2Properties
setMarks(String) - Method in interface org.w3c.dom.css.CSS2Properties
setMaxHeight(String) - Method in interface org.w3c.dom.css.CSS2Properties
setMaxLength(int) - Method in interface org.w3c.dom.html.HTMLInputElement
setMaxWidth(String) - Method in interface org.w3c.dom.css.CSS2Properties
setMedia(String) - Method in interface org.w3c.dom.html.HTMLLinkElement
setMedia(String) - Method in interface org.w3c.dom.html.HTMLStyleElement
setMediaText(String) - Method in interface org.w3c.dom.stylesheets.MediaList
setMethod(String) - Method in interface org.w3c.dom.html.HTMLFormElement
setMinHeight(String) - Method in interface org.w3c.dom.css.CSS2Properties
setMinWidth(String) - Method in interface org.w3c.dom.css.CSS2Properties
setMultiple(boolean) - Method in interface org.w3c.dom.html.HTMLSelectElement
setName(String) - Method in interface org.w3c.dom.html.HTMLAnchorElement
setName(String) - Method in interface org.w3c.dom.html.HTMLAppletElement
setName(String) - Method in interface org.w3c.dom.html.HTMLButtonElement
setName(String) - Method in interface org.w3c.dom.html.HTMLFormElement
setName(String) - Method in interface org.w3c.dom.html.HTMLFrameElement
setName(String) - Method in interface org.w3c.dom.html.HTMLIFrameElement
setName(String) - Method in interface org.w3c.dom.html.HTMLImageElement
setName(String) - Method in interface org.w3c.dom.html.HTMLInputElement
setName(String) - Method in interface org.w3c.dom.html.HTMLMapElement
setName(String) - Method in interface org.w3c.dom.html.HTMLMetaElement
setName(String) - Method in interface org.w3c.dom.html.HTMLObjectElement
setName(String) - Method in interface org.w3c.dom.html.HTMLParamElement
setName(String) - Method in interface org.w3c.dom.html.HTMLSelectElement
setName(String) - Method in interface org.w3c.dom.html.HTMLTextAreaElement
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.
setNoHref(boolean) - Method in interface org.w3c.dom.html.HTMLAreaElement
setNoResize(boolean) - Method in interface org.w3c.dom.html.HTMLFrameElement
setNoShade(boolean) - Method in interface org.w3c.dom.html.HTMLHRElement
setNoWrap(boolean) - Method in interface org.w3c.dom.html.HTMLTableCellElement
setNodeValue(String) - Method in interface org.w3c.dom.Node
The value of this node, depending on its type; see the table above.
setObject(String) - Method in interface org.w3c.dom.html.HTMLAppletElement
setOrphans(String) - Method in interface org.w3c.dom.css.CSS2Properties
setOutline(String) - Method in interface org.w3c.dom.css.CSS2Properties
setOutlineColor(String) - Method in interface org.w3c.dom.css.CSS2Properties
setOutlineStyle(String) - Method in interface org.w3c.dom.css.CSS2Properties
setOutlineWidth(String) - Method in interface org.w3c.dom.css.CSS2Properties
setOverflow(String) - Method in interface org.w3c.dom.css.CSS2Properties
setPadding(String) - Method in interface org.w3c.dom.css.CSS2Properties
setPaddingBottom(String) - Method in interface org.w3c.dom.css.CSS2Properties
setPaddingLeft(String) - Method in interface org.w3c.dom.css.CSS2Properties
setPaddingRight(String) - Method in interface org.w3c.dom.css.CSS2Properties
setPaddingTop(String) - Method in interface org.w3c.dom.css.CSS2Properties
setPage(String) - Method in interface org.w3c.dom.css.CSS2Properties
setPageBreakAfter(String) - Method in interface org.w3c.dom.css.CSS2Properties
setPageBreakBefore(String) - Method in interface org.w3c.dom.css.CSS2Properties
setPageBreakInside(String) - Method in interface org.w3c.dom.css.CSS2Properties
setPause(String) - Method in interface org.w3c.dom.css.CSS2Properties
setPauseAfter(String) - Method in interface org.w3c.dom.css.CSS2Properties
setPauseBefore(String) - Method in interface org.w3c.dom.css.CSS2Properties
setPitch(String) - Method in interface org.w3c.dom.css.CSS2Properties
setPitchRange(String) - Method in interface org.w3c.dom.css.CSS2Properties
setPlayDuring(String) - Method in interface org.w3c.dom.css.CSS2Properties
setPosition(String) - Method in interface org.w3c.dom.css.CSS2Properties
setPrefix(String) - Method in interface org.w3c.dom.Node
The namespace prefix of this node, or null if it is unspecified.
setProfile(String) - Method in interface org.w3c.dom.html.HTMLHeadElement
setPrompt(String) - Method in interface org.w3c.dom.html.HTMLIsIndexElement
setProperty(String, String, String) - Method in interface org.w3c.dom.css.CSSStyleDeclaration
Used to set a property value and priority within this declaration block.
setQuotes(String) - Method in interface org.w3c.dom.css.CSS2Properties
setReadOnly(boolean) - Method in interface org.w3c.dom.html.HTMLInputElement
setReadOnly(boolean) - Method in interface org.w3c.dom.html.HTMLTextAreaElement
setRel(String) - Method in interface org.w3c.dom.html.HTMLAnchorElement
setRel(String) - Method in interface org.w3c.dom.html.HTMLLinkElement
setRev(String) - Method in interface org.w3c.dom.html.HTMLAnchorElement
setRev(String) - Method in interface org.w3c.dom.html.HTMLLinkElement
setRichness(String) - Method in interface org.w3c.dom.css.CSS2Properties
setRight(String) - Method in interface org.w3c.dom.css.CSS2Properties
setRowSpan(int) - Method in interface org.w3c.dom.html.HTMLTableCellElement
setRows(String) - Method in interface org.w3c.dom.html.HTMLFrameSetElement
setRows(int) - Method in interface org.w3c.dom.html.HTMLTextAreaElement
setRules(String) - Method in interface org.w3c.dom.html.HTMLTableElement
setScheme(String) - Method in interface org.w3c.dom.html.HTMLMetaElement
setScope(String) - Method in interface org.w3c.dom.html.HTMLTableCellElement
setScrolling(String) - Method in interface org.w3c.dom.html.HTMLFrameElement
setScrolling(String) - Method in interface org.w3c.dom.html.HTMLIFrameElement
setSelected(boolean) - Method in interface org.w3c.dom.html.HTMLOptionElement
setSelectedIndex(int) - Method in interface org.w3c.dom.html.HTMLSelectElement
setSelectorText(String) - Method in interface org.w3c.dom.css.CSSPageRule
setSelectorText(String) - Method in interface org.w3c.dom.css.CSSStyleRule
setShape(String) - Method in interface org.w3c.dom.html.HTMLAnchorElement
setShape(String) - Method in interface org.w3c.dom.html.HTMLAreaElement
setSize(String) - Method in interface org.w3c.dom.css.CSS2Properties
setSize(String) - Method in interface org.w3c.dom.html.HTMLBaseFontElement
setSize(String) - Method in interface org.w3c.dom.html.HTMLFontElement
setSize(String) - Method in interface org.w3c.dom.html.HTMLHRElement
setSize(String) - Method in interface org.w3c.dom.html.HTMLInputElement
setSize(int) - Method in interface org.w3c.dom.html.HTMLSelectElement
setSpan(int) - Method in interface org.w3c.dom.html.HTMLTableColElement
setSpeak(String) - Method in interface org.w3c.dom.css.CSS2Properties
setSpeakHeader(String) - Method in interface org.w3c.dom.css.CSS2Properties
setSpeakNumeral(String) - Method in interface org.w3c.dom.css.CSS2Properties
setSpeakPunctuation(String) - Method in interface org.w3c.dom.css.CSS2Properties
setSpeechRate(String) - Method in interface org.w3c.dom.css.CSS2Properties
setSrc(String) - Method in interface org.w3c.dom.html.HTMLFrameElement
setSrc(String) - Method in interface org.w3c.dom.html.HTMLIFrameElement
setSrc(String) - Method in interface org.w3c.dom.html.HTMLImageElement
setSrc(String) - Method in interface org.w3c.dom.html.HTMLInputElement
setSrc(String) - Method in interface org.w3c.dom.html.HTMLScriptElement
setStandby(String) - Method in interface org.w3c.dom.html.HTMLObjectElement
setStart(int) - Method in interface org.w3c.dom.html.HTMLOListElement
setStress(String) - Method in interface org.w3c.dom.css.CSS2Properties
setStringValue(short, String) - Method in interface org.w3c.dom.css.CSSPrimitiveValue
A method to set the string value with the specified unit.
setSummary(String) - Method in interface org.w3c.dom.html.HTMLTableElement
setTFoot(HTMLTableSectionElement) - Method in interface org.w3c.dom.html.HTMLTableElement
setTHead(HTMLTableSectionElement) - Method in interface org.w3c.dom.html.HTMLTableElement
setTabIndex(int) - Method in interface org.w3c.dom.html.HTMLAnchorElement
setTabIndex(int) - Method in interface org.w3c.dom.html.HTMLAreaElement
setTabIndex(int) - Method in interface org.w3c.dom.html.HTMLButtonElement
setTabIndex(int) - Method in interface org.w3c.dom.html.HTMLInputElement
setTabIndex(int) - Method in interface org.w3c.dom.html.HTMLObjectElement
setTabIndex(int) - Method in interface org.w3c.dom.html.HTMLSelectElement
setTabIndex(int) - Method in interface org.w3c.dom.html.HTMLTextAreaElement
setTableLayout(String) - Method in interface org.w3c.dom.css.CSS2Properties
setTarget(String) - Method in interface org.w3c.dom.html.HTMLAnchorElement
setTarget(String) - Method in interface org.w3c.dom.html.HTMLAreaElement
setTarget(String) - Method in interface org.w3c.dom.html.HTMLBaseElement
setTarget(String) - Method in interface org.w3c.dom.html.HTMLFormElement
setTarget(String) - Method in interface org.w3c.dom.html.HTMLLinkElement
setText(String) - Method in interface org.w3c.dom.html.HTMLBodyElement
setText(String) - Method in interface org.w3c.dom.html.HTMLScriptElement
setText(String) - Method in interface org.w3c.dom.html.HTMLTitleElement
setTextAlign(String) - Method in interface org.w3c.dom.css.CSS2Properties
setTextDecoration(String) - Method in interface org.w3c.dom.css.CSS2Properties
setTextIndent(String) - Method in interface org.w3c.dom.css.CSS2Properties
setTextShadow(String) - Method in interface org.w3c.dom.css.CSS2Properties
setTextTransform(String) - Method in interface org.w3c.dom.css.CSS2Properties
setTitle(String) - Method in interface org.w3c.dom.html.HTMLDocument
setTitle(String) - Method in interface org.w3c.dom.html.HTMLElement
setTop(String) - Method in interface org.w3c.dom.css.CSS2Properties
setType(String) - Method in interface org.w3c.dom.html.HTMLAnchorElement
setType(String) - Method in interface org.w3c.dom.html.HTMLLIElement
setType(String) - Method in interface org.w3c.dom.html.HTMLLinkElement
setType(String) - Method in interface org.w3c.dom.html.HTMLOListElement
setType(String) - Method in interface org.w3c.dom.html.HTMLObjectElement
setType(String) - Method in interface org.w3c.dom.html.HTMLParamElement
setType(String) - Method in interface org.w3c.dom.html.HTMLScriptElement
setType(String) - Method in interface org.w3c.dom.html.HTMLStyleElement
setType(String) - Method in interface org.w3c.dom.html.HTMLUListElement
setUnicodeBidi(String) - Method in interface org.w3c.dom.css.CSS2Properties
setUseMap(String) - Method in interface org.w3c.dom.html.HTMLImageElement
setUseMap(String) - Method in interface org.w3c.dom.html.HTMLInputElement
setUseMap(String) - Method in interface org.w3c.dom.html.HTMLObjectElement
setVAlign(String) - Method in interface org.w3c.dom.html.HTMLTableCellElement
setVAlign(String) - Method in interface org.w3c.dom.html.HTMLTableColElement
setVAlign(String) - Method in interface org.w3c.dom.html.HTMLTableRowElement
setVAlign(String) - Method in interface org.w3c.dom.html.HTMLTableSectionElement
setVLink(String) - Method in interface org.w3c.dom.html.HTMLBodyElement
setValue(String) - Method in interface org.w3c.dom.Attr
On retrieval, the value of the attribute is returned as a string.
setValue(String) - Method in interface org.w3c.dom.html.HTMLButtonElement
setValue(String) - Method in interface org.w3c.dom.html.HTMLInputElement
setValue(int) - Method in interface org.w3c.dom.html.HTMLLIElement
setValue(String) - Method in interface org.w3c.dom.html.HTMLOptionElement
setValue(String) - Method in interface org.w3c.dom.html.HTMLParamElement
setValue(String) - Method in interface org.w3c.dom.html.HTMLSelectElement
setValue(String) - Method in interface org.w3c.dom.html.HTMLTextAreaElement
setValueType(String) - Method in interface org.w3c.dom.html.HTMLParamElement
setVersion(String) - Method in interface org.w3c.dom.html.HTMLHtmlElement
setVerticalAlign(String) - Method in interface org.w3c.dom.css.CSS2Properties
setVisibility(String) - Method in interface org.w3c.dom.css.CSS2Properties
setVoiceFamily(String) - Method in interface org.w3c.dom.css.CSS2Properties
setVolume(String) - Method in interface org.w3c.dom.css.CSS2Properties
setVspace(String) - Method in interface org.w3c.dom.html.HTMLAppletElement
setVspace(String) - Method in interface org.w3c.dom.html.HTMLImageElement
setVspace(String) - Method in interface org.w3c.dom.html.HTMLObjectElement
setWhiteSpace(String) - Method in interface org.w3c.dom.css.CSS2Properties
setWidows(String) - Method in interface org.w3c.dom.css.CSS2Properties
setWidth(String) - Method in interface org.w3c.dom.css.CSS2Properties
setWidth(String) - Method in interface org.w3c.dom.html.HTMLAppletElement
setWidth(String) - Method in interface org.w3c.dom.html.HTMLHRElement
setWidth(String) - Method in interface org.w3c.dom.html.HTMLIFrameElement
setWidth(String) - Method in interface org.w3c.dom.html.HTMLImageElement
setWidth(String) - Method in interface org.w3c.dom.html.HTMLObjectElement
setWidth(int) - Method in interface org.w3c.dom.html.HTMLPreElement
setWidth(String) - Method in interface org.w3c.dom.html.HTMLTableCellElement
setWidth(String) - Method in interface org.w3c.dom.html.HTMLTableColElement
setWidth(String) - Method in interface org.w3c.dom.html.HTMLTableElement
setWordSpacing(String) - Method in interface org.w3c.dom.css.CSS2Properties
setZIndex(String) - Method in interface org.w3c.dom.css.CSS2Properties
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.
stopPropagation() - Method in interface org.w3c.dom.events.Event
The stopPropagation method is used prevent further propagation of an event during event flow.
submit() - Method in interface org.w3c.dom.html.HTMLFormElement
Submits the form.
substringData(int, int) - Method in interface org.w3c.dom.CharacterData
Extracts a range of data from the node.
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
A B C D E F G H I L M N O P R S T U V W
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


T-Index (Common DOM API)

Common DOM API
PREV LETTER NEXT LETTER FRAMES NO FRAMES
A B C D E F G H I L M N O P R S T U V W

T

TEXT_NODE - Static variable in interface org.w3c.dom.Node
The node is a Text node.
Text - interface org.w3c.dom.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
A B C D E F G H I L M N O P R S T U V W
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


U-Index (Common DOM API)

Common DOM API
PREV LETTER NEXT LETTER FRAMES NO FRAMES
A B C D E F G H I L M N O P R S T U V W

U

UIEvent - interface org.w3c.dom.events.UIEvent.
The UIEvent interface provides specific contextual information associated with User Interface events.
UNKNOWN_RULE - Static variable in interface org.w3c.dom.css.CSSRule
The rule is a CSSUnknownRule.
UNSPECIFIED_EVENT_TYPE_ERR - Static variable in class org.w3c.dom.events.EventException
If the Event's type was not specified by initializing the event before the method was called.
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
A B C D E F G H I L M N O P R S T U V W
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


V-Index (Common DOM API)

Common DOM API
PREV LETTER NEXT LETTER FRAMES NO FRAMES
A B C D E F G H I L M N O P R S T U V W

V

ViewCSS - interface org.w3c.dom.css.ViewCSS.
This interface represents a CSS view.
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
A B C D E F G H I L M N O P R S T U V W
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


W-Index (Common DOM API)

Common DOM API
PREV LETTER NEXT LETTER FRAMES NO FRAMES
A B C D E F G H I L M N O P R S T U V W

W

WRONG_DOCUMENT_ERR - Static variable in class org.w3c.dom.DOMException
If a node is used in a different document than the one that created it (that doesn't support it)
write(String) - Method in interface org.w3c.dom.html.HTMLDocument
Write a string of text to a document stream opened by open() .
writeln(String) - Method in interface org.w3c.dom.html.HTMLDocument
Write a string of text followed by a newline character to a document stream opened by open() .
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV LETTER NEXT LETTER FRAMES NO FRAMES
A B C D E F G H I L M N O P R S T U V W
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Attr (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom
Interface Attr

All Superinterfaces:
Node
public interface Attr
extends Node

The Attr interface represents an attribute in an Element object. Typically the allowable values for the attribute are defined in a document type definition.

Attr objects inherit the Node interface, but since they are not actually child nodes of the element they describe, the DOM does not consider them part of the document tree. Thus, the Node attributes parentNode, previousSibling, and nextSibling have a null value for Attr objects. The DOM takes the view that attributes are properties of elements rather than having a separate identity from the elements they are associated with; this should make it more efficient to implement such features as default attributes associated with all elements of a given type. Furthermore, Attr nodes may not be immediate children of a DocumentFragment. However, they can be associated with Element nodes contained within a DocumentFragment. In short, users and implementors of the DOM need to be aware that Attr nodes have some things in common with other objects inheriting the Node interface, but they also are quite distinct.

The attribute's effective value is determined as follows: if this attribute has been explicitly assigned any value, that value is the attribute's effective value; otherwise, if there is a declaration for this attribute, and that declaration includes a default value, then that default value is the attribute's effective value; otherwise, the attribute does not exist on this element in the structure model until it has been explicitly added. Note that the nodeValue attribute on the Attr instance can also be used to retrieve the string version of the attribute's value(s).

In XML, where the value of an attribute can contain entity references, the child nodes of the Attr node may be either Text or EntityReference nodes (when these are in use; see the description of EntityReference for discussion). Because the DOM Core is not aware of attribute types, it treats all attribute values as simple strings, even if the DTD or schema declares them as having tokenized types.

See also the Document Object Model (DOM) Level 2 Core Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getName() Returns the name of this attribute.
Element | getOwnerElement() The Element node this attribute is attached to or null if this attribute is not in use.
boolean | getSpecified() If this attribute was explicitly given a value in the original document, this is true; otherwise, it is false.
String | getValue() On retrieval, the value of the attribute is returned as a string.
void | setValue(String value) On retrieval, the value of the attribute is returned as a string.
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getName

public String getName()
Returns the name of this attribute.

getSpecified

public boolean getSpecified()
If this attribute was explicitly given a value in the original document, this is true; otherwise, it is false. Note that the implementation is in charge of this attribute, not the user. If the user changes the value of the attribute (even if it ends up having the same value as the default value) then the specified flag is automatically flipped to true. To re-specify the attribute as the default value from the DTD, the user must delete the attribute. The implementation will then make a new attribute available with specified set to false and the default value (if one exists).
In summary: If the attribute has an assigned value in the document then specified is true, and the value is the assigned value.If the attribute has no assigned value in the document and has a default value in the DTD, then specified is false, and the value is the default value in the DTD.If the attribute has no assigned value in the document and has a value of #IMPLIED in the DTD, then the attribute does not appear in the structure model of the document.If the ownerElement attribute is null (i.e. because it was just created or was set to null by the various removal and cloning operations) specified is true.

getValue

public String getValue()
On retrieval, the value of the attribute is returned as a string. Character and general entity references are replaced with their values. See also the method getAttribute on the Element interface.
On setting, this creates a Text node with the unparsed contents of the string. I.e. any characters that an XML processor would recognize as markup are instead treated as literal text. See also the method setAttribute on the Element interface.

Throws:
DOMException - NO_MODIFICATION_ALLOWED_ERR: Raised when the node is readonly.

setValue

public void setValue(String value)
              throws DOMException
On retrieval, the value of the attribute is returned as a string. Character and general entity references are replaced with their values. See also the method getAttribute on the Element interface.
On setting, this creates a Text node with the unparsed contents of the string. I.e. any characters that an XML processor would recognize as markup are instead treated as literal text. See also the method setAttribute on the Element interface.

Throws:
DOMException - NO_MODIFICATION_ALLOWED_ERR: Raised when the node is readonly.

getOwnerElement

public Element getOwnerElement()
The Element node this attribute is attached to or null if this attribute is not in use.

Since:
DOM Level 2
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


CDATASection (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom
Interface CDATASection

All Superinterfaces:
CharacterData, Node, Text
public interface CDATASection
extends Text

CDATA sections are used to escape blocks of text containing characters that would otherwise be regarded as markup. The only delimiter that is recognized in a CDATA section is the "]]>" string that ends the CDATA section. CDATA sections cannot be nested. Their primary purpose is for including material such as XML fragments, without needing to escape all the delimiters.

The DOMString attribute of the Text node holds the text that is contained by the CDATA section. Note that this may contain characters that need to be escaped outside of CDATA sections and that, depending on the character encoding ("charset") chosen for serialization, it may be impossible to write out some characters as part of a CDATA section.

The CDATASection interface inherits from the CharacterData interface through the Text interface. Adjacent CDATASection nodes are not merged by use of the normalize method of the Node interface. Because no markup is recognized within a CDATASection, character numeric references cannot be used as an escape mechanism when serializing. Therefore, action needs to be taken when serializing a CDATASection with a character encoding where some of the contained characters cannot be represented. Failure to do so would not produce well-formed XML.One potential solution in the serialization process is to end the CDATA section before the character, output the character using a character reference or entity reference, and open a new CDATA section for any further characters in the text node. Note, however, that some code conversion libraries at the time of writing do not return an error or exception when a character is missing from the encoding, making the task of ensuring that data is not corrupted on serialization more difficult.

See also the Document Object Model (DOM) Level 2 Core Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Methods inherited from interface org.w3c.dom.Text
splitText
Methods inherited from interface org.w3c.dom.CharacterData
appendData, deleteData, getData, getLength, insertData, replaceData, setData, substringData
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


CharacterData (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom
Interface CharacterData

All Superinterfaces:
Node
All Known Subinterfaces:
CDATASection, Comment, Text
public interface CharacterData
extends Node

The CharacterData interface extends Node with a set of attributes and methods for accessing character data in the DOM. For clarity this set is defined here rather than on each object that uses these attributes and methods. No DOM objects correspond directly to CharacterData, though Text and others do inherit the interface from it. All offsets in this interface start from 0.

As explained in the DOMString interface, text strings in the DOM are represented in UTF-16, i.e. as a sequence of 16-bit units. In the following, the term 16-bit units is used whenever necessary to indicate that indexing on CharacterData is done in 16-bit units.

See also the Document Object Model (DOM) Level 2 Core Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
void | appendData(String arg) Append the string to the end of the character data of the node.
void | deleteData(int offset, int count) Remove a range of 16-bit units from the node.
String | getData() The character data of the node that implements this interface.
int | getLength() The number of 16-bit units that are available through data and the substringData method below.
void | insertData(int offset, String arg) Insert a string at the specified 16-bit unit offset.
void | replaceData(int offset, int count, String arg) Replace the characters starting at the specified 16-bit unit offset with the specified string.
void | setData(String data) The character data of the node that implements this interface.
String | substringData(int offset, int count) Extracts a range of data from the node.
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getData

public String getData()
               throws DOMException
The character data of the node that implements this interface. The DOM implementation may not put arbitrary limits on the amount of data that may be stored in a CharacterData node. However, implementation limits may mean that the entirety of a node's data may not fit into a single DOMString. In such cases, the user may call substringData to retrieve the data in appropriately sized pieces.

Throws:
DOMException - NO_MODIFICATION_ALLOWED_ERR: Raised when the node is readonly.
DOMException - DOMSTRING_SIZE_ERR: Raised when it would return more characters than fit in a DOMString variable on the implementation platform.

setData

public void setData(String data)
             throws DOMException
The character data of the node that implements this interface. The DOM implementation may not put arbitrary limits on the amount of data that may be stored in a CharacterData node. However, implementation limits may mean that the entirety of a node's data may not fit into a single DOMString. In such cases, the user may call substringData to retrieve the data in appropriately sized pieces.

Throws:
DOMException - NO_MODIFICATION_ALLOWED_ERR: Raised when the node is readonly.
DOMException - DOMSTRING_SIZE_ERR: Raised when it would return more characters than fit in a DOMString variable on the implementation platform.

getLength

public int getLength()
The number of 16-bit units that are available through data and the substringData method below. This may have the value zero, i.e., CharacterData nodes may be empty.

substringData

public String substringData(int offset,
                            int count)
                     throws DOMException
Extracts a range of data from the node.

Parameters:
offset - Start offset of substring to extract.
count - The number of 16-bit units to extract.
Returns:
The specified substring. If the sum of offset and count exceeds the length, then all 16-bit units to the end of the data are returned.
Throws:
DOMException - INDEX_SIZE_ERR: Raised if the specified offset is negative or greater than the number of 16-bit units in data, or if the specified count is negative.
DOMSTRING_SIZE_ERR: Raised if the specified range of text does not fit into a DOMString.

appendData

public void appendData(String arg)
                throws DOMException
Append the string to the end of the character data of the node. Upon success, data provides access to the concatenation of data and the DOMString specified.

Parameters:
arg - The DOMString to append.
Throws:
DOMException - NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.

insertData

public void insertData(int offset,
                       String arg)
                throws DOMException
Insert a string at the specified 16-bit unit offset.

Parameters:
offset - The character offset at which to insert.
arg - The DOMString to insert.
Throws:
DOMException - INDEX_SIZE_ERR: Raised if the specified offset is negative or greater than the number of 16-bit units in data.
NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.

deleteData

public void deleteData(int offset,
                       int count)
                throws DOMException
Remove a range of 16-bit units from the node. Upon success, data and length reflect the change.

Parameters:
offset - The offset from which to start removing.
count - The number of 16-bit units to delete. If the sum of offset and count exceeds length then all 16-bit units from offset to the end of the data are deleted.
Throws:
DOMException - INDEX_SIZE_ERR: Raised if the specified offset is negative or greater than the number of 16-bit units in data, or if the specified count is negative.
NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.

replaceData

public void replaceData(int offset,
                        int count,
                        String arg)
                 throws DOMException
Replace the characters starting at the specified 16-bit unit offset with the specified string.

Parameters:
offset - The offset from which to start replacing.
count - The number of 16-bit units to replace. If the sum of offset and count exceeds length, then all 16-bit units to the end of the data are replaced; (i.e., the effect is the same as a remove method call with the same range, followed by an append method invocation).
arg - The DOMString with which the range must be replaced.
Throws:
DOMException - INDEX_SIZE_ERR: Raised if the specified offset is negative or greater than the number of 16-bit units in data, or if the specified count is negative.
NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Comment (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom
Interface Comment

All Superinterfaces:
CharacterData, Node
public interface Comment
extends CharacterData

This interface inherits from CharacterData and represents the content of a comment, i.e., all the characters between the starting ' <!--' and ending '-->'. Note that this is the definition of a comment in XML, and, in practice, HTML, although some HTML tools may implement the full SGML comment structure.

See also the Document Object Model (DOM) Level 2 Core Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Methods inherited from interface org.w3c.dom.CharacterData
appendData, deleteData, getData, getLength, insertData, replaceData, setData, substringData
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Document (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom
Interface Document

All Superinterfaces:
Node
All Known Subinterfaces:
HTMLDocument
public interface Document
extends Node

The Document interface represents the entire HTML or XML document. Conceptually, it is the root of the document tree, and provides the primary access to the document's data.

Since elements, text nodes, comments, processing instructions, etc. cannot exist outside the context of a Document, the Document interface also contains the factory methods needed to create these objects. The Node objects created have a ownerDocument attribute which associates them with the Document within whose context they were created.

See also the Document Object Model (DOM) Level 2 Core Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
Attr | createAttribute(String name) Creates an Attr of the given name.
Attr | createAttributeNS(String namespaceURI, String qualifiedName) Creates an attribute of the given qualified name and namespace URI.
CDATASection | createCDATASection(String data) Creates a CDATASection node whose value is the specified string.
Comment | createComment(String data) Creates a Comment node given the specified string.
DocumentFragment | createDocumentFragment() Creates an empty DocumentFragment object.
Element | createElement(String tagName) Creates an element of the type specified.
Element | createElementNS(String namespaceURI, String qualifiedName) Creates an element of the given qualified name and namespace URI.
EntityReference | createEntityReference(String name) Creates an EntityReference object.
ProcessingInstruction | createProcessingInstruction(String target, String data) Creates a ProcessingInstruction node given the specified name and data strings.
Text | createTextNode(String data) Creates a Text node given the specified string.
DocumentType | getDoctype() The Document Type Declaration (see DocumentType) associated with this document.
Element | getDocumentElement() This is a convenience attribute that allows direct access to the child node that is the root element of the document.
Element | getElementById(String elementId) Returns the Element whose ID is given by elementId.
NodeList | getElementsByTagName(String tagname) Returns a NodeList of all the Elements with a given tag name in the order in which they are encountered in a preorder traversal of the Document tree.
NodeList | getElementsByTagNameNS(String namespaceURI, String localName) Returns a NodeList of all the Elements with a given local name and namespace URI in the order in which they are encountered in a preorder traversal of the Document tree.
DOMImplementation | getImplementation() The DOMImplementation object that handles this document.
Node | importNode(Node importedNode, boolean deep) Imports a node from another document to this document.
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getDoctype

public DocumentType getDoctype()
The Document Type Declaration (see DocumentType) associated with this document. For HTML documents as well as XML documents without a document type declaration this returns null. The DOM Level 2 does not support editing the Document Type Declaration. docType cannot be altered in any way, including through the use of methods inherited from the Node interface, such as insertNode or removeNode.

getImplementation

public DOMImplementation getImplementation()
The DOMImplementation object that handles this document. A DOM application may use objects from multiple implementations.

getDocumentElement

public Element getDocumentElement()
This is a convenience attribute that allows direct access to the child node that is the root element of the document. For HTML documents, this is the element with the tagName "HTML".

createElement

public Element createElement(String tagName)
                      throws DOMException
Creates an element of the type specified. Note that the instance returned implements the Element interface, so attributes can be specified directly on the returned object.
In addition, if there are known attributes with default values, Attr nodes representing them are automatically created and attached to the element.
To create an element with a qualified name and namespace URI, use the createElementNS method.

Parameters:
tagName - The name of the element type to instantiate. For XML, this is case-sensitive. For HTML, the tagName parameter may be provided in any case, but it must be mapped to the canonical uppercase form by the DOM implementation.
Returns:
A new Element object with the nodeName attribute set to tagName, and localName, prefix, and namespaceURI set to null.
Throws:
DOMException - INVALID_CHARACTER_ERR: Raised if the specified name contains an illegal character.

createDocumentFragment

public DocumentFragment createDocumentFragment()
Creates an empty DocumentFragment object.

Returns:
A new DocumentFragment.

createTextNode

public Text createTextNode(String data)
Creates a Text node given the specified string.

Parameters:
data - The data for the node.
Returns:
The new Text object.

createComment

public Comment createComment(String data)
Creates a Comment node given the specified string.

Parameters:
data - The data for the node.
Returns:
The new Comment object.

createCDATASection

public CDATASection createCDATASection(String data)
                                throws DOMException
Creates a CDATASection node whose value is the specified string.

Parameters:
data - The data for the CDATASection contents.
Returns:
The new CDATASection object.
Throws:
DOMException - NOT_SUPPORTED_ERR: Raised if this document is an HTML document.

createProcessingInstruction

public ProcessingInstruction createProcessingInstruction(String target,
                                                         String data)
                                                  throws DOMException
Creates a ProcessingInstruction node given the specified name and data strings.

Parameters:
target - The target part of the processing instruction.
data - The data for the node.
Returns:
The new ProcessingInstruction object.
Throws:
DOMException - INVALID_CHARACTER_ERR: Raised if the specified target contains an illegal character.
NOT_SUPPORTED_ERR: Raised if this document is an HTML document.

createAttribute

public Attr createAttribute(String name)
                     throws DOMException
Creates an Attr of the given name. Note that the Attr instance can then be set on an Element using the setAttributeNode method.
To create an attribute with a qualified name and namespace URI, use the createAttributeNS method.

Parameters:
name - The name of the attribute.
Returns:
A new Attr object with the nodeName attribute set to name, and localName, prefix, and namespaceURI set to null. The value of the attribute is the empty string.
Throws:
DOMException - INVALID_CHARACTER_ERR: Raised if the specified name contains an illegal character.

createEntityReference

public EntityReference createEntityReference(String name)
                                      throws DOMException
Creates an EntityReference object. In addition, if the referenced entity is known, the child list of the EntityReference node is made the same as that of the corresponding Entity node.If any descendant of the Entity node has an unbound namespace prefix, the corresponding descendant of the created EntityReference node is also unbound; (its namespaceURI is null). The DOM Level 2 does not support any mechanism to resolve namespace prefixes.

Parameters:
name - The name of the entity to reference.
Returns:
The new EntityReference object.
Throws:
DOMException - INVALID_CHARACTER_ERR: Raised if the specified name contains an illegal character.
NOT_SUPPORTED_ERR: Raised if this document is an HTML document.

getElementsByTagName

public NodeList getElementsByTagName(String tagname)
Returns a NodeList of all the Elements with a given tag name in the order in which they are encountered in a preorder traversal of the Document tree.

Parameters:
tagname - The name of the tag to match on. The special value "*" matches all tags.
Returns:
A new NodeList object containing all the matched Elements.

importNode

public Node importNode(Node importedNode,
                       boolean deep)
                throws DOMException
Imports a node from another document to this document. The returned node has no parent; (parentNode is null). The source node is not altered or removed from the original document; this method creates a new copy of the source node.
For all nodes, importing a node creates a node object owned by the importing document, with attribute values identical to the source node's nodeName and nodeType, plus the attributes related to namespaces (prefix, localName, and namespaceURI). As in the cloneNode operation on a Node, the source node is not altered.
Additional information is copied as appropriate to the nodeType, attempting to mirror the behavior expected if a fragment of XML or HTML source was copied from one document to another, recognizing that the two documents may have different DTDs in the XML case. The following list describes the specifics for each type of node.
ATTRIBUTE_NODE
The ownerElement attribute is set to null and the specified flag is set to true on the generated Attr. The descendants of the source Attr are recursively imported and the resulting nodes reassembled to form the corresponding subtree. Note that the deep parameter has no effect on Attr nodes; they always carry their children with them when imported.
DOCUMENT_FRAGMENT_NODE
If the deep option was set to true, the descendants of the source element are recursively imported and the resulting nodes reassembled to form the corresponding subtree. Otherwise, this simply generates an empty DocumentFragment.
DOCUMENT_NODE
Document nodes cannot be imported.
DOCUMENT_TYPE_NODE
DocumentType nodes cannot be imported.
ELEMENT_NODE
Specified attribute nodes of the source element are imported, and the generated Attr nodes are attached to the generated Element. Default attributes are not copied, though if the document being imported into defines default attributes for this element name, those are assigned. If the importNode deep parameter was set to true, the descendants of the source element are recursively imported and the resulting nodes reassembled to form the corresponding subtree.
ENTITY_NODE
Entity nodes can be imported, however in the current release of the DOM the DocumentType is readonly. Ability to add these imported nodes to a DocumentType will be considered for addition to a future release of the DOM.On import, the publicId, systemId, and notationName attributes are copied. If a deep import is requested, the descendants of the the source Entity are recursively imported and the resulting nodes reassembled to form the corresponding subtree.
ENTITY_REFERENCE_NODE
Only the EntityReference itself is copied, even if a deep import is requested, since the source and destination documents might have defined the entity differently. If the document being imported into provides a definition for this entity name, its value is assigned.
NOTATION_NODE
Notation nodes can be imported, however in the current release of the DOM the DocumentType is readonly. Ability to add these imported nodes to a DocumentType will be considered for addition to a future release of the DOM.On import, the publicId and systemId attributes are copied. Note that the deep parameter has no effect on Notation nodes since they never have any children.
PROCESSING_INSTRUCTION_NODE
The imported node copies its target and data values from those of the source node.
TEXT_NODE, CDATA_SECTION_NODE, COMMENT_NODE
These three types of nodes inheriting from CharacterData copy their data and length attributes from those of the source node.

Parameters:
importedNode - The node to import.
deep - If true, recursively import the subtree under the specified node; if false, import only the node itself, as explained above. This has no effect on Attr , EntityReference, and Notation nodes.
Returns:
The imported node that belongs to this Document.
Throws:
DOMException - NOT_SUPPORTED_ERR: Raised if the type of node being imported is not supported.
Since:
DOM Level 2

createElementNS

public Element createElementNS(String namespaceURI,
                               String qualifiedName)
                        throws DOMException
Creates an element of the given qualified name and namespace URI.

Parameters:
namespaceURI - The namespace URI of the element to create.
qualifiedName - The qualified name of the element type to instantiate.
Returns:
A new Element object with the following attributes:
Attribute | Value
Node.nodeName | qualifiedName
Node.namespaceURI | namespaceURI
Node.prefix | prefix, extracted from qualifiedName, or null if there is no prefix
Node.localName | local name, extracted from qualifiedName
Element.tagName | qualifiedName
Throws:
DOMException - INVALID_CHARACTER_ERR: Raised if the specified qualified name contains an illegal character, per the XML 1.0 specification .
NAMESPACE_ERR: Raised if the qualifiedName is malformed per the Namespaces in XML specification, if the qualifiedName has a prefix and the namespaceURI is null, or if the qualifiedName has a prefix that is "xml" and the namespaceURI is different from " http://www.w3.org/XML/1998/namespace" .
NOT_SUPPORTED_ERR: Always thrown if the current document does not support the "XML" feature, since namespaces were defined by XML.
Since:
DOM Level 2

createAttributeNS

public Attr createAttributeNS(String namespaceURI,
                              String qualifiedName)
                       throws DOMException
Creates an attribute of the given qualified name and namespace URI.

Parameters:
namespaceURI - The namespace URI of the attribute to create.
qualifiedName - The qualified name of the attribute to instantiate.
Returns:
A new Attr object with the following attributes:
Attribute | Value
Node.nodeName | qualifiedName
Node.namespaceURI | namespaceURI
Node.prefix | prefix, extracted from qualifiedName, or null if there is no prefix
Node.localName | local name, extracted from qualifiedName
Attr.name | qualifiedName
Node.nodeValue | the empty string
Throws:
DOMException - INVALID_CHARACTER_ERR: Raised if the specified qualified name contains an illegal character, per the XML 1.0 specification .
NAMESPACE_ERR: Raised if the qualifiedName is malformed per the Namespaces in XML specification, if the qualifiedName has a prefix and the namespaceURI is null, if the qualifiedName has a prefix that is "xml" and the namespaceURI is different from " http://www.w3.org/XML/1998/namespace", or if the qualifiedName, or its prefix, is "xmlns" and the namespaceURI is different from " http://www.w3.org/2000/xmlns/".
NOT_SUPPORTED_ERR: Always thrown if the current document does not support the "XML" feature, since namespaces were defined by XML.
Since:
DOM Level 2

getElementsByTagNameNS

public NodeList getElementsByTagNameNS(String namespaceURI,
                                       String localName)
Returns a NodeList of all the Elements with a given local name and namespace URI in the order in which they are encountered in a preorder traversal of the Document tree.

Parameters:
namespaceURI - The namespace URI of the elements to match on. The special value "*" matches all namespaces.
localName - The local name of the elements to match on. The special value "*" matches all local names.
Returns:
A new NodeList object containing all the matched Elements.
Since:
DOM Level 2

getElementById

public Element getElementById(String elementId)
Returns the Element whose ID is given by elementId. If no such element exists, returns null. Behavior is not defined if more than one element has this ID. The DOM implementation must have information that says which attributes are of type ID. Attributes with the name "ID" are not of type ID unless so defined. Implementations that do not know whether attributes are of type ID or not are expected to return null.

Parameters:
elementId - The unique id value for an element.
Returns:
The matching element.
Since:
DOM Level 2
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


DocumentFragment (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom
Interface DocumentFragment

All Superinterfaces:
Node
public interface DocumentFragment
extends Node

DocumentFragment is a "lightweight" or "minimal" Document object. It is very common to want to be able to extract a portion of a document's tree or to create a new fragment of a document. Imagine implementing a user command like cut or rearranging a document by moving fragments around. It is desirable to have an object which can hold such fragments and it is quite natural to use a Node for this purpose. While it is true that a Document object could fulfill this role, a Document object can potentially be a heavyweight object, depending on the underlying implementation. What is really needed for this is a very lightweight object. DocumentFragment is such an object.

Furthermore, various operations -- such as inserting nodes as children of another Node -- may take DocumentFragment objects as arguments; this results in all the child nodes of the DocumentFragment being moved to the child list of this node.

The children of a DocumentFragment node are zero or more nodes representing the tops of any sub-trees defining the structure of the document. DocumentFragment nodes do not need to be well-formed XML documents (although they do need to follow the rules imposed upon well-formed XML parsed entities, which can have multiple top nodes). For example, a DocumentFragment might have only one child and that child node could be a Text node. Such a structure model represents neither an HTML document nor a well-formed XML document.

When a DocumentFragment is inserted into a Document (or indeed any other Node that may take children) the children of the DocumentFragment and not the DocumentFragment itself are inserted into the Node. This makes the DocumentFragment very useful when the user wishes to create nodes that are siblings; the DocumentFragment acts as the parent of these nodes so that the user can use the standard methods from the Node interface, such as insertBefore and appendChild.

See also the Document Object Model (DOM) Level 2 Core Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


DocumentType (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom
Interface DocumentType

All Superinterfaces:
Node
public interface DocumentType
extends Node

Each Document has a doctype attribute whose value is either null or a DocumentType object. The DocumentType interface in the DOM Core provides an interface to the list of entities that are defined for the document, and little else because the effect of namespaces and the various XML schema efforts on DTD representation are not clearly understood as of this writing.

The DOM Level 2 doesn't support editing DocumentType nodes.

See also the Document Object Model (DOM) Level 2 Core Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
NamedNodeMap | getEntities() A NamedNodeMap containing the general entities, both external and internal, declared in the DTD.
String | getInternalSubset() The internal subset as a string, or null if there is none.
String | getName() The name of DTD; i.e., the name immediately following the DOCTYPE keyword.
NamedNodeMap | getNotations() A NamedNodeMap containing the notations declared in the DTD.
String | getPublicId() The public identifier of the external subset.
String | getSystemId() The system identifier of the external subset.
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getName

public String getName()
The name of DTD; i.e., the name immediately following the DOCTYPE keyword.

getEntities

public NamedNodeMap getEntities()
A NamedNodeMap containing the general entities, both external and internal, declared in the DTD. Parameter entities are not contained. Duplicates are discarded. For example in:
<!DOCTYPE
 ex SYSTEM "ex.dtd" [ <!ENTITY foo "foo"> <!ENTITY bar
 "bar"> <!ENTITY bar "bar2"> <!ENTITY % baz "baz">
 ]> <ex/>
the interface provides access to foo and the first declaration of bar but not the second declaration of bar or baz. Every node in this map also implements the Entity interface.
The DOM Level 2 does not support editing entities, therefore entities cannot be altered in any way.

getNotations

public NamedNodeMap getNotations()
A NamedNodeMap containing the notations declared in the DTD. Duplicates are discarded. Every node in this map also implements the Notation interface.
The DOM Level 2 does not support editing notations, therefore notations cannot be altered in any way.

getPublicId

public String getPublicId()
The public identifier of the external subset.

Since:
DOM Level 2

getSystemId

public String getSystemId()
The system identifier of the external subset.

Since:
DOM Level 2

getInternalSubset

public String getInternalSubset()
The internal subset as a string, or null if there is none. This is does not contain the delimiting square brackets.The actual content returned depends on how much information is available to the implementation. This may vary depending on various parameters, including the XML processor used to build the document.

Since:
DOM Level 2
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


DOMException (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom
Class DOMException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by org.w3c.dom.DOMException
All Implemented Interfaces:
Serializable
public class DOMException
extends RuntimeException

DOM operations only raise exceptions in "exceptional" circumstances, i.e., when an operation is impossible to perform (either for logical reasons, because data is lost, or because the implementation has become unstable). In general, DOM methods return specific error values in ordinary processing situations, such as out-of-bound errors when using NodeList.

Implementations should raise other exceptions under other circumstances. For example, implementations should raise an implementation-dependent exception if a null argument is passed.

Some languages and object systems do not support the concept of exceptions. For such systems, error conditions may be indicated using native error reporting mechanisms. For some bindings, for example, methods may return error codes similar to those listed in the corresponding method descriptions.

See also the Document Object Model (DOM) Level 2 Core Specification.

See Also:
Serialized Form

Field Summary
short | code
static short | DOMSTRING_SIZE_ERR If the specified range of text does not fit into a DOMString
static short | HIERARCHY_REQUEST_ERR If any node is inserted somewhere it doesn't belong
static short | INDEX_SIZE_ERR If index or size is negative, or greater than the allowed value
static short | INUSE_ATTRIBUTE_ERR If an attempt is made to add an attribute that is already in use elsewhere
static short | INVALID_ACCESS_ERR If a parameter or an operation is not supported by the underlying object.
static short | INVALID_CHARACTER_ERR If an invalid or illegal character is specified, such as in a name.
static short | INVALID_MODIFICATION_ERR If an attempt is made to modify the type of the underlying object.
static short | INVALID_STATE_ERR If an attempt is made to use an object that is not, or is no longer, usable.
static short | NAMESPACE_ERR If an attempt is made to create or change an object in a way which is incorrect with regard to namespaces.
static short | NO_DATA_ALLOWED_ERR If data is specified for a node which does not support data
static short | NO_MODIFICATION_ALLOWED_ERR If an attempt is made to modify an object where modifications are not allowed
static short | NOT_FOUND_ERR If an attempt is made to reference a node in a context where it does not exist
static short | NOT_SUPPORTED_ERR If the implementation does not support the requested type of object or operation.
static short | SYNTAX_ERR If an invalid or illegal string is specified.
static short | WRONG_DOCUMENT_ERR If a node is used in a different document than the one that created it (that doesn't support it)
Constructor Summary
DOMException(short code, String message)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

code

public short code

INDEX_SIZE_ERR

public static final short INDEX_SIZE_ERR
If index or size is negative, or greater than the allowed value

See Also:
Constant Field Values

DOMSTRING_SIZE_ERR

public static final short DOMSTRING_SIZE_ERR
If the specified range of text does not fit into a DOMString

See Also:
Constant Field Values

HIERARCHY_REQUEST_ERR

public static final short HIERARCHY_REQUEST_ERR
If any node is inserted somewhere it doesn't belong

See Also:
Constant Field Values

WRONG_DOCUMENT_ERR

public static final short WRONG_DOCUMENT_ERR
If a node is used in a different document than the one that created it (that doesn't support it)

See Also:
Constant Field Values

INVALID_CHARACTER_ERR

public static final short INVALID_CHARACTER_ERR
If an invalid or illegal character is specified, such as in a name. See production 2 in the XML specification for the definition of a legal character, and production 5 for the definition of a legal name character.

See Also:
Constant Field Values

NO_DATA_ALLOWED_ERR

public static final short NO_DATA_ALLOWED_ERR
If data is specified for a node which does not support data

See Also:
Constant Field Values

NO_MODIFICATION_ALLOWED_ERR

public static final short NO_MODIFICATION_ALLOWED_ERR
If an attempt is made to modify an object where modifications are not allowed

See Also:
Constant Field Values

NOT_FOUND_ERR

public static final short NOT_FOUND_ERR
If an attempt is made to reference a node in a context where it does not exist

See Also:
Constant Field Values

NOT_SUPPORTED_ERR

public static final short NOT_SUPPORTED_ERR
If the implementation does not support the requested type of object or operation.

See Also:
Constant Field Values

INUSE_ATTRIBUTE_ERR

public static final short INUSE_ATTRIBUTE_ERR
If an attempt is made to add an attribute that is already in use elsewhere

See Also:
Constant Field Values

INVALID_STATE_ERR

public static final short INVALID_STATE_ERR
If an attempt is made to use an object that is not, or is no longer, usable.

Since:
DOM Level 2
See Also:
Constant Field Values

SYNTAX_ERR

public static final short SYNTAX_ERR
If an invalid or illegal string is specified.

Since:
DOM Level 2
See Also:
Constant Field Values

INVALID_MODIFICATION_ERR

public static final short INVALID_MODIFICATION_ERR
If an attempt is made to modify the type of the underlying object.

Since:
DOM Level 2
See Also:
Constant Field Values

NAMESPACE_ERR

public static final short NAMESPACE_ERR
If an attempt is made to create or change an object in a way which is incorrect with regard to namespaces.

Since:
DOM Level 2
See Also:
Constant Field Values

INVALID_ACCESS_ERR

public static final short INVALID_ACCESS_ERR
If a parameter or an operation is not supported by the underlying object.

Since:
DOM Level 2
See Also:
Constant Field Values
Constructor Detail

DOMException

public DOMException(short code,
                    String message)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


DOMImplementation (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom
Interface DOMImplementation

All Known Subinterfaces:
DOMImplementationCSS, HTMLDOMImplementation
public interface DOMImplementation

The DOMImplementation interface provides a number of methods for performing operations that are independent of any particular instance of the document object model.

See also the Document Object Model (DOM) Level 2 Core Specification.

Method Summary
Document | createDocument(String namespaceURI, String qualifiedName, DocumentType doctype) Creates a DOM Document object of the specified type with its document element.
DocumentType | createDocumentType(String qualifiedName, String publicId, String systemId) Creates an empty DocumentType node.
boolean | hasFeature(String feature, String version) Test if the DOM implementation implements a specific feature.

Method Detail

hasFeature

public boolean hasFeature(String feature,
                          String version)
Test if the DOM implementation implements a specific feature.

Parameters:
feature - The name of the feature to test (case-insensitive). The values used by DOM features are defined throughout the DOM Level 2 specifications and listed in the section. The name must be an XML name. To avoid possible conflicts, as a convention, names referring to features defined outside the DOM specification should be made unique.
version - This is the version number of the feature to test. In Level 2, the string can be either "2.0" or "1.0". If the version is not specified, supporting any version of the feature causes the method to return true.
Returns:
true if the feature is implemented in the specified version, false otherwise.

createDocumentType

public DocumentType createDocumentType(String qualifiedName,
                                       String publicId,
                                       String systemId)
                                throws DOMException
Creates an empty DocumentType node. Entity declarations and notations are not made available. Entity reference expansions and default attribute additions do not occur. It is expected that a future version of the DOM will provide a way for populating a DocumentType.

Parameters:
qualifiedName - The qualified name of the document type to be created.
publicId - The external subset public identifier.
systemId - The external subset system identifier.
Returns:
A new DocumentType node with Node.ownerDocument set to null.
Throws:
DOMException - INVALID_CHARACTER_ERR: Raised if the specified qualified name contains an illegal character.
NAMESPACE_ERR: Raised if the qualifiedName is malformed.
NOT_SUPPORTED_ERR: May be raised by DOM implementations which do not support the "XML" feature, if they choose not to support this method. Other features introduced in the future, by the DOM WG or in extensions defined by other groups, may also demand support for this method; please consult the definition of the feature to see if it requires this method.
Since:
DOM Level 2

createDocument

public Document createDocument(String namespaceURI,
                               String qualifiedName,
                               DocumentType doctype)
                        throws DOMException
Creates a DOM Document object of the specified type with its document element.

Parameters:
namespaceURI - The namespace URI of the document element to create.
qualifiedName - The qualified name of the document element to be created.
doctype - The type of document to be created or null. When doctype is not null, its Node.ownerDocument attribute is set to the document being created.
Returns:
A new Document object.
Throws:
DOMException - INVALID_CHARACTER_ERR: Raised if the specified qualified name contains an illegal character.
NAMESPACE_ERR: Raised if the qualifiedName is malformed, if the qualifiedName has a prefix and the namespaceURI is null, or if the qualifiedName has a prefix that is "xml" and the namespaceURI is different from " http://www.w3.org/XML/1998/namespace" , or if the DOM implementation does not support the "XML" feature but a non-null namespace URI was provided, since namespaces were defined by XML.
WRONG_DOCUMENT_ERR: Raised if doctype has already been used with a different document or was created from a different implementation.
NOT_SUPPORTED_ERR: May be raised by DOM implementations which do not support the "XML" feature, if they choose not to support this method. Other features introduced in the future, by the DOM WG or in extensions defined by other groups, may also demand support for this method; please consult the definition of the feature to see if it requires this method.
Since:
DOM Level 2
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Element (Common DOM API)

s
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom
Interface Element

All Superinterfaces:
Node
All Known Subinterfaces:
HTMLAnchorElement, HTMLAppletElement, HTMLAreaElement, HTMLBaseElement, HTMLBaseFontElement, HTMLBodyElement, HTMLBRElement, HTMLButtonElement, HTMLDirectoryElement, HTMLDivElement, HTMLDListElement, HTMLElement, HTMLFieldSetElement, HTMLFontElement, HTMLFormElement, HTMLFrameElement, HTMLFrameSetElement, HTMLHeadElement, HTMLHeadingElement, HTMLHRElement, HTMLHtmlElement, HTMLIFrameElement, HTMLImageElement, HTMLInputElement, HTMLIsIndexElement, HTMLLabelElement, HTMLLegendElement, HTMLLIElement, HTMLLinkElement, HTMLMapElement, HTMLMenuElement, HTMLMetaElement, HTMLModElement, HTMLObjectElement, HTMLOListElement, HTMLOptGroupElement, HTMLOptionElement, HTMLParagraphElement, HTMLParamElement, HTMLPreElement, HTMLQuoteElement, HTMLScriptElement, HTMLSelectElement, HTMLStyleElement, HTMLTableCaptionElement, HTMLTableCellElement, HTMLTableColElement, HTMLTableElement, HTMLTableRowElement, HTMLTableSectionElement, HTMLTextAreaElement, HTMLTitleElement, HTMLUListElement
public interface Element
extends Node

The Element interface represents an element in an HTML or XML document. Elements may have attributes associated with them; since the Element interface inherits from Node, the generic Node interface attribute attributes may be used to retrieve the set of all attributes for an element. There are methods on the Element interface to retrieve either an Attr object by name or an attribute value by name. In XML, where an attribute value may contain entity references, an Attr object should be retrieved to examine the possibly fairly complex sub-tree representing the attribute value. On the other hand, in HTML, where all attributes have simple string values, methods to directly access an attribute value can safely be used as a convenience.In DOM Level 2, the method normalize is inherited from the Node interface where it was moved.

See also the Document Object Model (DOM) Level 2 Core Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getAttribute(String name) Retrieves an attribute value by name.
Attr | getAttributeNode(String name) Retrieves an attribute node by name.
Attr | getAttributeNodeNS(String namespaceURI, String localName) Retrieves an Attr node by local name and namespace URI.
String | getAttributeNS(String namespaceURI, String localName) Retrieves an attribute value by local name and namespace URI.
NodeList | getElementsByTagName(String name) Returns a NodeList of all descendant Elements with a given tag name, in the order in which they are encountered in a preorder traversal of this Element tree.
NodeList | getElementsByTagNameNS(String namespaceURI, String localName) Returns a NodeList of all the descendant Elements with a given local name and namespace URI in the order in which they are encountered in a preorder traversal of this Element tree.
String | getTagName() The name of the element.
boolean | hasAttribute(String name) Returns true when an attribute with a given name is specified on this element or has a default value, false otherwise.
boolean | 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.
void | removeAttribute(String name) Removes an attribute by name.
Attr | removeAttributeNode(Attr oldAttr) Removes the specified attribute node.
void | removeAttributeNS(String namespaceURI, String localName) Removes an attribute by local name and namespace URI.
void | setAttribute(String name, String value) Adds a new attribute.
Attr | setAttributeNode(Attr newAttr) Adds a new attribute node.
Attr | setAttributeNodeNS(Attr newAttr) Adds a new attribute.
void | setAttributeNS(String namespaceURI, String qualifiedName, String value) Adds a new attribute.
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getTagName

public String getTagName()
The name of the element. For example, in:
 <elementExample
 id="demo"> ... </elementExample> ,
tagName has the value "elementExample". Note that this is case-preserving in XML, as are all of the operations of the DOM. The HTML DOM returns the tagName of an HTML element in the canonical uppercase form, regardless of the case in the source HTML document.

getAttribute

public String getAttribute(String name)
Retrieves an attribute value by name.

Parameters:
name - The name of the attribute to retrieve.
Returns:
The Attr value as a string, or the empty string if that attribute does not have a specified or default value.

setAttribute

public void setAttribute(String name,
                         String value)
                  throws DOMException
Adds a new attribute. If an attribute with that name is already present in the element, its value is changed to be that of the value parameter. This value is a simple string; it is not parsed as it is being set. So any markup (such as syntax to be recognized as an entity reference) is treated as literal text, and needs to be appropriately escaped by the implementation when it is written out. In order to assign an attribute value that contains entity references, the user must create an Attr node plus any Text and EntityReference nodes, build the appropriate subtree, and use setAttributeNode to assign it as the value of an attribute.
To set an attribute with a qualified name and namespace URI, use the setAttributeNS method.

Parameters:
name - The name of the attribute to create or alter.
value - Value to set in string form.
Throws:
DOMException - INVALID_CHARACTER_ERR: Raised if the specified name contains an illegal character.
NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.

removeAttribute

public void removeAttribute(String name)
                     throws DOMException
Removes an attribute by name. If the removed attribute is known to have a default value, an attribute immediately appears containing the default value as well as the corresponding namespace URI, local name, and prefix when applicable.
To remove an attribute by local name and namespace URI, use the removeAttributeNS method.

Parameters:
name - The name of the attribute to remove.
Throws:
DOMException - NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.

getAttributeNode

public Attr getAttributeNode(String name)
Retrieves an attribute node by name.
To retrieve an attribute node by qualified name and namespace URI, use the getAttributeNodeNS method.

Parameters:
name - The name (nodeName) of the attribute to retrieve.
Returns:
The Attr node with the specified name ( nodeName) or null if there is no such attribute.

setAttributeNode

public Attr setAttributeNode(Attr newAttr)
                      throws DOMException
Adds a new attribute node. If an attribute with that name ( nodeName) is already present in the element, it is replaced by the new one.
To add a new attribute node with a qualified name and namespace URI, use the setAttributeNodeNS method.

Parameters:
newAttr - The Attr node to add to the attribute list.
Returns:
If the newAttr attribute replaces an existing attribute, the replaced Attr node is returned, otherwise null is returned.
Throws:
DOMException - WRONG_DOCUMENT_ERR: Raised if newAttr was created from a different document than the one that created the element.
NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.
INUSE_ATTRIBUTE_ERR: Raised if newAttr is already an attribute of another Element object. The DOM user must explicitly clone Attr nodes to re-use them in other elements.

removeAttributeNode

public Attr removeAttributeNode(Attr oldAttr)
                         throws DOMException
Removes the specified attribute node. If the removed Attr has a default value it is immediately replaced. The replacing attribute has the same namespace URI and local name, as well as the original prefix, when applicable.

Parameters:
oldAttr - The Attr node to remove from the attribute list.
Returns:
The Attr node that was removed.
Throws:
DOMException - NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.
NOT_FOUND_ERR: Raised if oldAttr is not an attribute of the element.

getElementsByTagName

public NodeList getElementsByTagName(String name)
Returns a NodeList of all descendant Elements with a given tag name, in the order in which they are encountered in a preorder traversal of this Element tree.

Parameters:
name - The name of the tag to match on. The special value "*" matches all tags.
Returns:
A list of matching Element nodes.

getAttributeNS

public String getAttributeNS(String namespaceURI,
                             String localName)
Retrieves an attribute value by local name and namespace URI.
Documents which do not support the "XML" feature will permit only the DOM Level 1 calls for creating/setting elements and attributes. Hence, if you specify a non-null namespace URI, these DOMs will never find a matching node.

Parameters:
namespaceURI - The namespace URI of the attribute to retrieve.
localName - The local name of the attribute to retrieve.
Returns:
The Attr value as a string, or the empty string if that attribute does not have a specified or default value.
Since:
DOM Level 2

setAttributeNS

public void setAttributeNS(String namespaceURI,
                           String qualifiedName,
                           String value)
                    throws DOMException
Adds a new attribute. If an attribute with the same local name and namespace URI is already present on the element, its prefix is changed to be the prefix part of the qualifiedName, and its value is changed to be the value parameter. This value is a simple string; it is not parsed as it is being set. So any markup (such as syntax to be recognized as an entity reference) is treated as literal text, and needs to be appropriately escaped by the implementation when it is written out. In order to assign an attribute value that contains entity references, the user must create an Attr node plus any Text and EntityReference nodes, build the appropriate subtree, and use setAttributeNodeNS or setAttributeNode to assign it as the value of an attribute.

Parameters:
namespaceURI - The namespace URI of the attribute to create or alter.
qualifiedName - The qualified name of the attribute to create or alter.
value - The value to set in string form.
Throws:
DOMException - INVALID_CHARACTER_ERR: Raised if the specified qualified name contains an illegal character, per the XML 1.0 specification .
NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.
NAMESPACE_ERR: Raised if the qualifiedName is malformed per the Namespaces in XML specification, if the qualifiedName has a prefix and the namespaceURI is null, if the qualifiedName has a prefix that is "xml" and the namespaceURI is different from " http://www.w3.org/XML/1998/namespace", or if the qualifiedName, or its prefix, is "xmlns" and the namespaceURI is different from " http://www.w3.org/2000/xmlns/".
NOT_SUPPORTED_ERR: Always thrown if the current document does not support the "XML" feature, since namespaces were defined by XML.
Since:
DOM Level 2

removeAttributeNS

public void removeAttributeNS(String namespaceURI,
                              String localName)
                       throws DOMException
Removes an attribute by local name and namespace URI. If the removed attribute has a default value it is immediately replaced. The replacing attribute has the same namespace URI and local name, as well as the original prefix.
Documents which do not support the "XML" feature will permit only the DOM Level 1 calls for creating/setting elements and attributes. Hence, if you specify a non-null namespace URI, these DOMs will never find a matching node.

Parameters:
namespaceURI - The namespace URI of the attribute to remove.
localName - The local name of the attribute to remove.
Throws:
DOMException - NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.
Since:
DOM Level 2

getAttributeNodeNS

public Attr getAttributeNodeNS(String namespaceURI,
                               String localName)
Retrieves an Attr node by local name and namespace URI.
Documents which do not support the "XML" feature will permit only the DOM Level 1 calls for creating/setting elements and attributes. Hence, if you specify a non-null namespace URI, these DOMs will never find a matching node.

Parameters:
namespaceURI - The namespace URI of the attribute to retrieve.
localName - The local name of the attribute to retrieve.
Returns:
The Attr node with the specified attribute local name and namespace URI or null if there is no such attribute.
Since:
DOM Level 2

setAttributeNodeNS

public Attr setAttributeNodeNS(Attr newAttr)
                        throws DOMException
Adds a new attribute. If an attribute with that local name and that namespace URI is already present in the element, it is replaced by the new one.

Parameters:
newAttr - The Attr node to add to the attribute list.
Returns:
If the newAttr attribute replaces an existing attribute with the same local name and namespace URI, the replaced Attr node is returned, otherwise null is returned.
Throws:
DOMException - WRONG_DOCUMENT_ERR: Raised if newAttr was created from a different document than the one that created the element.
NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.
INUSE_ATTRIBUTE_ERR: Raised if newAttr is already an attribute of another Element object. The DOM user must explicitly clone Attr nodes to re-use them in other elements.
NOT_SUPPORTED_ERR: Always thrown if the current document does not support the "XML" feature, since namespaces were defined by XML.
Since:
DOM Level 2

getElementsByTagNameNS

public NodeList getElementsByTagNameNS(String namespaceURI,
                                       String localName)
Returns a NodeList of all the descendant Elements with a given local name and namespace URI in the order in which they are encountered in a preorder traversal of this Element tree.
Documents which do not support the "XML" feature will permit only the DOM Level 1 calls for creating/setting elements and attributes. Hence, if you specify a non-null namespace URI, these DOMs will never find a matching node.

Parameters:
namespaceURI - The namespace URI of the elements to match on. The special value "*" matches all namespaces.
localName - The local name of the elements to match on. The special value "*" matches all local names.
Returns:
A new NodeList object containing all the matched Elements.
Since:
DOM Level 2

hasAttribute

public boolean hasAttribute(String name)
Returns true when an attribute with a given name is specified on this element or has a default value, false otherwise.

Parameters:
name - The name of the attribute to look for.
Returns:
true if an attribute with the given name is specified on this element or has a default value, false otherwise.
Since:
DOM Level 2

hasAttributeNS

public boolean 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.
Documents which do not support the "XML" feature will permit only the DOM Level 1 calls for creating/setting elements and attributes. Hence, if you specify a non-null namespace URI, these DOMs will never find a matching node.

Parameters:
namespaceURI - The namespace URI of the attribute to look for.
localName - The local name of the attribute to look for.
Returns:
true if an attribute with the given local name and namespace URI is specified or has a default value on this element, false otherwise.
Since:
DOM Level 2
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Entity (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom
Interface Entity

All Superinterfaces:
Node
public interface Entity
extends Node

This interface represents an entity, either parsed or unparsed, in an XML document. Note that this models the entity itself not the entity declaration. Entity declaration modeling has been left for a later Level of the DOM specification.

The nodeName attribute that is inherited from Node contains the name of the entity.

An XML processor may choose to completely expand entities before the structure model is passed to the DOM; in this case there will be no EntityReference nodes in the document tree.

XML does not mandate that a non-validating XML processor read and process entity declarations made in the external subset or declared in external parameter entities. This means that parsed entities declared in the external subset need not be expanded by some classes of applications, and that the replacement value of the entity may not be available. When the replacement value is available, the corresponding Entity node's child list represents the structure of that replacement text. Otherwise, the child list is empty.

The DOM Level 2 does not support editing Entity nodes; if a user wants to make changes to the contents of an Entity, every related EntityReference node has to be replaced in the structure model by a clone of the Entity's contents, and then the desired changes must be made to each of those clones instead. Entity nodes and all their descendants are readonly.

An Entity node does not have any parent.If the entity contains an unbound namespace prefix, the namespaceURI of the corresponding node in the Entity node subtree is null. The same is true for EntityReference nodes that refer to this entity, when they are created using the createEntityReference method of the Document interface. The DOM Level 2 does not support any mechanism to resolve namespace prefixes.

See also the Document Object Model (DOM) Level 2 Core Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getNotationName() For unparsed entities, the name of the notation for the entity.
String | getPublicId() The public identifier associated with the entity, if specified.
String | getSystemId() The system identifier associated with the entity, if specified.
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getPublicId

public String getPublicId()
The public identifier associated with the entity, if specified. If the public identifier was not specified, this is null.

getSystemId

public String getSystemId()
The system identifier associated with the entity, if specified. If the system identifier was not specified, this is null.

getNotationName

public String getNotationName()
For unparsed entities, the name of the notation for the entity. For parsed entities, this is null.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


EntityReference (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom
Interface EntityReference

All Superinterfaces:
Node
public interface EntityReference
extends Node

EntityReference objects may be inserted into the structure model when an entity reference is in the source document, or when the user wishes to insert an entity reference. Note that character references and references to predefined entities are considered to be expanded by the HTML or XML processor so that characters are represented by their Unicode equivalent rather than by an entity reference. Moreover, the XML processor may completely expand references to entities while building the structure model, instead of providing EntityReference objects. If it does provide such objects, then for a given EntityReference node, it may be that there is no Entity node representing the referenced entity. If such an Entity exists, then the subtree of the EntityReference node is in general a copy of the Entity node subtree. However, this may not be true when an entity contains an unbound namespace prefix. In such a case, because the namespace prefix resolution depends on where the entity reference is, the descendants of the EntityReference node may be bound to different namespace URIs.

As for Entity nodes, EntityReference nodes and all their descendants are readonly.

See also the Document Object Model (DOM) Level 2 Core Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


NamedNodeMap (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom
Interface NamedNodeMap

public interface NamedNodeMap

Objects implementing the NamedNodeMap interface are used to represent collections of nodes that can be accessed by name. Note that NamedNodeMap does not inherit from NodeList; NamedNodeMaps are not maintained in any particular order. Objects contained in an object implementing NamedNodeMap may also be accessed by an ordinal index, but this is simply to allow convenient enumeration of the contents of a NamedNodeMap, and does not imply that the DOM specifies an order to these Nodes.

NamedNodeMap objects in the DOM are live.

See also the Document Object Model (DOM) Level 2 Core Specification.

Method Summary
int | getLength() The number of nodes in this map.
Node | getNamedItem(String name) Retrieves a node specified by name.
Node | getNamedItemNS(String namespaceURI, String localName) Retrieves a node specified by local name and namespace URI.
Node | item(int index) Returns the indexth item in the map.
Node | removeNamedItem(String name) Removes a node specified by name.
Node | removeNamedItemNS(String namespaceURI, String localName) Removes a node specified by local name and namespace URI.
Node | setNamedItem(Node arg) Adds a node using its nodeName attribute.
Node | setNamedItemNS(Node arg) Adds a node using its namespaceURI and localName.

Method Detail

getNamedItem

public Node getNamedItem(String name)
Retrieves a node specified by name.

Parameters:
name - The nodeName of a node to retrieve.
Returns:
A Node (of any type) with the specified nodeName, or null if it does not identify any node in this map.

setNamedItem

public Node setNamedItem(Node arg)
                  throws DOMException
Adds a node using its nodeName attribute. If a node with that name is already present in this map, it is replaced by the new one.
As the nodeName attribute is used to derive the name which the node must be stored under, multiple nodes of certain types (those that have a "special" string value) cannot be stored as the names would clash. This is seen as preferable to allowing nodes to be aliased.

Parameters:
arg - A node to store in this map. The node will later be accessible using the value of its nodeName attribute.
Returns:
If the new Node replaces an existing node the replaced Node is returned, otherwise null is returned.
Throws:
DOMException - WRONG_DOCUMENT_ERR: Raised if arg was created from a different document than the one that created this map.
NO_MODIFICATION_ALLOWED_ERR: Raised if this map is readonly.
INUSE_ATTRIBUTE_ERR: Raised if arg is an Attr that is already an attribute of another Element object. The DOM user must explicitly clone Attr nodes to re-use them in other elements.
HIERARCHY_REQUEST_ERR: Raised if an attempt is made to add a node doesn't belong in this NamedNodeMap. Examples would include trying to insert something other than an Attr node into an Element's map of attributes, or a non-Entity node into the DocumentType's map of Entities.

removeNamedItem

public Node removeNamedItem(String name)
                     throws DOMException
Removes a node specified by name. When this map contains the attributes attached to an element, if the removed attribute is known to have a default value, an attribute immediately appears containing the default value as well as the corresponding namespace URI, local name, and prefix when applicable.

Parameters:
name - The nodeName of the node to remove.
Returns:
The node removed from this map if a node with such a name exists.
Throws:
DOMException - NOT_FOUND_ERR: Raised if there is no node named name in this map.
NO_MODIFICATION_ALLOWED_ERR: Raised if this map is readonly.

item

public Node item(int index)
Returns the indexth item in the map. If index is greater than or equal to the number of nodes in this map, this returns null.

Parameters:
index - Index into this map.
Returns:
The node at the indexth position in the map, or null if that is not a valid index.

getLength

public int getLength()
The number of nodes in this map. The range of valid child node indices is 0 to length-1 inclusive.

getNamedItemNS

public Node getNamedItemNS(String namespaceURI,
                           String localName)
Retrieves a node specified by local name and namespace URI.
Documents which do not support the "XML" feature will permit only the DOM Level 1 calls for creating/setting elements and attributes. Hence, if you specify a non-null namespace URI, these DOMs will never find a matching node.

Parameters:
namespaceURI - The namespace URI of the node to retrieve.
localName - The local name of the node to retrieve.
Returns:
A Node (of any type) with the specified local name and namespace URI, or null if they do not identify any node in this map.
Since:
DOM Level 2

setNamedItemNS

public Node setNamedItemNS(Node arg)
                    throws DOMException
Adds a node using its namespaceURI and localName. If a node with that namespace URI and that local name is already present in this map, it is replaced by the new one.

Parameters:
arg - A node to store in this map. The node will later be accessible using the value of its namespaceURI and localName attributes.
Returns:
If the new Node replaces an existing node the replaced Node is returned, otherwise null is returned.
Throws:
DOMException - WRONG_DOCUMENT_ERR: Raised if arg was created from a different document than the one that created this map.
NO_MODIFICATION_ALLOWED_ERR: Raised if this map is readonly.
INUSE_ATTRIBUTE_ERR: Raised if arg is an Attr that is already an attribute of another Element object. The DOM user must explicitly clone Attr nodes to re-use them in other elements.
HIERARCHY_REQUEST_ERR: Raised if an attempt is made to add a node doesn't belong in this NamedNodeMap. Examples would include trying to insert something other than an Attr node into an Element's map of attributes, or a non-Entity node into the DocumentType's map of Entities.
NOT_SUPPORTED_ERR: Always thrown if the current document does not support the "XML" feature, since namespaces were defined by XML.
Since:
DOM Level 2

removeNamedItemNS

public Node removeNamedItemNS(String namespaceURI,
                              String localName)
                       throws DOMException
Removes a node specified by local name and namespace URI. A removed attribute may be known to have a default value when this map contains the attributes attached to an element, as returned by the attributes attribute of the Node interface. If so, an attribute immediately appears containing the default value as well as the corresponding namespace URI, local name, and prefix when applicable.
Documents which do not support the "XML" feature will permit only the DOM Level 1 calls for creating/setting elements and attributes. Hence, if you specify a non-null namespace URI, these DOMs will never find a matching node.

Parameters:
namespaceURI - The namespace URI of the node to remove.
localName - The local name of the node to remove.
Returns:
The node removed from this map if a node with such a local name and namespace URI exists.
Throws:
DOMException - NOT_FOUND_ERR: Raised if there is no node with the specified namespaceURI and localName in this map.
NO_MODIFICATION_ALLOWED_ERR: Raised if this map is readonly.
Since:
DOM Level 2
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Node (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom
Interface Node

All Known Subinterfaces:
Attr, CDATASection, CharacterData, Comment, Document, DocumentFragment, DocumentType, Element, Entity, EntityReference, HTMLAnchorElement, HTMLAppletElement, HTMLAreaElement, HTMLBaseElement, HTMLBaseFontElement, HTMLBodyElement, HTMLBRElement, HTMLButtonElement, HTMLDirectoryElement, HTMLDivElement, HTMLDListElement, HTMLDocument, HTMLElement, HTMLFieldSetElement, HTMLFontElement, HTMLFormElement, HTMLFrameElement, HTMLFrameSetElement, HTMLHeadElement, HTMLHeadingElement, HTMLHRElement, HTMLHtmlElement, HTMLIFrameElement, HTMLImageElement, HTMLInputElement, HTMLIsIndexElement, HTMLLabelElement, HTMLLegendElement, HTMLLIElement, HTMLLinkElement, HTMLMapElement, HTMLMenuElement, HTMLMetaElement, HTMLModElement, HTMLObjectElement, HTMLOListElement, HTMLOptGroupElement, HTMLOptionElement, HTMLParagraphElement, HTMLParamElement, HTMLPreElement, HTMLQuoteElement, HTMLScriptElement, HTMLSelectElement, HTMLStyleElement, HTMLTableCaptionElement, HTMLTableCellElement, HTMLTableColElement, HTMLTableElement, HTMLTableRowElement, HTMLTableSectionElement, HTMLTextAreaElement, HTMLTitleElement, HTMLUListElement, Notation, ProcessingInstruction, Text
public interface Node

The Node interface is the primary datatype for the entire Document Object Model. It represents a single node in the document tree. While all objects implementing the Node interface expose methods for dealing with children, not all objects implementing the Node interface may have children. For example, Text nodes may not have children, and adding children to such nodes results in a DOMException being raised.

The attributes nodeName, nodeValue and attributes are included as a mechanism to get at node information without casting down to the specific derived interface. In cases where there is no obvious mapping of these attributes for a specific nodeType (e.g., nodeValue for an Element or attributes for a Comment ), this returns null. Note that the specialized interfaces may contain additional and more convenient mechanisms to get and set the relevant information.

The values of nodeName, nodeValue, and attributes vary according to the node type as follows:

Interface | nodeName | nodeValue | attributes
Attr | name of attribute | value of attribute | null
CDATASection | "#cdata-section" | content of the CDATA Section | null
Comment | "#comment" | content of the comment | null
Document | "#document" | null | null
DocumentFragment | "#document-fragment" | null | null
DocumentType | document type name | null | null
Element | tag name | null | NamedNodeMap
Entity | entity name | null | null
EntityReference | name of entity referenced | null | null
Notation | notation name | null | null
ProcessingInstruction | target | entire content excluding the target | null
Text | "#text" | content of the text node | null

See also the Document Object Model (DOM) Level 2 Core Specification.

Field Summary
static short | ATTRIBUTE_NODE The node is an Attr.
static short | CDATA_SECTION_NODE The node is a CDATASection.
static short | COMMENT_NODE The node is a Comment.
static short | DOCUMENT_FRAGMENT_NODE The node is a DocumentFragment.
static short | DOCUMENT_NODE The node is a Document.
static short | DOCUMENT_TYPE_NODE The node is a DocumentType.
static short | ELEMENT_NODE The node is an Element.
static short | ENTITY_NODE The node is an Entity.
static short | ENTITY_REFERENCE_NODE The node is an EntityReference.
static short | NOTATION_NODE The node is a Notation.
static short | PROCESSING_INSTRUCTION_NODE The node is a ProcessingInstruction.
static short | TEXT_NODE The node is a Text node.
Method Summary
Node | appendChild(Node newChild) Adds the node newChild to the end of the list of children of this node.
Node | cloneNode(boolean deep) Returns a duplicate of this node, i.e., serves as a generic copy constructor for nodes.
NamedNodeMap | getAttributes() A NamedNodeMap containing the attributes of this node (if it is an Element) or null otherwise.
NodeList | getChildNodes() A NodeList that contains all children of this node.
Node | getFirstChild() The first child of this node.
Node | getLastChild() The last child of this node.
String | getLocalName() Returns the local part of the qualified name of this node.
String | getNamespaceURI() The namespace URI of this node, or null if it is unspecified.
Node | getNextSibling() The node immediately following this node.
String | getNodeName() The name of this node, depending on its type; see the table above.
short | getNodeType() A code representing the type of the underlying object, as defined above.
String | getNodeValue() The value of this node, depending on its type; see the table above.
Document | getOwnerDocument() The Document object associated with this node.
Node | getParentNode() The parent of this node.
String | getPrefix() The namespace prefix of this node, or null if it is unspecified.
Node | getPreviousSibling() The node immediately preceding this node.
boolean | hasAttributes() Returns whether this node (if it is an element) has any attributes.
boolean | hasChildNodes() Returns whether this node has any children.
Node | insertBefore(Node newChild, Node refChild) Inserts the node newChild before the existing child node refChild.
boolean | isSupported(String feature, String version) Tests whether the DOM implementation implements a specific feature and that feature is supported by this node.
void | normalize() 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.
Node | removeChild(Node oldChild) Removes the child node indicated by oldChild from the list of children, and returns it.
Node | replaceChild(Node newChild, Node oldChild) Replaces the child node oldChild with newChild in the list of children, and returns the oldChild node.
void | setNodeValue(String nodeValue) The value of this node, depending on its type; see the table above.
void | setPrefix(String prefix) The namespace prefix of this node, or null if it is unspecified.

Field Detail

ELEMENT_NODE

public static final short ELEMENT_NODE
The node is an Element.

See Also:
Constant Field Values

ATTRIBUTE_NODE

public static final short ATTRIBUTE_NODE
The node is an Attr.

See Also:
Constant Field Values

TEXT_NODE

public static final short TEXT_NODE
The node is a Text node.

See Also:
Constant Field Values

CDATA_SECTION_NODE

public static final short CDATA_SECTION_NODE
The node is a CDATASection.

See Also:
Constant Field Values

ENTITY_REFERENCE_NODE

public static final short ENTITY_REFERENCE_NODE
The node is an EntityReference.

See Also:
Constant Field Values

ENTITY_NODE

public static final short ENTITY_NODE
The node is an Entity.

See Also:
Constant Field Values

PROCESSING_INSTRUCTION_NODE

public static final short PROCESSING_INSTRUCTION_NODE
The node is a ProcessingInstruction.

See Also:
Constant Field Values

COMMENT_NODE

public static final short COMMENT_NODE
The node is a Comment.

See Also:
Constant Field Values

DOCUMENT_NODE

public static final short DOCUMENT_NODE
The node is a Document.

See Also:
Constant Field Values

DOCUMENT_TYPE_NODE

public static final short DOCUMENT_TYPE_NODE
The node is a DocumentType.

See Also:
Constant Field Values

DOCUMENT_FRAGMENT_NODE

public static final short DOCUMENT_FRAGMENT_NODE
The node is a DocumentFragment.

See Also:
Constant Field Values

NOTATION_NODE

public static final short NOTATION_NODE
The node is a Notation.

See Also:
Constant Field Values
Method Detail

getNodeName

public String getNodeName()
The name of this node, depending on its type; see the table above.

getNodeValue

public String getNodeValue()
                    throws DOMException
The value of this node, depending on its type; see the table above. When it is defined to be null, setting it has no effect.

Throws:
DOMException - NO_MODIFICATION_ALLOWED_ERR: Raised when the node is readonly.
DOMException - DOMSTRING_SIZE_ERR: Raised when it would return more characters than fit in a DOMString variable on the implementation platform.

setNodeValue

public void setNodeValue(String nodeValue)
                  throws DOMException
The value of this node, depending on its type; see the table above. When it is defined to be null, setting it has no effect.

Throws:
DOMException - NO_MODIFICATION_ALLOWED_ERR: Raised when the node is readonly.
DOMException - DOMSTRING_SIZE_ERR: Raised when it would return more characters than fit in a DOMString variable on the implementation platform.

getNodeType

public short getNodeType()
A code representing the type of the underlying object, as defined above.

getParentNode

public Node getParentNode()
The parent of this node. All nodes, except Attr, Document, DocumentFragment, Entity, and Notation may have a parent. However, if a node has just been created and not yet added to the tree, or if it has been removed from the tree, this is null.

getChildNodes

public NodeList getChildNodes()
A NodeList that contains all children of this node. If there are no children, this is a NodeList containing no nodes.

getFirstChild

public Node getFirstChild()
The first child of this node. If there is no such node, this returns null.

getLastChild

public Node getLastChild()
The last child of this node. If there is no such node, this returns null.

getPreviousSibling

public Node getPreviousSibling()
The node immediately preceding this node. If there is no such node, this returns null.

getNextSibling

public Node getNextSibling()
The node immediately following this node. If there is no such node, this returns null.

getAttributes

public NamedNodeMap getAttributes()
A NamedNodeMap containing the attributes of this node (if it is an Element) or null otherwise.

getOwnerDocument

public Document getOwnerDocument()
The Document object associated with this node. This is also the Document object used to create new nodes. When this node is a Document or a DocumentType which is not used with any Document yet, this is null.

insertBefore

public Node insertBefore(Node newChild,
                         Node refChild)
                  throws DOMException
Inserts the node newChild before the existing child node refChild. If refChild is null, insert newChild at the end of the list of children.
If newChild is a DocumentFragment object, all of its children are inserted, in the same order, before refChild. If the newChild is already in the tree, it is first removed.

Parameters:
newChild - The node to insert.
refChild - The reference node, i.e., the node before which the new node must be inserted.
Returns:
The node being inserted.
Throws:
DOMException - HIERARCHY_REQUEST_ERR: Raised if this node is of a type that does not allow children of the type of the newChild node, or if the node to insert is one of this node's ancestors or this node itself.
WRONG_DOCUMENT_ERR: Raised if newChild was created from a different document than the one that created this node.
NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly or if the parent of the node being inserted is readonly.
NOT_FOUND_ERR: Raised if refChild is not a child of this node.

replaceChild

public Node replaceChild(Node newChild,
                         Node oldChild)
                  throws DOMException
Replaces the child node oldChild with newChild in the list of children, and returns the oldChild node.
If newChild is a DocumentFragment object, oldChild is replaced by all of the DocumentFragment children, which are inserted in the same order. If the newChild is already in the tree, it is first removed.

Parameters:
newChild - The new node to put in the child list.
oldChild - The node being replaced in the list.
Returns:
The node replaced.
Throws:
DOMException - HIERARCHY_REQUEST_ERR: Raised if this node is of a type that does not allow children of the type of the newChild node, or if the node to put in is one of this node's ancestors or this node itself.
WRONG_DOCUMENT_ERR: Raised if newChild was created from a different document than the one that created this node.
NO_MODIFICATION_ALLOWED_ERR: Raised if this node or the parent of the new node is readonly.
NOT_FOUND_ERR: Raised if oldChild is not a child of this node.

removeChild

public Node removeChild(Node oldChild)
                 throws DOMException
Removes the child node indicated by oldChild from the list of children, and returns it.

Parameters:
oldChild - The node being removed.
Returns:
The node removed.
Throws:
DOMException - NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.
NOT_FOUND_ERR: Raised if oldChild is not a child of this node.

appendChild

public Node appendChild(Node newChild)
                 throws DOMException
Adds the node newChild to the end of the list of children of this node. If the newChild is already in the tree, it is first removed.

Parameters:
newChild - The node to add.If it is a DocumentFragment object, the entire contents of the document fragment are moved into the child list of this node
Returns:
The node added.
Throws:
DOMException - HIERARCHY_REQUEST_ERR: Raised if this node is of a type that does not allow children of the type of the newChild node, or if the node to append is one of this node's ancestors or this node itself.
WRONG_DOCUMENT_ERR: Raised if newChild was created from a different document than the one that created this node.
NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly or if the previous parent of the node being inserted is readonly.

hasChildNodes

public boolean hasChildNodes()
Returns whether this node has any children.

Returns:
true if this node has any children, false otherwise.

cloneNode

public Node cloneNode(boolean deep)
Returns a duplicate of this node, i.e., serves as a generic copy constructor for nodes. The duplicate node has no parent; ( parentNode is null.).
Cloning an Element copies all attributes and their values, including those generated by the XML processor to represent defaulted attributes, but this method does not copy any text it contains unless it is a deep clone, since the text is contained in a child Text node. Cloning an Attribute directly, as opposed to be cloned as part of an Element cloning operation, returns a specified attribute ( specified is true). Cloning any other type of node simply returns a copy of this node.
Note that cloning an immutable subtree results in a mutable copy, but the children of an EntityReference clone are readonly . In addition, clones of unspecified Attr nodes are specified. And, cloning Document, DocumentType, Entity, and Notation nodes is implementation dependent.

Parameters:
deep - If true, recursively clone the subtree under the specified node; if false, clone only the node itself (and its attributes, if it is an Element).
Returns:
The duplicate node.

normalize

public void normalize()
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. This can be used to ensure that the DOM view of a document is the same as if it were saved and re-loaded, and is useful when operations (such as XPointer lookups) that depend on a particular document tree structure are to be used.In cases where the document contains CDATASections, the normalize operation alone may not be sufficient, since XPointers do not differentiate between Text nodes and CDATASection nodes.

isSupported

public boolean isSupported(String feature,
                           String version)
Tests whether the DOM implementation implements a specific feature and that feature is supported by this node.

Parameters:
feature - The name of the feature to test. This is the same name which can be passed to the method hasFeature on DOMImplementation.
version - This is the version number of the feature to test. In Level 2, version 1, this is the string "2.0". If the version is not specified, supporting any version of the feature will cause the method to return true.
Returns:
Returns true if the specified feature is supported on this node, false otherwise.
Since:
DOM Level 2

getNamespaceURI

public String getNamespaceURI()
The namespace URI of this node, or null if it is unspecified.
This is not a computed value that is the result of a namespace lookup based on an examination of the namespace declarations in scope. It is merely the namespace URI given at creation time.
For nodes of any type other than ELEMENT_NODE and ATTRIBUTE_NODE and nodes created with a DOM Level 1 method, such as createElement from the Document interface, this is always null.Per the Namespaces in XML Specification an attribute does not inherit its namespace from the element it is attached to. If an attribute is not explicitly given a namespace, it simply has no namespace.

Since:
DOM Level 2

getPrefix

public String getPrefix()
The namespace prefix of this node, or null if it is unspecified.
Note that setting this attribute, when permitted, changes the nodeName attribute, which holds the qualified name, as well as the tagName and name attributes of the Element and Attr interfaces, when applicable.
Note also that changing the prefix of an attribute that is known to have a default value, does not make a new attribute with the default value and the original prefix appear, since the namespaceURI and localName do not change.
For nodes of any type other than ELEMENT_NODE and ATTRIBUTE_NODE and nodes created with a DOM Level 1 method, such as createElement from the Document interface, this is always null.

Throws:
DOMException - INVALID_CHARACTER_ERR: Raised if the specified prefix contains an illegal character, per the XML 1.0 specification .
NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.
NAMESPACE_ERR: Raised if the specified prefix is malformed per the Namespaces in XML specification, if the namespaceURI of this node is null, if the specified prefix is "xml" and the namespaceURI of this node is different from "http://www.w3.org/XML/1998/namespace", if this node is an attribute and the specified prefix is "xmlns" and the namespaceURI of this node is different from " http://www.w3.org/2000/xmlns/", or if this node is an attribute and the qualifiedName of this node is "xmlns" .
Since:
DOM Level 2

setPrefix

public void setPrefix(String prefix)
               throws DOMException
The namespace prefix of this node, or null if it is unspecified.
Note that setting this attribute, when permitted, changes the nodeName attribute, which holds the qualified name, as well as the tagName and name attributes of the Element and Attr interfaces, when applicable.
Note also that changing the prefix of an attribute that is known to have a default value, does not make a new attribute with the default value and the original prefix appear, since the namespaceURI and localName do not change.
For nodes of any type other than ELEMENT_NODE and ATTRIBUTE_NODE and nodes created with a DOM Level 1 method, such as createElement from the Document interface, this is always null.

Throws:
DOMException - INVALID_CHARACTER_ERR: Raised if the specified prefix contains an illegal character, per the XML 1.0 specification .
NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.
NAMESPACE_ERR: Raised if the specified prefix is malformed per the Namespaces in XML specification, if the namespaceURI of this node is null, if the specified prefix is "xml" and the namespaceURI of this node is different from "http://www.w3.org/XML/1998/namespace", if this node is an attribute and the specified prefix is "xmlns" and the namespaceURI of this node is different from " http://www.w3.org/2000/xmlns/", or if this node is an attribute and the qualifiedName of this node is "xmlns" .
Since:
DOM Level 2

getLocalName

public String getLocalName()
Returns the local part of the qualified name of this node.
For nodes of any type other than ELEMENT_NODE and ATTRIBUTE_NODE and nodes created with a DOM Level 1 method, such as createElement from the Document interface, this is always null.

Since:
DOM Level 2

hasAttributes

public boolean hasAttributes()
Returns whether this node (if it is an element) has any attributes.

Returns:
true if this node has any attributes, false otherwise.
Since:
DOM Level 2
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


NodeList (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom
Interface NodeList

public interface NodeList

The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. NodeList objects in the DOM are live.

The items in the NodeList are accessible via an integral index, starting from 0.

See also the Document Object Model (DOM) Level 2 Core Specification.

Method Summary
int | getLength() The number of nodes in the list.
Node | item(int index) Returns the indexth item in the collection.

Method Detail

item

public Node item(int index)
Returns the indexth item in the collection. If index is greater than or equal to the number of nodes in the list, this returns null.

Parameters:
index - Index into the collection.
Returns:
The node at the indexth position in the NodeList, or null if that is not a valid index.

getLength

public int getLength()
The number of nodes in the list. The range of valid child node indices is 0 to length-1 inclusive.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Notation (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom
Interface Notation

All Superinterfaces:
Node
public interface Notation
extends Node

This interface represents a notation declared in the DTD. A notation either declares, by name, the format of an unparsed entity (see section 4.7 of the XML 1.0 specification ), or is used for formal declaration of processing instruction targets (see section 2.6 of the XML 1.0 specification ). The nodeName attribute inherited from Node is set to the declared name of the notation.

The DOM Level 1 does not support editing Notation nodes; they are therefore readonly.

A Notation node does not have any parent.

See also the Document Object Model (DOM) Level 2 Core Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getPublicId() The public identifier of this notation.
String | getSystemId() The system identifier of this notation.
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getPublicId

public String getPublicId()
The public identifier of this notation. If the public identifier was not specified, this is null.

getSystemId

public String getSystemId()
The system identifier of this notation. If the system identifier was not specified, this is null.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


org.w3c.dom (Common DOM API)

 org.w3c.dom
Interfaces
Attr
CDATASection
CharacterData
Comment
Document
DocumentFragment
DocumentType
DOMImplementation
Element
Entity
EntityReference
NamedNodeMap
Node
NodeList
Notation
ProcessingInstruction
Text
Exceptions
DOMException


org.w3c.dom (Common DOM API)

Common DOM API
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

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.

See:
Description

Interface Summary
Attr | The Attr interface represents an attribute in an Element object.
CDATASection | CDATA sections are used to escape blocks of text containing characters that would otherwise be regarded as markup.
CharacterData | The CharacterData interface extends Node with a set of attributes and methods for accessing character data in the DOM.
Comment | This interface inherits from CharacterData and represents the content of a comment, i.e., all the characters between the starting ' <!--' and ending '-->'.
Document | The Document interface represents the entire HTML or XML document.
DocumentFragment | DocumentFragment is a "lightweight" or "minimal" Document object.
DocumentType | Each Document has a doctype attribute whose value is either null or a DocumentType object.
DOMImplementation | The DOMImplementation interface provides a number of methods for performing operations that are independent of any particular instance of the document object model.
Element | The Element interface represents an element in an HTML or XML document.
Entity | This interface represents an entity, either parsed or unparsed, in an XML document.
EntityReference | EntityReference objects may be inserted into the structure model when an entity reference is in the source document, or when the user wishes to insert an entity reference.
NamedNodeMap | Objects implementing the NamedNodeMap interface are used to represent collections of nodes that can be accessed by name.
Node | The Node interface is the primary datatype for the entire Document Object Model.
NodeList | The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented.
Notation | This interface represents a notation declared in the DTD.
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.
Text | The Text interface inherits from CharacterData and represents the textual content (termed character data in XML) of an Element or Attr.

Exception Summary
DOMException DOM operations only raise exceptions in "exceptional" circumstances, i.e., when an operation is impossible to perform (either for logical reasons, because data is lost, or because the implementation has become unstable).

Package org.w3c.dom Description

Provides the interfaces for the Document Object Model (DOM) which is a component API of the Java API for XML Processing. The Document Object Model Level 2 Core API allows programs to dynamically access and update the content and structure of documents. See the specification for more information.

Since:
JDK1.4
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


org.w3c.dom Class Hierarchy (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Hierarchy For Package org.w3c.dom

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class java.lang.Throwable (implements java.io.Serializable)
      • class java.lang.Exception
        • class java.lang.RuntimeException
          • class org.w3c.dom.DOMException

Interface Hierarchy

  • interface org.w3c.dom.DOMImplementation
  • interface org.w3c.dom.NamedNodeMap
  • interface org.w3c.dom.Node
    • interface org.w3c.dom.Attr
    • interface org.w3c.dom.CharacterData
      • interface org.w3c.dom.Comment
      • interface org.w3c.dom.Text
        • interface org.w3c.dom.CDATASection
    • interface org.w3c.dom.Document
    • interface org.w3c.dom.DocumentFragment
    • interface org.w3c.dom.DocumentType
    • interface org.w3c.dom.Element
    • interface org.w3c.dom.Entity
    • interface org.w3c.dom.EntityReference
    • interface org.w3c.dom.Notation
    • interface org.w3c.dom.ProcessingInstruction
  • interface org.w3c.dom.NodeList
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Package org.w3c.dom (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Package
org.w3c.dom

Packages that use org.w3c.dom
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.stylesheets |

Classes in org.w3c.dom used by com.sun.java.browser.dom
Document
The Document interface represents the entire HTML or XML document.
DOMException
DOM operations only raise exceptions in "exceptional" circumstances, i.e., when an operation is impossible to perform (either for logical reasons, because data is lost, or because the implementation has become unstable).
DOMImplementation
The DOMImplementation interface provides a number of methods for performing operations that are independent of any particular instance of the document object model.

Classes in org.w3c.dom used by org.w3c.dom
Attr
The Attr interface represents an attribute in an Element object.
CDATASection
CDATA sections are used to escape blocks of text containing characters that would otherwise be regarded as markup.
CharacterData
The CharacterData interface extends Node with a set of attributes and methods for accessing character data in the DOM.
Comment
This interface inherits from CharacterData and represents the content of a comment, i.e., all the characters between the starting ' <!--' and ending '-->'.
Document
The Document interface represents the entire HTML or XML document.
DocumentFragment
DocumentFragment is a "lightweight" or "minimal" Document object.
DocumentType
Each Document has a doctype attribute whose value is either null or a DocumentType object.
DOMException
DOM operations only raise exceptions in "exceptional" circumstances, i.e., when an operation is impossible to perform (either for logical reasons, because data is lost, or because the implementation has become unstable).
DOMImplementation
The DOMImplementation interface provides a number of methods for performing operations that are independent of any particular instance of the document object model.
Element
The Element interface represents an element in an HTML or XML document.
EntityReference
EntityReference objects may be inserted into the structure model when an entity reference is in the source document, or when the user wishes to insert an entity reference.
NamedNodeMap
Objects implementing the NamedNodeMap interface are used to represent collections of nodes that can be accessed by name.
Node
The Node interface is the primary datatype for the entire Document Object Model.
NodeList
The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented.
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.
Text
The Text interface inherits from CharacterData and represents the textual content (termed character data in XML) of an Element or Attr.

Classes in org.w3c.dom used by org.w3c.dom.css
DOMException
DOM operations only raise exceptions in "exceptional" circumstances, i.e., when an operation is impossible to perform (either for logical reasons, because data is lost, or because the implementation has become unstable).
DOMImplementation
The DOMImplementation interface provides a number of methods for performing operations that are independent of any particular instance of the document object model.
Element
The Element interface represents an element in an HTML or XML document.

Classes in org.w3c.dom used by org.w3c.dom.events
DOMException
DOM operations only raise exceptions in "exceptional" circumstances, i.e., when an operation is impossible to perform (either for logical reasons, because data is lost, or because the implementation has become unstable).
Node
The Node interface is the primary datatype for the entire Document Object Model.

Classes in org.w3c.dom used by org.w3c.dom.html
Document
The Document interface represents the entire HTML or XML document.
DOMException
DOM operations only raise exceptions in "exceptional" circumstances, i.e., when an operation is impossible to perform (either for logical reasons, because data is lost, or because the implementation has become unstable).
DOMImplementation
The DOMImplementation interface provides a number of methods for performing operations that are independent of any particular instance of the document object model.
Element
The Element interface represents an element in an HTML or XML document.
Node
The Node interface is the primary datatype for the entire Document Object Model.
NodeList
The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented.

Classes in org.w3c.dom used by org.w3c.dom.stylesheets
DOMException
DOM operations only raise exceptions in "exceptional" circumstances, i.e., when an operation is impossible to perform (either for logical reasons, because data is lost, or because the implementation has become unstable).
Node
The Node interface is the primary datatype for the entire Document Object Model.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


ProcessingInstruction (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom
Interface ProcessingInstruction

All Superinterfaces:
Node
public interface ProcessingInstruction
extends Node

The ProcessingInstruction interface represents a "processing instruction", used in XML as a way to keep processor-specific information in the text of the document.

See also the Document Object Model (DOM) Level 2 Core Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getData() The content of this processing instruction.
String | getTarget() The target of this processing instruction.
void | setData(String data) The content of this processing instruction.
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getTarget

public String getTarget()
The target of this processing instruction. XML defines this as being the first token following the markup that begins the processing instruction.

getData

public String getData()
The content of this processing instruction. This is from the first non white space character after the target to the character immediately preceding the ?>.

Throws:
DOMException - NO_MODIFICATION_ALLOWED_ERR: Raised when the node is readonly.

setData

public void setData(String data)
             throws DOMException
The content of this processing instruction. This is from the first non white space character after the target to the character immediately preceding the ?>.

Throws:
DOMException - NO_MODIFICATION_ALLOWED_ERR: Raised when the node is readonly.
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Text (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom
Interface Text

All Superinterfaces:
CharacterData, Node
All Known Subinterfaces:
CDATASection
public interface Text
extends CharacterData

The Text interface inherits from CharacterData and represents the textual content (termed character data in XML) of an Element or Attr. If there is no markup inside an element's content, the text is contained in a single object implementing the Text interface that is the only child of the element. If there is markup, it is parsed into the information items (elements, comments, etc.) and Text nodes that form the list of children of the element.

When a document is first made available via the DOM, there is only one Text node for each block of text. Users may create adjacent Text nodes that represent the contents of a given element without any intervening markup, but should be aware that there is no way to represent the separations between these nodes in XML or HTML, so they will not (in general) persist between DOM editing sessions. The normalize() method on Node merges any such adjacent Text objects into a single node for each block of text.

See also the Document Object Model (DOM) Level 2 Core Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
 Text splitText(int offset)
Breaks this node into two nodes at the specified offset, keeping both in the tree as siblings.
Methods inherited from interface org.w3c.dom.CharacterData
appendData, deleteData, getData, getLength, insertData, replaceData, setData, substringData
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

splitText

public Text splitText(int offset)
               throws DOMException
Breaks this node into two nodes at the specified offset, keeping both in the tree as siblings. After being split, this node will contain all the content up to the offset point. A new node of the same type, which contains all the content at and after the offset point, is returned. If the original node had a parent node, the new node is inserted as the next sibling of the original node. When the offset is equal to the length of this node, the new node has no data.

Parameters:
offset - The 16-bit unit offset at which to split, starting from 0.
Returns:
The new node, of the same type as this node.
Throws:
DOMException - INDEX_SIZE_ERR: Raised if the specified offset is negative or greater than the number of 16-bit units in data.
NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.Attr (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.Attr

Packages that use Attr
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
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.setAttributeNode(Attr newAttr) Adds a new attribute node.
Attr | Element.removeAttributeNode(Attr oldAttr) Removes the specified attribute node.
Attr | Element.getAttributeNodeNS(String namespaceURI, String localName) Retrieves an Attr node by local name and namespace URI.
Attr | Element.setAttributeNodeNS(Attr newAttr) Adds a new attribute.

Methods in org.w3c.dom with parameters of type Attr
Attr | Element.setAttributeNode(Attr newAttr) Adds a new attribute node.
Attr | Element.removeAttributeNode(Attr oldAttr) Removes the specified attribute node.
Attr | Element.setAttributeNodeNS(Attr newAttr) Adds a new attribute.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.CDATASection (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.CDATASection

Packages that use CDATASection
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
 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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.CharacterData (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.CharacterData

Packages that use CharacterData
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
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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.Comment (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.Comment

Packages that use Comment
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
 Comment Document.createComment(String data)
Creates a Comment node given the specified string.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.Document (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.Document

Packages that use Document
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 |

Uses of Document in com.sun.java.browser.dom

Methods in com.sun.java.browser.dom that return Document
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
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
 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
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.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.DocumentFragment (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.DocumentFragment

Packages that use DocumentFragment
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 DocumentFragment in org.w3c.dom

Methods in org.w3c.dom that return DocumentFragment
 DocumentFragment Document.createDocumentFragment()
Creates an empty DocumentFragment object.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.DocumentType (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.DocumentType

Packages that use DocumentType
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
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
 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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Class org.w3c.dom.DOMException (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Class
org.w3c.dom.DOMException

Packages that use DOMException
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.stylesheets |

Uses of DOMException in com.sun.java.browser.dom

Methods in com.sun.java.browser.dom that throw DOMException
 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
void | ProcessingInstruction.setData(String data) The content of this processing instruction.
String | CharacterData.getData() The character data of the node that implements this interface.
void | CharacterData.setData(String data) The character data of the node that implements this interface.
String | CharacterData.substringData(int offset, int count) Extracts a range of data from the node.
void | CharacterData.appendData(String arg) Append the string to the end of the character data of the node.
void | CharacterData.insertData(int offset, String arg) Insert a string at the specified 16-bit unit offset.
void | CharacterData.deleteData(int offset, int count) Remove a range of 16-bit units from the 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.splitText(int offset) Breaks this node into two nodes at the specified offset, keeping both in the tree as siblings.
DocumentType | DOMImplementation.createDocumentType(String qualifiedName, String publicId, String systemId) Creates an empty DocumentType node.
Document | DOMImplementation.createDocument(String namespaceURI, String qualifiedName, DocumentType doctype) Creates a DOM Document object of the specified type with its document element.
Element | Document.createElement(String tagName) Creates an element of the type specified.
CDATASection | Document.createCDATASection(String data) Creates a CDATASection node whose value is the specified string.
ProcessingInstruction | Document.createProcessingInstruction(String target, String data) Creates a ProcessingInstruction node given the specified name and data strings.
Attr | Document.createAttribute(String name) Creates an Attr of the given name.
EntityReference | Document.createEntityReference(String name) Creates an EntityReference object.
Node | Document.importNode(Node importedNode, boolean deep) Imports a node from another document to this document.
Element | Document.createElementNS(String namespaceURI, String qualifiedName) Creates an element of the given qualified name and namespace URI.
Attr | Document.createAttributeNS(String namespaceURI, String qualifiedName) Creates an attribute of the given qualified name and namespace URI.
Node | NamedNodeMap.setNamedItem(Node arg) Adds a node using its nodeName attribute.
Node | NamedNodeMap.removeNamedItem(String name) Removes a node specified by name.
Node | NamedNodeMap.setNamedItemNS(Node arg) Adds a node using its namespaceURI and localName.
Node | NamedNodeMap.removeNamedItemNS(String namespaceURI, String localName) Removes a node specified by local name and namespace URI.
void | Attr.setValue(String value) On retrieval, the value of the attribute is returned as a string.
String | Node.getNodeValue() The value of this node, depending on its type; see the table above.
void | Node.setNodeValue(String nodeValue) The value of this node, depending on its type; see the table above.
Node | Node.insertBefore(Node newChild, Node refChild) Inserts the node newChild before the existing child node refChild.
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 | Node.removeChild(Node oldChild) Removes the child node indicated by oldChild from the list of children, and returns it.
Node | Node.appendChild(Node newChild) Adds the node newChild to the end of the list of children of this node.
void | Node.setPrefix(String prefix) The namespace prefix of this node, or null if it is unspecified.
void | Element.setAttribute(String name, String value) Adds a new attribute.
void | Element.removeAttribute(String name) Removes an attribute by name.
Attr | Element.setAttributeNode(Attr newAttr) Adds a new attribute node.
Attr | Element.removeAttributeNode(Attr oldAttr) Removes the specified attribute node.
void | Element.setAttributeNS(String namespaceURI, String qualifiedName, String value) Adds a new attribute.
void | Element.removeAttributeNS(String namespaceURI, String localName) Removes an attribute by local name and namespace URI.
Attr | Element.setAttributeNodeNS(Attr newAttr) Adds a new attribute.

Uses of DOMException in org.w3c.dom.css

Methods in org.w3c.dom.css that throw DOMException
CSSStyleSheet | DOMImplementationCSS.createCSSStyleSheet(String title, String media) Creates a new CSSStyleSheet.
void | CSSStyleRule.setSelectorText(String selectorText)
void | CSSPrimitiveValue.setFloatValue(short unitType, float floatValue) A method to set the float value with a specified unit.
float | CSSPrimitiveValue.getFloatValue(short unitType) This method is used to get a float value in a specified unit.
void | CSSPrimitiveValue.setStringValue(short stringType, String stringValue) A method to set the string value with the specified unit.
String | CSSPrimitiveValue.getStringValue() This method is used to get the string value.
Counter | CSSPrimitiveValue.getCounterValue() This method is used to get the Counter value.
Rect | CSSPrimitiveValue.getRectValue() This method is used to get the Rect value.
RGBColor | CSSPrimitiveValue.getRGBColorValue() This method is used to get the RGB color.
void | CSSPageRule.setSelectorText(String selectorText)
int | CSSMediaRule.insertRule(String rule, int index) Used to insert a new rule into the media block.
void | CSSMediaRule.deleteRule(int index) Used to delete a rule from the media block.
void | CSSValue.setCssText(String cssText)
void | CSSStyleDeclaration.setCssText(String cssText)
String | CSSStyleDeclaration.removeProperty(String propertyName) Used to remove a CSS property if it has been explicitly set within this declaration block.
void | CSSStyleDeclaration.setProperty(String propertyName, String value, String priority) Used to set a property value and priority within this declaration block.
int | CSSStyleSheet.insertRule(String rule, int index) Used to insert a new rule into the style sheet.
void | CSSStyleSheet.deleteRule(int index) Used to delete a rule from the style sheet.
void | CSSRule.setCssText(String cssText)
void | CSSCharsetRule.setEncoding(String encoding)
void | CSS2Properties.setAzimuth(String azimuth)
void | CSS2Properties.setBackground(String background)
void | CSS2Properties.setBackgroundAttachment(String backgroundAttachment)
void | CSS2Properties.setBackgroundColor(String backgroundColor)
void | CSS2Properties.setBackgroundImage(String backgroundImage)
void | CSS2Properties.setBackgroundPosition(String backgroundPosition)
void | CSS2Properties.setBackgroundRepeat(String backgroundRepeat)
void | CSS2Properties.setBorder(String border)
void | CSS2Properties.setBorderCollapse(String borderCollapse)
void | CSS2Properties.setBorderColor(String borderColor)
void | CSS2Properties.setBorderSpacing(String borderSpacing)
void | CSS2Properties.setBorderStyle(String borderStyle)
void | CSS2Properties.setBorderTop(String borderTop)
void | CSS2Properties.setBorderRight(String borderRight)
void | CSS2Properties.setBorderBottom(String borderBottom)
void | CSS2Properties.setBorderLeft(String borderLeft)
void | CSS2Properties.setBorderTopColor(String borderTopColor)
void | CSS2Properties.setBorderRightColor(String borderRightColor)
void | CSS2Properties.setBorderBottomColor(String borderBottomColor)
void | CSS2Properties.setBorderLeftColor(String borderLeftColor)
void | CSS2Properties.setBorderTopStyle(String borderTopStyle)
void | CSS2Properties.setBorderRightStyle(String borderRightStyle)
void | CSS2Properties.setBorderBottomStyle(String borderBottomStyle)
void | CSS2Properties.setBorderLeftStyle(String borderLeftStyle)
void | CSS2Properties.setBorderTopWidth(String borderTopWidth)
void | CSS2Properties.setBorderRightWidth(String borderRightWidth)
void | CSS2Properties.setBorderBottomWidth(String borderBottomWidth)
void | CSS2Properties.setBorderLeftWidth(String borderLeftWidth)
void | CSS2Properties.setBorderWidth(String borderWidth)
void | CSS2Properties.setBottom(String bottom)
void | CSS2Properties.setCaptionSide(String captionSide)
void | CSS2Properties.setClear(String clear)
void | CSS2Properties.setClip(String clip)
void | CSS2Properties.setColor(String color)
void | CSS2Properties.setContent(String content)
void | CSS2Properties.setCounterIncrement(String counterIncrement)
void | CSS2Properties.setCounterReset(String counterReset)
void | CSS2Properties.setCue(String cue)
void | CSS2Properties.setCueAfter(String cueAfter)
void | CSS2Properties.setCueBefore(String cueBefore)
void | CSS2Properties.setCursor(String cursor)
void | CSS2Properties.setDirection(String direction)
void | CSS2Properties.setDisplay(String display)
void | CSS2Properties.setElevation(String elevation)
void | CSS2Properties.setEmptyCells(String emptyCells)
void | CSS2Properties.setCssFloat(String cssFloat)
void | CSS2Properties.setFont(String font)
void | CSS2Properties.setFontFamily(String fontFamily)
void | CSS2Properties.setFontSize(String fontSize)
void | CSS2Properties.setFontSizeAdjust(String fontSizeAdjust)
void | CSS2Properties.setFontStretch(String fontStretch)
void | CSS2Properties.setFontStyle(String fontStyle)
void | CSS2Properties.setFontVariant(String fontVariant)
void | CSS2Properties.setFontWeight(String fontWeight)
void | CSS2Properties.setHeight(String height)
void | CSS2Properties.setLeft(String left)
void | CSS2Properties.setLetterSpacing(String letterSpacing)
void | CSS2Properties.setLineHeight(String lineHeight)
void | CSS2Properties.setListStyle(String listStyle)
void | CSS2Properties.setListStyleImage(String listStyleImage)
void | CSS2Properties.setListStylePosition(String listStylePosition)
void | CSS2Properties.setListStyleType(String listStyleType)
void | CSS2Properties.setMargin(String margin)
void | CSS2Properties.setMarginTop(String marginTop)
void | CSS2Properties.setMarginRight(String marginRight)
void | CSS2Properties.setMarginBottom(String marginBottom)
void | CSS2Properties.setMarginLeft(String marginLeft)
void | CSS2Properties.setMarkerOffset(String markerOffset)
void | CSS2Properties.setMarks(String marks)
void | CSS2Properties.setMaxHeight(String maxHeight)
void | CSS2Properties.setMaxWidth(String maxWidth)
void | CSS2Properties.setMinHeight(String minHeight)
void | CSS2Properties.setMinWidth(String minWidth)
void | CSS2Properties.setOrphans(String orphans)
void | CSS2Properties.setOutline(String outline)
void | CSS2Properties.setOutlineColor(String outlineColor)
void | CSS2Properties.setOutlineStyle(String outlineStyle)
void | CSS2Properties.setOutlineWidth(String outlineWidth)
void | CSS2Properties.setOverflow(String overflow)
void | CSS2Properties.setPadding(String padding)
void | CSS2Properties.setPaddingTop(String paddingTop)
void | CSS2Properties.setPaddingRight(String paddingRight)
void | CSS2Properties.setPaddingBottom(String paddingBottom)
void | CSS2Properties.setPaddingLeft(String paddingLeft)
void | CSS2Properties.setPage(String page)
void | CSS2Properties.setPageBreakAfter(String pageBreakAfter)
void | CSS2Properties.setPageBreakBefore(String pageBreakBefore)
void | CSS2Properties.setPageBreakInside(String pageBreakInside)
void | CSS2Properties.setPause(String pause)
void | CSS2Properties.setPauseAfter(String pauseAfter)
void | CSS2Properties.setPauseBefore(String pauseBefore)
void | CSS2Properties.setPitch(String pitch)
void | CSS2Properties.setPitchRange(String pitchRange)
void | CSS2Properties.setPlayDuring(String playDuring)
void | CSS2Properties.setPosition(String position)
void | CSS2Properties.setQuotes(String quotes)
void | CSS2Properties.setRichness(String richness)
void | CSS2Properties.setRight(String right)
void | CSS2Properties.setSize(String size)
void | CSS2Properties.setSpeak(String speak)
void | CSS2Properties.setSpeakHeader(String speakHeader)
void | CSS2Properties.setSpeakNumeral(String speakNumeral)
void | CSS2Properties.setSpeakPunctuation(String speakPunctuation)
void | CSS2Properties.setSpeechRate(String speechRate)
void | CSS2Properties.setStress(String stress)
void | CSS2Properties.setTableLayout(String tableLayout)
void | CSS2Properties.setTextAlign(String textAlign)
void | CSS2Properties.setTextDecoration(String textDecoration)
void | CSS2Properties.setTextIndent(String textIndent)
void | CSS2Properties.setTextShadow(String textShadow)
void | CSS2Properties.setTextTransform(String textTransform)
void | CSS2Properties.setTop(String top)
void | CSS2Properties.setUnicodeBidi(String unicodeBidi)
void | CSS2Properties.setVerticalAlign(String verticalAlign)
void | CSS2Properties.setVisibility(String visibility)
void | CSS2Properties.setVoiceFamily(String voiceFamily)
void | CSS2Properties.setVolume(String volume)
void | CSS2Properties.setWhiteSpace(String whiteSpace)
void | CSS2Properties.setWidows(String widows)
void | CSS2Properties.setWidth(String width)
void | CSS2Properties.setWordSpacing(String wordSpacing)
void | CSS2Properties.setZIndex(String zIndex)

Uses of DOMException in org.w3c.dom.events

Methods in org.w3c.dom.events that throw DOMException
 Event DocumentEvent.createEvent(String eventType)

Uses of DOMException in org.w3c.dom.html

Methods in org.w3c.dom.html that throw DOMException
HTMLElement | HTMLTableRowElement.insertCell(int index) Insert an empty TD cell into this row.
void | HTMLTableRowElement.deleteCell(int index) Delete a cell from the current row.
HTMLElement | HTMLTableSectionElement.insertRow(int index) Insert a row into this section.
void | HTMLTableSectionElement.deleteRow(int index) Delete a row from this section.
HTMLElement | HTMLTableElement.insertRow(int index) Insert a new empty row in the table.
void | HTMLTableElement.deleteRow(int index) Delete a table row.
void | HTMLSelectElement.add(HTMLElement element, HTMLElement before) Add a new element to the collection of OPTION elements for this SELECT .

Uses of DOMException in org.w3c.dom.stylesheets

Methods in org.w3c.dom.stylesheets that throw DOMException
void | MediaList.setMediaText(String mediaText)
void | MediaList.deleteMedium(String oldMedium) Deletes the medium indicated by oldMedium from the list.
void | MediaList.appendMedium(String newMedium) Adds the medium newMedium to the end of the list.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.DOMImplementation (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.DOMImplementation

Packages that use DOMImplementation
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.html |

Uses of DOMImplementation in com.sun.java.browser.dom

Methods in com.sun.java.browser.dom that return DOMImplementation
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
 DOMImplementation Document.getImplementation()
The DOMImplementation object that handles this document.

Uses of DOMImplementation in org.w3c.dom.css

Subinterfaces of DOMImplementation in org.w3c.dom.css
 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
 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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.Element (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.Element

Packages that use Element
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 |

Uses of Element in org.w3c.dom

Methods in org.w3c.dom that return Element
Element | Document.getDocumentElement() This is a convenience attribute that allows direct access to the child node that is the root element of the document.
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.getElementById(String elementId) Returns the Element whose ID is given by elementId.
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
CSSStyleDeclaration | ViewCSS.getComputedStyle(Element elt, String pseudoElt) This method is used to get the computed style as it is defined in .
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
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.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.Entity (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.EntityReference (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.EntityReference

Packages that use EntityReference
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
 EntityReference Document.createEntityReference(String name)
Creates an EntityReference object.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.NamedNodeMap (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.NamedNodeMap

Packages that use NamedNodeMap
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
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.
NamedNodeMap | Node.getAttributes() A NamedNodeMap containing the attributes of this node (if it is an Element) or null otherwise.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.Node (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.Node

Packages that use Node
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.stylesheets |

Uses of Node in org.w3c.dom

Subinterfaces of Node in org.w3c.dom
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 an entity, either parsed or unparsed, in an XML document.
interface | EntityReference EntityReference objects may be inserted into the structure model when an entity reference is in the source document, or when the user wishes to insert an entity reference.
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
Node | Document.importNode(Node importedNode, boolean deep) Imports a node from another document to this document.
Node | NamedNodeMap.getNamedItem(String name) Retrieves a node specified by name.
Node | NamedNodeMap.setNamedItem(Node arg) Adds a node using its nodeName attribute.
Node | NamedNodeMap.removeNamedItem(String name) Removes a node specified by name.
Node | NamedNodeMap.item(int index) Returns the indexth item in the map.
Node | NamedNodeMap.getNamedItemNS(String namespaceURI, String localName) Retrieves a node specified by local name and namespace URI.
Node | NamedNodeMap.setNamedItemNS(Node arg) Adds a node using its namespaceURI and localName.
Node | NamedNodeMap.removeNamedItemNS(String namespaceURI, String localName) Removes a node specified by local name and namespace URI.
Node | NodeList.item(int index) Returns the indexth item in the collection.
Node | Node.getParentNode() The parent of this node.
Node | Node.getFirstChild() The first child of this node.
Node | Node.getLastChild() The last child of this node.
Node | Node.getPreviousSibling() The node immediately preceding this node.
Node | Node.getNextSibling() The node immediately following this node.
Node | Node.insertBefore(Node newChild, Node refChild) Inserts the node newChild before the existing child node refChild.
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 | Node.removeChild(Node oldChild) Removes the child node indicated by oldChild from the list of children, and returns it.
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.

Methods in org.w3c.dom with parameters of type Node
Node | Document.importNode(Node importedNode, boolean deep) Imports a node from another document to this document.
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.
Node | Node.insertBefore(Node newChild, Node refChild) Inserts the node newChild before the existing child node refChild.
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 | Node.removeChild(Node oldChild) Removes the child node indicated by oldChild from the list of children, and returns it.
Node | Node.appendChild(Node newChild) Adds the node newChild to the end of the list of children of this node.

Uses of Node in org.w3c.dom.events

Methods in org.w3c.dom.events that return Node
 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
 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
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
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.stylesheets

Methods in org.w3c.dom.stylesheets that return Node
 Node StyleSheet.getOwnerNode()
The node that associates this style sheet with the document.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.NodeList (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.NodeList

Packages that use NodeList
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
NodeList | Document.getElementsByTagName(String tagname) Returns a NodeList of all the Elements with a given tag name in the order in which they are encountered in a preorder traversal of the Document tree.
NodeList | Document.getElementsByTagNameNS(String namespaceURI, String localName) Returns a NodeList of all the Elements with a given local name and namespace URI in the order in which they are encountered in a preorder traversal of the Document tree.
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 the order in which they are encountered in a preorder traversal of this Element tree.
NodeList | Element.getElementsByTagNameNS(String namespaceURI, String localName) Returns a NodeList of all the descendant Elements with a given local name and namespace URI in the order in which they are encountered in a preorder traversal of this Element tree.

Uses of NodeList in org.w3c.dom.html

Methods in org.w3c.dom.html that return NodeList
 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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.Notation (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.ProcessingInstruction (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.ProcessingInstruction

Packages that use ProcessingInstruction
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
 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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.Text (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.Text

Packages that use Text
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
 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
Text | Text.splitText(int offset) Breaks this node into two nodes at the specified offset, keeping both in the tree as siblings.
Text | Document.createTextNode(String data) Creates a Text node given the specified string.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Counter (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.css
Interface Counter

public interface Counter

The Counter interface is used to represent any counter or counters function value. This interface reflects the values in the underlying style property.

See also the Document Object Model (DOM) Level 2 Style Specification.

Since:
DOM Level 2

Method Summary
String | getIdentifier() This attribute is used for the identifier of the counter.
String | getListStyle() This attribute is used for the style of the list.
String | getSeparator() This attribute is used for the separator of the nested counters.

Method Detail

getIdentifier

public String getIdentifier()
This attribute is used for the identifier of the counter.

getListStyle

public String getListStyle()
This attribute is used for the style of the list.

getSeparator

public String getSeparator()
This attribute is used for the separator of the nested counters.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


CSS2Properties (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.css
Interface CSS2Properties

public interface CSS2Properties

The CSS2Properties interface represents a convenience mechanism for retrieving and setting properties within a CSSStyleDeclaration. The attributes of this interface correspond to all the properties specified in CSS2. Getting an attribute of this interface is equivalent to calling the getPropertyValue method of the CSSStyleDeclaration interface. Setting an attribute of this interface is equivalent to calling the setProperty method of the CSSStyleDeclaration interface.

A conformant implementation of the CSS module is not required to implement the CSS2Properties interface. If an implementation does implement this interface, the expectation is that language-specific methods can be used to cast from an instance of the CSSStyleDeclaration interface to the CSS2Properties interface.

If an implementation does implement this interface, it is expected to understand the specific syntax of the shorthand properties, and apply their semantics; when the margin property is set, for example, the marginTop, marginRight, marginBottom and marginLeft properties are actually being set by the underlying implementation.

When dealing with CSS "shorthand" properties, the shorthand properties should be decomposed into their component longhand properties as appropriate, and when querying for their value, the form returned should be the shortest form exactly equivalent to the declarations made in the ruleset. However, if there is no shorthand declaration that could be added to the ruleset without changing in any way the rules already declared in the ruleset (i.e., by adding longhand rules that were previously not declared in the ruleset), then the empty string should be returned for the shorthand property.

For example, querying for the font property should not return "normal normal normal 14pt/normal Arial, sans-serif", when "14pt Arial, sans-serif" suffices. (The normals are initial values, and are implied by use of the longhand property.)

If the values for all the longhand properties that compose a particular string are the initial values, then a string consisting of all the initial values should be returned (e.g. a border-width value of "medium" should be returned as such, not as "").

For some shorthand properties that take missing values from other sides, such as the margin, padding, and border-[width|style|color] properties, the minimum number of sides possible should be used; i.e., "0px 10px" will be returned instead of "0px 10px 0px 10px".

If the value of a shorthand property can not be decomposed into its component longhand properties, as is the case for the font property with a value of "menu", querying for the values of the component longhand properties should return the empty string.

See also the Document Object Model (DOM) Level 2 Style Specification.

Since:
DOM Level 2

Method Summary
String | getAzimuth() See the azimuth property definition in CSS2.
String | getBackground() See the background property definition in CSS2.
String | getBackgroundAttachment() See the background-attachment property definition in CSS2.
String | getBackgroundColor() See the background-color property definition in CSS2.
String | getBackgroundImage() See the background-image property definition in CSS2.
String | getBackgroundPosition() See the background-position property definition in CSS2.
String | getBackgroundRepeat() See the background-repeat property definition in CSS2.
String | getBorder() See the border property definition in CSS2.
String | getBorderBottom() See the border-bottom property definition in CSS2.
String | getBorderBottomColor() See the border-bottom-color property definition in CSS2.
String | getBorderBottomStyle() See the border-bottom-style property definition in CSS2.
String | getBorderBottomWidth() See the border-bottom-width property definition in CSS2.
String | getBorderCollapse() See the border-collapse property definition in CSS2.
String | getBorderColor() See the border-color property definition in CSS2.
String | getBorderLeft() See the border-left property definition in CSS2.
String | getBorderLeftColor() See the border-left-color property definition in CSS2.
String | getBorderLeftStyle() See the border-left-style property definition in CSS2.
String | getBorderLeftWidth() See the border-left-width property definition in CSS2.
String | getBorderRight() See the border-right property definition in CSS2.
String | getBorderRightColor() See the border-right-color property definition in CSS2.
String | getBorderRightStyle() See the border-right-style property definition in CSS2.
String | getBorderRightWidth() See the border-right-width property definition in CSS2.
String | getBorderSpacing() See the border-spacing property definition in CSS2.
String | getBorderStyle() See the border-style property definition in CSS2.
String | getBorderTop() See the border-top property definition in CSS2.
String | getBorderTopColor() See the border-top-color property definition in CSS2.
String | getBorderTopStyle() See the border-top-style property definition in CSS2.
String | getBorderTopWidth() See the border-top-width property definition in CSS2.
String | getBorderWidth() See the border-width property definition in CSS2.
String | getBottom() See the bottom property definition in CSS2.
String | getCaptionSide() See the caption-side property definition in CSS2.
String | getClear() See the clear property definition in CSS2.
String | getClip() See the clip property definition in CSS2.
String | getColor() See the color property definition in CSS2.
String | getContent() See the content property definition in CSS2.
String | getCounterIncrement() See the counter-increment property definition in CSS2.
String | getCounterReset() See the counter-reset property definition in CSS2.
String | getCssFloat() See the float property definition in CSS2.
String | getCue() See the cue property definition in CSS2.
String | getCueAfter() See the cue-after property definition in CSS2.
String | getCueBefore() See the cue-before property definition in CSS2.
String | getCursor() See the cursor property definition in CSS2.
String | getDirection() See the direction property definition in CSS2.
String | getDisplay() See the display property definition in CSS2.
String | getElevation() See the elevation property definition in CSS2.
String | getEmptyCells() See the empty-cells property definition in CSS2.
String | getFont() See the font property definition in CSS2.
String | getFontFamily() See the font-family property definition in CSS2.
String | getFontSize() See the font-size property definition in CSS2.
String | getFontSizeAdjust() See the font-size-adjust property definition in CSS2.
String | getFontStretch() See the font-stretch property definition in CSS2.
String | getFontStyle() See the font-style property definition in CSS2.
String | getFontVariant() See the font-variant property definition in CSS2.
String | getFontWeight() See the font-weight property definition in CSS2.
String | getHeight() See the height property definition in CSS2.
String | getLeft() See the left property definition in CSS2.
String | getLetterSpacing() See the letter-spacing property definition in CSS2.
String | getLineHeight() See the line-height property definition in CSS2.
String | getListStyle() See the list-style property definition in CSS2.
String | getListStyleImage() See the list-style-image property definition in CSS2.
String | getListStylePosition() See the list-style-position property definition in CSS2.
String | getListStyleType() See the list-style-type property definition in CSS2.
String | getMargin() See the margin property definition in CSS2.
String | getMarginBottom() See the margin-bottom property definition in CSS2.
String | getMarginLeft() See the margin-left property definition in CSS2.
String | getMarginRight() See the margin-right property definition in CSS2.
String | getMarginTop() See the margin-top property definition in CSS2.
String | getMarkerOffset() See the marker-offset property definition in CSS2.
String | getMarks() See the marks property definition in CSS2.
String | getMaxHeight() See the max-height property definition in CSS2.
String | getMaxWidth() See the max-width property definition in CSS2.
String | getMinHeight() See the min-height property definition in CSS2.
String | getMinWidth() See the min-width property definition in CSS2.
String | getOrphans() See the orphans property definition in CSS2.
String | getOutline() See the outline property definition in CSS2.
String | getOutlineColor() See the outline-color property definition in CSS2.
String | getOutlineStyle() See the outline-style property definition in CSS2.
String | getOutlineWidth() See the outline-width property definition in CSS2.
String | getOverflow() See the overflow property definition in CSS2.
String | getPadding() See the padding property definition in CSS2.
String | getPaddingBottom() See the padding-bottom property definition in CSS2.
String | getPaddingLeft() See the padding-left property definition in CSS2.
String | getPaddingRight() See the padding-right property definition in CSS2.
String | getPaddingTop() See the padding-top property definition in CSS2.
String | getPage() See the page property definition in CSS2.
String | getPageBreakAfter() See the page-break-after property definition in CSS2.
String | getPageBreakBefore() See the page-break-before property definition in CSS2.
String | getPageBreakInside() See the page-break-inside property definition in CSS2.
String | getPause() See the pause property definition in CSS2.
String | getPauseAfter() See the pause-after property definition in CSS2.
String | getPauseBefore() See the pause-before property definition in CSS2.
String | getPitch() See the pitch property definition in CSS2.
String | getPitchRange() See the pitch-range property definition in CSS2.
String | getPlayDuring() See the play-during property definition in CSS2.
String | getPosition() See the position property definition in CSS2.
String | getQuotes() See the quotes property definition in CSS2.
String | getRichness() See the richness property definition in CSS2.
String | getRight() See the right property definition in CSS2.
String | getSize() See the size property definition in CSS2.
String | getSpeak() See the speak property definition in CSS2.
String | getSpeakHeader() See the speak-header property definition in CSS2.
String | getSpeakNumeral() See the speak-numeral property definition in CSS2.
String | getSpeakPunctuation() See the speak-punctuation property definition in CSS2.
String | getSpeechRate() See the speech-rate property definition in CSS2.
String | getStress() See the stress property definition in CSS2.
String | getTableLayout() See the table-layout property definition in CSS2.
String | getTextAlign() See the text-align property definition in CSS2.
String | getTextDecoration() See the text-decoration property definition in CSS2.
String | getTextIndent() See the text-indent property definition in CSS2.
String | getTextShadow() See the text-shadow property definition in CSS2.
String | getTextTransform() See the text-transform property definition in CSS2.
String | getTop() See the top property definition in CSS2.
String | getUnicodeBidi() See the unicode-bidi property definition in CSS2.
String | getVerticalAlign() See the vertical-align property definition in CSS2.
String | getVisibility() See the visibility property definition in CSS2.
String | getVoiceFamily() See the voice-family property definition in CSS2.
String | getVolume() See the volume property definition in CSS2.
String | getWhiteSpace() See the white-space property definition in CSS2.
String | getWidows() See the widows property definition in CSS2.
String | getWidth() See the width property definition in CSS2.
String | getWordSpacing() See the word-spacing property definition in CSS2.
String | getZIndex() See the z-index property definition in CSS2.
void | setAzimuth(String azimuth)
void | setBackground(String background)
void | setBackgroundAttachment(String backgroundAttachment)
void | setBackgroundColor(String backgroundColor)
void | setBackgroundImage(String backgroundImage)
void | setBackgroundPosition(String backgroundPosition)
void | setBackgroundRepeat(String backgroundRepeat)
void | setBorder(String border)
void | setBorderBottom(String borderBottom)
void | setBorderBottomColor(String borderBottomColor)
void | setBorderBottomStyle(String borderBottomStyle)
void | setBorderBottomWidth(String borderBottomWidth)
void | setBorderCollapse(String borderCollapse)
void | setBorderColor(String borderColor)
void | setBorderLeft(String borderLeft)
void | setBorderLeftColor(String borderLeftColor)
void | setBorderLeftStyle(String borderLeftStyle)
void | setBorderLeftWidth(String borderLeftWidth)
void | setBorderRight(String borderRight)
void | setBorderRightColor(String borderRightColor)
void | setBorderRightStyle(String borderRightStyle)
void | setBorderRightWidth(String borderRightWidth)
void | setBorderSpacing(String borderSpacing)
void | setBorderStyle(String borderStyle)
void | setBorderTop(String borderTop)
void | setBorderTopColor(String borderTopColor)
void | setBorderTopStyle(String borderTopStyle)
void | setBorderTopWidth(String borderTopWidth)
void | setBorderWidth(String borderWidth)
void | setBottom(String bottom)
void | setCaptionSide(String captionSide)
void | setClear(String clear)
void | setClip(String clip)
void | setColor(String color)
void | setContent(String content)
void | setCounterIncrement(String counterIncrement)
void | setCounterReset(String counterReset)
void | setCssFloat(String cssFloat)
void | setCue(String cue)
void | setCueAfter(String cueAfter)
void | setCueBefore(String cueBefore)
void | setCursor(String cursor)
void | setDirection(String direction)
void | setDisplay(String display)
void | setElevation(String elevation)
void | setEmptyCells(String emptyCells)
void | setFont(String font)
void | setFontFamily(String fontFamily)
void | setFontSize(String fontSize)
void | setFontSizeAdjust(String fontSizeAdjust)
void | setFontStretch(String fontStretch)
void | setFontStyle(String fontStyle)
void | setFontVariant(String fontVariant)
void | setFontWeight(String fontWeight)
void | setHeight(String height)
void | setLeft(String left)
void | setLetterSpacing(String letterSpacing)
void | setLineHeight(String lineHeight)
void | setListStyle(String listStyle)
void | setListStyleImage(String listStyleImage)
void | setListStylePosition(String listStylePosition)
void | setListStyleType(String listStyleType)
void | setMargin(String margin)
void | setMarginBottom(String marginBottom)
void | setMarginLeft(String marginLeft)
void | setMarginRight(String marginRight)
void | setMarginTop(String marginTop)
void | setMarkerOffset(String markerOffset)
void | setMarks(String marks)
void | setMaxHeight(String maxHeight)
void | setMaxWidth(String maxWidth)
void | setMinHeight(String minHeight)
void | setMinWidth(String minWidth)
void | setOrphans(String orphans)
void | setOutline(String outline)
void | setOutlineColor(String outlineColor)
void | setOutlineStyle(String outlineStyle)
void | setOutlineWidth(String outlineWidth)
void | setOverflow(String overflow)
void | setPadding(String padding)
void | setPaddingBottom(String paddingBottom)
void | setPaddingLeft(String paddingLeft)
void | setPaddingRight(String paddingRight)
void | setPaddingTop(String paddingTop)
void | setPage(String page)
void | setPageBreakAfter(String pageBreakAfter)
void | setPageBreakBefore(String pageBreakBefore)
void | setPageBreakInside(String pageBreakInside)
void | setPause(String pause)
void | setPauseAfter(String pauseAfter)
void | setPauseBefore(String pauseBefore)
void | setPitch(String pitch)
void | setPitchRange(String pitchRange)
void | setPlayDuring(String playDuring)
void | setPosition(String position)
void | setQuotes(String quotes)
void | setRichness(String richness)
void | setRight(String right)
void | setSize(String size)
void | setSpeak(String speak)
void | setSpeakHeader(String speakHeader)
void | setSpeakNumeral(String speakNumeral)
void | setSpeakPunctuation(String speakPunctuation)
void | setSpeechRate(String speechRate)
void | setStress(String stress)
void | setTableLayout(String tableLayout)
void | setTextAlign(String textAlign)
void | setTextDecoration(String textDecoration)
void | setTextIndent(String textIndent)
void | setTextShadow(String textShadow)
void | setTextTransform(String textTransform)
void | setTop(String top)
void | setUnicodeBidi(String unicodeBidi)
void | setVerticalAlign(String verticalAlign)
void | setVisibility(String visibility)
void | setVoiceFamily(String voiceFamily)
void | setVolume(String volume)
void | setWhiteSpace(String whiteSpace)
void | setWidows(String widows)
void | setWidth(String width)
void | setWordSpacing(String wordSpacing)
void | setZIndex(String zIndex)

Method Detail

getAzimuth

public String getAzimuth()
See the azimuth property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setAzimuth

public void setAzimuth(String azimuth)
                throws DOMException
Throws:
DOMException

getBackground

public String getBackground()
See the background property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setBackground

public void setBackground(String background)
                   throws DOMException
Throws:
DOMException

getBackgroundAttachment

public String getBackgroundAttachment()
See the background-attachment property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setBackgroundAttachment

public void setBackgroundAttachment(String backgroundAttachment)
                             throws DOMException
Throws:
DOMException

getBackgroundColor

public String getBackgroundColor()
See the background-color property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setBackgroundColor

public void setBackgroundColor(String backgroundColor)
                        throws DOMException
Throws:
DOMException

getBackgroundImage

public String getBackgroundImage()
See the background-image property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setBackgroundImage

public void setBackgroundImage(String backgroundImage)
                        throws DOMException
Throws:
DOMException

getBackgroundPosition

public String getBackgroundPosition()
See the background-position property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setBackgroundPosition

public void setBackgroundPosition(String backgroundPosition)
                           throws DOMException
Throws:
DOMException

getBackgroundRepeat

public String getBackgroundRepeat()
See the background-repeat property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setBackgroundRepeat

public void setBackgroundRepeat(String backgroundRepeat)
                         throws DOMException
Throws:
DOMException

getBorder

public String getBorder()
See the border property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setBorder

public void setBorder(String border)
               throws DOMException
Throws:
DOMException

getBorderCollapse

public String getBorderCollapse()
See the border-collapse property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setBorderCollapse

public void setBorderCollapse(String borderCollapse)
                       throws DOMException
Throws:
DOMException

getBorderColor

public String getBorderColor()
See the border-color property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setBorderColor

public void setBorderColor(String borderColor)
                    throws DOMException
Throws:
DOMException

getBorderSpacing

public String getBorderSpacing()
See the border-spacing property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setBorderSpacing

public void setBorderSpacing(String borderSpacing)
                      throws DOMException
Throws:
DOMException

getBorderStyle

public String getBorderStyle()
See the border-style property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setBorderStyle

public void setBorderStyle(String borderStyle)
                    throws DOMException
Throws:
DOMException

getBorderTop

public String getBorderTop()
See the border-top property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setBorderTop

public void setBorderTop(String borderTop)
                  throws DOMException
Throws:
DOMException

getBorderRight

public String getBorderRight()
See the border-right property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setBorderRight

public void setBorderRight(String borderRight)
                    throws DOMException
Throws:
DOMException

getBorderBottom

public String getBorderBottom()
See the border-bottom property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setBorderBottom

public void setBorderBottom(String borderBottom)
                     throws DOMException
Throws:
DOMException

getBorderLeft

public String getBorderLeft()
See the border-left property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setBorderLeft

public void setBorderLeft(String borderLeft)
                   throws DOMException
Throws:
DOMException

getBorderTopColor

public String getBorderTopColor()
See the border-top-color property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setBorderTopColor

public void setBorderTopColor(String borderTopColor)
                       throws DOMException
Throws:
DOMException

getBorderRightColor

public String getBorderRightColor()
See the border-right-color property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setBorderRightColor

public void setBorderRightColor(String borderRightColor)
                         throws DOMException
Throws:
DOMException

getBorderBottomColor

public String getBorderBottomColor()
See the border-bottom-color property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setBorderBottomColor

public void setBorderBottomColor(String borderBottomColor)
                          throws DOMException
Throws:
DOMException

getBorderLeftColor

public String getBorderLeftColor()
See the border-left-color property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setBorderLeftColor

public void setBorderLeftColor(String borderLeftColor)
                        throws DOMException
Throws:
DOMException

getBorderTopStyle

public String getBorderTopStyle()
See the border-top-style property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setBorderTopStyle

public void setBorderTopStyle(String borderTopStyle)
                       throws DOMException
Throws:
DOMException

getBorderRightStyle

public String getBorderRightStyle()
See the border-right-style property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setBorderRightStyle

public void setBorderRightStyle(String borderRightStyle)
                         throws DOMException
Throws:
DOMException

getBorderBottomStyle

public String getBorderBottomStyle()
See the border-bottom-style property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setBorderBottomStyle

public void setBorderBottomStyle(String borderBottomStyle)
                          throws DOMException
Throws:
DOMException

getBorderLeftStyle

public String getBorderLeftStyle()
See the border-left-style property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setBorderLeftStyle

public void setBorderLeftStyle(String borderLeftStyle)
                        throws DOMException
Throws:
DOMException

getBorderTopWidth

public String getBorderTopWidth()
See the border-top-width property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setBorderTopWidth

public void setBorderTopWidth(String borderTopWidth)
                       throws DOMException
Throws:
DOMException

getBorderRightWidth

public String getBorderRightWidth()
See the border-right-width property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setBorderRightWidth

public void setBorderRightWidth(String borderRightWidth)
                         throws DOMException
Throws:
DOMException

getBorderBottomWidth

public String getBorderBottomWidth()
See the border-bottom-width property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setBorderBottomWidth

public void setBorderBottomWidth(String borderBottomWidth)
                          throws DOMException
Throws:
DOMException

getBorderLeftWidth

public String getBorderLeftWidth()
See the border-left-width property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setBorderLeftWidth

public void setBorderLeftWidth(String borderLeftWidth)
                        throws DOMException
Throws:
DOMException

getBorderWidth

public String getBorderWidth()
See the border-width property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setBorderWidth

public void setBorderWidth(String borderWidth)
                    throws DOMException
Throws:
DOMException

getBottom

public String getBottom()
See the bottom property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setBottom

public void setBottom(String bottom)
               throws DOMException
Throws:
DOMException

getCaptionSide

public String getCaptionSide()
See the caption-side property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setCaptionSide

public void setCaptionSide(String captionSide)
                    throws DOMException
Throws:
DOMException

getClear

public String getClear()
See the clear property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setClear

public void setClear(String clear)
              throws DOMException
Throws:
DOMException

getClip

public String getClip()
See the clip property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setClip

public void setClip(String clip)
             throws DOMException
Throws:
DOMException

getColor

public String getColor()
See the color property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setColor

public void setColor(String color)
              throws DOMException
Throws:
DOMException

getContent

public String getContent()
See the content property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setContent

public void setContent(String content)
                throws DOMException
Throws:
DOMException

getCounterIncrement

public String getCounterIncrement()
See the counter-increment property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setCounterIncrement

public void setCounterIncrement(String counterIncrement)
                         throws DOMException
Throws:
DOMException

getCounterReset

public String getCounterReset()
See the counter-reset property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setCounterReset

public void setCounterReset(String counterReset)
                     throws DOMException
Throws:
DOMException

getCue

public String getCue()
See the cue property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setCue

public void setCue(String cue)
            throws DOMException
Throws:
DOMException

getCueAfter

public String getCueAfter()
See the cue-after property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setCueAfter

public void setCueAfter(String cueAfter)
                 throws DOMException
Throws:
DOMException

getCueBefore

public String getCueBefore()
See the cue-before property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setCueBefore

public void setCueBefore(String cueBefore)
                  throws DOMException
Throws:
DOMException

getCursor

public String getCursor()
See the cursor property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setCursor

public void setCursor(String cursor)
               throws DOMException
Throws:
DOMException

getDirection

public String getDirection()
See the direction property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setDirection

public void setDirection(String direction)
                  throws DOMException
Throws:
DOMException

getDisplay

public String getDisplay()
See the display property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setDisplay

public void setDisplay(String display)
                throws DOMException
Throws:
DOMException

getElevation

public String getElevation()
See the elevation property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setElevation

public void setElevation(String elevation)
                  throws DOMException
Throws:
DOMException

getEmptyCells

public String getEmptyCells()
See the empty-cells property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setEmptyCells

public void setEmptyCells(String emptyCells)
                   throws DOMException
Throws:
DOMException

getCssFloat

public String getCssFloat()
See the float property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setCssFloat

public void setCssFloat(String cssFloat)
                 throws DOMException
Throws:
DOMException

getFont

public String getFont()
See the font property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setFont

public void setFont(String font)
             throws DOMException
Throws:
DOMException

getFontFamily

public String getFontFamily()
See the font-family property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setFontFamily

public void setFontFamily(String fontFamily)
                   throws DOMException
Throws:
DOMException

getFontSize

public String getFontSize()
See the font-size property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setFontSize

public void setFontSize(String fontSize)
                 throws DOMException
Throws:
DOMException

getFontSizeAdjust

public String getFontSizeAdjust()
See the font-size-adjust property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setFontSizeAdjust

public void setFontSizeAdjust(String fontSizeAdjust)
                       throws DOMException
Throws:
DOMException

getFontStretch

public String getFontStretch()
See the font-stretch property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setFontStretch

public void setFontStretch(String fontStretch)
                    throws DOMException
Throws:
DOMException

getFontStyle

public String getFontStyle()
See the font-style property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setFontStyle

public void setFontStyle(String fontStyle)
                  throws DOMException
Throws:
DOMException

getFontVariant

public String getFontVariant()
See the font-variant property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setFontVariant

public void setFontVariant(String fontVariant)
                    throws DOMException
Throws:
DOMException

getFontWeight

public String getFontWeight()
See the font-weight property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setFontWeight

public void setFontWeight(String fontWeight)
                   throws DOMException
Throws:
DOMException

getHeight

public String getHeight()
See the height property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setHeight

public void setHeight(String height)
               throws DOMException
Throws:
DOMException

getLeft

public String getLeft()
See the left property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setLeft

public void setLeft(String left)
             throws DOMException
Throws:
DOMException

getLetterSpacing

public String getLetterSpacing()
See the letter-spacing property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setLetterSpacing

public void setLetterSpacing(String letterSpacing)
                      throws DOMException
Throws:
DOMException

getLineHeight

public String getLineHeight()
See the line-height property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setLineHeight

public void setLineHeight(String lineHeight)
                   throws DOMException
Throws:
DOMException

getListStyle

public String getListStyle()
See the list-style property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setListStyle

public void setListStyle(String listStyle)
                  throws DOMException
Throws:
DOMException

getListStyleImage

public String getListStyleImage()
See the list-style-image property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setListStyleImage

public void setListStyleImage(String listStyleImage)
                       throws DOMException
Throws:
DOMException

getListStylePosition

public String getListStylePosition()
See the list-style-position property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setListStylePosition

public void setListStylePosition(String listStylePosition)
                          throws DOMException
Throws:
DOMException

getListStyleType

public String getListStyleType()
See the list-style-type property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setListStyleType

public void setListStyleType(String listStyleType)
                      throws DOMException
Throws:
DOMException

getMargin

public String getMargin()
See the margin property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setMargin

public void setMargin(String margin)
               throws DOMException
Throws:
DOMException

getMarginTop

public String getMarginTop()
See the margin-top property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setMarginTop

public void setMarginTop(String marginTop)
                  throws DOMException
Throws:
DOMException

getMarginRight

public String getMarginRight()
See the margin-right property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setMarginRight

public void setMarginRight(String marginRight)
                    throws DOMException
Throws:
DOMException

getMarginBottom

public String getMarginBottom()
See the margin-bottom property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setMarginBottom

public void setMarginBottom(String marginBottom)
                     throws DOMException
Throws:
DOMException

getMarginLeft

public String getMarginLeft()
See the margin-left property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setMarginLeft

public void setMarginLeft(String marginLeft)
                   throws DOMException
Throws:
DOMException

getMarkerOffset

public String getMarkerOffset()
See the marker-offset property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setMarkerOffset

public void setMarkerOffset(String markerOffset)
                     throws DOMException
Throws:
DOMException

getMarks

public String getMarks()
See the marks property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setMarks

public void setMarks(String marks)
              throws DOMException
Throws:
DOMException

getMaxHeight

public String getMaxHeight()
See the max-height property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setMaxHeight

public void setMaxHeight(String maxHeight)
                  throws DOMException
Throws:
DOMException

getMaxWidth

public String getMaxWidth()
See the max-width property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setMaxWidth

public void setMaxWidth(String maxWidth)
                 throws DOMException
Throws:
DOMException

getMinHeight

public String getMinHeight()
See the min-height property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setMinHeight

public void setMinHeight(String minHeight)
                  throws DOMException
Throws:
DOMException

getMinWidth

public String getMinWidth()
See the min-width property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setMinWidth

public void setMinWidth(String minWidth)
                 throws DOMException
Throws:
DOMException

getOrphans

public String getOrphans()
See the orphans property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setOrphans

public void setOrphans(String orphans)
                throws DOMException
Throws:
DOMException

getOutline

public String getOutline()
See the outline property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setOutline

public void setOutline(String outline)
                throws DOMException
Throws:
DOMException

getOutlineColor

public String getOutlineColor()
See the outline-color property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setOutlineColor

public void setOutlineColor(String outlineColor)
                     throws DOMException
Throws:
DOMException

getOutlineStyle

public String getOutlineStyle()
See the outline-style property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setOutlineStyle

public void setOutlineStyle(String outlineStyle)
                     throws DOMException
Throws:
DOMException

getOutlineWidth

public String getOutlineWidth()
See the outline-width property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setOutlineWidth

public void setOutlineWidth(String outlineWidth)
                     throws DOMException
Throws:
DOMException

getOverflow

public String getOverflow()
See the overflow property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setOverflow

public void setOverflow(String overflow)
                 throws DOMException
Throws:
DOMException

getPadding

public String getPadding()
See the padding property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setPadding

public void setPadding(String padding)
                throws DOMException
Throws:
DOMException

getPaddingTop

public String getPaddingTop()
See the padding-top property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setPaddingTop

public void setPaddingTop(String paddingTop)
                   throws DOMException
Throws:
DOMException

getPaddingRight

public String getPaddingRight()
See the padding-right property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setPaddingRight

public void setPaddingRight(String paddingRight)
                     throws DOMException
Throws:
DOMException

getPaddingBottom

public String getPaddingBottom()
See the padding-bottom property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setPaddingBottom

public void setPaddingBottom(String paddingBottom)
                      throws DOMException
Throws:
DOMException

getPaddingLeft

public String getPaddingLeft()
See the padding-left property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setPaddingLeft

public void setPaddingLeft(String paddingLeft)
                    throws DOMException
Throws:
DOMException

getPage

public String getPage()
See the page property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setPage

public void setPage(String page)
             throws DOMException
Throws:
DOMException

getPageBreakAfter

public String getPageBreakAfter()
See the page-break-after property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setPageBreakAfter

public void setPageBreakAfter(String pageBreakAfter)
                       throws DOMException
Throws:
DOMException

getPageBreakBefore

public String getPageBreakBefore()
See the page-break-before property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setPageBreakBefore

public void setPageBreakBefore(String pageBreakBefore)
                        throws DOMException
Throws:
DOMException

getPageBreakInside

public String getPageBreakInside()
See the page-break-inside property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setPageBreakInside

public void setPageBreakInside(String pageBreakInside)
                        throws DOMException
Throws:
DOMException

getPause

public String getPause()
See the pause property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setPause

public void setPause(String pause)
              throws DOMException
Throws:
DOMException

getPauseAfter

public String getPauseAfter()
See the pause-after property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setPauseAfter

public void setPauseAfter(String pauseAfter)
                   throws DOMException
Throws:
DOMException

getPauseBefore

public String getPauseBefore()
See the pause-before property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setPauseBefore

public void setPauseBefore(String pauseBefore)
                    throws DOMException
Throws:
DOMException

getPitch

public String getPitch()
See the pitch property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setPitch

public void setPitch(String pitch)
              throws DOMException
Throws:
DOMException

getPitchRange

public String getPitchRange()
See the pitch-range property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setPitchRange

public void setPitchRange(String pitchRange)
                   throws DOMException
Throws:
DOMException

getPlayDuring

public String getPlayDuring()
See the play-during property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setPlayDuring

public void setPlayDuring(String playDuring)
                   throws DOMException
Throws:
DOMException

getPosition

public String getPosition()
See the position property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setPosition

public void setPosition(String position)
                 throws DOMException
Throws:
DOMException

getQuotes

public String getQuotes()
See the quotes property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setQuotes

public void setQuotes(String quotes)
               throws DOMException
Throws:
DOMException

getRichness

public String getRichness()
See the richness property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setRichness

public void setRichness(String richness)
                 throws DOMException
Throws:
DOMException

getRight

public String getRight()
See the right property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setRight

public void setRight(String right)
              throws DOMException
Throws:
DOMException

getSize

public String getSize()
See the size property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setSize

public void setSize(String size)
             throws DOMException
Throws:
DOMException

getSpeak

public String getSpeak()
See the speak property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setSpeak

public void setSpeak(String speak)
              throws DOMException
Throws:
DOMException

getSpeakHeader

public String getSpeakHeader()
See the speak-header property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setSpeakHeader

public void setSpeakHeader(String speakHeader)
                    throws DOMException
Throws:
DOMException

getSpeakNumeral

public String getSpeakNumeral()
See the speak-numeral property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setSpeakNumeral

public void setSpeakNumeral(String speakNumeral)
                     throws DOMException
Throws:
DOMException

getSpeakPunctuation

public String getSpeakPunctuation()
See the speak-punctuation property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setSpeakPunctuation

public void setSpeakPunctuation(String speakPunctuation)
                         throws DOMException
Throws:
DOMException

getSpeechRate

public String getSpeechRate()
See the speech-rate property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setSpeechRate

public void setSpeechRate(String speechRate)
                   throws DOMException
Throws:
DOMException

getStress

public String getStress()
See the stress property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setStress

public void setStress(String stress)
               throws DOMException
Throws:
DOMException

getTableLayout

public String getTableLayout()
See the table-layout property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setTableLayout

public void setTableLayout(String tableLayout)
                    throws DOMException
Throws:
DOMException

getTextAlign

public String getTextAlign()
See the text-align property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setTextAlign

public void setTextAlign(String textAlign)
                  throws DOMException
Throws:
DOMException

getTextDecoration

public String getTextDecoration()
See the text-decoration property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setTextDecoration

public void setTextDecoration(String textDecoration)
                       throws DOMException
Throws:
DOMException

getTextIndent

public String getTextIndent()
See the text-indent property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setTextIndent

public void setTextIndent(String textIndent)
                   throws DOMException
Throws:
DOMException

getTextShadow

public String getTextShadow()
See the text-shadow property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setTextShadow

public void setTextShadow(String textShadow)
                   throws DOMException
Throws:
DOMException

getTextTransform

public String getTextTransform()
See the text-transform property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setTextTransform

public void setTextTransform(String textTransform)
                      throws DOMException
Throws:
DOMException

getTop

public String getTop()
See the top property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setTop

public void setTop(String top)
            throws DOMException
Throws:
DOMException

getUnicodeBidi

public String getUnicodeBidi()
See the unicode-bidi property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setUnicodeBidi

public void setUnicodeBidi(String unicodeBidi)
                    throws DOMException
Throws:
DOMException

getVerticalAlign

public String getVerticalAlign()
See the vertical-align property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setVerticalAlign

public void setVerticalAlign(String verticalAlign)
                      throws DOMException
Throws:
DOMException

getVisibility

public String getVisibility()
See the visibility property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setVisibility

public void setVisibility(String visibility)
                   throws DOMException
Throws:
DOMException

getVoiceFamily

public String getVoiceFamily()
See the voice-family property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setVoiceFamily

public void setVoiceFamily(String voiceFamily)
                    throws DOMException
Throws:
DOMException

getVolume

public String getVolume()
See the volume property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setVolume

public void setVolume(String volume)
               throws DOMException
Throws:
DOMException

getWhiteSpace

public String getWhiteSpace()
See the white-space property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setWhiteSpace

public void setWhiteSpace(String whiteSpace)
                   throws DOMException
Throws:
DOMException

getWidows

public String getWidows()
See the widows property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setWidows

public void setWidows(String widows)
               throws DOMException
Throws:
DOMException

getWidth

public String getWidth()
See the width property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setWidth

public void setWidth(String width)
              throws DOMException
Throws:
DOMException

getWordSpacing

public String getWordSpacing()
See the word-spacing property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setWordSpacing

public void setWordSpacing(String wordSpacing)
                    throws DOMException
Throws:
DOMException

getZIndex

public String getZIndex()
See the z-index property definition in CSS2.

Throws:
DOMException - SYNTAX_ERR: Raised if the new value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

setZIndex

public void setZIndex(String zIndex)
               throws DOMException
Throws:
DOMException
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


CSSCharsetRule (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.css
Interface CSSCharsetRule

All Superinterfaces:
CSSRule
public interface CSSCharsetRule
extends CSSRule

The CSSCharsetRule interface represents a @charset rule in a CSS style sheet. The value of the encoding attribute does not affect the encoding of text data in the DOM objects; this encoding is always UTF-16. After a stylesheet is loaded, the value of the encoding attribute is the value found in the @charset rule. If there was no @charset in the original document, then no CSSCharsetRule is created. The value of the encoding attribute may also be used as a hint for the encoding used on serialization of the style sheet.

The value of the @charset rule (and therefore of the CSSCharsetRule) may not correspond to the encoding the document actually came in; character encoding information e.g. in an HTTP header, has priority (see CSS document representation) but this is not reflected in the CSSCharsetRule.

See also the Document Object Model (DOM) Level 2 Style Specification.

Since:
DOM Level 2

Field Summary
Fields inherited from interface org.w3c.dom.css.CSSRule
CHARSET_RULE, FONT_FACE_RULE, IMPORT_RULE, MEDIA_RULE, PAGE_RULE, STYLE_RULE, UNKNOWN_RULE
Method Summary
String | getEncoding() The encoding information used in this @charset rule.
void | setEncoding(String encoding)
Methods inherited from interface org.w3c.dom.css.CSSRule
getCssText, getParentRule, getParentStyleSheet, getType, setCssText

Method Detail

getEncoding

public String getEncoding()
The encoding information used in this @charset rule.

Throws:
DOMException - SYNTAX_ERR: Raised if the specified encoding value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this encoding rule is readonly.

setEncoding

public void setEncoding(String encoding)
                 throws DOMException
Throws:
DOMException
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


CSSFontFaceRule (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.css
Interface CSSFontFaceRule

All Superinterfaces:
CSSRule
public interface CSSFontFaceRule
extends CSSRule

The CSSFontFaceRule interface represents a @font-face rule in a CSS style sheet. The @font-face rule is used to hold a set of font descriptions.

See also the Document Object Model (DOM) Level 2 Style Specification.

Since:
DOM Level 2

Field Summary
Fields inherited from interface org.w3c.dom.css.CSSRule
CHARSET_RULE, FONT_FACE_RULE, IMPORT_RULE, MEDIA_RULE, PAGE_RULE, STYLE_RULE, UNKNOWN_RULE
Method Summary
 CSSStyleDeclaration getStyle()
The declaration-block of this rule.
Methods inherited from interface org.w3c.dom.css.CSSRule
getCssText, getParentRule, getParentStyleSheet, getType, setCssText

Method Detail

getStyle

public CSSStyleDeclaration getStyle()
The declaration-block of this rule.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


CSSImportRule (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.css
Interface CSSImportRule

All Superinterfaces:
CSSRule
public interface CSSImportRule
extends CSSRule

The CSSImportRule interface represents a @import rule within a CSS style sheet. The @import rule is used to import style rules from other style sheets.

See also the Document Object Model (DOM) Level 2 Style Specification.

Since:
DOM Level 2

Field Summary
Fields inherited from interface org.w3c.dom.css.CSSRule
CHARSET_RULE, FONT_FACE_RULE, IMPORT_RULE, MEDIA_RULE, PAGE_RULE, STYLE_RULE, UNKNOWN_RULE
Method Summary
String | getHref() The location of the style sheet to be imported.
MediaList | getMedia() A list of media types for which this style sheet may be used.
CSSStyleSheet | getStyleSheet() The style sheet referred to by this rule, if it has been loaded.
Methods inherited from interface org.w3c.dom.css.CSSRule
getCssText, getParentRule, getParentStyleSheet, getType, setCssText

Method Detail

getHref

public String getHref()
The location of the style sheet to be imported. The attribute will not contain the "url(...)" specifier around the URI.

getMedia

public MediaList getMedia()
A list of media types for which this style sheet may be used.

getStyleSheet

public CSSStyleSheet getStyleSheet()
The style sheet referred to by this rule, if it has been loaded. The value of this attribute is null if the style sheet has not yet been loaded or if it will not be loaded (e.g. if the style sheet is for a media type not supported by the user agent).

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


CSSMediaRule (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.css
Interface CSSMediaRule

All Superinterfaces:
CSSRule
public interface CSSMediaRule
extends CSSRule

The CSSMediaRule interface represents a @media rule in a CSS style sheet. A @media rule can be used to delimit style rules for specific media types.

See also the Document Object Model (DOM) Level 2 Style Specification.

Since:
DOM Level 2

Field Summary
Fields inherited from interface org.w3c.dom.css.CSSRule
CHARSET_RULE, FONT_FACE_RULE, IMPORT_RULE, MEDIA_RULE, PAGE_RULE, STYLE_RULE, UNKNOWN_RULE
Method Summary
void | deleteRule(int index) Used to delete a rule from the media block.
CSSRuleList | getCssRules() A list of all CSS rules contained within the media block.
MediaList | getMedia() A list of media types for this rule.
int | insertRule(String rule, int index) Used to insert a new rule into the media block.
Methods inherited from interface org.w3c.dom.css.CSSRule
getCssText, getParentRule, getParentStyleSheet, getType, setCssText

Method Detail

getMedia

public MediaList getMedia()
A list of media types for this rule.

getCssRules

public CSSRuleList getCssRules()
A list of all CSS rules contained within the media block.

insertRule

public int insertRule(String rule,
                      int index)
               throws DOMException
Used to insert a new rule into the media block.

Parameters:
rule - The parsable text representing the rule. For rule sets this contains both the selector and the style declaration. For at-rules, this specifies both the at-identifier and the rule content.
index - The index within the media block's rule collection of the rule before which to insert the specified rule. If the specified index is equal to the length of the media blocks's rule collection, the rule will be added to the end of the media block.
Returns:
The index within the media block's rule collection of the newly inserted rule.
Throws:
DOMException - HIERARCHY_REQUEST_ERR: Raised if the rule cannot be inserted at the specified index, e.g., if an @import rule is inserted after a standard rule set or other at-rule.
INDEX_SIZE_ERR: Raised if the specified index is not a valid insertion point.
NO_MODIFICATION_ALLOWED_ERR: Raised if this media rule is readonly.
SYNTAX_ERR: Raised if the specified rule has a syntax error and is unparsable.

deleteRule

public void deleteRule(int index)
                throws DOMException
Used to delete a rule from the media block.

Parameters:
index - The index within the media block's rule collection of the rule to remove.
Throws:
DOMException - INDEX_SIZE_ERR: Raised if the specified index does not correspond to a rule in the media rule list.
NO_MODIFICATION_ALLOWED_ERR: Raised if this media rule is readonly.
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


CSSPageRule (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.css
Interface CSSPageRule

All Superinterfaces:
CSSRule
public interface CSSPageRule
extends CSSRule

The CSSPageRule interface represents a @page rule within a CSS style sheet. The @page rule is used to specify the dimensions, orientation, margins, etc. of a page box for paged media.

See also the Document Object Model (DOM) Level 2 Style Specification.

Since:
DOM Level 2

Field Summary
Fields inherited from interface org.w3c.dom.css.CSSRule
CHARSET_RULE, FONT_FACE_RULE, IMPORT_RULE, MEDIA_RULE, PAGE_RULE, STYLE_RULE, UNKNOWN_RULE
Method Summary
String | getSelectorText() The parsable textual representation of the page selector for the rule.
CSSStyleDeclaration | getStyle() The declaration-block of this rule.
void | setSelectorText(String selectorText)
Methods inherited from interface org.w3c.dom.css.CSSRule
getCssText, getParentRule, getParentStyleSheet, getType, setCssText

Method Detail

getSelectorText

public String getSelectorText()
The parsable textual representation of the page selector for the rule.

Throws:
DOMException - SYNTAX_ERR: Raised if the specified CSS string value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this rule is readonly.

setSelectorText

public void setSelectorText(String selectorText)
                     throws DOMException
Throws:
DOMException

getStyle

public CSSStyleDeclaration getStyle()
The declaration-block of this rule.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


CSSPrimitiveValue (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.css
Interface CSSPrimitiveValue

All Superinterfaces:
CSSValue
public interface CSSPrimitiveValue
extends CSSValue

The CSSPrimitiveValue interface represents a single CSS value . This interface may be used to determine the value of a specific style property currently set in a block or to set a specific style property explicitly within the block. An instance of this interface might be obtained from the getPropertyCSSValue method of the CSSStyleDeclaration interface. A CSSPrimitiveValue object only occurs in a context of a CSS property.

Conversions are allowed between absolute values (from millimeters to centimeters, from degrees to radians, and so on) but not between relative values. (For example, a pixel value cannot be converted to a centimeter value.) Percentage values can't be converted since they are relative to the parent value (or another property value). There is one exception for color percentage values: since a color percentage value is relative to the range 0-255, a color percentage value can be converted to a number; (see also the RGBColor interface).

See also the Document Object Model (DOM) Level 2 Style Specification.

Since:
DOM Level 2

Field Summary
static short | CSS_ATTR The value is a attribute function.
static short | CSS_CM The value is a length (cm).
static short | CSS_COUNTER The value is a counter or counters function.
static short | CSS_DEG The value is an angle (deg).
static short | CSS_DIMENSION The value is a number with an unknown dimension.
static short | CSS_EMS The value is a length (ems).
static short | CSS_EXS The value is a length (exs).
static short | CSS_GRAD The value is an angle (grad).
static short | CSS_HZ The value is a frequency (Hz).
static short | CSS_IDENT The value is an identifier.
static short | CSS_IN The value is a length (in).
static short | CSS_KHZ The value is a frequency (kHz).
static short | CSS_MM The value is a length (mm).
static short | CSS_MS The value is a time (ms).
static short | CSS_NUMBER The value is a simple number.
static short | CSS_PC The value is a length (pc).
static short | CSS_PERCENTAGE The value is a percentage.
static short | CSS_PT The value is a length (pt).
static short | CSS_PX The value is a length (px).
static short | CSS_RAD The value is an angle (rad).
static short | CSS_RECT The value is a rect function.
static short | CSS_RGBCOLOR The value is a RGB color.
static short | CSS_S The value is a time (s).
static short | CSS_STRING The value is a STRING.
static short | CSS_UNKNOWN The value is not a recognized CSS2 value.
static short | CSS_URI The value is a URI.
Fields inherited from interface org.w3c.dom.css.CSSValue
CSS_CUSTOM, CSS_INHERIT, CSS_PRIMITIVE_VALUE, CSS_VALUE_LIST
Method Summary
Counter | getCounterValue() This method is used to get the Counter value.
float | getFloatValue(short unitType) This method is used to get a float value in a specified unit.
short | getPrimitiveType() The type of the value as defined by the constants specified above.
Rect | getRectValue() This method is used to get the Rect value.
RGBColor | getRGBColorValue() This method is used to get the RGB color.
String | getStringValue() This method is used to get the string value.
void | setFloatValue(short unitType, float floatValue) A method to set the float value with a specified unit.
void | setStringValue(short stringType, String stringValue) A method to set the string value with the specified unit.
Methods inherited from interface org.w3c.dom.css.CSSValue
getCssText, getCssValueType, setCssText

Field Detail

CSS_UNKNOWN

public static final short CSS_UNKNOWN
The value is not a recognized CSS2 value. The value can only be obtained by using the cssText attribute.

See Also:
Constant Field Values

CSS_NUMBER

public static final short CSS_NUMBER
The value is a simple number. The value can be obtained by using the getFloatValue method.

See Also:
Constant Field Values

CSS_PERCENTAGE

public static final short CSS_PERCENTAGE
The value is a percentage. The value can be obtained by using the getFloatValue method.

See Also:
Constant Field Values

CSS_EMS

public static final short CSS_EMS
The value is a length (ems). The value can be obtained by using the getFloatValue method.

See Also:
Constant Field Values

CSS_EXS

public static final short CSS_EXS
The value is a length (exs). The value can be obtained by using the getFloatValue method.

See Also:
Constant Field Values

CSS_PX

public static final short CSS_PX
The value is a length (px). The value can be obtained by using the getFloatValue method.

See Also:
Constant Field Values

CSS_CM

public static final short CSS_CM
The value is a length (cm). The value can be obtained by using the getFloatValue method.

See Also:
Constant Field Values

CSS_MM

public static final short CSS_MM
The value is a length (mm). The value can be obtained by using the getFloatValue method.

See Also:
Constant Field Values

CSS_IN

public static final short CSS_IN
The value is a length (in). The value can be obtained by using the getFloatValue method.

See Also:
Constant Field Values

CSS_PT

public static final short CSS_PT
The value is a length (pt). The value can be obtained by using the getFloatValue method.

See Also:
Constant Field Values

CSS_PC

public static final short CSS_PC
The value is a length (pc). The value can be obtained by using the getFloatValue method.

See Also:
Constant Field Values

CSS_DEG

public static final short CSS_DEG
The value is an angle (deg). The value can be obtained by using the getFloatValue method.

See Also:
Constant Field Values

CSS_RAD

public static final short CSS_RAD
The value is an angle (rad). The value can be obtained by using the getFloatValue method.

See Also:
Constant Field Values

CSS_GRAD

public static final short CSS_GRAD
The value is an angle (grad). The value can be obtained by using the getFloatValue method.

See Also:
Constant Field Values

CSS_MS

public static final short CSS_MS
The value is a time (ms). The value can be obtained by using the getFloatValue method.

See Also:
Constant Field Values

CSS_S

public static final short CSS_S
The value is a time (s). The value can be obtained by using the getFloatValue method.

See Also:
Constant Field Values

CSS_HZ

public static final short CSS_HZ
The value is a frequency (Hz). The value can be obtained by using the getFloatValue method.

See Also:
Constant Field Values

CSS_KHZ

public static final short CSS_KHZ
The value is a frequency (kHz). The value can be obtained by using the getFloatValue method.

See Also:
Constant Field Values

CSS_DIMENSION

public static final short CSS_DIMENSION
The value is a number with an unknown dimension. The value can be obtained by using the getFloatValue method.

See Also:
Constant Field Values

CSS_STRING

public static final short CSS_STRING
The value is a STRING. The value can be obtained by using the getStringValue method.

See Also:
Constant Field Values

CSS_URI

public static final short CSS_URI
The value is a URI. The value can be obtained by using the getStringValue method.

See Also:
Constant Field Values

CSS_IDENT

public static final short CSS_IDENT
The value is an identifier. The value can be obtained by using the getStringValue method.

See Also:
Constant Field Values

CSS_ATTR

public static final short CSS_ATTR
The value is a attribute function. The value can be obtained by using the getStringValue method.

See Also:
Constant Field Values

CSS_COUNTER

public static final short CSS_COUNTER
The value is a counter or counters function. The value can be obtained by using the getCounterValue method.

See Also:
Constant Field Values

CSS_RECT

public static final short CSS_RECT
The value is a rect function. The value can be obtained by using the getRectValue method.

See Also:
Constant Field Values

CSS_RGBCOLOR

public static final short CSS_RGBCOLOR
The value is a RGB color. The value can be obtained by using the getRGBColorValue method.

See Also:
Constant Field Values
Method Detail

getPrimitiveType

public short getPrimitiveType()
The type of the value as defined by the constants specified above.

setFloatValue

public void setFloatValue(short unitType,
                          float floatValue)
                   throws DOMException
A method to set the float value with a specified unit. If the property attached with this value can not accept the specified unit or the float value, the value will be unchanged and a DOMException will be raised.

Parameters:
unitType - A unit code as defined above. The unit code can only be a float unit type (i.e. CSS_NUMBER, CSS_PERCENTAGE, CSS_EMS, CSS_EXS, CSS_PX, CSS_CM, CSS_MM, CSS_IN, CSS_PT, CSS_PC, CSS_DEG, CSS_RAD, CSS_GRAD, CSS_MS, CSS_S, CSS_HZ, CSS_KHZ, CSS_DIMENSION).
floatValue - The new float value.
Throws:
DOMException - INVALID_ACCESS_ERR: Raised if the attached property doesn't support the float value or the unit type.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

getFloatValue

public float getFloatValue(short unitType)
                    throws DOMException
This method is used to get a float value in a specified unit. If this CSS value doesn't contain a float value or can't be converted into the specified unit, a DOMException is raised.

Parameters:
unitType - A unit code to get the float value. The unit code can only be a float unit type (i.e. CSS_NUMBER, CSS_PERCENTAGE, CSS_EMS, CSS_EXS, CSS_PX, CSS_CM, CSS_MM, CSS_IN, CSS_PT, CSS_PC, CSS_DEG, CSS_RAD, CSS_GRAD, CSS_MS, CSS_S, CSS_HZ, CSS_KHZ, CSS_DIMENSION).
Returns:
The float value in the specified unit.
Throws:
DOMException - INVALID_ACCESS_ERR: Raised if the CSS value doesn't contain a float value or if the float value can't be converted into the specified unit.

setStringValue

public void setStringValue(short stringType,
                           String stringValue)
                    throws DOMException
A method to set the string value with the specified unit. If the property attached to this value can't accept the specified unit or the string value, the value will be unchanged and a DOMException will be raised.

Parameters:
stringType - A string code as defined above. The string code can only be a string unit type (i.e. CSS_STRING, CSS_URI, CSS_IDENT, and CSS_ATTR).
stringValue - The new string value.
Throws:
DOMException - INVALID_ACCESS_ERR: Raised if the CSS value doesn't contain a string value or if the string value can't be converted into the specified unit.
NO_MODIFICATION_ALLOWED_ERR: Raised if this property is readonly.

getStringValue

public String getStringValue()
                      throws DOMException
This method is used to get the string value. If the CSS value doesn't contain a string value, a DOMException is raised. Some properties (like 'font-family' or 'voice-family') convert a whitespace separated list of idents to a string.

Returns:
The string value in the current unit. The current primitiveType can only be a string unit type (i.e. CSS_STRING, CSS_URI, CSS_IDENT and CSS_ATTR).
Throws:
DOMException - INVALID_ACCESS_ERR: Raised if the CSS value doesn't contain a string value.

getCounterValue

public Counter getCounterValue()
                        throws DOMException
This method is used to get the Counter value. If this CSS value doesn't contain a counter value, a DOMException is raised. Modification to the corresponding style property can be achieved using the Counter interface.

Returns:
The Counter value.
Throws:
DOMException - INVALID_ACCESS_ERR: Raised if the CSS value doesn't contain a Counter value (e.g. this is not CSS_COUNTER).

getRectValue

public Rect getRectValue()
                  throws DOMException
This method is used to get the Rect value. If this CSS value doesn't contain a rect value, a DOMException is raised. Modification to the corresponding style property can be achieved using the Rect interface.

Returns:
The Rect value.
Throws:
DOMException - INVALID_ACCESS_ERR: Raised if the CSS value doesn't contain a Rect value. (e.g. this is not CSS_RECT).

getRGBColorValue

public RGBColor getRGBColorValue()
                          throws DOMException
This method is used to get the RGB color. If this CSS value doesn't contain a RGB color value, a DOMException is raised. Modification to the corresponding style property can be achieved using the RGBColor interface.

Returns:
the RGB color value.
Throws:
DOMException - INVALID_ACCESS_ERR: Raised if the attached property can't return a RGB color value (e.g. this is not CSS_RGBCOLOR).
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


CSSRule (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.css
Interface CSSRule

All Known Subinterfaces:
CSSCharsetRule, CSSFontFaceRule, CSSImportRule, CSSMediaRule, CSSPageRule, CSSStyleRule, CSSUnknownRule
public interface CSSRule

The CSSRule interface is the abstract base interface for any type of CSS statement. This includes both rule sets and at-rules. An implementation is expected to preserve all rules specified in a CSS style sheet, even if the rule is not recognized by the parser. Unrecognized rules are represented using the CSSUnknownRule interface.

See also the Document Object Model (DOM) Level 2 Style Specification.

Since:
DOM Level 2

Field Summary
static short | CHARSET_RULE The rule is a CSSCharsetRule.
static short | FONT_FACE_RULE The rule is a CSSFontFaceRule.
static short | IMPORT_RULE The rule is a CSSImportRule.
static short | MEDIA_RULE The rule is a CSSMediaRule.
static short | PAGE_RULE The rule is a CSSPageRule.
static short | STYLE_RULE The rule is a CSSStyleRule.
static short | UNKNOWN_RULE The rule is a CSSUnknownRule.
Method Summary
String | getCssText() The parsable textual representation of the rule.
CSSRule | getParentRule() If this rule is contained inside another rule (e.g.
CSSStyleSheet | getParentStyleSheet() The style sheet that contains this rule.
short | getType() The type of the rule, as defined above.
void | setCssText(String cssText)

Field Detail

UNKNOWN_RULE

public static final short UNKNOWN_RULE
The rule is a CSSUnknownRule.

See Also:
Constant Field Values

STYLE_RULE

public static final short STYLE_RULE
The rule is a CSSStyleRule.

See Also:
Constant Field Values

CHARSET_RULE

public static final short CHARSET_RULE
The rule is a CSSCharsetRule.

See Also:
Constant Field Values

IMPORT_RULE

public static final short IMPORT_RULE
The rule is a CSSImportRule.

See Also:
Constant Field Values

MEDIA_RULE

public static final short MEDIA_RULE
The rule is a CSSMediaRule.

See Also:
Constant Field Values

FONT_FACE_RULE

public static final short FONT_FACE_RULE
The rule is a CSSFontFaceRule.

See Also:
Constant Field Values

PAGE_RULE

public static final short PAGE_RULE
The rule is a CSSPageRule.

See Also:
Constant Field Values
Method Detail

getType

public short getType()
The type of the rule, as defined above. The expectation is that binding-specific casting methods can be used to cast down from an instance of the CSSRule interface to the specific derived interface implied by the type.

getCssText

public String getCssText()
The parsable textual representation of the rule. This reflects the current state of the rule and not its initial value.

Throws:
DOMException - SYNTAX_ERR: Raised if the specified CSS string value has a syntax error and is unparsable.
INVALID_MODIFICATION_ERR: Raised if the specified CSS string value represents a different type of rule than the current one.
HIERARCHY_REQUEST_ERR: Raised if the rule cannot be inserted at this point in the style sheet.
NO_MODIFICATION_ALLOWED_ERR: Raised if the rule is readonly.

setCssText

public void setCssText(String cssText)
                throws DOMException
Throws:
DOMException

getParentStyleSheet

public CSSStyleSheet getParentStyleSheet()
The style sheet that contains this rule.

getParentRule

public CSSRule getParentRule()
If this rule is contained inside another rule (e.g. a style rule inside an @media block), this is the containing rule. If this rule is not nested inside any other rules, this returns null.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


CSSRuleList (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.css
Interface CSSRuleList

public interface CSSRuleList

The CSSRuleList interface provides the abstraction of an ordered collection of CSS rules.

The items in the CSSRuleList are accessible via an integral index, starting from 0.

See also the Document Object Model (DOM) Level 2 Style Specification.

Since:
DOM Level 2

Method Summary
int | getLength() The number of CSSRules in the list.
CSSRule | item(int index) Used to retrieve a CSS rule by ordinal index.

Method Detail

getLength

public int getLength()
The number of CSSRules in the list. The range of valid child rule indices is 0 to length-1 inclusive.

item

public CSSRule item(int index)
Used to retrieve a CSS rule by ordinal index. The order in this collection represents the order of the rules in the CSS style sheet. If index is greater than or equal to the number of rules in the list, this returns null.

Returns:
The style rule at the index position in the CSSRuleList, or null if that is not a valid index.
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


CSSStyleDeclaration (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.css
Interface CSSStyleDeclaration

public interface CSSStyleDeclaration

The CSSStyleDeclaration interface represents a single CSS declaration block. This interface may be used to determine the style properties currently set in a block or to set style properties explicitly within the block.

While an implementation may not recognize all CSS properties within a CSS declaration block, it is expected to provide access to all specified properties in the style sheet through the CSSStyleDeclaration interface. Furthermore, implementations that support a specific level of CSS should correctly handle CSS shorthand properties for that level. For a further discussion of shorthand properties, see the CSS2Properties interface.

This interface is also used to provide a read-only access to the computed values of an element. See also the ViewCSS interface. The CSS Object Model doesn't provide an access to the specified or actual values of the CSS cascade.

See also the Document Object Model (DOM) Level 2 Style Specification.

Since:
DOM Level 2

Method Summary
String | getCssText() The parsable textual representation of the declaration block (excluding the surrounding curly braces).
int | getLength() The number of properties that have been explicitly set in this declaration block.
CSSRule | getParentRule() The CSS rule that contains this declaration block or null if this CSSStyleDeclaration is not attached to a CSSRule.
CSSValue | 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.
String | getPropertyPriority(String propertyName) Used to retrieve the priority of a CSS property (e.g.
String | getPropertyValue(String propertyName) Used to retrieve the value of a CSS property if it has been explicitly set within this declaration block.
String | item(int index) Used to retrieve the properties that have been explicitly set in this declaration block.
String | removeProperty(String propertyName) Used to remove a CSS property if it has been explicitly set within this declaration block.
void | setCssText(String cssText)
void | setProperty(String propertyName, String value, String priority) Used to set a property value and priority within this declaration block.

Method Detail

getCssText

public String getCssText()
The parsable textual representation of the declaration block (excluding the surrounding curly braces). Setting this attribute will result in the parsing of the new value and resetting of all the properties in the declaration block including the removal or addition of properties.

Throws:
DOMException - SYNTAX_ERR: Raised if the specified CSS string value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this declaration is readonly or a property is readonly.

setCssText

public void setCssText(String cssText)
                throws DOMException
Throws:
DOMException

getPropertyValue

public String getPropertyValue(String propertyName)
Used to retrieve the value of a CSS property if it has been explicitly set within this declaration block.

Parameters:
propertyName - The name of the CSS property. See the CSS property index.
Returns:
Returns the value of the property if it has been explicitly set for this declaration block. Returns the empty string if the property has not been set.

getPropertyCSSValue

public CSSValue 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. This method returns null if the property is a shorthand property. Shorthand property values can only be accessed and modified as strings, using the getPropertyValue and setProperty methods.

Parameters:
propertyName - The name of the CSS property. See the CSS property index.
Returns:
Returns the value of the property if it has been explicitly set for this declaration block. Returns null if the property has not been set.

removeProperty

public String removeProperty(String propertyName)
                      throws DOMException
Used to remove a CSS property if it has been explicitly set within this declaration block.

Parameters:
propertyName - The name of the CSS property. See the CSS property index.
Returns:
Returns the value of the property if it has been explicitly set for this declaration block. Returns the empty string if the property has not been set or the property name does not correspond to a known CSS property.
Throws:
DOMException - NO_MODIFICATION_ALLOWED_ERR: Raised if this declaration is readonly or the property is readonly.

getPropertyPriority

public String getPropertyPriority(String propertyName)
Used to retrieve the priority of a CSS property (e.g. the "important" qualifier) if the property has been explicitly set in this declaration block.

Parameters:
propertyName - The name of the CSS property. See the CSS property index.
Returns:
A string representing the priority (e.g. "important") if one exists. The empty string if none exists.

setProperty

public void setProperty(String propertyName,
                        String value,
                        String priority)
                 throws DOMException
Used to set a property value and priority within this declaration block.

Parameters:
propertyName - The name of the CSS property. See the CSS property index.
value - The new value of the property.
priority - The new priority of the property (e.g. "important").
Throws:
DOMException - SYNTAX_ERR: Raised if the specified value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this declaration is readonly or the property is readonly.

getLength

public int getLength()
The number of properties that have been explicitly set in this declaration block. The range of valid indices is 0 to length-1 inclusive.

item

public String item(int index)
Used to retrieve the properties that have been explicitly set in this declaration block. The order of the properties retrieved using this method does not have to be the order in which they were set. This method can be used to iterate over all properties in this declaration block.

Parameters:
index - Index of the property name to retrieve.
Returns:
The name of the property at this ordinal position. The empty string if no property exists at this position.

getParentRule

public CSSRule getParentRule()
The CSS rule that contains this declaration block or null if this CSSStyleDeclaration is not attached to a CSSRule.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


CSSStyleRule (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.css
Interface CSSStyleRule

All Superinterfaces:
CSSRule
public interface CSSStyleRule
extends CSSRule

The CSSStyleRule interface represents a single rule set in a CSS style sheet.

See also the Document Object Model (DOM) Level 2 Style Specification.

Since:
DOM Level 2

Field Summary
Fields inherited from interface org.w3c.dom.css.CSSRule
CHARSET_RULE, FONT_FACE_RULE, IMPORT_RULE, MEDIA_RULE, PAGE_RULE, STYLE_RULE, UNKNOWN_RULE
Method Summary
String | getSelectorText() The textual representation of the selector for the rule set.
CSSStyleDeclaration | getStyle() The declaration-block of this rule set.
void | setSelectorText(String selectorText)
Methods inherited from interface org.w3c.dom.css.CSSRule
getCssText, getParentRule, getParentStyleSheet, getType, setCssText

Method Detail

getSelectorText

public String getSelectorText()
The textual representation of the selector for the rule set. The implementation may have stripped out insignificant whitespace while parsing the selector.

Throws:
DOMException - SYNTAX_ERR: Raised if the specified CSS string value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this rule is readonly.

setSelectorText

public void setSelectorText(String selectorText)
                     throws DOMException
Throws:
DOMException

getStyle

public CSSStyleDeclaration getStyle()
The declaration-block of this rule set.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


CSSStyleSheet (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.css
Interface CSSStyleSheet

All Superinterfaces:
StyleSheet
public interface CSSStyleSheet
extends StyleSheet

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".

See also the Document Object Model (DOM) Level 2 Style Specification.

Since:
DOM Level 2

Method Summary
void | deleteRule(int index) Used to delete a rule from the style sheet.
CSSRuleList | getCssRules() The list of all CSS rules contained within the style sheet.
CSSRule | getOwnerRule() If this style sheet comes from an @import rule, the ownerRule attribute will contain the CSSImportRule.
int | insertRule(String rule, int index) Used to insert a new rule into the style sheet.
Methods inherited from interface org.w3c.dom.stylesheets.StyleSheet
getDisabled, getHref, getMedia, getOwnerNode, getParentStyleSheet, getTitle, getType, setDisabled

Method Detail

getOwnerRule

public CSSRule getOwnerRule()
If this style sheet comes from an @import rule, the ownerRule attribute will contain the CSSImportRule. In that case, the ownerNode attribute in the StyleSheet interface will be null. If the style sheet comes from an element or a processing instruction, the ownerRule attribute will be null and the ownerNode attribute will contain the Node.

getCssRules

public CSSRuleList getCssRules()
The list of all CSS rules contained within the style sheet. This includes both rule sets and at-rules.

insertRule

public int insertRule(String rule,
                      int index)
               throws DOMException
Used to insert a new rule into the style sheet. The new rule now becomes part of the cascade.

Parameters:
rule - The parsable text representing the rule. For rule sets this contains both the selector and the style declaration. For at-rules, this specifies both the at-identifier and the rule content.
index - The index within the style sheet's rule list of the rule before which to insert the specified rule. If the specified index is equal to the length of the style sheet's rule collection, the rule will be added to the end of the style sheet.
Returns:
The index within the style sheet's rule collection of the newly inserted rule.
Throws:
DOMException - HIERARCHY_REQUEST_ERR: Raised if the rule cannot be inserted at the specified index e.g. if an @import rule is inserted after a standard rule set or other at-rule.
INDEX_SIZE_ERR: Raised if the specified index is not a valid insertion point.
NO_MODIFICATION_ALLOWED_ERR: Raised if this style sheet is readonly.
SYNTAX_ERR: Raised if the specified rule has a syntax error and is unparsable.

deleteRule

public void deleteRule(int index)
                throws DOMException
Used to delete a rule from the style sheet.

Parameters:
index - The index within the style sheet's rule list of the rule to remove.
Throws:
DOMException - INDEX_SIZE_ERR: Raised if the specified index does not correspond to a rule in the style sheet's rule list.
NO_MODIFICATION_ALLOWED_ERR: Raised if this style sheet is readonly.
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


CSSUnknownRule (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.css
Interface CSSUnknownRule

All Superinterfaces:
CSSRule
public interface CSSUnknownRule
extends CSSRule

The CSSUnknownRule interface represents an at-rule not supported by this user agent.

See also the Document Object Model (DOM) Level 2 Style Specification.

Since:
DOM Level 2

Field Summary
Fields inherited from interface org.w3c.dom.css.CSSRule
CHARSET_RULE, FONT_FACE_RULE, IMPORT_RULE, MEDIA_RULE, PAGE_RULE, STYLE_RULE, UNKNOWN_RULE
Methods inherited from interface org.w3c.dom.css.CSSRule
getCssText, getParentRule, getParentStyleSheet, getType, setCssText

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


CSSValue (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.css
Interface CSSValue

All Known Subinterfaces:
CSSPrimitiveValue, CSSValueList
public interface CSSValue

The CSSValue interface represents a simple or a complex value. A CSSValue object only occurs in a context of a CSS property.

See also the Document Object Model (DOM) Level 2 Style Specification.

Since:
DOM Level 2

Field Summary
static short | CSS_CUSTOM The value is a custom value.
static short | CSS_INHERIT The value is inherited and the cssText contains "inherit".
static short | CSS_PRIMITIVE_VALUE The value is a primitive value and an instance of the CSSPrimitiveValue interface can be obtained by using binding-specific casting methods on this instance of the CSSValue interface.
static short | CSS_VALUE_LIST The value is a CSSValue list and an instance of the CSSValueList interface can be obtained by using binding-specific casting methods on this instance of the CSSValue interface.
Method Summary
String | getCssText() A string representation of the current value.
short | getCssValueType() A code defining the type of the value as defined above.
void | setCssText(String cssText)

Field Detail

CSS_INHERIT

public static final short CSS_INHERIT
The value is inherited and the cssText contains "inherit".

See Also:
Constant Field Values

CSS_PRIMITIVE_VALUE

public static final short CSS_PRIMITIVE_VALUE
The value is a primitive value and an instance of the CSSPrimitiveValue interface can be obtained by using binding-specific casting methods on this instance of the CSSValue interface.

See Also:
Constant Field Values

CSS_VALUE_LIST

public static final short CSS_VALUE_LIST
The value is a CSSValue list and an instance of the CSSValueList interface can be obtained by using binding-specific casting methods on this instance of the CSSValue interface.

See Also:
Constant Field Values

CSS_CUSTOM

public static final short CSS_CUSTOM
The value is a custom value.

See Also:
Constant Field Values
Method Detail

getCssText

public String getCssText()
A string representation of the current value.

Throws:
DOMException - SYNTAX_ERR: Raised if the specified CSS string value has a syntax error (according to the attached property) or is unparsable.
INVALID_MODIFICATION_ERR: Raised if the specified CSS string value represents a different type of values than the values allowed by the CSS property.
NO_MODIFICATION_ALLOWED_ERR: Raised if this value is readonly.

setCssText

public void setCssText(String cssText)
                throws DOMException
Throws:
DOMException

getCssValueType

public short getCssValueType()
A code defining the type of the value as defined above.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


CSSValueList (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.css
Interface CSSValueList

All Superinterfaces:
CSSValue
public interface CSSValueList
extends CSSValue

The CSSValueList interface provides the abstraction of an ordered collection of CSS values.

Some properties allow an empty list into their syntax. In that case, these properties take the none identifier. So, an empty list means that the property has the value none.

The items in the CSSValueList are accessible via an integral index, starting from 0.

See also the Document Object Model (DOM) Level 2 Style Specification.

Since:
DOM Level 2

Field Summary
Fields inherited from interface org.w3c.dom.css.CSSValue
CSS_CUSTOM, CSS_INHERIT, CSS_PRIMITIVE_VALUE, CSS_VALUE_LIST
Method Summary
int | getLength() The number of CSSValues in the list.
CSSValue | item(int index) Used to retrieve a CSSValue by ordinal index.
Methods inherited from interface org.w3c.dom.css.CSSValue
getCssText, getCssValueType, setCssText

Method Detail

getLength

public int getLength()
The number of CSSValues in the list. The range of valid values of the indices is 0 to length-1 inclusive.

item

public CSSValue item(int index)
Used to retrieve a CSSValue by ordinal index. The order in this collection represents the order of the values in the CSS style property. If index is greater than or equal to the number of values in the list, this returns null.

Returns:
The CSSValue at the index position in the CSSValueList, or null if that is not a valid index.
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


DocumentCSS (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.css
Interface DocumentCSS

All Superinterfaces:
DocumentStyle
public interface DocumentCSS
extends DocumentStyle

This interface represents a document with a CSS view.

The getOverrideStyle method provides a mechanism through which a DOM author could effect immediate change to the style of an element without modifying the explicitly linked style sheets of a document or the inline style of elements in the style sheets. This style sheet comes after the author style sheet in the cascade algorithm and is called override style sheet. The override style sheet takes precedence over author style sheets. An "!important" declaration still takes precedence over a normal declaration. Override, author, and user style sheets all may contain "!important" declarations. User "!important" rules take precedence over both override and author "!important" rules, and override "!important" rules take precedence over author "!important" rules.

The expectation is that an instance of the DocumentCSS interface can be obtained by using binding-specific casting methods on an instance of the Document interface.

See also the Document Object Model (DOM) Level 2 Style Specification.

Since:
DOM Level 2

Method Summary
 CSSStyleDeclaration getOverrideStyle(Element elt, String pseudoElt)
This method is used to retrieve the override style declaration for a specified element and a specified pseudo-element.
Methods inherited from interface org.w3c.dom.stylesheets.DocumentStyle
getStyleSheets

Method Detail

getOverrideStyle

public CSSStyleDeclaration getOverrideStyle(Element elt,
                                            String pseudoElt)
This method is used to retrieve the override style declaration for a specified element and a specified pseudo-element.

Parameters:
elt - The element whose style is to be modified. This parameter cannot be null.
pseudoElt - The pseudo-element or null if none.
Returns:
The override style declaration.
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


DOMImplementationCSS (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.css
Interface DOMImplementationCSS

All Superinterfaces:
DOMImplementation
public interface DOMImplementationCSS
extends DOMImplementation

This interface allows the DOM user to create a CSSStyleSheet outside the context of a document. There is no way to associate the new CSSStyleSheet with a document in DOM Level 2.

See also the Document Object Model (DOM) Level 2 Style Specification.

Since:
DOM Level 2

Method Summary
 CSSStyleSheet createCSSStyleSheet(String title, String media)
Creates a new CSSStyleSheet.
Methods inherited from interface org.w3c.dom.DOMImplementation
createDocument, createDocumentType, hasFeature

Method Detail

createCSSStyleSheet

public CSSStyleSheet createCSSStyleSheet(String title,
                                         String media)
                                  throws DOMException
Creates a new CSSStyleSheet.

Parameters:
title - The advisory title. See also the section.
media - The comma-separated list of media associated with the new style sheet. See also the section.
Returns:
A new CSS style sheet.
Throws:
DOMException - SYNTAX_ERR: Raised if the specified media string value has a syntax error and is unparsable.
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


ElementCSSInlineStyle (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.css
Interface ElementCSSInlineStyle

public interface ElementCSSInlineStyle

Inline style information attached to elements is exposed through the style attribute. This represents the contents of the STYLE attribute for HTML elements (or elements in other schemas or DTDs which use the STYLE attribute in the same way). The expectation is that an instance of the ElementCSSInlineStyle interface can be obtained by using binding-specific casting methods on an instance of the Element interface when the element supports inline CSS style informations.

See also the Document Object Model (DOM) Level 2 Style Specification.

Since:
DOM Level 2

Method Summary
 CSSStyleDeclaration getStyle()
The style attribute.

Method Detail

getStyle

public CSSStyleDeclaration getStyle()
The style attribute.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


org.w3c.dom.css (Common DOM API)

 org.w3c.dom.css
Interfaces
Counter
CSS2Properties
CSSCharsetRule
CSSFontFaceRule
CSSImportRule
CSSMediaRule
CSSPageRule
CSSPrimitiveValue
CSSRule
CSSRuleList
CSSStyleDeclaration
CSSStyleRule
CSSStyleSheet
CSSUnknownRule
CSSValue
CSSValueList
DocumentCSS
DOMImplementationCSS
ElementCSSInlineStyle
Rect
RGBColor
ViewCSS


org.w3c.dom.css (Common DOM API)

Common DOM API
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package org.w3c.dom.css

Interface Summary
Counter | The Counter interface is used to represent any counter or counters function value.
CSS2Properties | The CSS2Properties interface represents a convenience mechanism for retrieving and setting properties within a CSSStyleDeclaration.
CSSCharsetRule | The CSSCharsetRule interface represents a @charset rule in a CSS style sheet.
CSSFontFaceRule | The CSSFontFaceRule interface represents a @font-face rule in a CSS style sheet.
CSSImportRule | The CSSImportRule interface represents a @import rule within a CSS style sheet.
CSSMediaRule | The CSSMediaRule interface represents a @media rule in a CSS style sheet.
CSSPageRule | The CSSPageRule interface represents a @page rule within a CSS style sheet.
CSSPrimitiveValue | The CSSPrimitiveValue interface represents a single CSS value .
CSSRule | The CSSRule interface is the abstract base interface for any type of CSS statement.
CSSRuleList | The CSSRuleList interface provides the abstraction of an ordered collection of CSS rules.
CSSStyleDeclaration | The CSSStyleDeclaration interface represents a single CSS declaration block.
CSSStyleRule | The CSSStyleRule interface represents a single rule set in a CSS style sheet.
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".
CSSUnknownRule | The CSSUnknownRule interface represents an at-rule not supported by this user agent.
CSSValue | The CSSValue interface represents a simple or a complex value.
CSSValueList | The CSSValueList interface provides the abstraction of an ordered collection of CSS values.
DocumentCSS | This interface represents a document with a CSS view.
DOMImplementationCSS | This interface allows the DOM user to create a CSSStyleSheet outside the context of a document.
ElementCSSInlineStyle | Inline style information attached to elements is exposed through the style attribute.
Rect | The Rect interface is used to represent any rect value.
RGBColor | The RGBColor interface is used to represent any RGB color value.
ViewCSS | This interface represents a CSS view.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


org.w3c.dom.css Class Hierarchy (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Hierarchy For Package org.w3c.dom.css

Package Hierarchies:
All Packages

Interface Hierarchy

  • interface org.w3c.dom.views.AbstractView
    • interface org.w3c.dom.css.ViewCSS
  • interface org.w3c.dom.css.Counter
  • interface org.w3c.dom.css.CSS2Properties
  • interface org.w3c.dom.css.CSSRule
    • interface org.w3c.dom.css.CSSCharsetRule
    • interface org.w3c.dom.css.CSSFontFaceRule
    • interface org.w3c.dom.css.CSSImportRule
    • interface org.w3c.dom.css.CSSMediaRule
    • interface org.w3c.dom.css.CSSPageRule
    • interface org.w3c.dom.css.CSSStyleRule
    • interface org.w3c.dom.css.CSSUnknownRule
  • interface org.w3c.dom.css.CSSRuleList
  • interface org.w3c.dom.css.CSSStyleDeclaration
  • interface org.w3c.dom.css.CSSValue
    • interface org.w3c.dom.css.CSSPrimitiveValue
    • interface org.w3c.dom.css.CSSValueList
  • interface org.w3c.dom.stylesheets.DocumentStyle
    • interface org.w3c.dom.css.DocumentCSS
  • interface org.w3c.dom.DOMImplementation
    • interface org.w3c.dom.css.DOMImplementationCSS
  • interface org.w3c.dom.css.ElementCSSInlineStyle
  • interface org.w3c.dom.css.Rect
  • interface org.w3c.dom.css.RGBColor
  • interface org.w3c.dom.stylesheets.StyleSheet
    • interface org.w3c.dom.css.CSSStyleSheet
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Package org.w3c.dom.css (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Package
org.w3c.dom.css

Packages that use org.w3c.dom.css
org.w3c.dom.css

Classes in org.w3c.dom.css used by org.w3c.dom.css
Counter
The Counter interface is used to represent any counter or counters function value.
CSSPrimitiveValue
The CSSPrimitiveValue interface represents a single CSS value .
CSSRule
The CSSRule interface is the abstract base interface for any type of CSS statement.
CSSRuleList
The CSSRuleList interface provides the abstraction of an ordered collection of CSS rules.
CSSStyleDeclaration
The CSSStyleDeclaration interface represents a single CSS declaration block.
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".
CSSValue
The CSSValue interface represents a simple or a complex value.
Rect
The Rect interface is used to represent any rect value.
RGBColor
The RGBColor interface is used to represent any RGB color value.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Rect (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.css
Interface Rect

public interface Rect

The Rect interface is used to represent any rect value. This interface reflects the values in the underlying style property. Hence, modifications made to the CSSPrimitiveValue objects modify the style property.

See also the Document Object Model (DOM) Level 2 Style Specification.

Since:
DOM Level 2

Method Summary
CSSPrimitiveValue | getBottom() This attribute is used for the bottom of the rect.
CSSPrimitiveValue | getLeft() This attribute is used for the left of the rect.
CSSPrimitiveValue | getRight() This attribute is used for the right of the rect.
CSSPrimitiveValue | getTop() This attribute is used for the top of the rect.

Method Detail

getTop

public CSSPrimitiveValue getTop()
This attribute is used for the top of the rect.

getRight

public CSSPrimitiveValue getRight()
This attribute is used for the right of the rect.

getBottom

public CSSPrimitiveValue getBottom()
This attribute is used for the bottom of the rect.

getLeft

public CSSPrimitiveValue getLeft()
This attribute is used for the left of the rect.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


RGBColor (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.css
Interface RGBColor

public interface RGBColor

The RGBColor interface is used to represent any RGB color value. This interface reflects the values in the underlying style property. Hence, modifications made to the CSSPrimitiveValue objects modify the style property.

A specified RGB color is not clipped (even if the number is outside the range 0-255 or 0%-100%). A computed RGB color is clipped depending on the device.

Even if a style sheet can only contain an integer for a color value, the internal storage of this integer is a float, and this can be used as a float in the specified or the computed style.

A color percentage value can always be converted to a number and vice versa.

See also the Document Object Model (DOM) Level 2 Style Specification.

Since:
DOM Level 2

Method Summary
CSSPrimitiveValue | getBlue() This attribute is used for the blue value of the RGB color.
CSSPrimitiveValue | getGreen() This attribute is used for the green value of the RGB color.
CSSPrimitiveValue | getRed() This attribute is used for the red value of the RGB color.

Method Detail

getRed

public CSSPrimitiveValue getRed()
This attribute is used for the red value of the RGB color.

getGreen

public CSSPrimitiveValue getGreen()
This attribute is used for the green value of the RGB color.

getBlue

public CSSPrimitiveValue getBlue()
This attribute is used for the blue value of the RGB color.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


ViewCSS (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.css
Interface ViewCSS

All Superinterfaces:
AbstractView
public interface ViewCSS
extends AbstractView

This interface represents a CSS view. The getComputedStyle method provides a read only access to the computed values of an element.

The expectation is that an instance of the ViewCSS interface can be obtained by using binding-specific casting methods on an instance of the AbstractView interface.

Since a computed style is related to an Element node, if this element is removed from the document, the associated CSSStyleDeclaration and CSSValue related to this declaration are no longer valid.

See also the Document Object Model (DOM) Level 2 Style Specification.

Since:
DOM Level 2

Method Summary
 CSSStyleDeclaration getComputedStyle(Element elt, String pseudoElt)
This method is used to get the computed style as it is defined in .
Methods inherited from interface org.w3c.dom.views.AbstractView
getDocument

Method Detail

getComputedStyle

public CSSStyleDeclaration getComputedStyle(Element elt,
                                            String pseudoElt)
This method is used to get the computed style as it is defined in .

Parameters:
elt - The element whose style is to be computed. This parameter cannot be null.
pseudoElt - The pseudo-element or null if none.
Returns:
The computed style. The CSSStyleDeclaration is read-only and contains only absolute values.
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.css.Counter (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.css.Counter

Packages that use Counter
org.w3c.dom.css

Uses of Counter in org.w3c.dom.css

Methods in org.w3c.dom.css that return Counter
 Counter CSSPrimitiveValue.getCounterValue()
This method is used to get the Counter value.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.css.CSS2Properties (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.css.CSSCharsetRule (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.css.CSSFontFaceRule (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.css.CSSImportRule (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.css.CSSMediaRule (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.css.CSSPageRule (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.css.CSSPrimitiveValue (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.css.CSSPrimitiveValue

Packages that use CSSPrimitiveValue
org.w3c.dom.css

Uses of CSSPrimitiveValue in org.w3c.dom.css

Methods in org.w3c.dom.css that return CSSPrimitiveValue
CSSPrimitiveValue | RGBColor.getRed() This attribute is used for the red value of the RGB color.
CSSPrimitiveValue | RGBColor.getGreen() This attribute is used for the green value of the RGB color.
CSSPrimitiveValue | RGBColor.getBlue() This attribute is used for the blue value of the RGB color.
CSSPrimitiveValue | Rect.getTop() This attribute is used for the top of the rect.
CSSPrimitiveValue | Rect.getRight() This attribute is used for the right of the rect.
CSSPrimitiveValue | Rect.getBottom() This attribute is used for the bottom of the rect.
CSSPrimitiveValue | Rect.getLeft() This attribute is used for the left of the rect.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.css.CSSRule (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.css.CSSRule

Packages that use CSSRule
org.w3c.dom.css

Uses of CSSRule in org.w3c.dom.css

Subinterfaces of CSSRule in org.w3c.dom.css
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
CSSRule | CSSStyleDeclaration.getParentRule() The CSS rule that contains this declaration block or null if this CSSStyleDeclaration is not attached to a CSSRule.
CSSRule | CSSRuleList.item(int index) Used to retrieve a CSS rule by ordinal index.
CSSRule | CSSStyleSheet.getOwnerRule() If this style sheet comes from an @import rule, the ownerRule attribute will contain the CSSImportRule.
CSSRule | CSSRule.getParentRule() If this rule is contained inside another rule (e.g.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.css.CSSRuleList (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.css.CSSRuleList

Packages that use CSSRuleList
org.w3c.dom.css

Uses of CSSRuleList in org.w3c.dom.css

Methods in org.w3c.dom.css that return CSSRuleList
CSSRuleList | CSSMediaRule.getCssRules() A list of all CSS rules contained within the media block.
CSSRuleList | CSSStyleSheet.getCssRules() The list of all CSS rules contained within the style sheet.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.css.CSSStyleDeclaration (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.css.CSSStyleDeclaration

Packages that use CSSStyleDeclaration
org.w3c.dom.css

Uses of CSSStyleDeclaration in org.w3c.dom.css

Methods in org.w3c.dom.css that return CSSStyleDeclaration
CSSStyleDeclaration | ViewCSS.getComputedStyle(Element elt, String pseudoElt) This method is used to get the computed style as it is defined in .
CSSStyleDeclaration | ElementCSSInlineStyle.getStyle() The style attribute.
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 | 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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.css.CSSStyleRule (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.css.CSSStyleSheet (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.css.CSSStyleSheet

Packages that use CSSStyleSheet
org.w3c.dom.css

Uses of CSSStyleSheet in org.w3c.dom.css

Methods in org.w3c.dom.css that return CSSStyleSheet
CSSStyleSheet | DOMImplementationCSS.createCSSStyleSheet(String title, String media) Creates a new CSSStyleSheet.
CSSStyleSheet | CSSImportRule.getStyleSheet() The style sheet referred to by this rule, if it has been loaded.
CSSStyleSheet | CSSRule.getParentStyleSheet() The style sheet that contains this rule.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.css.CSSUnknownRule (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.css.CSSValue (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.css.CSSValue

Packages that use CSSValue
org.w3c.dom.css

Uses of CSSValue in org.w3c.dom.css

Subinterfaces of CSSValue in org.w3c.dom.css
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
CSSValue | CSSValueList.item(int index) Used to retrieve a CSSValue by ordinal index.
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.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.css.CSSValueList (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.css.DocumentCSS (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.css.DOMImplementationCSS (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.css.ElementCSSInlineStyle (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.css.Rect (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.css.Rect

Packages that use Rect
org.w3c.dom.css

Uses of Rect in org.w3c.dom.css

Methods in org.w3c.dom.css that return Rect
 Rect CSSPrimitiveValue.getRectValue()
This method is used to get the Rect value.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.css.RGBColor (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.css.RGBColor

Packages that use RGBColor
org.w3c.dom.css

Uses of RGBColor in org.w3c.dom.css

Methods in org.w3c.dom.css that return RGBColor
 RGBColor CSSPrimitiveValue.getRGBColorValue()
This method is used to get the RGB color.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.css.ViewCSS (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


DocumentEvent (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.events
Interface DocumentEvent

public interface DocumentEvent

The DocumentEvent interface provides a mechanism by which the user can create an Event of a type supported by the implementation. It is expected that the DocumentEvent interface will be implemented on the same object which implements the Document interface in an implementation which supports the Event model.

See also the Document Object Model (DOM) Level 2 Events Specification.

Since:
DOM Level 2

Method Summary
 Event createEvent(String eventType)

Method Detail

createEvent

public Event createEvent(String eventType)
                  throws DOMException
Returns:
The newly created Event
Throws:
DOMException - NOT_SUPPORTED_ERR: Raised if the implementation does not support the type of Event interface requested
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Event (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.events
Interface Event

All Known Subinterfaces:
MouseEvent, MutationEvent, UIEvent
public interface Event

The Event interface is used to provide contextual information about an event to the handler processing the event. An object which implements the Event interface is generally passed as the first parameter to an event handler. More specific context information is passed to event handlers by deriving additional interfaces from Event which contain information directly relating to the type of event they accompany. These derived interfaces are also implemented by the object passed to the event listener.

See also the Document Object Model (DOM) Level 2 Events Specification.

Since:
DOM Level 2

Field Summary
static short | AT_TARGET The event is currently being evaluated at the target EventTarget.
static short | BUBBLING_PHASE The current event phase is the bubbling phase.
static short | CAPTURING_PHASE The current event phase is the capturing phase.
Method Summary
boolean | getBubbles() Used to indicate whether or not an event is a bubbling event.
boolean | getCancelable() Used to indicate whether or not an event can have its default action prevented.
EventTarget | getCurrentTarget() Used to indicate the EventTarget whose EventListeners are currently being processed.
short | getEventPhase() Used to indicate which phase of event flow is currently being evaluated.
EventTarget | getTarget() Used to indicate the EventTarget to which the event was originally dispatched.
long | getTimeStamp() Used to specify the time (in milliseconds relative to the epoch) at which the event was created.
String | getType() The name of the event (case-insensitive).
void | initEvent(String eventTypeArg, boolean canBubbleArg, boolean cancelableArg) The initEvent method is used to initialize the value of an Event created through the DocumentEvent interface.
void | preventDefault() 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.
void | stopPropagation() The stopPropagation method is used prevent further propagation of an event during event flow.

Field Detail

CAPTURING_PHASE

public static final short CAPTURING_PHASE
The current event phase is the capturing phase.

See Also:
Constant Field Values

AT_TARGET

public static final short AT_TARGET
The event is currently being evaluated at the target EventTarget.

See Also:
Constant Field Values

BUBBLING_PHASE

public static final short BUBBLING_PHASE
The current event phase is the bubbling phase.

See Also:
Constant Field Values
Method Detail

getType

public String getType()
The name of the event (case-insensitive). The name must be an XML name.

getTarget

public EventTarget getTarget()
Used to indicate the EventTarget to which the event was originally dispatched.

getCurrentTarget

public EventTarget getCurrentTarget()
Used to indicate the EventTarget whose EventListeners are currently being processed. This is particularly useful during capturing and bubbling.

getEventPhase

public short getEventPhase()
Used to indicate which phase of event flow is currently being evaluated.

getBubbles

public boolean getBubbles()
Used to indicate whether or not an event is a bubbling event. If the event can bubble the value is true, else the value is false.

getCancelable

public boolean getCancelable()
Used to indicate whether or not an event can have its default action prevented. If the default action can be prevented the value is true, else the value is false.

getTimeStamp

public long getTimeStamp()
Used to specify the time (in milliseconds relative to the epoch) at which the event was created. Due to the fact that some systems may not provide this information the value of timeStamp may be not available for all events. When not available, a value of 0 will be returned. Examples of epoch time are the time of the system start or 0:0:0 UTC 1st January 1970.

stopPropagation

public void stopPropagation()
The stopPropagation method is used prevent further propagation of an event during event flow. If this method is called by any EventListener the event will cease propagating through the tree. The event will complete dispatch to all listeners on the current EventTarget before event flow stops. This method may be used during any stage of event flow.

preventDefault

public void preventDefault()
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. If, during any stage of event flow, the preventDefault method is called the event is canceled. Any default action associated with the event will not occur. Calling this method for a non-cancelable event has no effect. Once preventDefault has been called it will remain in effect throughout the remainder of the event's propagation. This method may be used during any stage of event flow.

initEvent

public void initEvent(String eventTypeArg,
                      boolean canBubbleArg,
                      boolean cancelableArg)
The initEvent method is used to initialize the value of an Event created through the DocumentEvent interface. This method may only be called before the Event has been dispatched via the dispatchEvent method, though it may be called multiple times during that phase if necessary. If called multiple times the final invocation takes precedence. If called from a subclass of Event interface only the values specified in the initEvent method are modified, all other attributes are left unchanged.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


EventException (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.events
Class EventException

java.lang.Object
    extended by java.lang.Throwable
        extended by java.lang.Exception
            extended by java.lang.RuntimeException
                extended by org.w3c.dom.events.EventException
All Implemented Interfaces:
Serializable
public class EventException
extends RuntimeException

Event operations may throw an EventException as specified in their method descriptions.

See also the Document Object Model (DOM) Level 2 Events Specification.

Since:
DOM Level 2
See Also:
Serialized Form

Field Summary
short | code
static short | UNSPECIFIED_EVENT_TYPE_ERR If the Event's type was not specified by initializing the event before the method was called.
Constructor Summary
EventException(short code, String message)
Methods inherited from class java.lang.Throwable
fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

code

public short code

UNSPECIFIED_EVENT_TYPE_ERR

public static final short UNSPECIFIED_EVENT_TYPE_ERR
If the Event's type was not specified by initializing the event before the method was called. Specification of the Event's type as null or an empty string will also trigger this exception.

See Also:
Constant Field Values
Constructor Detail

EventException

public EventException(short code,
                      String message)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


EventListener (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.events
Interface EventListener

public interface EventListener

The EventListener interface is the primary method for handling events. Users implement the EventListener interface and register their listener on an EventTarget using the AddEventListener method. The users should also remove their EventListener from its EventTarget after they have completed using the listener.

When a Node is copied using the cloneNode method the EventListeners attached to the source Node are not attached to the copied Node. If the user wishes the same EventListeners to be added to the newly created copy the user must add them manually.

See also the Document Object Model (DOM) Level 2 Events Specification.

Since:
DOM Level 2

Method Summary
 void handleEvent(Event evt)
This method is called whenever an event occurs of the type for which the EventListener interface was registered.

Method Detail

handleEvent

public void handleEvent(Event evt)
This method is called whenever an event occurs of the type for which the EventListener interface was registered.

Parameters:
evt - The Event contains contextual information about the event. It also contains the stopPropagation and preventDefault methods which are used in determining the event's flow and default action.
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


EventTarget (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.events
Interface EventTarget

public interface EventTarget

The EventTarget interface is implemented by all Nodes in an implementation which supports the DOM Event Model. Therefore, this interface can be obtained by using binding-specific casting methods on an instance of the Node interface. The interface allows registration and removal of EventListeners on an EventTarget and dispatch of events to that EventTarget.

See also the Document Object Model (DOM) Level 2 Events Specification.

Since:
DOM Level 2

Method Summary
void | addEventListener(String type, EventListener listener, boolean useCapture) This method allows the registration of event listeners on the event target.
boolean | dispatchEvent(Event evt) This method allows the dispatch of events into the implementations event model.
void | removeEventListener(String type, EventListener listener, boolean useCapture) This method allows the removal of event listeners from the event target.

Method Detail

addEventListener

public void addEventListener(String type,
                             EventListener listener,
                             boolean useCapture)
This method allows the registration of event listeners on the event target. If an EventListener is added to an EventTarget while it is processing an event, it will not be triggered by the current actions but may be triggered during a later stage of event flow, such as the bubbling phase.
If multiple identical EventListeners are registered on the same EventTarget with the same parameters the duplicate instances are discarded. They do not cause the EventListener to be called twice and since they are discarded they do not need to be removed with the removeEventListener method.

removeEventListener

public void removeEventListener(String type,
                                EventListener listener,
                                boolean useCapture)
This method allows the removal of event listeners from the event target. If an EventListener is removed from an EventTarget while it is processing an event, it will not be triggered by the current actions. EventListeners can never be invoked after being removed.
Calling removeEventListener with arguments which do not identify any currently registered EventListener on the EventTarget has no effect.

dispatchEvent

public boolean dispatchEvent(Event evt)
                      throws EventException
This method allows the dispatch of events into the implementations event model. Events dispatched in this manner will have the same capturing and bubbling behavior as events dispatched directly by the implementation. The target of the event is the EventTarget on which dispatchEvent is called.

Returns:
The return value of dispatchEvent indicates whether any of the listeners which handled the event called preventDefault. If preventDefault was called the value is false, else the value is true.
Throws:
EventException - UNSPECIFIED_EVENT_TYPE_ERR: Raised if the Event's type was not specified by initializing the event before dispatchEvent was called. Specification of the Event's type as null or an empty string will also trigger this exception.
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


MouseEvent (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.events
Interface MouseEvent

All Superinterfaces:
Event, UIEvent
public interface MouseEvent
extends UIEvent

The MouseEvent interface provides specific contextual information associated with Mouse events.

The detail attribute inherited from UIEvent indicates the number of times a mouse button has been pressed and released over the same screen location during a user action. The attribute value is 1 when the user begins this action and increments by 1 for each full sequence of pressing and releasing. If the user moves the mouse between the mousedown and mouseup the value will be set to 0, indicating that no click is occurring.

In the case of nested elements mouse events are always targeted at the most deeply nested element. Ancestors of the targeted element may use bubbling to obtain notification of mouse events which occur within its descendent elements.

See also the Document Object Model (DOM) Level 2 Events Specification.

Since:
DOM Level 2

Field Summary
Fields inherited from interface org.w3c.dom.events.Event
AT_TARGET, BUBBLING_PHASE, CAPTURING_PHASE
Method Summary
boolean | getAltKey() Used to indicate whether the 'alt' key was depressed during the firing of the event.
short | getButton() During mouse events caused by the depression or release of a mouse button, button is used to indicate which mouse button changed state.
int | getClientX() The horizontal coordinate at which the event occurred relative to the DOM implementation's client area.
int | getClientY() The vertical coordinate at which the event occurred relative to the DOM implementation's client area.
boolean | getCtrlKey() Used to indicate whether the 'ctrl' key was depressed during the firing of the event.
boolean | getMetaKey() Used to indicate whether the 'meta' key was depressed during the firing of the event.
EventTarget | getRelatedTarget() Used to identify a secondary EventTarget related to a UI event.
int | getScreenX() The horizontal coordinate at which the event occurred relative to the origin of the screen coordinate system.
int | getScreenY() The vertical coordinate at which the event occurred relative to the origin of the screen coordinate system.
boolean | getShiftKey() Used to indicate whether the 'shift' key was depressed during the firing of the event.
void | 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.
Methods inherited from interface org.w3c.dom.events.UIEvent
getDetail, getView, initUIEvent
Methods inherited from interface org.w3c.dom.events.Event
getBubbles, getCancelable, getCurrentTarget, getEventPhase, getTarget, getTimeStamp, getType, initEvent, preventDefault, stopPropagation

Method Detail

getScreenX

public int getScreenX()
The horizontal coordinate at which the event occurred relative to the origin of the screen coordinate system.

getScreenY

public int getScreenY()
The vertical coordinate at which the event occurred relative to the origin of the screen coordinate system.

getClientX

public int getClientX()
The horizontal coordinate at which the event occurred relative to the DOM implementation's client area.

getClientY

public int getClientY()
The vertical coordinate at which the event occurred relative to the DOM implementation's client area.

getCtrlKey

public boolean getCtrlKey()
Used to indicate whether the 'ctrl' key was depressed during the firing of the event.

getShiftKey

public boolean getShiftKey()
Used to indicate whether the 'shift' key was depressed during the firing of the event.

getAltKey

public boolean getAltKey()
Used to indicate whether the 'alt' key was depressed during the firing of the event. On some platforms this key may map to an alternative key name.

getMetaKey

public boolean getMetaKey()
Used to indicate whether the 'meta' key was depressed during the firing of the event. On some platforms this key may map to an alternative key name.

getButton

public short getButton()
During mouse events caused by the depression or release of a mouse button, button is used to indicate which mouse button changed state. The values for button range from zero to indicate the left button of the mouse, one to indicate the middle button if present, and two to indicate the right button. For mice configured for left handed use in which the button actions are reversed the values are instead read from right to left.

getRelatedTarget

public EventTarget getRelatedTarget()
Used to identify a secondary EventTarget related to a UI event. Currently this attribute is used with the mouseover event to indicate the EventTarget which the pointing device exited and with the mouseout event to indicate the EventTarget which the pointing device entered.

initMouseEvent

public void 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. This method may only be called before the MouseEvent has been dispatched via the dispatchEvent method, though it may be called multiple times during that phase if necessary. If called multiple times, the final invocation takes precedence.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


MutationEvent (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.events
Interface MutationEvent

All Superinterfaces:
Event
public interface MutationEvent
extends Event

The MutationEvent interface provides specific contextual information associated with Mutation events.

See also the Document Object Model (DOM) Level 2 Events Specification.

Since:
DOM Level 2

Field Summary
static short | ADDITION The Attr was just added.
static short | MODIFICATION The Attr was modified in place.
static short | REMOVAL The Attr was just removed.
Fields inherited from interface org.w3c.dom.events.Event
AT_TARGET, BUBBLING_PHASE, CAPTURING_PHASE
Method Summary
short | getAttrChange() attrChange indicates the type of change which triggered the DOMAttrModified event.
String | getAttrName() attrName indicates the name of the changed Attr node in a DOMAttrModified event.
String | getNewValue() newValue indicates the new value of the Attr node in DOMAttrModified events, and of the CharacterData node in DOMCharDataModified events.
String | getPrevValue() prevValue indicates the previous value of the Attr node in DOMAttrModified events, and of the CharacterData node in DOMCharDataModified events.
Node | getRelatedNode() relatedNode is used to identify a secondary node related to a mutation event.
void | 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.
Methods inherited from interface org.w3c.dom.events.Event
getBubbles, getCancelable, getCurrentTarget, getEventPhase, getTarget, getTimeStamp, getType, initEvent, preventDefault, stopPropagation

Field Detail

MODIFICATION

public static final short MODIFICATION
The Attr was modified in place.

See Also:
Constant Field Values

ADDITION

public static final short ADDITION
The Attr was just added.

See Also:
Constant Field Values

REMOVAL

public static final short REMOVAL
The Attr was just removed.

See Also:
Constant Field Values
Method Detail

getRelatedNode

public Node getRelatedNode()
relatedNode is used to identify a secondary node related to a mutation event. For example, if a mutation event is dispatched to a node indicating that its parent has changed, the relatedNode is the changed parent. If an event is instead dispatched to a subtree indicating a node was changed within it, the relatedNode is the changed node. In the case of the DOMAttrModified event it indicates the Attr node which was modified, added, or removed.

getPrevValue

public String getPrevValue()
prevValue indicates the previous value of the Attr node in DOMAttrModified events, and of the CharacterData node in DOMCharDataModified events.

getNewValue

public String getNewValue()
newValue indicates the new value of the Attr node in DOMAttrModified events, and of the CharacterData node in DOMCharDataModified events.

getAttrName

public String getAttrName()
attrName indicates the name of the changed Attr node in a DOMAttrModified event.

getAttrChange

public short getAttrChange()
attrChange indicates the type of change which triggered the DOMAttrModified event. The values can be MODIFICATION , ADDITION, or REMOVAL.

initMutationEvent

public void 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. This method may only be called before the MutationEvent has been dispatched via the dispatchEvent method, though it may be called multiple times during that phase if necessary. If called multiple times, the final invocation takes precedence.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


org.w3c.dom.events (Common DOM API)

 org.w3c.dom.events
Interfaces
DocumentEvent
Event
EventListener
EventTarget
MouseEvent
MutationEvent
UIEvent
Exceptions
EventException


org.w3c.dom.events (Common DOM API)

Common DOM API
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package org.w3c.dom.events

Interface Summary
DocumentEvent | The DocumentEvent interface provides a mechanism by which the user can create an Event of a type supported by the implementation.
Event | The Event interface is used to provide contextual information about an event to the handler processing the event.
EventListener | The EventListener interface is the primary method for handling events.
EventTarget | The EventTarget interface is implemented by all Nodes in an implementation which supports the DOM Event Model.
MouseEvent | The MouseEvent interface provides specific contextual information associated with Mouse events.
MutationEvent | The MutationEvent interface provides specific contextual information associated with Mutation events.
UIEvent | The UIEvent interface provides specific contextual information associated with User Interface events.

Exception Summary
EventException Event operations may throw an EventException as specified in their method descriptions.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


org.w3c.dom.events Class Hierarchy (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Hierarchy For Package org.w3c.dom.events

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class java.lang.Throwable (implements java.io.Serializable)
      • class java.lang.Exception
        • class java.lang.RuntimeException
          • class org.w3c.dom.events.EventException

Interface Hierarchy

  • interface org.w3c.dom.events.DocumentEvent
  • interface org.w3c.dom.events.Event
    • interface org.w3c.dom.events.MutationEvent
    • interface org.w3c.dom.events.UIEvent
      • interface org.w3c.dom.events.MouseEvent
  • interface org.w3c.dom.events.EventListener
  • interface org.w3c.dom.events.EventTarget
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Package org.w3c.dom.events (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Package
org.w3c.dom.events

Packages that use org.w3c.dom.events
org.w3c.dom.events

Classes in org.w3c.dom.events used by org.w3c.dom.events
Event
The Event interface is used to provide contextual information about an event to the handler processing the event.
EventException
Event operations may throw an EventException as specified in their method descriptions.
EventListener
The EventListener interface is the primary method for handling events.
EventTarget
The EventTarget interface is implemented by all Nodes in an implementation which supports the DOM Event Model.
UIEvent
The UIEvent interface provides specific contextual information associated with User Interface events.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


UIEvent (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.events
Interface UIEvent

All Superinterfaces:
Event
All Known Subinterfaces:
MouseEvent
public interface UIEvent
extends Event

The UIEvent interface provides specific contextual information associated with User Interface events.

See also the Document Object Model (DOM) Level 2 Events Specification.

Since:
DOM Level 2

Field Summary
Fields inherited from interface org.w3c.dom.events.Event
AT_TARGET, BUBBLING_PHASE, CAPTURING_PHASE
Method Summary
int | getDetail() Specifies some detail information about the Event, depending on the type of event.
AbstractView | getView() The view attribute identifies the AbstractView from which the event was generated.
void | 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.
Methods inherited from interface org.w3c.dom.events.Event
getBubbles, getCancelable, getCurrentTarget, getEventPhase, getTarget, getTimeStamp, getType, initEvent, preventDefault, stopPropagation

Method Detail

getView

public AbstractView getView()
The view attribute identifies the AbstractView from which the event was generated.

getDetail

public int getDetail()
Specifies some detail information about the Event, depending on the type of event.

initUIEvent

public void 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. This method may only be called before the UIEvent has been dispatched via the dispatchEvent method, though it may be called multiple times during that phase if necessary. If called multiple times, the final invocation takes precedence.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.events.DocumentEvent (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.events.Event (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.events.Event

Packages that use Event
org.w3c.dom.events

Uses of Event in org.w3c.dom.events

Subinterfaces of Event in org.w3c.dom.events
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
 Event DocumentEvent.createEvent(String eventType)

Methods in org.w3c.dom.events with parameters of type Event
void | EventListener.handleEvent(Event evt) This method is called whenever an event occurs of the type for which the EventListener interface was registered.
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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Class org.w3c.dom.events.EventException (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Class
org.w3c.dom.events.EventException

Packages that use EventException
org.w3c.dom.events

Uses of EventException in org.w3c.dom.events

Methods in org.w3c.dom.events that throw EventException
 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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.events.EventListener (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.events.EventListener

Packages that use EventListener
org.w3c.dom.events

Uses of EventListener in org.w3c.dom.events

Methods in org.w3c.dom.events with parameters of type EventListener
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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.events.EventTarget (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.events.EventTarget

Packages that use EventTarget
org.w3c.dom.events

Uses of EventTarget in org.w3c.dom.events

Methods in org.w3c.dom.events that return EventTarget
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.
EventTarget | Event.getCurrentTarget() Used to indicate the EventTarget whose EventListeners are currently being processed.

Methods in org.w3c.dom.events with parameters of type EventTarget
 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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.events.MouseEvent (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.events.MutationEvent (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.events.UIEvent (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.events.UIEvent

Packages that use UIEvent
org.w3c.dom.events

Uses of UIEvent in org.w3c.dom.events

Subinterfaces of UIEvent in org.w3c.dom.events
 interface MouseEvent
The MouseEvent interface provides specific contextual information associated with Mouse events.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLAnchorElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLAnchorElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLAnchorElement
extends HTMLElement

The anchor element. See the A element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
void | blur() Removes keyboard focus from this element.
void | focus() Gives keyboard focus to this element.
String | getAccessKey() A single character access key to give access to the form control.
String | getCharset() The character encoding of the linked resource.
String | getCoords() Comma-separated list of lengths, defining an active region geometry.
String | getHref() The URI of the linked resource.
String | getHreflang() Language code of the linked resource.
String | getName() Anchor name.
String | getRel() Forward link type.
String | getRev() Reverse link type.
String | getShape() The shape of the active area.
int | getTabIndex() Index that represents the element's position in the tabbing order.
String | getTarget() Frame to render the resource in.
String | getType() Advisory content type.
void | setAccessKey(String accessKey)
void | setCharset(String charset)
void | setCoords(String coords)
void | setHref(String href)
void | setHreflang(String hreflang)
void | setName(String name)
void | setRel(String rel)
void | setRev(String rev)
void | setShape(String shape)
void | setTabIndex(int tabIndex)
void | setTarget(String target)
void | setType(String type)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getAccessKey

public String getAccessKey()
A single character access key to give access to the form control. See the accesskey attribute definition in HTML 4.0.

setAccessKey

public void setAccessKey(String accessKey)

getCharset

public String getCharset()
The character encoding of the linked resource. See the charset attribute definition in HTML 4.0.

setCharset

public void setCharset(String charset)

getCoords

public String getCoords()
Comma-separated list of lengths, defining an active region geometry. See also shape for the shape of the region. See the coords attribute definition in HTML 4.0.

setCoords

public void setCoords(String coords)

getHref

public String getHref()
The URI of the linked resource. See the href attribute definition in HTML 4.0.

setHref

public void setHref(String href)

getHreflang

public String getHreflang()
Language code of the linked resource. See the hreflang attribute definition in HTML 4.0.

setHreflang

public void setHreflang(String hreflang)

getName

public String getName()
Anchor name. See the name attribute definition in HTML 4.0.

setName

public void setName(String name)

getRel

public String getRel()
Forward link type. See the rel attribute definition in HTML 4.0.

setRel

public void setRel(String rel)

getRev

public String getRev()
Reverse link type. See the rev attribute definition in HTML 4.0.

setRev

public void setRev(String rev)

getShape

public String getShape()
The shape of the active area. The coordinates are given by coords . See the shape attribute definition in HTML 4.0.

setShape

public void setShape(String shape)

getTabIndex

public int getTabIndex()
Index that represents the element's position in the tabbing order. See the tabindex attribute definition in HTML 4.0.

setTabIndex

public void setTabIndex(int tabIndex)

getTarget

public String getTarget()
Frame to render the resource in. See the target attribute definition in HTML 4.0.

setTarget

public void setTarget(String target)

getType

public String getType()
Advisory content type. See the type attribute definition in HTML 4.0.

setType

public void setType(String type)

blur

public void blur()
Removes keyboard focus from this element.

focus

public void focus()
Gives keyboard focus to this element.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLAppletElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLAppletElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLAppletElement
extends HTMLElement

An embedded Java applet. See the APPLET element definition in HTML 4.0. This element is deprecated in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getAlign() Aligns this object (vertically or horizontally) with respect to its surrounding text.
String | getAlt() Alternate text for user agents not rendering the normal content of this element.
String | getArchive() Comma-separated archive list.
String | getCode() Applet class file.
String | getCodeBase() Optional base URI for applet.
String | getHeight() Override height.
String | getHspace() Horizontal space to the left and right of this image, applet, or object.
String | getName() The name of the applet.
String | getObject() Serialized applet file.
String | getVspace() Vertical space above and below this image, applet, or object.
String | getWidth() Override width.
void | setAlign(String align)
void | setAlt(String alt)
void | setArchive(String archive)
void | setCode(String code)
void | setCodeBase(String codeBase)
void | setHeight(String height)
void | setHspace(String hspace)
void | setName(String name)
void | setObject(String object)
void | setVspace(String vspace)
void | setWidth(String width)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getAlign

public String getAlign()
Aligns this object (vertically or horizontally) with respect to its surrounding text. See the align attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setAlign

public void setAlign(String align)

getAlt

public String getAlt()
Alternate text for user agents not rendering the normal content of this element. See the alt attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setAlt

public void setAlt(String alt)

getArchive

public String getArchive()
Comma-separated archive list. See the archive attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setArchive

public void setArchive(String archive)

getCode

public String getCode()
Applet class file. See the code attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setCode

public void setCode(String code)

getCodeBase

public String getCodeBase()
Optional base URI for applet. See the codebase attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setCodeBase

public void setCodeBase(String codeBase)

getHeight

public String getHeight()
Override height. See the height attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setHeight

public void setHeight(String height)

getHspace

public String getHspace()
Horizontal space to the left and right of this image, applet, or object. See the hspace attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setHspace

public void setHspace(String hspace)

getName

public String getName()
The name of the applet. See the name attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setName

public void setName(String name)

getObject

public String getObject()
Serialized applet file. See the object attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setObject

public void setObject(String object)

getVspace

public String getVspace()
Vertical space above and below this image, applet, or object. See the vspace attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setVspace

public void setVspace(String vspace)

getWidth

public String getWidth()
Override width. See the width attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setWidth

public void setWidth(String width)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLAreaElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLAreaElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLAreaElement
extends HTMLElement

Client-side image map area definition. See the AREA element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getAccessKey() A single character access key to give access to the form control.
String | getAlt() Alternate text for user agents not rendering the normal content of this element.
String | getCoords() Comma-separated list of lengths, defining an active region geometry.
String | getHref() The URI of the linked resource.
boolean | getNoHref() Specifies that this area is inactive, i.e., has no associated action.
String | getShape() The shape of the active area.
int | getTabIndex() Index that represents the element's position in the tabbing order.
String | getTarget() Frame to render the resource in.
void | setAccessKey(String accessKey)
void | setAlt(String alt)
void | setCoords(String coords)
void | setHref(String href)
void | setNoHref(boolean noHref)
void | setShape(String shape)
void | setTabIndex(int tabIndex)
void | setTarget(String target)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getAccessKey

public String getAccessKey()
A single character access key to give access to the form control. See the accesskey attribute definition in HTML 4.0.

setAccessKey

public void setAccessKey(String accessKey)

getAlt

public String getAlt()
Alternate text for user agents not rendering the normal content of this element. See the alt attribute definition in HTML 4.0.

setAlt

public void setAlt(String alt)

getCoords

public String getCoords()
Comma-separated list of lengths, defining an active region geometry. See also shape for the shape of the region. See the coords attribute definition in HTML 4.0.

setCoords

public void setCoords(String coords)

getHref

public String getHref()
The URI of the linked resource. See the href attribute definition in HTML 4.0.

setHref

public void setHref(String href)

getNoHref

public boolean getNoHref()
Specifies that this area is inactive, i.e., has no associated action. See the nohref attribute definition in HTML 4.0.

setNoHref

public void setNoHref(boolean noHref)

getShape

public String getShape()
The shape of the active area. The coordinates are given by coords . See the shape attribute definition in HTML 4.0.

setShape

public void setShape(String shape)

getTabIndex

public int getTabIndex()
Index that represents the element's position in the tabbing order. See the tabindex attribute definition in HTML 4.0.

setTabIndex

public void setTabIndex(int tabIndex)

getTarget

public String getTarget()
Frame to render the resource in. See the target attribute definition in HTML 4.0.

setTarget

public void setTarget(String target)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLBaseElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLBaseElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLBaseElement
extends HTMLElement

Document base URI. See the BASE element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getHref() The base URI.
String | getTarget() The default target frame.
void | setHref(String href)
void | setTarget(String target)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getHref

public String getHref()
The base URI. See the href attribute definition in HTML 4.0.

setHref

public void setHref(String href)

getTarget

public String getTarget()
The default target frame. See the target attribute definition in HTML 4.0.

setTarget

public void setTarget(String target)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLBaseFontElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLBaseFontElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLBaseFontElement
extends HTMLElement

Base font. See the BASEFONT element definition in HTML 4.0. This element is deprecated in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getColor() Font color.
String | getFace() Font face identifier.
String | getSize() Font size.
void | setColor(String color)
void | setFace(String face)
void | setSize(String size)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getColor

public String getColor()
Font color. See the color attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setColor

public void setColor(String color)

getFace

public String getFace()
Font face identifier. See the face attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setFace

public void setFace(String face)

getSize

public String getSize()
Font size. See the size attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setSize

public void setSize(String size)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLBodyElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLBodyElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLBodyElement
extends HTMLElement

The HTML document body. This element is always present in the DOM API, even if the tags are not present in the source document. See the BODY element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getALink() Color of active links (after mouse-button down, but before mouse-button up).
String | getBackground() URI of the background texture tile image.
String | getBgColor() Document background color.
String | getLink() Color of links that are not active and unvisited.
String | getText() Document text color.
String | getVLink() Color of links that have been visited by the user.
void | setALink(String aLink)
void | setBackground(String background)
void | setBgColor(String bgColor)
void | setLink(String link)
void | setText(String text)
void | setVLink(String vLink)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getALink

public String getALink()
Color of active links (after mouse-button down, but before mouse-button up). See the alink attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setALink

public void setALink(String aLink)

getBackground

public String getBackground()
URI of the background texture tile image. See the background attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setBackground

public void setBackground(String background)

getBgColor

public String getBgColor()
Document background color. See the bgcolor attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setBgColor

public void setBgColor(String bgColor)

getLink

public String getLink()
Color of links that are not active and unvisited. See the link attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setLink

public void setLink(String link)

getText

public String getText()
Document text color. See the text attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setText

public void setText(String text)

getVLink

public String getVLink()
Color of links that have been visited by the user. See the vlink attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setVLink

public void setVLink(String vLink)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLBRElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLBRElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLBRElement
extends HTMLElement

Force a line break. See the BR element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getClear() Control flow of text around floats.
void | setClear(String clear)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getClear

public String getClear()
Control flow of text around floats. See the clear attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setClear

public void setClear(String clear)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLButtonElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLButtonElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLButtonElement
extends HTMLElement

Push button. See the BUTTON element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getAccessKey() A single character access key to give access to the form control.
boolean | getDisabled() The control is unavailable in this context.
HTMLFormElement | getForm() Returns the FORM element containing this control.
String | getName() Form control or object name when submitted with a form.
int | getTabIndex() Index that represents the element's position in the tabbing order.
String | getType() The type of button.
String | getValue() The current form control value.
void | setAccessKey(String accessKey)
void | setDisabled(boolean disabled)
void | setName(String name)
void | setTabIndex(int tabIndex)
void | setValue(String value)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getForm

public HTMLFormElement getForm()
Returns the FORM element containing this control. Returns null if this control is not within the context of a form.

getAccessKey

public String getAccessKey()
A single character access key to give access to the form control. See the accesskey attribute definition in HTML 4.0.

setAccessKey

public void setAccessKey(String accessKey)

getDisabled

public boolean getDisabled()
The control is unavailable in this context. See the disabled attribute definition in HTML 4.0.

setDisabled

public void setDisabled(boolean disabled)

getName

public String getName()
Form control or object name when submitted with a form. See the name attribute definition in HTML 4.0.

setName

public void setName(String name)

getTabIndex

public int getTabIndex()
Index that represents the element's position in the tabbing order. See the tabindex attribute definition in HTML 4.0.

setTabIndex

public void setTabIndex(int tabIndex)

getType

public String getType()
The type of button. See the type attribute definition in HTML 4.0.

getValue

public String getValue()
The current form control value. See the value attribute definition in HTML 4.0.

setValue

public void setValue(String value)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLCollection (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLCollection

public interface HTMLCollection

An HTMLCollection is a list of nodes. An individual node may be accessed by either ordinal index or the node'sname or id attributes. Note: Collections in the HTML DOM are assumed to be live meaning that they are automatically updated when the underlying document is changed.

See also the Document Object Model (DOM) Level 2 Specification.

Method Summary
int | getLength() This attribute specifies the length or size of the list.
Node | item(int index) This method retrieves a node specified by ordinal index.
Node | namedItem(String name) This method retrieves a Node using a name.

Method Detail

getLength

public int getLength()
This attribute specifies the length or size of the list.

item

public Node item(int index)
This method retrieves a node specified by ordinal index. Nodes are numbered in tree order (depth-first traversal order).

Parameters:
index - The index of the node to be fetched. The index origin is 0.
Returns:
The Node at the corresponding position upon success. A value of null is returned if the index is out of range.

namedItem

public Node namedItem(String name)
This method retrieves a Node using a name. It first searches for a Node with a matching id attribute. If it doesn't find one, it then searches for a Node with a matching name attribute, but only on those elements that are allowed a name attribute.

Parameters:
name - The name of the Node to be fetched.
Returns:
The Node with a name or id attribute whose value corresponds to the specified string. Upon failure (e.g., no node with this name exists), returns null .
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLDirectoryElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLDirectoryElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLDirectoryElement
extends HTMLElement

Directory list. See the DIR element definition in HTML 4.0. This element is deprecated in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
boolean | getCompact() Reduce spacing between list items.
void | setCompact(boolean compact)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getCompact

public boolean getCompact()
Reduce spacing between list items. See the compact attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setCompact

public void setCompact(boolean compact)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLDivElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLDivElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLDivElement
extends HTMLElement

Generic block container. See the DIV element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getAlign() Horizontal text alignment.
void | setAlign(String align)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getAlign

public String getAlign()
Horizontal text alignment. See the align attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setAlign

public void setAlign(String align)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLDListElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLDListElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLDListElement
extends HTMLElement

Definition list. See the DL element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
boolean | getCompact() Reduce spacing between list items.
void | setCompact(boolean compact)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getCompact

public boolean getCompact()
Reduce spacing between list items. See the compact attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setCompact

public void setCompact(boolean compact)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLDocument (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLDocument

All Superinterfaces:
Document, Node
public interface HTMLDocument
extends Document

An HTMLDocument is the root of the HTML hierarchy and holds the entire content. Besides providing access to the hierarchy, it also provides some convenience methods for accessing certain sets of information from the document.

The following properties have been deprecated in favor of the corresponding ones for the BODY element: alinkColor background bgColor fgColor linkColor vlinkColor In DOM Level 2, the method getElementById is inherited from the Document interface where it was moved.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
 void close()
Closes a document stream opened by open() and forces rendering.
 HTMLCollection getAnchors()
A collection of all the anchor (A ) elements in a document with a value for the name attribute.
 HTMLCollection getApplets()
A collection of all the OBJECT elements that include applets and APPLET ( deprecated ) elements in a document.
 HTMLElement getBody()
The element that contains the content for the document.
 String getCookie()
The cookies associated with this document.
 String getDomain()
The domain name of the server that served the document, or null if the server cannot be identified by a domain name.
 NodeList getElementsByName(String elementName)
Returns the (possibly empty) collection of elements whose name value is given by elementName .
 HTMLCollection getForms()
A collection of all the forms of a document.
 HTMLCollection getImages()
A collection of all the IMG elements in a document.
 HTMLCollection getLinks()
A collection of all AREA elements and anchor ( A ) elements in a document with a value for the href attribute.
 String getReferrer()
Returns the URI of the page that linked to this page.
 String getTitle()
The title of a document as specified by the TITLE element in the head of the document.
 String getURL()
The complete URI of the document.
 void open()
Note.
 void setBody(HTMLElement body)
 void setCookie(String cookie)
 void setTitle(String title)
 void write(String text)
Write a string of text to a document stream opened by open() .
 void writeln(String text)
Write a string of text followed by a newline character to a document stream opened by open() .
Methods inherited from interface org.w3c.dom.Document
createAttribute, createAttributeNS, createCDATASection, createComment, createDocumentFragment, createElement, createElementNS, createEntityReference, createProcessingInstruction, createTextNode, getDoctype, getDocumentElement, getElementById, getElementsByTagName, getElementsByTagNameNS, getImplementation, importNode
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getTitle

public String getTitle()
The title of a document as specified by the TITLE element in the head of the document.

setTitle

public void setTitle(String title)

getReferrer

public String getReferrer()
Returns the URI of the page that linked to this page. The value is an empty string if the user navigated to the page directly (not through a link, but, for example, via a bookmark).

getDomain

public String getDomain()
The domain name of the server that served the document, or null if the server cannot be identified by a domain name.

getURL

public String getURL()
The complete URI of the document.

getBody

public HTMLElement getBody()
The element that contains the content for the document. In documents with BODY contents, returns the BODY element. In frameset documents, this returns the outermost FRAMESET element.

setBody

public void setBody(HTMLElement body)

getImages

public HTMLCollection getImages()
A collection of all the IMG elements in a document. The behavior is limited to IMG elements for backwards compatibility.

getApplets

public HTMLCollection getApplets()
A collection of all the OBJECT elements that include applets and APPLET ( deprecated ) elements in a document.

getLinks

public HTMLCollection getLinks()
A collection of all AREA elements and anchor ( A ) elements in a document with a value for the href attribute.

getForms

public HTMLCollection getForms()
A collection of all the forms of a document.

getAnchors

public HTMLCollection getAnchors()
A collection of all the anchor (A ) elements in a document with a value for the name attribute. Note. For reasons of backwards compatibility, the returned set of anchors only contains those anchors created with the name attribute, not those created with the id attribute.

getCookie

public String getCookie()
The cookies associated with this document. If there are none, the value is an empty string. Otherwise, the value is a string: a semicolon-delimited list of "name, value" pairs for all the cookies associated with the page. For example, name=value;expires=date .

setCookie

public void setCookie(String cookie)

open

public void open()
Note. This method and the ones following allow a user to add to or replace the structure model of a document using strings of unparsed HTML. At the time of writing alternate methods for providing similar functionality for both HTML and XML documents were being considered. The following methods may be deprecated at some point in the future in favor of a more general-purpose mechanism.
Open a document stream for writing. If a document exists in the target, this method clears it.

close

public void close()
Closes a document stream opened by open() and forces rendering.

write

public void write(String text)
Write a string of text to a document stream opened by open() . The text is parsed into the document's structure model.

Parameters:
text - The string to be parsed into some structure in the document structure model.

writeln

public void writeln(String text)
Write a string of text followed by a newline character to a document stream opened by open() . The text is parsed into the document's structure model.

Parameters:
text - The string to be parsed into some structure in the document structure model.

getElementsByName

public NodeList getElementsByName(String elementName)
Returns the (possibly empty) collection of elements whose name value is given by elementName .

Parameters:
elementName - The name attribute value for an element.
Returns:
The matching elements.
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLDOMImplementation (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLDOMImplementation

All Superinterfaces:
DOMImplementation
public interface HTMLDOMImplementation
extends DOMImplementation

The HTMLDOMImplementation interface extends the DOMImplementation interface with a method for creating an HTML document instance.

See also the Document Object Model (DOM) Level 2 Specification.

Since:
DOM Level 2

Method Summary
 HTMLDocument createHTMLDocument(String title)
Creates an HTMLDocument object with the minimal tree made of the following elements: HTML , HEAD , TITLE , and BODY .
Methods inherited from interface org.w3c.dom.DOMImplementation
createDocument, createDocumentType, hasFeature

Method Detail

createHTMLDocument

public HTMLDocument createHTMLDocument(String title)
Creates an HTMLDocument object with the minimal tree made of the following elements: HTML , HEAD , TITLE , and BODY .

Parameters:
title - The title of the document to be set as the content of the TITLE element, through a child Text node.
Returns:
A new HTMLDocument object.
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLElement

All Superinterfaces:
Element, Node
All Known Subinterfaces:
HTMLAnchorElement, HTMLAppletElement, HTMLAreaElement, HTMLBaseElement, HTMLBaseFontElement, HTMLBodyElement, HTMLBRElement, HTMLButtonElement, HTMLDirectoryElement, HTMLDivElement, HTMLDListElement, HTMLFieldSetElement, HTMLFontElement, HTMLFormElement, HTMLFrameElement, HTMLFrameSetElement, HTMLHeadElement, HTMLHeadingElement, HTMLHRElement, HTMLHtmlElement, HTMLIFrameElement, HTMLImageElement, HTMLInputElement, HTMLIsIndexElement, HTMLLabelElement, HTMLLegendElement, HTMLLIElement, HTMLLinkElement, HTMLMapElement, HTMLMenuElement, HTMLMetaElement, HTMLModElement, HTMLObjectElement, HTMLOListElement, HTMLOptGroupElement, HTMLOptionElement, HTMLParagraphElement, HTMLParamElement, HTMLPreElement, HTMLQuoteElement, HTMLScriptElement, HTMLSelectElement, HTMLStyleElement, HTMLTableCaptionElement, HTMLTableCellElement, HTMLTableColElement, HTMLTableElement, HTMLTableRowElement, HTMLTableSectionElement, HTMLTextAreaElement, HTMLTitleElement, HTMLUListElement
public interface HTMLElement
extends Element

All HTML element interfaces derive from this class. Elements that only expose the HTML core attributes are represented by the base HTMLElement interface. These elements are as follows: HEAD special: SUB, SUP, SPAN, BDO font: TT, I, B, U, S, STRIKE, BIG, SMALL phrase: EM, STRONG, DFN, CODE, SAMP, KBD, VAR, CITE, ACRONYM, ABBR list: DD, DT NOFRAMES, NOSCRIPT ADDRESS, CENTER The style attribute of an HTML element is accessible through the ElementCSSInlineStyle interface which is defined in the .

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getClassName() The class attribute of the element.
String | getDir() Specifies the base direction of directionally neutral text and the directionality of tables.
String | getId() The element's identifier.
String | getLang() Language code defined in RFC 1766.
String | getTitle() The element's advisory title.
void | setClassName(String className)
void | setDir(String dir)
void | setId(String id)
void | setLang(String lang)
void | setTitle(String title)
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getId

public String getId()
The element's identifier. See the id attribute definition in HTML 4.0.

setId

public void setId(String id)

getTitle

public String getTitle()
The element's advisory title. See the title attribute definition in HTML 4.0.

setTitle

public void setTitle(String title)

getLang

public String getLang()
Language code defined in RFC 1766. See the lang attribute definition in HTML 4.0.

setLang

public void setLang(String lang)

getDir

public String getDir()
Specifies the base direction of directionally neutral text and the directionality of tables. See the dir attribute definition in HTML 4.0.

setDir

public void setDir(String dir)

getClassName

public String getClassName()
The class attribute of the element. This attribute has been renamed due to conflicts with the "class" keyword exposed by many languages. See the class attribute definition in HTML 4.0.

setClassName

public void setClassName(String className)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLFieldSetElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLFieldSetElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLFieldSetElement
extends HTMLElement

Organizes form controls into logical groups. See the FIELDSET element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
 HTMLFormElement getForm()
Returns the FORM element containing this control.
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getForm

public HTMLFormElement getForm()
Returns the FORM element containing this control. Returns null if this control is not within the context of a form.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLFontElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLFontElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLFontElement
extends HTMLElement

Local change to font. See the FONT element definition in HTML 4.0. This element is deprecated in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getColor() Font color.
String | getFace() Font face identifier.
String | getSize() Font size.
void | setColor(String color)
void | setFace(String face)
void | setSize(String size)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getColor

public String getColor()
Font color. See the color attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setColor

public void setColor(String color)

getFace

public String getFace()
Font face identifier. See the face attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setFace

public void setFace(String face)

getSize

public String getSize()
Font size. See the size attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setSize

public void setSize(String size)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLFormElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLFormElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLFormElement
extends HTMLElement

The FORM element encompasses behavior similar to a collection and an element. It provides direct access to the contained input elements as well as the attributes of the form element. See the FORM element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getAcceptCharset() List of character sets supported by the server.
String | getAction() Server-side form handler.
HTMLCollection | getElements() Returns a collection of all control elements in the form.
String | getEnctype() The content type of the submitted form, generally "application/x-www-form-urlencoded".
int | getLength() The number of form controls in the form.
String | getMethod() HTTP method used to submit form.
String | getName() Names the form.
String | getTarget() Frame to render the resource in.
void | reset() Restores a form element's default values.
void | setAcceptCharset(String acceptCharset)
void | setAction(String action)
void | setEnctype(String enctype)
void | setMethod(String method)
void | setName(String name)
void | setTarget(String target)
void | submit() Submits the form.
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getElements

public HTMLCollection getElements()
Returns a collection of all control elements in the form.

getLength

public int getLength()
The number of form controls in the form.

getName

public String getName()
Names the form.

setName

public void setName(String name)

getAcceptCharset

public String getAcceptCharset()
List of character sets supported by the server. See the accept-charset attribute definition in HTML 4.0.

setAcceptCharset

public void setAcceptCharset(String acceptCharset)

getAction

public String getAction()
Server-side form handler. See the action attribute definition in HTML 4.0.

setAction

public void setAction(String action)

getEnctype

public String getEnctype()
The content type of the submitted form, generally "application/x-www-form-urlencoded". See the enctype attribute definition in HTML 4.0.

setEnctype

public void setEnctype(String enctype)

getMethod

public String getMethod()
HTTP method used to submit form. See the method attribute definition in HTML 4.0.

setMethod

public void setMethod(String method)

getTarget

public String getTarget()
Frame to render the resource in. See the target attribute definition in HTML 4.0.

setTarget

public void setTarget(String target)

submit

public void submit()
Submits the form. It performs the same action as a submit button.

reset

public void reset()
Restores a form element's default values. It performs the same action as a reset button.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLFrameElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLFrameElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLFrameElement
extends HTMLElement

Create a frame. See the FRAME element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
Document | getContentDocument() The document this frame contains, if there is any and it is available, or null otherwise.
String | getFrameBorder() Request frame borders.
String | getLongDesc() URI designating a long description of this image or frame.
String | getMarginHeight() Frame margin height, in pixels.
String | getMarginWidth() Frame margin width, in pixels.
String | getName() The frame name (object of the target attribute).
boolean | getNoResize() When true, forbid user from resizing frame.
String | getScrolling() Specify whether or not the frame should have scrollbars.
String | getSrc() A URI designating the initial frame contents.
void | setFrameBorder(String frameBorder)
void | setLongDesc(String longDesc)
void | setMarginHeight(String marginHeight)
void | setMarginWidth(String marginWidth)
void | setName(String name)
void | setNoResize(boolean noResize)
void | setScrolling(String scrolling)
void | setSrc(String src)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getFrameBorder

public String getFrameBorder()
Request frame borders. See the frameborder attribute definition in HTML 4.0.

setFrameBorder

public void setFrameBorder(String frameBorder)

getLongDesc

public String getLongDesc()
URI designating a long description of this image or frame. See the longdesc attribute definition in HTML 4.0.

setLongDesc

public void setLongDesc(String longDesc)

getMarginHeight

public String getMarginHeight()
Frame margin height, in pixels. See the marginheight attribute definition in HTML 4.0.

setMarginHeight

public void setMarginHeight(String marginHeight)

getMarginWidth

public String getMarginWidth()
Frame margin width, in pixels. See the marginwidth attribute definition in HTML 4.0.

setMarginWidth

public void setMarginWidth(String marginWidth)

getName

public String getName()
The frame name (object of the target attribute). See the name attribute definition in HTML 4.0.

setName

public void setName(String name)

getNoResize

public boolean getNoResize()
When true, forbid user from resizing frame. See the noresize attribute definition in HTML 4.0.

setNoResize

public void setNoResize(boolean noResize)

getScrolling

public String getScrolling()
Specify whether or not the frame should have scrollbars. See the scrolling attribute definition in HTML 4.0.

setScrolling

public void setScrolling(String scrolling)

getSrc

public String getSrc()
A URI designating the initial frame contents. See the src attribute definition in HTML 4.0.

setSrc

public void setSrc(String src)

getContentDocument

public Document getContentDocument()
The document this frame contains, if there is any and it is available, or null otherwise.

Since:
DOM Level 2
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLFrameSetElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLFrameSetElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLFrameSetElement
extends HTMLElement

Create a grid of frames. See the FRAMESET element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getCols() The number of columns of frames in the frameset.
String | getRows() The number of rows of frames in the frameset.
void | setCols(String cols)
void | setRows(String rows)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getCols

public String getCols()
The number of columns of frames in the frameset. See the cols attribute definition in HTML 4.0.

setCols

public void setCols(String cols)

getRows

public String getRows()
The number of rows of frames in the frameset. See the rows attribute definition in HTML 4.0.

setRows

public void setRows(String rows)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLHeadElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLHeadElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLHeadElement
extends HTMLElement

Document head information. See the HEAD element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getProfile() URI designating a metadata profile.
void | setProfile(String profile)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getProfile

public String getProfile()
URI designating a metadata profile. See the profile attribute definition in HTML 4.0.

setProfile

public void setProfile(String profile)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLHeadingElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLHeadingElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLHeadingElement
extends HTMLElement

For the H1 to H6 elements. See the H1 element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getAlign() Horizontal text alignment.
void | setAlign(String align)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getAlign

public String getAlign()
Horizontal text alignment. See the align attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setAlign

public void setAlign(String align)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLHRElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLHRElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLHRElement
extends HTMLElement

Create a horizontal rule. See the HR element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getAlign() Align the rule on the page.
boolean | getNoShade() Indicates to the user agent that there should be no shading in the rendering of this element.
String | getSize() The height of the rule.
String | getWidth() The width of the rule.
void | setAlign(String align)
void | setNoShade(boolean noShade)
void | setSize(String size)
void | setWidth(String width)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getAlign

public String getAlign()
Align the rule on the page. See the align attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setAlign

public void setAlign(String align)

getNoShade

public boolean getNoShade()
Indicates to the user agent that there should be no shading in the rendering of this element. See the noshade attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setNoShade

public void setNoShade(boolean noShade)

getSize

public String getSize()
The height of the rule. See the size attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setSize

public void setSize(String size)

getWidth

public String getWidth()
The width of the rule. See the width attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setWidth

public void setWidth(String width)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLHtmlElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLHtmlElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLHtmlElement
extends HTMLElement

Root of an HTML document. See the HTML element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getVersion() Version information about the document's DTD.
void | setVersion(String version)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getVersion

public String getVersion()
Version information about the document's DTD. See the version attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setVersion

public void setVersion(String version)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLIFrameElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLIFrameElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLIFrameElement
extends HTMLElement

Inline subwindows. See the IFRAME element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getAlign() Aligns this object (vertically or horizontally) with respect to its surrounding text.
Document | getContentDocument() The document this frame contains, if there is any and it is available, or null otherwise.
String | getFrameBorder() Request frame borders.
String | getHeight() Frame height.
String | getLongDesc() URI designating a long description of this image or frame.
String | getMarginHeight() Frame margin height, in pixels.
String | getMarginWidth() Frame margin width, in pixels.
String | getName() The frame name (object of the target attribute).
String | getScrolling() Specify whether or not the frame should have scrollbars.
String | getSrc() A URI designating the initial frame contents.
String | getWidth() Frame width.
void | setAlign(String align)
void | setFrameBorder(String frameBorder)
void | setHeight(String height)
void | setLongDesc(String longDesc)
void | setMarginHeight(String marginHeight)
void | setMarginWidth(String marginWidth)
void | setName(String name)
void | setScrolling(String scrolling)
void | setSrc(String src)
void | setWidth(String width)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getAlign

public String getAlign()
Aligns this object (vertically or horizontally) with respect to its surrounding text. See the align attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setAlign

public void setAlign(String align)

getFrameBorder

public String getFrameBorder()
Request frame borders. See the frameborder attribute definition in HTML 4.0.

setFrameBorder

public void setFrameBorder(String frameBorder)

getHeight

public String getHeight()
Frame height. See the height attribute definition in HTML 4.0.

setHeight

public void setHeight(String height)

getLongDesc

public String getLongDesc()
URI designating a long description of this image or frame. See the longdesc attribute definition in HTML 4.0.

setLongDesc

public void setLongDesc(String longDesc)

getMarginHeight

public String getMarginHeight()
Frame margin height, in pixels. See the marginheight attribute definition in HTML 4.0.

setMarginHeight

public void setMarginHeight(String marginHeight)

getMarginWidth

public String getMarginWidth()
Frame margin width, in pixels. See the marginwidth attribute definition in HTML 4.0.

setMarginWidth

public void setMarginWidth(String marginWidth)

getName

public String getName()
The frame name (object of the target attribute). See the name attribute definition in HTML 4.0.

setName

public void setName(String name)

getScrolling

public String getScrolling()
Specify whether or not the frame should have scrollbars. See the scrolling attribute definition in HTML 4.0.

setScrolling

public void setScrolling(String scrolling)

getSrc

public String getSrc()
A URI designating the initial frame contents. See the src attribute definition in HTML 4.0.

setSrc

public void setSrc(String src)

getWidth

public String getWidth()
Frame width. See the width attribute definition in HTML 4.0.

setWidth

public void setWidth(String width)

getContentDocument

public Document getContentDocument()
The document this frame contains, if there is any and it is available, or null otherwise.

Since:
DOM Level 2
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLImageElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLImageElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLImageElement
extends HTMLElement

Embedded image. See the IMG element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getAlign() Aligns this object (vertically or horizontally) with respect to its surrounding text.
String | getAlt() Alternate text for user agents not rendering the normal content of this element.
String | getBorder() Width of border around image.
String | getHeight() Override height.
String | getHspace() Horizontal space to the left and right of this image.
boolean | getIsMap() Use server-side image map.
String | getLongDesc() URI designating a long description of this image or frame.
String | getLowSrc() URI designating the source of this image, for low-resolution output.
String | getName() The name of the element (for backwards compatibility).
String | getSrc() URI designating the source of this image.
String | getUseMap() Use client-side image map.
String | getVspace() Vertical space above and below this image.
String | getWidth() Override width.
void | setAlign(String align)
void | setAlt(String alt)
void | setBorder(String border)
void | setHeight(String height)
void | setHspace(String hspace)
void | setIsMap(boolean isMap)
void | setLongDesc(String longDesc)
void | setLowSrc(String lowSrc)
void | setName(String name)
void | setSrc(String src)
void | setUseMap(String useMap)
void | setVspace(String vspace)
void | setWidth(String width)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getLowSrc

public String getLowSrc()
URI designating the source of this image, for low-resolution output.

setLowSrc

public void setLowSrc(String lowSrc)

getName

public String getName()
The name of the element (for backwards compatibility).

setName

public void setName(String name)

getAlign

public String getAlign()
Aligns this object (vertically or horizontally) with respect to its surrounding text. See the align attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setAlign

public void setAlign(String align)

getAlt

public String getAlt()
Alternate text for user agents not rendering the normal content of this element. See the alt attribute definition in HTML 4.0.

setAlt

public void setAlt(String alt)

getBorder

public String getBorder()
Width of border around image. See the border attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setBorder

public void setBorder(String border)

getHeight

public String getHeight()
Override height. See the height attribute definition in HTML 4.0.

setHeight

public void setHeight(String height)

getHspace

public String getHspace()
Horizontal space to the left and right of this image. See the hspace attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setHspace

public void setHspace(String hspace)

getIsMap

public boolean getIsMap()
Use server-side image map. See the ismap attribute definition in HTML 4.0.

setIsMap

public void setIsMap(boolean isMap)

getLongDesc

public String getLongDesc()
URI designating a long description of this image or frame. See the longdesc attribute definition in HTML 4.0.

setLongDesc

public void setLongDesc(String longDesc)

getSrc

public String getSrc()
URI designating the source of this image. See the src attribute definition in HTML 4.0.

setSrc

public void setSrc(String src)

getUseMap

public String getUseMap()
Use client-side image map. See the usemap attribute definition in HTML 4.0.

setUseMap

public void setUseMap(String useMap)

getVspace

public String getVspace()
Vertical space above and below this image. See the vspace attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setVspace

public void setVspace(String vspace)

getWidth

public String getWidth()
Override width. See the width attribute definition in HTML 4.0.

setWidth

public void setWidth(String width)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLInputElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLInputElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLInputElement
extends HTMLElement

Form control. Note. Depending upon the environment in which the page is being viewed, the value property may be read-only for the file upload input type. For the "password" input type, the actual value returned may be masked to prevent unauthorized use. See the INPUT element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
void | blur() Removes keyboard focus from this element.
void | click() Simulate a mouse-click.
void | focus() Gives keyboard focus to this element.
String | getAccept() A comma-separated list of content types that a server processing this form will handle correctly.
String | getAccessKey() A single character access key to give access to the form control.
String | getAlign() Aligns this object (vertically or horizontally) with respect to its surrounding text.
String | getAlt() Alternate text for user agents not rendering the normal content of this element.
boolean | getChecked() When the type attribute of the element has the value "Radio" or "Checkbox", this represents the current state of the form control, in an interactive user agent.
boolean | getDefaultChecked() When type has the value "Radio" or "Checkbox", this represents the HTML checked attribute of the element.
String | getDefaultValue() When the type attribute of the element has the value "Text", "File" or "Password", this represents the HTML value attribute of the element.
boolean | getDisabled() The control is unavailable in this context.
HTMLFormElement | getForm() Returns the FORM element containing this control.
int | getMaxLength() Maximum number of characters for text fields, when type has the value "Text" or "Password".
String | getName() Form control or object name when submitted with a form.
boolean | getReadOnly() This control is read-only.
String | getSize() Size information.
String | getSrc() When the type attribute has the value "Image", this attribute specifies the location of the image to be used to decorate the graphical submit button.
int | getTabIndex() Index that represents the element's position in the tabbing order.
String | getType() The type of control created.
String | getUseMap() Use client-side image map.
String | getValue() When the type attribute of the element has the value "Text", "File" or "Password", this represents the current contents of the corresponding form control, in an interactive user agent.
void | select() Select the contents of the text area.
void | setAccept(String accept)
void | setAccessKey(String accessKey)
void | setAlign(String align)
void | setAlt(String alt)
void | setChecked(boolean checked)
void | setDefaultChecked(boolean defaultChecked)
void | setDefaultValue(String defaultValue)
void | setDisabled(boolean disabled)
void | setMaxLength(int maxLength)
void | setName(String name)
void | setReadOnly(boolean readOnly)
void | setSize(String size)
void | setSrc(String src)
void | setTabIndex(int tabIndex)
void | setUseMap(String useMap)
void | setValue(String value)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getDefaultValue

public String getDefaultValue()
When the type attribute of the element has the value "Text", "File" or "Password", this represents the HTML value attribute of the element. The value of this attribute does not change if the contents of the corresponding form control, in an interactive user agent, changes. Changing this attribute, however, resets the contents of the form control. See the value attribute definition in HTML 4.0.

setDefaultValue

public void setDefaultValue(String defaultValue)

getDefaultChecked

public boolean getDefaultChecked()
When type has the value "Radio" or "Checkbox", this represents the HTML checked attribute of the element. The value of this attribute does not change if the state of the corresponding form control, in an interactive user agent, changes. Changes to this attribute, however, resets the state of the form control. See the checked attribute definition in HTML 4.0.

setDefaultChecked

public void setDefaultChecked(boolean defaultChecked)

getForm

public HTMLFormElement getForm()
Returns the FORM element containing this control. Returns null if this control is not within the context of a form.

getAccept

public String getAccept()
A comma-separated list of content types that a server processing this form will handle correctly. See the accept attribute definition in HTML 4.0.

setAccept

public void setAccept(String accept)

getAccessKey

public String getAccessKey()
A single character access key to give access to the form control. See the accesskey attribute definition in HTML 4.0.

setAccessKey

public void setAccessKey(String accessKey)

getAlign

public String getAlign()
Aligns this object (vertically or horizontally) with respect to its surrounding text. See the align attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setAlign

public void setAlign(String align)

getAlt

public String getAlt()
Alternate text for user agents not rendering the normal content of this element. See the alt attribute definition in HTML 4.0.

setAlt

public void setAlt(String alt)

getChecked

public boolean getChecked()
When the type attribute of the element has the value "Radio" or "Checkbox", this represents the current state of the form control, in an interactive user agent. Changes to this attribute change the state of the form control, but do not change the value of the HTML value attribute of the element.

setChecked

public void setChecked(boolean checked)

getDisabled

public boolean getDisabled()
The control is unavailable in this context. See the disabled attribute definition in HTML 4.0.

setDisabled

public void setDisabled(boolean disabled)

getMaxLength

public int getMaxLength()
Maximum number of characters for text fields, when type has the value "Text" or "Password". See the maxlength attribute definition in HTML 4.0.

setMaxLength

public void setMaxLength(int maxLength)

getName

public String getName()
Form control or object name when submitted with a form. See the name attribute definition in HTML 4.0.

setName

public void setName(String name)

getReadOnly

public boolean getReadOnly()
This control is read-only. Relevant only when type has the value "Text" or "Password". See the readonly attribute definition in HTML 4.0.

setReadOnly

public void setReadOnly(boolean readOnly)

getSize

public String getSize()
Size information. The precise meaning is specific to each type of field. See the size attribute definition in HTML 4.0.

setSize

public void setSize(String size)

getSrc

public String getSrc()
When the type attribute has the value "Image", this attribute specifies the location of the image to be used to decorate the graphical submit button. See the src attribute definition in HTML 4.0.

setSrc

public void setSrc(String src)

getTabIndex

public int getTabIndex()
Index that represents the element's position in the tabbing order. See the tabindex attribute definition in HTML 4.0.

setTabIndex

public void setTabIndex(int tabIndex)

getType

public String getType()
The type of control created. See the type attribute definition in HTML 4.0.

getUseMap

public String getUseMap()
Use client-side image map. See the usemap attribute definition in HTML 4.0.

setUseMap

public void setUseMap(String useMap)

getValue

public String getValue()
When the type attribute of the element has the value "Text", "File" or "Password", this represents the current contents of the corresponding form control, in an interactive user agent. Changing this attribute changes the contents of the form control, but does not change the value of the HTML value attribute of the element. When the type attribute of the element has the value "Button", "Hidden", "Submit", "Reset", "Image", "Checkbox" or "Radio", this represents the HTML value attribute of the element. See the value attribute definition in HTML 4.0.

setValue

public void setValue(String value)

blur

public void blur()
Removes keyboard focus from this element.

focus

public void focus()
Gives keyboard focus to this element.

select

public void select()
Select the contents of the text area. For INPUT elements whose type attribute has one of the following values: "Text", "File", or "Password".

click

public void click()
Simulate a mouse-click. For INPUT elements whose type attribute has one of the following values: "Button", "Checkbox", "Radio", "Reset", or "Submit".

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLIsIndexElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLIsIndexElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLIsIndexElement
extends HTMLElement

This element is used for single-line text input. See the ISINDEX element definition in HTML 4.0. This element is deprecated in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
HTMLFormElement | getForm() Returns the FORM element containing this control.
String | getPrompt() The prompt message.
void | setPrompt(String prompt)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getForm

public HTMLFormElement getForm()
Returns the FORM element containing this control. Returns null if this control is not within the context of a form.

getPrompt

public String getPrompt()
The prompt message. See the prompt attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setPrompt

public void setPrompt(String prompt)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLLabelElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLLabelElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLLabelElement
extends HTMLElement

Form field label text. See the LABEL element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getAccessKey() A single character access key to give access to the form control.
HTMLFormElement | getForm() Returns the FORM element containing this control.
String | getHtmlFor() This attribute links this label with another form control by id attribute.
void | setAccessKey(String accessKey)
void | setHtmlFor(String htmlFor)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getForm

public HTMLFormElement getForm()
Returns the FORM element containing this control. Returns null if this control is not within the context of a form.

getAccessKey

public String getAccessKey()
A single character access key to give access to the form control. See the accesskey attribute definition in HTML 4.0.

setAccessKey

public void setAccessKey(String accessKey)

getHtmlFor

public String getHtmlFor()
This attribute links this label with another form control by id attribute. See the for attribute definition in HTML 4.0.

setHtmlFor

public void setHtmlFor(String htmlFor)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLLegendElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLLegendElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLLegendElement
extends HTMLElement

Provides a caption for a FIELDSET grouping. See the LEGEND element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getAccessKey() A single character access key to give access to the form control.
String | getAlign() Text alignment relative to FIELDSET .
HTMLFormElement | getForm() Returns the FORM element containing this control.
void | setAccessKey(String accessKey)
void | setAlign(String align)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getForm

public HTMLFormElement getForm()
Returns the FORM element containing this control. Returns null if this control is not within the context of a form.

getAccessKey

public String getAccessKey()
A single character access key to give access to the form control. See the accesskey attribute definition in HTML 4.0.

setAccessKey

public void setAccessKey(String accessKey)

getAlign

public String getAlign()
Text alignment relative to FIELDSET . See the align attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setAlign

public void setAlign(String align)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLLIElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLLIElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLLIElement
extends HTMLElement

List item. See the LI element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getType() List item bullet style.
int | getValue() Reset sequence number when used in OL .
void | setType(String type)
void | setValue(int value)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getType

public String getType()
List item bullet style. See the type attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setType

public void setType(String type)

getValue

public int getValue()
Reset sequence number when used in OL . See the value attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setValue

public void setValue(int value)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLLinkElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLLinkElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLLinkElement
extends HTMLElement

The LINK element specifies a link to an external resource, and defines this document's relationship to that resource (or vice versa). See the LINK element definition in HTML 4.0 (see also the LinkStyle interface in the module).

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getCharset() The character encoding of the resource being linked to.
boolean | getDisabled() Enables/disables the link.
String | getHref() The URI of the linked resource.
String | getHreflang() Language code of the linked resource.
String | getMedia() Designed for use with one or more target media.
String | getRel() Forward link type.
String | getRev() Reverse link type.
String | getTarget() Frame to render the resource in.
String | getType() Advisory content type.
void | setCharset(String charset)
void | setDisabled(boolean disabled)
void | setHref(String href)
void | setHreflang(String hreflang)
void | setMedia(String media)
void | setRel(String rel)
void | setRev(String rev)
void | setTarget(String target)
void | setType(String type)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getDisabled

public boolean getDisabled()
Enables/disables the link. This is currently only used for style sheet links, and may be used to activate or deactivate style sheets.

setDisabled

public void setDisabled(boolean disabled)

getCharset

public String getCharset()
The character encoding of the resource being linked to. See the charset attribute definition in HTML 4.0.

setCharset

public void setCharset(String charset)

getHref

public String getHref()
The URI of the linked resource. See the href attribute definition in HTML 4.0.

setHref

public void setHref(String href)

getHreflang

public String getHreflang()
Language code of the linked resource. See the hreflang attribute definition in HTML 4.0.

setHreflang

public void setHreflang(String hreflang)

getMedia

public String getMedia()
Designed for use with one or more target media. See the media attribute definition in HTML 4.0.

setMedia

public void setMedia(String media)

getRel

public String getRel()
Forward link type. See the rel attribute definition in HTML 4.0.

setRel

public void setRel(String rel)

getRev

public String getRev()
Reverse link type. See the rev attribute definition in HTML 4.0.

setRev

public void setRev(String rev)

getTarget

public String getTarget()
Frame to render the resource in. See the target attribute definition in HTML 4.0.

setTarget

public void setTarget(String target)

getType

public String getType()
Advisory content type. See the type attribute definition in HTML 4.0.

setType

public void setType(String type)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLMapElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLMapElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLMapElement
extends HTMLElement

Client-side image map. See the MAP element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
HTMLCollection | getAreas() The list of areas defined for the image map.
String | getName() Names the map (for use with usemap ).
void | setName(String name)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getAreas

public HTMLCollection getAreas()
The list of areas defined for the image map.

getName

public String getName()
Names the map (for use with usemap ). See the name attribute definition in HTML 4.0.

setName

public void setName(String name)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLMenuElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLMenuElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLMenuElement
extends HTMLElement

Menu list. See the MENU element definition in HTML 4.0. This element is deprecated in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
boolean | getCompact() Reduce spacing between list items.
void | setCompact(boolean compact)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getCompact

public boolean getCompact()
Reduce spacing between list items. See the compact attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setCompact

public void setCompact(boolean compact)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLMetaElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLMetaElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLMetaElement
extends HTMLElement

This contains generic meta-information about the document. See the META element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getContent() Associated information.
String | getHttpEquiv() HTTP response header name.
String | getName() Meta information name.
String | getScheme() Select form of content.
void | setContent(String content)
void | setHttpEquiv(String httpEquiv)
void | setName(String name)
void | setScheme(String scheme)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getContent

public String getContent()
Associated information. See the content attribute definition in HTML 4.0.

setContent

public void setContent(String content)

getHttpEquiv

public String getHttpEquiv()
HTTP response header name. See the http-equiv attribute definition in HTML 4.0.

setHttpEquiv

public void setHttpEquiv(String httpEquiv)

getName

public String getName()
Meta information name. See the name attribute definition in HTML 4.0.

setName

public void setName(String name)

getScheme

public String getScheme()
Select form of content. See the scheme attribute definition in HTML 4.0.

setScheme

public void setScheme(String scheme)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLModElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLModElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLModElement
extends HTMLElement

Notice of modification to part of a document. See the INS and DEL element definitions in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getCite() A URI designating a document that describes the reason for the change.
String | getDateTime() The date and time of the change.
void | setCite(String cite)
void | setDateTime(String dateTime)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getCite

public String getCite()
A URI designating a document that describes the reason for the change. See the cite attribute definition in HTML 4.0.

setCite

public void setCite(String cite)

getDateTime

public String getDateTime()
The date and time of the change. See the datetime attribute definition in HTML 4.0.

setDateTime

public void setDateTime(String dateTime)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLObjectElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLObjectElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLObjectElement
extends HTMLElement

Generic embedded object. Note. In principle, all properties on the object element are read-write but in some environments some properties may be read-only once the underlying object is instantiated. See the OBJECT element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getAlign() Aligns this object (vertically or horizontally) with respect to its surrounding text.
String | getArchive() Space-separated list of archives.
String | getBorder() Width of border around the object.
String | getCode() Applet class file.
String | getCodeBase() Base URI for classid , data , and archive attributes.
String | getCodeType() Content type for data downloaded via classid attribute.
Document | getContentDocument() The document this object contains, if there is any and it is available, or null otherwise.
String | getData() A URI specifying the location of the object's data.
boolean | getDeclare() Declare (for future reference), but do not instantiate, this object.
HTMLFormElement | getForm() Returns the FORM element containing this control.
String | getHeight() Override height.
String | getHspace() Horizontal space to the left and right of this image, applet, or object.
String | getName() Form control or object name when submitted with a form.
String | getStandby() Message to render while loading the object.
int | getTabIndex() Index that represents the element's position in the tabbing order.
String | getType() Content type for data downloaded via data attribute.
String | getUseMap() Use client-side image map.
String | getVspace() Vertical space above and below this image, applet, or object.
String | getWidth() Override width.
void | setAlign(String align)
void | setArchive(String archive)
void | setBorder(String border)
void | setCode(String code)
void | setCodeBase(String codeBase)
void | setCodeType(String codeType)
void | setData(String data)
void | setDeclare(boolean declare)
void | setHeight(String height)
void | setHspace(String hspace)
void | setName(String name)
void | setStandby(String standby)
void | setTabIndex(int tabIndex)
void | setType(String type)
void | setUseMap(String useMap)
void | setVspace(String vspace)
void | setWidth(String width)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getForm

public HTMLFormElement getForm()
Returns the FORM element containing this control. Returns null if this control is not within the context of a form.

getCode

public String getCode()
Applet class file. See the code attribute for HTMLAppletElement.

setCode

public void setCode(String code)

getAlign

public String getAlign()
Aligns this object (vertically or horizontally) with respect to its surrounding text. See the align attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setAlign

public void setAlign(String align)

getArchive

public String getArchive()
Space-separated list of archives. See the archive attribute definition in HTML 4.0.

setArchive

public void setArchive(String archive)

getBorder

public String getBorder()
Width of border around the object. See the border attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setBorder

public void setBorder(String border)

getCodeBase

public String getCodeBase()
Base URI for classid , data , and archive attributes. See the codebase attribute definition in HTML 4.0.

setCodeBase

public void setCodeBase(String codeBase)

getCodeType

public String getCodeType()
Content type for data downloaded via classid attribute. See the codetype attribute definition in HTML 4.0.

setCodeType

public void setCodeType(String codeType)

getData

public String getData()
A URI specifying the location of the object's data. See the data attribute definition in HTML 4.0.

setData

public void setData(String data)

getDeclare

public boolean getDeclare()
Declare (for future reference), but do not instantiate, this object. See the declare attribute definition in HTML 4.0.

setDeclare

public void setDeclare(boolean declare)

getHeight

public String getHeight()
Override height. See the height attribute definition in HTML 4.0.

setHeight

public void setHeight(String height)

getHspace

public String getHspace()
Horizontal space to the left and right of this image, applet, or object. See the hspace attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setHspace

public void setHspace(String hspace)

getName

public String getName()
Form control or object name when submitted with a form. See the name attribute definition in HTML 4.0.

setName

public void setName(String name)

getStandby

public String getStandby()
Message to render while loading the object. See the standby attribute definition in HTML 4.0.

setStandby

public void setStandby(String standby)

getTabIndex

public int getTabIndex()
Index that represents the element's position in the tabbing order. See the tabindex attribute definition in HTML 4.0.

setTabIndex

public void setTabIndex(int tabIndex)

getType

public String getType()
Content type for data downloaded via data attribute. See the type attribute definition in HTML 4.0.

setType

public void setType(String type)

getUseMap

public String getUseMap()
Use client-side image map. See the usemap attribute definition in HTML 4.0.

setUseMap

public void setUseMap(String useMap)

getVspace

public String getVspace()
Vertical space above and below this image, applet, or object. See the vspace attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setVspace

public void setVspace(String vspace)

getWidth

public String getWidth()
Override width. See the width attribute definition in HTML 4.0.

setWidth

public void setWidth(String width)

getContentDocument

public Document getContentDocument()
The document this object contains, if there is any and it is available, or null otherwise.

Since:
DOM Level 2
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLOListElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLOListElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLOListElement
extends HTMLElement

Ordered list. See the OL element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
boolean | getCompact() Reduce spacing between list items.
int | getStart() Starting sequence number.
String | getType() Numbering style.
void | setCompact(boolean compact)
void | setStart(int start)
void | setType(String type)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getCompact

public boolean getCompact()
Reduce spacing between list items. See the compact attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setCompact

public void setCompact(boolean compact)

getStart

public int getStart()
Starting sequence number. See the start attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setStart

public void setStart(int start)

getType

public String getType()
Numbering style. See the type attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setType

public void setType(String type)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLOptGroupElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLOptGroupElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLOptGroupElement
extends HTMLElement

Group options together in logical subdivisions. See the OPTGROUP element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
boolean | getDisabled() The control is unavailable in this context.
String | getLabel() Assigns a label to this option group.
void | setDisabled(boolean disabled)
void | setLabel(String label)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getDisabled

public boolean getDisabled()
The control is unavailable in this context. See the disabled attribute definition in HTML 4.0.

setDisabled

public void setDisabled(boolean disabled)

getLabel

public String getLabel()
Assigns a label to this option group. See the label attribute definition in HTML 4.0.

setLabel

public void setLabel(String label)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLOptionElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLOptionElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLOptionElement
extends HTMLElement

A selectable choice. See the OPTION element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
boolean | getDefaultSelected() Represents the value of the HTML selected attribute.
boolean | getDisabled() The control is unavailable in this context.
HTMLFormElement | getForm() Returns the FORM element containing this control.
int | getIndex() The index of this OPTION in its parent SELECT , starting from 0.
String | getLabel() Option label for use in hierarchical menus.
boolean | getSelected() Represents the current state of the corresponding form control, in an interactive user agent.
String | getText() The text contained within the option element.
String | getValue() The current form control value.
void | setDefaultSelected(boolean defaultSelected)
void | setDisabled(boolean disabled)
void | setLabel(String label)
void | setSelected(boolean selected)
void | setValue(String value)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getForm

public HTMLFormElement getForm()
Returns the FORM element containing this control. Returns null if this control is not within the context of a form.

getDefaultSelected

public boolean getDefaultSelected()
Represents the value of the HTML selected attribute. The value of this attribute does not change if the state of the corresponding form control, in an interactive user agent, changes. Changing defaultSelected , however, resets the state of the form control. See the selected attribute definition in HTML 4.0.

setDefaultSelected

public void setDefaultSelected(boolean defaultSelected)

getText

public String getText()
The text contained within the option element.

getIndex

public int getIndex()
The index of this OPTION in its parent SELECT , starting from 0.

getDisabled

public boolean getDisabled()
The control is unavailable in this context. See the disabled attribute definition in HTML 4.0.

setDisabled

public void setDisabled(boolean disabled)

getLabel

public String getLabel()
Option label for use in hierarchical menus. See the label attribute definition in HTML 4.0.

setLabel

public void setLabel(String label)

getSelected

public boolean getSelected()
Represents the current state of the corresponding form control, in an interactive user agent. Changing this attribute changes the state of the form control, but does not change the value of the HTML selected attribute of the element.

setSelected

public void setSelected(boolean selected)

getValue

public String getValue()
The current form control value. See the value attribute definition in HTML 4.0.

setValue

public void setValue(String value)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLParagraphElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLParagraphElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLParagraphElement
extends HTMLElement

Paragraphs. See the P element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getAlign() Horizontal text alignment.
void | setAlign(String align)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getAlign

public String getAlign()
Horizontal text alignment. See the align attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setAlign

public void setAlign(String align)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLParamElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLParamElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLParamElement
extends HTMLElement

Parameters fed to the OBJECT element. See the PARAM element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getName() The name of a run-time parameter.
String | getType() Content type for the value attribute when valuetype has the value "ref".
String | getValue() The value of a run-time parameter.
String | getValueType() Information about the meaning of the value attribute value.
void | setName(String name)
void | setType(String type)
void | setValue(String value)
void | setValueType(String valueType)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getName

public String getName()
The name of a run-time parameter. See the name attribute definition in HTML 4.0.

setName

public void setName(String name)

getType

public String getType()
Content type for the value attribute when valuetype has the value "ref". See the type attribute definition in HTML 4.0.

setType

public void setType(String type)

getValue

public String getValue()
The value of a run-time parameter. See the value attribute definition in HTML 4.0.

setValue

public void setValue(String value)

getValueType

public String getValueType()
Information about the meaning of the value attribute value. See the valuetype attribute definition in HTML 4.0.

setValueType

public void setValueType(String valueType)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLPreElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLPreElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLPreElement
extends HTMLElement

Preformatted text. See the PRE element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
int | getWidth() Fixed width for content.
void | setWidth(int width)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getWidth

public int getWidth()
Fixed width for content. See the width attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setWidth

public void setWidth(int width)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLQuoteElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLQuoteElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLQuoteElement
extends HTMLElement

For the Q and BLOCKQUOTE elements. See the Q element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getCite() A URI designating a source document or message.
void | setCite(String cite)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getCite

public String getCite()
A URI designating a source document or message. See the cite attribute definition in HTML 4.0.

setCite

public void setCite(String cite)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLScriptElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLScriptElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLScriptElement
extends HTMLElement

Script statements. See the SCRIPT element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getCharset() The character encoding of the linked resource.
boolean | getDefer() Indicates that the user agent can defer processing of the script.
String | getEvent() Reserved for future use.
String | getHtmlFor() Reserved for future use.
String | getSrc() URI designating an external script.
String | getText() The script content of the element.
String | getType() The content type of the script language.
void | setCharset(String charset)
void | setDefer(boolean defer)
void | setEvent(String event)
void | setHtmlFor(String htmlFor)
void | setSrc(String src)
void | setText(String text)
void | setType(String type)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getText

public String getText()
The script content of the element.

setText

public void setText(String text)

getHtmlFor

public String getHtmlFor()
Reserved for future use.

setHtmlFor

public void setHtmlFor(String htmlFor)

getEvent

public String getEvent()
Reserved for future use.

setEvent

public void setEvent(String event)

getCharset

public String getCharset()
The character encoding of the linked resource. See the charset attribute definition in HTML 4.0.

setCharset

public void setCharset(String charset)

getDefer

public boolean getDefer()
Indicates that the user agent can defer processing of the script. See the defer attribute definition in HTML 4.0.

setDefer

public void setDefer(boolean defer)

getSrc

public String getSrc()
URI designating an external script. See the src attribute definition in HTML 4.0.

setSrc

public void setSrc(String src)

getType

public String getType()
The content type of the script language. See the type attribute definition in HTML 4.0.

setType

public void setType(String type)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLSelectElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLSelectElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLSelectElement
extends HTMLElement

The select element allows the selection of an option. The contained options can be directly accessed through the select element as a collection. See the SELECT element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
void | add(HTMLElement element, HTMLElement before) Add a new element to the collection of OPTION elements for this SELECT .
void | blur() Removes keyboard focus from this element.
void | focus() Gives keyboard focus to this element.
boolean | getDisabled() The control is unavailable in this context.
HTMLFormElement | getForm() Returns the FORM element containing this control.
int | getLength() The number of options in this SELECT .
boolean | getMultiple() If true, multiple OPTION elements may be selected in this SELECT .
String | getName() Form control or object name when submitted with a form.
HTMLCollection | getOptions() The collection of OPTION elements contained by this element.
int | getSelectedIndex() The ordinal index of the selected option, starting from 0.
int | getSize() Number of visible rows.
int | getTabIndex() Index that represents the element's position in the tabbing order.
String | getType() The type of this form control.
String | getValue() The current form control value.
void | remove(int index) Remove an element from the collection of OPTION elements for this SELECT .
void | setDisabled(boolean disabled)
void | setMultiple(boolean multiple)
void | setName(String name)
void | setSelectedIndex(int selectedIndex)
void | setSize(int size)
void | setTabIndex(int tabIndex)
void | setValue(String value)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getType

public String getType()
The type of this form control. This is the string "select-multiple" when the multiple attribute is true and the string "select-one" when false .

getSelectedIndex

public int getSelectedIndex()
The ordinal index of the selected option, starting from 0. The value -1 is returned if no element is selected. If multiple options are selected, the index of the first selected option is returned.

setSelectedIndex

public void setSelectedIndex(int selectedIndex)

getValue

public String getValue()
The current form control value.

setValue

public void setValue(String value)

getLength

public int getLength()
The number of options in this SELECT .

getForm

public HTMLFormElement getForm()
Returns the FORM element containing this control. Returns null if this control is not within the context of a form.

getOptions

public HTMLCollection getOptions()
The collection of OPTION elements contained by this element.

getDisabled

public boolean getDisabled()
The control is unavailable in this context. See the disabled attribute definition in HTML 4.0.

setDisabled

public void setDisabled(boolean disabled)

getMultiple

public boolean getMultiple()
If true, multiple OPTION elements may be selected in this SELECT . See the multiple attribute definition in HTML 4.0.

setMultiple

public void setMultiple(boolean multiple)

getName

public String getName()
Form control or object name when submitted with a form. See the name attribute definition in HTML 4.0.

setName

public void setName(String name)

getSize

public int getSize()
Number of visible rows. See the size attribute definition in HTML 4.0.

setSize

public void setSize(int size)

getTabIndex

public int getTabIndex()
Index that represents the element's position in the tabbing order. See the tabindex attribute definition in HTML 4.0.

setTabIndex

public void setTabIndex(int tabIndex)

add

public void add(HTMLElement element,
                HTMLElement before)
         throws DOMException
Add a new element to the collection of OPTION elements for this SELECT . This method is the equivalent of the appendChild method of the Node interface if the before parameter is null . It is equivalent to the insertBefore method on the parent of before in all other cases.

Parameters:
element - The element to add.
before - The element to insert before, or null for the tail of the list.
Throws:
DOMException - NOT_FOUND_ERR: Raised if before is not a descendant of the SELECT element.

remove

public void remove(int index)
Remove an element from the collection of OPTION elements for this SELECT . Does nothing if no element has the given index.

Parameters:
index - The index of the item to remove, starting from 0.

blur

public void blur()
Removes keyboard focus from this element.

focus

public void focus()
Gives keyboard focus to this element.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLStyleElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLStyleElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLStyleElement
extends HTMLElement

Style information. See the STYLE element definition in HTML 4.0, the module and the LinkStyle interface in the module.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
boolean | getDisabled() Enables/disables the style sheet.
String | getMedia() Designed for use with one or more target media.
String | getType() The content type pf the style sheet language.
void | setDisabled(boolean disabled)
void | setMedia(String media)
void | setType(String type)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getDisabled

public boolean getDisabled()
Enables/disables the style sheet.

setDisabled

public void setDisabled(boolean disabled)

getMedia

public String getMedia()
Designed for use with one or more target media. See the media attribute definition in HTML 4.0.

setMedia

public void setMedia(String media)

getType

public String getType()
The content type pf the style sheet language. See the type attribute definition in HTML 4.0.

setType

public void setType(String type)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLTableCaptionElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLTableCaptionElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLTableCaptionElement
extends HTMLElement

Table caption See the CAPTION element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getAlign() Caption alignment with respect to the table.
void | setAlign(String align)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getAlign

public String getAlign()
Caption alignment with respect to the table. See the align attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setAlign

public void setAlign(String align)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLTableCellElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLTableCellElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLTableCellElement
extends HTMLElement

The object used to represent the TH and TD elements. See the TD element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getAbbr() Abbreviation for header cells.
String | getAlign() Horizontal alignment of data in cell.
String | getAxis() Names group of related headers.
String | getBgColor() Cell background color.
int | getCellIndex() The index of this cell in the row, starting from 0.
String | getCh() Alignment character for cells in a column.
String | getChOff() Offset of alignment character.
int | getColSpan() Number of columns spanned by cell.
String | getHeaders() List of id attribute values for header cells.
String | getHeight() Cell height.
boolean | getNoWrap() Suppress word wrapping.
int | getRowSpan() Number of rows spanned by cell.
String | getScope() Scope covered by header cells.
String | getVAlign() Vertical alignment of data in cell.
String | getWidth() Cell width.
void | setAbbr(String abbr)
void | setAlign(String align)
void | setAxis(String axis)
void | setBgColor(String bgColor)
void | setCh(String ch)
void | setChOff(String chOff)
void | setColSpan(int colSpan)
void | setHeaders(String headers)
void | setHeight(String height)
void | setNoWrap(boolean noWrap)
void | setRowSpan(int rowSpan)
void | setScope(String scope)
void | setVAlign(String vAlign)
void | setWidth(String width)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getCellIndex

public int getCellIndex()
The index of this cell in the row, starting from 0. This index is in document tree order and not display order.

getAbbr

public String getAbbr()
Abbreviation for header cells. See the abbr attribute definition in HTML 4.0.

setAbbr

public void setAbbr(String abbr)

getAlign

public String getAlign()
Horizontal alignment of data in cell. See the align attribute definition in HTML 4.0.

setAlign

public void setAlign(String align)

getAxis

public String getAxis()
Names group of related headers. See the axis attribute definition in HTML 4.0.

setAxis

public void setAxis(String axis)

getBgColor

public String getBgColor()
Cell background color. See the bgcolor attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setBgColor

public void setBgColor(String bgColor)

getCh

public String getCh()
Alignment character for cells in a column. See the char attribute definition in HTML 4.0.

setCh

public void setCh(String ch)

getChOff

public String getChOff()
Offset of alignment character. See the charoff attribute definition in HTML 4.0.

setChOff

public void setChOff(String chOff)

getColSpan

public int getColSpan()
Number of columns spanned by cell. See the colspan attribute definition in HTML 4.0.

setColSpan

public void setColSpan(int colSpan)

getHeaders

public String getHeaders()
List of id attribute values for header cells. See the headers attribute definition in HTML 4.0.

setHeaders

public void setHeaders(String headers)

getHeight

public String getHeight()
Cell height. See the height attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setHeight

public void setHeight(String height)

getNoWrap

public boolean getNoWrap()
Suppress word wrapping. See the nowrap attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setNoWrap

public void setNoWrap(boolean noWrap)

getRowSpan

public int getRowSpan()
Number of rows spanned by cell. See the rowspan attribute definition in HTML 4.0.

setRowSpan

public void setRowSpan(int rowSpan)

getScope

public String getScope()
Scope covered by header cells. See the scope attribute definition in HTML 4.0.

setScope

public void setScope(String scope)

getVAlign

public String getVAlign()
Vertical alignment of data in cell. See the valign attribute definition in HTML 4.0.

setVAlign

public void setVAlign(String vAlign)

getWidth

public String getWidth()
Cell width. See the width attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setWidth

public void setWidth(String width)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLTableColElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLTableColElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLTableColElement
extends HTMLElement

Regroups the COL and COLGROUP elements. See the COL element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getAlign() Horizontal alignment of cell data in column.
String | getCh() Alignment character for cells in a column.
String | getChOff() Offset of alignment character.
int | getSpan() Indicates the number of columns in a group or affected by a grouping.
String | getVAlign() Vertical alignment of cell data in column.
String | getWidth() Default column width.
void | setAlign(String align)
void | setCh(String ch)
void | setChOff(String chOff)
void | setSpan(int span)
void | setVAlign(String vAlign)
void | setWidth(String width)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getAlign

public String getAlign()
Horizontal alignment of cell data in column. See the align attribute definition in HTML 4.0.

setAlign

public void setAlign(String align)

getCh

public String getCh()
Alignment character for cells in a column. See the char attribute definition in HTML 4.0.

setCh

public void setCh(String ch)

getChOff

public String getChOff()
Offset of alignment character. See the charoff attribute definition in HTML 4.0.

setChOff

public void setChOff(String chOff)

getSpan

public int getSpan()
Indicates the number of columns in a group or affected by a grouping. See the span attribute definition in HTML 4.0.

setSpan

public void setSpan(int span)

getVAlign

public String getVAlign()
Vertical alignment of cell data in column. See the valign attribute definition in HTML 4.0.

setVAlign

public void setVAlign(String vAlign)

getWidth

public String getWidth()
Default column width. See the width attribute definition in HTML 4.0.

setWidth

public void setWidth(String width)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLTableElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLTableElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLTableElement
extends HTMLElement

The create* and delete* methods on the table allow authors to construct and modify tables. HTML 4.0 specifies that only one of each of the CAPTION , THEAD , and TFOOT elements may exist in a table. Therefore, if one exists, and the createTHead() or createTFoot() method is called, the method returns the existing THead or TFoot element. See the TABLE element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
HTMLElement | createCaption() Create a new table caption object or return an existing one.
HTMLElement | createTFoot() Create a table footer row or return an existing one.
HTMLElement | createTHead() Create a table header row or return an existing one.
void | deleteCaption() Delete the table caption, if one exists.
void | deleteRow(int index) Delete a table row.
void | deleteTFoot() Delete the footer from the table, if one exists.
void | deleteTHead() Delete the header from the table, if one exists.
String | getAlign() Specifies the table's position with respect to the rest of the document.
String | getBgColor() Cell background color.
String | getBorder() The width of the border around the table.
HTMLTableCaptionElement | getCaption() Returns the table's CAPTION , or void if none exists.
String | getCellPadding() Specifies the horizontal and vertical space between cell content and cell borders.
String | getCellSpacing() Specifies the horizontal and vertical separation between cells.
String | getFrame() Specifies which external table borders to render.
HTMLCollection | getRows() Returns a collection of all the rows in the table, including all in THEAD , TFOOT , all TBODY elements.
String | getRules() Specifies which internal table borders to render.
String | getSummary() Description about the purpose or structure of a table.
HTMLCollection | getTBodies() Returns a collection of the defined table bodies.
HTMLTableSectionElement | getTFoot() Returns the table's TFOOT , or null if none exists.
HTMLTableSectionElement | getTHead() Returns the table's THEAD , or null if none exists.
String | getWidth() Specifies the desired table width.
HTMLElement | insertRow(int index) Insert a new empty row in the table.
void | setAlign(String align)
void | setBgColor(String bgColor)
void | setBorder(String border)
void | setCaption(HTMLTableCaptionElement caption)
void | setCellPadding(String cellPadding)
void | setCellSpacing(String cellSpacing)
void | setFrame(String frame)
void | setRules(String rules)
void | setSummary(String summary)
void | setTFoot(HTMLTableSectionElement tFoot)
void | setTHead(HTMLTableSectionElement tHead)
void | setWidth(String width)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getCaption

public HTMLTableCaptionElement getCaption()
Returns the table's CAPTION , or void if none exists.

setCaption

public void setCaption(HTMLTableCaptionElement caption)

getTHead

public HTMLTableSectionElement getTHead()
Returns the table's THEAD , or null if none exists.

setTHead

public void setTHead(HTMLTableSectionElement tHead)

getTFoot

public HTMLTableSectionElement getTFoot()
Returns the table's TFOOT , or null if none exists.

setTFoot

public void setTFoot(HTMLTableSectionElement tFoot)

getRows

public HTMLCollection getRows()
Returns a collection of all the rows in the table, including all in THEAD , TFOOT , all TBODY elements.

getTBodies

public HTMLCollection getTBodies()
Returns a collection of the defined table bodies.

getAlign

public String getAlign()
Specifies the table's position with respect to the rest of the document. See the align attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setAlign

public void setAlign(String align)

getBgColor

public String getBgColor()
Cell background color. See the bgcolor attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setBgColor

public void setBgColor(String bgColor)

getBorder

public String getBorder()
The width of the border around the table. See the border attribute definition in HTML 4.0.

setBorder

public void setBorder(String border)

getCellPadding

public String getCellPadding()
Specifies the horizontal and vertical space between cell content and cell borders. See the cellpadding attribute definition in HTML 4.0.

setCellPadding

public void setCellPadding(String cellPadding)

getCellSpacing

public String getCellSpacing()
Specifies the horizontal and vertical separation between cells. See the cellspacing attribute definition in HTML 4.0.

setCellSpacing

public void setCellSpacing(String cellSpacing)

getFrame

public String getFrame()
Specifies which external table borders to render. See the frame attribute definition in HTML 4.0.

setFrame

public void setFrame(String frame)

getRules

public String getRules()
Specifies which internal table borders to render. See the rules attribute definition in HTML 4.0.

setRules

public void setRules(String rules)

getSummary

public String getSummary()
Description about the purpose or structure of a table. See the summary attribute definition in HTML 4.0.

setSummary

public void setSummary(String summary)

getWidth

public String getWidth()
Specifies the desired table width. See the width attribute definition in HTML 4.0.

setWidth

public void setWidth(String width)

createTHead

public HTMLElement createTHead()
Create a table header row or return an existing one.

Returns:
A new table header element (THEAD ).

deleteTHead

public void deleteTHead()
Delete the header from the table, if one exists.

createTFoot

public HTMLElement createTFoot()
Create a table footer row or return an existing one.

Returns:
A footer element (TFOOT ).

deleteTFoot

public void deleteTFoot()
Delete the footer from the table, if one exists.

createCaption

public HTMLElement createCaption()
Create a new table caption object or return an existing one.

Returns:
A CAPTION element.

deleteCaption

public void deleteCaption()
Delete the table caption, if one exists.

insertRow

public HTMLElement insertRow(int index)
                      throws DOMException
Insert a new empty row in the table. The new row is inserted immediately before and in the same section as the current index th row in the table. If index is equal to the number of rows, the new row is appended. In addition, when the table is empty the row is inserted into a TBODY which is created and inserted into the table. Note. A table row cannot be empty according to HTML 4.0 Recommendation.

Parameters:
index - The row number where to insert a new row. This index starts from 0 and is relative to all the rows contained inside the table, regardless of section parentage.
Returns:
The newly created row.
Throws:
DOMException - INDEX_SIZE_ERR: Raised if the specified index is greater than the number of rows or if the index is negative.

deleteRow

public void deleteRow(int index)
               throws DOMException
Delete a table row.

Parameters:
index - The index of the row to be deleted. This index starts from 0 and is relative to all the rows contained inside the table, regardless of section parentage.
Throws:
DOMException - INDEX_SIZE_ERR: Raised if the specified index is greater than or equal to the number of rows or if the index is negative.
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLTableRowElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLTableRowElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLTableRowElement
extends HTMLElement

A row in a table. See the TR element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
void | deleteCell(int index) Delete a cell from the current row.
String | getAlign() Horizontal alignment of data within cells of this row.
String | getBgColor() Background color for rows.
HTMLCollection | getCells() The collection of cells in this row.
String | getCh() Alignment character for cells in a column.
String | getChOff() Offset of alignment character.
int | getRowIndex() The index of this row, relative to the entire table, starting from 0.
int | getSectionRowIndex() The index of this row, relative to the current section ( THEAD , TFOOT , or TBODY ), starting from 0.
String | getVAlign() Vertical alignment of data within cells of this row.
HTMLElement | insertCell(int index) Insert an empty TD cell into this row.
void | setAlign(String align)
void | setBgColor(String bgColor)
void | setCh(String ch)
void | setChOff(String chOff)
void | setVAlign(String vAlign)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getRowIndex

public int getRowIndex()
The index of this row, relative to the entire table, starting from 0. This is in document tree order and not display order. The rowIndex does not take into account sections ( THEAD , TFOOT , or TBODY ) within the table.

getSectionRowIndex

public int getSectionRowIndex()
The index of this row, relative to the current section ( THEAD , TFOOT , or TBODY ), starting from 0.

getCells

public HTMLCollection getCells()
The collection of cells in this row.

getAlign

public String getAlign()
Horizontal alignment of data within cells of this row. See the align attribute definition in HTML 4.0.

setAlign

public void setAlign(String align)

getBgColor

public String getBgColor()
Background color for rows. See the bgcolor attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setBgColor

public void setBgColor(String bgColor)

getCh

public String getCh()
Alignment character for cells in a column. See the char attribute definition in HTML 4.0.

setCh

public void setCh(String ch)

getChOff

public String getChOff()
Offset of alignment character. See the charoff attribute definition in HTML 4.0.

setChOff

public void setChOff(String chOff)

getVAlign

public String getVAlign()
Vertical alignment of data within cells of this row. See the valign attribute definition in HTML 4.0.

setVAlign

public void setVAlign(String vAlign)

insertCell

public HTMLElement insertCell(int index)
                       throws DOMException
Insert an empty TD cell into this row. If index is equal to the number of cells, the new cell is appended

Parameters:
index - The place to insert the cell, starting from 0.
Returns:
The newly created cell.
Throws:
DOMException - INDEX_SIZE_ERR: Raised if the specified index is greater than the number of cells or if the index is negative.

deleteCell

public void deleteCell(int index)
                throws DOMException
Delete a cell from the current row.

Parameters:
index - The index of the cell to delete, starting from 0.
Throws:
DOMException - INDEX_SIZE_ERR: Raised if the specified index is greater than or equal to the number of cells or if the index is negative.
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLTableSectionElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLTableSectionElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLTableSectionElement
extends HTMLElement

The THEAD , TFOOT , and TBODY elements.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
void | deleteRow(int index) Delete a row from this section.
String | getAlign() Horizontal alignment of data in cells.
String | getCh() Alignment character for cells in a column.
String | getChOff() Offset of alignment character.
HTMLCollection | getRows() The collection of rows in this table section.
String | getVAlign() Vertical alignment of data in cells.
HTMLElement | insertRow(int index) Insert a row into this section.
void | setAlign(String align)
void | setCh(String ch)
void | setChOff(String chOff)
void | setVAlign(String vAlign)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getAlign

public String getAlign()
Horizontal alignment of data in cells. See the align attribute for HTMLTheadElement for details.

setAlign

public void setAlign(String align)

getCh

public String getCh()
Alignment character for cells in a column. See the char attribute definition in HTML 4.0.

setCh

public void setCh(String ch)

getChOff

public String getChOff()
Offset of alignment character. See the charoff attribute definition in HTML 4.0.

setChOff

public void setChOff(String chOff)

getVAlign

public String getVAlign()
Vertical alignment of data in cells. See the valign attribute for HTMLTheadElement for details.

setVAlign

public void setVAlign(String vAlign)

getRows

public HTMLCollection getRows()
The collection of rows in this table section.

insertRow

public HTMLElement insertRow(int index)
                      throws DOMException
Insert a row into this section. The new row is inserted immediately before the current index th row in this section. If index is equal to the number of rows in this section, the new row is appended.

Parameters:
index - The row number where to insert a new row. This index starts from 0 and is relative only to the rows contained inside this section, not all the rows in the table.
Returns:
The newly created row.
Throws:
DOMException - INDEX_SIZE_ERR: Raised if the specified index is greater than the number of rows of if the index is neagative.

deleteRow

public void deleteRow(int index)
               throws DOMException
Delete a row from this section.

Parameters:
index - The index of the row to be deleted. This index starts from 0 and is relative only to the rows contained inside this section, not all the rows in the table.
Throws:
DOMException - INDEX_SIZE_ERR: Raised if the specified index is greater than or equal to the number of rows or if the index is negative.
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLTextAreaElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLTextAreaElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLTextAreaElement
extends HTMLElement

Multi-line text field. See the TEXTAREA element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
void | blur() Removes keyboard focus from this element.
void | focus() Gives keyboard focus to this element.
String | getAccessKey() A single character access key to give access to the form control.
int | getCols() Width of control (in characters).
String | getDefaultValue() Represents the contents of the element.
boolean | getDisabled() The control is unavailable in this context.
HTMLFormElement | getForm() Returns the FORM element containing this control.
String | getName() Form control or object name when submitted with a form.
boolean | getReadOnly() This control is read-only.
int | getRows() Number of text rows.
int | getTabIndex() Index that represents the element's position in the tabbing order.
String | getType() The type of this form control.
String | getValue() Represents the current contents of the corresponding form control, in an interactive user agent.
void | select() Select the contents of the TEXTAREA .
void | setAccessKey(String accessKey)
void | setCols(int cols)
void | setDefaultValue(String defaultValue)
void | setDisabled(boolean disabled)
void | setName(String name)
void | setReadOnly(boolean readOnly)
void | setRows(int rows)
void | setTabIndex(int tabIndex)
void | setValue(String value)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getDefaultValue

public String getDefaultValue()
Represents the contents of the element. The value of this attribute does not change if the contents of the corresponding form control, in an interactive user agent, changes. Changing this attribute, however, resets the contents of the form control.

setDefaultValue

public void setDefaultValue(String defaultValue)

getForm

public HTMLFormElement getForm()
Returns the FORM element containing this control. Returns null if this control is not within the context of a form.

getAccessKey

public String getAccessKey()
A single character access key to give access to the form control. See the accesskey attribute definition in HTML 4.0.

setAccessKey

public void setAccessKey(String accessKey)

getCols

public int getCols()
Width of control (in characters). See the cols attribute definition in HTML 4.0.

setCols

public void setCols(int cols)

getDisabled

public boolean getDisabled()
The control is unavailable in this context. See the disabled attribute definition in HTML 4.0.

setDisabled

public void setDisabled(boolean disabled)

getName

public String getName()
Form control or object name when submitted with a form. See the name attribute definition in HTML 4.0.

setName

public void setName(String name)

getReadOnly

public boolean getReadOnly()
This control is read-only. See the readonly attribute definition in HTML 4.0.

setReadOnly

public void setReadOnly(boolean readOnly)

getRows

public int getRows()
Number of text rows. See the rows attribute definition in HTML 4.0.

setRows

public void setRows(int rows)

getTabIndex

public int getTabIndex()
Index that represents the element's position in the tabbing order. See the tabindex attribute definition in HTML 4.0.

setTabIndex

public void setTabIndex(int tabIndex)

getType

public String getType()
The type of this form control. This the string "textarea".

getValue

public String getValue()
Represents the current contents of the corresponding form control, in an interactive user agent. Changing this attribute changes the contents of the form control, but does not change the contents of the element. If the entirety of the data can not fit into a single DOMString , the implementation may truncate the data.

setValue

public void setValue(String value)

blur

public void blur()
Removes keyboard focus from this element.

focus

public void focus()
Gives keyboard focus to this element.

select

public void select()
Select the contents of the TEXTAREA .

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLTitleElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLTitleElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLTitleElement
extends HTMLElement

The document title. See the TITLE element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
String | getText() The specified title as a string.
void | setText(String text)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getText

public String getText()
The specified title as a string.

setText

public void setText(String text)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


HTMLUListElement (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.html
Interface HTMLUListElement

All Superinterfaces:
Element, HTMLElement, Node
public interface HTMLUListElement
extends HTMLElement

Unordered list. See the UL element definition in HTML 4.0.

See also the Document Object Model (DOM) Level 2 Specification.

Field Summary
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
Method Summary
boolean | getCompact() Reduce spacing between list items.
String | getType() Bullet style.
void | setCompact(boolean compact)
void | setType(String type)
Methods inherited from interface org.w3c.dom.html.HTMLElement
getClassName, getDir, getId, getLang, getTitle, setClassName, setDir, setId, setLang, setTitle
Methods inherited from interface org.w3c.dom.Element
getAttribute, getAttributeNode, getAttributeNodeNS, getAttributeNS, getElementsByTagName, getElementsByTagNameNS, getTagName, hasAttribute, hasAttributeNS, removeAttribute, removeAttributeNode, removeAttributeNS, setAttribute, setAttributeNode, setAttributeNodeNS, setAttributeNS
Methods inherited from interface org.w3c.dom.Node
appendChild, cloneNode, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeName, getNodeType, getNodeValue, getOwnerDocument, getParentNode, getPrefix, getPreviousSibling, hasAttributes, hasChildNodes, insertBefore, isSupported, normalize, removeChild, replaceChild, setNodeValue, setPrefix

Method Detail

getCompact

public boolean getCompact()
Reduce spacing between list items. See the compact attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setCompact

public void setCompact(boolean compact)

getType

public String getType()
Bullet style. See the type attribute definition in HTML 4.0. This attribute is deprecated in HTML 4.0.

setType

public void setType(String type)
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


org.w3c.dom.html (Common DOM API)

 org.w3c.dom.html
Interfaces
HTMLAnchorElement
HTMLAppletElement
HTMLAreaElement
HTMLBaseElement
HTMLBaseFontElement
HTMLBodyElement
HTMLBRElement
HTMLButtonElement
HTMLCollection
HTMLDirectoryElement
HTMLDivElement
HTMLDListElement
HTMLDocument
HTMLDOMImplementation
HTMLElement
HTMLFieldSetElement
HTMLFontElement
HTMLFormElement
HTMLFrameElement
HTMLFrameSetElement
HTMLHeadElement
HTMLHeadingElement
HTMLHRElement
HTMLHtmlElement
HTMLIFrameElement
HTMLImageElement
HTMLInputElement
HTMLIsIndexElement
HTMLLabelElement
HTMLLegendElement
HTMLLIElement
HTMLLinkElement
HTMLMapElement
HTMLMenuElement
HTMLMetaElement
HTMLModElement
HTMLObjectElement
HTMLOListElement
HTMLOptGroupElement
HTMLOptionElement
HTMLParagraphElement
HTMLParamElement
HTMLPreElement
HTMLQuoteElement
HTMLScriptElement
HTMLSelectElement
HTMLStyleElement
HTMLTableCaptionElement
HTMLTableCellElement
HTMLTableColElement
HTMLTableElement
HTMLTableRowElement
HTMLTableSectionElement
HTMLTextAreaElement
HTMLTitleElement
HTMLUListElement


org.w3c.dom.html (Common DOM API)

Common DOM API
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package org.w3c.dom.html

Interface Summary
HTMLAnchorElement | The anchor element.
HTMLAppletElement | An embedded Java applet.
HTMLAreaElement | Client-side image map area definition.
HTMLBaseElement | Document base URI.
HTMLBaseFontElement | Base font.
HTMLBodyElement | The HTML document body.
HTMLBRElement | Force a line break.
HTMLButtonElement | Push button.
HTMLCollection | An HTMLCollection is a list of nodes.
HTMLDirectoryElement | Directory list.
HTMLDivElement | Generic block container.
HTMLDListElement | Definition list.
HTMLDocument | An HTMLDocument is the root of the HTML hierarchy and holds the entire content.
HTMLDOMImplementation | The HTMLDOMImplementation interface extends the DOMImplementation interface with a method for creating an HTML document instance.
HTMLElement | All HTML element interfaces derive from this class.
HTMLFieldSetElement | Organizes form controls into logical groups.
HTMLFontElement | Local change to font.
HTMLFormElement | The FORM element encompasses behavior similar to a collection and an element.
HTMLFrameElement | Create a frame.
HTMLFrameSetElement | Create a grid of frames.
HTMLHeadElement | Document head information.
HTMLHeadingElement | For the H1 to H6 elements.
HTMLHRElement | Create a horizontal rule.
HTMLHtmlElement | Root of an HTML document.
HTMLIFrameElement | Inline subwindows.
HTMLImageElement | Embedded image.
HTMLInputElement | Form control.
HTMLIsIndexElement | This element is used for single-line text input.
HTMLLabelElement | Form field label text.
HTMLLegendElement | Provides a caption for a FIELDSET grouping.
HTMLLIElement | List item.
HTMLLinkElement | The LINK element specifies a link to an external resource, and defines this document's relationship to that resource (or vice versa).
HTMLMapElement | Client-side image map.
HTMLMenuElement | Menu list.
HTMLMetaElement | This contains generic meta-information about the document.
HTMLModElement | Notice of modification to part of a document.
HTMLObjectElement | Generic embedded object.
HTMLOListElement | Ordered list.
HTMLOptGroupElement | Group options together in logical subdivisions.
HTMLOptionElement | A selectable choice.
HTMLParagraphElement | Paragraphs.
HTMLParamElement | Parameters fed to the OBJECT element.
HTMLPreElement | Preformatted text.
HTMLQuoteElement | For the Q and BLOCKQUOTE elements.
HTMLScriptElement | Script statements.
HTMLSelectElement | The select element allows the selection of an option.
HTMLStyleElement | Style information.
HTMLTableCaptionElement | Table caption See the CAPTION element definition in HTML 4.0.
HTMLTableCellElement | The object used to represent the TH and TD elements.
HTMLTableColElement | Regroups the COL and COLGROUP elements.
HTMLTableElement | The create* and delete* methods on the table allow authors to construct and modify tables.
HTMLTableRowElement | A row in a table.
HTMLTableSectionElement | The THEAD , TFOOT , and TBODY elements.
HTMLTextAreaElement | Multi-line text field.
HTMLTitleElement | The document title.
HTMLUListElement | Unordered list.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


org.w3c.dom.html Class Hierarchy (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Hierarchy For Package org.w3c.dom.html

Package Hierarchies:
All Packages

Interface Hierarchy

  • interface org.w3c.dom.DOMImplementation
    • interface org.w3c.dom.html.HTMLDOMImplementation
  • interface org.w3c.dom.html.HTMLCollection
  • interface org.w3c.dom.Node
    • interface org.w3c.dom.Document
      • interface org.w3c.dom.html.HTMLDocument
    • interface org.w3c.dom.Element
      • interface org.w3c.dom.html.HTMLElement
        • interface org.w3c.dom.html.HTMLAnchorElement
        • interface org.w3c.dom.html.HTMLAppletElement
        • interface org.w3c.dom.html.HTMLAreaElement
        • interface org.w3c.dom.html.HTMLBaseElement
        • interface org.w3c.dom.html.HTMLBaseFontElement
        • interface org.w3c.dom.html.HTMLBodyElement
        • interface org.w3c.dom.html.HTMLBRElement
        • interface org.w3c.dom.html.HTMLButtonElement
        • interface org.w3c.dom.html.HTMLDirectoryElement
        • interface org.w3c.dom.html.HTMLDivElement
        • interface org.w3c.dom.html.HTMLDListElement
        • interface org.w3c.dom.html.HTMLFieldSetElement
        • interface org.w3c.dom.html.HTMLFontElement
        • interface org.w3c.dom.html.HTMLFormElement
        • interface org.w3c.dom.html.HTMLFrameElement
        • interface org.w3c.dom.html.HTMLFrameSetElement
        • interface org.w3c.dom.html.HTMLHeadElement
        • interface org.w3c.dom.html.HTMLHeadingElement
        • interface org.w3c.dom.html.HTMLHRElement
        • interface org.w3c.dom.html.HTMLHtmlElement
        • interface org.w3c.dom.html.HTMLIFrameElement
        • interface org.w3c.dom.html.HTMLImageElement
        • interface org.w3c.dom.html.HTMLInputElement
        • interface org.w3c.dom.html.HTMLIsIndexElement
        • interface org.w3c.dom.html.HTMLLabelElement
        • interface org.w3c.dom.html.HTMLLegendElement
        • interface org.w3c.dom.html.HTMLLIElement
        • interface org.w3c.dom.html.HTMLLinkElement
        • interface org.w3c.dom.html.HTMLMapElement
        • interface org.w3c.dom.html.HTMLMenuElement
        • interface org.w3c.dom.html.HTMLMetaElement
        • interface org.w3c.dom.html.HTMLModElement
        • interface org.w3c.dom.html.HTMLObjectElement
        • interface org.w3c.dom.html.HTMLOListElement
        • interface org.w3c.dom.html.HTMLOptGroupElement
        • interface org.w3c.dom.html.HTMLOptionElement
        • interface org.w3c.dom.html.HTMLParagraphElement
        • interface org.w3c.dom.html.HTMLParamElement
        • interface org.w3c.dom.html.HTMLPreElement
        • interface org.w3c.dom.html.HTMLQuoteElement
        • interface org.w3c.dom.html.HTMLScriptElement
        • interface org.w3c.dom.html.HTMLSelectElement
        • interface org.w3c.dom.html.HTMLStyleElement
        • interface org.w3c.dom.html.HTMLTableCaptionElement
        • interface org.w3c.dom.html.HTMLTableCellElement
        • interface org.w3c.dom.html.HTMLTableColElement
        • interface org.w3c.dom.html.HTMLTableElement
        • interface org.w3c.dom.html.HTMLTableRowElement
        • interface org.w3c.dom.html.HTMLTableSectionElement
        • interface org.w3c.dom.html.HTMLTextAreaElement
        • interface org.w3c.dom.html.HTMLTitleElement
        • interface org.w3c.dom.html.HTMLUListElement
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Package org.w3c.dom.html (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Package
org.w3c.dom.html

Packages that use org.w3c.dom.html
org.w3c.dom.html

Classes in org.w3c.dom.html used by org.w3c.dom.html
HTMLCollection
An HTMLCollection is a list of nodes.
HTMLDocument
An HTMLDocument is the root of the HTML hierarchy and holds the entire content.
HTMLElement
All HTML element interfaces derive from this class.
HTMLFormElement
The FORM element encompasses behavior similar to a collection and an element.
HTMLTableCaptionElement
Table caption See the CAPTION element definition in HTML 4.0.
HTMLTableSectionElement
The THEAD , TFOOT , and TBODY elements.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLAnchorElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLAppletElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLAreaElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLBaseElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLBaseFontElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLBodyElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLBRElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLButtonElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLCollection (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.html.HTMLCollection

Packages that use HTMLCollection
org.w3c.dom.html

Uses of HTMLCollection in org.w3c.dom.html

Methods in org.w3c.dom.html that return HTMLCollection
HTMLCollection | HTMLTableRowElement.getCells() The collection of cells in this row.
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.
HTMLCollection | HTMLSelectElement.getOptions() The collection of OPTION elements contained by this element.
HTMLCollection | HTMLMapElement.getAreas() The list of areas defined for the image map.
HTMLCollection | HTMLDocument.getImages() A collection of all the IMG elements in a document.
HTMLCollection | HTMLDocument.getApplets() A collection of all the OBJECT elements that include applets and APPLET ( deprecated ) 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 | HTMLDocument.getForms() A collection of all the forms of a document.
HTMLCollection | HTMLDocument.getAnchors() A collection of all the anchor (A ) elements in a document with a value for the name attribute.
HTMLCollection | HTMLFormElement.getElements() Returns a collection of all control elements in the form.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLDirectoryElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLDivElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLDListElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLDocument (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.html.HTMLDocument

Packages that use HTMLDocument
org.w3c.dom.html

Uses of HTMLDocument in org.w3c.dom.html

Methods in org.w3c.dom.html that return HTMLDocument
 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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLDOMImplementation (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.html.HTMLElement

Packages that use HTMLElement
org.w3c.dom.html

Uses of HTMLElement in org.w3c.dom.html

Subinterfaces of HTMLElement in org.w3c.dom.html
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
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.createTHead() Create a table header row or return an existing one.
HTMLElement | HTMLTableElement.createTFoot() Create a table footer row or return an existing one.
HTMLElement | HTMLTableElement.createCaption() Create a new table caption object or return an existing one.
HTMLElement | HTMLTableElement.insertRow(int index) Insert a new empty row in the table.
HTMLElement | HTMLDocument.getBody() The element that contains the content for the document.

Methods in org.w3c.dom.html with parameters of type HTMLElement
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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLFieldSetElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLFontElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLFormElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.html.HTMLFormElement

Packages that use HTMLFormElement
org.w3c.dom.html

Uses of HTMLFormElement in org.w3c.dom.html

Methods in org.w3c.dom.html that return HTMLFormElement
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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLFrameElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLFrameSetElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLHeadElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLHeadingElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLHRElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLHtmlElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLIFrameElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLImageElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLInputElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLIsIndexElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLLabelElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLLegendElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLLIElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLLinkElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLMapElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLMenuElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLMetaElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLModElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLObjectElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLOListElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLOptGroupElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLOptionElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLParagraphElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLParamElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLPreElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLQuoteElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLScriptElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLSelectElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLStyleElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLTableCaptionElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.html.HTMLTableCaptionElement

Packages that use HTMLTableCaptionElement
org.w3c.dom.html

Uses of HTMLTableCaptionElement in org.w3c.dom.html

Methods in org.w3c.dom.html that return HTMLTableCaptionElement
 HTMLTableCaptionElement HTMLTableElement.getCaption()
Returns the table's CAPTION , or void if none exists.

Methods in org.w3c.dom.html with parameters of type HTMLTableCaptionElement
 void HTMLTableElement.setCaption(HTMLTableCaptionElement caption)

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLTableCellElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLTableColElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLTableElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLTableRowElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLTableSectionElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.html.HTMLTableSectionElement

Packages that use HTMLTableSectionElement
org.w3c.dom.html

Uses of HTMLTableSectionElement in org.w3c.dom.html

Methods in org.w3c.dom.html that return HTMLTableSectionElement
HTMLTableSectionElement | HTMLTableElement.getTHead() Returns the table's THEAD , or null if none exists.
HTMLTableSectionElement | HTMLTableElement.getTFoot() Returns the table's TFOOT , or null if none exists.

Methods in org.w3c.dom.html with parameters of type HTMLTableSectionElement
void | HTMLTableElement.setTHead(HTMLTableSectionElement tHead)
void | HTMLTableElement.setTFoot(HTMLTableSectionElement tFoot)

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLTextAreaElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLTitleElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.html.HTMLUListElement (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


DocumentStyle (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.stylesheets
Interface DocumentStyle

All Known Subinterfaces:
DocumentCSS
public interface DocumentStyle

The DocumentStyle interface provides a mechanism by which the style sheets embedded in a document can be retrieved. The expectation is that an instance of the DocumentStyle interface can be obtained by using binding-specific casting methods on an instance of the Document interface.

See also the Document Object Model (DOM) Level 2 Style Specification.

Since:
DOM Level 2

Method Summary
 StyleSheetList getStyleSheets()
A list containing all the style sheets explicitly linked into or embedded in a document.

Method Detail

getStyleSheets

public StyleSheetList getStyleSheets()
A list containing all the style sheets explicitly linked into or embedded in a document. For HTML documents, this includes external style sheets, included via the HTML LINK element, and inline STYLE elements. In XML, this includes external style sheets, included via style sheet processing instructions (see ).

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


LinkStyle (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.stylesheets
Interface LinkStyle

public interface LinkStyle

The LinkStyle interface provides a mechanism by which a style sheet can be retrieved from the node responsible for linking it into a document. An instance of the LinkStyle interface can be obtained using binding-specific casting methods on an instance of a linking node (HTMLLinkElement, HTMLStyleElement or ProcessingInstruction in DOM Level 2).

See also the Document Object Model (DOM) Level 2 Style Specification.

Since:
DOM Level 2

Method Summary
 StyleSheet getSheet()
The style sheet.

Method Detail

getSheet

public StyleSheet getSheet()
The style sheet.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


MediaList (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.stylesheets
Interface MediaList

public interface MediaList

The MediaList interface provides the abstraction of an ordered collection of media, without defining or constraining how this collection is implemented. An empty list is the same as a list that contains the medium "all".

The items in the MediaList are accessible via an integral index, starting from 0.

See also the Document Object Model (DOM) Level 2 Style Specification.

Since:
DOM Level 2

Method Summary
void | appendMedium(String newMedium) Adds the medium newMedium to the end of the list.
void | deleteMedium(String oldMedium) Deletes the medium indicated by oldMedium from the list.
int | getLength() The number of media in the list.
String | getMediaText() The parsable textual representation of the media list.
String | item(int index) Returns the indexth in the list.
void | setMediaText(String mediaText)

Method Detail

getMediaText

public String getMediaText()
The parsable textual representation of the media list. This is a comma-separated list of media.

Throws:
DOMException - SYNTAX_ERR: Raised if the specified string value has a syntax error and is unparsable.
NO_MODIFICATION_ALLOWED_ERR: Raised if this media list is readonly.

setMediaText

public void setMediaText(String mediaText)
                  throws DOMException
Throws:
DOMException

getLength

public int getLength()
The number of media in the list. The range of valid media is 0 to length-1 inclusive.

item

public String item(int index)
Returns the indexth in the list. If index is greater than or equal to the number of media in the list, this returns null.

Parameters:
index - Index into the collection.
Returns:
The medium at the indexth position in the MediaList, or null if that is not a valid index.

deleteMedium

public void deleteMedium(String oldMedium)
                  throws DOMException
Deletes the medium indicated by oldMedium from the list.

Throws:
DOMException - NO_MODIFICATION_ALLOWED_ERR: Raised if this list is readonly.
NOT_FOUND_ERR: Raised if oldMedium is not in the list.

appendMedium

public void appendMedium(String newMedium)
                  throws DOMException
Adds the medium newMedium to the end of the list. If the newMedium is already used, it is first removed.

Throws:
DOMException - INVALID_CHARACTER_ERR: If the medium contains characters that are invalid in the underlying style language.
NO_MODIFICATION_ALLOWED_ERR: Raised if this list is readonly.
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


org.w3c.dom.stylesheets (Common DOM API)

 org.w3c.dom.stylesheets
Interfaces
DocumentStyle
LinkStyle
MediaList
StyleSheet
StyleSheetList


org.w3c.dom.stylesheets (Common DOM API)

Common DOM API
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package org.w3c.dom.stylesheets

Interface Summary
DocumentStyle | The DocumentStyle interface provides a mechanism by which the style sheets embedded in a document can be retrieved.
LinkStyle | The LinkStyle interface provides a mechanism by which a style sheet can be retrieved from the node responsible for linking it into a document.
MediaList | The MediaList interface provides the abstraction of an ordered collection of media, without defining or constraining how this collection is implemented.
StyleSheet | The StyleSheet interface is the abstract base interface for any type of style sheet.
StyleSheetList | The StyleSheetList interface provides the abstraction of an ordered collection of style sheets.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


org.w3c.dom.stylesheets Class Hierarchy (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Hierarchy For Package org.w3c.dom.stylesheets

Package Hierarchies:
All Packages

Interface Hierarchy

  • interface org.w3c.dom.stylesheets.DocumentStyle
  • interface org.w3c.dom.stylesheets.LinkStyle
  • interface org.w3c.dom.stylesheets.MediaList
  • interface org.w3c.dom.stylesheets.StyleSheet
  • interface org.w3c.dom.stylesheets.StyleSheetList
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Package org.w3c.dom.stylesheets (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Package
org.w3c.dom.stylesheets

Packages that use org.w3c.dom.stylesheets
org.w3c.dom.css
org.w3c.dom.stylesheets

Classes in org.w3c.dom.stylesheets used by org.w3c.dom.css
DocumentStyle
The DocumentStyle interface provides a mechanism by which the style sheets embedded in a document can be retrieved.
MediaList
The MediaList interface provides the abstraction of an ordered collection of media, without defining or constraining how this collection is implemented.
StyleSheet
The StyleSheet interface is the abstract base interface for any type of style sheet.

Classes in org.w3c.dom.stylesheets used by org.w3c.dom.stylesheets
MediaList
The MediaList interface provides the abstraction of an ordered collection of media, without defining or constraining how this collection is implemented.
StyleSheet
The StyleSheet interface is the abstract base interface for any type of style sheet.
StyleSheetList
The StyleSheetList interface provides the abstraction of an ordered collection of style sheets.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


StyleSheet (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.stylesheets
Interface StyleSheet

All Known Subinterfaces:
CSSStyleSheet
public interface StyleSheet

The StyleSheet interface is the abstract base interface for any type of style sheet. It represents a single style sheet associated with a structured document. In HTML, the StyleSheet interface represents either an external style sheet, included via the HTML LINK element, or an inline STYLE element. In XML, this interface represents an external style sheet, included via a style sheet processing instruction.

See also the Document Object Model (DOM) Level 2 Style Specification.

Since:
DOM Level 2

Method Summary
boolean | getDisabled() false if the style sheet is applied to the document.
String | getHref() If the style sheet is a linked style sheet, the value of its attribute is its location.
MediaList | getMedia() The intended destination media for style information.
Node | getOwnerNode() The node that associates this style sheet with the document.
StyleSheet | getParentStyleSheet() For style sheet languages that support the concept of style sheet inclusion, this attribute represents the including style sheet, if one exists.
String | getTitle() The advisory title.
String | getType() This specifies the style sheet language for this style sheet.
void | setDisabled(boolean disabled)

Method Detail

getType

public String getType()
This specifies the style sheet language for this style sheet. The style sheet language is specified as a content type (e.g. "text/css"). The content type is often specified in the ownerNode. Also see the type attribute definition for the LINK element in HTML 4.0, and the type pseudo-attribute for the XML style sheet processing instruction.

getDisabled

public boolean getDisabled()
false if the style sheet is applied to the document. true if it is not. Modifying this attribute may cause a new resolution of style for the document. A stylesheet only applies if both an appropriate medium definition is present and the disabled attribute is false. So, if the media doesn't apply to the current user agent, the disabled attribute is ignored.

setDisabled

public void setDisabled(boolean disabled)

getOwnerNode

public Node getOwnerNode()
The node that associates this style sheet with the document. For HTML, this may be the corresponding LINK or STYLE element. For XML, it may be the linking processing instruction. For style sheets that are included by other style sheets, the value of this attribute is null.

getParentStyleSheet

public StyleSheet getParentStyleSheet()
For style sheet languages that support the concept of style sheet inclusion, this attribute represents the including style sheet, if one exists. If the style sheet is a top-level style sheet, or the style sheet language does not support inclusion, the value of this attribute is null.

getHref

public String getHref()
If the style sheet is a linked style sheet, the value of its attribute is its location. For inline style sheets, the value of this attribute is null. See the href attribute definition for the LINK element in HTML 4.0, and the href pseudo-attribute for the XML style sheet processing instruction.

getTitle

public String getTitle()
The advisory title. The title is often specified in the ownerNode. See the title attribute definition for the LINK element in HTML 4.0, and the title pseudo-attribute for the XML style sheet processing instruction.

getMedia

public MediaList getMedia()
The intended destination media for style information. The media is often specified in the ownerNode. If no media has been specified, the MediaList will be empty. See the media attribute definition for the LINK element in HTML 4.0, and the media pseudo-attribute for the XML style sheet processing instruction . Modifying the media list may cause a change to the attribute disabled.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


StyleSheetList (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.stylesheets
Interface StyleSheetList

public interface StyleSheetList

The StyleSheetList interface provides the abstraction of an ordered collection of style sheets.

The items in the StyleSheetList are accessible via an integral index, starting from 0.

See also the Document Object Model (DOM) Level 2 Style Specification.

Since:
DOM Level 2

Method Summary
int | getLength() The number of StyleSheets in the list.
StyleSheet | item(int index) Used to retrieve a style sheet by ordinal index.

Method Detail

getLength

public int getLength()
The number of StyleSheets in the list. The range of valid child stylesheet indices is 0 to length-1 inclusive.

item

public StyleSheet item(int index)
Used to retrieve a style sheet by ordinal index. If index is greater than or equal to the number of style sheets in the list, this returns null.

Returns:
The style sheet at the index position in the StyleSheetList, or null if that is not a valid index.
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.stylesheets.DocumentStyle (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.stylesheets.DocumentStyle

Packages that use DocumentStyle
org.w3c.dom.css

Uses of DocumentStyle in org.w3c.dom.css

Subinterfaces of DocumentStyle in org.w3c.dom.css
 interface DocumentCSS
This interface represents a document with a CSS view.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.stylesheets.LinkStyle (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.stylesheets.MediaList (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.stylesheets.MediaList

Packages that use MediaList
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
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
 MediaList StyleSheet.getMedia()
The intended destination media for style information.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.stylesheets.StyleSheet (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.stylesheets.StyleSheet

Packages that use StyleSheet
org.w3c.dom.css
org.w3c.dom.stylesheets

Uses of StyleSheet in org.w3c.dom.css

Subinterfaces of StyleSheet in org.w3c.dom.css
 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
StyleSheet | LinkStyle.getSheet() The style sheet.
StyleSheet | StyleSheetList.item(int index) Used to retrieve a style sheet by ordinal index.
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.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.stylesheets.StyleSheetList (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.stylesheets.StyleSheetList

Packages that use StyleSheetList
org.w3c.dom.stylesheets

Uses of StyleSheetList in org.w3c.dom.stylesheets

Methods in org.w3c.dom.stylesheets that return StyleSheetList
 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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


AbstractView (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.views
Interface AbstractView

All Known Subinterfaces:
ViewCSS
public interface AbstractView

A base interface that all views shall derive from.

See also the Document Object Model (DOM) Level 2 Views Specification.

Since:
DOM Level 2

Method Summary
 DocumentView getDocument()
The source DocumentView of which this is an AbstractView.

Method Detail

getDocument

public DocumentView getDocument()
The source DocumentView of which this is an AbstractView.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


DocumentView (Common DOM API)

Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

org.w3c.dom.views
Interface DocumentView

public interface DocumentView

The DocumentView interface is implemented by Document objects in DOM implementations supporting DOM Views. It provides an attribute to retrieve the default view of a document.

See also the Document Object Model (DOM) Level 2 Views Specification.

Since:
DOM Level 2

Method Summary
 AbstractView getDefaultView()
The default AbstractView for this Document, or null if none available.

Method Detail

getDefaultView

public AbstractView getDefaultView()
The default AbstractView for this Document, or null if none available.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


org.w3c.dom.views (Common DOM API)

 org.w3c.dom.views
Interfaces
AbstractView
DocumentView


org.w3c.dom.views (Common DOM API)

Common DOM API
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package org.w3c.dom.views

Interface Summary
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
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


org.w3c.dom.views Class Hierarchy (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Hierarchy For Package org.w3c.dom.views

Package Hierarchies:
All Packages

Interface Hierarchy

  • interface org.w3c.dom.views.AbstractView
  • interface org.w3c.dom.views.DocumentView
Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Package org.w3c.dom.views (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Package
org.w3c.dom.views

Packages that use org.w3c.dom.views
org.w3c.dom.css
org.w3c.dom.events
org.w3c.dom.views

Classes in org.w3c.dom.views used by org.w3c.dom.css
AbstractView
A base interface that all views shall derive from.

Classes in org.w3c.dom.views used by org.w3c.dom.events
AbstractView
A base interface that all views shall derive from.

Classes in org.w3c.dom.views used by org.w3c.dom.views
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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.views.AbstractView (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.views.AbstractView

Packages that use AbstractView
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
 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
 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
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.
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.

Uses of AbstractView in org.w3c.dom.views

Methods in org.w3c.dom.views that return AbstractView
 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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface org.w3c.dom.views.DocumentView (Common DOM API)

Common DOM API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
org.w3c.dom.views.DocumentView

Packages that use DocumentView
org.w3c.dom.views

Uses of DocumentView in org.w3c.dom.views

Methods in org.w3c.dom.views that return DocumentView
 DocumentView AbstractView.getDocument()
The source DocumentView of which this is an AbstractView.

Overview Package Class Use Tree Deprecated Index Help
Common DOM API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Reflection

 Documentation Contents
Reflection enables Java code to discover information about the fields, methods and constructors of loaded classes, and to use reflected fields, methods, and constructors to operate on their underlying counterparts on objects, within security restrictions. The API accommodates applications that need access to either the public members of a target object (based on its runtime class) or the members declared by a given class.

The JavaTM 2 Platform allows programs to suppress default reflective access control.

Performance Enhancement
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.
Dynamic Proxy Classes
  • Dyanmic Proxy Classes are supported by three classes and interfaces in the Java 2 Platform.

Reflection Overview
  • Reflection Overview 1.1 (Not Updated for the Java 2 Platform)

Suppressing Reflective Access Control
  • Suppressing Reflective Access Control

Reflection API Specification
(javadoc)
  • java.lang.reflect Package

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: reflection-comments@eng.sun.com 		Sun

Java Software


Dynamic Proxy Classes

 Documentation Contents

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.
  • No two interfaces may each have a method with the same name and parameter signature but different return type.
  • 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 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 © 1999 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: reflect ion-comments@sun.com 		Sun

Java Software


Suppressing Reflective Access Control

Java Documentation Contents
Certain sophisticated clients of the Java Core Reflection API require a means to suppress default Java language access control checks when using reflected members and constructors. These checks--for public, default (package) access, protected, and private members--are performed when Fields, Methods or Constructors are used to set or get fields, to invoke methods, or to create new instances of classes, respectively.

Examples of such clients are the Java Object Serialization service, development tools such as object inspectors and debuggers, and other applications such as database persistence mechanisms.

SOLUTION

In Java 1.2, a Field, Method or Constructor object may be explicitly flagged as suppressing default Java language access control. When the reflective object is used, this flag--a new instance field--is consulted as part of access checking. If the flag is true, access checks are disabled and the requested operation proceeds; otherwise, normal access checks are performed as in Java 1.1. The flag is false by default in a reflected member or constructor.

The act of setting the flag is security-checked using the new Java 1.2 security mechanisms. A client's calling context must have sufficient privilege to perform this operation.

Thus, in Java 1.2 each concrete reflected class (Field, Method and Constructor) extends a new base class, AccessibleObject, defined below. This class provides the necessary state and methods to set and get an "accessible" flag for a reflected object. A new ReflectPermission class, also defined below, provides the ability to grant the necessary permission via the security policy file.

PROGRAMMING INTERFACE

package java.lang.reflect;
/**
 * The AccessibleObject class is the base class for Field, Method and
 * Constructor objects.  It provides the ability to flag a reflected
 * object as suppressing default Java language access control checks
 * when it is used.  The access checks--for public, default (package)
 * access, protected, and private members--are performed when Fields,
 * Methods or Constructors are used to set or get fields, to invoke
 * methods, or to create and initialize new instances of classes,
 * respectively.
 *
 * <p>Setting the <tt>accessible</tt> flag in a reflected object
 * permits sophisticated applications with sufficient privilege, such
 * as Java Object Serialization or other persistence mechanisms, to
 * manipulate objects in a manner that would normally be prohibited.
 *
 * @see Field
 * @see Method
 * @see Constructor
 * @see ReflectPermission
 *
 * @since JDK1.2
 */
public
class AccessibleObject {

    /**
     * Convenience method to set the <tt>accessible</tt> flag for an
     * array of objects with a single security check (for efficiency).
     *
     * @param array the array of AccessibleObjects
     * @param flag the new value for the <tt>accessible</tt> flag in each object
     * @throws SecurityException if the request is denied
     */
    public static void setAccessible(AccessibleObject[] array, boolean flag)
    throws SecurityException;

    /**
     * Set the <tt>accessible</tt> flag for this object to
     * the indicated boolean value.  A value of <tt>true</tt> indicates that
     * the reflected object should suppress Java language access
     * checking when it is used.  A value of <tt>false</tt> indicates
     * that the reflected object should enforce Java language access checks.
     *
     * @param flag the new value for the <tt>accessible</tt> flag
     * @throws SecurityException if the request is denied
     */
    public void setAccessible(boolean flag) throws SecurityException;

    /**
     * Get the value of the <tt>accessible</tt> flag for this object.
     */
    public boolean isAccessible();

    /**
     * Constructor: only used by the Java Virtual Machine.
     */
    protected AccessibleObject();

}

package java.lang.reflect;

/**
 * The Permission class for reflective operations.  A
 * ReflectPermission is a <em>named permission</em> and has no
 * actions.  The only name currently defined is <tt>access</tt>,
 * which allows suppressing the standard Java language access checks
 * --for public, default (package) access, protected, and private
 * members--performed by reflected objects at their point of use.
 *
 * <p>An example of permitting the identity "Duke" to suppress the
 * language access checking for reflected members might be:
 * <code>
 *	grant signedBy "Duke" {
 *		java.lang.reflect.ReflectPermission "access";
 *	}
 * </code>
 *
 * @see java.security.Permission
 * @see java.security.BasicPermission
 * @see AccessibleObject
 * @see Field#get
 * @see Field#set
 * @see Method#invoke
 * @see Constructor#newInstance
 *
 * @since JDK1.2
 */
public final
class ReflectPermission extends java.security.BasicPermission {

    /**
     * Constructs a ReflectPermission with the specified name.
     *
     * @param name the name of the ReflectPermission
     */
    public ReflectPermission(String name);

    /**
     * Constructs a ReflectPermission with the specified name and actions.
     * The actions should be null; they are ignored.
     *
     * @param name the name of the ReflectPermission
     * @param actions should be null.
     */
    public ReflectPermission(String name, String actions);
}

Copyright © 1995-97 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software


Contents | Prev | Next Java Core Reflection

Copyright Information

© 1996, 1997, 1998 Sun Microsystems, Inc. All rights reserved.
2550 Garcia Avenue, Mountain View, California 94043-1100 U.S.A.

This document is protected by copyright. No part of this document may be reproduced in any form by any means without prior written authorization of Sun and its licensors, if any.

The information described in this document may be protected by one or more U.S. patents, foreign patents, or pending applications.

TRADEMARKS

Sun, Sun Microsystems, Sun Microelectronics, the Sun Logo, SunXTL, JavaSoft, JavaOS, the JavaSoft Logo, Java, HotJava, JavaChips, picoJava, microJava, UltraJava, JDBC, the Java Cup and Steam Logo, "Write Once, Run Anywhere" and Solaris are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries.
UNIX ® is a registered trademark in the United States and other countries, exclusively licensed through X/Open Company, Ltd.
Adobe ® is a registered trademark of Adobe Systems, Inc.
Netscape NavigatorTM is a trademark of Netscape Communications Corporation.
All other product names mentioned herein are the trademarks of their respective owners.

THIS DOCUMENT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.

THIS DOCUMENT COULD INCLUDE TECHNICAL INACCURACIES OR TYPOGRAPHICAL ERRORS. CHANGES ARE PERIODICALLY ADDED TO THE INFORMATION HEREIN; THESE CHANGES WILL BE INCORPORATED IN NEW EDITIONS OF THE DOCUMENT. SUN MICROSYSTEMS, INC. MAY MAKE IMPROVEMENTS AND/OR CHANGES IN THE PRODUCT(S) AND/OR THE PROGRAM(S) DESCRIBED IN THIS DOCUMENT AT ANY TIME.

Contents | Prev | Next
Copyright © 1996, 1997, 1998 Sun Microsystems, Inc. All rights reserved.


Java Core Reflection

Contents | Prev | Next Java Core Reflection

Overview

The Java(TM) Core Reflection API provides a small, type-safe, and secure API that supports introspection about the classes and objects in the current Java Virtual Machine*. If permitted by security policy, the API can be used to:

  • construct new class instances and new arrays

  • access and modify fields of objects and classes

  • invoke methods on objects and classes

  • access and modify elements of arrays

The Core Reflection API defines classes and methods, as follows:

  • Three classes-Field, Method, and Constructor-that reflect class and interface members and constructors. These classes provide:

    • reflective information about the underlying member or constructor

    • a type-safe means to use the member or constructor to operate on Java objects

  • Methods of class Class that provide for the construction of new instances of the Field, Method, and Constructor classes.

  • The class Array provides methods to dynamically construct and access Java arrays.

  • The utility class Modifier helps decode Java language modifier information about classes and their members.

  • The class InvocationTargetException is used to wrap exceptions thrown by reflected methods or constructors.

  • Two classes-AccessibleObject and ReflectPermission-that provide a mechanism to suppress standard Java language access control.

There are also some parts of the java.lang package that support reflection. These are:

  • Static fields that hold instances of the class Class. These represent the primitive Java types boolean, byte, char, short, int, long, float, and double, and the keyword void, at run-time.

  • An uninstantiable placeholder class-Void-to hold a reference to the Class object representing the keyword void.

Applications

The Core Reflection API accommodates two categories of applications.

One category is comprised of applications that need to discover and use all of the public members of a target object based on its run-time class. These applications require run-time access to all the public fields, methods, and constructors of an object. Examples in this category are services such as Java(TM) Beans[1], and lightweight tools, such as object inspectors. These applications use the instances of the classes Field, Method, and Constructor obtained through the methods getField, getMethod, getConstructor, getFields, getMethods, and getConstructors of class Class.

The second category consists of sophisticated applications that need to discover and use the members declared by a given class. These applications need run-time access to the implementation of a class at the level provided by a class file. Examples in this category are development tools, such as interpreters, inspectors, and class browsers, and run-time services, such as Java(TM) Object Serialization[2]. These applications use instances of the classes Field, Method, and Constructor obtained through the methods getDeclaredField, getDeclaredMethod, getDeclaredConstructor, getDeclaredFields, getDeclaredMethods, and getDeclaredConstructors of class Class.

Reflection Model

The three classes Field, Method, and Constructor are final. Only the Java Virtual Machine may create instances of these classes; these objects are used to manipulate the underlying objects; that is, to:

  • get reflective information about the underlying member or constructor

  • get and set field values

  • invoke methods on objects or classes

  • create new instances of classes

The final uninstantiable class Array provides static methods that permit creating new arrays, and getting and setting the elements of arrays.

Member Interface

The classes Field, Method and Constructor implement the Member interface. The methods of Member are used to query a reflected member for basic identifying information. Identifying information consists of the class or interface that declared the member, the name of the member itself, and the Java language modifiers (such as public, protected, abstract, synchronized, and so on) for the member.

Field Objects

A Field object represents a reflected field. The underlying field may be a class variable (a static field) or an instance variable (a non-static field). Methods of class Field are used to obtain the type of the underlying field, and to get and set the underlying field's value on objects.

Method Objects

A Method object represents a reflected method. The underlying method may be an abstract method, an instance method, or a class (static) method.

Methods of class Method are used to obtain the formal parameter types, the return type, and the checked exception types of the underlying method. In addition, the invoke method of class Method is used to invoke the underlying method on target objects. Instance and abstract method invocation uses dynamic method resolution based on the target object's run-time class and the reflected method's declaring class, name, and formal parameter types. (Thus, it is permissible to invoke a reflected interface method on an object that is an instance of a class that implements the interface.) Static method invocation uses the underlying static method of the method's declaring class.

Constructor Objects

A Constructor object represents a reflected constructor. Methods of class Constructor are used to obtain the formal parameter types and the checked exception types of the underlying constructor. In addition, the newInstance method of class Constructor is used to create and initialize a new instance of the class that declares the constructor, provided the class is instantiable.

Array and Modifier Classes

The Array class is an uninstantiable class that exports class methods to create Java arrays with primitive or class component types. Methods of class Array are also used to get and set array component values.

The Modifier class is an uninstantiable class that exports class methods to decode Java language modifiers for classes and members. The language modifiers are encoded in an integer, and use the encoding constants defined by The Java Virtual Machine Specification.

Representation of Primitive Java Types

Finally, there are nine Class objects that are used to represent the eight primitive Java types and void at run-time. (Note that these are Class objects, not classes.) The Core Reflection API uses these objects to identify the following:

  • primitive field types

  • primitive method and constructor parameter types

  • primitive method return types

The Java Virtual Machine creates these nine Class objects. They have the same names as the types that they represent. The Class objects may only be referenced via the following public final static variables:

        java.lang.Boolean.TYPE

        java.lang.Character.TYPE

        java.lang.Byte.TYPE

        java.lang.Short.TYPE

        java.lang.Integer.TYPE

        java.lang.Long.TYPE

        java.lang.Float.TYPE

        java.lang.Double.TYPE

        java.lang.Void.TYPE
In particular, these Class objects are not accessible via the forName method of class Class.

Security Model

The Java security manager controls access to the Core Reflection API on a class-by-class basis. There are two levels of checks to enforce security and safety, as follows:

  • The methods of class Class that give reflective access to a member or a set of members of a class are the only source for instances of Field, Method, and Constructor. These methods first delegate security checking to the system security manager (if installed), which throws a SecurityException should the request for reflective access be denied.

  • Once the system security manager grants initial reflective access to a member, any code may query the reflected member for its identifying information. However, standard Java language access control checks-for protected, default (package) access, and private classes and members-will normally occur when the individual reflected members are used to operate on the underlying members of objects,that is, to get or set field values, to invoke methods, or to create and initialize new objects. Unrestricted access, which overrides standard language access control rules, may be granted to privileged code using the setAccessible method. This method is inherited from AccessibleObject by the classes Field, Method, and Constructor.

The initial policy decision is centralized in two methods of class SecurityManager:

void checkMemberAccess(Class,int) throws SecurityException

The Class parameter of checkMemberAccess identifies the class or interface whose members need to be accessed. The int parameter identifies the set of members to be accessed-either Member.PUBLIC or Member.DECLARED.

void checkPackageAccess(String pkg) throws SecurityException

The policy is determined based on what permissions are granted to the caller. There are two actions of class java.lang.RuntimePermission that affect these policies. These are:

  • accessDeclaredMembers. This grants the ability to reflect on non-public members of classes.

  • accessClassInPackage{package name}. This grants access to classes in the specified package. These permissions are determined by the security manager.

If the requested access to the specified set of members of the specified class is denied, the method should throw a SecurityException. If the requested access to the set is granted, the method should return.

As stated earler, standard Java language access control will usually be enforced when a reflected member from this set is used to operate on an underlying object, that is, when:

  • a Field is used to get or set a field value

  • a Method is used to invoke a method

  • a Constructor is used to create and initialize a new instance of a class

If access is denied at that point, the reflected member will throw an IllegalAccessException. Java language access control may be suppressed for a particular reflected member by setting a flag using the setAccessible method, as explained below.

Java Language Policy

The Java language security policy for applications is that any code may gain reflective access to all the members and constructors (including non-public members and constructors) of any class it may link against. By default, application code that gains reflective access to a member or constructor may only use the reflected member or constructor with standard Java language access control.

The standard policy may be overridden by calling the reflected member's setAccessible method. The ability to call the setAccessible method is in turn controlled by the suppressAccessChecks target of the permission ReflectPermission.

Data Conversions

Certain methods in the reflection package perform automatic data conversions between values of primitive types and objects of class types. These are the generic methods for getting and setting field and array component values, and the methods for method and constructor invocation.

There are two types of automatic data conversions. Wrapping conversions convert from values of primitive types to objects of class types. Unwrapping conversions convert objects of class types to values of primitive types. The rules for these conversions are defined in "Wrapping and Unwrapping Conversions."

Additionally, field access and method invocation permit widening conversions on primitive and reference types. These conversions are documented in The Java Language Specification, section 5, and are detailed in "Widening Conversions."

Wrapping and Unwrapping Conversions

A primitive value is automatically wrapped in an object when it is retrieved via Field.get or Array.get, or when it is returned by a method invoked via Method.invoke.

Similarly, an object value is automatically unwrapped when supplied as a parameter in a context that requires a value of a primitive type. These contexts are:

  • Field.set, where the underlying field has a primitive type

  • Array.set, where the underlying array has a primitive element type

  • Method.invoke or Constructor.newInstance, where the corresponding formal parameter of the underlying method or constructor has a primitive type

The following table shows the correspondences between primitive types and class (wrapper) types:

Primitive Type | Class Type
boolean | java.lang.Boolean
char | java.lang.Character
byte | java.lang.Byte
short | java.lang.Short
int | java.lang.Integer
long | java.lang.Long
float | java.lang.Float
double | java.lang.Double

A method that is declared void returns the special reference null when it is invoked via Method.invoke.

Widening Conversions

The reflection package permits the same widening conversions at run-time as permitted in method invocation contexts at compile time. These conversions are defined in The Java Language Specification, section 5.3.

Widening conversions are performed at run-time:

  • when a value is retrieved from a field or an array via the methods of Field and Array

  • when a value is stored into a field or an array via the methods of Field and Array

  • when an unwrapped actual parameter value is converted to the type of its corresponding formal parameter during method or constructor invocation via Method.invoke or Constructor.newInstance

The permitted widening primitive conversions are:

  • From byte to short, int, long, float, or double

  • From short to int, long, float, or double

  • From char to int, long, float, or double

  • From int to long, float, or double

  • From long to float or double

  • From float to double.

The permitted widening reference conversions are:

  • From a class type S to a class type T, provided that S is a subclass of T

  • From a class type S to an interface type K, provided that S implements K

  • From an interface type J to an interface type K, provided that J is a subinterface of K

Packaging

The Core Reflection API is in a subpackage of java.lang named java.lang.reflect. This avoids compatibility problems caused by Java's default package importation rules.

*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 © 1996, 1997, 1998 Sun Microsystems, Inc. All rights reserved.


Contents | Prev | Next Java Core Reflection

Acknowledgements

The reflection API was designed by Nakul Saraiya and Bill Joy, and benefited from substantial input from John Rose. Thanks also to our colleagues at JavaSoft and our external reviewers for their valuable comments.

References

JavaTM Beans Specification, JavaSoft

JavaTM Object Serialization Specification, JavaSoft

Contents | Prev | Next
Copyright © 1996, 1997, 1998 Sun Microsystems, Inc. All rights reserved.


Java Core Reflection

Overview
Applications
Reflection Model
Member Interface
Field Objects
Method Objects
Constructor Objects
Array and Modifier Classes
Representation of Primitive Java Types
Security Model
Java Language Policy
JDK 1.1 Security Policy
Data Conversions
Wrapping and Unwrapping Conversions
Widening Conversions
Packaging
Acknowledgements
References

Contents | Prev | Next
Copyright © 1996, 1997, 1998 Sun Microsystems, Inc. All rights reserved.


Reference Objects

 Documentation Contents
Reference objects support a limited degree of interaction with the garbage collector. A program may use a reference object to maintain a reference to some other object in such a way that the latter object may still be reclaimed by the collector. A program may also arrange to be notified some time after the collector has determined that the reachability of a given object has changed. Reference objects are therefore useful for building simple caches as well as caches that are flushed when memory runs low, for implementing mappings that do not prevent their keys (or values) from being reclaimed, and for scheduling pre-mortem cleanup actions in a more flexible way than is possible with the Java finalization mechanism.
API Specification
(javadoc)
  • java.lang.ref
  • java.lang.ref.Reference
  • java.lang.ref.ReferenceQueue
  • java.lang.ref.SoftReference
  • java.lang.ref.WeakReference
  • java.lang.ref.PhantomReference

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-gc-comments@eng.sun.com. This is not a subscription list. 		Sun
Java Software


Resources

 Documentation Contents
The Java platform supports supports resource access in a location-independent manner.
Programming Guides
  • Accessing Resources in a Location-Independent Manner.

API References
(javadoc)
  • java.lang.Class class
  • java.lang.ClassLoader class
  • java.net.URLClassLoader class
  • java.util.ResourceBundle class
  • java.lang.SecurityManager class
  • java.security Package
Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: pelegri@eng.sun.com

Sun Microsystems, Inc
Java Software


Accessing Resources

Accessing Resources in a Location-Independent Manner

Code written for the Java 1.0 platform uses two mechanisms to access resources.

  • Applets use Applet.getCodeBase() to get a URL to the base of the code for the applet. This base can be extended with a "relative path" to point to the desired resource, which can then be loaded (for example using Applet.getAudioClip(url)).
  • Applications use "well known locations" (such as System.getProperty("user.home") or System.getProperty("java.home")). They add "/lib/<resource>" to the location and then open that file.

The Java 1.0 platform lacks a mechanism to locate resources that are independent of the code. That is, there is no way locate resources for an applet loaded from the net using multiple http connects, or for an applet loaded using JAR files, or for a Bean loaded or a Bean installed in the CLASSPATH, or for a "library" installed in the CLASSPATH, and so on. The APIs described here provide such a mechanism.

The I18N APIs use this API as a primitive operation to locate ResourceBundles. See the latest I18N documentation for details.

Resources, names, and contexts

A resource is identified by a String. This String, while possibly empty, is a /-separated sequence of substrings, each a valid Java programming lanaugage identifier, followed by a name of the form "<shortName>" or "<shortName>.<extension>". Both "shortName" and "extension" are composed of valid Java Letters and Numbers (section 3.8 in JLS). If the optional sequence exists, it is separated from the "shortName" by a /.

The name of a resource is independent of the Java implementation; in particular, the / is always used as a separator. 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 ClassLoader instance. Methods implemented by the ClassLoader do this interpretation.

System Resources

A system resource is similar to a system class (section 20.14.5 of the JLS). A system resource is a resource that is either built-in to the system, or it is kept by the host implementation in, for example, a local file system. System resources are accessed through special methods (getSystemResource and getSystemResourceAsStream) that consult the base host implementation.

For example, in a particular implementation, locating a system resource may involve searching the entries in the CLASSPATH. Each directory, zip file, or jar file entry in the CLASSPATH is searched for the resource file, and, if found, either an InputStream, or its name, is returned. If not found, null is returned. Note that a resource may be found in a different entry in the CLASSPATH than where the class file was loaded.

Non-System Resources

The implementation of getResource on a given ClassLoader will depend on the details of the ClassLoader. For example AppletClassLoader will:
  • First try to locate the resource as a system resource; then, if not found,
  • Search through the resources in ARCHIVES (JAR files) already loaded in this CODEBASE; then, if not found,
  • Use CODEBASE and attempt to locate the resource (which may involve contacting a remote site).

All ClassLoaders 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, convert all "." to "/", and add a resource name of the form "<Name>.<ext>". 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.

Manipulating Resources

The method getResource() returns a URL for the resource. The URL (and its representation) is implementation and JVM*-instance specific (the URL obtained in one runtime instance may not work in another) and may vary depending on the implementation details Its protocol is (usually) specific to the ClassLoader loading the resource. If the resource does not exist, a null will be returned; if the resource is not visible due to security considerations, a null will also be returned.

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() is semantically identical to getResource().openStream(), except that IO exceptions are caught and returned as a null InputStream.

The client code code can also request the contents of the resource as an object by applying the getContent() method on the url. This is useful when the resource contains the data for an image, for instance. Note that in this case, the result is an awt.image.ImageProducer object, not an Image object.

API Additions to Class

Specifically, the class Class methods are of the following form:

class Class {

    /**
     * Find a resource with a given name.  Will return null if no
     * resource with this name is found.  The rules for searching a
     * resources associated with a given class are implemented by the
     * ClassLoader of the class.
     *
     * 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 "." to "/".
     *
     * @see java.lang.ClassLoader
     */
    public InputStream getResourceAsStream(String name) {
    name = resolveName(name);
    ClassLoader cl = getClassLoader();
    if (cl==null) {
        // A system class.
        return ClassLoader.getSystemResourceAsStream(name);
    }
    return cl.getResourceAsStream(name);
    }

    public java.net.URL getResource(String name) {
    name = resolveName(name);
    ClassLoader cl = getClassLoader();
    if (cl==null) {
        // A system class.
        return ClassLoader.getSystemResource(name);
    }
    return cl.getResource(name);
    }

    /**
     * Add a package name prefix if the name is not absolute
     * Remove leading "/" if name is absolute
     */
    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;
    }

Note that it is possible, albeit somewhat uncommon, to have two classes in two diffent packages sharing the same resource.

API Additions to ClassLoader

We provide two sets of methods to access a resource. One set returns an InputStream on the resource. The other set returns a URL. The methods that return an InputStream are somewhat 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.

Resources are managed through ClassLoaders in a manner analogous to 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. Class Class provides some convenience methods that delegate functionality to the appropriate ClassLoader methods.

Many Java programs will access these methods indirectly through the I18N APIs. Others will access it through methods in class 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 (cf. the methods in Class). The name should not have a leading "/".

class ClassLoader {

    /**
     * A resource is some data (images, audio, text, etc) that wants to be
     * accessed by some class code in a way that is independent of the
     * location of the code.  Resources are found with cooperation of the
     * class loaders, since they are the only ones who know where the class
     * actually came from.

     *
     * 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 as a URL.
     *
     * @see	Class
     */

    /**
     * Get an InputStream on a given resource..  Will return null if no
     * resource with this name is found.

     *
     * The resource name may be any system resource (e.g. follows CLASSPATH order)
     * @param	name	the name of the resource, to be used as is.
     * @return		an InputStream on the resource, or null if not found.
     */

    public static final InputStream getSystemResourceAsStream(String name) {
    ... this is equivalent to getSystemResource() call plus a openStream()
    }

    /**
     * Find a resource with a given name.  The return is a URL to the resource
     * Doing a getContent() on the URL may return an ImageProducer, an AudioClip, or
     * an InputStream.

     *
     * The resource name may be any system resource (e.g. follows CLASSPATH order)
     * @param	name	the name of the resource, to be used as is.
     * @return		the URL on the resource, or null if not found.
     */
    public static final java.net.URL getSystemResource(String name) {
    ...
    }

    /**
     */

    /**
     * Get an InputStream on a given resource.  Will return null if no
     * resource with this name is found.

     *
     * The class loader can choose what to do to locate the resource.
     * @param	name	the name of the resource, to be used as is.
     * @return		an InputStream on the resource, or null if not found.
     */
    public InputStream getResourceAsStream(String name) {
    return null;
    }

    /**
     * Find a resource with a given name.  The return is a URL to the resource.
     * Doing a getContent() on the URL may return an ImageProducer, an AudioClip,
     * or an InputStream.

     *
     * The class loader can choose what to do to locate the resource.
     * @param	name	the name of the resource, to be used as is.
     * @return		an InputStream on the resource, or null if not found.
     */
    public java.net.URL getResource(String name) {
    return null;
    }

    }

Client code

Below are two examples of client code. The first example uses "absolute resource" names and traditional mechanisms to get a class 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.
    }

The second example uses "relative resource" names and the new mechanism, available from the compiler through the -experimental flag, to get a class 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.
    }

Security Details

Since getResource() provides access to information, it must have well defined and well founded security rules that at the same time support the intended use of this mechanism. Below we describe the exact details, as specified and implemented in releases starting at version 1.1.5 of the Java Development Kit. The semantics are described only for ClassLoader.getResource and ClassLoader.getSystemResource() and extend to the AsStream methods as defined in the previous section.

If security considerations do not allow a resource to be visible in some security context, the getResource() method will fail (will return null) as if the resource was not present at all, this addresses existence attacks.

All classloaders will not provide access to the contents of a .class file. This is for both security and performance issues. Whether it is possible to obtain a URL into 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 some 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 Class Loader provides access to information in the CLASSPATH. A CLASSPATH may have directories and/or JAR files. Since a JAR file is created intentionally, we ascribe a different significance to it than in 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 the 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 getContent() on corresponding URLs.

Related Topics & Known Bugs

The getResource interface does not provide specific support for locating localized resources. Localized resources are supported by the internationalization facilities.

*As used on this web site, the terms "Java Virtual Machine" or "JVM" mean a virtual machine for the Java platform.

Copyright © 1996-98 Sun Microsystems, Inc. All Rights Reserved. Please send comments to: jdk-comments@java.sun.com Sun Microsystems, Inc
Java Software


    Remote Object Activation

 Documentation Comments
    Prior to the release of the JavaTM 2 SDK, an instance of a UnicastRemoteObject could be accessed from a program that (1) created an instance of the remote object, and (2) ran all the time. Now with the introduction of the class java.rmi.activation.Activatable and the RMI daemon, rmid, programs can be written to register information about remote object implementations that should be created and execute "on demand", rather than running all the time. The RMI daemon, rmid, provides a Java virtual machine* (JVM) from which other JVM instances may be spawned.

    Starting out with activation
    None of the activation tutorials should be the first material you read on RMI. If you have never used RMI before, you should take a look at Getting Started before you try these. The first three activation tutorials are intended for developers who have had some experience developing Java programs that access remote objects by means of the RMI classes provided as part of the Java 2 SDK.

    • Creating an Activatable Object

      • This tutorial illustrates the process of creating a new class that extends java.rmi.activation.Activatable.
    • Making a UnicastRemoteObject Activatable

      • This tutorial takes you through the process of moving an existing remote object implementation, that extends UnicastRemoteObject, to a class that extends java.rmi.activation.Activatable.
    • Activating an object that does not extend java.rmi.activation.Activatable

      • This tutorial shows you how to use the static method Activatable.exportObject in the constructor of a class that does not extend from Activatable, and how to create a remote interface, based on the methods that should be made available to remote clients.

    Going further with activation
    This next tutorial on using a MarshalledObject is intended for developers who have gone through at least one of the first three activation tutorials. More tutorials may be added to this section in a future release, based on your feedback.
    • Using a MarshalledObject to create persistent data

For all of the source code used in the activation tutorials, you may choose from these formats:

  • activation.zip
  • activation.tar
  • activation.tar.Z
For more information on object activation, you can also refer to the RMI Specification.

We are very interested in knowing whether these tutorials are useful. Please send any comments or suggestions to: rmi-comments@java.sun.com, with a subject of "activation tutorials".

*As used on this web site, the terms "Java virtual machine" or "JVM" mean a virtual machine for the Java platform.

Copyright © 2003 Sun Microsystems, Inc. All Rights Reserved.
Please send comments to: rmi-comments@java.sun.com 		Sun


Dynamic code downloading using 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 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 JavaTM platform is the ability to dynamically download Java software from any Uniform Resource Locator (URL) to a Java virtual machine* (JVM) 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 (RMI).

For example, a JVM 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 RMI API any JVM, not only those in browsers, can download any Java class file including specialized 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 Java 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 JVM, 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 RMI

Using RMI, applications can create remote objects that accept method calls from clients in other JVMs. 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, 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 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 RMI server registers a remote object, bound to a name, with the RMI registry. The codebase set on the server JVM is annotated to the remote object reference in the RMI registry.

  2. The 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 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 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.
    6. 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 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 JVM, the RMI client uses the remote object's codebase to execute code in another, potentially remote JVM, as illustrated in Figure 3:
illustrates the final step of the above procedure

Figure 3: RMI client making a remote method call

4.0 Using codebase in 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: 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 JVMs. 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 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 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 RMI stubs, can be downloaded if your 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 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 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 RMI client code, then your problem is the CLASSPATH with which your 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.

We are very interested in knowing whether these tutorials are useful. Please send any comments or suggestions to: rmi-comments@java.sun.com, with a subject of "codebase tutorial".

*As used on this web site, the terms "Java virtual machine" or "JVM" mean a virtual machine for the Java platform.

Copyright © 2003 Sun Microsystems, Inc. All Rights Reserved.
Please send comments to: rmi-comments@java.sun.com 		Sun


Applying the Factory Pattern to 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 introduced in the book, Design Patterns, Elements of Reusable Object-Oriented Software. 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 RMI, you can reduce the number of objects that you need to register with the 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 RMI?

Just like any other 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 andthe ProductImpl implements the Product interface
Illustrates the 6 actions listed below.

  1. The FactoryImpl registers, or is registered, with the rmiregistry
  2. The client requests a reference to a Factory
  3. The rmiregistry returns a remote reference to a FactoryImpl
  4. The client invokes a remote method on the FactoryImpl to obtain a remote reference to a ProductImpl
  5. The FactoryImpl returns a remote reference to an existing ProductImpl or to one that it just created, based on the client request
  6. The client invokes a remote method on the ProductImpl

How Could the Bank and Library be Implemented in 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 RMI, only the instance of the AccountManager implementation would be registered with the 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 RMI, only the instance of the Librarian implementation would be registered with the 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 RMI.
Copyright © 2003 Sun Microsystems, Inc. All Rights Reserved.
Please send comments to: rmi-comments@java.sun.com 		Sun


Frequently Asked Questions - RMI and Object Serialization

Java(TM) Software, a Division of Sun Microsystems(TM)

Frequently Asked Questions
RMI and Object Serialization

 Contents of the
JavaTM 2 SDK,
Standard Edition,
v1.4

RMI

Very Frequent Questions

  • A.1 Why do I get an exception for an unexpected hostname and/or port number when I call Naming.lookup?
  • A.2 Do I have to install the _Stub file in the client's CLASSPATH? I thought it could be downloaded.
  • A.3 Does RMI require me to use an HTTP server?
  • A.4 Why am I getting a ClassNotFoundException?
  • A.5 Why does the RMI implementation create so many sockets when my application uses custom socket factories; or why are stubs (using a custom socket factory) that refer to the same remote object not equal; or why does the RMI implementation not reuse server-side ports when I use a custom server socket factory?

Debugging RMI programs

  • B.1 Will there be debugging mechanisms built into RMI?
  • B.2 I am having a problem debugging my program on Windows 95. Any suggestions?
  • B.3 Why do I get a java.lang.ClassMismatchError while running my program?
  • B.4 I am sending an array of remote objects and receive an ArrayStoreException. What's going on?
  • B.5 I have local objects that are synchronized. When I make them remote, my application hangs. What's the problem?
  • B.6 I am getting a ClassNotFoundException for my stub class when I try to register a remote object in the registry. What's happening?
  • B.7 My server died. Can I get a trace of the server activity?
  • B.8 Where can I find a list of system properties that might be useful for implementing and debugging RMI applications?

Networking

  • C.1 How do RMI clients contact remote RMI servers?
  • C.2 Why does my remote method or "callback" routine fail with a nested java.net.UnknownHostException?
  • C.3 My server is using a fully qualified domain name or IP address, so why do I still get an UnknownHostException?
  • C.4 I am using the latest release of the Java 2 Software Development Kit (SDK) and I have a host that has multiple IP addresses. RMI is choosing the wrong IP address for its server hostname, how do I work around this problem?
  • C.5 How does RMI obtain a server hostname in each of the versions of the JDK?
  • C.6 Why do Naming.bind and Naming.lookup take an extraordinarily long time on Windows?
  • C.7 How do I use RMI on a Windows 95 standalone machine, not connected to the network?
  • C.8 Why do I get the exception "java.net.SocketException: Address already in use" when I try to run the registry?
  • C.9 How can I use RMI through a firewall?
  • C.10 How can I make outgoing RMI calls through a local firewall?
  • C.11 How can I receive incoming RMI calls through a local firewall?
  • C.12 So what do I have to do to get RMI to operate through two firewalls?
  • C.13 Is it possible to replace the java-rmi.cgi script that comes with the JDK distribution with a servlet?

Using RMI to achieve X (for some X)

  • D.1 Is there a way to get automatic notification as soon as a remote virtual machine fails?
  • D.2 From within a virtual machine, can a new virtual machine be spawned on a remote machine?
  • D.3 Is it possible for a remote object to be notified when all clients disconnect?
  • D.4 Why doesn't my server program exit when all clients disconnect?
  • D.5 How does the distributed garbage collector detect a client that disconnects? Is it advisable to use System.exit for graceful client termination?
  • D.6 How can my server tell when a client crashes?
  • D.7 The unreferenced() method doesn't get called until ten minutes after I have stopped using the remote object! How can I shorten this delay?
  • D.8 Why can't I get an immediate notification when a client crashes?
  • D.9 How do I run the rmic command in a DOS batch file?
  • D.10 In a remote object implementation, how can I find the host name of the caller of a remote method?
  • D.11 Does RMI handle "out" and "inout" parameters (like CORBA)?
  • D.12 Normally in the Java programming language, it is possible to cast an interface instance to an instance of the class from which it was created and use the result. Why doesn't this work in RMI?

How does RMI work with X (for some X)

  • E.1 What if my browser does not support the JDK or J2SE version I need?
  • E.2 Can I implement remote observer/observable objects in RMI?

Internals, resources, and performance

  • F.1 At what point is there a "live" connection between the client and the server and how are connections managed?
  • F.2 Does the Java platform replace all remote objects with their stubs during a remote method invocation?
  • F.3 Is it possible to write a new transport layer for RMI which does not use sockets? As a follow-up question, how about a transport layer that uses non-TCP based sockets?
  • F.4 I notice the registry continues to use CPU resources, as if it were polling rather than blocking on a select() call. Is the registry implemented by polling?
  • F.5 Is there only one socket connection between a client process and the server, no matter how many stubs exist in that client process?

Miscellaneous

  • G.1 What are the licensing issues surrounding the use of RMI?
  • G.2 I have a single-threaded program that waits on standard input for a user command which will initiate an RMI call. However, my remote object cannot service this incoming remote call as the program appears to be blocked on standard input. What's the problem?
  • G.3 I am copying array elements to my remote server and changing the values, but the incremented values are not copied back to the client. Why?
  • G.4 Am I allowed to have static fields in a remote interface?
  • G.5 I locate the registry, but then it seems that it's not there, what's happening?
  • G.6 I can't find the answer to my question here, are there any other resources?

Object Serialization

  1. Why must classes implement Serializable in order to be written to an ObjectOutputStream?
  2. Which JDK v1.1 system classes are marked serializable?
  3. I am having problems deserializing AWT components. How can I make this work?
  4. Does object serialization support encryption?
  5. The object serialization classes are stream oriented. How do I write objects to a random-access file?
  6. When a local object is serialized and passed as a parameter in an RMI call, are the bytecodes for the local object's methods also passed? What about object coherency, if the remote virtual machine (VM) application "keeps" the object handle?
  7. How can I create an ObjectInputStream from an ObjectOutputStream without a file in between?
  8. I create an object and then send it across the net using the writeObject method and receive it using the readObject method. If I then change the value of a field in the object and send it as before, the object that the readObject method returns appears to be the same as the first object and does not reflect the new value of the field. Should I be experiencing this behavior?
  9. Are there any plans to support the serialization of thread objects?
  10. Can I compute diff(serial(x),serial(y))?
  11. Can I compress the serial representation of my objects using my own zip and unzip methods?
  12. Can I execute methods on compressed versions of my objects, for example isempty(zip(serial(x)))?
  13. If I try to serialize a font or image object and then try to reconstitute it in a different VM, my application dies. Why?
  14. How do I serialize a tree of objects?
  15. If class A does not implement Serializable but a subclass B implements Serializable, will the fields of class A be serialized when B is serialized?

RMI

A.1 Why do I get an exception for an unexpected hostname and/or port number when I call Naming.lookup?

The hostname and port number you see in the exception trace represent the address on which the looked-up server believes it is listening. While the RMI server can theoretically be on any host, it is usually the same host as that on which the registry is running, and on a different port.

Even if the server is mistaken about its hostname or IP address (or has a hostname that simply isn't resolvable by clients), it will still export all of its objects using that mistaken hostname, but you will see an exception every time you try to receive one of those objects.

The hostname which you specified in Naming.lookup to locate the registry has no effect on the hostname which is already embedded in the remote reference to the server.

Usually, the mysterious hostname is the unqualified hostname of the server, or a private name unknown to the client's nameservice, or (in the case of Microsoft Windows platforms) the server's Network->Identification->Machine Name.

The appropriate workaround is to set the system property java.rmi.server.hostname when starting the server. The value of the property should be the externally reachable hostname (or IP address) of the server -- whatever works when specified as the host-part in Naming.lookup is good enough.

For more detail, see the questions on callbacks and fully qualified domain names.

A.2 Do I have to install the _Stub file in the client's CLASSPATH? I thought it could be downloaded.

A stub class can be downloaded, if the server that is exporting the remote object annotates the marshalled stub instance with the java.rmi.server.codebase property, which indicates the location from where the stub class can be loaded. You should set the java.rmi.server.codebase property on the server exporting a remote object. While remote clients could set this property, they would then be limited to only getting remote objects from the specified codebase. You should not assume that any client VM will have specified a codebase that resolves to the location of your object.

When a remote object is marshalled by RMI (whether as an argument to a remote call or as a return value), the codebase for the stub class is retrieved by RMI and used to annotate the serialized stub. When the stub is unmarshalled, the codebase is used to load the stub classfile using the RMIClassLoader, unless the class can already be found in the CLASSPATH or by the context classloader for the receiving object, such as an applet codebase.

If the _Stub class was loaded by an RMIClassLoader, then RMI already knows which codebase to use for its annotation. If the _Stub class was loaded from the CLASSPATH, then there is no obvious codebase, and RMI consults the java.rmi.server.codebase system property to find the codebase. If the system property is not set, then the stub is marshalled with a null codebase, which means that it cannot be used unless the client has a matching copy of the _Stub classfile in the client's CLASSPATH.

It is easy to forget to specify the codebase property. One way to detect this error is to start the rmiregistry separately and without access to the application classes. This will force Naming.rebind to fail if the codebase is omitted.

For more information on the java.rmi.server.codebase property, please take a look at our tutorial, Dynamic code downloading using RMI (Using the java.rmi.server.codebase Property).

A.3 Does RMI require me to use an HTTP server?

No. You can set your java.rmi.server.codebase property to use any valid URL protocol, such as file or ftp. Using an HTTP server just makes your life simpler by providing an automated mechanism for class file downloading. If you don't have access to an HTTP server nor the inclination to set one up, you can use our small class file server found at ftp://ftp.java.sun.com/pub/jdk1.1/rmi/class-server.zip.

A.4 Why am I getting a ClassNotFoundException?

Most likely the java.rmi.server.codebase property has not been set (or has not been set correctly) on a VM that is exporting your remote object(s). Please take a look at our tutorial, Dynamic code downloading using RMI (Using the java.rmi.server.codebase Property).

A.5 Why does the RMI implementation create so many sockets when my application uses custom socket factories; or why are stubs (using a custom socket factory) that refer to the same remote object not equal; or why does the RMI implementation not reuse server-side ports when I use a custom server socket factory?

The RMI implementation attempts to reuse open sockets where possible for remote invocations. When a remote method is invoked on a stub that uses a custom socket factory, the RMI implementation will reuse an open connection (if any) as long as that socket was created by an equivalent socket factory. Since client socket factories are serialized to clients, a single client may have several distinct copies of the same logical socket factory. To ensure that the RMI implementation will reuse sockets created by custom socket factories, make sure your custom client socket factory classes implement the hashCode and equals methods appropriately. If the client socket factory does not implement these methods correctly, another ramification is that stubs (using the client socket factory) that refer to the same remote object will not be equal.

The RMI implementation attempts to reuse server-side ports as well. It will only do so if there is an existing server socket for the port created by an equivalent socket factory. Make sure the server socket factory class implements the hashCode and equals methods too.

If your socket factory has no instance state, a trivial implementation of the hashCode and equals methods are the following:

    public int hashCode() { return 57; }
    public boolean equals(Object o) { return this.getClass() == o.getClass() }

B.1 Will there be debugging mechanisms built into RMI?

RMI supports a simple call-logging facility for debugging. But there are no current plans to support a full-featured, interactive, remote debugger.

B.2 I am having a problem debugging my program on Windows 95. Any suggestions?

The javaw command throws away output to stdout and stderr, so for debugging purposes it is better to run the java command in a separate window so that you can see reported errors. To do this, execute a command like the following:
        start java EchoImpl

It is advised not to use the javaw command during development. To watch the server activity, start the server with -Djava.rmi.server.logCalls=true.

B.3 Why do I get a java.lang.ClassMismatchError while running my program?

You probably modified one or more classes that were being used by RMI programs while your program was running. Try restarting all RMI applications (including java.rmi.registry.RegistryImpl). This should clear things up.

B.4 I am sending an array of remote objects and receive an ArrayStoreException. What's going on?

RMI replaces the remote objects with the stub and therefore the type of the array must be that of the interface. The code would look like:
   FooRemote[] f = new FooRemote[10];
   for (int i = 0; i < f.length; i++) {
      f[i] = new FooRemoteImpl();
   }

Now RMI can put the stub into each cell of the array without an exception on the remote call.

B.5 I have local objects that are synchronized. When I make them remote, my application hangs. What's the problem?

What you encountered was distributed deadlock. In the local VM case, the VM can tell that the calling object "A" owns the lock and will allow the call back to "A" to proceed. In the distributed case, no such determination can be made, so the result is deadlock.

Distributed objects behave differently than local objects. If you simply reuse a local implementation without handling locking and failure, you will probably get unpredictable results.

B.6 I am getting a ClassNotFoundException for my stub class when I try to register a remote object in the registry. What's happening?

When you make a call to the registry to bind an object, the registry actually binds a reference to the stub for the remote object. In order to instantiate a stub object, the registry VM needs to be able to load its class definition. The VM (in this case the server VM) that sends the serialized forms of a stub in a remote method call to the registry is responsible for annotating the stub with the location from which its classes can be downloaded. If stubs are not annotated properly, RMI will throw a ClassNotFoundException when it tries to instantiate the stub.

To annotate classes properly, the server needs to set the value of the java.rmi.server.codebase property value to the location(s) of the stub classes. RMI will automatically annotate the serialized form of outgoing object instances with the value of the java.rmi.server.codebase property.

NOTE: It is possible (and in a small number of environments appropriate) to enable the rmiregistry to unmarshal stub objects by placing all relevant stub class files in the CLASSPATH of the rmiregistry. However, the rmiregistry does not have to download stub classes. If stub classes are available locally, it will use those classes. Using the rmiregistry's CLASSPATH for stub deployment requires that all VMs that reference a stub instance obtained from that registry have the stub's class file installed locally (in the VM's CLASSPATH).

For example, if the registry loads stub classes from its CLASSPATH, when the registry sends serialized stub objects to other VMs, those serialized objects will be annotated with the value of the registry's java.rmi.server.codebase property (which will almost always be null). If the VMs receiving serialized stub objects from the registry do not have the class files for those stubs installed locally then those VMs are likely to throw a ClassNotFoundException.

Instead, if classes are downloaded dynamically from a server VM's java.rmi.server.codebase annotation, only the server VM needs to have the stub classes in its CLASSPATH. With this approach, application deployment is simpler and it is possible to introduce new stub versions into a running distributed system.

For more information on dynamic code downloading in RMI, please see the tutorial, Dynamic code downloading using RMI (Using the java.rmi.server.codebase).

B.7 My server died. Can I get a trace of the server activity?

To get a trace of the server activity, start the server as follows:
    java -Djava.rmi.server.logCalls=true YourServerImpl
where YourServerImpl is the name of your server. If your server has hung, you can get a monitor dump and thread dump by doing a ctrl-\ on the SolarisTM Operating Environment (Solaris OE) and a ctrl-break on Microsoft Windows platforms.

B.8 Where can I find a list of system properties that might be useful for implementing and debugging RMI applications?

Properties that begin with "java.rmi." are elements of the public specification and are documented in the Java RMI Specification.

Properties that begin with "sun.rmi." are only supported by certain versions of the JDKTM software or JavaTM 2 Platform, Standard Edition (J2SETM) from Sun Microsystems. While these "sun.rmi.*" properties can be quite useful for debugging and tuning at runtime, please note that they are not considered part of the public API, and their use is subject to change (or may be removed completely) in future versions of the implementation.

C.1 How do RMI clients contact remote RMI servers?

Illustrates the means by which RMI clients contact remote RMI servers, as discussed below.

For an RMI client to contact a remote RMI server, the client must first hold a reference to the server. The Naming.lookup method call is the most common mechanism by which clients initially obtain references to remote servers. Remote references may be obtained by other means, for example: all remote method calls can return remote references. This is what Naming.lookup does; it uses a well-known stub to make a remote method call to the rmiregistry, which sends back the remote reference to the object requested by the lookup method.

Every remote reference contains a server hostname and port number that allow clients to locate the VM that is serving a particular remote object. Once an RMI client has a remote reference, the client will use the hostname and port provided in the reference to open a socket connection to the remote server.

Please note that with RMI the terms client and server can refer to the same program. A Java program that acts as an RMI server contains an exported remote object. An RMI client is a program that invokes one or more methods on a remote object in another virtual machine. If a VM performs both of these functions, it may be referred to as an RMI client and an RMI server.

C.2 Why does my remote method or "callback" routine fail with a nested java.net.UnknownHostException?

In many versions of the JDK (all versions of the JDK except in v1.1 and the latest releases), RMI may default to using an unresolvable server hostname (for example: unqualified names, Windows Internet Naming Service (WINS) names, or unqualified DHCP names). When an RMI client invokes a remote method using a reference that contains an unresolvable server hostname, the client will throw an UnknownHostException.

In order to generate functional remote references, RMI servers must be able to supply a fully qualified hostname or IP address that is resolvable from all RMI clients (an example of a fully qualified hostname is foo.bar.com). If an RMI program provides a remote callback operation, then that program serves an RMI object and consequently, must be able to determine a resolvable hostname to use as its server hostname in the remote references it passes to RMI clients. VM's that make calls to applets that serve remote objects may throw UnknownHostExceptions because the applet has failed to provide a usable server hostname.

If your RMI application throws an UnknownHostException, you can look at the resulting stack trace to see if the hostname that the client is using to contact its remote server is incorrect or not fully qualified. If necessary, you can set the java.rmi.server.hostname property on the server to the correct IP address or hostname of the server machine and RMI will use this property's value to generate remote references to the server.

C.3 My server is using a fully qualified domain name or IP address, so why do I still get an UnknownHostException?

Depending on the configuration of your network's name service, a fully qualified hostname that is recognized on one RMI host may not be resolvable from another RMI host. Some examples where this situation may arise are:
  • Misconfigured DHCP servers may set the fully qualified domain name of RMI server machines to be the domain name of the resolver domain instead of the domain in which the RMI server actually resides. In this case, RMI clients outside the server's DHCP domain will be unable to contact the server, because of its incorrect domain name.
  • The server machine is on a network that is configured to use WINS. Hosts that are only registered under WINS may not be reachable by hosts that rely solely upon DNS.
  • The RMI client and server reside on opposite sides of a firewall. If your RMI client lies outside a firewall and the server resides inside it, the client will not be able to make any remote calls to the server. If the RMI client lies inside the firewall, you will need to configure the RMI client to contact the server using HTTP.

C.4 I am using the latest release of the JDK and I have a host that has multiple IP addresses. RMI is choosing the wrong IP address for its server hostname. How do I work around this problem?

Set the java.rmi.server.hostname property to the correct IP address of the RMI server machine. You can also specify that your server use a fully qualified hostname obtained from a name service by setting the property:
    java.rmi.server.useLocalHostname=true

C.5 How does RMI obtain a server hostname in each of the versions of the JDK?

Methods that RMI uses to obtain a server hostname in each of the versions of the JDK:

JDK v1.1

RMI relied upon java.net.InetAddress.getLocalHost() to return a fully qualified domain name. InetAddress objects initialized local hostnames in a static block of code, performing a reverse lookup on the local IP address to retrieve a local hostname. However, on machines that were not connected to the network, this behavior caused the program to hang while InetAddress looked for a hostname that could not be found.

JDK v1.1.1-1.1.6

To work around the JDK v1.1 problem on stand-alone systems, InetAddress was modified in JDK v1.1.1 to only retrieve the [potentially unqualified] hostname returned from a native system call, which did not attempt to consult a name service. RMI was not modified to compensate for this change since the property java.rmi.server.hostname allowed users to override incorrect hostnames provided by InetAddress. RMI made no attempt to consult a name service and could default to using unqualified hostnames.

Later versions

To compensate for the many problems that were generated by the v1.1.1 change in functionality of InetAddress, the following behavior has been integrated into the most recent versions of the JDK:

RMI will use an IP address or a fully qualified domain name to identify a machine that serves a remote object. Server hostnames are initialized to the value obtained by performing the following actions:

  1. By default, RMI uses the IP address of the server host as the server name for remote references.
  2. If the property java.rmi.server.hostname is set, RMI will use its value as the server hostname, and will not attempt to find a fully qualified domain name through any other method. This property takes precedence over all other means of finding an RMI server name.
  3. If the property java.rmi.server.useLocalHostname is set to true (by default, the value of this property is false), RMI applies the following routine to obtain a hostname for the RMI server:
    1. If the value returned by the InetAddress.getLocalHost().getHostName() method contains a "." character, then RMI will assume that this value is the server's fully qualified domain name and will use it as the server hostname.
    2. Otherwise, RMI will spawn a thread to query the local name service for the fully qualified domain name of the RMI server. If the name service takes too long to return, or the name service returns but its response does not contain a "." then RMI will use the server's IP address obtained from InetAddress.getLocalHost().getHostAddress().
    Users can override the default time (10 seconds or 10000 milliseconds) that RMI will look for a fully qualified domain name by setting the following property:
    sun.rmi.transport.tcp.localHostnameTimeOut=timeOutMillis
    where timeOutMillis is the time that RMI will wait in milliseconds. For example:
                java -Dsun.rmi.transport.tcp.localHostnameTimeOut=2000 MyServerApp
When using activatable remote objects, it is recommended that RMI servers set the value of the java.rmi.server.useLocalHostname property to true. In general, hostnames are more stable than IP addresses. Activatable remote objects tend to last longer than transient remote objects (for example, surviving a reboot). An RMI client will be more likely to locate a remote object over a long period of time if it uses a qualified hostname rather than an explicit IP address.

C.6 Why do Naming.bind and Naming.lookup take an extraordinarily long time on Microsoft Windows platforms?

Most likely, your host's networking setup is incorrect. RMI uses the Java API networking classes, in particular java.net.InetAddress, which will cause TCP/IP host name lookups - both host to address mapping and address to hostname mapping (the InetAddress class does this for security reasons). On Microsoft Windows platforms, the lookup functions are performed by the native socket library, so the delays are happening not in RMI, but in the libraries. If your host is set up to use DNS, then it is usually a problem with the DNS server not knowing about the hosts involved in communication, and what you are experiencing are DNS lookup timeouts. Try specifying all the involved hostnames/addresses in the local file \winnt\system32\drivers\etc\hosts or \windows\hosts. The format of a typical host file is:
    IPAddress     Machine Name
e.g.:
    208.2.84.61   homer
This should dramatically cut down the time it takes to make the first lookup.

C.7 How do I use RMI on a Windows 95 standalone machine, not connected to the network?

To get RMI working on a Windows 95 machine that is not on a network, TCP/IP must be configured. One way to accomplish this is to configure an unused COM port as a dedicated PPP or SLIP connection. Then disable DHCP and manually configure an IP address (e.g. 192.168.1.1). You should then find that from a DOS Shell, you can ping yourself (for example, ping mymachine). You should now be able to run the stock RMI example.

C.8 Why do I get the exception "java.net.SocketException: Address already in use" when I try to run the registry?

This exception means that the port that the RegistryImpl uses (by default 1099) is already in use. You may have another registry running on your machine and will need to stop it.

C.9 How can I use RMI through a firewall?

It depends on whether you need to traverse a firewall for outgoing calls or for incoming calls.

C.10 How can I make outgoing RMI calls through a local firewall?

There are three main methods: HTTP tunnelling, SOCKS, and downloaded socket factories.

HTTP tunnelling

This well-worn method is popular since it requires almost no setup, and works quite well in firewalled environments which permit you to handle HTTP through a proxy, but disallow regular outbound TCP connections.

If RMI fails to make a normal (or SOCKS) connection to the intended server, and it notices that a HTTP proxy server is configured, it will attempt to tunnel RMI requests through that proxy server, one at a time.

There are two forms of HTTP tunnelling, tried in order. The first is http-to-port; the second is http-to-cgi.

In http-to-port tunneling, RMI attempts a HTTP POST request to a http: URL directed at the exact hostname and port number of the target server. The HTTP request contains a single RMI request. If the HTTP proxy accepts this URL, it will forward the POST request to the listening RMI server, which will recognize the request and unwrap it. The result of the call is wrapped in a HTTP reply, which is returned through the same proxy.

Often, HTTP proxies will refuse to proxy requests to unusual port numbers. In this case, RMI will fall back to http-to-cgi tunneling. The RMI request is encapsulated in a HTTP POST request as before, but the request URL is of the form http://hostname:80/cgi-bin/java-rmi.cgi?port=n (where hostname and n are the hostname and port number of the intended server). There must be a HTTP server listening on port 80 on the server host, which will run the java-rmi.cgi script (supplied with the JDK), which will in turn forward the request to an RMI server listening on port n. RMI can unwrap a HTTP-tunneled request without help from a http server, CGI script, or any other external entity. So, if the client's HTTP proxy can connect directly to the server's port, then you don't need a java-rmi.cgi script at all.

To trigger the use of HTTP tunneling, the standard system property http.proxyHost must be set to the hostname of the local HTTP proxy. (There are reports that some Navigator versions do not set this property.)

The major disadvantage of HTTP tunneling is that it does not permit inward calls or multiplexed connections. A secondary disadvantage is that the http-to-cgi method opens a dramatic security hole on the server side, since without modification it will redirect any incoming request to any port.

SOCKS

The default implementation of sockets in the JDK will use a SOCKS server if available and configured. The system property socksProxyHost must have been set to the hostname of the SOCKS server; if the port number of the SOCKS server is not 1080, it must be specified in the socksProxyPort property.

This approach would appear to be the most generally useful solution. As yet, ServerSockets do not use SOCKS, so incoming calls must use another mechanism.

Downloaded socket factories

This is an innovation in the Java 2 SDK, allowing the server to specify the socket factory that the clients must use. The clients must be running Java 2 SDK, Standard Edition, v1.2 or later. See the tutorial Using a Custom RMI Socket Factory for details.

The disadvantage of this approach is that the traversal of the firewall must be done by code provided by the RMI server side, which does not necessarily know how that traversal must be done, nor does it automatically have sufficient privilege to traverse the firewall.

C.11 How can I receive incoming RMI calls through a local firewall?

There are three main methods: known ports, transport-level bridges, and application-level proxies.

Known Ports

If the exported objects are all exported on a known port on a known host, then that host and port can be explicitly permitted at the firewall. Normally, RMI asks for port 0 (which is code for "any port"). In the Java 2 SDK, there is an extra argument to the exportObject method to specify the exact port number. In JDK v1.1, the server must subclass the RMISocketFactory and intercept requests to createServerSocket(0), replacing it with a request to bind to a specific port number.

This approach has the disadvantage that it requires the assistance of the network administrator responsible for the local firewall. If the exported object is being run in a different location (because code was downloaded to that site), then the local firewall may be run by network administrators who don't know who you are.

Transport-level bridges

A transport-level bridge is a program that reads bytes from one TCP connection and writes them to another (and vice versa) without knowing or caring what the bytes represent.

The idea here is to export objects in such a way that anyone outside the firewall who wants to call remote methods on that object instead contacts a different port (perhaps on a different machine). That different port has a running program which makes a second connection to the real server and then pumps bytes each way.

The tricky part is convincing the client to connect to the bridge. A downloadable socket factory (Java 2 SDK, v1.2 or later) can do this efficiently; otherwise, it is possible to set the java.rmi.server.hostname property to name the bridge host and arrange for port numbers to be the same.

Application-level proxies

This approach is quite a bit of work, but leads to a very secure arrangement. A proxy program runs on a firewall host (one which can be accessed from outside as well as inside). When an internal server intends to make an exported object available to the world, it contacts the proxy server and gives it a remote reference. The proxy server creates a proxy object (a new remote object residing in the proxy server) which implements the same remote interfaces as the original. The proxy server returns a remote reference for the new proxy object to the internal server, which communicates it to the outside world (somehow).

When an outsider makes a call on the proxy, the proxy immediately forwards the call to its original object on the internal server. The use of the proxy is transparent to the outsider (but not to the internal server, who has to decide whether to pass the original reference or the proxy reference when talking to anyone).

Needless to say, this requires considerable setup and the cooperation of the local network administrators.

C.12 So what do I have to do to get RMI to operate through two firewalls?

First of all, what cooperation can you expect from the client-side firewall?

In the most pessimistic case, the client-side firewall allows no direct TCP connections and has only a HTTP proxy server so that firewalled clients can "surf the web". In this case, your server host will receive connections at port 80 containing RMI requests embedded in HTTP requests. You can use a HTTP server with the java-rmi.cgi program, or you can run the RMI server directly on port 80. Either way, the server cannot use callback objects exported by the clients..

A more optimistic case is that the client can make direct connections to the server but cannot receive incoming connections from the server. In this case, callback objects are not normally possible either.

The most conservative approach, assuming no help from the client firewall administrators, is:

  • Avoid using callback objects
  • Run your servers on `public' ports such as 80, 81, 8001, or 443
  • If the servers are not running on port 80, either:
    • Put a CGI-capable HTTP server on port 80 using the java-rmi.cgi script; or
    • Run a port redirector (such as DeleGate) on port 80, which will accept connections and immediately connect to the real server port to pass bytes back and forth. This will cause getClientHost() to return misleading information, so don't make the Registry available through this method unless it's on a different host.

C.13 Is it possible to replace the java-rmi.cgi script that comes with the JDK distribution with a servlet?

We've provided an example that demonstrates how to implement the java-rmi.cgi script using a servlet. The example also explains how to run a remote object inside a servlet VM.

Note: If you do not understand the role that java-rmi.cgi plays in tunnelling remote method calls over HTTP, please see the FAQ question regarding HTTP tunnelling in RMI.

D.1 Is there a way to get automatic notification as soon as a remote VM fails?

Not at this time.

D.2 From within a virtual machine, can a new virtual machine be spawned on a remote machine?

The Java 2 SDK includes object activation, and there are several tutorials explaining how to use it.

D.3 Is it possible for a remote object to be notified when all clients disconnect?

Yes. Your remote object will need to implement the java.rmi.server.Unreferenced interface (in addition to any other necessary interfaces). RMI will provide the notification by calling the unreferenced method when all clients disconnect. Your implementation of the unreferenced method will determine what action your remote object should take upon receiving such a notification. However, if there is a reference in the registry, then the Unreferenced.unreferenced method will never be called.

D.4 Why doesn't my server program exit when all clients disconnect?

In RMI, a server VM should exit if there are
  • No outstanding client-held references to the remote objects in VM, and
  • No non-daemon threads executing in the VM.
However, just because there are no local or remote references to a remote object does not mean the object will be garbage collected in a timely fashion. It does mean that the remote object's memory can be collected to satisfy a memory allocation that would otherwise fail (with an OutOfMemoryError).

Although the Java API does not specify the timeliness of collection anyway, there is a particular reason for the what can seem like indefinitely delayed collection of remote objects in the JDK v1.1 implementation. Under the covers, the RMI runtime holds a weak reference to exported remote objects in a table (to keep track of local as well as remote references to the object). The only weak reference mechanism available in the JDK v1.1 VM uses a non-aggressive, caching collection policy (well-suited for a browser), so objects that are only "weakly reachable" will not get collected until the local GC decides that it really needs that memory to satisfy another allocation. For an idle server, this could never happen. But if memory is needed, an unreferenced server object will be collected.

The Java 2 platform includes a new infrastructure that RMI will use to reduce significantly the number of conditions under which this problem occurs.

D.5 How does the distributed garbage collector detect a client that disconnects? Is it advisable to use System.exit for graceful client termination?

When the RMI runtime in a client VM detects that a remote object is no longer referenced locally, it asynchronously notifies the server relatively quickly so that the server can update the object's referenced set accordingly. The distributed garbage collector uses a lease associated with each client-held remote object reference, and renews leases to remote objects while the client still holds such references. The purpose of the lease renewal mechanism is to allow the server to detect the abnormal termination of clients, so that a server does not hold on to a remote object forever because of a client that was not able to send the appropriate "unreferenced" message before it stopped running. In this context, a client invoking System.exit() is considered abnormal termination, because it does not allow the RMI runtime to send the appropriate "unreferenced" messages to the server. Executing System.runFinalizersOnExit in the client before termination is not sufficient, because not all of the necessary processing is handled in a finalizer; i.e. the "unreferenced" message will not get sent to the server. (Using "runFinalizersOnExit" is generally ill-advised and deadlock-prone anyway.)

If you need to use System.exit() to terminate a client VM, to ensure that remote references held in that VM are cleaned up in a more timely fashion, you should make sure that there are no remote references still reachable. Explicitly null any local references to make them unreachable from running threads. It also may help to run a full garbage collection and to run finalizers before exiting:

    System.gc();
    System.runFinalization();

D.6 How can my server tell when a client crashes?

If you wait for the client's lease to run out, and the unreferenced() method will then be called by the RMI implementation (remember that the registry is also a client for this purpose, since it holds references for all its bindings).

If a client is holding a remote reference, it also holds a lease for that reference, which must be renewed (by contacting the server and making a dirty() call). When the final lease for an exported object has expired or closed, the object is considered unreferenced, and (if it implements java.rmi.Unreferenced) its unreferenced() method will be invoked.

If two or more clients have references to the same remote object, the unreferenced() method will not be called until all of them have expired their leases on it. Consequently, if you are using this technique to track individual clients, each client must have a reference to its own Unreferenced object.

D.7 The unreferenced() method doesn't get called until ten minutes after I have stopped using the remote object! How can I shorten this delay?

The lease expiration time is specified by the server, where it can be set using a system property, java.rmi.dgc.leaseValue, whose value is in milliseconds. To set this to a shorter time (for example: 30 seconds), start the server like this:
    java -Djava.rmi.dgc.leaseValue=30000 ServerMain

The default value is 600000 milliseconds (or 10 minutes).

The client will renew each lease when it is halfway expired. If the lease interval is too short, the client will waste a lot of network bandwidth needlessly renewing its lease. If the lease interval is much too short, the client will be unable to renew the lease in time, and the exported object may be deleted as a result.

Future releases of RMI may invalidate remote references if they fail to renew their leases (in order to preserve referential integrity); you should not rely on being able to use stale references to remote objects.

Note that you'll only have to wait for the timeout if the client machine crashes. If the client has some control when the disconnect occurs, it can send out the DGC clean call quickly, making the use of Unreferenced quite timely. You can help this process along by nulling out any references the client may have to the remote object and then calling System.gc(). (In v1.1.x, you may have to run finalizers synchronously and then run GC again.)

D.8 Why can't I get an immediate notification when a client crashes?

Because nothing the server does can distinguish a crashed host from a network delay.

If or when the crashed client later restarts and contacts the server, the server can infer that the client has lost its state. If a TCP connection is held open between the client and the server throughout their interaction, then the server can detect the client reboot when a later attempt to write to the connection fails (including the hourly TCP keepalive packet, if enabled). However, RMI is designed not to require such permanent connections, as it impairs scalability and doesn't help very much.

Given that it is absolutely impossible to instantly determine when a network peer crashes or becomes otherwise unavailable, you must decide how your application should behave when a peer stops responding.

The major tools you have for this task are timeouts and resets. After a timeout, you may conclude that a peer is unreachable, but the peer must be aware of the timeout so that it gives up trying to reach you. The leasing mechanism is designed to do this semi-automatically.

A reset is a purge of existing state held for a peer. For example, a client may cause a reset when it first registers with its server, causing the server to discard any previous state held for that client (having deduced that the client has restarted without memory of the previous, dead, session).

Frequently, the aim is to have and maintain a definitive list of clients at the server, and to keep it up-to-date without error or failure. Since failure and delay can happen at any time in a networked system, some degree of error in the list must be anticipated. If a lease or other mechanism is used to enforce a timeout, then the problem of resource leakage is solved. If the problem of stale data is more serious -- that is, if it would interfere with correct operation -- then it must be explicitly purged in cases where it would otherwise have an effect.

For example, if a business object is locked for editing by a human, and the session dies, then the lock must be broken somehow. In this case, the lock would need a timeout, but if the same human logs in immediately and expects not to have to wait for the timeout to expire, the new session must either take over the lock or assert that the user holds no locks (allowing the server to safely kill the lock).

D.9 How do I run the rmic command in a DOS batch file?

In a DOS batch file, you have to insert the command call before the executable in order for control to return to the batch file. For example:
    call rmic ClientHandler
    call rmic Server
    call rmic ServerHandler
    call rmic Client

D.10 In a remote object implementation, how can I find the host name of the caller of a remote method?

The java.rmi.server.RemoteServer.getClientHost method returns the client host for the current invocation on the current thread.

D.11 Does RMI handle "out" and "inout" parameters (like CORBA)?

RMI does not support "out" or "inout" parameters, just like the rest of the core Java programming language. All remote calls are methods of a remote object. Local objects are passed by copy and remote objects are passed by reference to a stub. For more details, see Parameter Passing in Remote Method Invocation in the RMI Specification.

D.12 Normally in the Java programming language, it is possible to cast an interface instance to an instance of the class from which it was created and use the result. Why doesn't this work in RMI?

In RMI the client sees only a stub for the original object. The stub implements only the remote interfaces and their remote methods and cannot be cast back to the original implementation class because it's just a stub.

So, you cannot pass a remote object reference from a server to a client, and then send it back to the server and be able to cast it back to the original implementation class. You can, though, use the remote object reference on the server to make a remote call to the object.

If you need to find the implementation class again, you'll need to keep a table that maps the remote reference to the implementation class.

E.1 What if my browser does not support the JDK or J2SE version I need?

Try using the Java Plug-in for browsers that do not support the JDK or J2SE version you need.

E.2 Can I implement remote observer/observable objects in RMI?

What you can do is "wrap" java.util.Observable and java.util.Observer with new interfaces (you could call them RemoteObservable and RemoteObserver). In these new interfaces, make each of the methods throw java.rmi.RemoteException. Then, your remote objects can implement these interfaces.

Note that since the "wrapped" non-remote object does not extend java.rmi.server.UnicastRemoteObject, you will need to explicitly export the object using the exportObject method of UnicastRemoteObject. In doing this though, you lose the java.rmi.server.RemoteObject implementations of the equals, hashCode, and toString methods.

F.1 At what point is there a "live" connection between the client and the server and how are connections managed?

When a client does a "lookup" operation, a connection is made to the rmiregistry on the specified host. In general, a new connection may or may not be created for a remote call. Connections are cached by the RMI transport for future use, so if a connection is free to the right destination for a remote call, then it is used. A client cannot explicitly close a connection to a server, since connections are managed at the RMI transport level. Connections will time out if they are unused for a period of time.

F.2 Does the Java platform replace all remote objects with their stubs during a remote method invocation?

The JRMP and RMI-IIOP implementations will replace each remote object with a corresponding stub (of the same protocol), even deep inside graphs of serializable objects.

F.3 Is it possible to write a new transport layer for RMI which does not use sockets? As a follow-up question, how about a transport layer that uses non-TCP-based sockets?

We have designed the transport interfaces so that different implementations of these interfaces can be used by RMI. In earlier releases, this abstraction was used for our purposes and was not exposed for general use. Now, in the Java 2 SDK, RMI supports client and server socket factories that can be used to make RMI calls over non-TCP-based sockets.

F.4 I notice the registry continues to use CPU resources, as if it were polling rather than blocking on a select() call. Is the registry implemented by polling?

RMI does not poll on select calls. There is a thread that wakes up every so often and polls the table of exported remote objects. This "reap" thread is used for the purposes of the distributed garbage collector.

F.5 Is there only one socket connection between a client process and the server, no matter how many stubs exist in that client process?

RMI reuses the socket connections between client and server whenever possible. The current implementation creates additional sockets on demand when they are needed. For example, if the existing socket is in use by a call then a new socket is created for the new call. Typically, there are at least two sockets open since the distributed garbage collector needs to make remote calls when remote objects are returned from the server. If a cached connection remains unused for a period of time, the connection is closed.

G.1 What are the licensing issues surrounding the use of RMI?

Java RMI is part of the J2SE platform and as such is subject to the licensing terms of J2SE.

G.2 I have a single-threaded program that waits on standard input for a user command which will initiate an RMI call. However, my remote object cannot service this incoming remote call as the program appears to be blocked on standard input. What's the problem?

This is a known problem, not with RMI, but with the thread that reads standard input. The thread does not yield on the blocking read, but instead stays running, hardly letting the listener get any cycles. We have tried two workarounds that seem successful: set the main thread (the one reading standard input) to a lower priority, or yield while bytes are not available in the stream before actually reading it.

G.3 I am copying array elements to my remote server and changing the values, but the incremented values are not copied back to the client. Why?

Non-remote objects are passed by copy, so if you want to have the new values of the array reflected in the client, you will have to send them back as a return argument.

G.4 Am I allowed to have static fields in a remote interface?

Yes. An initializer is run in each VM that loads the remote interface, creating a new static variable with the specified values. So, you have a separate copy of this static variable in each VM that loads the remote interface.

G.5 I locate the registry, but then it seems that it's not there, what's happening?

The method LocateRegistry.getRegistry(String host) does not contact the registry on the host, but rather just looks up the host to make sure it exists. So, even though this method succeeded, this does not necessarily mean that a registry is running on the specified host. It just returns a stub that can then access the registry.

G.6 I can't find the answer to my question here, are there any other resources?

A vast amount of information can be found from the hypermail archive of the RMI-USERS mailing list.

Users of both RMI and object serialization can discuss issues and tips with other users via the mailing list rmi-users@java.sun.com. You can subscribe by sending an email message containing the line

    subscribe RMI-USERS
to listserv@java.sun.com, and unsubscribe by sending a message containing the line
    unsubscribe RMI-USERS

Object Serialization

1. Why must classes implement Serializable in order to be written to an ObjectOutputStream?

The decision to require that classes implement the java.io.Serializable interface was not made lightly. The design called for a balance between the needs of developers and the needs of the system to be able to provide a predictable and safe mechanism. The most difficult design constraint to satisfy was the safety and security of classes for the Java programming language.

If classes were to be marked as being serializable the design team worried that a developer, either out of forgetfulness, laziness, or ignorance might not declare a class as being Serializable and then make that class useless for RMI or for purposes of persistence. We worried that the requirement would place on a developer the burden of knowing how a class was to be used by others in the future, an essentially unknowable condition. Indeed, our preliminary design, as reflected in the alpha API, concluded that the default case for a class ought to be that the objects in the class be serializable. We changed our design only after considerations of security and correctness convinced us that the default had to be that an object not be serialized.

Security restrictions

The first consideration that caused us to change the default behavior of objects had to do with security, and in particular in the privacy of fields declared to be private, package protected, or protected. The Java platform restricts access to such fields for either read or write to a subset of the objects within the runtime.

No such restriction can be made on an object once it has been serialized; the stream of bytes that is the result of object serialization can be read and altered by any object that has access to that stream. This allows any object access to the state of a serialized object, which can violate the privacy guarantees users of the language expect. Further, the bytes in the stream can be altered in arbitrary ways, allowing the reconstruction of an object that was never created within the protections of a Java platform. There are cases in which the re-creation of such an object could compromise not only the privacy guarantees expected by users of the Java platform, but the integrity of the platform itself.

These violations cannot be guarded against, since the whole idea of serialization is to allow an object to be converted into a form that can be moved outside of the Java platform (and therefore outside of the privacy and integrity guarantees of that environment) and then be brought back into the environment. Requiring objects to be declared serializable does mean that the class designer must make an active decision to allow the possibility of such a breach in privacy or integrity. A developer who does not know about serialization should not be open to compromise because of this lack of knowledge. In addition, we would hope that the developer who declares a class to be serializable does so after some thought about the possible consequences of that declaration.

Note that this sort of security problem is not one that can be dealt with by the mechanism of a security manager. Since serialization is intended to allow the transport of an object from one virtual machine to some other (either over space, as it is used in RMI, or over time, as when the stream is saved to a file), the mechanisms used for security need to be independent of the runtime environment of any particular virtual machine. We wanted to avoid as much as possible the problem of being able to serialize an object in one virtual machine and not being able to deserialize that object in some other virtual machine. Since the security manager is part of the runtime environment, using the security manager for serialization would have violated this requirement.

Forcing a conscious decision

While security concerns were the first reason for considering the design change, a reason that we feel is at least as convincing is that serialization should only be added to a class after some design consideration. It is far too easy to design a class that falls apart under serialization and re-construction. By requiring a class designer to declare support for the serialization interface, we hoped that the designer would also give some thought to the process of serializing that class.

Examples are easy to cite. Many classes deal with information that only makes sense in the context of the runtime in which the particular object exists; examples of such information include file handles, open socket connections, security information, etc. Such data can be dealt with easily by simply declaring the fields as transient, but such a declaration is only necessary if the object is going to be serialized. A novice (or forgetful, or hurried) programmer might neglect to mark fields as transient in much the same way he or she might neglect to mark the class as implementing the Serializable interface. Such a case should not lead to incorrect behavior; the way to avoid this is to not serialize objects not marked as implementing Serializable.

Another example of this sort is the "simple" object that is the root of a graph that spans a large number of objects. Serializing such an object could result in serializing lots of others, since serialization works over an entire graph. Doing something like this should be a conscious decision, not one that happens by default.

The need for this sort of thought was brought home to us in the group when we were going through the base Java API class libraries, marking the system classes as serializable (where appropriate). We had originally thought that this would be a fairly simple process, and that most of the system classes could just be marked as implementing Serializable and then use the default implementation with no other changes. What we found was that this was far less often the case than we had suspected. In a large number of the classes, careful thought had to be given to whether or not a field should be marked as transient or whether it made sense to serialize the class at all.

Of course, there is no way to guarantee that a programmer or class designer is actually going to think about these issues when marking a class as serializable. However, by requiring the class to declare itself as implementing the Serializable interface we do require that some thought be given by the programmer. Having serialization be the default state of an object would mean that lack of thought could cause bad effects in a program, something that the overall design of the Java platform has attempted to avoid.

2. Which JDK v1.1 system classes are marked serializable?

Removed. This information is readily available from the API documentation generated by the javadoc tool.

3. I am having problems deserializing JDK v1.0.2 AWT components. How can I make this work?

When you serialize AWT widgets, also serialized are the Peer objects that map the AWT functions to the local window system. When you deserialize (reconstitute) the AWT widgets, the old Peers are re-created, but they are out of date. Peers are native to the local window system and contain pointers to data structures in the local address space, and therefore cannot be moved.

As a work around, you should first remove the top-level widget from its container (so the widgets are no longer "live"). The peers are discarded at this point and you will save only the AWT widget state. When you later deserialize and read the widgets back in, add the top level widget to the frame to make the AWT widgets appear. You may need to add a show call.

In JDK v1.1 and later, AWT widgets are serializable. The java.awt.Component class implements Serializable.

4. Does object serialization support encryption?

Object serialization does not contain any encryption/decryption in itself. It writes to and reads from standard streams in the Java API, so it can be coupled with any available encryption technology. Object serialization can be used in many different ways. Other than just writing and reading to and from files, it can also be used for RMI to communicate between hosts.

RMI's use of serialization leaves encryption and decryption to the lower network transport. We expect that when a secure channel is needed the network connections will be made using SSL or the like (see Using RMI with SSL).

5. The object serialization classes are stream oriented. How do I write objects to a random-access file?

Currently there is no direct way to write objects to a random-access file.

You can use ByteArrayInputStream and ByteArrayOutputStream objects as intermediate places to write and read bytes to and from the random access file and create ObjectInputStreams and ObjectOutputStreams from the byte streams to transport the objects. You just have to make sure that you have the entire object in the byte stream or reading/writing the object will fail.

For example, java.io.ByteArrayOutputStream can be used to receive the bytes of ObjectOutputStream. From it you can get a result in the form of a byte array. That in turn can be used with ByteArrayInputStream as input to an ObjectInput stream.

6. When a local object is serialized and passed as a parameter in an RMI call, are the bytecodes for the local object's methods also passed? What about object coherency, if the remote VM application "keeps" the object handle?

The bytecodes for a local object's methods are not passed directly in the ObjectOutputStream, but the object's class may need to be loaded by the receiver if the class is not already available locally. The class files themselves are not serialized, just the names of the classes. All classes must be able to be loaded during deserialization using the normal class loading mechanisms. For applets, this means they are loaded by the AppletClassLoader.

There are no coherency guarantees for local objects passed to a remote VM since such objects are passed by copying their contents (a true pass-by-value).

7. How can I create an ObjectInputStream from an ObjectOutputStream without a file in between?

ObjectOutputStream and ObjectInputStream work to/from any stream object. You could use a ByteArrayOutputStream and then get the array and insert it into a ByteArrayInputStream. You could also use the piped stream classes as well. Any java.io class that extends the OutputStream and InputStream classes can be used.

8. I create an object and then send it across the net using the writeObject method and receive it using the readObject method. If I then change the value of a field in the object and send it as before, the object that the readObject method returns appears to be the same as the first object and does not reflect the new value of the field. Should I be experiencing this behavior?

The ObjectOutputStream class keeps track of each object it serializes and sends only the handle if that object is seen again. This is the way it deals with graphs of objects. The corresponding ObjectInputStream keeps track of all of the objects it has created and their handles so when the handle is seen again it can return the same object. Both output and input streams keep this state until they are freed.

Alternatively, the ObjectOutputStream class implements a reset method that discards the memory of having sent an object, so sending an object again will make a copy.

9. Are there any plans to support the serialization of thread objects?

Threads will NOT be serializable. In the present implementation, if you attempt to serialize and then deserialize a thread, there is NO explicit allocation of a new native thread or stack; all that happens is that the object is allocated system resources with none of the native implementation. In short, it just won't work and will fail in unpredictable ways.

The difficulty with threads is that they have so much state which is intricately tied into the virtual machine that it is difficult or impossible to re-establish the context somewhere else. For example, saving the VM call stack is insufficient because if there were native methods that had called C procedures that in turn called code for the Java platform, there would be an incredible mix of Java programming language constructs and C pointers to deal with. Also, serializing the stack would imply serializing any object reachable from any stack variable.

If a thread were resumed in the same VM, it would be sharing a lot of state with the original thread, and would therefore fail in unpredictable ways if both threads were running at once, just like two C threads trying to share a stack. When deserialized in a separate VM, it's hard to tell what might happen.

10. Can I compute diff(serial(x),serial(y))?

The diff will produce the same stream each time the same object is serialized. You will need to create a new ObjectOutputStream to serialize each object.

11. Can I compress the serial representation of my objects using my own zip and unzip methods?

ObjectOutputStream produces an OutputStream; if your zip object extends the OutputStream class there is no problem compressing it.

12. Can I execute methods on compressed versions of my objects, for example isempty(zip(serial(x)))?

This is not really viable for arbitrary objects because of the encoding of objects. For a particular object (such as a String) you can compare the resulting bit streams. The encoding is stable, in that every time the same object is encoded it is encoded to the same set of bits.

13. If I try to serialize a font or image object and then try to reconstitute it in a different VM, my application dies. Why?

Removed. Fonts are now serializable, but images are not.

14. How do I serialize a tree of objects?

Here's a brief example that shows how to serialize a tree of objects.

import java.io.*;

class tree implements java.io.Serializable {
    public tree left;
    public tree right;
    public int id;
    public int level;

    private static int count = 0;

    public tree(int depth) {
        id = count++;
        level = depth;
        if (depth > 0) {
            left = new tree(depth-1);
            right = new tree(depth-1);
        }
    }

    public void print(int levels) {
        for (int i = 0; i < level; i++)
            System.out.print("  ");
        System.out.println("node " + id);

        if (level <= levels && left != null)
            left.print(levels);

        if (level <= levels && right != null)
            right.print(levels);
    }

    public static void main (String argv[]) {

        try {
            /* Create a file to write the serialized tree to. */
            FileOutputStream ostream = new FileOutputStream("tree.tmp");
            /* Create the output stream */
            ObjectOutputStream p = new ObjectOutputStream(ostream);

            /* Create a tree with three levels. */
            tree base = new tree(3);

            p.writeObject(base); // Write the tree to the stream.
            p.flush();
            ostream.close();    // close the file.

            /* Open the file and set to read objects from it. */
            FileInputStream istream = new FileInputStream("tree.tmp");
            ObjectInputStream q = new ObjectInputStream(istream);

            /* Read a tree object, and all the subtrees */
            tree new_tree = (tree)q.readObject();

            new_tree.print(3);  // Print out the top 3 levels of the tree
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

15. If class A does not implement Serializable but a subclass B implements Serializable, will the fields of class A be serialized when B is serialized?

Only the fields of Serializable objects are written out and restored. The object may be restored only if class A has a no-arg constructor that will initialize the fields of non-serializable supertypes. If the subclass has access to the state of the superclass it can implement writeObject and readObject to save and restore that state.

Talk with RMI developers via the mailing list RMI-USERS
To subscribe, send subscribe rmi-users to listserv@javasoft.com


Getting Started Using RMI

This tutorial shows you the steps to follow to create a distributed version of the classic Hello World program using JavaTM Remote Method Invocation (RMI). While you work through this example, you will probably come up with a number of related questions. You may find the answers in the RMI FAQ, or you may wish to look in the email archives of the rmi-users alias. If you'd like to subscribe to the rmi-users email alias, click here.

The distributed Hello World example uses an applet to make a remote method call to an RMI server, running on the host from which the applet was downloaded. When the applet runs, "Hello World!" is displayed on the client browser.

This tutorial is organized as follows:

  1. The steps to write the source files and the HTML file
  2. The steps to compile and deploy class files and the HTML file
  3. The steps to start the RMI registry, server, and applet
The files needed for this tutorial are:
  • Hello.java - a remote interface
  • HelloImpl.java - a remote object implementation that implements examples.hello.Hello
  • HelloApplet.java - an applet that invokes the remote method, sayHello
  • hello.html - the HTML page that references the applet
Note: For the remainder of this tutorial, the terms "remote object implementation," "object implementation," and "implementation" may be used interchangeably to refer to the class, examples.hello.HelloImpl, which implements a remote interface.

For all of the source code used in this tutorial, you may choose from the following formats:

  • getStart.zip
  • getStart.tar
  • getStart.tar.Z

Write the Source and HTML files

Because the JavaTM programming language requires a mapping between the fully-qualified package name of a class and the directory path to that class, you should decide on package and directory names before you begin writing any code written in the Java programming language. This mapping allows the compiler for the Java programming language to know the directory in which to find the class files mentioned in a program. For the programs in this tutorial, the package name is examples.hello and the source directory is $HOME/mysrc/examples/hello.

To create the directory for your source files in the SolarisTM operating environment, execute the command:

    mkdir -p $HOME/mysrc/examples/hello
On Microsoft Windows platforms, you would go to the directory of your choice, and type:
    mkdir mysrc
    mkdir mysrc\examples
    mkdir mysrc\examples\hello

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 and server classes
  3. Write a client program that uses the remote service

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 JavaTM virtual machines* (JVMs). 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, Hello) not the implementation class (HelloImpl).

Here is the interface definition for the remote interface, examples.hello.Hello. The interface contains just one method, sayHello, which returns a string to the caller:

    package examples.hello;

    import java.rmi.Remote;
    import java.rmi.RemoteException;

    public interface Hello extends Remote {
    String sayHello() throws 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 and server classes

At a minimum, a remote object implementation class 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
A "server" class, in this context, 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 rmiregistry. 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 examples.hello.HelloImpl. The server program needs to:

  • Create and install a security manager
  • Create one or more instances of a remote object
  • Register at least one of the remote objects with the RMI remote object registry, for bootstrapping purposes
An explanation of each of the preceding six steps follows the source for HelloImpl.java:
    package examples.hello;

    import java.rmi.Naming;
    import java.rmi.RemoteException;
    import java.rmi.RMISecurityManager;
    import java.rmi.server.UnicastRemoteObject;

    public class HelloImpl extends UnicastRemoteObject implements Hello {

        public HelloImpl() throws RemoteException {
        super();
        }

        public String sayHello() {
        return "Hello World!";
        }

        public static void main(String args[]) {

        // Create and install a security manager
        if (System.getSecurityManager() == null) {
            System.setSecurityManager(new RMISecurityManager());
        }

        try {
            HelloImpl obj = new HelloImpl();

            // Bind this object instance to the name "HelloServer"
            Naming.rebind("//myhost/HelloServer", obj);

            System.out.println("HelloServer bound in registry");
        } catch (Exception e) {
            System.out.println("HelloImpl err: " + e.getMessage());
            e.printStackTrace();
        }
        }
    }

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 examples.hello.HelloImpl. The implementation class declares which remote interface(s) it is implementing. Here is the HelloImpl class declaration:

    public class HelloImpl extends UnicastRemoteObject
        implements Hello {
As a convenience, the implementation class can extend a remote class, which in this example is java.rmi.server.UnicastRemoteObject. By extending UnicastRemoteObject, the HelloImpl class can be used to create a remote object that:
  • Uses RMI's default sockets-based transport for communication
  • Runs all the time
If you want a remote object that can be activated (created) when a client requests it, rather than running all the time, after you finish this tutorial, you can take a look at the RMI Activation tutorial. Also, you can learn about how to use your own communication protocol, rather than the TCP sockets that RMI uses by default, in the tutorial on Using a Custom RMI Socket Factory.

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 java.rmi.server.UnicastRemoteObject or java.rmi.activation.Activatable, your class will be exported automatically upon creation.

If you choose to extend a remote object from any class other than UnicastRemoteObject or Activatable, you will need to explicitly export the remote object by calling either the UnicastRemoteObject.exportObject method or the Activatable.exportObject method from your class's constructor (or another initialization method, as appropriate).

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:13: Exception java.rmi.RemoteException must be caught, or it must be
        declared in the throws clause of this method.
                super();
                     ^
        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 examples.hello.HelloImpl class:
    public HelloImpl() throws RemoteException {
    super();
    }
Note the following:
  • The super method call invokes the no-argument constructor of java.rmi.server.UnicastRemoteObject, 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.

If you are interested in why java.rmi.RemoteException is a checked exception rather than runtime exception, please refer to the archives of the rmi-users email list:

http://archives.java.sun.com/archives/rmi-users.html

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 Java virtual machine (JVM) constructs the superclass 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 World!" to the caller:
    public String sayHello() throws RemoteException {
    return "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. 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.
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 install a security manager

The main method of the server first needs to create and install a security manager: either the RMISecurityManager or one that you have defined yourself. For example:
if (System.getSecurityManager() == null) {

        System.setSecurityManager(new RMISecurityManager());
}
A security manager needs to be running so that it can guarantee that the classes that get loaded do not perform operations that they are not allowed to perform. If no security manager is specified no class loading, by RMI clients or servers, is allowed, aside from what can be found in the local CLASSPATH. In this example, a security manager is not installed in the client code because applets use the security manager already installed in the client browser. If the client were an application rather than an applet, however, you would need to use the same procedure as is used above to install a security manager in the client. A security manager is required in any JVM that needs to download code, and RMI clients need to download RMI stubs (as well as any other custom classes or interfaces needed to communicate with the RMI server).

Create one or more instances of a remote object

The main method of the server needs to create one or more instances of the remote object implementation which provides the service. For example:
HelloImpl obj = new HelloImpl();
The constructor exports the remote object, which means that once created, the remote object is ready to accept incoming calls.

Register the remote object

For a caller (client, peer, or applet) to be able to invoke a method on a remote object, that caller must first obtain a reference to the remote object.

For bootstrapping, the RMI system provides a remote object registry that allows you to bind a URL-formatted name of the form "//host/objectname" to the remote object, where objectname is a simple string name.

The RMI registry is a simple server-side name service that allows remote clients to get a reference to a remote object. It is typically used only to locate the first remote object an RMI client needs to talk to. Then 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 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 remotely invoke methods on the object.

For example, the following code binds the name "HelloServer" to a reference for the remote object:

Naming.rebind("//myhost/HelloServer", obj);
Note the following about the arguments to the rebind method call:
  • The first parameter is a URL-formatted java.lang.String, representing the location and name of the remote object.

    • No protocol needs to be specified in the URL-formatted string.
    • You will need to change the value of myhost to be the name or IP address of your server machine; otherwise, the remote object host defaults to the current host. For example, "HelloServer" is a valid name string that refers to a remote object bound to the name HelloServer, running on the local host.
    • Optionally, a port number can be supplied in the URL-formatted string. Specifying the port number is necessary when the registry that needs to be contacted is running on a port other than the default port, 1099. For example, "//myhost:1234/HelloServer" is a valid name string for the HelloServer remote object, reachable through an RMI registry that is running on the host myhost and is listening for incoming calls on port 1234.

  • The second parameter is a reference to the object implementation, on which remote methods will be invoked.

  • Once an object is exported, the RMI runtime substitutes a reference to the remote object's stub for the actual remote object reference specified by the obj argument. When a client performs a lookup in a server's remote object registry, a serialized instance of the stub for the implementation is returned.
For security reasons, an application can bind or unbind only to a registry running on the same host. This prevents a client from removing or overwriting any of the entries in a server's remote registry. A lookup, however, can be done from any host.

Write a client program that uses the remote service

The applet in this example remotely invokes the sayHello method in order to get the string "Hello World!" to display when the applet runs. Here is the code for the applet:

package examples.hello;

import java.applet.Applet;
import java.awt.Graphics;
import java.rmi.Naming;
import java.rmi.RemoteException;

public class HelloApplet extends Applet {

    String message = "blank";

    // "obj" is the identifier that we'll use to refer
    // to the remote object that implements the "Hello"
    // interface
    Hello obj = null;

    public void init() {
        try {
            obj = (Hello)Naming.lookup("//" +
                getCodeBase().getHost() + "/HelloServer");
            message = obj.sayHello();
        } catch (Exception e) {
            System.out.println("HelloApplet exception: " + e.getMessage());
            e.printStackTrace();
        }
    }

    public void paint(Graphics g) {
        g.drawString(message, 25, 50);
    }
}
  1. First, the applet gets a reference to the remote object implementation (advertised as "HelloServer") from the server host's rmiregistry. Like the Naming.rebind method, the Naming.lookup method takes a URL-formatted java.lang.String. In this example, the applet constructs the URL string by using the getCodeBase method in conjunction with the getHost method. Naming.lookup takes care of the following tasks:

    • Constructing a registry stub instance (to contact the server's registry) using the hostname and port number supplied as arguments to Naming.lookup
    • Using the registry stub to call the remote lookup method on the registry, using the URL's name component ("HelloServer")

      • The registry 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 (examples.hello.HelloImpl_Stub) from the CLASSPATH or the applet's codebase

    • Naming.lookup returns the stub to its caller (HelloApplet)

  2. The applet invokes the remote sayHello method on the server's remote object

    • RMI serializes and returns the reply string "Hello World!"
    • RMI deserializes the string and stores it in a variable named message.

  3. The applet invokes the paint method, causing the string "Hello World!" to be displayed in the drawing area of the applet.
The URL-formatted string that is passed as a parameter to the Naming.lookup method must include the server's hostname. Otherwise, the applet's lookup attempt will default to the client, and the AppletSecurityManager will throw an exception because the applet cannot access the local system, but is instead limited to only communicating with the applet's host.

Here is the HTML code for the web page that references the Hello World applet:

    <HTML>
    <title>Hello World</title>
    <center> <h1>Hello World</h1> </center>
    <applet codebase="myclasses/"
            code="examples.hello.HelloApplet"
            width=500 height=120>
    </applet>
    </HTML>
Note the following:
  • There needs to be an HTTP server running on the machine from which you want to download classes.
  • The codebase in the HTML file specifies a directory below the directory from which the web page was itself loaded. Using this kind of relative path is usually a good idea. For example, if the codebase directory (where the applet's class files live), referenced by the applet's HTML, was in the directory above the the HTML directory, you would use the relative path, "../".
  • The applet's code attribute specifies the fully-qualified package name of the applet, in this example examples.hello.HelloApplet:
    code="examples.hello.HelloApplet"

Compile and Deploy Class Files and HTML Files

The source code for this example is now complete and the $HOME/mysrc/examples/hello directory has four files:
  • Hello.java contains the source code for the Hello remote interface
  • HelloImpl.java contains the source code for the HelloImpl remote object implementation and the RMI server for the applet
  • HelloApplet.java contains the source code for the applet
  • hello.html is the web page that references the Hello World applet.
In this section, you compile the .java source files to create .class files. 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 calls to the server-side dispatcher, which in turn forwards the call to the actual remote object implementation.

When you use the javac and rmic compilers, you must specify where the resulting class files should reside. For applets, all files should be in the applet's codebase directory. For our example, this directory is $HOME/public_html/myclasses.

Some web servers allow accessing a user's public_html directory via an HTTP URL constructed as "http://host/~username/". If your web server does not support this convention, you could use a file URL of the form "file:/home/username/public_html" for testing, but this approach will limit you to communicating between a client and server that have access to the same physical file system. As an alternative, you can use an HTTP URL by setting up a minimal web server on your system; we have one available for download here.

There are four tasks to complete in this section:

  1. Compile the source files
  2. Use rmic to generate stubs and skeletons
  3. Move the HTML file to the deployment directory
  4. Set paths for runtime

Compile the source files

Make sure that the deployment directory $HOME/public_html/myclasses and the development directory $HOME/mysrc/examples/hello are each accessible through the local CLASSPATH on the development machine before attempting to compile.

To compile the source files, run the javac command as follows:

javac  -d  $HOME/public_html/myclasses Hello.java  HelloImpl.java  HelloApplet.java

This command creates the directory examples/hello (if it does not already exist) in the directory $HOME/public_html/myclasses. The command then writes to that directory the files Hello.class, HelloImpl.class, and HelloApplet.class. These are the remote interface, the implementation, and the applet respectively. For an explanation of javac options, you can refer to the Solaris javac manual page or the Windows javac manual page.

Use rmic to generate skeletons and/or stubs

To create stub and skeleton files, run the rmic compiler on the fully-qualified package names of compiled class files that contain remote object implementations, like my.package.MyImpl. The rmic command takes one or more class names as an argument and produces class files of the form MyImpl_Skel.class and MyImpl_Stub.class.

By default, in the Java 2 SDK, v1.2 and later, rmic runs with the -vcompat flag on, which produces stubs and skeletons that support access to:

  1. Unicast (not Activatable) remote objects from 1.1 clients and
  2. All types of remote objects from 1.2 (and later) clients
If you will never need support for 1.1 clients, rmic can be run with the -v1.2 option. For an explanation of rmic options, you can refer to the Solaris rmic manual page or the Windows rmic manual page.

For example, to create the stub and skeleton for the HelloImpl remote object implementation, run rmic like this:

rmic  -d  $HOME/public_html/myclasses  examples.hello.HelloImpl

The "-d" option indicates the root directory in which to place the compiled stub and skeleton class files. So the preceding command creates the following files in the directory $HOME/public_html/myclasses/examples/hello:

  • HelloImpl_Stub.class
  • HelloImpl_Skel.class
The generated stub class implements exactly the same set of remote interfaces as the remote object itself. This means that a client can use the Java programming language's built-in operators for casting and type checking. It also means that remote objects written for the Java platform support true object-oriented polymorphism.

Move the HTML file to the deployment directory

To make the web page that references the applet visible to clients, the hello.html file must be moved from the development directory to the applet's codebase directory. For example:

mv  $HOME/mysrc/examples/hello/hello.html  $HOME/public_html/

Set paths for runtime

Make sure that the $HOME/public_html/myclasses directory is available through the server's local CLASSPATH when you run the HelloImpl server.

Start the RMI registry, server, and applet

There are three tasks to complete in this section:
  1. Start the RMI registry
  2. Start the server
  3. Run the applet

Start the RMI registry

The RMI registry is a simple server-side name server that allows remote clients to get a reference to a remote object. Typically, it is used only to locate the first remote object an application needs to talk to. Then that object in turn would provide application-specific support for finding other objects.

Note: Before you start the rmiregistry, you must make sure that the shell or window in which you will run the registry either has no CLASSPATH set or has a CLASSPATH that does not include the path to any classes that you want downloaded to your client, including the stubs for your remote object implementation classes.

If you start the rmiregistry, and it can find your stub classes in its CLASSPATH, it will ignore the server's java.rmi.server.codebase property, and as a result, your client(s) will not be able to download the stub code for your remote object. For an explanation of how code downloading works in RMI, please take a look at the tutorial on Dynamic code downloading using RMI.

To start the registry on the server, execute the rmiregistry command. This command produces no output and is typically run in the background. For more on the rmiregistry, you can refer to the Solaris rmiregistry manual page or the Windows rmiregistry manual page.

For example, in the Solaris operating environment:

rmiregistry &

For example, on Microsoft Windows 95 systems:

start rmiregistry

(Use javaw if start is not available.)

By default, the registry runs on port 1099. To start the registry on a different port, specify the port number from the command line. For example, to start the registry on port 2001 on a Microsoft Windows NT system:

start rmiregistry 2001

If the registry is running on a port other than 1099, you'll need to specify the port number in the name handed to the URL-based methods of the java.rmi.Naming class when making calls to the registry. For example, if the registry is running on port 2001 in this example, the call required to bind the name "HelloServer" to the remote object reference would be:

Naming.rebind("//myhost:2001/HelloServer", obj);

You must stop and restart the registry 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 registry will not match the modified class.

Start the server

When starting the server, the java.rmi.server.codebase property must be specified, so that the stub class can be dynamically downloaded to the registry and then to the client. Run the server, setting the codebase property to be the location of the implementation stubs. Because the codebase property in this example references a directory, make sure that any other classes that may need to be downloaded have also been installed in the directory referenced by java.rmi.server.codebase. For other command-line examples of codebase settings, please take a look at the tutorial on Dynamic code downloading using RMI.

For explanations of each of the java.rmi.server properties, click here. To see all the available java.rmi.activation properties, click here. For an explanation of java options, you can refer to the Solaris java manual page or the Windows java manual page. If you have problems running the example code, please take a look at the RMI and Serialization FAQ.

Note: A stub class is dynamically downloaded to a client's virtual machine only when the class is not already available locally and the java.rmi.server.codebase property has been set properly to specify where the class files are located on the server.

There are four things that need to go on the same command line: the "java" command, followed by two property name=value pairs (for the codebase property, note that there are no spaces from the "-D" all the way though the last "/") and then the fully-qualified package name of the server program. There should be a space just after the word "java", between the two properties, and just before the word "examples" (which is very hard to see when you view this as text, in a browser, or on paper). The following command shows how to start the HelloImpl server, specifying the java.rmi.server.codebase and java.security.policy properties:

java  -Djava.rmi.server.codebase=http://myhost/~myusrname/myclasses/  -Djava.security.policy=$HOME/mysrc/policy  examples.hello.HelloImpl

In order to run this code on your system, you'll need to change the location of the policy file to be the location of the directory on your system, where you've installed the example source code.

Note: In this example, for simplicity, we will use a policy file that gives global permission to anyone from anywhere. Do not use this policy file in a production environment. For more information on how to properly open up permissions using a java.security.policy file, please refer to to the following documents:

    Default Policy Implementation and Policy File Syntax

    Permissions in the Java 2 SDK

The codebase property will be resolved to a URL, so it must have the form of "http://aHost/somesource/" or "file:/myDirectory/location/" or, due to the requirements of some operating systems, "file:///myDirectory/location/" (three slashes after the "file:").

Please note that each of the URL strings above has a trailing "/". The trailing slash is a requirement for the URL set by the java.rmi.server.codebase property, so the implementation can resolve (find) your class definition(s) properly.

If you forget the trailing slash on the codebase property, or if the class files can't be located at the source (they aren't really being made available for download) or if you misspell the property name, you'll get thrown a java.lang.ClassNotFoundException. This exception will be thrown when you try to bind your remote object to the rmiregistry, or when the first client attempts to access that object's stub. If the latter case occurs, you have another problem as well because the rmiregistry was finding the stubs in its CLASSPATH.

The output should look like this:

HelloServer bound in registry

Run the applet

Once the registry and server are running, the applet can be run. An applet is run by loading its web page into a browser or appletviewer, as shown here:
appletviewer http://myhost/~myusrname/hello.html &
After running the appletviewer, you will see output similar to the following on your display:
Screenshot of the running Hello World applet.

*As used on this web site, the terms "Java virtual machine" or "JVM" mean a virtual machine for the Java platform.

Copyright © 2003 Sun Microsystems, Inc. All Rights Reserved.
Please send comments to: rmi-comments@java.sun.com 		Sun


Java(TM) Remote Method Invocation (RMI)

Java

JavaTM Remote Method Invocation (RMI)

 Documentation Contents

Enhancements since version 1.3 of the JavaTM 2 SDK

  • RMI Release Notes
    The RMI Release notes contain changes to the RMI and serialization APIs, as well as changes to the RMI tools, rmic and rmid.
RMI Tutorials
  • Getting Started
    The Getting Started Tutorial shows you the steps to follow to create a distributed version of the classic Hello World program using JavaTM Remote Method Invocation (RMI). The Hello World applet makes a remote method call to the server from which it was downloaded to retrieve the message "Hello World!"
  • The Custom Socket Factory Tutorial
    The Custom Socket Factory Tutorial shows you how to create a version of the distributed Hello World program in which the RMI runtime uses sockets of a type chosen by the programmer. This tutorial also includes a discussion of how RMI can be used over SSL sockets.
  • The Activation Tutorials
    • The Activation Tutorials take you through the steps of creating a new class that defines an activatable object, migrating a UnicastRemoteObject to be an activatable object, activating classes that do not extend from java.rmi.activation.Activatable, and using a MarshalledObject to create persistent data.

RMI Architecture and Functional Specification
  • RMI Specification (also in PDF)

RMI API Specification
(javadoc)
  • java.rmi Package
  • java.rmi.dgc Package
  • java.rmi.registry Package
  • java.rmi.server Package
  • java.rmi.activation Package

RMI Tools
  • rmic - Java RMI stub compiler - (for Microsoft Windows) (for the SolarisTM operating environment)
  • rmiregistry - Java remote object registry - (for Microsoft Windows) (for the Solaris operating environment)
  • rmid - Java RMI activation system daemon - (for Microsoft Windows) (for the Solaris operating environment)

For More Information

  • The RMI and Object Serialization FAQ

  • Search the archives of the RMI-USERS list

  • Subscribe to the RMI-USERS list

  • Dynamic code downloading using RMI
    (Using the java.rmi.server.codebase Property)

  • Useful java.rmi Properties

  • Useful sun.rmi Properties

  • Applying the Factory Pattern to RMI

  • The RMI trail of The JavaTM Tutorial Continued

  • Using RMI with SSL

  • The Java Remote Method Invocation (RMI) Home Page

Copyright © 2003 Sun Microsystems, Inc. All Rights Reserved.
Please send comments to: rmi-comments@java.sun.com 		Sun


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 JVMs* that export remote objects

java.rmi.activation.port (1.2 and later)
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 (1.1 and later)
The value of this property represents the lease duration (in milliseconds) granted to other JVMs that hold remote references to objects which have been exported by this JVM. 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 (1.1 and later)
This property specifies the locations from which classes that are published by this JVM (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 in 1.2 and later) that will be the codebase annotation for all classes loaded from the CLASSPATH of (and subsequently marshalled by) this JVM.

Note:This property must be set correctly in order to dynamically download classes and interfaces using 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 RMI (Using the java.rmi.server.codebase Property).

java.rmi.server.hostname (1.1 and later)
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. In 1.1.7 and later, the default value of this property is the IP address of the local host, in "dotted-quad" format.

java.rmi.server.logCalls (1.1 and later)
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 (1.1.8 and later)
If this value is true, object identifiers for remote objects exported by this JVM will be generated by using a cryptographically secure random number generator. The default value is false.

java.rmi.server.useCodebaseOnly (1.1 and later)
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 JVM. Use of this property prevents client JVMs 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 (1.1.7 and later)
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 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 JVMs that make remote method calls

java.rmi.server.codebase (1.1 and later)
This property specifies the locations from which classes that are published by this JVM (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 JVM.

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 RMI (Using the java.rmi.server.codebase Property).

java.rmi.server.disableHttp (1.1 and later)
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 (1.1 and later)
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 JVM. Use of this property prevents client JVMs 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.
We are very interested in knowing whether this information is useful. Please send any comments or suggestions to: rmi-comments@java.sun.com, with a subject of "java.rmi properties FAQ".

*As used on this web site, the terms "Java(TM) virtual machine" or "JVM" mean a virtual machine for the Java platform.

Copyright © 2003 Sun Microsystems, Inc. All Rights Reserved.
Please send comments to: rmi-comments@java.sun.com 		Sun


RMI Implementation Logging

Java

RMI Implementation Logging
in J2SETM 1.4

 Documentation Contents

As of J2SETM 1.4, Sun's RMI implementation uses the new Logging APIs to provide implementation logging output. The logging configuration file and programmatic API (java.util.logging) can be used to configure RMI implementation logging.

The java.rmi.server.logCalls system property and the implementation-specific sun.rmi.* logging properties that were recognized by previous J2SE versions still function to set the default levels for the 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 RMI implementation and how they correspond to the logging properties supported by previous versions.

Note that the RMI implementation supports a new logging category: client-side call logging, analagous 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

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 © 2003 Sun Microsystems, Inc. All Rights Reserved.
Please send comments to: rmi-comments@java.sun.com 		Sun


RMI Release Notes

Java

RMI Release Notes
for J2SETM 1.4.2

 Documentation Contents
RMI Changes in J2SETM 1.4.2
Changes to RMI for J2SETM 1.4.2 included minor bug fixes.

RMI Changes in J2SETM 1.4.1
HTTP Fallback Is More Configurable
The implementation-specific system property sun.rmi.transport.proxy.eagerHttpFallback has been added to allow additional control over when RMI's default socket factory will fall back to HTTP tunneling. This property configures the default socket factory so that any SocketException thrown by an initial (direct) connection attempt will trigger HTTP tunneling; this more "eager" fallback strategy can be useful when dealing with firewalls which deny instead of ignore connection attempts to unauthorized ports.

java.rmi.Naming.list Method No Longer Prepends a Scheme to Names Returned
In previous releases, the Naming.list method prepended the scheme rmi: to each name contained in the returned array of strings. The Naming.list implementation now matches the specification, returning an array of names that are URL-formatted, but without the scheme component.

java.rmi.server.RemoteServer.setLog Method Now Requires a Permission
The RemoteServer.setLog method now specifies that it throws a SecurityException if the caller does not have permission to set the global call log. The method requires that the calling context has the permission java.util.logging.LoggingPermission("control") to set the log.

java.rmi.server.RMISocketFactory.setFailureHandler Method Now Requires a Permission
The RMISocketFactory.setFailureHandler method now specifies that it throws a SecurityException if the caller does not have permission to set the global java.rmi.server.RMIFailureHandler. The method requires that the calling context has the permission java.lang.RuntimePermission("setFactory") to set the failure handler.
RMI Enhancements in J2SETM 1.4
Server-side Stack Traces Now Retained in Remote Exceptions
The RMI runtime implementation will now preserve the server-side stack trace information of an exception that is thrown from a remote call, in addition to filling in the client-side stack trace as it did in previous releases. Therefore, when such an exception becomes accessible to client code, its stack trace will now contain all of its original server-side trace data followed by the client-side trace.

This feature is made possible by the new "programmatic access to stack trace information" feature of java.lang.Throwable in J2SE 1.4, which included making a Throwable's stack trace data part of its default serialized form. What the client-side RMI runtime implementation now does to cooperate with this feature is to append the client-side trace to the unmarshalled server-side trace, rather than simply overwriting with the client-side trace as it did in previous releases.

Certain RMI server applications may wish to prevent any server-side stack trace data from accompanying an exception to be marshalled as the result of a remote call (as part of the exception's default serialized form in J2SE 1.4), perhaps for reasons of performance or confidentiality. In such cases, the implementation-specific system property

sun.rmi.server.suppressStackTraces
can be set to "true" to cause the server-side RMI runtime implementation to clear the stack traces of all exceptions thrown from the current virtual machine as the result of remote method invocations.

Service Provider Interface for RMIClassLoader
Certain static methods of java.rmi.server.RMIClassLoader now delegate their behavior to an instance of a new service provider interface, java.rmi.server.RMIClassLoaderSpi. The service provider can be configured to augment RMI's dynamic class loading behavior for a given application. By default, the service provider implements the standard behavior of all of the static methods in RMIClassLoader. See the class documentation of RMIClassLoader and RMIClassLoaderSpi for more details.

Dynamic Server Host Name
The java.rmi.server.hostname property can now be dynamically updated to indicate that future exports should use a new host name. Therefore, the new host name value will be contained in the stub for an object that is exported after the property is updated.

Serializing Primitive Class Objects
In previous releases, a ClassNotFoundException would be thrown if an attempt was made to pass a primitive Class object in an RMI call. Now, an object that contains Class objects for primitive types can be passed as a remote method parameter or return value, and can be stored in a java.rmi.MarshalledObject instance.

Enhanced RMI Implementation Logging
Sun's implementation of RMI in J2SE 1.4 now uses the new Logging APIs to provide implemention-specific logging output. See the RMI Implementation Logging page for more information.

Serialization Enhancements
See the Serialization Release Notes for more information on enhancements and improvements to Object Serialization in J2SE 1.4.
RMI Enhancements in Previous Releases
java.rmi.activation.ActivationGroupDesc (since 1.3)
The getClassName method, which returns the group's class name, can now return null, indicating the system's default group implementation. Previously, the getClassName method would return the name of the internal implementation class if the default group implementation was chosen when the descriptor was constructed.

Due to this change, if an application running in a 1.3 JVM registers an new activatable object with the ActivationSystem, rmid must also be upgraded to run 1.3, since a pre-1.3 rmid will not be able to activate the newly registered activatable object.

Constructors of activatable objects (since 1.3)
An activatable object's "activation" constructor, which takes an ActivationID and a MarshalledObjectas arguments and which is called by the ActivationInstantiator each time the object is activated, can now be private or protected. Previously, the implementation only allowed public activation constructors.

java.rmi.server.RMIClassLoader (since 1.3)
java.rmi.server.RMIClassLoader has a new method, getClassLoader. This method returns the class loader that RMI uses to load classes from a specified codebase URL path. This API can be used in an implementation that requires complete RMI marshalling/unmarshalling behavior. See java.rmi.server.RMIClassLoader for details.

Serializing remote objects (since 1.2.2)
Prior to 1.2.2, an attempt to pass an unexported remote object in a RMI call would result in a java.rmi.StubNotFoundException. This exception was a result of the RMI runtime's failure to locate a stub object during an attempt to replace a remote object implementation with its corresponding stub. In 1.2.2 and later releases, an unexported remote object passed in an RMI call will no longer result in an exception, but rather the remote object will be serialized instead of its stub. If the remote object implementation is not serializable, an attempt to pass an unexported object in an RMI call will result in a java.rmi.RemoteException with the nested exception java.io.NotSerializableException.
Changes to RMI Tools (since 1.3)
The RMI Stub Compiler, rmic
  • By default, rmic now assumes that the destination directory for generated stubs is the package-named subdirectory of the current working directory. If the "-d" option is not specified, the result is the same as though it were specified with the current working directory "." as an argument. The "-d" may still be used to override the default destination directory.
  • Two new options, "-idl" and "-iiop" have been added to generate IDL and stubs for IIOP, respectively.
The RMI Activation Daemon, rmid
By default, rmid now requires a security policy file.

*As used on this web site, the terms "Java virtual machine" or "JVM" mean a virtual machine for the Java platform.

Copyright © 2003 Sun Microsystems, Inc. All Rights Reserved.
Please send comments to: rmi-comments@java.sun.com 		Sun


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 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 RMI and Object Serialization .

Copyright © 2003 Sun Microsystems, Inc. All Rights Reserved.
Please send comments to: rmi-comments@java.sun.com 		Sun


sun.rmi Properties

WARNING: The properties described here are not supported, can change at any time, and only exist in certain implementations of RMI from Sun MicrosystemsTM. These properties are not part of the RMI public API. To see a list of the properties that are part of the RMI 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.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.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.rmid.maxstartgroup (1.2 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.

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 JVMs* 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 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 RMI runtime checks for expired DGC leases. The default value is 300000 milliseconds (5 minutes).

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 RMI runtime will allow between garbage collections of the local heap. The default value is 60000 milliseconds (60 seconds).

sun.rmi.loader.logLevel (1.2 and later)
This property controls the logging of each class name and codebase, whenever the 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.

Please note in 1.3 that while the codebase that is printed is the annotated codebase, it may not necessarily be the actual codebase from which the class gets loaded; the RMI class loader defers the class loading to the current thread's context class loader, which may load the class from the CLASSPATH, rather than the annotated codebase. This issue no longer exists in 1.4.

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 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 RMI 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 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 RMI-TCP connections. 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 (2 hours).

Properties that are useful to set on JVMs 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 RMI runtime will wait before retrying a failed DGC "clean" call. The default value is 180000 milliseconds (3 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 RMI runtime will allow between garbage collections of the local heap. The default value is 60000 milliseconds (60 seconds).

sun.rmi.loader.logLevel (1.2 and later)
This property controls the logging of each class name and codebase, whenever the 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.

Please note in 1.3 that while the codebase that is printed is the annotated codebase, it may not necessarily be the actual codebase from which the class gets loaded; the RMI class loader defers the class loading to the current thread's context class loader, which may load the class from the CLASSPATH, rather than the annotated codebase. This issue no longer exists in 1.4.

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 RMI socket connections may reside in an "unused" state, before the 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 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 RMI's default socket factory 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 RMI socket factory. 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 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 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 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 an 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.logLevel (1.1 and later)
This property provides detailed logging for the TCP-specific transport sub-layer. It sends output to the "tcp" log.
We are very interested in knowing whether this information is useful. Please send any comments or suggestions to: rmi-comments@java.sun.com, with a subject of "sun.rmi properties FAQ".

*As used on this web site, the terms "Java(TM) virtual machine" or "JVM" mean a virtual machine for the Java platform.

Copyright © 2003 Sun Microsystems, Inc. All Rights Reserved.
Please send comments to: rmi-comments@java.sun.com 		Sun


Creating an Activatable Remote Object

Creating an Activatable Object

This tutorial shows you the steps for creating an activatable object by extending java.rmi.activation.Activatable. If you are interested in finding out about Making a UnicastRemoteObject Activatable or Activating an object that does not extend java.rmi.activation.Activatable, these are also available as tutorials.

Prior to the release of the JavaTM 2 SDK, an instance of a UnicastRemoteObject could be accessed from a server program that (1) created an instance of the remote object, and (2) ran all the time. Now with the introduction of the class java.rmi.activation.Activatable and the RMI daemon, rmid, programs can be written to register information about remote object implementations that should be created and execute "on demand," rather than running all the time. The RMI daemon, rmid, provides a Java virtual machine* (JVM) from which other JVM instances may be spawned.

Note: For the remainder of this tutorial, the terms "activatable object implementation", "activatable object," and "implementation" may be used interchangeably to refer to the class, examples.activation.ActivatableImplementation, which implements a remote interface and is activatable.

This tutorial is organized as follows:

  • The steps to create the implementation class
  • The steps to create the setup class
  • The steps to compile and run the example code

The files needed for this tutorial are:

  • Client.java, the class which will invoke a method on an activatable object
  • MyRemoteInterface.java, the interface that extends java.rmi.Remote, implemented by:
  • ActivatableImplementation.java, the class which will be activated
  • Setup.java, the class which registers information about the activatable class with the RMI registry and the RMI daemon

You may notice that while the client code is included, it is not discussed in a step-by-step manner, like the implementation and setup classes. The reason for this omission, is that the client code for activatable objects is no different than the RMI client code for accessing non-activatable remote objects. Activation is strictly a server-side implementation decision.

For all of the source code used in the activation tutorials, you may choose from these formats:

  • activation.zip
  • activation.tar
  • activation.tar.Z

Creating the implementation class

For this example, the implementation class will be examples.activation.ActivatableImplementation. There are four steps to create an implementation class:

  1. Make the appropriate imports in the implementation class
  2. Extend your class from java.rmi.activation.Activatable
  3. Declare a two-argument constructor in the implementation class
  4. Implement the remote interface method(s)
Step 1:
Make the appropriate imports in the implementation class
import java.rmi.*;
import java.rmi.activation.*;

Step 2:
Extend your class from java.rmi.activation.Activatable

public class ActivatableImplementation extends Activatable
    implements examples.activation.MyRemoteInterface {
Step 3:
Declare a two-argument constructor in the implementation class
public ActivatableImplementation(ActivationID id, MarshalledObject data)
    throws RemoteException {
    // Register the object with the activation system
    // then export it on an anonymous port
    super(id, 0);
}

Step 4:
Implement the remote interface method(s)

public Object callMeRemotely() throws RemoteException {
    return "Success";
}

Creating the "setup" class

The job of the "setup" class is to create all the information necessary for the activatable class, without necessarily creating an instance of the remote object. For this example the setup class will be examples.activation.Setup.

The setup class passes the information about the activatable class to rmid, registers a remote reference (an instance of the activatable class's stub class) and an identifier (name) with the rmiregistry, and then the setup class may exit. There are seven steps to create a setup class:

  1. Make the appropriate imports
  2. Install a SecurityManager
  3. Create an ActivationGroup instance
  4. Create an ActivationDesc instance
  5. Declare an instance of your remote interface and register with rmid
  6. Bind the stub to a name in the rmiregistry
  7. Quit the setup application

Step 1:
Make the appropriate imports in the setup class

import java.rmi.*;
import java.rmi.activation.*
import java.util.Properties;

Step 2:
Install a SecurityManager

System.setSecurityManager(new RMISecurityManager());

Step 3:
Create an ActivationGroup instance

Note: In this example, for simplicity, we will use a policy file that gives global permission to anyone from anywhere. Do not use this policy file in a production environment. For more information on how to properly open up permissions using a java.security.policy file, please refer to to the following documents:

    Default Policy Implementation and Policy File Syntax

    Permissions in the Java 2 SDK

In the setup application, the job of the activation group descriptor is to provide all the information that rmid will require to contact the appropriate existing JVM or spawn a new JVM for the activatable object.

Note: In order to run this code on your system, you'll need to change the policy file location to be the absolute path to where you've installed the example policy file that came with the source code.

// Because of the Java 2 security model, a security policy should
// be specified for the ActivationGroup VM. The first argument
// to the Properties put method, inherited from Hashtable, is
// the key and the second is the value
//
Properties props = new Properties();
props.put("java.security.policy",
   "/home/rmi_tutorial/activation/policy");

ActivationGroupDesc.CommandEnvironment ace = null;
ActivationGroupDesc exampleGroup = new ActivationGroupDesc(props, ace);

// Once the ActivationGroupDesc has been created, register it
// with the activation system to obtain its ID
//
ActivationGroupID agi =
   ActivationGroup.getSystem().registerGroup(exampleGroup);

Step 4:
Create an ActivationDesc instance

The job of the activation descriptor is to provide all the information that rmid will require to create a new instance of the implementation class.

Note: In order to run this code on your system, you'll need to change the file URL location to be the location of the directory on your system, where you've installed the example source code.

// The "location" String specifies a URL from where the class
// definition will come when this object is requested (activated).
// Don't forget the trailing slash at the end of the URL
// or your classes won't be found.
//
String location = "file:/home/rmi_tutorial/activation/";

// Create the rest of the parameters that will be passed to
// the ActivationDesc constructor
//
MarshalledObject data = null;

// The location argument to the ActivationDesc constructor will be used
// to uniquely identify this class; it's location is relative to the
// URL-formatted String, location.
//
ActivationDesc desc = new ActivationDesc
    (agi, "examples.activation.ActivatableImplementation",
      location, data);

Step 5:
Declare an instance of your remote interface and register the activation descriptor with rmid

MyRemoteInterface mri = (MyRemoteInterface)Activatable.register(desc);
System.out.println("Got the stub for the ActivatableImplementation");

Step 6:
Bind the stub, that was returned by the Activatable.register method, to a name in the rmiregistry

Naming.rebind("ActivatableImplementation", mri);
System.out.println("Exported ActivatableImplementation");

Step 7:
Quit the setup application

System.exit(0);

Compile and run the code

There are six steps to compile and run the code:

  1. Compile the remote interface, implementation, client, and setup classes
  2. Run rmic on the implementation class
  3. Start the rmiregistry
  4. Start the activation daemon, rmid
  5. Run the setup program
  6. Run the client

Step 1:
Compile the remote interface, implementation, client and setup classes

% javac -d . MyRemoteInterface.java
% javac -d . ActivatableImplementation.java
% javac -d . Client.java
% javac -d . Setup.java

Step 2:
Run rmic on the implementation class

% rmic -d . examples.activation.ActivatableImplementation

Step 3:
Start the rmiregistry

% rmiregistry &

Note: Before you start the rmiregistry, you must make sure that the shell or window in which you will run the registry, either has no CLASSPATH set or has a CLASSPATH that does not include the path to any classes that you want downloaded to your client, including the stubs for your remote object implementation classes.

If you start the rmiregistry, and it can find your stub classes in its CLASSPATH, it will ignore the server's java.rmi.server.codebase property, and as a result, your client(s) will not be able to download the stub code for your remote object.

Step 4:
Start the activation daemon, rmid

% rmid -J-Djava.security.policy=rmid.policy &
Where rmid.policy is the name of the security policy file for rmid.

Note: By default, rmid now requires a security policy file, that is used to verify whether or not the information in each ActivationGroupDescriptor is allowed to be used to launch a JVM for an activation group. For complete details, please refer to the rmid man page for the Solaris operating environment and the rmid man page for the Microsoft Windows platform.

Step 5:
Run the setup program

Run the setup, setting the codebase property to be the location of the implementation stubs. There are four things that need to go on the same command line:

  1. The "java" command
  2. A property name=value pair that specifies the location of the security policy file
  3. A property to specify where the stub code lives (no spaces from the "-D" all the way though the last "/")
  4. The fully-qualified package name of the setup program.

There should be one space just after the word "java", one between the two properties, and a third one just before the word "examples" (which is very hard to see when you view this as text, in a browser, or on paper).

% java  -Djava.security.policy=/home/rmi_tutorial/activation/policy   -Djava.rmi.server.codebase=file:/home/rmi_tutorial/activation/  examples.activation.Setup

The codebase property will be resolved to a URL, so it must have the form of "http://aHost/somesource/" or "file:/myDirectory/location/" or, due to the requirements of some operating systems, "file:///myDirectory/location/" (three slashes after the "file:").

While a file: URL is sometimes easier to use for running example code, using the file: URL will mean that the only clients that will be able to access the server are those that can access the same files system as the server (either by virtue of running on the same machine as the server or by using a shared filesystem, such as NFS). If you wish to use an HTTP server, but don't have one available to you, please feel free to download our HTTP server.

Please note that each of these sample URL strings has a trailing "/". The trailing slash is a requirement for the URL set by the java.rmi.server.codebase property, so the implementation can resolve (find) your class definition(s) properly. For more information on setting the java.rmi.server.codebase property from the command line, please take a look at our tutorial on dynamic code downloading using the java.rmi.server.codebase property.

If you forget the trailing slash on the property, or if the class files can't be located at the source (they aren't really being made available for download) or if you misspell the property name, you'll get thrown a java.lang.ClassNotFoundException. This exception will be thrown when you try to bind your remote object to the rmiregistry, or when the first client attempts to access that object's stub. If the latter case occurs, you have another problem as well because the rmiregistry was finding the stubs in its CLASSPATH.

The server output should look like this:

      Got the stub for the ActivatableImplementation
      Exported ActivatableImplementation

Step 6:
Run the client

The argument to the examples.activation.Client program is the hostname of the implementation server, in this case, "vector".

% java -Djava.security.policy=/home/rmi_tutorial/activation/policy
 examples.activation.Client vector

The client output should look like this:

      Got a remote reference to the object that extends Activatable.
      Making remote call to the server
      Returned from remote call
      Result: Success
*As used on this web site, the terms "Java virtual machine" or "JVM" mean a virtual machine for the Java platform.
Copyright © 2003 Sun Microsystems, Inc. All Rights Reserved.
Please send comments to: rmi-comments@java.sun.com 		Sun


Making a UnicastRemoteObject Activatable

This tutorial shows you the steps for migrating an existing UnicastRemoteObject to an activatable object by extending java.rmi.activation.Activatable. This page is just for developers who wish to change an existing class from being a sub-class of UnicastRemoteObject to being a sub-class of java.rmi.activation.Activatable. If you are interested in finding out about Creating an Activatable Object or Activating an object that does not extend java.rmi.activation.Activatable, these are also available as tutorials.

Prior to the release of the JavaTM 2 SDK, an instance of a UnicastRemoteObject could be accessed from a server program that (1) created an instance of the remote object, and (2) ran all the time. Now with the introduction of the class java.rmi.activation.Activatable and the RMI daemon, rmid, programs can be written to register information about remote object implementations that should be created and execute "on demand," rather than running all the time. The RMI daemon, rmid, provides a Java virtual machine* (JVM) from which other JVM instances may be spawned.

Note: For the remainder of this tutorial, the terms "activatable object implementation", "activatable object," and "implementation" may be used interchangeably to refer to the class, examples.activation.MyRemoteInterfaceImpl, which implements a remote interface and is activatable.

This tutorial is organized as follows:

  • The steps to modify the implementation class
  • The steps to modify the server class
  • The steps to compile and run the example code

The files needed for this tutorial are:

  • Client2.java, the class which will invoke a method on an activatable object
  • MyRemoteInterface.java, the interface that extends java.rmi.Remote, implemented by:
  • MyRemoteInterfaceImpl.java, the class which will be activated
  • Setup2.java, the class which registers information about the activatable class with the RMI registry and the RMI daemon

You may notice that while the client code is included, it is not discussed in a step-by-step manner, like the implementation and setup classes. The reason for this omission, is that the client code for activatable objects is no different than the RMI client code for accessing non-activatable remote objects. Activation is strictly a server-side implementation decision.

For all of the source code used in the activation tutorials, you may choose from these formats:

  • activation.zip
  • activation.tar
  • activation.tar.Z

Creating the implementation class

For this example, the implementation class will be examples.activation.MyRemoteInterfaceImpl. There are four steps to migrate an existing implementation class that extends from UnicastRemoteObject:

  1. Make the appropriate imports in the implementation class
  2. Modify the class declaration so that the class now extends from java.rmi.activation.Activatable
  3. Remove or comment out the old no-argument constructor
  4. Declare a two-argument constructor in the implementation class
Step 1:
Make the appropriate imports in the implementation class
import java.rmi.*;
import java.rmi.activation.*;

Step 2:
Modify the class declaration so that the class now extends from java.rmi.activation.Activatable

public class MyRemoteInterfaceImpl extends Activatable
    implements examples.activation.MyRemoteInterface {
Step 3:
Remove or comment out the old no-argument constructor
// public MyRemoteInterfaceImpl() throws RemoteException
// {
// }

Step 4:
Declare a two-argument constructor in the implementation class

public MyRemoteInterfaceImpl(ActivationID id, MarshalledObject data)
    throws RemoteException {

    // Register the object with the activation system
    // then export it on an anonymous port
    //
    super(id, 0);
}

Creating the "setup" class

Unlike the RMI server class that must stay alive as long as the implementation needs to be made available, the job of the "setup" class is to create all the information necessary for the activatable class, without necessarily creating an instance of the remote object. For this example the setup class will be examples.activation.Setup2.

The setup class passes information about the activatable class to rmid, registers a remote reference (an instance of the activatable class's stub class) and an identifier (name) with the rmiregistry, and then the setup class may exit. There are seven steps to create a setup class:

  1. Make the appropriate imports
  2. Install a SecurityManager
  3. Create an ActivationGroup instance
  4. Create an ActivationDesc instance
  5. Remove the reference to the implementation class creation, and register with rmid
  6. Bind the stub to a name in the rmiregistry
  7. Quit the setup application

Step 1:
Make the appropriate imports in the setup class

import java.rmi.*;
import java.rmi.activation.*
import java.util.Properties;

Step 2:
Install a SecurityManager

System.setSecurityManager(new RMISecurityManager());

Step 3:
Create an ActivationGroup instance

Note: In this example, for simplicity, we will use a policy file that gives global permission to anyone from anywhere. Do not use this policy file in a production environment. For more information on how to properly open up permissions using a java.security.policy file, please refer to to the following documents:

    Default Policy Implementation and Policy File Syntax

    Permissions in the Java 2 SDK

In the setup application, the job of the activation group descriptor is to provide all the information that rmid will require to contact the appropriate existing JVM or spawn a new JVM for the activatable object.

Note: In order to run this code on your system, you'll need to change the policy file location to be the absolute path to where you've installed the example policy file that came with the source code.

// Because of the Java 2 security model, a security policy should
// be specified for the ActivationGroup VM. The first argument
// to the Properties put method, inherited from Hashtable, is
// the key and the second is the value
//
Properties props = new Properties();
props.put("java.security.policy",
   "/home/rmi_tutorial/activation/policy");

ActivationGroupDesc.CommandEnvironment ace = null;
ActivationGroupDesc exampleGroup = new ActivationGroupDesc(props, ace);

// Once the ActivationGroupDesc has been created, register it
// with the activation system to obtain its ID
//
ActivationGroupID agi =
   ActivationGroup.getSystem().registerGroup(exampleGroup);

Step 4:
Create an ActivationDesc instance

In the setup application, the job of the activation descriptor is to provide all the information that rmid will require to create a new instance of the implementation class.

Note: In order to run this code on your system, you'll need to change the file URL location to be the location of the directory on your system, where you've installed the example source code.

// Don't forget the trailing slash at the end of the URL
// or your classes won't be found
//
String location = "file:/home/rmi_tutorial/activation/";

// Create the rest of the parameters that will be passed to
// the ActivationDesc constructor
//
MarshalledObject data = null;

// The location argument to the ActivationDesc constructor will be used
// to uniquely identify this class; it's location is relative to the
// URL-formatted String, location.
//
ActivationDesc desc = new ActivationDesc
    (agi, "examples.activation.ActivatableImplementation",
      location, data);

Step 5:
Remove the reference to the implementation class creation, declare an instance of your remote interface, and register the activation descriptor with rmid

// MyRemoteInterfaceImpl mri = new MyRemoteInterfaceImpl();
// the above line is replaced with the following:
//
MyRemoteInterface mri = (MyRemoteInterface)Activatable.register(desc);
System.out.println("Got the stub for the MyRemoteInterfaceImpl");

Step 6:
Bind the stub, that was returned by the Activatable.register method, to a name in the rmiregistry

Naming.rebind("MyRemoteInterfaceImpl", mri);
System.out.println("Exported MyRemoteInterfaceImpl");

Step 7:
Quit the setup application

System.exit(0);

Compile and run the code

There are six steps to compile and run the code:

  1. Compile the remote interface, implementation, client, and setup classes
  2. Run rmic on the implementation class
  3. Start the rmiregistry
  4. Start the activation daemon, rmid
  5. Run the setup program
  6. Run the client

Step 1:
Compile the remote interface, implementation, client and setup classes

% javac -d . MyRemoteInterface.java
% javac -d . MyRemoteInterfaceImpl.java
% javac -d . Client2.java
% javac -d . Setup2.java

Step 2:
Run rmic on the implementation class

% rmic -d . examples.activation.MyRemoteInterfaceImpl

Step 3:
Start the rmiregistry

% rmiregistry &

Note: Before you start the rmiregistry, you must make sure that the shell or window in which you will run the registry, either has no CLASSPATH set or has a CLASSPATH that does not include the path to any classes that you want downloaded to your client, including the stubs for your remote object implementation classes.

If you start the rmiregistry, and it can find your stub classes in its CLASSPATH, it will ignore the server's java.rmi.server.codebase property, and as a result, your client(s) will not be able to download the stub code for your remote object.

Step 4:
Start the activation daemon, rmid

% rmid -J-Djava.security.policy=rmid.policy &
Where rmid.policy is the name of the security policy file for rmid.

Note: By default, rmid now requires a security policy file, that is used to verify whether or not the information in each ActivationGroupDescriptor is allowed to be used to launch a JVM for an activation group. For complete details, please refer to the rmid man page for the Solaris operating environment and the rmid man page for the Microsoft Windows platform.

Step 5:
Run the setup program

Run the setup, setting the codebase property to be the location of the implementation stubs. There are four things that need to go on the same command line:

  1. The "java" command
  2. A property name=value pair that specifies the location of the security policy file
  3. A property to specify where the stub code lives (no spaces from the "-D" all the way though the last "/")
  4. The fully-qualified package name of the setup program.

There should be one space just after the word "java", one between the two properties, and a third one just before the word "examples" (which is very hard to see when you view this as text, in a browser, or on paper).

% java  -Djava.security.policy=/home/rmi_tutorial/activation/policy  -Djava.rmi.server.codebase=file:/home/rmi_tutorial/activation/  examples.activation.Setup2

The codebase property will be resolved to a URL, so it must have the form of "http://aHost/somesource/" or "file:/myDirectory/location/" or, due to the requirements of some operating systems, "file:///myDirectory/location/" (three slashes after the "file:").

While a file: URL is sometimes easier to use for running example code, using the file: URL will mean that the only clients that will be able to access the server are those that can access the same files system as the server (either by virtue of running on the same machine as the server or by using a shared filesystem, such as NFS). If you wish to use an HTTP server, but don't have one available to you, please feel free to download our HTTP server.

Please note that each of these sample URL strings has a trailing "/". The trailing slash is a requirement for the URL set by the java.rmi.server.codebase property, so the implementation can resolve (find) your class definition(s) properly. For more information on setting the java.rmi.server.codebase property from the command line, please take a look at our tutorial on dynamic code downloading using the java.rmi.server.codebase property.

If you forget the trailing slash on the property, or if the class files can't be located at the source (they aren't really being made available for download) or if you misspell the property name, you'll get thrown a java.lang.ClassNotFoundException. This exception will be thrown when you try to bind your remote object to the rmiregistry, or when the first client attempts to access that object's stub. If the latter case occurs, you have another problem as well because the rmiregistry was finding the stubs in its CLASSPATH.

The server output should look like this:

    Got the stub for the MyRemoteInterfaceImpl
    Exported MyRemoteInterfaceImpl
Step 6:
Run the client

The argument to the client program is the hostname of the implementation server, in this case, "vector".

% java -Djava.security.policy=/home/rmi_tutorial/activation/policy
examples.activation.Client2 vector

The client output should look like this:

    Got a remote reference to the newly-Activatable object
    Returned from remote call
    Result: Successful execution of callMeRemotely() in MyRemoteInterfaceImpl
*As used on this web site, the terms "Java virtual machine" or "JVM" mean a virtual machine for the Java platform.
Copyright © 2003 Sun Microsystems, Inc. All Rights Reserved.
Please send comments to: rmi-comments@java.sun.com 		Sun


Activating an object that does not extend java.rmi.activation.Activatable

This tutorial shows you the steps for enabling an existing class to become activatable. If you are interested in finding out about Creating an Activatable Object or Making a UnicastRemoteObject Activatable, these are also available as tutorials.

Prior to the release of the JavaTM 2 SDK, an instance of a class that did not extend from UnicastRemoteObject could be accessed from a server program that (1) created an instance of the remote object, and (2) ran all the time. This functionality was provided by creating a constructor which exported the object by calling the static method UnicastRemoteObject.exportObject. The exportObject method accepts as an argument an object that implements an interface that extends from java.rmi.Remote.

Now with the introduction of the class java.rmi.activation.Activatable and the RMI daemon, rmid, programs can be written to register information about remote object implementations that should be created and execute "on demand," rather than running all the time. The RMI daemon, rmid, provides a Java virtual machine* (JVM) from which other JVM instances may be spawned. As in the UnicastRemoteObject.exportObject case, activatable objects may be exported using a static method, Activatable.exportObject, and these objects must implement a remote interface.

Note: For the remainder of this tutorial, the terms "activatable object implementation", "activatable object," and "implementation" may be used interchangeably to refer to the class, examples.activation.MyClass, which implements a remote interface and is activatable.

This tutorial is organized as follows:

  • The steps to create a remote interface
  • The steps to modify the implementation class
  • The steps to create the setup class
  • The steps to compile and run the example code
The files needed for this tutorial are:
  • Client3.java, the class which will invoke a method on an activatable object
  • AnotherRemoteInterface.java, the interface that extends java.rmi.Remote, implemented by:
  • MyClass.java, the class which is being modified to be activatable
  • Setup3.java, the class which registers information about the activatable class with the RMI registry and the RMI daemon

You may notice that while the client code is included, it is not discussed in a step-by-step manner, like the implementation and setup classes. The reason for this omission, is that the client code for activatable objects is no different than the RMI client code for accessing non-activatable remote objects. Activation is strictly a server-side implementation decision.

For all of the source code used in the activation tutorials, you may choose from these formats:

  • activation.zip
  • activation.tar
  • activation.tar.Z

Creating the remote interface

Create an interface that describes each of the methods that you would like to call remotely. For this example, the remote interface will be examples.activation.AnotherRemoteInterface. There are three steps to create a remote interface.

  1. Make the appropriate imports in the interface
  2. Extend java.rmi.Remote
  3. Declare each of the methods that may be called remotely

Step 1:
Make the appropriate imports in your interface

import java.rmi.*;

Step 2:
Extend java.rmi.Remote

public interface AnotherRemoteInterface extends Remote {

Step 3:
Declare each of the methods that may be called remotely

public String calltheServer(String s) throws RemoteException;

Creating the implementation class

For this example, the implementation class will be examples.activation.MyClass. There are three steps to migrate a class which does not extend Activatable or UnicastRemoteObject to become activatable:

  1. Make the appropriate imports in the implementation class
  2. Modify the class declaration so that the class now implements an interface that extends from java.rmi.Remote
  3. Declare a two-argument constructor in the implementation class
Step 1:
Make the appropriate imports in the implementation class
import java.rmi.*;
import java.rmi.activation.*;

Step 2:
Modify the class declaration so that the class implements an interface that extends from java.rmi.Remote

public class MyClass
    implements examples.activation.AnotherRemoteInterface
{
Step 3:
Add a new two-argument constructor to the implementation class
public MyClass(ActivationID id, MarshalledObject data)
    throws RemoteException
{
    // Register the object with the activation system
    // then export it on an anonymous port
    //
    Activatable.exportObject(this, id, 0);
}

Creating the "setup" class

The job of the "setup" class is to create all the information necessary for the activatable class, without necessarily creating an instance of the remote object. For this example, the setup class will be examples.activation.Setup3.

The setup class passes information about the activatable class to rmid, registers a remote reference (an instance of the activatable class's stub class) and an identifier (name) with the rmiregistry, and then the setup class may exit. There are seven steps to create a setup class:

  1. Make the appropriate imports
  2. Install a SecurityManager
  3. Create an ActivationGroup instance
  4. Create an ActivationDesc instance
  5. Remove the reference to the implementation class creation, and register with rmid
  6. Bind the stub to a name in the rmiregistry
  7. Quit the setup application

Step 1:
Make the appropriate imports in the setup class

import java.rmi.*;
import java.rmi.activation.*
import java.util.Properties;

Step 2:
Install a SecurityManager

System.setSecurityManager(new RMISecurityManager());

Step 3:
Create an ActivationGroup instance

Note: In this example, for simplicity, we will use a policy file that gives global permission to anyone from anywhere. Do not use this policy file in a production environment. For more information on how to properly open up permissions using a java.security.policy file, please refer to to the following documents:

    Default Policy Implementation and Policy File Syntax

    Permissions in the Java 2 SDK

In the setup application, the job of the activation group descriptor is to provide all the information that rmid will require to contact the appropriate existing JVM or spawn a new JVM for the activatable object.

Note: In order to run this code on your system, you'll need to change the policy file location to be the absolute path to where you've installed the example policy file that came with the source code.

// Because of the Java 2 security model, a security policy should
// be specified for the ActivationGroup VM. The first argument
// to the Properties put method, inherited from Hashtable, is
// the key and the second is the value
//
Properties props = new Properties();
props.put("java.security.policy",
   "/home/rmi_tutorial/activation/policy");

ActivationGroupDesc.CommandEnvironment ace = null;
ActivationGroupDesc exampleGroup = new ActivationGroupDesc(props, ace);

// Once the ActivationGroupDesc has been created, register it
// with the activation system to obtain its ID
//
ActivationGroupID agi =
   ActivationGroup.getSystem().registerGroup(exampleGroup);

Step 4:
Create an ActivationDesc instance

In the setup application, the job of the activation descriptor is to provide all the information that rmid will require to create a new instance of the implementation class.

Note: In order to run this code on your system, you'll need to change the file URL location to be the location of the directory on your system, where you've installed the example source code.

// The "location" URL specifies where the class definition
// will come from when this object is requested (activated).
// Don't forget the trailing slash at the end of the URL
// or your classes won't be found
//
String location = "file:/home/rmi_tutorial/activation/";

// Create the rest of the parameters that will be passed to
// the ActivationDesc constructor
//
MarshalledObject data = null;

// The location argument to the ActivationDesc constructor will be used
// to uniquely identify this class; it's location is relative to the
// URL-formatted String, location.
//
ActivationDesc desc = new ActivationDesc
    (agi, "examples.activation.ActivatableImplementation",
      location, data);

Step 5:
Declare an instance of your remote interface and register the activation descriptor with rmid

AnotherRemoteInterface ari =
    (AnotherRemoteInterface)Activatable.register(desc);
System.out.println("Got the stub for MyClass");

Step 6:
Bind the stub, that was returned by the Activatable.register method, to a name in the rmiregistry

Naming.rebind("MyClass", ari);
System.out.println("Exported MyClass");

Step 7:
Quit the setup application

System.exit(0);

Compile and run the code

There are six steps to compile and run the code:

  1. Compile the remote interface, implementation, client and setup classes
  2. Run rmic on the implementation class
  3. Start the rmiregistry
  4. Start the activation daemon, rmid
  5. Run the setup program
  6. Run the client

    Step 1:
    Compile the remote interface, implementation, client and setup classes

    % javac -d . AnotherRemoteInterface.java
% javac -d . MyClass.java
% javac -d . Client3.java
% javac -d . Setup3.java

    Step 2:
    Run rmic on the implementation class

    % rmic -d . examples.activation.MyClass

    Step 3:
    Start the rmiregistry

    % rmiregistry &

    Note: Before you start the rmiregistry, you must make sure that the shell or window in which you will run the registry, either has no CLASSPATH set or has a CLASSPATH that does not include the path to any classes that you want downloaded to your client, including the stubs for your remote object implementation classes.

    If you start the rmiregistry, and it can find your stub classes in its CLASSPATH, it will ignore the server's java.rmi.server.codebase property, and as a result, your client(s) will not be able to download the stub code for your remote object.

    Step 4:
    Start the activation daemon, rmid

    % rmid -J-Djava.security.policy=rmid.policy &
    Where rmid.policy is the name of the security policy file for rmid.

    Note: By default, rmid now requires a security policy file, that is used to verify whether or not the information in each ActivationGroupDescriptor is allowed to be used to launch a JVM for an activation group. For complete details, please refer to the rmid man page for the Solaris operating environment and the rmid man page for the Microsoft Windows platform.

    Step 5:
    Run the setup program

    Run the setup, setting the codebase property to be the location of the implementation stubs. There are four things that need to go on the same command line:

    1. The "java" command
    2. A property name=value pair that specifies the location of the security policy file
    3. A property to specify where the stub code lives (no spaces from the "-D" all the way though the last "/")
    4. The fully-qualified package name of the setup program.

    There should be one space just after the word "java", one between the two properties, and a third one just before the word "examples" (which is very hard to see when you view this as text, in a browser, or on paper).

    % java  -Djava.security.policy=/home/rmi_tutorial/activation/policy  -Djava.rmi.server.codebase=file:/home/rmi_tutorial/activation/  examples.activation.Setup3

    The codebase property will be resolved to a URL, so it must have the form of "http://aHost/somesource/" or "file:/myDirectory/location/" or, due to the requirements of some operating systems, "file:///myDirectory/location/" (three slashes after the "file:").

    While a file: URL is sometimes easier to use for running example code, using the file: URL will mean that the only clients that will be able to access the server are those that can access the same files system as the server (either by virtue of running on the same machine as the server or by using a shared filesystem, such as NFS). If you wish to use an HTTP server, but don't have one available to you, please feel free to download our HTTP server.

    Please note that each of these sample URL strings has a trailing "/". The trailing slash is a requirement for the URL set by the java.rmi.server.codebase property, so the implementation can resolve (find) your class definition(s) properly. For more information on setting the java.rmi.server.codebase property from the command line, please take a look at our tutorial on dynamic code downloading using the java.rmi.server.codebase property.

    If you forget the trailing slash on the property, or if the class files can't be located at the source (they aren't really being made available for download) or if you misspell the property name, you'll get thrown a java.lang.ClassNotFoundException. This exception will be thrown when you try to bind your remote object to the rmiregistry, or when the first client attempts to access that object's stub. If the latter case occurs, you have another problem as well because the rmiregistry was finding the stubs in its CLASSPATH.

    The server output should look like this:

          Got the stub for MyClass
      Exported MyClass
    Step 6:
    Run the client

    The argument to the client program is the hostname of the implementation server, in this case, "vector".

    % java -Djava.security.policy=/home/rmi_tutorial/activation/policy
 examples.activation.Client3 vector

    The client output should look like this:

          Got a remote reference to the class MyClass
      Called the remote method
      Result: Watson are you there?  I'm here!

    An Alternate Approach

    An alternative approach to what we just went through is to create an "adapter" class that implements the remote interface, gets registered with rmid and the registry by the setup program, and which then creates the object instance and forwards the remote method to that instance. The benefit to this approach is that you don't have to make a change to the original non-remote class.

    So, let's assume that the original, non-remote class, looks like this:

      package examples.activation;

  public class MyNonRemoteClass {

      private String result = null;

      // Here's the original class, which concatenates two strings
      //
      public String calltheServer(String takeThis) {

      result = takeThis + "I'm here!";
      return result;
      }

  }

    We write the same interface, examples.activation.AnotherRemoteInterface, to describe the methods we'd like to call remotely:

      package examples.activation;

  import java.rmi.*;

  public interface AnotherRemoteInterface extends Remote {

      public String calltheServer(String s) throws RemoteException;

  }

    But rather than editing MyNonRemoteClass.java, which we may not always have the source code to do anyway, we'll create a new class examples.activation.MyNonRemoteClassAdapter , which (like an event adapter) implements the specified interface, and then takes appropriate action. What's new in MyNonRemoteClassAdapter from what we did earlier, is that it creates an instance of MyNonRemoteClass in it's constructor and it calls the MyNonRemoteClass.calltheServer method.

      package examples.activation;

  import java.rmi.*;
  import java.rmi.activation.*;

  public class MyNonRemoteClassAdapter implements
      examples.activation.AnotherRemoteInterface
  {
      private String result = null;
      private MyNonRemoteClass mnrc;

      // The constructor for activation and export; this
      // constructor is called by the method
      // ActivationInstantiator.newInstance during
      // activation, to construct the object.
      //
      public MyNonRemoteClassAdapter(ActivationID id,
      MarshalledObject data) throws RemoteException
      {
      // Register the object with the activation system
      // then export it on an anonymous port
      //
      Activatable.exportObject(this, id, 0);

      // Create an instance of the class MyNonRemoteClass
      //
      mnrc = new MyNonRemoteClass();
      }

      // Define the method declared in AnotherRemoteInterface
      // to accept a String, modify it, and return it to
      // the client
      //
      public String calltheServer(String takeThis)
      throws RemoteException
      {
      // Rather than modify the String here, forward
      // it on to the non-remote object implementation
      //
      result = mnrc.calltheServer(takeThis);
      return result;
      }

  }

    Now the class we'll run rmic on and the class referenced by the setup program will be the adapter class. The setup program examples.activation.Setup3alt looks like this now:

      package examples.activation;

  import java.rmi.*;
  import java.rmi.activation.*;
  import java.util.Properties;

  public class Setup3alt {

      // This class registers information about the MyClass
      // class with rmid and the rmiregistry
      //
      public static void main(String[] args) throws Exception {

      System.setSecurityManager(new RMISecurityManager());

      AnotherRemoteInterface ari;

      // Don't forget the trailing slash at the end of the URL
      // or your classes won't be found
      //
      String location = "file:/home/rmi_tutorial/activation/";

      // Create the rest of the parameters that will be passed to
      // the ActivationDesc constructor
      //
      MarshalledObject data = null;

      // The second argument to the ActivationDesc constructor
      // will be used to uniquely identify this class; it's
      // location is relative to theURL-formatted String, location.
      //
      ActivationDesc desc = new ActivationDesc
          ("examples.activation.MyNonRemoteClassAdapter",
          location, data);

      ari = (AnotherRemoteInterface)Activatable.register(desc);
      System.out.println("Got the stub for MyNonRemoteClassAdapter");

      // Bind the stub to a name in the registry running on 1099
      //
      Naming.rebind("MyNonRemoteClassAdapter", ari);
      System.out.println("Exported MyNonRemoteClassAdapter");

      System.exit(0);
      }

  }
    *As used on this web site, the terms "Java virtual machine" or "JVM" mean a virtual machine for the Java platform.
    Copyright © 2003 Sun Microsystems, Inc. All Rights Reserved.
    Please send comments to: rmi-comments@java.sun.com     		Sun


Using a MarshalledObject to create persistent data

This tutorial should not be the first activation tutorial that you read. This tutorial assumes that you have already read one or more of the three introductory activation tutorials:

  • Creating an Activatable Object
  • Making a UnicastRemoteObject Activatable
  • Activating an object that does not extend java.rmi.activation.Activatable

In the case of a UnicastRemoteObject, it is easy to pass command-line arguments to the implementation class, because the server program that received those arguments is always running during the lifetime of the remote object implementation. For activatable objects, however, the setup class may exit immediately after registering the activation descriptor with the RMI daemon and registering the stub with the rmiregistry.

The MarshalledObject class provides a flexible mechanism for passing persistence or initialization data through the ActivationDesc, registered with rmid, rather than hard-coding values into the implementation's class file.

Note: For the remainder of this tutorial, the terms "activatable object implementation", "activatable object," and "implementation" may be used interchangeably to refer to the class, examples.activation.MyPersistentClass, which implements a remote interface and is activatable.

In this tutorial the setup class, examples.activation.Setup4, does two new things:

  • It constructs a java.util.Properties object to pass the location of the java.security.properties file to the constructor of an ActivationGroupDescriptor, which in turn, gets passed to the constructor of the ActivationDesc.
  • It uses the MarshalledObject, that it passes to the ActivationDesc constructor, to store a java.io.File object that represents the location of the persistent data storage.

In this example, if the persistentObjectStore.ser file exists, the activatable object implementation is initialized with the persistent data from the file. Otherwise, if the file does not exist, the activatable object initializes itself as though this is the first time a client has tried to send data.

The client program, examples.activation.Client4, passes a vector of transaction-like data to the activatable object, and that data is added to the implementation object's vector. Each time a client calls the implementation (to add more transaction data), the activatable implementation stores its state (writes the vector) out to the file specified by the MarshalledObject.

This tutorial is organized as follows:

  • The steps to create a remote interface
  • The steps to create the implementation class
  • The steps to create the setup class
  • The steps to compile and run the example code
The files needed for this tutorial are:
  • Client4.java, the class which will invoke a method on an activatable object
  • YetAnotherRemoteInterface.java, the interface that extends java.rmi.Remote, implemented by:
  • MyPersistentClass.java, the class which is activatable
  • Setup4.java, the class which registers information about the activatable class with the RMI registry and the RMI daemon

You may notice that while the client code is included, it is not discussed in a step-by-step manner, like the implementation and setup classes. The reason for this omission, is that the client code for activatable objects is no different than the RMI client code for accessing non-activatable remote objects. Activation is strictly a server-side implementation decision.

For all of the source code used in the activation tutorials, you may choose from these formats:

  • activation.zip
  • activation.tar
  • activation.tar.Z

Creating the remote interface

Create an interface that describes each of the methods that you would like to call remotely. For this example, the remote interface will be examples.activation.YetAnotherRemoteInterface. There are three steps to create a remote interface:

  1. Make the appropriate imports in the interface
  2. Extend java.rmi.Remote
  3. Declare each of the methods that may be called remotely
Step 1:
Make the appropriate imports in your interface
import java.rmi.*;
import java.util.Vector;
Step 2:
Extend java.rmi.Remote
public interface YetAnotherRemoteInterface extends Remote {
Step 3:
Declare each of the methods that may be called remotely
public Vector calltheServer(Vector v) throws RemoteException;

Creating the implementation class

For this example, the implementation class will be examples.activation.MyPersistentClass. There are five steps to create an activatable implementation class that uses a MarshalledObject:

  1. Make the appropriate imports in the implementation class
  2. Extend your class from java.rmi.activation.Activatable
  3. Declare a two-argument constructor in the implementation class
  4. Write the methods that use the MarshalledObject, to save and restore the object's data state
  5. Implement the remote interface method(s)

Step 1:
Make the appropriate imports in the implementation class
import java.io.*;
import java.rmi.*;
import java.rmi.activation.*;
import java.util.Vector;

Step 2:
Extend your class from java.rmi.activation.Activatable

public class MyPersistentClass extends Activatable
    implements examples.activation.YetAnotherRemoteInterface {
Step 3:
Declare a two-argument constructor in the implementation class

In the constructor, in addition to the normal call to the superclass's constructor, in this example the MarshalledObject is used to specify the file name of the persistent data store. If the file exists, it's used to initialize this object's variable, a Vector named "transactions". If the file object doesn't exist, then the vector is manually initialized. If there is any error reading the file, then object construction fails.

private Vector transactions;
private File holder;

public MyPersistentClass(ActivationID id, MarshalledObject data)
    throws RemoteException, ClassNotFoundException, java.io.IOException {

    // Register the object with the activation system
    // then export it on an anonymous port
    super(id, 0);

    // Extract the File object from the MarshalledObject that was
    // passed to the constructor
    //
    holder = (File)data.get();

    if (holder.exists()) {
        // Use the MarshalledObject to restore my state
    //
    this.restoreState();
    } else {
    transactions = new Vector(1,1);
    transactions.addElement("Initializing transaction vector");
    }

}

Step 4:
Write the methods that use the MarshalledObject, to save and restore the object's data state

// If the MarshalledObject that was passed to the constructor was
// a file, then use it to recover the vector of transaction data
//
private void restoreState() throws IOException, ClassNotFoundException {
    File f = holder;
    FileInputStream fis = new FileInputStream(f);
    ObjectInputStream ois = new ObjectInputStream(fis);
    transactions = (Vector)ois.readObject();
    ois.close();
}

private void saveState() {
    try {
    File f  = holder;
    FileOutputStream fos = new FileOutputStream(f);
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(getTransactions());
    oos.close();
    } catch (Exception e) {
    throw new RuntimeException("Error saving vector of data");
    }
}

Step 5:
Implement the remote interface method(s)

Add each of the vector elements passed from the client to the object instance and save the updated vector out to a file.

public Vector calltheServer(Vector v) throws RemoteException {

     int limit = v.size();
     for (int i = 0; i < limit; i++) {
         transactions.addElement(v.elementAt(i));
     }

     // Save this object's data out to file
     //
     this.saveState();
     return transactions;
}

Creating the "setup" class

The job of the "setup" class is to create all the information necessary for the activatable class, without necessarily creating an instance of the remote object. For this example, the setup class will be examples.activation.Setup4.

The setup class passes information about the activatable class to rmid, registers a remote reference (an instance of the activatable class's stub class) and an identifier (name) with the rmiregistry, and then the setup class may exit. There are seven steps to create a setup class:

  1. Make the appropriate imports
  2. Install a SecurityManager
  3. Create an ActivationGroup instance
  4. Create an ActivationDesc instance
  5. Remove the reference to the implementation class creation, and register with rmid
  6. Bind the stub to a name in the rmiregistry
  7. Quit the setup application

Step 1:
Make the appropriate imports in the setup class

import java.io.File;
import java.rmi.*;
import java.rmi.activation.*;
import java.util.Properties;

Step 2:
Install a SecurityManager

System.setSecurityManager(new RMISecurityManager());

Step 3:
Create an ActivationGroup instance

Note: In this example, for simplicity, we will use a policy file that gives global permission to anyone from anywhere. Do not use this policy file in a production environment. For more information on how to properly open up permissions using a java.security.policy file, please refer to to the following documents:

    Default Policy Implementation and Policy File Syntax

    Permissions in the Java 2 SDK

In the setup application, the job of the activation group descriptor is to provide all the information that rmid will require to contact the appropriate existing JavaTM virtual machine* (JVM) or spawn a new JVM for the activatable object.

Note: In order to run this code on your system, you'll need to change the policy file location to be the absolute path to where you've installed the example policy file that came with the source code.

// Because of the Java 2 security model, a security policy should
// be specified for the ActivationGroup VM. The first argument
// to the Properties put method, inherited from Hashtable, is
// the key and the second is the value
//
Properties props = new Properties();
props.put("java.security.policy",
   "/home/rmi_tutorial/activation/policy");

ActivationGroupDesc.CommandEnvironment ace = null;
ActivationGroupDesc exampleGroup = new ActivationGroupDesc(props, ace);

// Once the ActivationGroupDesc has been created, register it
// with the activation system to obtain its ID
//
ActivationGroupID agi =
   ActivationGroup.getSystem().registerGroup(exampleGroup);

Step 4:
Create an ActivationDesc instance

In the setup application, the job of the activation descriptor is to provide all the information that rmid will require to create a new instance of the implementation class.

Note: In order to run this code on your system, you'll need to change the file URL location to be the location of the directory on your system, where you've installed the example source code.

// Don't forget the trailing slash at the end of the URL
// or your classes won't be found
//
String location = "file:/home/rmi_tutorial/activation/";

// Pass the file that we want to persist to as the Marshalled
// object
MarshalledObject data =  new MarshalledObject (new File(
    "/home/rmi_tutorial/activation/persistentObjectStore.ser"));

// The location argument to the ActivationDesc constructor will be used
// to uniquely identify this class; it's location is relative to the
// URL-formatted String, location.
//
ActivationDesc desc = new ActivationDesc
    (agi, "examples.activation.ActivatableImplementation",
      location, data);

Step 5:
Declare an instance of your remote interface and register the activation descriptor with rmid

YetAnotherRemoteInterface yari =
    (YetAnotherRemoteInterface)Activatable.register(desc);
System.out.println("Got the stub for MyPersistentClass");

Step 6:
Bind the stub, that was returned by the Activatable.register method, to a name in the rmiregistry

Naming.rebind("MyPersistentClass", yari);
System.out.println("Exported MyPersistentClass");

Step 7:
Quit the setup application

System.exit(0);

Compile and run the code

There are six steps to compile and run the code:

  1. Compile the remote interface, implementation, client and setup classes
  2. Run rmic on the implementation class
  3. Start the rmiregistry
  4. Start the activation daemon, rmid
  5. Run the setup program
  6. Run the client

Step 1:
Compile the remote interface, implementation, client and setup classes

% javac -d . YetAnotherRemoteInterface.java
% javac -d . MyPersistentClass.java
% javac -d . Client4.java
% javac -d . Setup4.java

Step 2:
Run rmic on the implementation class

% rmic -d . examples.activation.MyPersistentClass

Step 3:
Start the rmiregistry

% rmiregistry &

Note: Before you start the rmiregistry, you must make sure that the shell or window in which you will run the registry, either has no CLASSPATH set or has a CLASSPATH that does not include the path to any classes that you want downloaded to your client, including the stubs for your remote object implementation classes.

If you start the rmiregistry, and it can find your stub classes in its CLASSPATH, it will ignore the server's java.rmi.server.codebase property, and as a result, your client(s) will not be able to download the stub code for your remote object.

Step 4:
Start the activation daemon, rmid

% rmid -J-Djava.security.policy=rmid.policy &
Where rmid.policy is the name of the security policy file for rmid.

Note: By default, rmid now requires a security policy file, that is used to verify whether or not the information in each ActivationGroupDescriptor is allowed to be used to launch a JVM for an activation group. For complete details, please refer to the rmid man page for the Solaris operating environment and the rmid man page for the Microsoft Windows platform.

Step 5:
Run the setup program

Run the setup, setting the codebase property to be the location of the implementation stubs. There are four things that need to go on the same command line:

  1. The "java" command
  2. A property name=value pair that specifies the location of the security policy file
  3. A property to specify where the stub code lives (no spaces from the "-D" all the way though the last "/")
  4. The fully-qualified package name of the setup program.
There should be one space just after the word "java", one between the two properties, and a third one just before the word "examples" (which is very hard to see when you view this as text, in a browser, or on paper).

% java  -Djava.security.policy=/home/rmi_tutorial/activation/policy  -Djava.rmi.server.codebase=file:/home/rmi_tutorial/activation/  examples.activation.Setup4

The codebase property will be resolved to a URL, so it must have the form of "http://aHost/somesource/" or "file:/myDirectory/location/" or, due to the requirements of some operating systems, "file:///myDirectory/location/" (three slashes after the "file:").

While a file: URL is sometimes easier to use for running example code, using the file: URL will mean that the only clients that will be able to access the server are those that can access the same files system as the server (either by virtue of running on the same machine as the server or by using a shared filesystem, such as NFS). If you wish to use an HTTP server, but don't have one available to you, please feel free to download our HTTP server.

Please note that each of these sample URL strings has a trailing "/". The trailing slash is a requirement for the URL set by the java.rmi.server.codebase property, so the implementation can resolve (find) your class definition(s) properly. For more information on setting the java.rmi.server.codebase property from the command line, please take a look at our tutorial on dynamic code downloading using the java.rmi.server.codebase property.

If you forget the trailing slash on the property, or if the class files can't be located at the source (they aren't really being made available for download) or if you misspell the property name, you'll get thrown a java.lang.ClassNotFoundException. This exception will be thrown when you try to bind your remote object to the rmiregistry, or when the first client attempts to access that object's stub. If the latter case occurs, you have another problem as well because the rmiregistry was finding the stubs in its CLASSPATH.

The server output should look like this:

     Got the stub for MyPersistentClass
     Exported MyPersistentClass
Step 6:
Run the client

The argument to the client program is the hostname of the implementation server, in this case, "vector".

% java -Djava.security.policy=/home/rmi_tutorial/activation/policy
examples.activation.Client4 vector

The first time that the client is run against this implementation, the output should look like this:

    Got a remote reference to the class MyPersistentClass
        Called the remote method
    Result:
    Initializing transaction vector
    Deposited money
    Withdrew money
    Transferred money from Savings
    Check cleared
    Point-of-sale charge at grocery store
The second time that the client is run against this implementation, the output will include five additional "transactions", so it should look like this:
        Got a remote reference to the class MyPersistentClass
    Called the remote method
    Result:
    Initializing transaction vector
    Deposited money
    Withdrew money
    Transferred money from Savings
    Check cleared
    Point-of-sale charge at grocery store
    Deposited money
    Withdrew money
    Transferred money from Savings
    Check cleared
    Point-of-sale charge at grocery store
Additionally, you should see the size of the persistentObjectStore.ser file increase, with each subsequent client call.

*As used on this web site, the terms "Java virtual machine" or "JVM" mean a virtual machine for the Java platform.

Copyright © 2003 Sun Microsystems, Inc. All Rights Reserved.
Please send comments to: rmi-comments@java.sun.com 		Sun


Stock Watcher

Here is the example StockApplet:


Stock Example Using RMI

 Documentation Comments

This directory contains an example that illustrates an applet that exports a remote object in order to receive stock updates from a stock server. The applet displays the stock data dynamically as notifications are received from the server. The interfaces and classes for this example are:

  • StockWatch is the remote interface for stock server.

  • StockNotify is the remote interface for stock observer.

  • Stock is the serializable object containing stock data.

  • StockServer (implements StockWatch) sends notifications of stock updates to remote objects that have registered to receive updates.

  • StockApplet (implements StockNotify) exports a remote object (itself), registers with StockServer for stock updates, and displays stock notifications as they are received.

On Windows systems, after downloading the JavaTM 2 SDK, execute run.bat in the docs/guide/rmi/examples/stock directory, which will explain each step as it builds and runs the example. Upon completion, you will need to explicitly destroy the window created for the server process.

On Solaris, after downloading the Java 2 SDK, execute the run script in this examples/stock directory, and the script will print out what it is doing while it runs the example. It assumes that you have installed the JavaTM 2 SDK and set your PATH, CLASSPATH and LD_LIBRARY_PATH according to the SDK installation instructions. The stock server creates its own RMI registry, so the "rmiregistry" command does not need to be run. Here are the basic steps that the run script executes:

    setenv CLASSPATH ../..:$CLASSPATH

    javac -d ../.. *.java

    rmic -d ../.. examples.stock.StockServer examples.stock.StockApplet

    java -Djava.security.policy=security.policy examples.stock.StockServer &

    appletviewer index.html

Note: You can set your CLASSPATH back to the old CLASSPATH (without ../.. in it) before running the appletviewer, so that classes get downloaded from the network rather than from your CLASSPATH; each of the scripts actually does this.

Sun Copyright © 1996-2003 Sun Microsystems, Inc., 2550 Garcia Ave., Mtn. View, CA 94043-1100 USA. All rights reserved.


    Using a Custom RMI Socket Factory

 Documentation Comments

This tutorial shows you the steps to follow to implement and use a custom RMI socket factory. A custom RMI socket factory is useful if (1) your RMI client and server need to use sockets that encrypt or compress data, and/or (2) your application requires different socket types for different remote objects.

Prior to the JavaTM 2 SDK, v1.2 release, it was possible to create and install a custom java.rmi.server.RMISocketFactory subclass used globally for all connections created by the RMI transport. It was not possible, however, to associate a different RMI socket factory on a per-object basis. For example in JDKTM v1.1.x, an RMI socket factory could not produce SSL sockets for one object and use the Java Remote Method Protocol (JRMP) directly over TCP for a different object in the same virtual machine. Also before 1.2, it was necessary to spawn an instance of the rmiregistry that used only your custom socket protocol.

As of the Java 2 SDK, v1.2 release, an RMI application can use a custom RMI socket factory on a per-object basis, download a client-side socket factory, and continue to use the default rmiregistry.

This tutorial has three parts:

  • Implementing a Custom RMI Socket Factory.
  • Using a Custom RMI Socket Factory in an Application.
  • Compiling and Running the Application.

The source code for this tutorial is available in the following formats:

  • sockets.zip
  • sockets.tar
  • sockets.tar.Z
Many people are interested in secure communication between RMI clients and servers. For more information see Using RMI with SSL.

Implementing a Custom RMI Socket Factory

There are three steps to implementing a custom RMI socket factory:
  1. Implement a custom ServerSocket and Socket.
  2. Implement a custom RMIClientSocketFactory.
  3. Implement a custom RMIServerSocketFactory.

Step 1:
Implement a custom ServerSocket and Socket

The type of socket to use is an application-specific decision. If your server sends or receives sensitive data, you might want a socket that encrypts the data.

For this example, the custom RMI socket factory will create sockets that perform simple XOR encryption. This type of encryption will protect data from a casual snooper sniffing packets on the wire, but is easily decoded by a knowledgeable cryptanalyst.

The custom XOR socket implementation includes the following sources. XOR sockets use special input and output stream implementations to handle xor-ing the data written to or read from the socket.

  • XorInputStream.java
  • XorOutputStream.java
  • XorServerSocket.java
  • XorSocket.java

Step 2:
Implement a custom RMIClientSocketFactory

The client-side RMI socket factory, XorClientSocketFactory, implements the java.rmi.server.RMIClientSocketFactory interface. The client socket factory needs to implement the createSocket method to return the approriate client socket instance, an XorSocket.

The client socket factory must implement the java.io.Serializable interface so that instances can be serialized to clients. It is also important to implement the equals and hashCode methods so that the RMI implementation will reuse the socket factory's connections to remote objects using equivalent factories.

package examples.rmisocfac;

import java.io.*;
import java.net.*;
import java.rmi.server.*;

public class XorClientSocketFactory
    implements RMIClientSocketFactory, Serializable {

    private byte pattern;

    public XorClientSocketFactory(byte pattern) {
    this.pattern = pattern;
    }

    public Socket createSocket(String host, int port)
    throws IOException
    {
    return new XorSocket(host, port, pattern);
    }

    public int hashCode() {
    return (int) pattern;
    }

    public boolean equals(Object obj) {
    return (getClass() == obj.getClass() &&
        pattern == ((XorClientSocketFactory) obj).pattern);
    }
}

Step 3:
Implement a custom RMIServerSocketFactory

The server-side RMI socket factory, XorServerSocketFactory, implements the java.rmi.server.RMIServerSocketFactory interface. The server socket factory needs to implement the createServerSocket method to return the appropriate server socket instance, an XorServerSocket.

The server socket factory does not need to implement the Serializable interface because server socket factory instances are not serialized to clients. The factory should implement the equals and hashcode methods so that the RMI implementation will reuse the socket factory's accept connection for equivalent factories.

package examples.rmisocfac;

import java.io.*;
import java.net.*;
import java.rmi.server.*;

public class XorServerSocketFactory
    implements RMIServerSocketFactory {

    private byte pattern;

    public XorServerSocketFactory(byte pattern) {
    this.pattern = pattern;
    }

    public ServerSocket createServerSocket(int port)
    throws IOException
    {
    return new XorServerSocket(port, pattern);
    }

    public int hashCode() {
    return (int) pattern;
    }

    public boolean equals(Object obj) {
    return (getClass() == obj.getClass() &&
        pattern == ((XorServerSocketFactory) obj).pattern);
    }

}

Using a Custom Socket Factory in an Application

There are only two more steps to complete when using a custom RMI socket factory for a remote object:
  1. Write a server application that creates a remote object and exports it to use your custom RMIClientSocketFactory and RMIServerSocketFactory. Store a reference to the remote object's stub in an RMI registry so that clients can look it up.

  2. Write a client application that looks up the stub for the remote object and invokes a remote method. The custom socket factories do not need to be referenced in the client application. The client-side RMI socket factory will be downloaded to the client when the client looks up the stub for the remote object.

Step 1:
Write a server application

If communication with a remote object requires the use of custom sockets, you need to inform the RMI runtime which custom socket factories to use when you export the remote object. When your application exports the object specifying custom socket factories, the RMI runtime will use the corresponding custom RMIServerSocketFactory to create a server socket to accept incoming calls to the remote object. Also, the RMI runtime will create a stub that refers to the corresponding custom RMIClientSocketFactory. This client socket factory will be used to create connections upon initating a remote invocation to the remote object using the stub.

This example is similar to the example in the tutorial Getting Started Using RMI, but uses custom socket factories instead of the default sockets used by the RMI implementation.

The application uses the following Hello remote interface:

package examples.rmisocfac;

public interface Hello extends java.rmi.Remote {
    String sayHello() throws java.rmi.RemoteException;
}
The server application creates a remote object implementing the Hello remote interface and exports the object to use custom socket factories using the java.rmi.server.UnicastRemoteObject.exportObject method that takes the custom socket factories as arguments. Next, it creates a local registry and, in that registry, it binds a reference to the remote object's stub with the name "Hello".
package examples.rmisocfac;

import java.io.*;
import java.rmi.*;
import java.rmi.server.*;
import java.rmi.registry.*;

public class HelloImpl implements Hello {

    public HelloImpl() {}

    public String sayHello() {
        return  "Hello World!";
    }

    public static void main(String args[]) {

    if (System.getSecurityManager() == null) {
        System.setSecurityManager(new SecurityManager());
    }

        byte pattern = (byte) 0xAC;
    try {
        /*
         * Create remote object and export it to use
         * custom socket factories.
         */
        HelloImpl obj = new HelloImpl();
        RMIClientSocketFactory csf = new XorClientSocketFactory(pattern);
        RMIServerSocketFactory ssf = new XorServerSocketFactory(pattern);
        Hello stub =
        (Hello) UnicastRemoteObject.exportObject(obj, 0, csf, ssf);

        /*
         * Create a registry and bind stub in registry.
         *
        LocateRegistry.createRegistry(2002);
        Registry registry = LocateRegistry.getRegistry(2002);
        registry.rebind("Hello", stub);
        System.out.println("HelloImpl bound in registry");

    } catch (Exception e) {
        System.out.println("HelloImpl exception: " + e.getMessage());
        e.printStackTrace();
    }
    }
}

Step 2:
Write a client application

The client application obtains a reference to the registry used by the server application. It then looks up the remote object's stub and invokes its remote method sayHello:

package examples.rmisocfac;

import java.rmi.*;
import java.rmi.registry.*;

public class HelloClient {

    public static void main(String args[]) {

    if (System.getSecurityManager() == null) {
        System.setSecurityManager(new SecurityManager());
    }

        try {
        Registry registry = LocateRegistry.getRegistry(2002);
            Hello obj = (Hello) registry.lookup("Hello");
            String message = obj.sayHello();
            System.out.println(message);

        } catch (Exception e) {
        System.out.println("HelloClient exception: " +
                               e.getMessage());
            e.printStackTrace();
        }
    }

}

Compiling and Running the Application

There are four steps to compile and run the application:

  1. Compile the remote interface, client, and server classes
  2. Run rmic on the implementation class
  3. Start the server
  4. Run the client

Step 1:
Compile the remote interface, client, and server classes

javac -d . Hello.java
javac -d . HelloClient.java
javac -d . HelloImpl.java
javac -d . XorClientSocketFactory.java
javac -d . XorInputStream.java
javac -d . XorOutputStream.java
javac -d . XorServerSocket.java
javac -d . XorServerSocketFactory.java
javac -d . XorSocket.java

Step 2:
Run rmic on the implementation class

rmic -d . examples.rmisocfac.HelloImpl

Step 3:
Start the server

java -Djava.security.policy=policy examples.rmisocfac.HelloImpl

The server output should look like this:

      HelloImpl bound in registry

Step 4:
Run the client

In another window start the client application making sure that the application classes are in the class path:

java -Djava.security.policy=policy examples.rmisocfac.HelloClient

The client output should look like this:

      Hello World!

Note: Both the server and client applications use a security policy file that grants permissions only to files in the local class path (the current directory). The server application needs permission to accept connections, and both the server and client applications need permission to make connections. The permission java.net.SocketPermission is granted to the specified codebase URL, a "file:" URL relative to the current directory. This permission grants the ability to both accept connections from and make connections to any host on unprivileged ports (that is ports >= 1024).

grant codeBase "file:." {

    permission java.net.SocketPermission "*:1024-", "connect,accept";
};

Copyright © 2003 Sun Microsystems, Inc. All Rights Reserved.
Please send comments to: rmi-comments@java.sun.com 		Sun


Using RMI with SSL

Many have asked how an RMI application can make remote invocations over secure SSL connections. Below are some questions and answers about using RMI with SSL.

Q1: Is it possible to use RMI with SSL?

A1: Yes, it is possible, due to RMI enhancements available in the JavaTM 2 SDK, Standard Edition, v1.2 (Java 2 SDK).

Q2: How do I use RMI with SSL?

A2: The version of RMI included in the Java 2 SDK enables the RMI developer to use custom socket factories for RMI-based communication. An application can export a remote object to use an RMI socket factory that creates sockets of the desired type (for example, SSL sockets). Using this technique, an RMI application can use SSL socket communication instead of the default socket communication. For further details on using custom socket factories, see the tutorial: Using a Custom RMI Socket Factory.

Q3: Where can I find a pure Java programming language implementation of SSL?

A3: Java 2 SDK, v1.4 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.

Q4: Where can I find an example using RMI with SSL?

A4: There is an RMI/SSL example bundled with the JSSE code examples. The RMI example illustrates how to use SSL-based connections for RMI calls to a remote object. This is achieved by exporting a remote object to use a custom RMI socket factory that creates SSL sockets.

Copyright © 2003 Sun Microsystems, Inc. All Rights Reserved.
Please send comments to: rmi-comments@java.sun.com 		Sun


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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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 or a default group cannot be created, an ActivationException is thrown. If the groupID is null, an IllegalArgumentException is thrown.

Note - As a side-effect of creating an ActivationDesc, if an ActivationGroup for this JVM is not currently active, a default one is created. The default activation group uses the java.lang.SecurityManager as a security manager and upon reactivation will set the properties in the activated group's JVM to be the current set of properties in the JVM. If your application needs to use a different security manager, it must set the group for the JVM before creating a default ActivationDesc. See the method ActivationGroup.createGroup for details on how to create an ActivationGroup for the JVM.
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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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:

    1. 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.
    2. 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 exception being thrown, such as a java.net.ConnectException, an HTTP connection will not be attempted.
  • 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

There is no special configuration necessary to enable the client to send RMI calls through a firewall.

The client can, however, 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.

      2. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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

    Any remote exception that occurs while the server is executing a remote method. 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 are propagated to clients in tact.

    CONTENTS | PREV | NEXT
    Copyright © 1997-2003 Sun Microsystems, Inc. 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.

java.rmi.MarshalException

Protocol error marshaling return.

java.rmi.RemoteException

Method number out of range due to corrupted stream.

CONTENTS | PREV | NEXT
Copyright © 1997-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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 2 platform.

CONTENTS | PREV | NEXT
Copyright © 1997-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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 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-2003 Sun Microsystems, Inc. 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 platform's distributed object model is similar to the Java 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 platform's distributed object model differs from the Java 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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 (see section 2.3 of the JLS).
  • 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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.

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 © 1997-2003 Sun Microsystems, Inc. All Rights Reserved.

size (bytes)

name

description

1

opcode

operation code (OPEN)

2

ID

connection identifier

4

count

number of bytes in transmission

count

data

transmission data


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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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 2 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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 Environment:
http://java.sun.com/products/j2se/1.4/docs/tooldocs/solaris/rmic.html
  • For the Microsoft Windows platform:
http://java.sun.com/products/j2se/1.4/docs/tooldocs/windows/rmic.html

CONTENTS | PREV | NEXT
Copyright © 1997-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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 first invoke 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 section 4.3.3 of The Java Virtual Machine Specification 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 hash value is assembled from the first two 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;
Note - The newCall, invoke, and done methods 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. Passing the operation array and index allows the stubs generator to assign the operation indexes and interpret them. The remote reference may need the operation description to encode in the call.

The method invoke 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. 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-2003 Sun Microsystems, Inc. All Rights Reserved.


Java Remote Method Invocation: Contents

JavaTM Remote Method Invocation Specification

JavaTM Remote Method Invocation (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 platform.
Revision 1.9, JavaTM 2 SDK, Standard Edition, v1.4.2

CONTENTS | NEXT
Copyright © 1997-2003 Sun Microsystems, Inc. All Rights Reserved.


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-2003 Sun Microsystems, Inc. All Rights Reserved.


Java(TM) RMI over IIOP Documentation

JavaTM RMI over IIOP
Technology
Documentation Home Page

JavaTM Remote Method Invocation over Internet Inter-ORB Protocol technology ("RMI-IIOP") is part of the JavaTM 2 Platform, Standard Edition (J2SETM). The RMI Programming Model enables the programming of CORBA servers and applications via the rmi API. You can choose to work completely within the Java programming language using the Java Remote Method Protocol (JRMP) as the transport, or work with other CORBA-compliant programming languages using the Internet InterORB Protocol (IIOP).

RMI-IIOP utilizes the Java CORBA Object Request Broker (ORB) and IIOP, so you can write all of your code in the Java programming language, and use the rmic compiler to generate the code necessary for connecting your applications via the Internet InterORB Protocol (IIOP) to others written in any CORBA-compliant language. To work with CORBA applications in other languages, IDL can be generated from Java programming language interfaces using the rmic compiler with the -idl option. To generate IIOP stubs and tie classes, use the rmic compiler with the -iiop option. For more information on using rmic, link to rmic - The Java RMI Compiler.

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.

New Java RMI-IIOP Features in J2SE 1.4

    • New command line argument for rmic tool allows programmers to construct object implementations using the Portable Object Adapter (POA) that are portable between different ORB products.

      When the command rmic -iiop -poa is run on a Java program that defines a remote object implementation of a remote interface, the inheritance changes from org.omg.CORBA_2_3.portable.ObjectImpl (if command is run without the -poa option) to org.omg.PortableServer.Servant .

      In the Java programming language, Portable Object Adaptor (POA)-based Dynamic Skeleton Interface (DSI) servants inherit from the standard DynamicImplementation class, which inherits from the Servant class. The native Servant type is defined by the PortableServer module for the POA. In the Java programming language, the Servant type is mapped to the 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. For more information on the POA, see the CORBA/IIOP 2.3.1 Specification, Chapter 11, formal/99-10-07.

    • New Object Request Broker Daemon, orbd. The orbd tool is a daemon process containing a Bootstrap Service, a Transient Name Service, a Persistent Name Service, and a Server Manager. For more information on the orbd tool, see the orbd manpage and Naming Service.

    • Other new CORBA features include support for Portable Interceptors, an Interoperable Naming Service, the General Inter-ORB Protocol (GIOP) 1.2, Dynamic Anys, and the new Server Tool. For more information about these features, which are shared with the Java IDL technology, see Changes in CORBA Features Between J2SE 1.3 and 1.4.

Java RMI over IIOP Tutorials

    • Getting Started Using Java RMI over IIOP
    • Tutorial: RMI over IIOP with POA server-side model

Java RMI-IIOP Developer Documentation

    • Java RMI-IIOP Programmer's Guide
    • Enterprise JavaBeans Components and CORBA Clients (click here for pdf version)
    • Using Portable Interceptors - updated 4/2002

Java RMI-IIOP Tools Documentation

    • IDL-to-Java Compiler (idlj) man page
    • RMI Compiler (rmic) man page Solaris / Windows
    • Object Request Broker Daemon (ordb) man page
    • Server Tool man page

RMI-IIOP Javadoc API Reference

    • package org.omg.CORBA
    • package org.omg.PortableServer
    • package org.omg.CosNaming
    • package javax.rmi.CORBA
    • package javax.rmi (with link to class PortableRemoteObject)

For more information

The Java IDL technology pages include a lot of information that is useful to developers using Java RMI-IIOP technology.

The OMG is the official source of information for all CORBA and IIOP related information. The CORBA 2.3.1 Specification is available electronically from formal/99-10-07. The URLs for the CORBA specifications may change. If this link is broken, link to http://www.omg.org and search the specifications.

For more information on which specifications are implemented in this release of the Java platform, see the compliance document.

For questions, please try the user supported forum for RMI-IIOP technology, which is available at http://forum.java.sun.com. For general questions on the RMI-IIOP technology, please send email to rmi-iiop@sun.com. For comments on the tutorials, or to report errors in the tutorials, please send email to corba-tutorial@sun.com.

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Send questions or comments to: rmi-iiop@sun.com.

Sun


Enterprise JavaBeans[tm] Components and CORBA Clients: A Developer Guide

To get this document in PDF format, click here.

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.

    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.

  1. Create the files Logger.java , LoggerHome.java , LoggerEJB.java , and LogMessage.java in the /Java/src/ejbinterop directory.

    2. 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();
    }
}

  2. 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.

  3. 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 http://java.sun.com/j2se/1.4.2/docs/guide/idl/jidlExceptions.html.

  4. 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 a new feature in the J2EE v 1.3 platform as 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 http://java.sun.com/j2se/1.4.2/docs/guide/idl/jidlNaming.html#INS.

    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.

  5. 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;
}
  6. 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

  7. 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:
      2. 	$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

  8. 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

  9. Stop the J2EE server. To stop the server, enter this command in a terminal window or command prompt.
    10. $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:
    2. 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:

  • IONA - EJB-CORBA and CORBA-EJB Interoperability at http://www.iona.com/whitepapers/CORBA-EJBInteropWPV02-00.pdf.
  • BEA - EJB-to-CORBA/Java Simpapp Sample Application at http://edocs.bea.com/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 © 2002 Sun Microsystems, Inc., 901 San Antonio Road, Palo Alto, California 94303, U.S.A. All rights reserved.

Sun Microsystems, Inc. has intellectual property rights relating to technology embodied in this product. In particular, and without limitation, these intellectual property rights may include one or more of the U.S. patents listed at http://www.sun.com/patents and one or more additional patents or pending patent applications in the U.S. and other countries.

This product is distributed under licenses restricting its use, copying distribution, and decompilation. No part of this product may be reproduced in any form by any means without prior written authorization of Sun and its licensors, if any.

Third-party software, including font technology, is copyrighted and licensed from Sun suppliers.

Sun, Sun Microsystems, the Sun logo, Java, Enterprise JavaBeans, EJB, J2EE and J2SE are trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S. and other countries.

UNIX is a registered trademark in the United States and other countries, exclusively licensed through X/Open Company, Ltd.


RMI-IIOP Programmer's Guide

 RMI-IIOP Documentation

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), v.1.4 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 , 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 J2SE 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:
      2.          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:
      3.          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:
      4.         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.

    3. 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:
    7.      _<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:
    9.      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:
    10.      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 J2SE v.1.4, see the compliance document.

RMI-IIOP Home

Send your comments to rmi-iiop@sun.com.


Getting Started Using RMI-IIOP: POA Model

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 JavaTM 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.

Another option for creating distributed applications is JavaTM 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 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 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/helloWorld. 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.

If you are interested in why java.rmi.RemoteException is a checked exception rather than runtime exception, please refer to the archives of the rmi-users email list:

http://java.sun.com/products/jdk/rmi/archives/3490.html

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. 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 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 ;
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
      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 is new 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 on your display:
Client: Obtained a ref. to Hello server.
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.
Copyright © 2001 Sun Microsystems, Inc. All Rights Reserved.
Please send questions or comments to: rmi-iiop@sun.com 		Sun


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.

NEW in 1.4! 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 older version 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 older version of the IDL to Java language mapping in versions of J2SE before 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 NT it is a semicolon, on Solaris it is a colon, etc. For more information on includes, read the CLASSPATH (Solaris) or CLASSPATH (Windows) documentation.

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
emit 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 old (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 Null Ptr Exception in the ServerDelegate DSI code.

Copyright © 2001 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software


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 JavaTM 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:

  • JavaTM 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.

  • JavaTM 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 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 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/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.

If you are interested in why java.rmi.RemoteException is a checked exception rather than runtime exception, please refer to the archives of the rmi-users email list:

http://java.sun.com/products/jdk/rmi/archives/3490.html

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:
    Client: Obtained a ref. to Hello server.
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.

    RMI-IIOP Documentation Home

    Send questions or comments to: rmi-iiop@sun.com


X.509 certificates

X.509 Certificates and Certificate Revocation Lists (CRLs)

Last Modified: 1 May, 2001

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 Netscape Navigator and Microsoft Internet Explorer) that support the SSL protocol. SSL (Secure Socket Layer) 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 SSL.

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 are supporting its X.509 Certificate and CRL Profile, which is being specified.

    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 and certificate revocation list (CRL) 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.

    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 v1 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 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.

    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 v1 certificates. For examples, see the "EXAMPLES" section of the keytool documentation ( for Solaris ) ( for Windows ).

    Copyright © 1995-2001 Sun Microsystems, Inc. All Rights Reserved. Please send comments to: java-security@sun.com

            Sun
    Java Software Division


Java Cryptography Architecture

JavaTM Cryptography Architecture

API Specification & Reference

Last Modified: 4 August 2002

Introduction
Design Principles
Architecture
Concepts
Core Classes and Interfaces
The Provider Class
How Provider Implementations are Requested and Supplied
Installing Providers
The Security Class
The MessageDigest Class
The Signature Class
Algorithm Parameters Classes
    Algorithm Parameter Specification Interfaces and Classes
    The AlgorithmParameterSpec Interface
    The DSAParameterSpec Class
    The AlgorithmParameters Class
    The AlgorithmParameterGenerator Class
    Key Interfaces
    Key Specification Interfaces and Classes
    The KeySpec Interface
    The DSAPrivateKeySpec Class
    The DSAPublicKeySpec Class
    The RSAPrivateKeySpec Class
    The RSAPrivateCrtKeySpec Class
    The RSAMultiPrimePrivateCrtKeySpec Class
    The RSAPublicKeySpec Class
    The EncodedKeySpec Class
    The PKCS8EncodedKeySpec Class
    The X509EncodedKeySpec Class
    The KeyFactory Class
    The CertificateFactory Class
    The KeyPair Class
    The KeyPairGenerator Class
    Key Management
    Keystore Location
    Keystore Implementation
    The KeyStore Class
    The SecureRandom Class
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
Appendix A: Standard Names

Appendix B: Algorithms

Introduction

The Security API is a core API of the Java programming language, built around the java.security package (and its subpackages). This API is designed to allow developers to incorporate both low-level and high-level security functionality into their programs.

The first release of Security API in JDK 1.1 introduced the "Java Cryptography Architecture" (JCA), a framework for accessing and developing cryptographic functionality for the Java platform. In JDK 1.1, the JCA included APIs for digital signatures and message digests.

In subsequent releases, the Java 2 SDK significantly extended the Java Cryptography Architecture, as described in this document. It also upgraded the certificate management infrastructure to support X.509 v3 certificates, and introduced a new Java Security Architecture for fine-grain, highly configurable, flexible, and extensible access control.

The Java Cryptography Architecture encompasses the parts of the Java 2 SDK Security API related to cryptography, as well as a set of conventions and specifications provided in this document. It includes a "provider" architecture that allows for multiple and interoperable cryptography implementations.

The Java Cryptography Extension (JCE) extends the JCA API to include APIs for encryption, key exchange, and Message Authentication Code (MAC). Together, the JCE and the cryptography aspects of the SDK provide a complete, platform-independent cryptography API. JCE was previously an optional package (extension) to the Java 2 SDK, Standard Edition, versions 1.2.x and 1.3.x. JCE has now been integrated into the Java 2 SDK, v 1.4.

This document is both a high-level description and a specification of the Java Cryptography Architecture API and its default provider, as shipped in the Java 2 SDK. A separate document describing the JCE API is provided with the JCE release. See the "Java Security Architecture Specification" for information about the Java Security Architecture aspects of the Security API.

Note: The most recent version of this JCA specification can be found online at: http://java.sun.com/j2se/1.4.2/docs/guide/security/CryptoSpec.html.

Design Principles

The Java Cryptography Architecture (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. When 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, and KeyPairGenerator classes.

Implementation independence is achieved using a "provider"-based architecture. The term Cryptographic Service Provider (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

The Java Cryptography Architecture introduced the notion of a Cryptographic Service Provider (used interchangeably with "provider" in this document). This term refers to a package (or a set of packages) that supplies a concrete implementation of a subset of the cryptography aspects of the Security API.

For example, in JDK 1.1 a provider could contain an implementation of one or more digital signature algorithms, message digest algorithms, and key generation algorithms. Java 2 SDK adds five additional types of services: key factories, keystore creation and management, algorithm parameter management, algorithm parameter generation, and certificate factories. It also enables a provider to supply a random number generation (RNG) algorithm. Previously, RNGs were not provider-based; a particular algorithm was hard-coded in the JDK.

As previously noted, a program may simply request a particular type of object (such as a Signature object) for a particular service (such as the DSA signature algorithm) and get 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.)

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. The SUN provider package includes:

  • An implementation of the Digital Signature Algorithm (DSA), described in NIST FIPS 186.

  • An implementation of the MD5 (RFC 1321) and SHA-1 (NIST FIPS 180-1) message digest algorithms.

  • A DSA key pair generator for generating a pair of public and private keys suitable for the DSA algorithm.

  • A DSA algorithm parameter generator.

  • A DSA algorithm parameter manager.

  • A DSA key factory providing bi-directional conversions between (opaque) DSA private and public key objects and their underlying key material.

  • An implementation of the proprietary "SHA1PRNG" pseudo-random number generation algorithm, following the recommendations in the IEEE P1363 standard (Appendix G.7).

  • A certificate path builder and validator for PKIX, as defined in the Internet X.509 Public Key Infrastructure Certificate and CRL Profile (available as a draft from Internet Engineering Task Force at the time of this writing.).

  • A certificate store implementation for retrieving certificates and CRLs from Collection and LDAP directories, using the PKIX LDAP V2 Schema (RFC 2587).

  • A certificate factory for X.509 certificates and Certificate Revocation Lists (CRLs).

  • A keystore implementation for the proprietary keystore type named JKS.

Each SDK installation has one or more provider packages installed. New providers may be added statically or dynamically (see the Provider and Security classes). The Java Cryptography Architecture offers a set of APIs that allow users to query which providers are installed and what services they support.

Clients may configure their runtime 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 services when no specific provider is requested.

Key Management

A database called a "keystore" can be used to manage a repository of keys and certificates. A keystore is available to applications that need it for authentication 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".

Applications can choose different types of keystore implementations from different providers, using the getInstance factory method supplied in the KeyStore class.

See the Key Management section for more information.

Concepts

This section covers the major concepts introduced in the API.

Engine Classes and Algorithms

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, and it either provides cryptographic operations (like those for digital signatures or message digests), 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, two of the engine classes are the Signature and KeyFactory classes. The Signature class provides access to the functionality of a digital signature algorithm. A DSA KeyFactory 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 Java Cryptography Architecture encompasses the classes of the Java 2 SDK Security package related to cryptography, including the engine classes. Users of the API request and use instances of the engine classes to carry out corresponding operations. The following engine classes are defined in Java 2 SDK:

  • 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.

  • CertificateFactory: used to create public key certificates and Certificate Revocation Lists (CRLs).

  • 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.

  • 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.
In the 1.4 release of the Java 2 SDK, the following new engines were added:
  • 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).
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. The Signature engine class, for example, provides access to the functionality of a digital signature algorithm. The actual implementation supplied in a SignatureSpi subclass would be that for a specific kind of signature algorithm, such as SHA-1 with DSA, SHA-1 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 SPI methods that cryptographic service providers must implement.

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, 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 the Key Specification Interfaces and Classes section.) The KeyFactorySpi subclass supplies an actual implementation for a specific type of keys, for example, DSA public and private keys.

Implementations and Providers

Implementations for various cryptographic services are provided by JCA Cryptographic Service Providers. Cryptographic service providers are essentially packages that supply one or more cryptographic service implementations. The Engine Classes and Algorithms section includes a list of implemenations supplied by SUN, the Java 2 SDK's default provider.

Other providers may define their own implementations of these services or of other services, such as one of the RSA-based signature algorithms or the MD2 message digest algorithm.

Factory Methods to Obtain Implementation Instances

For each engine class in the API, a particular implementation is requested and instantiated by calling a factory method on the engine class. A factory method is a static method that returns an instance of a class.

The basic mechanism for obtaining an appropriate Signature object, for example, is as follows: A user requests such an object by calling the getInstance method in the Signature class, specifying the name of a signature algorithm (such as "SHA1withDSA"), and, optionally, the name of the provider or the Provider class. The getInstance method finds an implementation that satisfies the supplied algorithm and provider parameters. If no provider is specified, getInstance searches the registered providers, in preference order, for one with an implementation of the specified algorithm. See The Provider Class for more information about registering providers.

Core Classes and Interfaces

This section discusses the core classes and interfaces provided in the Java Cryptography Architecture:

  • the Provider and Security classes

  • the MessageDigest, Signature, KeyPairGenerator, KeyFactory, AlgorithmParameters, AlgorithmParameterGenerator, CertificateFactory, KeyStore, SecureRandom, CertPathBuilder, CertPathValidator, and CertStore.
engine classes

  • the Key interfaces and classes

  • the Algorithm Parameter Specification Interfaces and Classes and the Key Specification Interfaces and Classes

    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:

    • java.security package summary
    • java.security.spec package summary
    • java.security.interfaces package summary
    • java.security.cert package summary

    • 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 Java 2 SDK 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 Java 2 SDK 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 Java 2 SDK 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.

    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 Java Cryptography Architecture (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 particular implementation is requested and instantiated by calling a getInstance method 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.

    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.

    Installing Providers

    There are two parts to installing a provider: installing the provider package classes, and configuring the provider.

    Installing the Provider Classes

    There are two possible ways to install the provider classes:

    1. Place a zip or JAR file containing the classes anywhere in your classpath.

    2. Supply your provider JAR file as an "installed" or "bundled" extension. For more information on how to deploy an extension, see How is an extension deployed?.

    Configuring the Provider

    The next step is to add the provider to your list of approved providers. This step can be done statically by editing the java.security file in the lib/security directory of the SDK; therefore, if the SDK is installed in a directory called j2sdk1.2, the file would be j2sdk1.2/lib/security/java.security. One of the types of properties you can set in java.security has 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 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.

    Suppose that the master class is COM.acme.provider.Acme, and that you would like to configure Acme as your third preferred provider. To do so, you would add the following line to the java.security file:

    security.provider.3=COM.acme.provider.Acme
    Providers may also be registered dynamically. To do so, call either the addProvider or insertProviderAt method in the Security class. This type of registration is not persistent and can only be done by "trusted" programs. See Security.

    Provider Class Methods

    Each Providerclass 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 permission for that particular action.

    For example, in the Policy reference implementation, the policy configuration file(s) for a SDK 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 applet originated from, but also a reference to the public key(s) corresponding to the private key(s) 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 only 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 codeBase is missing:

    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.

    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.

    Quering 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 accessible and settable by a trusted program via the following methods:

    static String getProperty(String key)
static void setProperty(String key, String datum)

    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. A digest has two properties:

    • It should be computationally infeasible to find two messages that hashed 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 the "digital fingerprints" of data.

    Creating a MessageDigest Object

    The first step for computing a digest is to create a message digest instance. As with all engine classes, the way to get a MessageDigest object for a particular type of message digest algorithm is to call the getInstance static factory method on the MessageDigest class:

    static MessageDigest getInstance(String algorithm)
    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")

    A caller may optionally specify the name of a provider or a Provider instance, which guarantees that the implementation of the algorithm requested is from the specified provider:

    static MessageDigest getInstance(String algorithm, String provider)
static MessageDigest getInstance(String algorithm, Provider provider)

    A call to getInstance 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. This is done 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 has been supplied by calls to update methods, 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 two methods return the computed digest. The latter 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.

    A call to the digest method that takes an input byte array argument is equivalent to making a call to

    void update(byte[] input)
    with the specified input, followed by a call to the digest method without any arguments.

    Please see the 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 RSA with MD5. 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:
    • 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.

    A Signature object can be used to sign data. 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. 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. As with all engine classes, the way to get a Signature object for a particular type of signature algorithm is to call the getInstance static factory method on the Signature class:
    static Signature getInstance(String algorithm)
    Note: The algorithm name is not case-sensitive.
    A caller may optionally specify the name of a provider or the Provider class, which will guarantee that the implementation of the algorithm requested is from the named provider:

    static Signature getInstance(String algorithm, String provider)
static Signature getInstance(String algorithm, Provider provider)

    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 Appendix B 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).

    Algorithm Parameters Classes

    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 a set of parameters 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 algorithm parameter specification interfaces and classes in the java.security.spec package are described in the following sections.

    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 interface) specifies the set of parameters used with the DSA algorithm. It has the following methods:
    BigInteger getP()
BigInteger getQ()
BigInteger getG()
    These methods return the DSA algorithm parameters: the prime p, the sub-prime q, and the base g.

    The AlgorithmParameters Class

    The AlgorithmParameters class is an engine class that provides an opaque representation of cryptographic parameters.

    An opaque representation is one 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 and some kind of encoding for the parameter set. This is in contrast to a transparent representation of parameters, in which you can access each value individually, through one of the get methods defined in the corresponding specification class. Note that you can call the AlgorithmParameters getParameterSpec method to convert an AlgorithmParameters object to a transparent specification (see the following section).

    Creating an AlgorithmParameters Object

    As with all engine classes, the way to get an AlgorithmParameters object for a particular type of algorithm is to call the getInstance static factory method on the AlgorithmParameters class:

    static AlgorithmParameters getInstance(String algorithm)
    Note: The algorithm name is not case-sensitive.
    A caller may optionally specify the name of a provider or the Provider class, which will guarantee that the algorithm parameter implementation requested is from the named provider:
    static AlgorithmParameters getInstance(String algorithm, String provider)
static AlgorithmParameters getInstance(String algorithm, Provider provider)

    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 parameters suitable for a certain algorithm (the algorithm specified when an AlgorithmParameterGenerator instance is created).

    Creating an AlgorithmParameterGenerator Object

    As with all engine classes, the way to get an AlgorithmParameterGenerator object for a particular type of algorithm is to call the getInstance static factory method on the AlgorithmParameterGenerator class:

    static AlgorithmParameterGenerator getInstance(
                                   String algorithm)
    Note: The algorithm name is not case-sensitive.

    A caller may optionally specify the name of a provider or the Provider class, which will guarantee that the algorithm parameter generator implementation is from the named provider:

    static AlgorithmParameterGenerator getInstance(
                                   String algorithm,
                                   String provider)

static AlgorithmParameterGenerator getInstance(
                                   String algorithm,
                                   Provider provider)

    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 Appendix B: Algorithms 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. (The Diffie-Hellman algorithm has been part of the JCE since JCE 1.2.)

    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()

    Key Interfaces

    The 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 DSA or RSA), which will work with those algorithms and with related algorithms (such as MD5 with RSA, SHA-1 with RSA, 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 PKCS #8), 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, 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 package:
    • DHPrivateKey
    • DHPublicKey
    • DSAPrivateKey
    • DSAPublicKey
    • PBEKey
    • PrivateKey
    • PublicKey
    • RSAMultiPrimePrivateCrtKey
    • RSAPrivateCrtKey
    • RSAPrivateKey
    • RSAPublicKey
    • SecretKey

    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.

    Key Specification Interfaces and Classes

    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, 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 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).

    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 DSAPrivateKeySpec Class

    This class (which implements the KeySpec interface) specifies a DSA private key with its associated parameters. DSAPrivateKeySpec has the following methods:
    BigInteger getX()
BigInteger getP()
BigInteger getQ()
BigInteger getG()
    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. DSAPublicKeySpec has the following methods:
    BigInteger getY()
BigInteger getP()
BigInteger getQ()
BigInteger getG()
    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. RSAPrivateKeySpec has the following methods:
    BigInteger getModulus()
BigInteger getPrivateExponent()
    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. RSAPrivateCrtKeySpec has the following methods (in addition to the methods inherited from its superclass RSAPrivateKeySpec):
    BigInteger getPublicExponent()
BigInteger getPrimeP()
BigInteger getPrimeQ()
BigInteger getPrimeExponentP()
BigInteger getPrimeExponentQ()
BigInteger getCrtCoefficient()
    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 RSAMultiPrimePrivateCrtKeySpec Class

    This class (which extends the RSAPrivateKeySpec class) specifies an RSA multi-prime private key, as defined in the PKCS#1 v2.1, using the Chinese Remainder Theorem (CRT) information values. RSAMultiPrimePrivateCrtKeySpec has the following methods (in addition to the methods inherited from its superclass RSAPrivateKeySpec):
    BigInteger getPublicExponent()
BigInteger getPrimeP()
BigInteger getPrimeQ()
BigInteger getPrimeExponentP()
BigInteger getPrimeExponentQ()
BigInteger getCrtCoefficient()
RSAOtherPrimeInfo[] getOtherPrimeInfo()
    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.

    Method getOtherPrimeInfo returns a copy of the otherPrimeInfo (defined in PKCS#1 v 2.1) or null if there are only two prime factors (p and q).

    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. RSAPublicKeySpec has the following methods:
    BigInteger getModulus()
BigInteger getPublicExponent()
    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. 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 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 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".

    The KeyFactory Class

    The KeyFactory class is an engine class designed to provide conversions between opaque cryptographic keys (of type Key) and key specifications (transparent representations of the underlying key material).

    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 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

    As with all engine classes, the way to get a KeyFactory object for a particular type of key algorithm is to call the getInstance static factory method on the KeyFactory class:

    static KeyFactory getInstance(String algorithm)
    Note: The algorithm name is not case-sensitive.
    A caller may optionally specify the name of a provider or the Provider class, which will guarantee that the implementation of the key factory requested is from the named provider.
    static KeyFactory getInstance(String algorithm, String provider)
static KeyFactory getInstance(String algorithm, Provider provider)

    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 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

    As with all engine classes, the way to get a CertificateFactory object for a particular certificate or CRL type is to call the getInstance static factory method on the CertificateFactory class:

    static CertificateFactory getInstance(String type)
    Note: The type name is not case-sensitive.
    A caller may optionally specify the name of a provider or the Provider class, which will guarantee that the implementation of the certificate factory requested is from the named provider.
    static CertificateFactory getInstance(String type, String provider)

static CertificateFactory getInstance(String type, Provider provider)

    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

    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.

    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()

    The KeyPairGenerator Class

    The KeyPairGenerator class is an engine class used to generate pairs of public and private keys.

    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. This generation is done using one of the factory methods on KeyPairGenerator:

    static KeyPairGenerator getInstance(String algorithm)
static KeyPairGenerator getInstance(String algorithm,
                                    String provider)
static KeyPairGenerator getInstance(String algorithm,
                                    Provider provider)
    Note: The algorithm name is not case-sensitive.

    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 is 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 Appendix B: Algorithms 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.

    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 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

    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, 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 SPI 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 2 SDK Security API.) Therefore, 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 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.

    The default keystore type is "jks" (the proprietary type of the keystore implementation provided by the "SUN" provider). This is specified by the following line in the security properties file:

    keystore.type=jks
    To have tools and other applications use a keystore implementation other than the default keystore, you can change that line to specify a different keystore type. Another solution would be to let users of your tools and applications specify a keystore type, and pass that value to the getInstance method of KeyStore.

    An example of the former approach is the following: 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: Keystore type designations are not case-sensitive. For example, "JKS" would be considered the same as "jks".

    The KeyStore Class

    The KeyStore class is an engine class that supplies well-defined interfaces to access and modify the information in a keystore.

    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

    As with all engine classes, the way to get a KeyStore object is to call the getInstance static factory method on the KeyStore class:

    static KeyStore getInstance(String type)

    A caller may optionally specify the name of a provider or the Provider class, which will guarantee that the implementation of the type requested is from the named provider:

    static KeyStore getInstance(String type, String provider)
static KeyStore getInstance(String type, Provider provider)

    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 PKCS #8 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.

    The SecureRandom Class

    The SecureRandom class is an engine class that provides the functionality of a random number generator.

    Creating a SecureRandom Object

    As with all engine classes, the way to get a SecureRandom object is to call the getInstance static factory method on the SecureRandom class:

    static SecureRandom getInstance(String algorithm)

    A caller may optionally specify the name of a provider or the Provider class, which will guarantee that the implementation of the random number generation (RNG) algorithm requested is from the named provider:

    static final SecureRandom getInstance(String algorithm,
                                      String provider)
static final SecureRandom getInstance(String algorithm,
                                      Provider provider)

    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)

    Code Examples

    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-1 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). We will generate keys with a 1024-bit modulus, using a user-derived seed, called userSeed. 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. A KeyPairGenerator class initialize method has these two types of arguments. Thus, to generate keys with a keysize of 1024 and a new SecureRandom object seeded by the userSeed value, you can use the following code:

    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 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 key pair 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 PKCS #7-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);
}

    Appendix A: Standard Names

    The Java 2 SDK 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 suggested for forming names that are not explicitly listed, to facilitate name consistency across provider implementations. Such suggestions use items in angle brackets (such as <digest> and <encryption>) as placeholders to be replaced by specific message digest, encryption algorithm, and other names.

    Note: Algorithm names are not case-sensitive.
    This appendix includes corresponding lists of standard names relevant to the various security subareas:
    • Java Certification Path API Programmer's Guide

    • JCE Reference Guide

    • JSSE Reference Guide

    See Appendix B for algorithm specifications.

    Message Digest Algorithms

    The algorithm names in this section can be specified when generating an instance of MessageDigest.

    MD2: The MD2 message digest algorithm as defined in RFC 1319.

    MD5: The MD5 message digest algorithm as defined in RFC 1321.

    SHA-1: The Secure Hash Algorithm, as defined in Secure Hash Standard, NIST FIPS 180-1.

    SHA-256, SHA-384, and SHA-512: New hash algorithms for which the draft Federal Information Processing Standard 180-2, Secure Hash Standard (SHS) is now available. 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.

    Key and Parameter Algorithms

    The algorithm names in this section can be specified when generating an instance of KeyPairGenerator, KeyFactory, AlgorithmParameterGenerator, and AlgorithmParameters.

    DSA: The Digital Signature Algorithm as defined in FIPS PUB 186.

    RSA: The RSA encryption algorithm as defined in PKCS #1.

    Digital Signature Algorithms

    The algorithm names in this section can be specified when generating an instance of Signature.

    MD2withRSA: The MD2 with RSA Encryption signature algorithm which uses the MD2 digest algorithm and RSA to create and verify RSA digital signatures as defined in PKCS #1.

    MD5withRSA: The MD5 with RSA Encryption signature algorithm which uses the MD5 digest algorithm and RSA to create and verify RSA digital signatures as defined in PKCS #1.

    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.

    SHA1withRSA: The signature algorithm with SHA-1 and the RSA encryption algorithm as defined in the OSI Interoperability Workshop, using the padding conventions described in PKCS #1.

    <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, etc.). 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.

    Random Number Generation (RNG) Algorithms

    The algorithm names in this section can be specified when generating an instance of SecureRandom.

    SHA1PRNG: The name of the pseudo-random number generation (PRNG) algorithm supplied by the SUN provider. This implementation follows the IEEE P1363 standard, Appendix G.7: "Expansion of source bits", and 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.

    Certificate Types

    The types in this section can be specified when generating an instance of CertificateFactory.

    X.509: The certificate type defined in X.509.

    Keystore Types

    The types in this section can be specified when generating an instance of KeyStore.

    JKS: The name of the keystore implementation provided by the SUN provider.

    PKCS12: The transfer syntax for personal identity information as defined in PKCS #12.

    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 (e.g., DSA), and a CertificateFactory service is always associated with a particular certificate type (e.g., 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.

    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".

    Appendix B: Algorithms

    This appendix specifies details concerning some of the algorithms defined in Appendix A. Any provider supplying an implementation of the listed algorithms must comply with the specifications in this appendix.

    Note: The most recent version of this document is available online at: http://java.sun.com/j2se/1.4.2/docs/guide/security/index.html.

    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 Appendix B, 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, etc.
    KeyPair Algorithm (optional) | The keypair algorithm for this algorithm.
    Keysize (optional) | For a keyed algorithm or key generation algorithm: the legal keysizes.

    Size (optional)

            For an algorithm parameter generation algorithm: the legal "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

    Name | SHA-1
    Type | MessageDigest
    Description | The message digest algorithm as defined in NIST's FIPS 180-1. The output of this algorithm is a 160-bit digest.

    MD2 Message Digest Algorithm

    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

    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

    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

    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 PKCS #1 block as defined in RSA Laboratory's Public Key Cryptography Standards Note #1. The data encrypted is the digest of the data signed.

    DSA KeyPair Generation Algorithm

    Name | DSA
    Type | KeyPairGenerator
    Description | This algorithm is the key pair generation algorithm described in 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

    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

    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.

    Copyright © 1996-2002 Sun Microsystems, Inc. All Rights Reserved.

    Please send comments to: java-security@sun.com. This is not a subscription list.     		Sun
    Java Software


Privileged Block API

API for Privileged Blocks

Last Modified: 30 April, 2001

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 © 1997-2001 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-security@sun.com 		Sun
Java Software


How to Implement a Provider for the Java Cryptography Architecture

How to Implement a Provider for the JavaTM Cryptography Architecture

Last Modified: 13 January 2003

Introduction
Who Should Read This Document
Related Documentation

Engine Classes and Corresponding SPI Classes

Steps to Implement and Integrate a Provider
Step 1: Write your Service Implementation Code
Step 2: Give your Provider a Name
Step 3: Write your "Master Class," a subclass of Provider
Step 4: Compile your Code
Step 5: Prepare for Testing: Install the Provider
Step 6: Write and Compile Test Programs
Step 7: Run your Test Programs
Step 8: Document your Provider and its Supported Services
Step 9: Make your Class Files and Documentation Available to Clients

Further Implementation Details and Requirements
Alias Names
Service Interdependencies
Default Initializations
Default Key Pair Generator Parameter Requirements
Signature Formats
DSA Interfaces and their Required Implementations
RSA 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
Adding New Object Identifiers

Appendix A: The "SUN" Provider's Master Class

Appendix B: The java.security Properties File

Introduction

JDK 1.1 introduced the notion of a Cryptographic Service Provider, or "provider" for short. This term 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.

In JDK 1.1 a provider could, for example, contain an implementation of one or more digital signature algorithms, message digest algorithms, and key generation algorithms. Java 2 SDK adds five additional types of services: key factories, keystore creation and management, algorithm parameter management, algorithm parameter generation, and certificate factories. It also enables a provider to supply a random number generation (RNG) algorithm. Previously, RNGs were not provider-based; a particular algorithm was hard-coded in the JDK.

A program wishing to use cryptography functionality 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 an implementation from a particular provider is desired, the program can request that provider by name, along with the service desired.

Each SDK 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. The "SUN" provider package includes:

  • An implementation of the Digital Signature Algorithm (DSA), described in NIST FIPS 186.

  • An implementation of the MD5 (RFC 1321) and SHA-1 (NIST FIPS 180-1) message digest algorithms.

  • A DSA key pair generator for generating a pair of public and private keys suitable for the DSA algorithm.

  • A DSA algorithm parameter generator.

  • A DSA algorithm parameter manager.

  • A DSA "key factory" providing bi-directional conversions between (opaque) DSA private and public key objects and their underlying key material.

  • An implementation of the proprietary "SHA1PRNG" pseudo-random number generation algorithm, following the recommendations in the IEEE P1363 standard (Appendix G.7).

  • A "certificate factory" for X.509 certificates and Certificate Revocation Lists (CRLs).

  • A keystore implementation for the proprietary keystore type named "JKS".

New providers may be added statically or dynamically. Clients may also query which providers are currently installed.

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.

Who Should 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 2 SDK Security so that your algorithms and other services can be found when SDK Security API clients request them. Programmers that only need to use the SDK Security API to access existing cryptography algorithms and other services do not need to read this document.

Related Documentation

This document assumes you have already read the Java Cryptography Architecture API Specification and Reference.

It also discusses various classes and interfaces in the Java 2 Security API. The complete reference documentation for the relevant Security API packages can be found in:

  • java.security package
  • java.security.spec package
  • java.security.interfaces package

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, and it either provides cryptographic operations (like those for digital signatures or message digests), 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, two of the engine classes are the Signature and KeyFactory classes. The Signature class provides access to the functionality of a digital signature algorithm. A DSA KeyFactory 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 Java Cryptography Architecture encompasses the classes of the Java 2 SDK Security package related to cryptography, including the engine classes. Users of the API request and utilize instances of the engine classes to carry out corresponding operations. The following engine classes are defined in the Java 2 SDK:

  • 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.

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. The Signature engine class, for example, 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.

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, 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.) 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

The steps required in order to implement a provider and integrate it into SDK Security are the following:

  • Step 1: Write your Service Implementation Code

  • Step 2: Give your Provider a Name

  • Step 3: Write your "Master Class", a subclass of Provider

  • Step 4: Compile your Code

  • Step 5: Prepare for Testing: Install the Provider

  • Step 6: Write and Compile your Test Programs

  • Step 7: Run your Test Programs

  • Step 8: Document your Provider and its Supported Services

  • Step 9: Make your Class Files and Documentation Available to Clients

Step 1: Write your Service Implementation Code

The first thing you need to do is write the code supplying algorithm-specific implementations of the cryptographic services you want to support.

In Java 2 SDK, you can supply signature, message digest, key pair generation, and (pseudo-)random number generation algorithms, as well as key and certificate factories and keystore creation and management, algorithm parameter management, and algorithm parameter generation services.

For each cryptographic service, you need to create a subclass of the appropriate SPI class: SignatureSpi, MessageDigestSpi, KeyPairGeneratorSpi, SecureRandomSpi, AlgorithmParameterGeneratorSpi, AlgorithmParametersSpi, KeyFactorySpi, CertificateFactorySpi, or KeyStoreSpi. (See "Engine Classes and Corresponding SPI 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, SDK Security looks up the subclass implementing that service, as specified by a property in your "master class" (see Step 3). Java 2 SDK 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.

    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 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 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("ACME", 1.0, "ACME provider v1.0, implementing " +
      "RSA signing and key generation, SHA-1 and MD5 message digests.");
  • set the values of various properties that are required for the Java 2 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 (Signature, MessageDigest, KeyPairGenerator, SecureRandom, KeyFactory, KeyStore, CertificateFactory, AlgorithmParameterGenerator, or AlgorithmParameters), followed by a period and the name of the algorithm, certificate type, or keystore type 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 properties that must be defined for the various types of services, where the actual algorithm name is substitued for algName, certificate type for certType, and keystore type for storeType:

    • Signature.algName
    • MessageDigest.algName
    • KeyPairGenerator.algName
    • SecureRandom.algName
    • KeyFactory.algName
    • CertificateFactory.certType
    • KeyStore.storeType
    • AlgorithmParameterGenerator.algName
    • AlgorithmParameters.algName

    In each of these, algName, certType , or storeType is the "standard" name of the algorithm, certificate type, or keystore type. (See Appendix A of the Java Cryptography Architecture API Specification & Reference for the standard names that should be used.)

    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
    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 API Specification & Reference 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 Java 2 SDK Sun.java source file. This shows how the Sun class constructor sets all the properties for the "SUN" provider.

Note: The Provider subclass can get its information from wherever it wants. Thus, the information can be hard-wired in, or retrieved at runtime, e.g., from a file.

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 compiler to compile your files.

Step 5: Prepare for Testing: 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 SDK Security to find your algorithm implementations when clients request them.

There are two parts to installing a provider: 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) or ZIP file.

There are a couple possible ways of installing the provider classes:

  • Place a zip or JAR file containing the classes anywhere on your CLASSPATH.

  • Supply your provider JAR file as an "installed" or "bundled" extension. For more information on how to deploy an extension, see How is an extension deployed?.

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         [Win32]
<java-home>/lib/security/java.security         [Solaris]
Here <java-home> refers to the directory where the runtime environment was installed. For example, if you have the J2SDK, v 1.4 installed on Solaris in a directory named /home/user1/j2sdk1.4.0, or on Win32 in a directory named C:\j2sdk1.4.0, then you need to edit the following file:
/home/user1/j2sdk1.4.0/jre/lib/security/java.security  [Solaris]
C:\j2sdk1.4.0\jre\lib\security\java.security           [Win32]

Similarly, if you have the Java 2 Runtime Environment, v 1.4 installed on Solaris in a directory named /home/user1/j2re1.4.0, or on Win32 in a directory named C:\j2re1.4.0, then you need to edit this file:

/home/user1/j2re1.4.0/lib/security/java.security       [Solaris]
C:\j2re1.4.0\lib\security\java.security                [Win32]

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.

Whenever the Java 2 SDK is installed, it contains some built-in (default) providers, including the provider referred to as "SUN". The java.security file includes the following provider specification for the "SUN" provider:

    security.provider.1=sun.security.provider.Sun
(Recall that the "SUN" provider's master class is the Sun class in the sun.security.provider package.)

Suppose that your master class is the Acme class in the COM.acme.provider package, and that you would like to make your provider the second preferred provider. To do so, add the following line to the java.security file below the line for the "SUN" provider, and increment the preference order numbers for all other providers whose numbers were greater than or equal to 2 before your addition:

    security.provider.2=COM.acme.provider.Acme
Note: Providers may also be registered dynamically. To do so, a program (such as your test program, to be written in Step 7) 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 "trusted" programs. See the Security class section of the Java Cryptography Architecture API Specification and Reference.

Step 6: 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 hashed or signed.

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 a SHA-1 message digest algorithm, you could check to ensure it's found when requested by using the following code (again substituting your provider name for "MyPro"):

    MessageDigest sha = MessageDigest.getInstance("SHA", "MyPro");

    System.out.println("My MessageDigest algorithm name is " +
        sha.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.

Step 7: Run your Test Programs

Run your test program(s). Debug your code and continue testing as needed. If the Java 2 Security API cannot seem to find one of your algorithms, review the steps above and ensure they are all completed.

Step 8: Document your Provider and its Supported Services

The next-to-last 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. Please note: As of this writing, provider name searches are case-sensitive. That is, if your master class specifies your provider name as "ACME" but a user requests "Acme", 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 5, except that the information and examples should be specific to your provider.
In addition, your documentation should specify anything else of interest to clients, such as any default algorithm parameters.

Message Digests

For each message digest algorithm, tell 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 hashes may be possible through cloning. Clients who do not know whether or not a message digest implementation is cloneable can find out by attempting to clone the MessageDigest object and catching the potential exception, as illustrated by the following example:

try {
   // try and clone it
    /* 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();
} catch (CloneNotSupportedException cnse) {
  // have to use an approach not involving cloning
}
where
  • sha is the message digest object they received when they requested one via a call to MessageDigest.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

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.

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 "SUN" provider uses a default modulus size (strength) of 1024 bits.

Key Factories

A provider should document all the key specifications supported by its key factory.

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.

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 "SUN" provider uses a default modulus prime size of 1024 bits for the generation of DSA parameters.

Step 9: Make your Class Files and Documentation Available to Clients

The final step is to make your class files and documentation available to clients in whatever form (.class files, zip files, JAR files, ...) and methods (web download, floppy, mail, ...) you feel are appropriate.

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 API Specification & Reference.

For example, "MD5" is the standard name for the RSA-MD5 Message Digest algorithm defined by RSA DSI in RFC 1321.

In the Java 2 SDK, 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");

Currently, aliases defined by the "SUN" provider are available to all clients, no matter which provider clients request. For example, if you create a provider named "MyPro" that implements the SHA1withDSA algorithm, then even if you don't define any aliases for it, the "SHA1/DSA" alias defined by "SUN" can be used to refer to your provider's SHA1withDSA implementation as follows:

    Signature sig = Signature.getInstance("SHA1/DSA", "MyPro");
WARNING: The aliasing scheme may be changed or eliminated in future releases.

Service Interdependencies

Some algorithms require the use of other types of algorithms. For example, a signature algorithm usually needs to use a message digest algorithm in order to sign and verify data.

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 SDK installation. For example, if you are implementing a signature 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.

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 8) 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.)

Signature Formats

If you implement a signature algorithm, the documentation you supply (Step 8) 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 2 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 2 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 SDK: 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 2 SDK 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, RSAPrivateCrtKey, and RSAPrivateKey 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, RSAPrivateCrtKey, and RSAPrivateKey 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 RSAPrivateCrtKey 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.

Interfaces for Other Algorithm Types

As noted above, the Java 2 SDK Security API contains interfaces for the convenience of programmers implementing DSA and RSA services. The API does not at this time contain similar interfaces for any other type of algorithm. Thus, you need to define your own.

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 private and public keys for non-DSA and non-RSA algorithms, there are currently no java.security.interfaces interfaces corresponding to the DSAPrivateKey and DSAPublicKey ones for DSA and the RSAPrivateKey, RSAPrivateCrtKey, and RSAPublicKey ones for RSA. 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.

The Java 2 SDK contains one AlgorithmParameterSpec implementation, the DSAParameterSpec class. If you are working with DSA algorithm parameters, you can utilize this class. If you are operating on algorithm parameters that should be for a different type of algorithm, you will need to supply your own AlgorithmParameterSpec implementation appropriate for that type of algorithm.

The Java 2 SDK defines the following algorithm parameter specification interfaces and classes in the java.security.spec package:

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.

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 the Java 2 SDK, 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).

The Java 2 SDK defines the following 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 Java 2 SDK 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 SDK 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 the Java 2 SDK. 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:
    public BigInteger getX()

    public BigInteger getP()

    public BigInteger getQ()

    public BigInteger getG()
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:
    public BigInteger getY()

    public BigInteger getP()

    public BigInteger getQ()

    public BigInteger getG()
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:
    public BigInteger getModulus()

    public BigInteger getPrivateExponent()
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):
    public BigInteger getPublicExponent()

    public BigInteger getPrimeP()

    public BigInteger getPrimeQ()

    public BigInteger getPrimeExponentP()

    public BigInteger getPrimeExponentQ()

    public BigInteger getCrtCoefficient()
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:
    public BigInteger getModulus()

    public BigInteger getPublicExponent()
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. Its getEncoded method returns the encoded key:
    public abstract byte[] getEncoded();
and its getFormat method returns the name of the encoding format:
    public abstract String getFormat();

The Java 2 SDK 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".

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 API Specification & Reference.

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 -genkey -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 -genkey and -certreq commands are invoked, the user can specify your (signature) algorithm with the -sigalg option.

Appendix A: The "SUN" Provider's Master Class

Below is a copy of the Sun.java file, which contains a class named Sun that is the master class for the provider named "SUN". (This provider is supplied with every SDK installation.)

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 "SUN" provider. Java 2 Security uses this information to look up the various algorithms and other services when they are requested.

This code is supplied as an example of a master class.

/*
 * @(#)Sun.java	1.28 99/05/27
 *
 * Copyright 1996-1998 by Sun Microsystems, Inc.,
 * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
 * 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.
 */

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 java.security Properties File

Below is a copy of the java.security file that appears in every JRE installation. This file appears 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. Thus, if you have the J2SDK v 1.4 installed on Solaris in a directory named /home/user1/j2sdk1.4.0, or on Win32 in a directory named C:\j2sdk1.4.0, then the file would be
/home/user1/j2sdk1.4.0/jre/lib/security/java.security  [Solaris]
C:\j2sdk1.4.0\jre\lib\security\java.security           [Win32]
Similarly, if you have Java 2 Runtime Environment v 1.4 installed on Solaris in a directory named /home/user1/j2re1.4.0, or on Win32 in a directory named C:\j2re1.4.0, then the file would be
/home/user1/j2re1.4.0/lib/security/java.security       [Solaris]
C:\j2re1.4.0\lib\security\java.security                [Win32]
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: 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 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=

Copyright © 1996-2003 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-security@sun.com. This is not a subscription list. 		Sun
Java Software


Security

 Documentation Contents
Security enhancements for the JavaTM 2 SDK, Standard Edition, v 1.4.2 include the following:
  • The following CA (Certification Authority) certificates were added to the cacerts file in the lib/security directory of the Java installation:
       Alias name: entrustglobalclientca
   Owner: CN=Entrust.net Client Certification Authority, OU=(c)
   2000 Entrust.net Limited, OU=www.entrust.net/GCCA_CPS incorp. by ref.
   (limits liab.), O=Entrust.net

   Alias name: entrustgsslca
   Owner: CN=Entrust.net Secure Server Certification Authority, OU=(c)
   2000 Entrust.net Limited, OU=www.entrust.net/SSL_CPS incorp. by ref.
   (limits liab.), O=Entrust.net

   Alias name: entrustsslca
   Owner: CN=Entrust.net Secure Server Certification Authority, OU=(c)
   1999 Entrust.net Limited, OU=www.entrust.net/CPS incorp. by ref.
   (limits liab.), O=Entrust.net, C=US

   Alias name: entrust2048ca
   Owner: CN=Entrust.net Certification Authority (2048), OU=(c)
   1999 Entrust.net Limited, OU=www.entrust.net/CPS_2048 incorp. by ref.
   (limits liab.), O=Entrust.net

   Alias name: entrustclientca
   Owner: CN=Entrust.net Client Certification Authority, OU=(c)
   1999 Entrust.net Limited, OU=www.entrust.net/Client_CA_Info/CPS incorp.
   by ref. limits liab., O=Entrust.net, C=US
  • Support for AES (the Advanced Encryption Standard) was added to the SunJCE cryptographic provider. For details see the JCE reference guide.

  • Support for the SHA-256, SHA-384, and SHA-512 hash algorithms was added to the Sun provider. For details see the cryptography architecture reference guide.

  • The SunJSSE implementation now supports a number of additional ciphersuites. They include ciphersuites using AES as a symmetric cipher and ephemeral Diffie-Hellman with RSA authentication (DHE_RSA). For details see the JSSE reference guide.

  • In addition to the simple X.509 based trustmanager previously available in the SunJSSE provider, it now supports a second, PKIX compliant trust manager. It is implemented utilizing the default CertPath PKIX implementation. See the JSSE reference guide for more information.

  • The PKIX CertPath implementation in the Sun provider has been made compliant with the recently published RFC 3280.

  • A number of performance related changes have been made to the certificate and PKIX implementation in the Sun provider. Depending on the usage scenario, performance can be substantially improved, in some case execution may be several times as fast as in previous releases. One of these changes is the addition of caching to the LDAPCertStore implementation, which can be configured as described in the CertPath API Programmer's Guide.

  • Limited support for the CRL DistributionPoints extension is now available in the Sun PKIX implementation. This allows the implementation to automatically locate and download CRLs in some cases, eliminating the need for manual configuration. This feature is disabled by default for compatibility reasons. For more information see the CertPath API Programmer's Guide.

  • Added Counter mode (CTR) support for all block ciphers in the SunJCE provider. For details see the JCE reference guide.

  • Security Enhancements in Java GSS
Security enhancements for the JavaTM 2 SDK, Standard Edition, v 1.4.1 include the following:
  • Three new security tools were added in the 1.4.1 release of the Java 2 platform: kinit, klist, and ktab. These tools help users obtain, list and manage Kerberos tickets. See the Security Tools section of the JavaTM 2 SDK Tools and Utilities documentation for more information.

  • The Sun SecureRandom implementation now also makes use of an operating system-provided entropy source on Windows platforms, which can improve the startup time of cryptographic applications considerably. Edit the <java.home>/lib/security/java.security to control this feature.

  • New root CA certificates with aliases baltimorecodesigningca, gtecybertrustglobalca, baltimorecybertrustca, gtecybertrustca, and gtecybertrust5ca have been added to the <java.home>/lib/security/cacerts keystore file. See The cacerts Certificates File.
Security enhancements for the previous release, JavaTM 2 SDK, Standard Edition, v 1.4 included the following:
  • The JavaTM Cryptography Extension (JCE), JavaTM Secure Socket Extension (JSSE), and JavaTM Authentication and Authorization Service (JAAS) security features have now been integrated into the Java 2 SDK, v 1.4 rather than being optional packages.

  • There are two new security features:
    • The JavaTM GSS-API can be used for securely exchanging messages between communicating applications using the Kerberos V5 mechanism.
    • The JavaTM Certification Path API includes new classes and methods in the java.security.cert package that allow you to build and validate certification paths (also known as "certificate chains").

  • Due to import control restrictions, the JCE jurisdiction policy files shipped with the Java 2 SDK, v 1.4 allow "strong" but limited cryptography to be used. A version of these files indicating no restrictions on cryptographic strengths is available.

  • The JSSE implementation provided in this release includes strong cipher suites. However, due to U.S. export control restrictions, this release does not allow alternate "pluggable" SSL/TLS implementations to be used. For more information, please see the JSSE Reference Guide.

  • With the integration of JAAS into the J2SDK, the java.security.Policy API handles Principal-based queries, and the default policy implementation supports Principal-based grant entries. Thus, access control can now be based not just on what code is running, but also on who is running it.

  • Support for dynamic policies has been added. In Java 2 SDK releases prior to version 1.4, classes were statically bound with permissions by querying security policy during class loading. The lifetime of this binding was scoped by the lifetime of the class loader. In version 1.4 this binding is now deferred until needed by a security check. The lifetime of the binding is now scoped by the lifetime of the security policy.

  • The graphical Policy Tool utility has been enhanced to enable specifying a Principal field indicating what user is to be granted specified access control permissions.
Security Guides
General Security
  • Security Architecture
  • Cryptography Architecture
  • How to Implement a Provider for the Java Cryptography Architecture
  • Policy Permissions
  • Default Policy Implementation and Policy File Syntax
  • API for Privileged Blocks
  • X.509 Certificates and Certificate Revocation Lists
  • Security Managers and the JavaTM 2 SDK
Certification Path
  • Java Certification Path API Programmer's Guide
JAAS
  • JAAS Reference Guide
  • See the JAAS Tutorials.
  • JAAS white paper
  • JAAS LoginModule Developer's Guide
Java GSS-API
  • See the Java GSS-API and JAAS Tutorials for Use with Kerberos.
  • Single Sign-on Using Kerberos in Java
JCE
  • JCE Reference Guide
  • How to Implement a Provider for the Java Cryptography Extension
JSSE
  • JSSE Reference Guide

Security API Specification
(javadoc)
General Security
  • java.security Package
  • java.security.cert Package
  • java.security.interfaces Package
  • java.security.spec Package
Certification Path
  • java.security.cert Package
JAAS
  • 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
Java GSS-API
  • org.ietf.jgss Package
  • com.sun.security.jgss Package
JCE
  • javax.crypto Package
  • javax.crypto.interfaces Package
  • javax.crypto.spec Package
JSSE
  • javax.net package
  • javax.net.ssl package
  • javax.security.cert package

Security Tools
  • Security Tools Summary
  • keytool (for Solaris) (for Windows)
  • jarsigner (for Solaris) (for Windows)
  • policytool (for Solaris) (for Windows)

Security Tutorials
  • The JavaTM 2 Platform Security trail of the Java Tutorial
  • JAAS Tutorials.
  • Java GSS-API and JAAS Tutorials for Use with Kerberos.

For More Information

Located on the Java Software web site:
  • The Security Home Page

Copyright © 1995-2003 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-security@sun.com. This is not a subscription list. 		Sun
Java Software


Permissions in the Java(TM) 2 SDK

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 Policy reference 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 granting 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 Java 2 SDK 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 tables are the following:

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 Java 2 SDK 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. Since DomainCombiners are given a reference to the ProtectionDomains currently on the stack, this could potentially lead to a privacy leak if the DomainCombiner is malicious.
    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.
    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 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.
    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]
    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.
    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.
    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.
    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.
    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.

    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:

    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.
    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.
    exitVM | Halting of the Java Virtual Machine | This allows an attacker to mount a denial-of-service attack by automatically forcing the virtual machine to halt.
    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 | stop, suspend, resume, setPriority, and setName methods | This allows an attacker to start or suspend 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 | Creation or modification of thread groups (adding a thread to a thread group during thread creation or calling the ThreadGroup destroy, resume, setDaemon, setMaxPriority, stop, and suspend methods) | This allows an attacker to create threads in thread groups or to create and modify thread groups (setting their run priority, for example).
    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.
    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.

    NIO-Related Targets

    Two NIO-related RuntimePermission targets were added in the 1.4 release of the Java 2 SDK:
    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.

    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 calls one of the setLogWriter methods. These methods include those in the following list.

    • DriverManager.setLogWriter
    • DriverManager.setLogStream (deprecated)
    • javax.sql.DataSource.setLogWriter
    • javax.sql.ConnectionPoolDataSource.setLogWriter
    • javax.sql.XADataSource.setLogWriter

    If there is no SQLPermission object, this method throws 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 below). The naming convention follows the hierarchical property naming convention. In addition, 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, but *loadLibrary or a*b is not valid.

    The following table lists all the possible SQLPermission target names. Currently, the only name allowed is setLog. 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 the 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 may contain usernames and passwords, SQL statements, and SQL data.

    The person running an applet decides what permissions to allow and will run the Policy Tool to create an 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:

    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.

    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.
    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.
    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:

    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 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 Java 2 SDK 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 Class[] getClasses()
             For this class and each of its superclasses, checkMemberAccess(this, Member.DECLARED) is called and, if the class is in a package, checkPackageAccess({pkgName}) is called. 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 the class is in a package, java.lang.RuntimePermission "accessClassInPackage.{pkgName}" is also required.
    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 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"
    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.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"

    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 g); | 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 "-", "execute";
    public void checkExit(int status); | java.lang.RuntimePermission "exitVM");
    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 © 1997-2002 Sun Microsystems, Inc. All Rights Reserved.

    Please send comments to: java-security@sun.com

            Sun
    Java Software


Default Policy Implementation and Policy File Syntax

Last Modified: 20 April 2002

The policy for a JavaTM 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) (for Win32).

Here is an outline for the rest of this document:

Policy Changes in the JavaTM 2 SDK, Standard Edition, v 1.4
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

Policy Changes in the JavaTM 2 SDK, Standard Edition, v 1.4

With the integration of JavaTM Authentication and Authorization Service (JAAS) into the J2SDK, v 1.4, the java.security.Policy API handles Principal-based queries, and the default policy implementation supports Principal-based grant entries. Thus, access control can now be based not just on what code is running, but also on who is running it. See other sections of this document for further information on principal-based grant entries.

Note: Starting with this version (v 1.4), policy files used by the default policy implementation must be encoded in the UTF-8 encoding scheme. You can use the native2ascii tool to assist with this conversion.
The rest of this section is relevant only for programmers who utilize the Policy API. If you're not such a progammer, you can skip to the next sections, Default Policy Implementation and Default Policy File Locations.

Policy-related API changes made in the J2SDK, v 1.4 include the following:

  • java.security.ProtectionDomain
    A new constructor, ProtectionDomain(CodeSource cs, PermissionCollection perms, ClassLoader loader, Principal[] principals), was added. This new constructor creates a new ProtectionDomain qualified by the given CodeSource, Permissions, ClassLoader, and Principals.
  • java.security.Policy
    Two new methods were added:
    1. getPermissions(ProtectionDomain domain) evaluates the system policy and returns a PermissionCollection object specifying the set of permissions allowed given the characteristics of the ProtectionDomain.
    2. implies(ProtectionDomain domain, Permission permission) evaluates the system policy for the permissions granted to the ProtectionDomain and tests whether the permission is granted.

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)
java.home\lib\security\java.policy  (Win32)

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 2 SDK or the top-level directory of the Java 2 Runtime Environment.

The system policy file is meant to grant system-wide code permissions. The java.policy file installed with the SDK 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)
user.home\.java.policy  (Win32)

Note: user.home refers to the value of the system property named "user.home", which specifies the user's home directory. On Win32 systems, given user name uName, the "user.home" property value defaults to

C:\Winnt\Profiles\uName on multi-user Windows NT systems
C:\Windows\Profiles\uName on multi-user Windows 95 systems
C:\Windows on single-user Windows 95 systems

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)
java.home\lib\security\java.security  (Win32)
As noted above, java.home indicates the directory that houses the runtime environment--either the jre directory in the Java 2 SDK or the top-level directory of the Java 2 Runtime Environment. 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 WriteFile

  • 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 SDK.

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 an SDK installation specify what permissions (which types of system resource accesses) are allowed 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) (for Win32) 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 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";
where "some_keystore_url" specifies the URL location of the keystore, and "keystore_type" specifies the keystore type.

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 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_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 Win32 system. Thus, if the source location for code on a Win32 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 Win32 Systems

Note: When you are specifying a java.io.FilePermission, the "target_name" is a file path. On Win32 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 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, 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 Win32 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 Win32 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.

Win32 Systems, File Paths, and Property Expansion

As noted above, on Win32 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 Java 2 SDK

  • Policy Tool (for Solaris) (for Win32)

Copyright © 1997-2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-security@sun.com. This is not a subscription list. 		Sun
Java Software


Summary of Security Tools

Summary of Tools for the JavaTM 2 Platform Security

Last Modified: 14 October, 2002

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

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.

kinit (Linux) (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. For example, for Solaris 8, see kinit reference page.

klist (Linux) (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. For example, for Solaris 8, see klist reference page.

ktab (Linux) (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 kadmin tool that is part of Solaris operating environment. For example, for Solaris 8, see kadmin reference page.

Examples of Use of the Tools

Examples of the use of several of these security tools can be found in the JavaTM 2 Platform Security trail of the Java Tutorial.

Copyright © 1997-2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-security@sun.com. This is not a subscription list. 		Sun
Java Software


Security Managers and the Java 2 SDK

Security Managers and the JavaTM 2 SDK

Last Modified: 1 May, 2001

Introduction
Security Model Evolution
Security Manager Evolution
Security Manager Methods
Security Managers in JDK 1.1
Security Managers in the Java 2 SDK
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 Java 2 SDK 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 2 SDK 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 SDK 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 2 SDK security architecture, please see the security documentaton.

Security Manager Evolution

Security Manager Methods

In both JDK 1.1 and the Java 2 SDK, 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 2 SDK

In the Java 2 SDK, 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 Java 2 SDK 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 Java 2 SDK, 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 Java 2 SDK, 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 SDK 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 Java 2 SDK, 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 SDK 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 SDK code modifications, such a check run in the Java 2 SDK would cause a security exception to be thrown when the SDK 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 SDK 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 SDK 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 Java 2 SDK 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 Java 2 SDK. Failure to do so could result in a security hole or prevent the proper operation of the SDK. 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 SDK itself to function correctly.

In the Java 2 SDK, 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 SDK itself may fail to operate properly. That is, if some SDK 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 Java 2 SDK 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 SDK 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 Java 2 SDK ( 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 Java 2 SDK to allow trusted SDK 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 Java 2 SDK. It calls java.security.AccessController.checkPermission with the given permission. Internally, the SDK 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 Java 2 SDK. 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 SDK 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 SDK 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 Java 2 SDK 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 © 1997-2001 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-security@sun.com. This is not a subscription list. 		Sun
Java Software


Java(TM) Certification Path API Programmer's Guide

Author: Sean Mullan

Last Modified: 11 February 2003

Changes in J2SE 1.4.2

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

Implementing a Service Provider

Appendix A: Standard Names

Appendix B: The "SUN" Provider

Changes in J2SE 1.4.2

Several enhancements have been made to the CertPath implementation in the SUN provider:
  • Compliance with RFC 3280.

  • Performance improvements. Several changes were made to improve the speed of validations. The performance improvement depends on the usage scenario; however, validations may be twice as fast as before. As part of these performance enhancements, the LDAP CertStore has been equipped with a cache. For details see Appendix B: The "SUN" Provider.

  • Limited support for the CRLDistributionPoints extension. For backwards compatibility, it is disabled by default. See Appendix B: The "SUN" Provider for more information and instructions on how to enable it.

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 Document.

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 is being reviewed using the Java Community ProcessSM program as JavaTM Specification Request (JSR) 000055. The API is included in the JavaTM 2 SDK, Standard Edition (J2SDK), v 1.4. Please refer to the JSR 055 Home Page for more information on the JSR and the latest status.

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 (available online at http://java.sun.com/j2se/1.4/docs/guide/security/index.html):

  • X.509 Certificates and Certificate Revocation Lists (CRLs)

  • Java Cryptography Architecture

  • 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 2 SDK, Standard Edition (J2SDK) 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 API Specification & Reference 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 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 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 J2SDK, v 1.4 it was used to generate Certificate and CRL objects. It has been enhanced in J2SDK, 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 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 getCertPathEncodings()

To generate a certification path object from a List of Certificate objects, use the following method:

    public final CertPath generateCertPath(List 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 certs = cp.getCertificates();
    Iterator i = certs.iterator();
    while (i.hasNext()) {
        X509Certificate cert = (X509Certificate) i.next();
        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 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 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(String issuerDN)
    public void setIssuer(byte[] issuerDN)

The specified distinguished name (in 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.

Similarly, the setSubject methods set the subject criterion:

    public void setSubject(String subjectDN)
    public void setSubject(byte[] subjectDN)

The specified distinguished name (in 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("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 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 setIssuerNames method sets the issuerNames criterion:

    public void setIssuerNames(Collection names)

The issuer distinguished name in the CRL must match at least one of the specified distinguished names. 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 X509CRLSelector API 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 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(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 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 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 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 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 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 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 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 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 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 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 checkers = params.getCertPathCheckers();
    ListIterator li = checkers.listIterator();
    while (li.hasNext()) {
        PKIXCertPathChecker checker = (PKIXCertPathChecker) li.next();
        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:

    ListIterator li = checkers.listIterator();
    while (li.hasNext()) {
        PKIXCertPathChecker checker = (PKIXCertPathChecker) li.next();
        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());
    }

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 has been enhanced in the J2SDK, 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. It
supplements the list of standard names defined in Appendix
A in the Java Cryptography Architecture API Specification and
Reference. Note that algorithm names are treated as
case-insensitive (for comparison).

Please note that a service provider may choose to define a new name for
a proprietary or non-standard algorithm not mentioned below. 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).

CertPathValidator Algorithms

The algorithm
names in this section can be specified when generating an instance of
CertPathValidator.

PKIX: The
PKIX certification path validation algorithm as defined in the ValidationAlgorithm
service attribute.

CertPathBuilder Algorithms

The algorithm
names in this section can be specified when generating an instance of
CertPathBuilder.

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.

CertStore Types

The following
types can be specified when generating an instance of CertStore:

LDAP: A
CertStore implementation that fetches certificates and CRLs
from an LDAP directory using the schema defined in the LDAPSchema
service attribute.

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.

CertPath Encodings

The following encodings may be passed to the getEncoded
method of CertPath or the generateCertPath(InputStream
inStream, String encoding) method of CertificateFactory.

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.

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, etc. 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) at:
ftp://ftp.bull.com/pub/OSIdirectory/DefectResolution/TechnicalCorrigenda/ApprovedTechnicalCorrigendaToX.509/8%7CX.509-TC1%284th%29.pdf.

Service Attributes

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.

Appendix B: The "SUN" Provider

The "SUN" provider which is supplied with J2SDK has been enhanced for
version 1.4 to support 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".

The PKIX Certificate and CRL Profile has many optional features.
The "SUN" provider implements support for the policy mapping extension and the
reason code CRL entry extension. It does not implement support for
the CRL distribution point, Freshest CRL, Authority Information
Access, or Subject Information Access certificate extensions. It
also does not include support for the Freshest CRL, Delta CRL,
and Issuing Distribution Point CRL extensions and the Certificate
Issuer, 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. An
application must specify one or more CertStores containing
CRLs in a PKIXParameters object. For each certificate in
the CertPath, the CertPathValidator searches the
specified CertStores for applicable CRLs. OCSP
(RFC 2560) is not
currently supported as a built in revocation checking mechanism.

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).

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

Limited 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 active CRLs will be retrieved for the locations specified in the
extension, provided the following three criteria are all met:

  1. the distribution point specifies a fullName of type URI.

  2. The URI is not of type LDAP.

  3. TRLIssuer and reasons are not set.

This allows interoperability with many simple certification
infrastructures as in use on the Internet today. We plan to remove the
above limitations in a future release.

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.

   Copyright © 1998-2003, Sun Microsystems, Inc.
   4150 Network Circle
   Santa Clara, California 95054
   All Rights Reserved.

   Please send comments to: java-security@sun.com. This is not a subscription list.


JAAS

JavaTM 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 JavaTM Authentication and Authorization Service (JAAS) was introduced as an optional package to the JavaTM 2 SDK, Standard Edition (J2SDK), v 1.3. JAAS has now been integrated into the J2SDK, v 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.

void initialize(Subject subject, CallbackHandler CallbackHandler, Map sharedState, Map 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.

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 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().

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.

     \
LOGIN \ COMMIT
       \
        \   SUCCESS          FAILURE
        +--------------+-----------------+
        |              |                 |
SUCCESS | return TRUE  | throw EXCEPTION |
        |              |                 |
        +--------------+-----------------+
        |              |                 |
FAILURE | return FALSE | return FALSE    |
        |              |                 |
        +--------------+-----------------+

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.

      \
COMMIT \ ABORT (assumes LOGIN method succeeded)
        \
         \   SUCCESS         FAILURE
        +--------------+-----------------+
        |              |                 |
SUCCESS | return TRUE  | throw EXCEPTION |
        |              |                 |
        +--------------+-----------------+
        |              |                 |
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.

      \
COMMIT \ ABORT (assumes LOGIN method failed)
        \
         \   SUCCESS         FAILURE
        +--------------+-----------------+
        |              |                 |
SUCCESS | return FALSE | return FALSE    |
        |              |                 |
        +--------------+-----------------+
        |              |                 |
FAILURE | return FALSE | return FALSE    |
        |              |                 |
        +--------------+-----------------+

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.

Last update: August 8, 2001


JAAS Reference Guide

JavaTM Authentication and Authorization Service (JAAS)

Reference Guide

for the JavaTM 2 SDK, Standard Edition, v 1.4

Introduction
Who Should Read This Document
Related Documentation

What's New in JAAS in the J2SDK, v 1.4

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 JavaTM Authentication and Authorization Service (JAAS) was introduced as an optional package (extension) to the JavaTM 2 SDK, Standard Edition (J2SDK), v 1.3. JAAS has now been integrated into the J2SDK, v 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 2 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 2 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 2 access control model to protect access to sensitive resources. Unlike in the J2SDK, v 1.3 and earlier, where access control decisions are based solely on code location and code signers (a CodeSource), in the J2SDK, v 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 2 Security Architecture

  • JAAS white paper

  • Java 2 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.

What's New in JAAS in the J2SDK, v 1.4

Below are listed the differences between the previous version of JAAS (JAAS 1.0) and the JAAS within the J2SDK, v 1.4.

  • JAAS Is Now in J2SDK

  • New Classes/Interfaces

  • Deprecated Items

JAAS Is Now in J2SDK

JAAS was previously an optional package (extension) to the JavaTM 2 SDK, Standard Edition (J2SDK), versions 1.3.x. JAAS has now been integrated into the J2SDK, v 1.4. JAAS augments the core Java 2 platform with the means to authenticate and enforce access controls upon users.

The major ramification of this integration stems around the system security policy. The J2SDK, versions 1.3 and earlier, has its own security policy class (java.security.Policy ). JAAS 1.0, as an optional package, provided an additional Principal-based security policy (javax.security.auth.Policy). Upon integration into the core SDK, the JAAS policy has been deprecated in favor of the SDK policy.

The SDK Policy API was upgraded to support Principal-based queries, and the Policy reference implementation was upgraded to support Principal-based grant entries in policy files, where such an entry may include a Principal field indicating that the user or other entity represented by the specified Principal, executing the specified code, has the designated permissions. In addition, the graphical Policy Tool utility used to create policy files was enhanced to support inclusion of Principal fields. Appropriately, the JAAS 1.0 Policy reference implementation and its supporting classes in the com.sun.security.auth package have been deprecated.

Please reference the Policy Document for more information on the Policy reference implementation and a list of the relevant API changes.

New Classes/Interfaces

Additions include

  • Two default CallbackHandler implementations:
    • com.sun.security.auth.callback.DialogCallbackHandler
    • com.sun.security.auth.callback.TextCallbackHandler

  • New com.sun.security.auth.module.Krb5LoginModule

  • New com.sun.security.auth.module.KeyStoreLoginModule

Deprecated Items

Deprecated items include:

  • Deprecation of
    • com.sun.security.auth.module.SolarisLoginModule
    in favor of
    • com.sun.security.auth.module.UnixLoginModule
    The new UnixLoginModule can be used on both Solaris and Linux.

  • Deprecation of
    • com.sun.security.auth.SolarisPrincipal
    in favor of
    • com.sun.security.auth.UnixPrincipal

  • Deprecation of
    • com.sun.security.auth.SolarisNumericUserPrincipal
    in favor of
    • com.sun.security.auth.UnixNumericUserPrincipal

  • Deprecation of
    • com.sun.security.auth.SolarisNumericGroupPrincipal
    in favor of
    • com.sun.security.auth.UnixNumericGroupPrincipal

  • Deprecation of
    • com.sun.security.auth.X500Principal
    in favor of
    • javax.security.auth.x500.X500Principal

  • Deprecation of the javax.security.auth.AuthPermission target name
    • "createLoginContext"
    in favor of
    • "createLoginContext.{configuration entry name}"

Core Classes and Interfaces

The JAAS-related core classes and interfaces can be broken into 3 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, v 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 2 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 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 2 runtime, v 1.4. 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 | 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.

Last update: August 8, 2001


All Classes (Java Authentication and Authorization Service )

 All Classes
ConfigFile
DialogCallbackHandler
JndiLoginModule
KeyStoreLoginModule
Krb5LoginModule
NTDomainPrincipal
NTLoginModule
NTNumericCredential
NTSid
NTSidDomainPrincipal
NTSidGroupPrincipal
NTSidPrimaryGroupPrincipal
NTSidUserPrincipal
NTSystem
NTUserPrincipal
PolicyFile
PrincipalComparator
SolarisLoginModule
SolarisNumericGroupPrincipal
SolarisNumericUserPrincipal
SolarisPrincipal
SolarisSystem
TextCallbackHandler
UnixLoginModule
UnixNumericGroupPrincipal
UnixNumericUserPrincipal
UnixPrincipal
UnixSystem
X500Principal


Constant Field Values (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Constant Field Values

Contents
  • com.sun.*
com.sun.*

com.sun.security.auth.module.JndiLoginModule
public final String | GROUP_PROVIDER | "group.provider.url"
public final String | USER_PROVIDER | "user.provider.url"

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


API Help (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

How This API Document Is Organized

This API (Application Programming Interface) document has pages corresponding to the items in the navigation bar, described as follows.

Overview

The Overview page is the front page of this API document and provides a list of all packages with a summary for each. This page can also contain an overall description of the set of packages.

Package

Each package has a page that contains a list of its classes and interfaces, with a summary for each. This page can contain four categories:

  • Interfaces (italic)
  • Classes
  • Exceptions
  • Errors

Class/Interface

Each class, interface, nested class and nested interface has its own separate page. Each of these pages has three sections consisting of a class/interface description, summary tables, and detailed member descriptions:

  • Class inheritance diagram
  • Direct Subclasses
  • All Known Subinterfaces
  • All Known Implementing Classes
  • Class/interface declaration
  • Class/interface description

  • Nested Class Summary
  • Field Summary
  • Constructor Summary
  • Method Summary

  • Field Detail
  • Constructor Detail
  • Method Detail
Each summary entry contains the first sentence from the detailed description for that item. The summary entries are alphabetical, while the detailed descriptions are in the order they appear in the source code. This preserves the logical groupings established by the programmer.

Use

Each documented package, class and interface has its own Use page. This page describes what packages, classes, methods, constructors and fields use any part of the given class 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.

Tree (Class Hierarchy)

There is a Class Hierarchy page for all packages, plus a hierarchy for each package. Each hierarchy page contains a list of classes and a list of interfaces. The classes are organized by inheritance structure starting with java.lang.Object. The interfaces do not inherit from java.lang.Object.
  • When viewing the Overview page, clicking on "Tree" displays the hierarchy for all packages.
  • When viewing a particular package, class or interface page, clicking "Tree" displays the hierarchy for only that package.

Index

The Index contains an alphabetic list of all classes, interfaces, constructors, methods, and fields.

Prev/Next

These links take you to the next or previous class, interface, package, or related page.

Frames/No Frames

These links show and hide the HTML frames. All pages are available with or without frames.

Serialized Form

Each serializable or externalizable 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 description.

This help file applies to API documentation generated using the standard doclet.

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


Java Authentication and Authorization Service

Frame Alert

This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client.
Link toNon-frame version.


Index (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES
A C D E G H I J K L N P R S T U X

A

abort() - Method in class com.sun.security.auth.module.JndiLoginModule
This method is called if the LoginContext's overall authentication failed.
abort() - Method in class com.sun.security.auth.module.KeyStoreLoginModule
This method is called if the LoginContext's overall authentication failed.
abort() - Method in class com.sun.security.auth.module.Krb5LoginModule
This method is called if the LoginContext's overall authentication failed.
abort() - Method in class com.sun.security.auth.module.NTLoginModule
This method is called if the LoginContext's overall authentication failed.
abort() - Method in class com.sun.security.auth.module.SolarisLoginModule
Deprecated. Abort the authentication (second phase).
abort() - Method in class com.sun.security.auth.module.UnixLoginModule
Abort the authentication (second phase).

C

ConfigFile - class com.sun.security.auth.login.ConfigFile.
This class represents a default implementation for javax.security.auth.login.Configuration.
ConfigFile() - Constructor for class com.sun.security.auth.login.ConfigFile
Create a new Configuration object.
com.sun.security.auth - package com.sun.security.auth
com.sun.security.auth.callback - package com.sun.security.auth.callback
com.sun.security.auth.login - package com.sun.security.auth.login
com.sun.security.auth.module - package com.sun.security.auth.module
commit() - Method in class com.sun.security.auth.module.JndiLoginModule
Abstract method to commit the authentication process (phase 2).
commit() - Method in class com.sun.security.auth.module.KeyStoreLoginModule
Abstract method to commit the authentication process (phase 2).
commit() - Method in class com.sun.security.auth.module.Krb5LoginModule
This method is called if the LoginContext's overall authentication succeeded (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules succeeded).
commit() - Method in class com.sun.security.auth.module.NTLoginModule
This method is called if the LoginContext's overall authentication succeeded (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules succeeded).
commit() - Method in class com.sun.security.auth.module.SolarisLoginModule
Deprecated. Commit the authentication (second phase).
commit() - Method in class com.sun.security.auth.module.UnixLoginModule
Commit the authentication (second phase).

D

DialogCallbackHandler - class com.sun.security.auth.callback.DialogCallbackHandler.
Uses a Swing dialog window to query the user for answers to authentication questions.
DialogCallbackHandler() - Constructor for class com.sun.security.auth.callback.DialogCallbackHandler
Creates a callback dialog with the default parent window.
DialogCallbackHandler(Component) - Constructor for class com.sun.security.auth.callback.DialogCallbackHandler
Creates a callback dialog and specify the parent window.

E

equals(Object) - Method in class com.sun.security.auth.NTDomainPrincipal
Compares the specified Object with this NTDomainPrincipal for equality.
equals(Object) - Method in class com.sun.security.auth.NTNumericCredential
Compares the specified Object with this NTNumericCredential for equality.
equals(Object) - Method in class com.sun.security.auth.NTSid
Compares the specified Object with this NTSid for equality.
equals(Object) - Method in class com.sun.security.auth.NTSidDomainPrincipal
Compares the specified Object with this NTSidDomainPrincipal for equality.
equals(Object) - Method in class com.sun.security.auth.NTSidGroupPrincipal
Compares the specified Object with this NTSidGroupPrincipal for equality.
equals(Object) - Method in class com.sun.security.auth.NTSidPrimaryGroupPrincipal
Compares the specified Object with this NTSidPrimaryGroupPrincipal for equality.
equals(Object) - Method in class com.sun.security.auth.NTSidUserPrincipal
Compares the specified Object with this NTSidUserPrincipal for equality.
equals(Object) - Method in class com.sun.security.auth.NTUserPrincipal
Compares the specified Object with this NTUserPrincipal for equality.
equals(Object) - Method in class com.sun.security.auth.SolarisNumericGroupPrincipal
Deprecated. Compares the specified Object with this SolarisNumericGroupPrincipal for equality.
equals(Object) - Method in class com.sun.security.auth.SolarisNumericUserPrincipal
Deprecated. Compares the specified Object with this SolarisNumericUserPrincipal for equality.
equals(Object) - Method in class com.sun.security.auth.SolarisPrincipal
Deprecated. Compares the specified Object with this SolarisPrincipal for equality.
equals(Object) - Method in class com.sun.security.auth.UnixNumericGroupPrincipal
Compares the specified Object with this UnixNumericGroupPrincipal for equality.
equals(Object) - Method in class com.sun.security.auth.UnixNumericUserPrincipal
Compares the specified Object with this UnixNumericUserPrincipal for equality.
equals(Object) - Method in class com.sun.security.auth.UnixPrincipal
Compares the specified Object with this UnixPrincipal for equality.
equals(Object) - Method in class com.sun.security.auth.X500Principal
Deprecated. Compares the specified Object with this X500Principal for equality.

G

GROUP_PROVIDER - Variable in class com.sun.security.auth.module.JndiLoginModule
getAppConfigurationEntry(String) - Method in class com.sun.security.auth.login.ConfigFile
Retrieve an entry from the Configuration using an application name as an index.
getDomain() - Method in class com.sun.security.auth.module.NTSystem
Get the domain for the current NT user.
getDomainSID() - Method in class com.sun.security.auth.module.NTSystem
Get a printable SID for the current NT user's domain.
getGid() - Method in class com.sun.security.auth.module.SolarisSystem
Get the GID for the current Solaris user.
getGid() - Method in class com.sun.security.auth.module.UnixSystem
Get the GID for the current Unix user.
getGroupIDs() - Method in class com.sun.security.auth.module.NTSystem
Get the printable group SIDs for the current NT user.
getGroups() - Method in class com.sun.security.auth.module.SolarisSystem
Get the supplementary groups for the current Solaris user.
getGroups() - Method in class com.sun.security.auth.module.UnixSystem
Get the supplementary groups for the current Unix user.
getImpersonationToken() - Method in class com.sun.security.auth.module.NTSystem
Get an impersonation token for the current NT user.
getName() - Method in class com.sun.security.auth.NTDomainPrincipal
Return the Windows NT domain name for this NTDomainPrincipal.
getName() - Method in class com.sun.security.auth.NTSid
Return a string version of this NTSid.
getName() - Method in class com.sun.security.auth.NTUserPrincipal
Return the Windows NT username for this NTPrincipal.
getName() - Method in class com.sun.security.auth.SolarisNumericGroupPrincipal
Deprecated. Return the user's group identification number (GID) for this SolarisNumericGroupPrincipal.
getName() - Method in class com.sun.security.auth.SolarisNumericUserPrincipal
Deprecated. Return the user identification number (UID) for this SolarisNumericUserPrincipal.
getName() - Method in class com.sun.security.auth.SolarisPrincipal
Deprecated. Return the Unix username for this SolarisPrincipal.
getName() - Method in class com.sun.security.auth.UnixNumericGroupPrincipal
Return the user's group identification number (GID) for this UnixNumericGroupPrincipal.
getName() - Method in class com.sun.security.auth.UnixNumericUserPrincipal
Return the user identification number (UID) for this UnixNumericUserPrincipal.
getName() - Method in class com.sun.security.auth.UnixPrincipal
Return the Unix username for this UnixPrincipal.
getName() - Method in class com.sun.security.auth.X500Principal
Deprecated. Return the Unix username for this X500Principal.
getName() - Method in class com.sun.security.auth.module.NTSystem
Get the username for the current NT user.
getPermissions(Subject, CodeSource) - Method in class com.sun.security.auth.PolicyFile
Deprecated. Examines this Policy and returns the Permissions granted to the specified Subject and CodeSource.
getPrimaryGroupID() - Method in class com.sun.security.auth.module.NTSystem
Get a printable primary group SID for the current NT user.
getToken() - Method in class com.sun.security.auth.NTNumericCredential
Return an integer representation of this NTNumericCredential.
getUid() - Method in class com.sun.security.auth.module.SolarisSystem
Get the UID for the current Solaris user.
getUid() - Method in class com.sun.security.auth.module.UnixSystem
Get the UID for the current Unix user.
getUserSID() - Method in class com.sun.security.auth.module.NTSystem
Get a printable SID for the current NT user.
getUsername() - Method in class com.sun.security.auth.module.SolarisSystem
Get the username for the current Solaris user.
getUsername() - Method in class com.sun.security.auth.module.UnixSystem
Get the username for the current Unix user.
gid - Variable in class com.sun.security.auth.module.SolarisSystem
gid - Variable in class com.sun.security.auth.module.UnixSystem
groups - Variable in class com.sun.security.auth.module.SolarisSystem
groups - Variable in class com.sun.security.auth.module.UnixSystem

H

handle(Callback[]) - Method in class com.sun.security.auth.callback.DialogCallbackHandler
Handles the specified set of callbacks.
handle(Callback[]) - Method in class com.sun.security.auth.callback.TextCallbackHandler
Handles the specified set of callbacks.
hashCode() - Method in class com.sun.security.auth.NTDomainPrincipal
Return a hash code for this NTDomainPrincipal.
hashCode() - Method in class com.sun.security.auth.NTNumericCredential
Return a hash code for this NTNumericCredential.
hashCode() - Method in class com.sun.security.auth.NTSid
Return a hash code for this NTSid.
hashCode() - Method in class com.sun.security.auth.NTUserPrincipal
Return a hash code for this NTUserPrincipal.
hashCode() - Method in class com.sun.security.auth.SolarisNumericGroupPrincipal
Deprecated. Return a hash code for this SolarisNumericGroupPrincipal.
hashCode() - Method in class com.sun.security.auth.SolarisNumericUserPrincipal
Deprecated. Return a hash code for this SolarisNumericUserPrincipal.
hashCode() - Method in class com.sun.security.auth.SolarisPrincipal
Deprecated. Return a hash code for this SolarisPrincipal.
hashCode() - Method in class com.sun.security.auth.UnixNumericGroupPrincipal
Return a hash code for this UnixNumericGroupPrincipal.
hashCode() - Method in class com.sun.security.auth.UnixNumericUserPrincipal
Return a hash code for this UnixNumericUserPrincipal.
hashCode() - Method in class com.sun.security.auth.UnixPrincipal
Return a hash code for this UnixPrincipal.
hashCode() - Method in class com.sun.security.auth.X500Principal
Deprecated. Return a hash code for this X500Principal.

I

implies(Subject) - Method in interface com.sun.security.auth.PrincipalComparator
Check if the specified Subject is implied by this object.
initialize(Subject, CallbackHandler, Map, Map) - Method in class com.sun.security.auth.module.JndiLoginModule
Initialize this LoginModule.
initialize(Subject, CallbackHandler, Map, Map) - Method in class com.sun.security.auth.module.KeyStoreLoginModule
Initialize this LoginModule.
initialize(Subject, CallbackHandler, Map, Map) - Method in class com.sun.security.auth.module.Krb5LoginModule
Initialize this LoginModule.
initialize(Subject, CallbackHandler, Map, Map) - Method in class com.sun.security.auth.module.NTLoginModule
Initialize this LoginModule.
initialize(Subject, CallbackHandler, Map, Map) - Method in class com.sun.security.auth.module.SolarisLoginModule
Deprecated. Initialize this LoginModule.
initialize(Subject, CallbackHandler, Map, Map) - Method in class com.sun.security.auth.module.UnixLoginModule
Initialize this LoginModule.
isPrimaryGroup() - Method in class com.sun.security.auth.SolarisNumericGroupPrincipal
Deprecated. Return whether this group identification number (GID) represents the primary group to which this user belongs.
isPrimaryGroup() - Method in class com.sun.security.auth.UnixNumericGroupPrincipal
Return whether this group identification number (GID) represents the primary group to which this user belongs.

J

JndiLoginModule - class com.sun.security.auth.module.JndiLoginModule.
The module prompts for a username and password and then verifies the password against the password stored in a directory service configured under JNDI.
JndiLoginModule() - Constructor for class com.sun.security.auth.module.JndiLoginModule

K

KeyStoreLoginModule - class com.sun.security.auth.module.KeyStoreLoginModule.
Provides a JAAS login module that prompts for a key store alias and populates the subject with the alias's principal and credentials.
KeyStoreLoginModule() - Constructor for class com.sun.security.auth.module.KeyStoreLoginModule
Krb5LoginModule - class com.sun.security.auth.module.Krb5LoginModule.
This LoginModule authenticates users using Kerberos protocols.
Krb5LoginModule() - Constructor for class com.sun.security.auth.module.Krb5LoginModule

L

login() - Method in class com.sun.security.auth.module.JndiLoginModule
Prompt for username and password.
login() - Method in class com.sun.security.auth.module.KeyStoreLoginModule
Authenticate the user .
login() - Method in class com.sun.security.auth.module.Krb5LoginModule
Authenticate the user
login() - Method in class com.sun.security.auth.module.NTLoginModule
Import underlying NT system identity information.
login() - Method in class com.sun.security.auth.module.SolarisLoginModule
Deprecated. Authenticate the user (first phase).
login() - Method in class com.sun.security.auth.module.UnixLoginModule
Authenticate the user (first phase).
logout() - Method in class com.sun.security.auth.module.JndiLoginModule
Logout a user.
logout() - Method in class com.sun.security.auth.module.KeyStoreLoginModule
Logout a user.
logout() - Method in class com.sun.security.auth.module.Krb5LoginModule
Logout the user.
logout() - Method in class com.sun.security.auth.module.NTLoginModule
Logout the user.
logout() - Method in class com.sun.security.auth.module.SolarisLoginModule
Deprecated. Logout the user
logout() - Method in class com.sun.security.auth.module.UnixLoginModule
Logout the user
longValue() - Method in class com.sun.security.auth.SolarisNumericGroupPrincipal
Deprecated. Return the user's group identification number (GID) for this SolarisNumericGroupPrincipal as a long.
longValue() - Method in class com.sun.security.auth.SolarisNumericUserPrincipal
Deprecated. Return the user identification number (UID) for this SolarisNumericUserPrincipal as a long.
longValue() - Method in class com.sun.security.auth.UnixNumericGroupPrincipal
Return the user's group identification number (GID) for this UnixNumericGroupPrincipal as a long.
longValue() - Method in class com.sun.security.auth.UnixNumericUserPrincipal
Return the user identification number (UID) for this UnixNumericUserPrincipal as a long.

N

NTDomainPrincipal - class com.sun.security.auth.NTDomainPrincipal.
This class implements the Principal interface and represents the name of the Windows NT domain into which the user authenticated.
NTDomainPrincipal(String) - Constructor for class com.sun.security.auth.NTDomainPrincipal
Create an NTDomainPrincipal with a Windows NT domain name.
NTLoginModule - class com.sun.security.auth.module.NTLoginModule.
This LoginModule renders a user's NT security information as some number of Principals and associates them with a Subject.
NTLoginModule() - Constructor for class com.sun.security.auth.module.NTLoginModule
NTNumericCredential - class com.sun.security.auth.NTNumericCredential.
This class abstracts an NT security token and provides a mechanism to do same-process security impersonation.
NTNumericCredential(long) - Constructor for class com.sun.security.auth.NTNumericCredential
Create an NTNumericCredential with an integer value.
NTSid - class com.sun.security.auth.NTSid.
This class implements the Principal interface and represents information about a Windows NT user, group or realm.
NTSid(String) - Constructor for class com.sun.security.auth.NTSid
Create an NTSid with a Windows NT SID.
NTSidDomainPrincipal - class com.sun.security.auth.NTSidDomainPrincipal.
This class extends NTSid and represents a Windows NT user's domain SID.
NTSidDomainPrincipal(String) - Constructor for class com.sun.security.auth.NTSidDomainPrincipal
Create an NTSidDomainPrincipal with a Windows NT SID.
NTSidGroupPrincipal - class com.sun.security.auth.NTSidGroupPrincipal.
This class extends NTSid and represents one of the groups to which a Windows NT user belongs.
NTSidGroupPrincipal(String) - Constructor for class com.sun.security.auth.NTSidGroupPrincipal
Create an NTSidGroupPrincipal with a Windows NT group name.
NTSidPrimaryGroupPrincipal - class com.sun.security.auth.NTSidPrimaryGroupPrincipal.
This class extends NTSid and represents a Windows NT user's primary group SID.
NTSidPrimaryGroupPrincipal(String) - Constructor for class com.sun.security.auth.NTSidPrimaryGroupPrincipal
Create an NTSidPrimaryGroupPrincipal with a Windows NT group SID.
NTSidUserPrincipal - class com.sun.security.auth.NTSidUserPrincipal.
This class extends NTSid and represents a Windows NT user's SID.
NTSidUserPrincipal(String) - Constructor for class com.sun.security.auth.NTSidUserPrincipal
Create an NTSidUserPrincipal with a Windows NT SID.
NTSystem - class com.sun.security.auth.module.NTSystem.
This class implementation retrieves and makes available NT security information for the current user.
NTSystem() - Constructor for class com.sun.security.auth.module.NTSystem
Instantiate an NTSystem and load the native library to access the underlying system information.
NTUserPrincipal - class com.sun.security.auth.NTUserPrincipal.
This class implements the Principal interface and represents a Windows NT user.
NTUserPrincipal(String) - Constructor for class com.sun.security.auth.NTUserPrincipal
Create an NTUserPrincipal with a Windows NT username.

P

PolicyFile - class com.sun.security.auth.PolicyFile.
Deprecated. As of JDK 1.4, replaced by sun.security.provider.PolicyFile. This class is entirely deprecated.
PolicyFile() - Constructor for class com.sun.security.auth.PolicyFile
Deprecated. Initializes the Policy object and reads the default policy configuration file(s) into the Policy object.
PrincipalComparator - interface com.sun.security.auth.PrincipalComparator.
An object that implements the java.security.Principal interface typically also implements this interface to provide a means for comparing that object to a specified Subject.

R

refresh() - Method in class com.sun.security.auth.PolicyFile
Deprecated. Refreshes the policy object by re-reading all the policy files.
refresh() - Method in class com.sun.security.auth.login.ConfigFile
Refresh and reload the Configuration by re-reading all of the login configurations.

S

SolarisLoginModule - class com.sun.security.auth.module.SolarisLoginModule.
Deprecated. As of JDK1.4, replaced by com.sun.security.auth.module.UnixLoginModule. This LoginModule is entirely deprecated and is here to allow for a smooth transition to the new UnixLoginModule.
SolarisLoginModule() - Constructor for class com.sun.security.auth.module.SolarisLoginModule
Deprecated.
SolarisNumericGroupPrincipal - class com.sun.security.auth.SolarisNumericGroupPrincipal.
Deprecated. As of JDK 1.4, replaced by UnixNumericGroupPrincipal. This class is entirely deprecated.
SolarisNumericGroupPrincipal(String, boolean) - Constructor for class com.sun.security.auth.SolarisNumericGroupPrincipal
Deprecated. Create a SolarisNumericGroupPrincipal using a String representation of the user's group identification number (GID).
SolarisNumericGroupPrincipal(long, boolean) - Constructor for class com.sun.security.auth.SolarisNumericGroupPrincipal
Deprecated. Create a SolarisNumericGroupPrincipal using a long representation of the user's group identification number (GID).
SolarisNumericUserPrincipal - class com.sun.security.auth.SolarisNumericUserPrincipal.
Deprecated. As of JDK 1.4, replaced by UnixNumericUserPrincipal. This class is entirely deprecated.
SolarisNumericUserPrincipal(String) - Constructor for class com.sun.security.auth.SolarisNumericUserPrincipal
Deprecated. Create a SolarisNumericUserPrincipal using a String representation of the user's identification number (UID).
SolarisNumericUserPrincipal(long) - Constructor for class com.sun.security.auth.SolarisNumericUserPrincipal
Deprecated. Create a SolarisNumericUserPrincipal using a long representation of the user's identification number (UID).
SolarisPrincipal - class com.sun.security.auth.SolarisPrincipal.
Deprecated. As of JDK 1.4, replaced by UnixPrincipal. This class is entirely deprecated.
SolarisPrincipal(String) - Constructor for class com.sun.security.auth.SolarisPrincipal
Deprecated. Create a SolarisPrincipal with a Solaris username.
SolarisSystem - class com.sun.security.auth.module.SolarisSystem.
This class implementation retrieves and makes available Solaris UID/GID/groups information for the current user.
SolarisSystem() - Constructor for class com.sun.security.auth.module.SolarisSystem
Instantiate a SolarisSystem and load the native library to access the underlying system information.

T

TextCallbackHandler - class com.sun.security.auth.callback.TextCallbackHandler.
Prompts and reads from the command line for answers to authentication questions.
TextCallbackHandler() - Constructor for class com.sun.security.auth.callback.TextCallbackHandler
Creates a callback handler that prompts and reads from the command line for answers to authentication questions.
toString() - Method in class com.sun.security.auth.NTDomainPrincipal
Return a string representation of this NTDomainPrincipal.
toString() - Method in class com.sun.security.auth.NTNumericCredential
Return a string representation of this NTNumericCredential.
toString() - Method in class com.sun.security.auth.NTSid
Return a string representation of this NTSid.
toString() - Method in class com.sun.security.auth.NTSidDomainPrincipal
Return a string representation of this NTSidDomainPrincipal.
toString() - Method in class com.sun.security.auth.NTSidGroupPrincipal
Return a string representation of this NTSidGroupPrincipal.
toString() - Method in class com.sun.security.auth.NTSidPrimaryGroupPrincipal
Return a string representation of this NTSidPrimaryGroupPrincipal.
toString() - Method in class com.sun.security.auth.NTSidUserPrincipal
Return a string representation of this NTSidUserPrincipal.
toString() - Method in class com.sun.security.auth.NTUserPrincipal
Return a string representation of this NTPrincipal.
toString() - Method in class com.sun.security.auth.SolarisNumericGroupPrincipal
Deprecated. Return a string representation of this SolarisNumericGroupPrincipal.
toString() - Method in class com.sun.security.auth.SolarisNumericUserPrincipal
Deprecated. Return a string representation of this SolarisNumericUserPrincipal.
toString() - Method in class com.sun.security.auth.SolarisPrincipal
Deprecated. Return a string representation of this SolarisPrincipal.
toString() - Method in class com.sun.security.auth.UnixNumericGroupPrincipal
Return a string representation of this UnixNumericGroupPrincipal.
toString() - Method in class com.sun.security.auth.UnixNumericUserPrincipal
Return a string representation of this UnixNumericUserPrincipal.
toString() - Method in class com.sun.security.auth.UnixPrincipal
Return a string representation of this UnixPrincipal.
toString() - Method in class com.sun.security.auth.X500Principal
Deprecated. Return a string representation of this X500Principal.

U

USER_PROVIDER - Variable in class com.sun.security.auth.module.JndiLoginModule
JNDI Provider
UnixLoginModule - class com.sun.security.auth.module.UnixLoginModule.
This LoginModule imports a user's Unix Principal information (UnixPrincipal, UnixNumericUserPrincipal, and UnixNumericGroupPrincipal) and associates them with the current Subject.
UnixLoginModule() - Constructor for class com.sun.security.auth.module.UnixLoginModule
UnixNumericGroupPrincipal - class com.sun.security.auth.UnixNumericGroupPrincipal.
This class implements the Principal interface and represents a user's Unix group identification number (GID).
UnixNumericGroupPrincipal(String, boolean) - Constructor for class com.sun.security.auth.UnixNumericGroupPrincipal
Create a UnixNumericGroupPrincipal using a String representation of the user's group identification number (GID).
UnixNumericGroupPrincipal(long, boolean) - Constructor for class com.sun.security.auth.UnixNumericGroupPrincipal
Create a UnixNumericGroupPrincipal using a long representation of the user's group identification number (GID).
UnixNumericUserPrincipal - class com.sun.security.auth.UnixNumericUserPrincipal.
This class implements the Principal interface and represents a user's Unix identification number (UID).
UnixNumericUserPrincipal(String) - Constructor for class com.sun.security.auth.UnixNumericUserPrincipal
Create a UnixNumericUserPrincipal using a String representation of the user's identification number (UID).
UnixNumericUserPrincipal(long) - Constructor for class com.sun.security.auth.UnixNumericUserPrincipal
Create a UnixNumericUserPrincipal using a long representation of the user's identification number (UID).
UnixPrincipal - class com.sun.security.auth.UnixPrincipal.
This class implements the Principal interface and represents a Unix user.
UnixPrincipal(String) - Constructor for class com.sun.security.auth.UnixPrincipal
Create a UnixPrincipal with a Unix username.
UnixSystem - class com.sun.security.auth.module.UnixSystem.
This class implementation retrieves and makes available Unix UID/GID/groups information for the current user.
UnixSystem() - Constructor for class com.sun.security.auth.module.UnixSystem
Instantiate a UnixSystem and load the native library to access the underlying system information.
uid - Variable in class com.sun.security.auth.module.SolarisSystem
uid - Variable in class com.sun.security.auth.module.UnixSystem
username - Variable in class com.sun.security.auth.module.SolarisSystem
username - Variable in class com.sun.security.auth.module.UnixSystem

X

X500Principal - class com.sun.security.auth.X500Principal.
Deprecated. A new X500Principal class is available in the Java 2 platform. This X500Principal classs is entirely deprecated and is here to allow for a smooth transition to the new class.
X500Principal(String) - Constructor for class com.sun.security.auth.X500Principal
Deprecated. Create a X500Principal with an X.500 Name, such as "CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US" (RFC 1779 style).
A C D E G H I J K L N P R S T U X
Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


Overview (Java Authentication and Authorization Service )

JAAS
All Classes

Packages
com.sun.security.auth
com.sun.security.auth.callback
com.sun.security.auth.login
com.sun.security.auth.module


Overview (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

JavaTM Authentication and Authorization Service

This package contains Sun's implementation of the javax.security.auth.* interfaces and authentication modules.

See:
Description

Packages
com.sun.security.auth
com.sun.security.auth.callback
com.sun.security.auth.login
com.sun.security.auth.module

This package contains Sun's implementation of the javax.security.auth.* interfaces and authentication modules.

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


Class Hierarchy (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Hierarchy For All Packages

Package Hierarchies:
com.sun.security.auth, com.sun.security.auth.callback, com.sun.security.auth.login, com.sun.security.auth.module

Class Hierarchy

  • class java.lang.Object
    • class javax.security.auth.login.Configuration
      • class com.sun.security.auth.login.ConfigFile
    • class com.sun.security.auth.callback.DialogCallbackHandler (implements javax.security.auth.callback.CallbackHandler)
    • class com.sun.security.auth.module.JndiLoginModule (implements javax.security.auth.spi.LoginModule)
    • class com.sun.security.auth.module.KeyStoreLoginModule (implements javax.security.auth.spi.LoginModule)
    • class com.sun.security.auth.module.Krb5LoginModule (implements javax.security.auth.spi.LoginModule)
    • class com.sun.security.auth.NTDomainPrincipal (implements java.security.Principal, java.io.Serializable)
    • class com.sun.security.auth.module.NTLoginModule (implements javax.security.auth.spi.LoginModule)
    • class com.sun.security.auth.NTNumericCredential
    • class com.sun.security.auth.NTSid (implements java.security.Principal, java.io.Serializable)
      • class com.sun.security.auth.NTSidDomainPrincipal
      • class com.sun.security.auth.NTSidGroupPrincipal
      • class com.sun.security.auth.NTSidPrimaryGroupPrincipal
      • class com.sun.security.auth.NTSidUserPrincipal
    • class com.sun.security.auth.module.NTSystem
    • class com.sun.security.auth.NTUserPrincipal (implements java.security.Principal, java.io.Serializable)
    • class javax.security.auth.Policy
      • class com.sun.security.auth.PolicyFile
    • class com.sun.security.auth.module.SolarisLoginModule (implements javax.security.auth.spi.LoginModule)
    • class com.sun.security.auth.SolarisNumericGroupPrincipal (implements java.security.Principal, java.io.Serializable)
    • class com.sun.security.auth.SolarisNumericUserPrincipal (implements java.security.Principal, java.io.Serializable)
    • class com.sun.security.auth.SolarisPrincipal (implements java.security.Principal, java.io.Serializable)
    • class com.sun.security.auth.module.SolarisSystem
    • class com.sun.security.auth.callback.TextCallbackHandler (implements javax.security.auth.callback.CallbackHandler)
    • class com.sun.security.auth.module.UnixLoginModule (implements javax.security.auth.spi.LoginModule)
    • class com.sun.security.auth.UnixNumericGroupPrincipal (implements java.security.Principal, java.io.Serializable)
    • class com.sun.security.auth.UnixNumericUserPrincipal (implements java.security.Principal, java.io.Serializable)
    • class com.sun.security.auth.UnixPrincipal (implements java.security.Principal, java.io.Serializable)
    • class com.sun.security.auth.module.UnixSystem
    • class com.sun.security.auth.X500Principal (implements java.security.Principal, java.io.Serializable)

Interface Hierarchy

  • interface com.sun.security.auth.PrincipalComparator
Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


Serialized Form (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Serialized Form

Package com.sun.security.auth

Class com.sun.security.auth.NTDomainPrincipal extends Object implements Serializable

serialVersionUID: -4408637351440771220l

Serialized Fields

name

String name

Class com.sun.security.auth.NTSid extends Object implements Serializable

Serialized Fields

sid

String sid

Class com.sun.security.auth.NTSidDomainPrincipal extends NTSid implements Serializable

Class com.sun.security.auth.NTSidGroupPrincipal extends NTSid implements Serializable

Class com.sun.security.auth.NTSidPrimaryGroupPrincipal extends NTSid implements Serializable

Class com.sun.security.auth.NTSidUserPrincipal extends NTSid implements Serializable

Class com.sun.security.auth.NTUserPrincipal extends Object implements Serializable

serialVersionUID: -8737649811939033735l

Serialized Fields

name

String name

Class com.sun.security.auth.SolarisNumericGroupPrincipal extends Object implements Serializable

Serialized Fields

name

String name
Deprecated.

primaryGroup

boolean primaryGroup
Deprecated.

Class com.sun.security.auth.SolarisNumericUserPrincipal extends Object implements Serializable

Serialized Fields

name

String name
Deprecated.

Class com.sun.security.auth.SolarisPrincipal extends Object implements Serializable

Serialized Fields

name

String name
Deprecated.

Class com.sun.security.auth.UnixNumericGroupPrincipal extends Object implements Serializable

Serialized Fields

name

String name

primaryGroup

boolean primaryGroup

Class com.sun.security.auth.UnixNumericUserPrincipal extends Object implements Serializable

Serialized Fields

name

String name

Class com.sun.security.auth.UnixPrincipal extends Object implements Serializable

Serialized Fields

name

String name

Class com.sun.security.auth.X500Principal extends Object implements Serializable

Serialization Methods

readObject

private void readObject(ObjectInputStream s)
                 throws IOException,
                        NotActiveException,
                        ClassNotFoundException
Deprecated.
Reads this object from a stream (i.e., deserializes it)

Serialized Fields

name

String name
Deprecated.

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


NTDomainPrincipal (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

com.sun.security.auth
Class NTDomainPrincipal

java.lang.Object
    extended by com.sun.security.auth.NTDomainPrincipal
All Implemented Interfaces:
Principal, Serializable
public class NTDomainPrincipal
extends Object
implements Principal, Serializable

This class implements the Principal interface and represents the name of the Windows NT domain into which the user authenticated. This will be a domain name if the user logged into a Windows NT domain, a workgroup name if the user logged into a workgroup, or a machine name if the user logged into a standalone configuration.

Principals such as this NTDomainPrincipal may be associated with a particular Subject to augment that Subject with an additional identity. Refer to the Subject class for more information on how to achieve this. Authorization decisions can then be based upon the Principals associated with a Subject.

See Also:
Principal, Subject, Serialized Form

Constructor Summary
NTDomainPrincipal(String name)
Create an NTDomainPrincipal with a Windows NT domain name.
Method Summary
boolean | equals(Object o) Compares the specified Object with this NTDomainPrincipal for equality.
String | getName() Return the Windows NT domain name for this NTDomainPrincipal.
int | hashCode() Return a hash code for this NTDomainPrincipal.
String | toString() Return a string representation of this NTDomainPrincipal.
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait

Constructor Detail

NTDomainPrincipal

public NTDomainPrincipal(String name)
Create an NTDomainPrincipal with a Windows NT domain name.

Parameters:
name - the Windows NT domain name for this user.

Throws:
NullPointerException - if the name is null.
Method Detail

getName

public String getName()
Return the Windows NT domain name for this NTDomainPrincipal.

Specified by:
getName in interface Principal
Returns:
the Windows NT domain name for this NTDomainPrincipal

toString

public String toString()
Return a string representation of this NTDomainPrincipal.

Specified by:
toString in interface Principal
Returns:
a string representation of this NTDomainPrincipal.

equals

public boolean equals(Object o)
Compares the specified Object with this NTDomainPrincipal for equality. Returns true if the given object is also a NTDomainPrincipal and the two NTDomainPrincipals have the same name.

Specified by:
equals in interface Principal
Parameters:
o - Object to be compared for equality with this NTDomainPrincipal.
Returns:
true if the specified Object is equal equal to this NTDomainPrincipal.

hashCode

public int hashCode()
Return a hash code for this NTDomainPrincipal.

Specified by:
hashCode in interface Principal
Returns:
a hash code for this NTDomainPrincipal.
Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


NTNumericCredential (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.security.auth
Class NTNumericCredential

java.lang.Object
    extended by com.sun.security.auth.NTNumericCredential
public class NTNumericCredential
extends Object

This class abstracts an NT security token and provides a mechanism to do same-process security impersonation.

Constructor Summary
NTNumericCredential(long token)
Create an NTNumericCredential with an integer value.
Method Summary
boolean | equals(Object o) Compares the specified Object with this NTNumericCredential for equality.
long | getToken() Return an integer representation of this NTNumericCredential.
int | hashCode() Return a hash code for this NTNumericCredential.
String | toString() Return a string representation of this NTNumericCredential.
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait

Constructor Detail

NTNumericCredential

public NTNumericCredential(long token)
Create an NTNumericCredential with an integer value.

Parameters:
token - the Windows NT security token for this user.

Method Detail

getToken

public long getToken()
Return an integer representation of this NTNumericCredential.

Returns:
an integer representation of this NTNumericCredential.

toString

public String toString()
Return a string representation of this NTNumericCredential.

Returns:
a string representation of this NTNumericCredential.

equals

public boolean equals(Object o)
Compares the specified Object with this NTNumericCredential for equality. Returns true if the given object is also a NTNumericCredential and the two NTNumericCredentials represent the same NT security token.

Parameters:
o - Object to be compared for equality with this NTNumericCredential.
Returns:
true if the specified Object is equal equal to this NTNumericCredential.

hashCode

public int hashCode()
Return a hash code for this NTNumericCredential.

Returns:
a hash code for this NTNumericCredential.
Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NTSid (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.security.auth
Class NTSid

java.lang.Object
    extended by com.sun.security.auth.NTSid
All Implemented Interfaces:
Principal, Serializable
Direct Known Subclasses:
NTSidDomainPrincipal, NTSidGroupPrincipal, NTSidPrimaryGroupPrincipal, NTSidUserPrincipal
public class NTSid
extends Object
implements Principal, Serializable

This class implements the Principal interface and represents information about a Windows NT user, group or realm.

Windows NT chooses to represent users, groups and realms (or domains) with not only common names, but also relatively unique numbers. These numbers are called Security IDentifiers, or SIDs. Windows NT also provides services that render these SIDs into string forms. This class represents these string forms.

Principals such as this NTSid may be associated with a particular Subject to augment that Subject with an additional identity. Refer to the Subject class for more information on how to achieve this. Authorization decisions can then be based upon the Principals associated with a Subject.

See Also:
Principal, Subject, Serialized Form

Constructor Summary
NTSid(String stringSid)
Create an NTSid with a Windows NT SID.
Method Summary
boolean | equals(Object o) Compares the specified Object with this NTSid for equality.
String | getName() Return a string version of this NTSid.
int | hashCode() Return a hash code for this NTSid.
String | toString() Return a string representation of this NTSid.
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait

Constructor Detail

NTSid

public NTSid(String stringSid)
Create an NTSid with a Windows NT SID.

Parameters:
stringSid - the Windows NT SID.

Throws:
NullPointerException - if the String is null.
IllegalArgumentException - if the String has zero length.
Method Detail

getName

public String getName()
Return a string version of this NTSid.

Specified by:
getName in interface Principal
Returns:
a string version of this NTSid

toString

public String toString()
Return a string representation of this NTSid.

Specified by:
toString in interface Principal
Returns:
a string representation of this NTSid.

equals

public boolean equals(Object o)
Compares the specified Object with this NTSid for equality. Returns true if the given object is also a NTSid and the two NTSids have the same String representation.

Specified by:
equals in interface Principal
Parameters:
o - Object to be compared for equality with this NTSid.
Returns:
true if the specified Object is equal to this NTSid.

hashCode

public int hashCode()
Return a hash code for this NTSid.

Specified by:
hashCode in interface Principal
Returns:
a hash code for this NTSid.
Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NTSidDomainPrincipal (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.security.auth
Class NTSidDomainPrincipal

java.lang.Object
    extended by com.sun.security.auth.NTSid
        extended by com.sun.security.auth.NTSidDomainPrincipal
All Implemented Interfaces:
Principal, Serializable
public class NTSidDomainPrincipal
extends NTSid

This class extends NTSid and represents a Windows NT user's domain SID.

An NT user only has a domain SID if in fact they are logged into an NT domain. If the user is logged into a workgroup or just a standalone configuration, they will NOT have a domain SID.

Principals such as this NTSidDomainPrincipal may be associated with a particular Subject to augment that Subject with an additional identity. Refer to the Subject class for more information on how to achieve this. Authorization decisions can then be based upon the Principals associated with a Subject.

See Also:
Principal, Subject, Serialized Form

Constructor Summary
NTSidDomainPrincipal(String name)
Create an NTSidDomainPrincipal with a Windows NT SID.
Method Summary
boolean | equals(Object o) Compares the specified Object with this NTSidDomainPrincipal for equality.
String | toString() Return a string representation of this NTSidDomainPrincipal.
Methods inherited from class com.sun.security.auth.NTSid
getName, hashCode
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait

Constructor Detail

NTSidDomainPrincipal

public NTSidDomainPrincipal(String name)
Create an NTSidDomainPrincipal with a Windows NT SID.

Parameters:
name - a string version of the Windows NT SID for this user's domain.

Throws:
NullPointerException - if the name is null.
Method Detail

toString

public String toString()
Return a string representation of this NTSidDomainPrincipal.

Specified by:
toString in interface Principal
Overrides:
toString in class NTSid
Returns:
a string representation of this NTSidDomainPrincipal.

equals

public boolean equals(Object o)
Compares the specified Object with this NTSidDomainPrincipal for equality. Returns true if the given object is also a NTSidDomainPrincipal and the two NTSidDomainPrincipals have the same SID.

Specified by:
equals in interface Principal
Overrides:
equals in class NTSid
Parameters:
o - Object to be compared for equality with this NTSidDomainPrincipal.
Returns:
true if the specified Object is equal equal to this NTSidDomainPrincipal.
Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NTSidGroupPrincipal (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.security.auth
Class NTSidGroupPrincipal

java.lang.Object
    extended by com.sun.security.auth.NTSid
        extended by com.sun.security.auth.NTSidGroupPrincipal
All Implemented Interfaces:
Principal, Serializable
public class NTSidGroupPrincipal
extends NTSid

This class extends NTSid and represents one of the groups to which a Windows NT user belongs.

Principals such as this NTSidGroupPrincipal may be associated with a particular Subject to augment that Subject with an additional identity. Refer to the Subject class for more information on how to achieve this. Authorization decisions can then be based upon the Principals associated with a Subject.

See Also:
Principal, Subject, NTSid, Serialized Form

Constructor Summary
NTSidGroupPrincipal(String name)
Create an NTSidGroupPrincipal with a Windows NT group name.
Method Summary
boolean | equals(Object o) Compares the specified Object with this NTSidGroupPrincipal for equality.
String | toString() Return a string representation of this NTSidGroupPrincipal.
Methods inherited from class com.sun.security.auth.NTSid
getName, hashCode
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait

Constructor Detail

NTSidGroupPrincipal

public NTSidGroupPrincipal(String name)
Create an NTSidGroupPrincipal with a Windows NT group name.

Parameters:
name - the Windows NT group SID for this user.

Throws:
NullPointerException - if the name is null.
Method Detail

toString

public String toString()
Return a string representation of this NTSidGroupPrincipal.

Specified by:
toString in interface Principal
Overrides:
toString in class NTSid
Returns:
a string representation of this NTSidGroupPrincipal.

equals

public boolean equals(Object o)
Compares the specified Object with this NTSidGroupPrincipal for equality. Returns true if the given object is also a NTSidGroupPrincipal and the two NTSidGroupPrincipals have the same SID.

Specified by:
equals in interface Principal
Overrides:
equals in class NTSid
Parameters:
o - Object to be compared for equality with this NTSidGroupPrincipal.
Returns:
true if the specified Object is equal equal to this NTSidGroupPrincipal.
Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NTSidPrimaryGroupPrincipal (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.security.auth
Class NTSidPrimaryGroupPrincipal

java.lang.Object
    extended by com.sun.security.auth.NTSid
        extended by com.sun.security.auth.NTSidPrimaryGroupPrincipal
All Implemented Interfaces:
Principal, Serializable
public class NTSidPrimaryGroupPrincipal
extends NTSid

This class extends NTSid and represents a Windows NT user's primary group SID.

Principals such as this NTSidPrimaryGroupPrincipal may be associated with a particular Subject to augment that Subject with an additional identity. Refer to the Subject class for more information on how to achieve this. Authorization decisions can then be based upon the Principals associated with a Subject.

See Also:
Principal, Subject, Serialized Form

Constructor Summary
NTSidPrimaryGroupPrincipal(String name)
Create an NTSidPrimaryGroupPrincipal with a Windows NT group SID.
Method Summary
boolean | equals(Object o) Compares the specified Object with this NTSidPrimaryGroupPrincipal for equality.
String | toString() Return a string representation of this NTSidPrimaryGroupPrincipal.
Methods inherited from class com.sun.security.auth.NTSid
getName, hashCode
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait

Constructor Detail

NTSidPrimaryGroupPrincipal

public NTSidPrimaryGroupPrincipal(String name)
Create an NTSidPrimaryGroupPrincipal with a Windows NT group SID.

Parameters:
name - the primary Windows NT group SID for this user.

Throws:
NullPointerException - if the name is null.
Method Detail

toString

public String toString()
Return a string representation of this NTSidPrimaryGroupPrincipal.

Specified by:
toString in interface Principal
Overrides:
toString in class NTSid
Returns:
a string representation of this NTSidPrimaryGroupPrincipal.

equals

public boolean equals(Object o)
Compares the specified Object with this NTSidPrimaryGroupPrincipal for equality. Returns true if the given object is also a NTSidPrimaryGroupPrincipal and the two NTSidPrimaryGroupPrincipals have the same SID.

Specified by:
equals in interface Principal
Overrides:
equals in class NTSid
Parameters:
o - Object to be compared for equality with this NTSidPrimaryGroupPrincipal.
Returns:
true if the specified Object is equal equal to this NTSidPrimaryGroupPrincipal.
Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NTSidUserPrincipal (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.security.auth
Class NTSidUserPrincipal

java.lang.Object
    extended by com.sun.security.auth.NTSid
        extended by com.sun.security.auth.NTSidUserPrincipal
All Implemented Interfaces:
Principal, Serializable
public class NTSidUserPrincipal
extends NTSid

This class extends NTSid and represents a Windows NT user's SID.

Principals such as this NTSidUserPrincipal may be associated with a particular Subject to augment that Subject with an additional identity. Refer to the Subject class for more information on how to achieve this. Authorization decisions can then be based upon the Principals associated with a Subject.

See Also:
Principal, Subject, Serialized Form

Constructor Summary
NTSidUserPrincipal(String name)
Create an NTSidUserPrincipal with a Windows NT SID.
Method Summary
boolean | equals(Object o) Compares the specified Object with this NTSidUserPrincipal for equality.
String | toString() Return a string representation of this NTSidUserPrincipal.
Methods inherited from class com.sun.security.auth.NTSid
getName, hashCode
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait

Constructor Detail

NTSidUserPrincipal

public NTSidUserPrincipal(String name)
Create an NTSidUserPrincipal with a Windows NT SID.

Parameters:
name - a string version of the Windows NT SID for this user.

Throws:
NullPointerException - if the name is null.
Method Detail

toString

public String toString()
Return a string representation of this NTSidUserPrincipal.

Specified by:
toString in interface Principal
Overrides:
toString in class NTSid
Returns:
a string representation of this NTSidUserPrincipal.

equals

public boolean equals(Object o)
Compares the specified Object with this NTSidUserPrincipal for equality. Returns true if the given object is also a NTSidUserPrincipal and the two NTSidUserPrincipals have the same SID.

Specified by:
equals in interface Principal
Overrides:
equals in class NTSid
Parameters:
o - Object to be compared for equality with this NTSidUserPrincipal.
Returns:
true if the specified Object is equal equal to this NTSidUserPrincipal.
Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NTUserPrincipal (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.security.auth
Class NTUserPrincipal

java.lang.Object
    extended by com.sun.security.auth.NTUserPrincipal
All Implemented Interfaces:
Principal, Serializable
public class NTUserPrincipal
extends Object
implements Principal, Serializable

This class implements the Principal interface and represents a Windows NT user.

Principals such as this NTUserPrincipal may be associated with a particular Subject to augment that Subject with an additional identity. Refer to the Subject class for more information on how to achieve this. Authorization decisions can then be based upon the Principals associated with a Subject.

See Also:
Principal, Subject, Serialized Form

Constructor Summary
NTUserPrincipal(String name)
Create an NTUserPrincipal with a Windows NT username.
Method Summary
boolean | equals(Object o) Compares the specified Object with this NTUserPrincipal for equality.
String | getName() Return the Windows NT username for this NTPrincipal.
int | hashCode() Return a hash code for this NTUserPrincipal.
String | toString() Return a string representation of this NTPrincipal.
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait

Constructor Detail

NTUserPrincipal

public NTUserPrincipal(String name)
Create an NTUserPrincipal with a Windows NT username.

Parameters:
name - the Windows NT username for this user.

Throws:
NullPointerException - if the name is null.
Method Detail

getName

public String getName()
Return the Windows NT username for this NTPrincipal.

Specified by:
getName in interface Principal
Returns:
the Windows NT username for this NTPrincipal

toString

public String toString()
Return a string representation of this NTPrincipal.

Specified by:
toString in interface Principal
Returns:
a string representation of this NTPrincipal.

equals

public boolean equals(Object o)
Compares the specified Object with this NTUserPrincipal for equality. Returns true if the given object is also a NTUserPrincipal and the two NTUserPrincipals have the same name.

Specified by:
equals in interface Principal
Parameters:
o - Object to be compared for equality with this NTPrincipal.
Returns:
true if the specified Object is equal equal to this NTPrincipal.

hashCode

public int hashCode()
Return a hash code for this NTUserPrincipal.

Specified by:
hashCode in interface Principal
Returns:
a hash code for this NTUserPrincipal.
Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


com.sun.security.auth (Java Authentication and Authorization Service )

 com.sun.security.auth
Interfaces
PrincipalComparator
Classes
NTDomainPrincipal
NTNumericCredential
NTSid
NTSidDomainPrincipal
NTSidGroupPrincipal
NTSidPrimaryGroupPrincipal
NTSidUserPrincipal
NTUserPrincipal
PolicyFile
SolarisNumericGroupPrincipal
SolarisNumericUserPrincipal
SolarisPrincipal
UnixNumericGroupPrincipal
UnixNumericUserPrincipal
UnixPrincipal
X500Principal


com.sun.security.auth (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package com.sun.security.auth

Interface Summary
PrincipalComparator An object that implements the java.security.Principal interface typically also implements this interface to provide a means for comparing that object to a specified Subject.

Class Summary
NTDomainPrincipal | This class implements the Principal interface and represents the name of the Windows NT domain into which the user authenticated.
NTNumericCredential | This class abstracts an NT security token and provides a mechanism to do same-process security impersonation.
NTSid | This class implements the Principal interface and represents information about a Windows NT user, group or realm.
NTSidDomainPrincipal | This class extends NTSid and represents a Windows NT user's domain SID.
NTSidGroupPrincipal | This class extends NTSid and represents one of the groups to which a Windows NT user belongs.
NTSidPrimaryGroupPrincipal | This class extends NTSid and represents a Windows NT user's primary group SID.
NTSidUserPrincipal | This class extends NTSid and represents a Windows NT user's SID.
NTUserPrincipal | This class implements the Principal interface and represents a Windows NT user.
PolicyFile | Deprecated. As of JDK 1.4, replaced by sun.security.provider.PolicyFile.
SolarisNumericGroupPrincipal | Deprecated. As of JDK 1.4, replaced by UnixNumericGroupPrincipal.
SolarisNumericUserPrincipal | Deprecated. As of JDK 1.4, replaced by UnixNumericUserPrincipal.
SolarisPrincipal | Deprecated. As of JDK 1.4, replaced by UnixPrincipal.
UnixNumericGroupPrincipal | This class implements the Principal interface and represents a user's Unix group identification number (GID).
UnixNumericUserPrincipal | This class implements the Principal interface and represents a user's Unix identification number (UID).
UnixPrincipal | This class implements the Principal interface and represents a Unix user.
X500Principal | Deprecated. A new X500Principal class is available in the Java 2 platform.

Overview Package Class Use Tree Index Help
JAAS
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


com.sun.security.auth Class Hierarchy (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Hierarchy For Package com.sun.security.auth

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class com.sun.security.auth.NTDomainPrincipal (implements java.security.Principal, java.io.Serializable)
    • class com.sun.security.auth.NTNumericCredential
    • class com.sun.security.auth.NTSid (implements java.security.Principal, java.io.Serializable)
      • class com.sun.security.auth.NTSidDomainPrincipal
      • class com.sun.security.auth.NTSidGroupPrincipal
      • class com.sun.security.auth.NTSidPrimaryGroupPrincipal
      • class com.sun.security.auth.NTSidUserPrincipal
    • class com.sun.security.auth.NTUserPrincipal (implements java.security.Principal, java.io.Serializable)
    • class javax.security.auth.Policy
      • class com.sun.security.auth.PolicyFile
    • class com.sun.security.auth.SolarisNumericGroupPrincipal (implements java.security.Principal, java.io.Serializable)
    • class com.sun.security.auth.SolarisNumericUserPrincipal (implements java.security.Principal, java.io.Serializable)
    • class com.sun.security.auth.SolarisPrincipal (implements java.security.Principal, java.io.Serializable)
    • class com.sun.security.auth.UnixNumericGroupPrincipal (implements java.security.Principal, java.io.Serializable)
    • class com.sun.security.auth.UnixNumericUserPrincipal (implements java.security.Principal, java.io.Serializable)
    • class com.sun.security.auth.UnixPrincipal (implements java.security.Principal, java.io.Serializable)
    • class com.sun.security.auth.X500Principal (implements java.security.Principal, java.io.Serializable)

Interface Hierarchy

  • interface com.sun.security.auth.PrincipalComparator
Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


Uses of Package com.sun.security.auth (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Uses of Package
com.sun.security.auth

Packages that use com.sun.security.auth
com.sun.security.auth

Classes in com.sun.security.auth used by com.sun.security.auth
NTSid
This class implements the Principal interface and represents information about a Windows NT user, group or realm.

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


PolicyFile (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.security.auth
Class PolicyFile

java.lang.Object
    extended by javax.security.auth.Policy
        extended by com.sun.security.auth.PolicyFile
Deprecated. As of JDK 1.4, replaced by sun.security.provider.PolicyFile. This class is entirely deprecated.

public class PolicyFile
extends Policy

This class represents a default implementation for javax.security.auth.Policy.

This object stores the policy for entire Java runtime, and is the amalgamation of multiple static policy configurations that resides in files. The algorithm for locating the policy file(s) and reading their information into this Policy object is:

  1. Loop through the java.security.Security properties, auth.policy.url.1, auth.policy.url.2, ..., auth.policy.url.X". These properties are set in the Java security properties file, which is located in the file named <JAVA_HOME>/lib/security/java.security, where <JAVA_HOME> refers to the directory where the JDK was installed. Each property value specifies a URL pointing to a policy file to be loaded. Read in and load each policy.
  2. The java.lang.System property java.security.auth.policy may also be set to a URL pointing to another policy file (which is the case when a user uses the -D switch at runtime). If this property is defined, and its use is allowed by the security property file (the Security property, policy.allowSystemProperty is set to true), also load that policy.
  3. If the java.security.auth.policy property is defined using "==" (rather than "="), then ignore all other specified policies and only load this policy.
Each policy file consists of one or more grant entries, each of which consists of a number of permission entries.
   grant signedBy "alias", codeBase "URL",
         principal principalClass "principalName",
         principal principalClass "principalName",
         ... {

     permission Type "name "action",
         signedBy "alias";
     permission Type "name "action",
         signedBy "alias";
     ....
   };
All non-bold 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 and codeBase name/value pairs are optional. If they are not present, then any signer (including unsigned code) will match, and any codeBase will match. Note that the principal name/value pair is not optional. This Policy implementation only permits Principal-based grant entries. Note that the principalClass may be set to the wildcard value, *, which allows it to match any Principal class. In addition, the principalName may also be set to the wildcard value, *, allowing it to match any Principal name. When setting the principalName to the *, do not surround the * with quotes.

A permission entry must begin with the word permission. The word Type in the template above is 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 that 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 "name" value following the type 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 in order for it to be granted. For example, suppose you have the following grant entry:

   grant principal foo.com.Principal "Duke" {
     permission Foo "foobar", signedBy "FooSoft";
   }

Then this permission of type Foo is granted if the Foo.class permission has been signed by the "FooSoft" alias, or if Foo.class is a system class (i.e., is found on the CLASSPATH).

Items that appear in an entry must appear in the specified order (permission, Type, "name", and "action"). An entry is terminated with a semicolon.

Case is unimportant for the identifiers (permission, signedBy, codeBase, etc.) but is significant for the Type or for any string that is passed in as a value.

An example of two entries in a policy configuration file is

   // if the code is comes from "foo.com" and is running as "Duke",
   // grant it read/write to all files in /tmp.

   grant codeBase "foo.com", principal foo.com.Principal "Duke" {
         permission java.io.FilePermission "/tmp/*", "read,write";
   };

   // grant any code running as "Duke" permission to read
   // the "java.vendor" Property.

   grant principal foo.com.Principal "Duke" {
        permission java.util.PropertyPermission "java.vendor";

This Policy implementation supports special handling for PrivateCredentialPermissions. If a grant entry is configured with a PrivateCredentialPermission, and the "Principal Class/Principal Name" for that PrivateCredentialPermission is "self", then the entry grants the specified Subject permission to access its own private Credential. For example, the following grants the Subject "Duke" access to its own a.b.Credential.

   grant principal foo.com.Principal "Duke" {
    permission javax.security.auth.PrivateCredentialPermission
        "a.b.Credential self",
        "read";
    };
The following grants the Subject "Duke" access to all of its own private Credentials:
   grant principal foo.com.Principal "Duke" {
    permission javax.security.auth.PrivateCredentialPermission
        "* self",
        "read";
    };
The following grants all Subjects authenticated as a SolarisPrincipal (regardless of their respective names) permission to access their own private Credentials:
   grant principal com.sun.security.auth.SolarisPrincipal * {
    permission javax.security.auth.PrivateCredentialPermission
        "* self",
        "read";
    };
The following grants all Subjects permission to access their own private Credentials:
   grant principal * * {
    permission javax.security.auth.PrivateCredentialPermission
        "* self",
        "read";
    };

See Also:
CodeSource, Permissions, ProtectionDomain

Constructor Summary
PolicyFile()
Deprecated. Initializes the Policy object and reads the default policy configuration file(s) into the Policy object.
Method Summary
PermissionCollection | getPermissions(Subject subject, CodeSource codesource) Deprecated. Examines this Policy and returns the Permissions granted to the specified Subject and CodeSource.
void | refresh() Deprecated. Refreshes the policy object by re-reading all the policy files.
Methods inherited from class javax.security.auth.Policy
getPolicy, setPolicy
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

PolicyFile

public PolicyFile()
Deprecated.
Initializes the Policy object and reads the default policy configuration file(s) into the Policy object.

Method Detail

refresh

public void refresh()
Deprecated.
Refreshes the policy object by re-reading all the policy files.

Throws:
SecurityException - if the caller doesn't have permission to refresh the Policy.

getPermissions

public PermissionCollection getPermissions(Subject subject,
                                           CodeSource codesource)
Deprecated.
Examines this Policy and returns the Permissions granted to the specified Subject and CodeSource.

Permissions for a particular grant entry are returned if the CodeSource constructed using the codebase and signedby values specified in the entry implies the CodeSource provided to this method, and if the Subject provided to this method contains all of the Principals specified in the entry.

The Subject provided to this method contains all of the Principals specified in the entry if, for each Principal, "P1", specified in the grant entry one of the following two conditions is met:

  1. the Subject has a Principal, "P2", where P2.getClass().getName() equals the P1's class name, and where P2.getName() equals the P1's name.
  2. P1 implements com.sun.security.auth.PrincipalComparator, and P1.implies the provided Subject.

Note that this Policy implementation has special handling for PrivateCredentialPermissions. When this method encounters a PrivateCredentialPermission which specifies "self" as the Principal class and name, it does not add that Permission to the returned PermissionCollection. Instead, it builds a new PrivateCredentialPermission for each Principal associated with the provided Subject. Each new PrivateCredentialPermission contains the same Credential class as specified in the originally granted permission, as well as the Class and name for the respective Principal.

Parameters:
subject - the Permissions granted to this Subject and the additionally provided CodeSource are returned.

codesource - the Permissions granted to this CodeSource and the additionally provided Subject are returned.
Returns:
the Permissions granted to the provided Subject CodeSource.
Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


PrincipalComparator (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

com.sun.security.auth
Interface PrincipalComparator

public interface PrincipalComparator

An object that implements the java.security.Principal interface typically also implements this interface to provide a means for comparing that object to a specified Subject.

The comparison is achieved via the implies method. The implementation of the implies method determines whether this object "implies" the specified Subject. One example application of this method may be for a "group" object to imply a particular Subject if that Subject belongs to the group. Another example application of this method would be for "role" object to imply a particular Subject if that Subject is currently acting in that role.

Although classes that implement this interface typically also implement the java.security.Principal interface, it is not required. In other words, classes may implement the java.security.Principal interface by itself, the PrincipalComparator interface by itself, or both at the same time.

See Also:
Principal, Subject

Method Summary
 boolean implies(Subject subject)
Check if the specified Subject is implied by this object.

Method Detail

implies

public boolean implies(Subject subject)
Check if the specified Subject is implied by this object.

Returns:
true if the specified Subject is implied by this object, or false otherwise.
Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


SolarisNumericGroupPrincipal (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.security.auth
Class SolarisNumericGroupPrincipal

java.lang.Object
    extended by com.sun.security.auth.SolarisNumericGroupPrincipal
All Implemented Interfaces:
Principal, Serializable
Deprecated. As of JDK 1.4, replaced by UnixNumericGroupPrincipal. This class is entirely deprecated.

public class SolarisNumericGroupPrincipal
extends Object
implements Principal, Serializable

This class implements the Principal interface and represents a user's Solaris group identification number (GID).

Principals such as this SolarisNumericGroupPrincipal may be associated with a particular Subject to augment that Subject with an additional identity. Refer to the Subject class for more information on how to achieve this. Authorization decisions can then be based upon the Principals associated with a Subject.

See Also:
Principal, Subject, Serialized Form

Constructor Summary
SolarisNumericGroupPrincipal(long name, boolean primaryGroup)
Deprecated. Create a SolarisNumericGroupPrincipal using a long representation of the user's group identification number (GID).
SolarisNumericGroupPrincipal(String name, boolean primaryGroup)
Deprecated. Create a SolarisNumericGroupPrincipal using a String representation of the user's group identification number (GID).
Method Summary
boolean | equals(Object o) Deprecated. Compares the specified Object with this SolarisNumericGroupPrincipal for equality.
String | getName() Deprecated. Return the user's group identification number (GID) for this SolarisNumericGroupPrincipal.
int | hashCode() Deprecated. Return a hash code for this SolarisNumericGroupPrincipal.
boolean | isPrimaryGroup() Deprecated. Return whether this group identification number (GID) represents the primary group to which this user belongs.
long | longValue() Deprecated. Return the user's group identification number (GID) for this SolarisNumericGroupPrincipal as a long.
String | toString() Deprecated. Return a string representation of this SolarisNumericGroupPrincipal.
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait

Constructor Detail

SolarisNumericGroupPrincipal

public SolarisNumericGroupPrincipal(String name,
                                    boolean primaryGroup)
Deprecated.
Create a SolarisNumericGroupPrincipal using a String representation of the user's group identification number (GID).

Parameters:
name - the user's group identification number (GID) for this user.

primaryGroup - true if the specified GID represents the primary group to which this user belongs.
Throws:
NullPointerException - if the name is null.

SolarisNumericGroupPrincipal

public SolarisNumericGroupPrincipal(long name,
                                    boolean primaryGroup)
Deprecated.
Create a SolarisNumericGroupPrincipal using a long representation of the user's group identification number (GID).

Parameters:
name - the user's group identification number (GID) for this user represented as a long.

primaryGroup - true if the specified GID represents the primary group to which this user belongs.
Method Detail

getName

public String getName()
Deprecated.
Return the user's group identification number (GID) for this SolarisNumericGroupPrincipal.

Specified by:
getName in interface Principal
Returns:
the user's group identification number (GID) for this SolarisNumericGroupPrincipal

longValue

public long longValue()
Deprecated.
Return the user's group identification number (GID) for this SolarisNumericGroupPrincipal as a long.

Returns:
the user's group identification number (GID) for this SolarisNumericGroupPrincipal as a long.

isPrimaryGroup

public boolean isPrimaryGroup()
Deprecated.
Return whether this group identification number (GID) represents the primary group to which this user belongs.

Returns:
true if this group identification number (GID) represents the primary group to which this user belongs, or false otherwise.

toString

public String toString()
Deprecated.
Return a string representation of this SolarisNumericGroupPrincipal.

Specified by:
toString in interface Principal
Returns:
a string representation of this SolarisNumericGroupPrincipal.

equals

public boolean equals(Object o)
Deprecated.
Compares the specified Object with this SolarisNumericGroupPrincipal for equality. Returns true if the given object is also a SolarisNumericGroupPrincipal and the two SolarisNumericGroupPrincipals have the same group identification number (GID).

Specified by:
equals in interface Principal
Parameters:
o - Object to be compared for equality with this SolarisNumericGroupPrincipal.
Returns:
true if the specified Object is equal equal to this SolarisNumericGroupPrincipal.

hashCode

public int hashCode()
Deprecated.
Return a hash code for this SolarisNumericGroupPrincipal.

Specified by:
hashCode in interface Principal
Returns:
a hash code for this SolarisNumericGroupPrincipal.
Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


SolarisNumericUserPrincipal (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.security.auth
Class SolarisNumericUserPrincipal

java.lang.Object
    extended by com.sun.security.auth.SolarisNumericUserPrincipal
All Implemented Interfaces:
Principal, Serializable
Deprecated. As of JDK 1.4, replaced by UnixNumericUserPrincipal. This class is entirely deprecated.

public class SolarisNumericUserPrincipal
extends Object
implements Principal, Serializable

This class implements the Principal interface and represents a user's Solaris identification number (UID).

Principals such as this SolarisNumericUserPrincipal may be associated with a particular Subject to augment that Subject with an additional identity. Refer to the Subject class for more information on how to achieve this. Authorization decisions can then be based upon the Principals associated with a Subject.

See Also:
Principal, Subject, Serialized Form

Constructor Summary
SolarisNumericUserPrincipal(long name)
Deprecated. Create a SolarisNumericUserPrincipal using a long representation of the user's identification number (UID).
SolarisNumericUserPrincipal(String name)
Deprecated. Create a SolarisNumericUserPrincipal using a String representation of the user's identification number (UID).
Method Summary
boolean | equals(Object o) Deprecated. Compares the specified Object with this SolarisNumericUserPrincipal for equality.
String | getName() Deprecated. Return the user identification number (UID) for this SolarisNumericUserPrincipal.
int | hashCode() Deprecated. Return a hash code for this SolarisNumericUserPrincipal.
long | longValue() Deprecated. Return the user identification number (UID) for this SolarisNumericUserPrincipal as a long.
String | toString() Deprecated. Return a string representation of this SolarisNumericUserPrincipal.
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait

Constructor Detail

SolarisNumericUserPrincipal

public SolarisNumericUserPrincipal(String name)
Deprecated.
Create a SolarisNumericUserPrincipal using a String representation of the user's identification number (UID).

Parameters:
name - the user identification number (UID) for this user.
Throws:
NullPointerException - if the name is null.

SolarisNumericUserPrincipal

public SolarisNumericUserPrincipal(long name)
Deprecated.
Create a SolarisNumericUserPrincipal using a long representation of the user's identification number (UID).

Parameters:
name - the user identification number (UID) for this user represented as a long.
Method Detail

getName

public String getName()
Deprecated.
Return the user identification number (UID) for this SolarisNumericUserPrincipal.

Specified by:
getName in interface Principal
Returns:
the user identification number (UID) for this SolarisNumericUserPrincipal

longValue

public long longValue()
Deprecated.
Return the user identification number (UID) for this SolarisNumericUserPrincipal as a long.

Returns:
the user identification number (UID) for this SolarisNumericUserPrincipal as a long.

toString

public String toString()
Deprecated.
Return a string representation of this SolarisNumericUserPrincipal.

Specified by:
toString in interface Principal
Returns:
a string representation of this SolarisNumericUserPrincipal.

equals

public boolean equals(Object o)
Deprecated.
Compares the specified Object with this SolarisNumericUserPrincipal for equality. Returns true if the given object is also a SolarisNumericUserPrincipal and the two SolarisNumericUserPrincipals have the same user identification number (UID).

Specified by:
equals in interface Principal
Parameters:
o - Object to be compared for equality with this SolarisNumericUserPrincipal.
Returns:
true if the specified Object is equal equal to this SolarisNumericUserPrincipal.

hashCode

public int hashCode()
Deprecated.
Return a hash code for this SolarisNumericUserPrincipal.

Specified by:
hashCode in interface Principal
Returns:
a hash code for this SolarisNumericUserPrincipal.
Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


SolarisPrincipal (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.security.auth
Class SolarisPrincipal

java.lang.Object
    extended by com.sun.security.auth.SolarisPrincipal
All Implemented Interfaces:
Principal, Serializable
Deprecated. As of JDK 1.4, replaced by UnixPrincipal. This class is entirely deprecated.

public class SolarisPrincipal
extends Object
implements Principal, Serializable

This class implements the Principal interface and represents a Solaris user.

Principals such as this SolarisPrincipal may be associated with a particular Subject to augment that Subject with an additional identity. Refer to the Subject class for more information on how to achieve this. Authorization decisions can then be based upon the Principals associated with a Subject.

See Also:
Principal, Subject, Serialized Form

Constructor Summary
SolarisPrincipal(String name)
Deprecated. Create a SolarisPrincipal with a Solaris username.
Method Summary
boolean | equals(Object o) Deprecated. Compares the specified Object with this SolarisPrincipal for equality.
String | getName() Deprecated. Return the Unix username for this SolarisPrincipal.
int | hashCode() Deprecated. Return a hash code for this SolarisPrincipal.
String | toString() Deprecated. Return a string representation of this SolarisPrincipal.
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait

Constructor Detail

SolarisPrincipal

public SolarisPrincipal(String name)
Deprecated.
Create a SolarisPrincipal with a Solaris username.

Parameters:
name - the Unix username for this user.
Throws:
NullPointerException - if the name is null.
Method Detail

getName

public String getName()
Deprecated.
Return the Unix username for this SolarisPrincipal.

Specified by:
getName in interface Principal
Returns:
the Unix username for this SolarisPrincipal

toString

public String toString()
Deprecated.
Return a string representation of this SolarisPrincipal.

Specified by:
toString in interface Principal
Returns:
a string representation of this SolarisPrincipal.

equals

public boolean equals(Object o)
Deprecated.
Compares the specified Object with this SolarisPrincipal for equality. Returns true if the given object is also a SolarisPrincipal and the two SolarisPrincipals have the same username.

Specified by:
equals in interface Principal
Parameters:
o - Object to be compared for equality with this SolarisPrincipal.
Returns:
true if the specified Object is equal equal to this SolarisPrincipal.

hashCode

public int hashCode()
Deprecated.
Return a hash code for this SolarisPrincipal.

Specified by:
hashCode in interface Principal
Returns:
a hash code for this SolarisPrincipal.
Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


UnixNumericGroupPrincipal (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.security.auth
Class UnixNumericGroupPrincipal

java.lang.Object
    extended by com.sun.security.auth.UnixNumericGroupPrincipal
All Implemented Interfaces:
Principal, Serializable
public class UnixNumericGroupPrincipal
extends Object
implements Principal, Serializable

This class implements the Principal interface and represents a user's Unix group identification number (GID).

Principals such as this UnixNumericGroupPrincipal may be associated with a particular Subject to augment that Subject with an additional identity. Refer to the Subject class for more information on how to achieve this. Authorization decisions can then be based upon the Principals associated with a Subject.

See Also:
Principal, Subject, Serialized Form

Constructor Summary
UnixNumericGroupPrincipal(long name, boolean primaryGroup)
Create a UnixNumericGroupPrincipal using a long representation of the user's group identification number (GID).
UnixNumericGroupPrincipal(String name, boolean primaryGroup)
Create a UnixNumericGroupPrincipal using a String representation of the user's group identification number (GID).
Method Summary
boolean | equals(Object o) Compares the specified Object with this UnixNumericGroupPrincipal for equality.
String | getName() Return the user's group identification number (GID) for this UnixNumericGroupPrincipal.
int | hashCode() Return a hash code for this UnixNumericGroupPrincipal.
boolean | isPrimaryGroup() Return whether this group identification number (GID) represents the primary group to which this user belongs.
long | longValue() Return the user's group identification number (GID) for this UnixNumericGroupPrincipal as a long.
String | toString() Return a string representation of this UnixNumericGroupPrincipal.
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait

Constructor Detail

UnixNumericGroupPrincipal

public UnixNumericGroupPrincipal(String name,
                                 boolean primaryGroup)
Create a UnixNumericGroupPrincipal using a String representation of the user's group identification number (GID).

Parameters:
name - the user's group identification number (GID) for this user.

primaryGroup - true if the specified GID represents the primary group to which this user belongs.
Throws:
NullPointerException - if the name is null.

UnixNumericGroupPrincipal

public UnixNumericGroupPrincipal(long name,
                                 boolean primaryGroup)
Create a UnixNumericGroupPrincipal using a long representation of the user's group identification number (GID).

Parameters:
name - the user's group identification number (GID) for this user represented as a long.

primaryGroup - true if the specified GID represents the primary group to which this user belongs.
Method Detail

getName

public String getName()
Return the user's group identification number (GID) for this UnixNumericGroupPrincipal.

Specified by:
getName in interface Principal
Returns:
the user's group identification number (GID) for this UnixNumericGroupPrincipal

longValue

public long longValue()
Return the user's group identification number (GID) for this UnixNumericGroupPrincipal as a long.

Returns:
the user's group identification number (GID) for this UnixNumericGroupPrincipal as a long.

isPrimaryGroup

public boolean isPrimaryGroup()
Return whether this group identification number (GID) represents the primary group to which this user belongs.

Returns:
true if this group identification number (GID) represents the primary group to which this user belongs, or false otherwise.

toString

public String toString()
Return a string representation of this UnixNumericGroupPrincipal.

Specified by:
toString in interface Principal
Returns:
a string representation of this UnixNumericGroupPrincipal.

equals

public boolean equals(Object o)
Compares the specified Object with this UnixNumericGroupPrincipal for equality. Returns true if the given object is also a UnixNumericGroupPrincipal and the two UnixNumericGroupPrincipals have the same group identification number (GID).

Specified by:
equals in interface Principal
Parameters:
o - Object to be compared for equality with this UnixNumericGroupPrincipal.
Returns:
true if the specified Object is equal equal to this UnixNumericGroupPrincipal.

hashCode

public int hashCode()
Return a hash code for this UnixNumericGroupPrincipal.

Specified by:
hashCode in interface Principal
Returns:
a hash code for this UnixNumericGroupPrincipal.
Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


UnixNumericUserPrincipal (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.security.auth
Class UnixNumericUserPrincipal

java.lang.Object
    extended by com.sun.security.auth.UnixNumericUserPrincipal
All Implemented Interfaces:
Principal, Serializable
public class UnixNumericUserPrincipal
extends Object
implements Principal, Serializable

This class implements the Principal interface and represents a user's Unix identification number (UID).

Principals such as this UnixNumericUserPrincipal may be associated with a particular Subject to augment that Subject with an additional identity. Refer to the Subject class for more information on how to achieve this. Authorization decisions can then be based upon the Principals associated with a Subject.

See Also:
Principal, Subject, Serialized Form

Constructor Summary
UnixNumericUserPrincipal(long name)
Create a UnixNumericUserPrincipal using a long representation of the user's identification number (UID).
UnixNumericUserPrincipal(String name)
Create a UnixNumericUserPrincipal using a String representation of the user's identification number (UID).
Method Summary
boolean | equals(Object o) Compares the specified Object with this UnixNumericUserPrincipal for equality.
String | getName() Return the user identification number (UID) for this UnixNumericUserPrincipal.
int | hashCode() Return a hash code for this UnixNumericUserPrincipal.
long | longValue() Return the user identification number (UID) for this UnixNumericUserPrincipal as a long.
String | toString() Return a string representation of this UnixNumericUserPrincipal.
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait

Constructor Detail

UnixNumericUserPrincipal

public UnixNumericUserPrincipal(String name)
Create a UnixNumericUserPrincipal using a String representation of the user's identification number (UID).

Parameters:
name - the user identification number (UID) for this user.
Throws:
NullPointerException - if the name is null.

UnixNumericUserPrincipal

public UnixNumericUserPrincipal(long name)
Create a UnixNumericUserPrincipal using a long representation of the user's identification number (UID).

Parameters:
name - the user identification number (UID) for this user represented as a long.
Method Detail

getName

public String getName()
Return the user identification number (UID) for this UnixNumericUserPrincipal.

Specified by:
getName in interface Principal
Returns:
the user identification number (UID) for this UnixNumericUserPrincipal

longValue

public long longValue()
Return the user identification number (UID) for this UnixNumericUserPrincipal as a long.

Returns:
the user identification number (UID) for this UnixNumericUserPrincipal as a long.

toString

public String toString()
Return a string representation of this UnixNumericUserPrincipal.

Specified by:
toString in interface Principal
Returns:
a string representation of this UnixNumericUserPrincipal.

equals

public boolean equals(Object o)
Compares the specified Object with this UnixNumericUserPrincipal for equality. Returns true if the given object is also a UnixNumericUserPrincipal and the two UnixNumericUserPrincipals have the same user identification number (UID).

Specified by:
equals in interface Principal
Parameters:
o - Object to be compared for equality with this UnixNumericUserPrincipal.
Returns:
true if the specified Object is equal equal to this UnixNumericUserPrincipal.

hashCode

public int hashCode()
Return a hash code for this UnixNumericUserPrincipal.

Specified by:
hashCode in interface Principal
Returns:
a hash code for this UnixNumericUserPrincipal.
Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


UnixPrincipal (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.security.auth
Class UnixPrincipal

java.lang.Object
    extended by com.sun.security.auth.UnixPrincipal
All Implemented Interfaces:
Principal, Serializable
public class UnixPrincipal
extends Object
implements Principal, Serializable

This class implements the Principal interface and represents a Unix user.

Principals such as this UnixPrincipal may be associated with a particular Subject to augment that Subject with an additional identity. Refer to the Subject class for more information on how to achieve this. Authorization decisions can then be based upon the Principals associated with a Subject.

See Also:
Principal, Subject, Serialized Form

Constructor Summary
UnixPrincipal(String name)
Create a UnixPrincipal with a Unix username.
Method Summary
boolean | equals(Object o) Compares the specified Object with this UnixPrincipal for equality.
String | getName() Return the Unix username for this UnixPrincipal.
int | hashCode() Return a hash code for this UnixPrincipal.
String | toString() Return a string representation of this UnixPrincipal.
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait

Constructor Detail

UnixPrincipal

public UnixPrincipal(String name)
Create a UnixPrincipal with a Unix username.

Parameters:
name - the Unix username for this user.
Throws:
NullPointerException - if the name is null.
Method Detail

getName

public String getName()
Return the Unix username for this UnixPrincipal.

Specified by:
getName in interface Principal
Returns:
the Unix username for this UnixPrincipal

toString

public String toString()
Return a string representation of this UnixPrincipal.

Specified by:
toString in interface Principal
Returns:
a string representation of this UnixPrincipal.

equals

public boolean equals(Object o)
Compares the specified Object with this UnixPrincipal for equality. Returns true if the given object is also a UnixPrincipal and the two UnixPrincipals have the same username.

Specified by:
equals in interface Principal
Parameters:
o - Object to be compared for equality with this UnixPrincipal.
Returns:
true if the specified Object is equal equal to this UnixPrincipal.

hashCode

public int hashCode()
Return a hash code for this UnixPrincipal.

Specified by:
hashCode in interface Principal
Returns:
a hash code for this UnixPrincipal.
Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


X500Principal (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

com.sun.security.auth
Class X500Principal

java.lang.Object
    extended by com.sun.security.auth.X500Principal
All Implemented Interfaces:
Principal, Serializable
Deprecated. A new X500Principal class is available in the Java 2 platform. This X500Principal classs is entirely deprecated and is here to allow for a smooth transition to the new class.

public class X500Principal
extends Object
implements Principal, Serializable

This class represents an X.500 Principal. X500Principals have names such as, "CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US" (RFC 1779 style).

Principals such as this X500Principal may be associated with a particular Subject to augment that Subject with an additional identity. Refer to the Subject class for more information on how to achieve this. Authorization decisions can then be based upon the Principals associated with a Subject.

See Also:
Principal, Subject, X500Principal, Serialized Form

Constructor Summary
X500Principal(String name)
Deprecated. Create a X500Principal with an X.500 Name, such as "CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US" (RFC 1779 style).
Method Summary
boolean | equals(Object o) Deprecated. Compares the specified Object with this X500Principal for equality.
String | getName() Deprecated. Return the Unix username for this X500Principal.
int | hashCode() Deprecated. Return a hash code for this X500Principal.
String | toString() Deprecated. Return a string representation of this X500Principal.
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait

Constructor Detail

X500Principal

public X500Principal(String name)
Deprecated.
Create a X500Principal with an X.500 Name, such as "CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US" (RFC 1779 style).

Parameters:
name - the X.500 name
Throws:
NullPointerException - if the name is null.

IllegalArgumentException - if the name is improperly specified.
Method Detail

getName

public String getName()
Deprecated.
Return the Unix username for this X500Principal.

Specified by:
getName in interface Principal
Returns:
the Unix username for this X500Principal

toString

public String toString()
Deprecated.
Return a string representation of this X500Principal.

Specified by:
toString in interface Principal
Returns:
a string representation of this X500Principal.

equals

public boolean equals(Object o)
Deprecated.
Compares the specified Object with this X500Principal for equality.

Specified by:
equals in interface Principal
Parameters:
o - Object to be compared for equality with this X500Principal.
Returns:
true if the specified Object is equal equal to this X500Principal.

hashCode

public int hashCode()
Deprecated.
Return a hash code for this X500Principal.

Specified by:
hashCode in interface Principal
Returns:
a hash code for this X500Principal.
Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


DialogCallbackHandler (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

com.sun.security.auth.callback
Class DialogCallbackHandler

java.lang.Object
    extended by com.sun.security.auth.callback.DialogCallbackHandler
All Implemented Interfaces:
CallbackHandler
public class DialogCallbackHandler
extends Object
implements CallbackHandler

Uses a Swing dialog window to query the user for answers to authentication questions. This can be used by a JAAS application to instantiate a CallbackHandler

See Also:
javax.security.auth.callback

Constructor Summary
DialogCallbackHandler()
Creates a callback dialog with the default parent window.
DialogCallbackHandler(Component parentComponent)
Creates a callback dialog and specify the parent window.
Method Summary
 void handle(Callback[] callbacks)
Handles the specified set of callbacks.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DialogCallbackHandler

public DialogCallbackHandler()
Creates a callback dialog with the default parent window.

DialogCallbackHandler

public DialogCallbackHandler(Component parentComponent)
Creates a callback dialog and specify the parent window.

Parameters:
parentComponent - the parent window -- specify null for the default parent
Method Detail

handle

public void handle(Callback[] callbacks)
            throws UnsupportedCallbackException
Handles the specified set of callbacks.

Specified by:
handle in interface CallbackHandler
Parameters:
callbacks - the callbacks to handle
Throws:
UnsupportedCallbackException - if the callback is not an instance of NameCallback or PasswordCallback
Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


com.sun.security.auth.callback (Java Authentication and Authorization Service )

 com.sun.security.auth.callback
Classes
DialogCallbackHandler
TextCallbackHandler


com.sun.security.auth.callback (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package com.sun.security.auth.callback

Class Summary
DialogCallbackHandler | Uses a Swing dialog window to query the user for answers to authentication questions.
TextCallbackHandler | Prompts and reads from the command line for answers to authentication questions.

Overview Package Class Use Tree Index Help
JAAS


com.sun.security.auth.callback Class Hierarchy (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Hierarchy For Package com.sun.security.auth.callback

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class com.sun.security.auth.callback.DialogCallbackHandler (implements javax.security.auth.callback.CallbackHandler)
    • class com.sun.security.auth.callback.TextCallbackHandler (implements javax.security.auth.callback.CallbackHandler)
Overview Package Class Use Tree Index Help
JAAS


Uses of Package com.sun.security.auth.callback (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Uses of Package
com.sun.security.auth.callback

No usage of com.sun.security.auth.callback

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


TextCallbackHandler (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

com.sun.security.auth.callback
Class TextCallbackHandler

java.lang.Object
    extended by com.sun.security.auth.callback.TextCallbackHandler
All Implemented Interfaces:
CallbackHandler
public class TextCallbackHandler
extends Object
implements CallbackHandler

Prompts and reads from the command line for answers to authentication questions. This can be used by a JAAS application to instantiate a CallbackHandler

See Also:
javax.security.auth.callback

Constructor Summary
TextCallbackHandler()
Creates a callback handler that prompts and reads from the command line for answers to authentication questions.
Method Summary
 void handle(Callback[] callbacks)
Handles the specified set of callbacks.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

TextCallbackHandler

public TextCallbackHandler()

Creates a callback handler that prompts and reads from the command line for answers to authentication questions. This can be used by JAAS applications to instantiate a CallbackHandler.

Method Detail

handle

public void handle(Callback[] callbacks)
            throws IOException,
                   UnsupportedCallbackException
Handles the specified set of callbacks.

Specified by:
handle in interface CallbackHandler
Parameters:
callbacks - the callbacks to handle
Throws:
IOException - if an input or output error occurs.
UnsupportedCallbackException - if the callback is not an instance of NameCallback or PasswordCallback
Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Uses of Class com.sun.security.auth.callback.DialogCallbackHandler (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.security.auth.callback.DialogCallbackHandler

No usage of com.sun.security.auth.callback.DialogCallbackHandler

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.security.auth.callback.TextCallbackHandler (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.security.auth.callback.TextCallbackHandler

No usage of com.sun.security.auth.callback.TextCallbackHandler

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.security.auth.NTDomainPrincipal (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.security.auth.NTDomainPrincipal

No usage of com.sun.security.auth.NTDomainPrincipal

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.security.auth.NTNumericCredential (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.security.auth.NTNumericCredential

No usage of com.sun.security.auth.NTNumericCredential

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.security.auth.NTSid (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.security.auth.NTSid

Packages that use NTSid
com.sun.security.auth

Uses of NTSid in com.sun.security.auth

Subclasses of NTSid in com.sun.security.auth
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 Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.security.auth.NTSidDomainPrincipal (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.security.auth.NTSidDomainPrincipal

No usage of com.sun.security.auth.NTSidDomainPrincipal

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.security.auth.NTSidGroupPrincipal (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.security.auth.NTSidGroupPrincipal

No usage of com.sun.security.auth.NTSidGroupPrincipal

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.security.auth.NTSidPrimaryGroupPrincipal (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.security.auth.NTSidPrimaryGroupPrincipal

No usage of com.sun.security.auth.NTSidPrimaryGroupPrincipal

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.security.auth.NTSidUserPrincipal (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.security.auth.NTSidUserPrincipal

No usage of com.sun.security.auth.NTSidUserPrincipal

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.security.auth.NTUserPrincipal (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.security.auth.NTUserPrincipal

No usage of com.sun.security.auth.NTUserPrincipal

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.security.auth.PolicyFile (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.security.auth.PolicyFile

No usage of com.sun.security.auth.PolicyFile

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


Uses of Interface com.sun.security.auth.PrincipalComparator (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.security.auth.PrincipalComparator

No usage of com.sun.security.auth.PrincipalComparator

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.security.auth.SolarisNumericGroupPrincipal (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.security.auth.SolarisNumericGroupPrincipal

No usage of com.sun.security.auth.SolarisNumericGroupPrincipal

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.security.auth.SolarisNumericUserPrincipal (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.security.auth.SolarisNumericUserPrincipal

No usage of com.sun.security.auth.SolarisNumericUserPrincipal

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.security.auth.SolarisPrincipal (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.security.auth.SolarisPrincipal

No usage of com.sun.security.auth.SolarisPrincipal

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.security.auth.UnixNumericGroupPrincipal (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.security.auth.UnixNumericGroupPrincipal

No usage of com.sun.security.auth.UnixNumericGroupPrincipal

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.security.auth.UnixNumericUserPrincipal (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.security.auth.UnixNumericUserPrincipal

No usage of com.sun.security.auth.UnixNumericUserPrincipal

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.security.auth.UnixPrincipal (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.security.auth.UnixPrincipal

No usage of com.sun.security.auth.UnixPrincipal

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.security.auth.X500Principal (Java Authentication and Authorization Service )

xs Uses of Class com.sun.security.auth.X500Principal (Java Authentication and Authorization Service )
Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.security.auth.X500Principal

No usage of com.sun.security.auth.X500Principal

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


ConfigFile (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

com.sun.security.auth.login
Class ConfigFile

java.lang.Object
    extended by javax.security.auth.login.Configuration
        extended by com.sun.security.auth.login.ConfigFile
public class ConfigFile
extends Configuration

This class represents a default implementation for javax.security.auth.login.Configuration.

This object stores the runtime login configuration representation, and is the amalgamation of multiple static login configurations that resides in files. The algorithm for locating the login configuration file(s) and reading their information into this Configuration object is:

  1. Loop through the java.security.Security properties, login.config.url.1, login.config.url.2, ..., login.config.url.X. These properties are set in the Java security properties file, which is located in the file named <JAVA_HOME>/lib/security/java.security, where <JAVA_HOME> refers to the directory where the JDK was installed. Each property value specifies a URL pointing to a login configuration file to be loaded. Read in and load each configuration.
  2. The java.lang.System property java.security.auth.login.config may also be set to a URL pointing to another login configuration file (which is the case when a user uses the -D switch at runtime). If this property is defined, and its use is allowed by the security property file (the Security property, policy.allowSystemProperty is set to true), also load that login configuration.
  3. If the java.security.auth.login.config property is defined using "==" (rather than "="), then ignore all other specified login configurations and only load this configuration.
  4. If no system or security properties were set, try to read from the file, ${user.home}/.java.login.config, where ${user.home} is the value represented by the "user.home" System property.

The configuration syntax supported by this implementation is exactly that syntax specified in the javax.security.auth.login.Configuration class.

See Also:
LoginContext

Constructor Summary
ConfigFile()
Create a new Configuration object.
Method Summary
AppConfigurationEntry[] | getAppConfigurationEntry(String applicationName) Retrieve an entry from the Configuration using an application name as an index.
void | refresh() Refresh and reload the Configuration by re-reading all of the login configurations.
Methods inherited from class javax.security.auth.login.Configuration
getConfiguration, setConfiguration
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ConfigFile

public ConfigFile()
Create a new Configuration object.

Method Detail

getAppConfigurationEntry

public AppConfigurationEntry[] getAppConfigurationEntry(String applicationName)
Retrieve an entry from the Configuration using an application name as an index.

Parameters:
applicationName - the name used to index the Configuration.
Returns:
an array of AppConfigurationEntries which correspond to the stacked configuration of LoginModules for this application, or null if this application has no configured LoginModules.

refresh

public void refresh()
Refresh and reload the Configuration by re-reading all of the login configurations.

Throws:
SecurityException - if the caller does not have permission to refresh the Configuration.
Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


com.sun.security.auth.login (Java Authentication and Authorization Service )

 com.sun.security.auth.login
Classes
ConfigFile


com.sun.security.auth.login (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package com.sun.security.auth.login

Class Summary
ConfigFile This class represents a default implementation for javax.security.auth.login.Configuration.

Overview Package Class Use Tree Index Help
JAAS


com.sun.security.auth.login Class Hierarchy (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Hierarchy For Package com.sun.security.auth.login

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class javax.security.auth.login.Configuration
      • class com.sun.security.auth.login.ConfigFile
Overview Package Class Use Tree Index Help
JAAS


Uses of Package com.sun.security.auth.login (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Uses of Package
com.sun.security.auth.login

No usage of com.sun.security.auth.login

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.security.auth.login.ConfigFile (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.security.auth.login.ConfigFile

No usage of com.sun.security.auth.login.ConfigFile

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


JndiLoginModule (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

com.sun.security.auth.module
Class JndiLoginModule

java.lang.Object
    extended by com.sun.security.auth.module.JndiLoginModule
All Implemented Interfaces:
LoginModule
public class JndiLoginModule
extends Object
implements LoginModule

The module prompts for a username and password and then verifies the password against the password stored in a directory service configured under JNDI.

This LoginModule interoperates with any conformant JNDI service provider. To direct this LoginModule to use a specific JNDI service provider, two options must be specified in the login Configuration for this LoginModule.

    user.provider.url=name_service_url
    group.provider.url=name_service_url
name_service_url specifies the directory service and path where this LoginModule can access the relevant user and group information. Because this LoginModule only performs one-level searches to find the relevant user information, the URL must point to a directory one level above where the user and group information is stored in the directory service. For example, to instruct this LoginModule to contact a NIS server, the following URLs must be specified:
    user.provider.url="nis://NISServerHostName/NISDomain/user"
    group.provider.url="nis://NISServerHostName/NISDomain/system/group"
NISServerHostName specifies the server host name of the NIS server (for example, nis.sun.com, and NISDomain specifies the domain for that NIS server (for example, jaas.sun.com. To contact an LDAP server, the following URLs must be specified:
    user.provider.url="ldap://LDAPServerHostName/LDAPName"
    group.provider.url="ldap://LDAPServerHostName/LDAPName"
LDAPServerHostName specifies the server host name of the LDAP server, which may include a port number (for example, ldap.sun.com:389), and LDAPName specifies the entry name in the LDAP directory (for example, ou=People,o=Sun,c=US and ou=Groups,o=Sun,c=US for user and group information, respectively).

The format in which the user's information must be stored in the directory service is specified in RFC 2307. Specifically, this LoginModule will search for the user's entry in the directory service using the user's uid attribute, where uid=username. If the search succeeds, this LoginModule will then obtain the user's encrypted password from the retrieved entry using the userPassword attribute. This LoginModule assumes that the password is stored as a byte array, which when converted to a String, has the following format:

    "{crypt}encrypted_password"
The LDAP directory server must be configured to permit read access to the userPassword attribute. If the user entered a valid username and password, this LoginModule associates a UnixPrincipal, UnixNumericUserPrincipal, and the relevant UnixNumericGroupPrincipals with the Subject.

This LoginModule also recognizes the following Configuration options:

    debug          if, true, debug messages are output to System.out.

    useFirstPass   if, true, this LoginModule retrieves the
                   username and password from the module's shared state,
                   using "javax.security.auth.login.name" and
                   "javax.security.auth.login.password" as the respective
                   keys.  The retrieved values are used for authentication.
                   If authentication fails, no attempt for a retry is made,
                   and the failure is reported back to the calling
                   application.

    tryFirstPass   if, true, this LoginModule retrieves the
                   the username and password from the module's shared state,
                   using "javax.security.auth.login.name" and
                   "javax.security.auth.login.password" as the respective
                   keys.  The retrieved values are used for authentication.
                   If authentication fails, the module uses the
                   CallbackHandler to retrieve a new username and password,
                   and another attempt to authenticate is made.
                   If the authentication fails, the failure is reported
                   back to the calling application.

    storePass      if, true, this LoginModule stores the username and password
                   obtained from the CallbackHandler in the module's
                   shared state, using "javax.security.auth.login.name" and
                   "javax.security.auth.login.password" as the respective
                   keys.  This is not performed if existing values already
                   exist for the username and password in the shared state,
                   or if authentication fails.

    clearPass     if, true, this LoginModule clears the
                  username and password stored in the module's shared state
                  after both phases of authentication (login and commit)
                  have completed.

Field Summary
String | GROUP_PROVIDER
String | USER_PROVIDER JNDI Provider
Constructor Summary
JndiLoginModule()
Method Summary
boolean | abort() This method is called if the LoginContext's overall authentication failed.
boolean | commit() Abstract method to commit the authentication process (phase 2).
void | initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) Initialize this LoginModule.
boolean | login() Prompt for username and password.
boolean | logout() Logout a user.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

USER_PROVIDER

public final String USER_PROVIDER
JNDI Provider

See Also:
Constant Field Values

GROUP_PROVIDER

public final String GROUP_PROVIDER
See Also:
Constant Field Values
Constructor Detail

JndiLoginModule

public JndiLoginModule()
Method Detail

initialize

public void initialize(Subject subject,
                       CallbackHandler callbackHandler,
                       Map sharedState,
                       Map options)
Initialize this LoginModule.

Specified by:
initialize in interface LoginModule
Parameters:
subject - the Subject to be authenticated.

callbackHandler - a CallbackHandler for communicating with the end user (prompting for usernames and passwords, for example).

sharedState - shared LoginModule state.

options - options specified in the login Configuration for this particular LoginModule.

login

public boolean login()
              throws LoginException

Prompt for username and password. Verify the password against the relevant name service.

Specified by:
login in interface LoginModule
Returns:
true always, since this LoginModule should not be ignored.
Throws:
FailedLoginException - if the authentication fails.

LoginException - if this LoginModule is unable to perform the authentication.

commit

public boolean commit()
               throws LoginException
Abstract method to commit the authentication process (phase 2).

This method is called if the LoginContext's overall authentication succeeded (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules succeeded).

If this LoginModule's own authentication attempt succeeded (checked by retrieving the private state saved by the login method), then this method associates a UnixPrincipal with the Subject located in the LoginModule. If this LoginModule's own authentication attempted failed, then this method removes any state that was originally saved.

Specified by:
commit in interface LoginModule
Returns:
true if this LoginModule's own login and commit attempts succeeded, or false otherwise.
Throws:
LoginException - if the commit fails

abort

public boolean abort()
              throws LoginException

This method is called if the LoginContext's overall authentication failed. (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules did not succeed).

If this LoginModule's own authentication attempt succeeded (checked by retrieving the private state saved by the login and commit methods), then this method cleans up any state that was originally saved.

Specified by:
abort in interface LoginModule
Returns:
false if this LoginModule's own login and/or commit attempts failed, and true otherwise.
Throws:
LoginException - if the abort fails.

logout

public boolean logout()
               throws LoginException
Logout a user.

This method removes the Principals that were added by the commit method.

Specified by:
logout in interface LoginModule
Returns:
true in all cases since this LoginModule should not be ignored.
Throws:
LoginException - if the logout fails.
Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


KeyStoreLoginModule (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.security.auth.module
Class KeyStoreLoginModule

java.lang.Object
    extended by com.sun.security.auth.module.KeyStoreLoginModule
All Implemented Interfaces:
LoginModule
public class KeyStoreLoginModule
extends Object
implements LoginModule

Provides a JAAS login module that prompts for a key store alias and populates the subject with the alias's principal and credentials. Stores an X500Principal for the subject distinguished name of the first certificate in the alias's credentials in the subject's principals, the alias's certificate path in the subject's public credentials, and a X500PrivateCredential whose certificate is the first certificate in the alias's certificate path and whose private key is the alias's private key in the subject's private credentials.

Recognizes the following options in the JAAS authentication policy file:

keyStoreURL
A URL that specifies the location of the key store file. Defaults to the .keystore file in the directory specified by the java.home system property.
keyStoreType
The key store type. If not specified, defaults to the result of calling KeyStore.getDefaultType().
keyStoreProvider
The key store provider. If not specified, uses the standard search order to find the provider.
keyStoreAlias
The alias in the key store to login as. Required when no callback handler is provided. No default value.
keyStorePasswordURL
A URL that specifies the location of the key store password. Required when no callback handler is provided. No default value.
privateKeyPasswordURL
A URL that specifies the location of the specific private key password needed to access the private key for this alias. The keystore password is used if this value is not specified.

Constructor Summary
KeyStoreLoginModule()
Method Summary
boolean | abort() This method is called if the LoginContext's overall authentication failed.
boolean | commit() Abstract method to commit the authentication process (phase 2).
void | initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) Initialize this LoginModule.
boolean | login() Authenticate the user .
boolean | logout() Logout a user.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

KeyStoreLoginModule

public KeyStoreLoginModule()
Method Detail

initialize

public void initialize(Subject subject,
                       CallbackHandler callbackHandler,
                       Map sharedState,
                       Map options)
Initialize this LoginModule.

Specified by:
initialize in interface LoginModule
Parameters:
subject - the Subject to be authenticated.

callbackHandler - a CallbackHandler for communicating with the end user (prompting for usernames and passwords, for example).

sharedState - shared LoginModule state.

options - options specified in the login Configuration for this particular LoginModule.

login

public boolean login()
              throws LoginException
Authenticate the user .

Prompt the user for the Keystore alias and the password. Retrieve the alias's principal and credentials from the Keystore.

Specified by:
login in interface LoginModule
Returns:
true in all cases (this LoginModule should not be ignored).
Throws:
FailedLoginException - if the authentication fails.

LoginException

commit

public boolean commit()
               throws LoginException
Abstract method to commit the authentication process (phase 2).

This method is called if the LoginContext's overall authentication succeeded (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules succeeded).

If this LoginModule's own authentication attempt succeeded (checked by retrieving the private state saved by the login method), then this method associates a X500Principal for the subject distinguished name of the first certificate in the alias's credentials in the subject's principals,the alias's certificate path in the subject's public credentials, and aX500PrivateCredential whose certificate is the first certificate in the alias's certificate path and whose private key is the alias's private key in the subject's private credentials. If this LoginModule's own authentication attempted failed, then this method removes any state that was originally saved.

Specified by:
commit in interface LoginModule
Returns:
true if this LoginModule's own login and commit attempts succeeded, or false otherwise.
Throws:
LoginException - if the commit fails

abort

public boolean abort()
              throws LoginException

This method is called if the LoginContext's overall authentication failed. (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules did not succeed).

If this LoginModule's own authentication attempt succeeded (checked by retrieving the private state saved by the login and commit methods), then this method cleans up any state that was originally saved.

Specified by:
abort in interface LoginModule
Returns:
false if this LoginModule's own login and/or commit attempts failed, and true otherwise.
Throws:
LoginException - if the abort fails.

logout

public boolean logout()
               throws LoginException
Logout a user.

This method removes the Principals, public credentials and the private credentials that were added by the commit method.

Specified by:
logout in interface LoginModule
Returns:
true in all cases since this LoginModule should not be ignored.
Throws:
LoginException - if the logout fails.
Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


Krb5LoginModule (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.security.auth.module
Class Krb5LoginModule

java.lang.Object
    extended by com.sun.security.auth.module.Krb5LoginModule
All Implemented Interfaces:
LoginModule
public class Krb5LoginModule
extends Object
implements LoginModule

This LoginModule authenticates users using Kerberos protocols.

Configuration entry for Krb5LoginModule has several options that control the authentication process and additions to the Subject's private credential set. Irrespective of the options, only when commit is called the Subject's principal set and private credentials set are updated. When commit is called the KerberosPrincipal is added to the Subject's principal set and KerberosTicket will be added to the Subject's private credentials.

If the configuration entry for KerberosLoginModule has the option storeKey set to true , then KerberosKey will also be added to the subject's private credentials. KerberosKey, the principal's key will be obtained either from the keytab or derived from user's password

This LoginModule recogonizes the doNotPrompt option. If set to true the user will not be prompted for the password.

The user can specify the location of the ticket cache by using the option ticketCache in the configuration entry.

The user can specify the keytab location by using the option keyTab in the configuraion entry.

The principal name can be specified in the configuration entry by using the option principal The principal name can either be a simple user name or a service name such as host/mission.eng.sun.com

The following are the list of configuration options supported for Krb5LoginModule

useTicketCache: Set this to true, if you want the TGT to be obtained from the ticket cache. Set this option to false if you do not want this module to use the ticket cache. (Default is False). This module will search for the tickect cache in the following locations: For Windows 2000, it will use Local Security Authority (LSA) API to get the TGT. On Solaris and Linux it will look for the ticket cache in /tmp/krb5cc_uid where the uid is numeric user identifier. If the ticket cache is not available in either of the above locations, or if we are on a different WIndows platform, it will look for the cache as {user.home}{file.separator}krb5cc_{user.name}. You can override the ticket cache location by using ticketCache

ticketCache: Set this to the name of the ticket cache that contains user's TGT. If this is set, useTicketcache must also be set to true; Otherwise a configuration error will be returned.

doNotPrompt: Set this to true if you do not want to be prompted for the password if credentials can not be obtained from the cache or keytab.(Default is false) If set to true authentication will fail if credentials can not be obtained from the cache or keytab.

useKeyTab:Set this to true if you want the module to get the principal's key from the the keytab.(default value is False) If keyatb is not set then the module will locate the keytab from the Kerberos configuration file. If it is not specifed in the Kerberos configuration file then it will look for the file {user.home}{file.separator}krb5.keytab.

keyTab: Set this to the file name of the keytab to get principal's secret key.

storeKey: Set this to True to if you want the principal's key to be stored in the Subject's private credentials.

principal: The name of the principal that should be used. It could be simple username such as "testuser" or a service name such as "host/testhost.eng.sun.com" . You can use principal option to set the principal when there are credentials for multiple principals in the keyTab or when you want a specific ticket cache only.

This LoginModule also recognizes the following additional Configuration options that enable you to share username and passwords across different authentication modules:

    useFirstPass   if, true, this LoginModule retrieves the
                   username and password from the module's shared state,
                   using "javax.security.auth.login.name" and
                   "javax.security.auth.login.password" as the respective
                   keys. The retrieved values are used for authentication.
                   If authentication fails, no attempt for a retry
                   is made, and the failure is reported back to the
                   calling application.

    tryFirstPass   if, true, this LoginModule retrieves the
                   the username and password from the module's shared
                   state using "javax.security.auth.login.name" and
                   "javax.security.auth.login.password" as the respective
                   keys.  The retrieved values are used for
                   authentication.
                   If authentication fails, the module uses the
                   CallbackHandler to retrieve a new username
                   and password, and another attempt to authenticate
                   is made. If the authentication fails,
                   the failure is reported back to the calling application

    storePass      if, true, this LoginModule stores the username and
                   password obtained from the CallbackHandler in the
                   modules shared state, using
                   "javax.security.auth.login.name" and
                   "javax.security.auth.login.password" as the respective
                   keys.  This is not performed if existing values already
                   exist for the username and password in the shared
                   state, or if authentication fails.

    clearPass     if, true, this LoginModule clears the
                  username and password stored in the module's shared
                  state  after both phases of authentication
                  (login and commit)  have completed.

Examples of some configuration values for Krb5LoginModule in JAAS config file and the results are:

    doNotPrompt=true;

This is an illegal combination since useTicketCache is not set and the user can not be prompted for the password.

    ticketCache = < filename >;

This is an illegal combination since useTicketCache is not set to true and the ticketCache is set. A configuratin error will occur.

    storeKey=true
useTicketCache = true
doNotPrompt=true;;

This is an illegal combination since storeKey is set to true but the key can not be obtained either by prompting the user or from the keytab.A configuratin error will occur.

    keyTab = < filename > doNotPrompt=true ;

This is an illegal combination since useKeyTab is not set to true and the keyTab is set. A configuration error will occur.

    debug=true

Prompt the user for the principal name and the password. Use the authentication exchange to get TGT from the KDC and populate the Subject with the principal and TGT. Output debug messages.

    useTicketCache = true doNotPrompt=true;

Check the default cache for TGT and populate the Subject with the principal and TGT. If the TGT is not available, do not prompt the user, instead fail the authentication.

    principal=< name >useTicketCache = true doNotPrompt=true;

Get the TGT from the default cache for the principal and populate the Subject's principal and private creds set. If ticket cache is not available or does not contain the principal's TGT authentication will fail.

    useTicketCache = true
ticketCache=< file name >useKeyTab = true
 keyTab=< keytab filename >
principal = < principal name >
doNotPrompt=true;

Search the cache for the principal's TGT. If it is not available use the key in the keytab to perform authentication exchange with the KDC and acquire the TGT. The Subject will be populated with the principal and the TGT. If the key is not available or valid then authentication will fail.

    useTicketCache = true ticketCache=< file name >

The TGT will be obtained from the cache specified. The Kerberos principal name used will be the principal name in the Ticket cache. If the TGT is not available in the ticket cache the user will be prompted for the principal name and the password. The TGT will be obtained using the authentication exchange with the KDC. The Subject will be populated with the TGT.

    useKeyTab = true
keyTab=< keytab filename >
principal= < principal name >
storeKey=true;

The key for the principal will be retrieved from the keytab. If the key is not available in the keytab the user will be prompted for the principal's password. The Subject will be populated with the principal's key either from the keytab or derived from the password entered.

    useKeyTab = true
keyTab=< keytabname >
storeKey=true
doNotPrompt=true;

The user will be prompted for the service principal name. If the principal's longterm key is available in the keytab , it will be added to the Subject's private credentials. An authentication exchange will be attempted with the principal name and the key from the Keytab. If successful the TGT will be added to the Subject's private credentials set. Otherwise the authentication will fail.

    useKeyTab = true
 keyTab=< file name > storeKey=true
 principal= < principal name >
 useTicketCache=true
 ticketCache=< file name >;

The principal's key will be retrieved from the keytab and added to the Subject's private credentials. If the key is not available, the user will be prompted for the password; the key derived from the password will be added to the Subject's private credentials set. The client's TGT will be retrieved from the ticket cache and added to the Subject's private credentials. If the TGT is not available in the ticket cache, it will be obtained using the authentication exchange and added to the Subject's private credentials.

Constructor Summary
Krb5LoginModule()
Method Summary
boolean | abort() This method is called if the LoginContext's overall authentication failed.
boolean | commit() This method is called if the LoginContext's overall authentication succeeded (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules succeeded).
void | initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) Initialize this LoginModule.
boolean | login() Authenticate the user
boolean | logout() Logout the user.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

Krb5LoginModule

public Krb5LoginModule()
Method Detail

initialize

public void initialize(Subject subject,
                       CallbackHandler callbackHandler,
                       Map sharedState,
                       Map options)
Initialize this LoginModule.

Specified by:
initialize in interface LoginModule
Parameters:
subject - the Subject to be authenticated.

callbackHandler - a CallbackHandler for communication with the end user (prompting for usernames and passwords, for example).

sharedState - shared LoginModule state.

options - options specified in the login Configuration for this particular LoginModule.

login

public boolean login()
              throws LoginException
Authenticate the user

Specified by:
login in interface LoginModule
Returns:
true in all cases since this LoginModule should not be ignored.
Throws:
FailedLoginException - if the authentication fails.

LoginException - if this LoginModule is unable to perform the authentication.

commit

public boolean commit()
               throws LoginException

This method is called if the LoginContext's overall authentication succeeded (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules succeeded).

If this LoginModule's own authentication attempt succeeded (checked by retrieving the private state saved by the login method), then this method associates a Krb5Principal with the Subject located in the LoginModule. It adds Kerberos Credentials to the the Subject's private credentials set. If this LoginModule's own authentication attempted failed, then this method removes any state that was originally saved.

Specified by:
commit in interface LoginModule
Returns:
true if this LoginModule's own login and commit attempts succeeded, or false otherwise.
Throws:
LoginException - if the commit fails.

abort

public boolean abort()
              throws LoginException

This method is called if the LoginContext's overall authentication failed. (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules did not succeed).

If this LoginModule's own authentication attempt succeeded (checked by retrieving the private state saved by the login and commit methods), then this method cleans up any state that was originally saved.

Specified by:
abort in interface LoginModule
Returns:
false if this LoginModule's own login and/or commit attempts failed, and true otherwise.
Throws:
LoginException - if the abort fails.

logout

public boolean logout()
               throws LoginException
Logout the user.

This method removes the Krb5Principal that was added by the commit method.

Specified by:
logout in interface LoginModule
Returns:
true in all cases since this LoginModule should not be ignored.
Throws:
LoginException - if the logout fails.
Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NTLoginModule (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.security.auth.module
Class NTLoginModule

java.lang.Object
    extended by com.sun.security.auth.module.NTLoginModule
All Implemented Interfaces:
LoginModule
public class NTLoginModule
extends Object
implements LoginModule

This LoginModule renders a user's NT security information as some number of Principals and associates them with a Subject.

This LoginModule recognizes the debug option. If set to true in the login Configuration, debug messages will be output to the output stream, System.out.

This LoginModule also recognizes the debugNative option. If set to true in the login Configuration, debug messages from the native component of the module will be output to the output stream, System.out.

See Also:
LoginModule

Constructor Summary
NTLoginModule()
Method Summary
boolean | abort() This method is called if the LoginContext's overall authentication failed.
boolean | commit() This method is called if the LoginContext's overall authentication succeeded (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules succeeded).
void | initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) Initialize this LoginModule.
boolean | login() Import underlying NT system identity information.
boolean | logout() Logout the user.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

NTLoginModule

public NTLoginModule()
Method Detail

initialize

public void initialize(Subject subject,
                       CallbackHandler callbackHandler,
                       Map sharedState,
                       Map options)
Initialize this LoginModule.

Specified by:
initialize in interface LoginModule
Parameters:
subject - the Subject to be authenticated.

callbackHandler - a CallbackHandler for communicating with the end user (prompting for usernames and passwords, for example). This particular LoginModule only extracts the underlying NT system information, so this parameter is ignored.

sharedState - shared LoginModule state.

options - options specified in the login Configuration for this particular LoginModule.

login

public boolean login()
              throws LoginException
Import underlying NT system identity information.

Specified by:
login in interface LoginModule
Returns:
true in all cases since this LoginModule should not be ignored.
Throws:
FailedLoginException - if the authentication fails.

LoginException - if this LoginModule is unable to perform the authentication.

commit

public boolean commit()
               throws LoginException

This method is called if the LoginContext's overall authentication succeeded (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules succeeded).

If this LoginModule's own authentication attempt succeeded (checked by retrieving the private state saved by the login method), then this method associates some number of various Principals with the Subject located in the LoginModuleContext. If this LoginModule's own authentication attempted failed, then this method removes any state that was originally saved.

Specified by:
commit in interface LoginModule
Returns:
true if this LoginModule's own login and commit attempts succeeded, or false otherwise.
Throws:
LoginException - if the commit fails.

abort

public boolean abort()
              throws LoginException

This method is called if the LoginContext's overall authentication failed. (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules did not succeed).

If this LoginModule's own authentication attempt succeeded (checked by retrieving the private state saved by the login and commit methods), then this method cleans up any state that was originally saved.

Specified by:
abort in interface LoginModule
Returns:
false if this LoginModule's own login and/or commit attempts failed, and true otherwise.
Throws:
LoginException - if the abort fails.

logout

public boolean logout()
               throws LoginException
Logout the user.

This method removes the NTUserPrincipal, NTDomainPrincipal, NTSidUserPrincipal, NTSidDomainPrincipal, NTSidGroupPrincipals, and NTSidPrimaryGroupPrincipal that may have been added by the commit method.

Specified by:
logout in interface LoginModule
Returns:
true in all cases since this LoginModule should not be ignored.
Throws:
LoginException - if the logout fails.
Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


NTSystem (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.security.auth.module
Class NTSystem

java.lang.Object
    extended by com.sun.security.auth.module.NTSystem
public class NTSystem
extends Object

This class implementation retrieves and makes available NT security information for the current user.

Constructor Summary
NTSystem()
Instantiate an NTSystem and load the native library to access the underlying system information.
Method Summary
String | getDomain() Get the domain for the current NT user.
String | getDomainSID() Get a printable SID for the current NT user's domain.
String[] | getGroupIDs() Get the printable group SIDs for the current NT user.
long | getImpersonationToken() Get an impersonation token for the current NT user.
String | getName() Get the username for the current NT user.
String | getPrimaryGroupID() Get a printable primary group SID for the current NT user.
String | getUserSID() Get a printable SID for the current NT user.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

NTSystem

public NTSystem()
Instantiate an NTSystem and load the native library to access the underlying system information.

Method Detail

getName

public String getName()
Get the username for the current NT user.

Returns:
the username for the current NT user.

getDomain

public String getDomain()
Get the domain for the current NT user.

Returns:
the domain for the current NT user.

getDomainSID

public String getDomainSID()
Get a printable SID for the current NT user's domain.

Returns:
a printable SID for the current NT user's domain.

getUserSID

public String getUserSID()
Get a printable SID for the current NT user.

Returns:
a printable SID for the current NT user.

getPrimaryGroupID

public String getPrimaryGroupID()
Get a printable primary group SID for the current NT user.

Returns:
the primary group SID for the current NT user.

getGroupIDs

public String[] getGroupIDs()
Get the printable group SIDs for the current NT user.

Returns:
the group SIDs for the current NT user.

getImpersonationToken

public long getImpersonationToken()
Get an impersonation token for the current NT user.

Returns:
an impersonation token for the current NT user.
Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


com.sun.security.auth.module (Java Authentication and Authorization Service )

 com.sun.security.auth.module
Classes
JndiLoginModule
KeyStoreLoginModule
Krb5LoginModule
NTLoginModule
NTSystem
SolarisLoginModule
SolarisSystem
UnixLoginModule
UnixSystem


com.sun.security.auth.module (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package com.sun.security.auth.module

Class Summary
JndiLoginModule | The module prompts for a username and password and then verifies the password against the password stored in a directory service configured under JNDI.
KeyStoreLoginModule | Provides a JAAS login module that prompts for a key store alias and populates the subject with the alias's principal and credentials.
Krb5LoginModule | This LoginModule authenticates users using Kerberos protocols.
NTLoginModule | This LoginModule renders a user's NT security information as some number of Principals and associates them with a Subject.
NTSystem | This class implementation retrieves and makes available NT security information for the current user.
SolarisLoginModule | Deprecated. As of JDK1.4, replaced by com.sun.security.auth.module.UnixLoginModule.
SolarisSystem | This class implementation retrieves and makes available Solaris UID/GID/groups information for the current user.
UnixLoginModule | This LoginModule imports a user's Unix Principal information (UnixPrincipal, UnixNumericUserPrincipal, and UnixNumericGroupPrincipal) and associates them with the current Subject.
UnixSystem | This class implementation retrieves and makes available Unix UID/GID/groups information for the current user.

Overview Package Class Use Tree Index Help
JAAS
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


com.sun.security.auth.module Class Hierarchy (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Hierarchy For Package com.sun.security.auth.module

Package Hierarchies:
All Packages

Class Hierarchy

  • class java.lang.Object
    • class com.sun.security.auth.module.JndiLoginModule (implements javax.security.auth.spi.LoginModule)
    • class com.sun.security.auth.module.KeyStoreLoginModule (implements javax.security.auth.spi.LoginModule)
    • class com.sun.security.auth.module.Krb5LoginModule (implements javax.security.auth.spi.LoginModule)
    • class com.sun.security.auth.module.NTLoginModule (implements javax.security.auth.spi.LoginModule)
    • class com.sun.security.auth.module.NTSystem
    • class com.sun.security.auth.module.SolarisLoginModule (implements javax.security.auth.spi.LoginModule)
    • class com.sun.security.auth.module.SolarisSystem
    • class com.sun.security.auth.module.UnixLoginModule (implements javax.security.auth.spi.LoginModule)
    • class com.sun.security.auth.module.UnixSystem
Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


Uses of Package com.sun.security.auth.module (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Uses of Package
com.sun.security.auth.module

No usage of com.sun.security.auth.module

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


SolarisLoginModule (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.security.auth.module
Class SolarisLoginModule

java.lang.Object
    extended by com.sun.security.auth.module.SolarisLoginModule
All Implemented Interfaces:
LoginModule
Deprecated. As of JDK1.4, replaced by com.sun.security.auth.module.UnixLoginModule. This LoginModule is entirely deprecated and is here to allow for a smooth transition to the new UnixLoginModule.

public class SolarisLoginModule
extends Object
implements LoginModule

This LoginModule imports a user's Solaris Principal information (SolarisPrincipal, SolarisNumericUserPrincipal, and SolarisNumericGroupPrincipal) and associates them with the current Subject.

This LoginModule recognizes the debug option. If set to true in the login Configuration, debug messages will be output to the output stream, System.out.

Constructor Summary
SolarisLoginModule()
Deprecated.
Method Summary
boolean | abort() Deprecated. Abort the authentication (second phase).
boolean | commit() Deprecated. Commit the authentication (second phase).
void | initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) Deprecated. Initialize this LoginModule.
boolean | login() Deprecated. Authenticate the user (first phase).
boolean | logout() Deprecated. Logout the user
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

SolarisLoginModule

public SolarisLoginModule()
Deprecated.
Method Detail

initialize

public void initialize(Subject subject,
                       CallbackHandler callbackHandler,
                       Map sharedState,
                       Map options)
Deprecated.
Initialize this LoginModule.

Specified by:
initialize in interface LoginModule
Parameters:
subject - the Subject to be authenticated.

callbackHandler - a CallbackHandler for communicating with the end user (prompting for usernames and passwords, for example).

sharedState - shared LoginModule state.

options - options specified in the login Configuration for this particular LoginModule.

login

public boolean login()
              throws LoginException
Deprecated.
Authenticate the user (first phase).

The implementation of this method attempts to retrieve the user's Solaris Subject information by making a native Solaris system call.

Specified by:
login in interface LoginModule
Returns:
true in all cases (this LoginModule should not be ignored).
Throws:
FailedLoginException - if attempts to retrieve the underlying system information fail.
LoginException

commit

public boolean commit()
               throws LoginException
Deprecated.
Commit the authentication (second phase).

This method is called if the LoginContext's overall authentication succeeded (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules succeeded).

If this LoginModule's own authentication attempt succeeded (the importing of the Solaris authentication information succeeded), then this method associates the Solaris Principals with the Subject currently tied to the LoginModule. If this LoginModule's authentication attempted failed, then this method removes any state that was originally saved.

Specified by:
commit in interface LoginModule
Returns:
true if this LoginModule's own login and commit attempts succeeded, or false otherwise.
Throws:
LoginException - if the commit fails

abort

public boolean abort()
              throws LoginException
Deprecated.
Abort the authentication (second phase).

This method is called if the LoginContext's overall authentication failed. (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules did not succeed).

This method cleans up any state that was originally saved as part of the authentication attempt from the login and commit methods.

Specified by:
abort in interface LoginModule
Returns:
false if this LoginModule's own login and/or commit attempts failed, and true otherwise.
Throws:
LoginException - if the abort fails

logout

public boolean logout()
               throws LoginException
Deprecated.
Logout the user

This method removes the Principals associated with the Subject.

Specified by:
logout in interface LoginModule
Returns:
true in all cases (this LoginModule should not be ignored).
Throws:
LoginException - if the logout fails
Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


SolarisSystem (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.security.auth.module
Class SolarisSystem

java.lang.Object
    extended by com.sun.security.auth.module.SolarisSystem
public class SolarisSystem
extends Object

This class implementation retrieves and makes available Solaris UID/GID/groups information for the current user.

Field Summary
protected long | gid
protected long[] | groups
protected long | uid
protected String | username
Constructor Summary
SolarisSystem()
Instantiate a SolarisSystem and load the native library to access the underlying system information.
Method Summary
long | getGid() Get the GID for the current Solaris user.
long[] | getGroups() Get the supplementary groups for the current Solaris user.
long | getUid() Get the UID for the current Solaris user.
String | getUsername() Get the username for the current Solaris user.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

username

protected String username

uid

protected long uid

gid

protected long gid

groups

protected long[] groups
Constructor Detail

SolarisSystem

public SolarisSystem()
Instantiate a SolarisSystem and load the native library to access the underlying system information.

Method Detail

getUsername

public String getUsername()
Get the username for the current Solaris user.

Returns:
the username for the current Solaris user.

getUid

public long getUid()
Get the UID for the current Solaris user.

Returns:
the UID for the current Solaris user.

getGid

public long getGid()
Get the GID for the current Solaris user.

Returns:
the GID for the current Solaris user.

getGroups

public long[] getGroups()
Get the supplementary groups for the current Solaris user.

Returns:
the supplementary groups for the current Solaris user.
Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


UnixLoginModule (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.security.auth.module
Class UnixLoginModule

java.lang.Object
    extended by com.sun.security.auth.module.UnixLoginModule
All Implemented Interfaces:
LoginModule
public class UnixLoginModule
extends Object
implements LoginModule

This LoginModule imports a user's Unix Principal information (UnixPrincipal, UnixNumericUserPrincipal, and UnixNumericGroupPrincipal) and associates them with the current Subject.

This LoginModule recognizes the debug option. If set to true in the login Configuration, debug messages will be output to the output stream, System.out.

Constructor Summary
UnixLoginModule()
Method Summary
boolean | abort() Abort the authentication (second phase).
boolean | commit() Commit the authentication (second phase).
void | initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) Initialize this LoginModule.
boolean | login() Authenticate the user (first phase).
boolean | logout() Logout the user
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

UnixLoginModule

public UnixLoginModule()
Method Detail

initialize

public void initialize(Subject subject,
                       CallbackHandler callbackHandler,
                       Map sharedState,
                       Map options)
Initialize this LoginModule.

Specified by:
initialize in interface LoginModule
Parameters:
subject - the Subject to be authenticated.

callbackHandler - a CallbackHandler for communicating with the end user (prompting for usernames and passwords, for example).

sharedState - shared LoginModule state.

options - options specified in the login Configuration for this particular LoginModule.

login

public boolean login()
              throws LoginException
Authenticate the user (first phase).

The implementation of this method attempts to retrieve the user's Unix Subject information by making a native Unix system call.

Specified by:
login in interface LoginModule
Returns:
true in all cases (this LoginModule should not be ignored).
Throws:
FailedLoginException - if attempts to retrieve the underlying system information fail.
LoginException

commit

public boolean commit()
               throws LoginException
Commit the authentication (second phase).

This method is called if the LoginContext's overall authentication succeeded (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules succeeded).

If this LoginModule's own authentication attempt succeeded (the importing of the Unix authentication information succeeded), then this method associates the Unix Principals with the Subject currently tied to the LoginModule. If this LoginModule's authentication attempted failed, then this method removes any state that was originally saved.

Specified by:
commit in interface LoginModule
Returns:
true if this LoginModule's own login and commit attempts succeeded, or false otherwise.
Throws:
LoginException - if the commit fails

abort

public boolean abort()
              throws LoginException
Abort the authentication (second phase).

This method is called if the LoginContext's overall authentication failed. (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules did not succeed).

This method cleans up any state that was originally saved as part of the authentication attempt from the login and commit methods.

Specified by:
abort in interface LoginModule
Returns:
false if this LoginModule's own login and/or commit attempts failed, and true otherwise.
Throws:
LoginException - if the abort fails

logout

public boolean logout()
               throws LoginException
Logout the user

This method removes the Principals associated with the Subject.

Specified by:
logout in interface LoginModule
Returns:
true in all cases (this LoginModule should not be ignored).
Throws:
LoginException - if the logout fails
Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD


UnixSystem (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

com.sun.security.auth.module
Class UnixSystem

java.lang.Object
    extended by com.sun.security.auth.module.UnixSystem
public class UnixSystem
extends Object

This class implementation retrieves and makes available Unix UID/GID/groups information for the current user.

Field Summary
protected long | gid
protected long[] | groups
protected long | uid
protected String | username
Constructor Summary
UnixSystem()
Instantiate a UnixSystem and load the native library to access the underlying system information.
Method Summary
long | getGid() Get the GID for the current Unix user.
long[] | getGroups() Get the supplementary groups for the current Unix user.
long | getUid() Get the UID for the current Unix user.
String | getUsername() Get the username for the current Unix user.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

username

protected String username

uid

protected long uid

gid

protected long gid

groups

protected long[] groups
Constructor Detail

UnixSystem

public UnixSystem()
Instantiate a UnixSystem and load the native library to access the underlying system information.

Method Detail

getUsername

public String getUsername()
Get the username for the current Unix user.

Returns:
the username for the current Unix user.

getUid

public long getUid()
Get the UID for the current Unix user.

Returns:
the UID for the current Unix user.

getGid

public long getGid()
Get the GID for the current Unix user.

Returns:
the GID for the current Unix user.

getGroups

public long[] getGroups()
Get the supplementary groups for the current Unix user.

Returns:
the supplementary groups for the current Unix user.
Overview Package Class Use Tree Index Help
JAAS
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


Uses of Class com.sun.security.auth.module.JndiLoginModule (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.security.auth.module.JndiLoginModule

No usage of com.sun.security.auth.module.JndiLoginModule

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.security.auth.module.KeyStoreLoginModule (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.security.auth.module.KeyStoreLoginModule

No usage of com.sun.security.auth.module.KeyStoreLoginModule

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.security.auth.module.Krb5LoginModule (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.security.auth.module.Krb5LoginModule

No usage of com.sun.security.auth.module.Krb5LoginModule

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.security.auth.module.NTLoginModule (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.security.auth.module.NTLoginModule

No usage of com.sun.security.auth.module.NTLoginModule

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.security.auth.module.NTSystem (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.security.auth.module.NTSystem

No usage of com.sun.security.auth.module.NTSystem

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.security.auth.module.SolarisLoginModule (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.security.auth.module.SolarisLoginModule

No usage of com.sun.security.auth.module.SolarisLoginModule

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.security.auth.module.SolarisSystem (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.security.auth.module.SolarisSystem

No usage of com.sun.security.auth.module.SolarisSystem

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.security.auth.module.UnixLoginModule (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.security.auth.module.UnixLoginModule

No usage of com.sun.security.auth.module.UnixLoginModule

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.security.auth.module.UnixSystem (Java Authentication and Authorization Service )

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.security.auth.module.UnixSystem

No usage of com.sun.security.auth.module.UnixSystem

Overview Package Class Use Tree Index Help
JAAS
PREV NEXT FRAMES NO FRAMES


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.


JAAS Authentication Tutorial

The JavaTM Authentication and Authorization Service (JAAS) was introduced as an optional package to the JavaTM 2 SDK, Standard Edition (J2SDK), v 1.3. JAAS has now been integrated into the J2SDK, v 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:./SampleAcn.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.


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.


JAAS Tutorials

This page links to two tutorials demonstrating various aspects of the use of JAAS (JavaTM Authentication and Authorization Service):

  1. JAAS Authentication

    Explains how an application can authenticate users using JAAS.

  2. JAAS Authorization

    Explains how to enforce user-based access controls using JAAS.

The authentication technology used for these tutorials is very basic, just ensuring that the user specifies a particular name and password. Thus, these tutorials can be run by everyone.

Related Documentation

API Specifications

  • com.sun.security.auth Package
  • com.sun.security.auth.callback Package
  • com.sun.security.auth.login Package
  • com.sun.security.auth.module Package

User Guides

  • JavaTM Authentication and Authorization Service (JAAS) Reference Guide.

Papers

  • JAAS white paper

Tutorials

  • 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.

  • Java 2 Security Tutorial

Other Java Security Documentation

  • J2SDK, v 1.4 Security Documentation
Copyright © 2001-2002 Sun Microsystems, Inc. All Rights Reserved.


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:

<name used by application to refer to this entry> {
    <LoginModule> <flag> <LoginModule options>;
    <optional additional LoginModules, flags and options>;
    };

Thus, each login configuration file entry consists of a name followed by one or more LoginModule-specific entries, where each LoginModule-specific entry is terminated by a semicolon and the entire group of LoginModule-specific entries 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

Sample {
   sample.module.SampleLoginModule required debug=true;
};

Here, the entry is named "Sample" and that is the name that the JAAS Authentication tutorial application (SampleAcn.java) 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 ones it expects ("testUser" and "testPassword", respectively).

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.

The specified LoginModules (described below) are used to control the authentication process. Authentication proceeds down the list in the exact order specified, as described here.

The subparts of each LoginModule-specific entry are the following:

  • LoginModule

    This specifies a class implementing the desired authentication technology. Specifically, the class must be a subclass of the LoginModule class, which is in the javax.security.auth.spi package. A typical LoginModule may prompt for and verify a user name and password, as is done by the SampleLoginModule (in the sample.module package) used for these tutorials. Any vendor can provide a LoginModule implementation that you can use. Some implementations are supplied with the JRE from Sun Microsystems. 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 preceding LoginModule is "required", "requisite", "sufficient", or "optional". If there is just one LoginModule-specific entry, as there is in our tutorials, then the flag for it should be "required". The options are described in more detail here.

  • 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.

    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 interpreter 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 SampleAcn application in the JAAS Authentication tutorial using the following command, which specifies that the configuration file is the sample_jaas.config file in the current directory:

    java -Djava.security.auth.login.config==sample_jaas.config sample.SampleAcn
  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 J2RE.

    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 sample_jaas.config 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/sample_jaas.config
    (Note that URLs always use forward slashes, regardless of what operating system the user is running.)


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
    4120 Network Circle MS: USCA12-204
    Santa Clara, CA  95054
    U.S.A.

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:  ____________________________________________


How to Implement a Provider for the Java Cryptography Extension

How to Implement a Provider for the JavaTM Cryptography Extension

in the JavaTM 2 SDK, Standard Edition, v 1.4

Introduction
Who Should Read This Document
Related Documentation
A Note on Terminology

What's New in JCE in the Java 2 SDK, v 1.4

Engine Classes and Corresponding SPI Classes

Steps to Implement and Integrate a Provider
Step 1: Write your Service Implementation Code
Step 2: Give your Provider a Name
Step 3: Write your "Master Class," a subclass of Provider
Step 4: Compile your Code
Step 5: Prepare for Testing
Step 6: Write and Compile Test Programs
Step 7: Run your Test Programs
Step 8: Apply for U.S. Government Export Approval If Required
Step 9: Document your Provider and its Supported Services
Step 10: Make Your Provider Software and Documentation Available to Clients

How a Provider Can Do Self-Integrity Checking

Further Implementation Details and Requirements
Algorithm Aliases
Service Interdependencies
Default Initializations
Diffie-Hellman Interfaces and their Required Implementations
Algorithm Parameter Specification Classes
Key Specification Classes Required by Key Factories
Secret-Key Generation
Ensuring Exportablity

Appendix A: The "SunJCE" Provider's Master Class

Appendix B: The "EMProvider" Provider's Master Class

Appendix C: The java.security Master Properties File

Introduction

The JavaTM Cryptography Extension (JCE) provides a framework and implementations for encryption, key generation and key agreement, and Message Authentication Code (MAC) algorithms. Support for encryption includes symmetric, asymmetric, block, and stream ciphers. The software also supports secure streams and sealed objects.

JCE was previously an optional package (extension) to the JavaTM 2 SDK, Standard Edition (Java 2 SDK), versions 1.2.x and 1.3.x. JCE has now been integrated into the Java 2 SDK, v 1.4.

JCE is based on the same design principles found elsewhere in the Java Cryptography Architecture framework utilized by all the cryptography-related security components of the Java 2 platform: implementation independence and, whenever possible, algorithm independence. It uses the same "provider" architecture, which uses the notion of a Cryptographic Service Provider, or "provider" for short. This term refers to a package (or a set of packages) that supply a concrete implementation of a subset of the cryptography aspects of the Java Security API.

JCE extends the list of cryptographic services of which a provider can supply implementations. A provider could, for example, contain an implementation of one or more digital signature algorithms and one or more cipher algorithms.

A program wishing to use cryptography functionality may simply request a particular type of object (such as a Cipher object) implementing a particular algorithm (such as DES) and get an implementation from one of the installed providers. If an implementation from a particular provider is desired, the program can request that provider by name, along with the algorithm desired.

Each Java 2 SDK installation has one or more provider packages installed. Each provider package supplies implementations of cryptographic services defined in one or more security components of the Java 2 SDK (including JCE).

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.

The Java 2 SDK, v 1.4 release comes standard with a JCE provider named "SunJCE", which comes pre-installed and registered and which supplies the following cryptographic services:

  • An implementation of the DES (FIPS PUB 46-1), Triple DES, and Blowfish encryption algorithms in the Electronic Code Book (ECB), Cipher Block Chaining (CBC), Cipher Feedback (CFB), Output Feedback (OFB), and Propagating Cipher Block Chaining (PCBC) modes. (Note: Throughout this document, the terms "Triple DES" and "DES-EDE" will be used interchangeably.)

  • Key generators for generating keys suitable for the DES, Triple DES, Blowfish, HMAC-MD5, and HMAC-SHA1 algorithms.

  • An implementation of the MD5 with DES-CBC password-based encryption (PBE) algorithm defined in PKCS #5.

  • "Secret-key factories" providing bi-directional conversions between opaque DES, Triple DES and PBE key objects and transparent representations of their underlying key material.

  • An implementation of the Diffie-Hellman key agreement algorithm between two or more parties.

  • A Diffie-Hellman key pair generator for generating a pair of public and private values suitable for the Diffie-Hellman algorithm.

  • A Diffie-Hellman algorithm parameter generator.

  • A Diffie-Hellman "key factory" providing bi-directional conversions between opaque Diffie-Hellman key objects and transparent representations of their underlying key material.

  • Algorithm parameter managers for Diffie-Hellman, DES, Triple DES, Blowfish, and PBE parameters.

  • An implementation of the HMAC-MD5 and HMAC-SHA1 keyed-hashing algorithms defined in RFC 2104.

  • An implementation of the padding scheme described in PKCS#5.

  • A keystore implementation for the proprietary keystore type named "JCEKS".

New providers may be added statically or dynamically. Clients may also query which providers are currently installed.

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.

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 developers of cryptographic service providers. It documents what you need to do in order to integrate your provider into Java Security so that your algorithms and other services can be found when Java Security API clients request them.

Only providers signed by a trusted entity can be plugged into the JCE framework.

Related Documentation

This document assumes you have already read the following documents:

  • Java Cryptography Architecture API Specification and Reference,
  • How to Implement a Provider for the Java Cryptography Architecture, and
  • JavaTM Cryptography Extension (JCE) Reference Guide for the JavaTM 2 SDK, Standard Edition, v 1.4.

It also discusses various classes and interfaces in the Java Security API. The complete reference documentation for the relevant Security API packages can be found in these packages:

  • java.security
  • java.security.spec
  • java.security.interfaces
  • javax.crypto
  • javax.crypto.spec
  • javax.crypto.interfaces

A Note on Terminology

The JCE within the Java 2 SDK, v 1.4 includes two software components:

  • the framework that defines and supports cryptographic services that providers can supply implementations for. This framework includes everything in the javax.crypto package.

  • a provider named "SunJCE"
Throughout this document, the term "JCE" by itself refers to the JCE framework in the Java 2 SDK, v 1.4. Whenever the JCE provider supplied with the Java 2 SDK, v 1.4 is mentioned, it will be referred to explicitly as the "SunJCE" provider.

What's New in JCE in the Java 2 SDK, v 1.4

These are the differences between JCE 1.2.1 and the JCE in the Java 2 SDK, v 1.4 that affect providers:

  • JCE Is Now in Java 2 SDK

  • Strong Cryptography Is the Default, Unlimited Is Available

  • Provider Authentication of JCE Framework No Longer Required

JCE Is Now in Java 2 SDK

JCE was previously an optional package (extension) to the JavaTM 2 SDK, Standard Edition (Java 2 SDK), versions 1.2.x and 1.3.x. JCE has now been integrated into the Java 2 SDK, v 1.4. The SunJCE provider is also included and is automatically registered in the java.security security properties file included with the Java 2 SDK, v 1.4.

Strong Cryptography Is the Default, Unlimited Is Available

Due to import control restrictions, the jurisdiction policy files shipped with the Java 2 SDK, v 1.4 allow "strong" but limited cryptography to 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). You can download this version and replace the strong cryptography versions supplied with the Java 2 SDK, v 1.4 with the unlimited ones. See

http://java.sun.com/products/jce/index-14.html
for information indicating where to go to download the unlimited version.

The jurisdiction policy files have been relocated to

<java-home>\lib\security         [Windows]
<java-home>/lib/security         [Solaris]
where <java-home> refers to the directory where the runtime software is installed, which is the top-level directory of the JavaTM 2 Runtime Environment (JRE) or the jre directory in the JavaTM 2 SDK (Java 2 SDK) software. They have been moved to this standard location so that it is easy to replace the strong cryptography versions that come with the Java 2 SDK, v 1.4 with the unlimited ones.

Provider Authentication of JCE Framework No Longer Required

In JCE 1.2.1, providers needed to include code to authenticate the JCE framework to assure themselves of the integrity and authenticity of the JCE that they plugged into. Now that JCE is integrated into the Java 2 SDK, v 1.4, this is no longer necessary.

JCE 1.2.1 providers which follow the guidance in How to Implement a Provider for the Java Cryptography Extension 1.2.1 will continue to work with the JCE framework in the Java 2 SDK, v 1.4.

However, a provider whose framework authentication code locates the JCE framework via protection domain instead of following the recommendations in the aforementioned JCE 1.2.1 JCE provider document will not work in the Java 2 SDK, v 1.4. Now that JCE has been integrated into the Java 2 SDK, v 1.4, the JCE framework has a null code source just like any other class in the Java 2 SDK, v 1.4. You can either modify your provider to follow the recommended approach for authenticating the framework, or put in a conditional so that the framework authentication code is only executed when the provider is being run with JCE 1.2.1.

Engine Classes and Corresponding SPI 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, and it either provides cryptographic operations (like those for ciphers or key agreement protocols), or generates or supplies the cryptographic material (keys or parameters) required for cryptographic operations. For example, two of the engine classes are the Cipher and KeyAgreement classes. The Cipher class provides access to the functionality of an encryption algorithm (such as DES), and the KeyAgreement class provides access to the functionality of a key agreement protocol (such as Diffie-Hellman).

The Java Cryptography Architecture encompasses the classes of the J2SE Java Security package related to cryptography, including the engine classes. Users of the API request and utilize instances of the engine classes to carry out corresponding operations.

JCE was previously an optional package (extension) to the JavaTM 2 SDK, Standard Edition (Java 2 SDK), versions 1.2.x and 1.3.x. JCE has now been integrated into the Java 2 SDK, v 1.4.

JCE defines the following engine classes:

  • 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.

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. The Cipher engine class, for example, provides access to the functionality of a cipher algorithm. The actual implementation supplied in a CipherSpi subclass (see next paragraph) would be that for a specific kind of encryption algorithm, such as DES or Triple DES.

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.

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 Cipher engine class is the CipherSpi class.

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.

Another example of an engine class is the KeyAgreement class, which provides access to a key agreement (key exchange) algorithm. Its implementations, in KeyAgreementSpi subclasses, may be those of various key agreement algorithms such as Diffie-Hellman.

As a final example, the SecretKeyFactory engine class supports the conversion from opaque secret keys to transparent key specifications, and vice versa. (See Key Specification Classes Required by Key Factories.) The actual implementation supplied in a SecretKeyFactorySpi subclass would be that for a specific type of secret keys, e.g., DES keys.

Steps to Implement and Integrate a Provider

The steps required in order to implement a provider and integrate it into JCE are the following:

Step 1: Write your Service Implementation Code
Step 2: Give your Provider a Name
Step 3: Write your "Master Class," a subclass of Provider
Step 4: Compile your Code
Step 5: Prepare for Testing
Step 5a: Get a Code-Signing Certificate
Step 5b: Place Your Provider in a JAR File
Step 5c: Sign Your Provider
Step 5d: Install the Provider
Step 5e: Set Provider Permissions
Step 6: Write and Compile Test Programs
Step 7: Run your Test Programs
Step 8: Apply for U.S. Government Export Approval If Required
Step 9: Document your Provider and its Supported Services
Step 10: Make Your Provider Software and Documentation Available to Clients

Step 1: Write your Service Implementation Code

The first thing you need to do is write the code supplying algorithm-specific implementations of the cryptographic services you want to support.

Note that your provider may supply implementations of cryptographic services defined in one or more of the security components of the Java 2 SDK v 1.4, including JCE.

In JCE in the Java 2 SDK, v 1.4 (as in the previous JCE 1.2.1 release), you can supply cipher, key agreement and MAC algorithms, as well as secret-key factories, secret-key generation services, and exemption mechanism implementations.

For cryptographic services not defined in JCE (e.g., signatures and message digests), please refer to Java Cryptography Architecture API Specification and Reference.

For each cryptographic service in the Java 2 SDK (including JCE ones), you need to create a subclass of the appropriate SPI class. JCE defines the following engine classes: CipherSpi, KeyAgreementSpi, KeyGeneratorSpi, MacSpi, SecretKeyFactorySpi, and ExemptionMechanismSpi. (See Engine Classes and Corresponding SPI Classes in this document for information on the JCE and other cryptographic classes in the Java 2 SDK, v 1.4.)

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.

    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.

Additional JCE Provider Requirements and Recommendations

When instantiating a provider's implementation (class) of a JCE service, the JCE framework will determine the provider's codebase (JAR file) and verify its signature. In this way, JCE authenticates the provider and ensures that only providers signed by a trusted entity can be plugged into JCE. Thus, one requirement for JCE 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 JCE. 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 JCE, 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 Extension (JCE) 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 Extension (JCE) 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 (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 properties that must be defined for the various types of JCE services, where the actual algorithm name is substitued for algName:

    • Cipher.algName
    • KeyAgreement.algName
    • KeyGenerator.algName
    • Mac.algName
    • SecretKeyFactory.algName
    • ExemptionMechanism.algName

    In all of these except ExemptionMechanism and Cipher, algName is the standard name of the algorithm.

    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 Extension (JCE) Reference Guide for the standard algorithm names that should be used.)

    The value of each property must be the fully qualified name of the class implementing the specified algorithm. 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 "SunJCE" provider implements the Diffie-Hellman key agreement algorithm in a class named DHKeyAgreement in the com.sun.crypto.provider package. Its subclass of Provider (which is the SunJCE class in the com.sun.crypto.provider package) sets the KeyAgreement.DiffieHellman property to have the value com.sun.crypto.provider.DHKeyAgreement via the following:

        put("KeyAgreement.DiffieHellman",
          "com.sun.crypto.provider.DHKeyAgreement")

For further master class property setting examples, see Appendix A to view the current SunJCE.java source file. This shows how the SunJCE class constructor sets all the properties for the "SunJCE" provider.

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 (e.g., 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 Extension (JCE) 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

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: Prepare for Testing

Step 5a: 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.
      keytool -genkey -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>

    (Note: This must be typed as a single line. Multiple lines and indentation are used in the examples so that they are legible.)

    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 -genkey 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 -genkey 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> -sigalg DSA
        -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 JCE 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 JCE 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.

    After the JCE Code Signing Certification Authority has received your email message, they will send you a request number via email. 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
    4120 Network Circle MS: USCA12-204
    Santa Clara, CA 95054
    U.S.A.
    After the JCE 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.

  4. Use keytool to import the certificates received from the CA.

    Once you have received the two certificates from the JCE 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 JCE Code Signing Certification Authority.

Now that you have in your keystore a certificate from an entity trusted by JCE (the JCE Code Signing Certification Authority), you can place your provider code in a JAR file (Step 5b) and then use that certificate to sign the JAR file (Step 5c).

Step 5b: 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 5c: Sign Your Provider

Sign the JAR file created in the previous step with the code-signing certificate obtained in Step 5a. 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 JCE Code Signing Certification Authority (the same alias as that specified in the commands in Step 5a).

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 5d: 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 JavaTM 2 Runtime Environment (JRE) or the jre directory in the JavaTM 2 SDK (Java 2 SDK) software. For example, if you have the Java 2 SDK, v 1.4 installed on Solaris in a directory named /home/user1/J2SDK1.4.0, or on Microsoft Windows in a directory named C:\J2SDK1.4.0, then you need to install the JAR file in the following directory:

/home/user1/J2SDK1.4.0/jre/lib/ext    [Solaris]
C:\J2SDK1.4.0\jre\lib\ext             [Windows]

Similarly, if you have the JRE, v 1.4 installed on Solaris in a directory named /home/user1/j2re1.4.0, or on Microsoft Windows in a directory named C:\j2re1.4.0, you need to install the JAR file in the following directory:

/home/user1/j2re1.4.0/lib/ext         [Solaris]
C:\j2re1.4.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 the Java 2 SDK v 1.4 installed on Solaris in a directory named /home/user1/J2SDK1.4.0, or on Microsoft indows in a directory named C:\J2SDK1.4.0, then you need to edit the following file:

/home/user1/J2SDK1.4.0/jre/lib/security/java.security  [Solaris]
C:\J2SDK1.4.0\jre\lib\security\java.security           [Windows]

Similarly, if you have the Java 2 Runtime Environment, v 1.4 installed on Solaris in a directory named /home/user1/j2re1.4.0, or on Windows in a directory named C:\j2re1.4.0, then you need to edit this file:

/home/user1/j2re1.4.0/lib/security/java.security       [Solaris]
C:\j2re1.4.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.

The Java 2 SDK, v 1.4 comes standard with a provider named "SUN", which is automatically configured as a static provider in the java.security properties file, as follows:

security.provider.1=sun.security.provider.Sun

(The "SUN" provider's master class is the Sun class in the sun.security.provider package.)

The JCE provider "SunJCE" and other security-related providers shipped with the Java 2 platform are also automatically configured as static providers.

To utilize another JCE provider, add a line registering the alternate provider, giving it whatever preference order you prefer (and making corresponding adjustments to the other providers' orders, if needed).

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 second preferred provider. To do so, add the following line to the java.security file below the line for the "SUN" provider, and increment the preference order numbers for all other providers whose numbers were greater than or equal to 2 before your addition:

    security.provider.2=com.cryptox.provider.CryptoX
Note: Providers may also be registered dynamically. To do so, a program (such as your test program, to be written in Step 6) 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 5e: Set Provider Permissions

Whenever JCE providers are not installed extensions, permissions must be granted for when applets or applications using JCE 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 6: 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 Extension (JCE) Reference Guide for complete information on creating and testing such an application.

Step 7: 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 5d. 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 5e.

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 5b), sign the JAR file (Step 5c), re-install the provider (Step 5d), if needed fix or add to the permissions (Step 5e), and then re-test your programs. Repeat these steps as needed.

Step 8: 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 Export Administration 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 Extension (JCE) Reference Guide.

Here are two URLs that may be useful:

  • U.S. Department of Commerce: http://www.doc.gov

  • Bureau of Export Administration: http://www.bxa.doc.gov

Step 9: 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 5d, 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 5e.
In addition, your documentation should specify anything else of interest to clients, such as any default algorithm parameters.

MACs

For each MAC algorithm, tell 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 authentication codes" (MACs) may be possible through cloning. Clients who do not know whether or not a MAC implementation is cloneable can find out by attempting to clone the Mac 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.

Step 10: Make your Provider Software and Documentation Available to Clients

The final step is to make your provider software and 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 JCE. Providers that provide implementations for JCE services 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' JCE Code Signing CA, and
  • IBM JCE Code Signing CA.
Please refer to Step 5b for detailed information on how to get a code-signing certificate from Sun Microsystems' JCE 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:

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
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 JCE 1.2.1, providers needed to include code to authenticate the JCE framework to assure themselves of the integrity and authenticity of the JCE that they plugged into. Now that JCE is integrated into the Java 2 SDK, v 1.4, this is no longer necessary.

One implication is that a provider written just for JCE 1.2.1 will not work in the Java 2 SDK, v 1.4 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 Java 2 SDK, v 1.4, 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.1 and with the JCE in the Java 2 SDK, v 1.4, 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.1. 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 Sample Code

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

Algorithm Aliases

For many cryptographic algorithms, there is a single official "standard name." The standard names defined by JCE in the Java 2 SDK, v 1.4 are listed in Appendix A of the Java Cryptography Extension (JCE) Reference Guide.

For example, DiffieHellman is the standard name for the Diffie-Hellman key agreement algorithm defined in PKCS #3.

JCE uses the same aliasing scheme for algorithm names as the rest of the security products in the Java 2 SDK, v 1.4. That scheme enables clients to use aliases when referring to algorithms, rather than their standard names. For example, the "SunJCE" provider's master class (SunJCE.java) defines the alias "DH" for the key agreement whose standard name is DiffieHellman. Thus, the following statements are equivalent:

    KeyAgreement ka = KeyAgreement.getInstance("DiffieHellman", "SunJCE");

    KeyAgreement ka = KeyAgreement.getInstance("DH", "SunJCE");
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 either Cipher, KeyAgreement, KeyGenerator, Mac, SecretKeyFactory, or ExemptionMechanism, and aliasName is your alias name. For all but ExemptionMechanism, the value of the property must be the standard algorithm name for the algorithm being aliased. For ExemptionMechanism, the value is the exemption mechanism name (KeyRecovery, KeyEscrow, or KeyWeakening).

As an example, the "SunJCE" provider defines the alias "DH" for the key agreement algorithm whose standard name is "DiffieHellman" by setting a property named Alg.Alias.KeyAgreement.DH to have the value DiffieHellman via the following:

    put("Alg.Alias.KeyAgreement.DH", "DiffieHellman");

Currently, aliases defined by the "SunJCE" provider are available to all clients, no matter which provider clients request. For example, if you create a provider named "MyPro" that implements the Diffie-Hellman algorithm, then even if you don't define any aliases for it, the "DH" alias defined by "SunJCE" can be used to refer to your provider's Diffie-Hellman implementation as follows:

    KeyAgreement ka = KeyAgreement.getInstance("DH", "MyPro");

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 2 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.

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 "SunJCE" provider uses a default modulus size (keysize) of 1024 bits for the generation of Diffie-Hellman parameters.

Diffie-Hellman Interfaces and their Required Implementations

JCE 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.

Algorithm Parameter Specification 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., DHParameterSpec defines getP, getG, and getL methods, to access the p, g, and l 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.

JCE 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 JCE, you will need to supply your own AlgorithmParameterSpec implementation appropriate for that type of algorithm.

JCE defines the following algorithm parameter specification classes in the javax.crypto.spec package:

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 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 Classes Required by Key Factories

Key specifications are transparent representations of the key material that constitutes a key. JCE defines the following key specification classes in the javax.crypto.spec package: 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.

Methods in DHPrivateKeySpec
Method | 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.

Methods in DHPublicKeySpec
Method | 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.

Methods in DESKeySpec
Method | 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.

Methods in DESedeKeySpec
Method | 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.

Methods in PBEKeySpec
Method | 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.

Methods in SecretKeySpec
Method | 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.

Ensuring Exportability

A key feature of JCE is the exportability of the JCE 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 Java 2 SDK, v 1.4 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 JCE 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 JCE, 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 JCE in the Java 2 SDK, v 1.4 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 JCE. 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 JCE framework. (See Step 5a through Step 5c.) U.S. vendors whose providers may be exported outside the U.S. first need to apply for U.S. government export approval. (See Step 8.)

Appendix A: The "SunJCE" Provider's 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.

/*
 * Copyright 2002 Sun Microsystems, Inc. All rights reserved.
 * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package com.sun.crypto.provider;

import java.security.AccessController;
import java.security.Provider;
. . .

/**
 * The "SunJCE" Cryptographic Service Provider.
 *
 * @author Jan Luehe
 * @author Sharon Liu
 *
 * @version 1.42, 01/08/01
 */

/**
 * Defines the "SunJCE" provider.
 *
 * Supported algorithms and their names:
 *
 * - DES (ECB, CBC, CFB, OFB, PCBC)
 *
 * - DES-EDE (ECB, CBC, CFB, OFB, PCBC)
 *
 * - Password-based Encryption (PBE)
 *
 * - Blowfish
 *
 * - Diffie-Hellman Key Agreement
 *
 * - HMAC-MD5, HMAC-SHA1
 *
 * - PKCS5Padding
 */

public final class SunJCE extends Provider {

    private static String info = "SunJCE Provider " +
    "(implements DES, Triple DES, Blowfish, PBE, Diffie-Hellman, HMAC-MD5, "
    + "HMAC-SHA1)";

    public SunJCE() {
    /* We are the "SunJCE" provider */
    super("SunJCE", 1.4, info);

        AccessController.doPrivileged(new java.security.PrivilegedAction() {
            public Object run() {

        /*
         * Cipher engines
         */
        put("Cipher.DES", "com.sun.crypto.provider.DESCipher");

        put("Cipher.DESede", "com.sun.crypto.provider.DESedeCipher");
        put("Alg.Alias.Cipher.TripleDES", "DESede");

        put("Cipher.PBEWithMD5AndDES",
            "com.sun.crypto.provider.PBEWithMD5AndDESCipher");
        put("Cipher.PBEWithMD5AndTripleDES",
            "com.sun.crypto.provider.PBEWithMD5AndTripleDESCipher");

        put("Cipher.Blowfish",
            "com.sun.crypto.provider.BlowfishCipher");

        /*
         *  Key(pair) Generator engines
         */
        put("KeyGenerator.DES",
            "com.sun.crypto.provider.DESKeyGenerator");

        put("KeyGenerator.DESede",
            "com.sun.crypto.provider.DESedeKeyGenerator");
        put("Alg.Alias.KeyGenerator.TripleDES", "DESede");

        put("KeyGenerator.Blowfish",
            "com.sun.crypto.provider.BlowfishKeyGenerator");

        put("KeyGenerator.HmacMD5",
            "com.sun.crypto.provider.HmacMD5KeyGenerator");

        put("KeyGenerator.HmacSHA1",
            "com.sun.crypto.provider.HmacSHA1KeyGenerator");

        put("KeyPairGenerator.DiffieHellman",
            "com.sun.crypto.provider.DHKeyPairGenerator");
        put("Alg.Alias.KeyPairGenerator.DH", "DiffieHellman");

        /*
         * Algorithm parameter generation engines
         */
        put("AlgorithmParameterGenerator.DiffieHellman",
            "com.sun.crypto.provider.DHParameterGenerator");
        put("Alg.Alias.AlgorithmParameterGenerator.DH",
            "DiffieHellman");

        /*
         * Key Agreement engines
         */
        put("KeyAgreement.DiffieHellman",
            "com.sun.crypto.provider.DHKeyAgreement");
        put("Alg.Alias.KeyAgreement.DH", "DiffieHellman");

        /*
         * Algorithm Parameter engines
         */
        put("AlgorithmParameters.DiffieHellman",
            "com.sun.crypto.provider.DHParameters");
        put("Alg.Alias.AlgorithmParameters.DH", "DiffieHellman");

        put("AlgorithmParameters.DES",
            "com.sun.crypto.provider.DESParameters");

        put("AlgorithmParameters.DESede",
            "com.sun.crypto.provider.DESedeParameters");
        put("Alg.Alias.AlgorithmParameters.TripleDES", "DESede");

        put("AlgorithmParameters.PBE",
            "com.sun.crypto.provider.PBEParameters");
        put("Alg.Alias.AlgorithmParameters.PBEWithMD5AndDES", "PBE");

        put("AlgorithmParameters.Blowfish",
            "com.sun.crypto.provider.BlowfishParameters");

        /*
         * Key factories
         */
        put("KeyFactory.DiffieHellman",
            "com.sun.crypto.provider.DHKeyFactory");
        put("Alg.Alias.KeyFactory.DH", "DiffieHellman");

        /*
         * Secret-key factories
         */
        put("SecretKeyFactory.DES",
            "com.sun.crypto.provider.DESKeyFactory");

        put("SecretKeyFactory.DESede",
            "com.sun.crypto.provider.DESedeKeyFactory");
        put("Alg.Alias.SecretKeyFactory.TripleDES", "DESede");

        put("SecretKeyFactory.PBEWithMD5AndDES",
            "com.sun.crypto.provider.PBEKeyFactory");

        /*
         * MAC
         */
        put("Mac.HmacMD5", "com.sun.crypto.provider.HmacMD5");
        put("Mac.HmacSHA1", "com.sun.crypto.provider.HmacSHA1");

        /*
         * KeyStore
         */
        put("KeyStore.JCEKS", "com.sun.crypto.provider.JceKeyStore");

        return null;
        }
    });
    }

}

Appendix B: The "EMProvider" Provider's Master Class

Below is an example of an EMProvider.java file, which contains a class named EMProvider that is the master class for the provider named "EMProvider".

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 "EMProvider" 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 master class for a provider that implements an exemption mechanism. It is included in addition to the Appendix A showing the master class for the "SunJCE" provider because the "SunJCE" provider does not include any exemption mechanism implementations. Note: A provider can implement both cryptographic services and exemption mechanism services.

package com.abc.crypto.provider;

import java.security.AccessController;
import java.security.Provider;

/**
 * The "EMProvider" Cryptographic Service Provider.
 *
 * @version 1.00, 03/15/2000
 */

/**
 * Defines the "EMProvider" provider.
 *
 * Supported algorithm(s) and their name(s):
 *
 * - Key Recovery
 */

public final class EMProvider extends Provider {

    private static String info = "EMProvider Exemption Mechanism Provider " +
    "(implements KeyRecovery)";

    public EMProvider() {
        /* We are the "EMProvider" provider */
        super("EMProvider", 1.2, info);

        AccessController.doPrivileged(new java.security.PrivilegedAction() {
            public Object run() {

                /*
                 * Algorithm Parameter engines
                 */
                put("AlgorithmParameters.KeyRecovery",
                    "com.abc.crypto.provider.KeyRecoveryParameters");
                put("Alg.Alias.AlgorithmParameters.KR", "KeyRecovery");

                /*
                 * ExemptionMechanism
                 */
                put("ExemptionMechanism.KeyRecovery",
                    "com.abc.crypto.provider.KeyRecovery");
                put("Alg.Alias.ExemptionMechanism.KR", "KeyRecovery");

                return null;
            }
        });
    }
}

Appendix C: The java.security Properties File

Below is a copy of the java.security file that appears in every JRE installation. This file appears at
<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. Thus, if you have the Java 2 SDK v 1.4 installed on Solaris in a directory named /home/user1/J2SDK1.4.0, or on Microsoft Windows in a directory named C:\J2SDK1.4.0, then the file would be
/home/user1/J2SDK1.4.0/jre/lib/security/java.security  [Solaris]
C:\J2SDK1.4.0\jre\lib\security\java.security           [Windows]
Similarly, if you have Java 2 Runtime Environment v 1.4 installed on Solaris in a directory named /home/user1/j2re1.4.0, or on Windows in a directory named C:\j2re1.4.0, then the file would be
/home/user1/j2re1.4.0/lib/security/java.security       [Solaris]
C:\j2re1.4.0\lib\security\java.security                [Windows]
See Step 5d 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: 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 an
# attempt is made to use the entropy gathering device specified by
# the securerandom.source property. If an exception occurs when
# accessing the URL then the traditional system/thread activity
# algorithm is used.
#
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=

#
# The Java-level namelookup cache policy for successful lookups:
#
# any negative value: caching forever
# any positive value: the number of seconds to cache an address for
# zero: do not cache
#
# default value is forever (FOREVER). For security reasons, this
# caching is made forever when a security manager is set.
#
# NOTE: Setting this value to anything other than the default value
#       can have serious security implications. Do not set it unless
#       you are sure you are not exposed to DNS spoofing attack.
#
#networkaddress.cache.ttl=-1

# The Java-level namelookup cache policy for failed lookups:
#
# any negative value: cache forever
# any positive value: the number of seconds to cache negative lookup results
# zero: do not cache
#
# In some Microsoft Windows networking environments that employ
# the WINS name service in addition to DNS, name service lookups
# that fail may take a noticeably long time to return (approx. 5 seconds).
# For this reason the default caching policy is to maintain these
# results for 10 seconds.
#
#
networkaddress.cache.negative.ttl=10

Copyright © 1996-2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-security@java.sun.com. 		Sun
Java Software
Last modified: 17 Jan 2002


Java Cryptography Extension

JavaTM Cryptography Extension (JCE)

Reference Guide

for the JavaTM 2 SDK, Standard Edition, v 1.4

Introduction

What's New in JCE in the Java 2 SDK, v 1.4

Cryptographic Concepts
Encryption and Decryption
Password-Based Encryption
Cipher
Key Agreement
Message Authentication Code

Core Classes
The Cipher Class
The Cipher Stream Classes
The CipherInputStream Class
The CipherOutputStream Class
The KeyGenerator Class
The SecretKeyFactory Class
The SealedObject Class
The KeyAgreement Class
The Mac Class

How to Make Applications "Exempt" from Cryptographic Restrictions

Installing JCE Providers for the Java 2 SDK, v 1.4

JCE Keystore

Code Examples
Using Encryption
Using Password-Based Encryption
Using Key Agreement

Appendix A: Standard Names

Appendix B: SunJCE Default Keysizes

Appendix C: SunJCE Keysize Restrictions

Appendix D: Jurisdiction Policy File Format

Appendix E: Maximum Key Sizes Allowed by "Strong" Jurisdiction Policy Files

Appendix F: Sample Programs
Diffie-Hellman Key Exchange between 2 Parties
Diffie-Hellman Key Exchange between 3 Parties
Blowfish Example
HMAC-MD5 Example

Introduction

This document is intended as a companion to the JavaTM Cryptography Architecture (JCA) API Specification & Reference. References to chapters not present in this document are to chapters in the JCA Specification.

The JavaTM Cryptography Extension (JCE) provides a framework and implementations for encryption, key generation and key agreement, and Message Authentication Code (MAC) algorithms. Support for encryption includes symmetric, asymmetric, block, and stream ciphers. The software also supports secure streams and sealed objects.

JCE was previously an optional package (extension) to the JavaTM 2 SDK, Standard Edition (Java 2 SDK), versions 1.2.x and 1.3.x. JCE has now been integrated into the Java 2 SDK, v 1.4.

JCE is based on the same design principles found elsewhere in the JCA: implementation independence and, whenever possible, algorithm independence. It uses the same "provider" architecture. Providers signed by a trusted entity can be plugged into the JCE framework, and new algorithms can be added seamlessly.

The JCE API covers:

  • Symmetric bulk encryption, such as DES, RC2, and IDEA

  • Symmetric stream encryption, such as RC4

  • Asymmetric encryption, such as RSA

  • Password-based encryption (PBE)

  • Key Agreement

  • Message Authentication Codes (MAC)

The Java 2 SDK, v 1.4 release comes standard with a JCE provider named "SunJCE", which comes pre-installed and registered and which supplies the following cryptographic services:

  • An implementation of the DES (FIPS PUB 46-1), Triple DES, and Blowfish encryption algorithms in the Electronic Code Book (ECB), Cipher Block Chaining (CBC), Cipher Feedback (CFB), Output Feedback (OFB), and Propagating Cipher Block Chaining (PCBC) modes. (Note: Throughout this document, the terms "Triple DES" and "DES-EDE" will be used interchangeably.)

  • Key generators for generating keys suitable for the DES, Triple DES, Blowfish, HMAC-MD5, and HMAC-SHA1 algorithms.

  • An implementation of the MD5 with DES-CBC password-based encryption (PBE) algorithm defined in PKCS #5.

  • "Secret-key factories" providing bi-directional conversions between opaque DES, Triple DES and PBE key objects and transparent representations of their underlying key material.

  • An implementation of the Diffie-Hellman key agreement algorithm between two or more parties.

  • A Diffie-Hellman key pair generator for generating a pair of public and private values suitable for the Diffie-Hellman algorithm.

  • A Diffie-Hellman algorithm parameter generator.

  • A Diffie-Hellman "key factory" providing bi-directional conversions between opaque Diffie-Hellman key objects and transparent representations of their underlying key material.

  • Algorithm parameter managers for Diffie-Hellman, DES, Triple DES, Blowfish, and PBE parameters.

  • An implementation of the HMAC-MD5 and HMAC-SHA1 keyed-hashing algorithms defined in RFC 2104.

  • An implementation of the padding scheme described in PKCS #5.

  • A keystore implementation for the proprietary keystore type named "JCEKS".

A Note on Terminology

The JCE within the Java 2 SDK, v 1.4 includes two software components:

  • the framework that defines and supports cryptographic services that providers can supply implementations for. This framework includes everything in the javax.crypto package.

  • a provider named "SunJCE"
Throughout this document, the term "JCE" by itself refers to the JCE framework in the Java 2 SDK, v 1.4. Whenever the JCE provider supplied with the Java 2 SDK, v 1.4 is mentioned, it will be referred to explicitly as the "SunJCE" provider.

What's New in JCE in the Java 2 SDK, v 1.4

Here are the differences between JCE 1.2.1 and the JCE within the Java 2 SDK, v 1.4:

  • JCE Is Now in Java 2 SDK

  • Strong Cryptography Is the Default, Unlimited Is Available

  • Provider Authentication of JCE Framework No Longer Required

  • Support for Additional Features of PKCS #1, #5 and #8

  • SunJCE Default Blowfish Keysize Has Changed

JCE Is Now in Java 2 SDK

JCE was previously an optional package (extension) to the JavaTM 2 SDK, Standard Edition (Java 2 SDK), versions 1.2.x and 1.3.x. JCE has now been integrated into the Java 2 SDK, v 1.4. The SunJCE provider is also included and is automatically registered in the java.security security properties file included with the Java 2 SDK, v 1.4.

Strong Cryptography Is the Default, Unlimited Is Available

Due to import control restrictions, the jurisdiction policy files shipped with the Java 2 SDK, v 1.4 allow "strong" but limited cryptography to 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). You can download this version and replace the strong cryptography versions supplied with the Java 2 SDK, v 1.4 with the unlimited ones. See

http://java.sun.com/products/jce/index-14.html
for information indicating where to go to download the unlimited version.

The jurisdiction policy files have been relocated to

<java-home>\lib\security         [Windows]
<java-home>/lib/security         [Solaris]
where <java-home> refers to the directory where the runtime software is installed, which is the top-level directory of the JavaTM 2 Runtime Environment (JRE) or the jre directory in the JavaTM 2 SDK (Java 2 SDK) software. They have been moved to this standard location so that it is easy to replace the strong cryptography versions that come with the Java 2 SDK, v 1.4 with the unlimited ones.

Provider Authentication of JCE Framework No Longer Required

In JCE 1.2.1, providers needed to include code to authenticate the JCE framework to assure themselves of the integrity and authenticity of the JCE that they plugged into. Now that JCE is integrated into the Java 2 SDK, v 1.4, this is no longer necessary.

JCE 1.2.1 providers which follow the guidance in How to Implement a Provider for the Java Cryptography Extension 1.2.1 will continue to work with the JCE framework in the Java 2 SDK, v 1.4.

However, a provider whose framework authentication code locates the JCE framework via protection domain instead of following the recommendations in the aforementioned JCE 1.2.1 JCE provider document will not work in the Java 2 SDK, v 1.4. Now that JCE has been integrated into the Java 2 SDK, v 1.4, the JCE framework has a null code source just like any other class in the Java 2 SDK, v 1.4. Provider vendors can either modify their provider to follow the recommended approach for authenticating the framework, or put in a conditional so that the framework authentication code is only executed when the provider is being run with JCE 1.2.1.

Support for Additional Features of PKCS #1, #5 and #8

JCE and JCA have been enhanced to support the additional features of PKCS #1, #5 and #8. The following classes were added:

  • java.security.spec.RSAOtherPrimeInfo
  • java.security.spec.RSAMultiPrimePrivateCrtKeySpec
  • java.security.interfaces.RSAMultiPrimePrivateCrtKey
  • java.security.spec.PSSParameterSpec
  • javax.crypto.interfaces.PBEKey
  • javax.crypto.EncryptedPrivateKeyInfo

The following methods were added to the javax.crypto.spec.PBEKeySpec class:

public PBEKeySpec(char[] password, byte[] salt,
    int iterationCount, int keyLength)
public PBEKeySpec(char[] password, byte[] salt,
    int iterationCount)
public final void clearPassword()
public final byte[] getSalt()
public final int getIterationCount()
public final int getKeyLength()

SunJCE Default Blowfish Keysize Has Changed

The SunJCE provider's default keysize for the Blowfish algorithm has changed from 56 bytes to 56 bits.

Cryptographic Concepts

This section provides a high-level description of the concepts implemented by the API, and the exact meaning of the technical terms used in the API specification.

Encryption and Decryption

Encryption is the process of taking data (called cleartext) and a short string (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 short key string, and producing cleartext.

Password-Based Encryption

Password-Based Encryption (PBE) derives an encryption key from a password. In order to make the task of getting from password to key very time-consuming for an attacker, most PBE implementations will mix in a random number, known as a salt, to create the key.

Cipher

Encryption and decryption are done using a cipher. A cipher is an object capable of carrying out encryption and decryption according to an encryption scheme (algorithm).

Key Agreement

Key agreement is a protocol by which 2 or more parties can establish the same cryptographic keys, without having to exchange any secret information.

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, message authentication codes 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, e.g., MD5 or SHA-1, in combination with a secret shared key. HMAC is specified in RFC 2104.

Core Classes

  • The Cipher Class

    The Cipher class provides the functionality of a cryptographic cipher used for encryption and decryption. It forms the core of the JCE framework.

    Creating a Cipher Object

    Like other engine classes in the API, Cipher objects are created using the getInstance factory methods of the Cipher class. A factory method is a static method that returns an instance of a class, in this case, an instance of Cipher, which implements a requested transformation.

    To create a Cipher object, you must specify the transformation name. You may also specify which provider you want to supply the implementation of the requested transformation:

        public static Cipher getInstance(String transformation);

    public static Cipher getInstance(String transformation,
                                     String provider);

    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, if 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.

    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 no mode or padding have been 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.

    When requesting a block cipher in stream cipher mode (e.g., DES in CFB or OFB 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.)

    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 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 a 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 was 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) was 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 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)

  • The Cipher Stream Classes

    JCE introduces the concept of secure streams, which combine an InputStream or OutputStream with a Cipher object. Secure streams are provided by the CipherInputStream and CipherOutputStream 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 additonally 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 have 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);
    }

      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);
    }

      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.

    • 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.

      There is one 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 KeyGenerator Class

    A key generator is used to generate secret keys for symmetric algorithms.

    Creating a Key Generator

    Like other engine classes in the API, KeyGenerator objects are created using the getInstance factory methods of the KeyGenerator class. A factory method is a static method that returns an instance of a class, in this case, an instance of KeyGenerator which provides an implementation of the requested key generator.

    getInstance takes as its argument the name of a symmetric algorithm for which a secret key is to be generated. Optionally, a package provider name may be specified:

        public static KeyGenerator getInstance(String algorithm);

    public static KeyGenerator getInstance(String algorithm,
                                           String provider);

    If just an algorithm name is specified, the system will determine if there is an implementation of the requested key generator available in the environment, and if there is more than one, if there is a preferred one.

    If both an algorithm name and a package provider are specified, the system will determine if there is an implementation of the requested key generator in the package requested, and throw an exception if there is not.

    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 SecretKeyFactory Class

    This class represents a factory for secret keys.

    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.

    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.

    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");

  • 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 KeyAgreement Class

    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. Like other engine classes in the API, KeyAgreement objects are created using the getInstance factory methods of the KeyAgreement class. A factory method is a static method that returns an instance of a class, in this case, an instance of KeyAgreement which provides the requested key agreement algorithm.

    getInstance takes as its argument the name of a key agreement algorithm. Optionally, a package provider name may be specified:

        public static KeyAgreement getInstance(String algorithm);

    public static KeyAgreement getInstance(String algorithm,
                                           String provider);

    If just an algorithm name is specified, the system will determine if there is an implementation of the requested key agreement available in the environment, and if there is more than one, if there is a preferred one.

    If both an algorithm name and a package provider are specified, the system will determine if there is an implementation of the requested key agreement in the package requested, and throw an exception if there is not.

    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 agreeement: 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 (see Appendix F), 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);

  • The Mac Class

    The Mac class provides the functionality of a Message Authentication Code (MAC). Please refer to the code example in Appendix F.

    Creating a Mac Object

    Like other engine classes in the API, Mac objects are created using the getInstance factory methods of the Mac class. A factory method is a static method that returns an instance of a class, in this case, an instance of Mac which provides the requested MAC algorithm.

    getInstance takes as its argument the name of a MAC algorithm. Optionally, a package provider name may be specified:

        public static Mac getInstance(String algorithm);

    public static Mac getInstance(String algorithm,
                                  String provider);

    If just an algorithm name is specified, the system will determine if there is an implementation of the requested MAC algorithm available in the environment, and if there is more than one, if there is a preferred one.

    If both an algorithm name and a package provider are specified, the system will determine if there is an implementation of the requested MAC algorithm in the package requested, and throw an exception if there is not.

    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);

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 desired that such applications have fewer cryptographic restrictions than those mandated. If you want to skip this section, you can go on to Installing JCE Providers for the Java 2 SDK, v 1.4.]

[Note 2: Throughout this section, the term "application" is meant to encompass both applications and applets.]

The JCE framework within the Java 2 SDK, v 1.4 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 2 SDK, v 1.4 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 JCE 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 JCE 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 JCE 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 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 JCE code searches the installed providers for one that implements the specified exemption mechanism. If it finds such a provider, JCE 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 Java 2 SDK, v 1.4, which is:

permission <crypto permission class name>[ <alg_name>
    [[, <exemption mechanism name>][, <maxKeySize>
    [, <AlgorithmParameterSpec class name>,
    <parameters for constructing an AlgorithmParameterSpec object>]]]];

See Appendix D 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, JCE 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.

Installing JCE Providers for the Java 2 SDK, v 1.4

In order to be used, a cryptographic provider must be installed and registered, either statically or dynamically. Cryptographic providers for JCE in the Java 2 SDK, v 1.4 are installed and configured the same way as all other providers for the JavaTM 2 platform. More information about installing and configuring providers can be found in the Installing Providers section of the JavaTM Cryptography Architecture API Specification & Reference document.

You do not need to register the "SunJCE" provider because it is pre-registered. If you want to use other providers, read the following sections to see how to register them.

Installing a provider is done in two steps: installing the provider package classes, and configuring the provider. In some situations you will also need to set permissions for the provider prior to using it.

Installing the Provider Classes

The first thing you must do is make the provider classes available so that they can be found when requested. Provider classes are shipped as a signed JAR (Java ARchive) file.

There are two possible ways to install the 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 class path.

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 JavaTM 2 Runtime Environment (JRE) or the jre directory in the JavaTM 2 SDK (Java 2 SDK) software. For example, if you have the Java 2 SDK, v 1.4 installed on Solaris in a directory named /home/user1/Java 2 SDK1.4.0, or on Microsoft Windows in a directory named C:\Java 2 SDK1.4.0, then you need to install the JAR file in the following directory:

/home/user1/Java 2 SDK1.4.0/jre/lib/ext    [Solaris]
C:\Java 2 SDK1.4.0\jre\lib\ext             [Windows]

Similarly, if you have the JRE, v 1.4 installed on Solaris in a directory named /home/user1/j2re1.4.0, or on Microsoft Windows in a directory named C:\j2re1.4.0, you need to install the JAR file in the following directory:

/home/user1/j2re1.4.0/lib/ext         [Solaris]
C:\j2re1.4.0\lib\ext                  [Windows]

For more information, refer to these sections in the "Extension Mechanism Architecture" specification: Installed Extensions and 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 the Java 2 SDK v 1.4 installed on Solaris in a directory named /home/user1/Java 2 SDK1.4.0, or on Microsoft Windows in a directory named C:\Java 2 SDK1.4.0, then you need to edit the following file:

/home/user1/Java 2 SDK1.4.0/jre/lib/security/java.security  [Solaris]
C:\Java 2 SDK1.4.0\jre\lib\security\java.security           [Windows]

Similarly, if you have the Java 2 Runtime Environment, v 1.4 installed on Solaris in a directory named /home/user1/j2re1.4.0, or on Microsoft Windows in a directory named C:\j2re1.4.0, then you need to edit this file:

/home/user1/j2re1.4.0/lib/security/java.security       [Solaris]
C:\j2re1.4.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". The provider vendor should supply you this name.

The Java 2 SDK, v 1.4 comes standard with a provider named "SUN", which is automatically configured as a static provider in the java.security properties file, as follows:

security.provider.1=sun.security.provider.Sun

(The "SUN" provider's master class is the Sun class in the sun.security.provider package.)

The JCE provider "SunJCE" and other security-related providers shipped with the Java 2 platform are also automatically configured as static providers.

To utilize another JCE provider, add a line registering the alternate provider, giving it whatever preference order you prefer (and making corresponding adjustments to the other providers' orders, if needed).

Suppose that the master class of a provider you want to register is the CryptoX class in the com.cryptox.provider package, and that you would like to make this provider the second preferred provider. To do so, add the following line to the java.security file below the line for the "SUN" provider, and increment the preference order numbers for all other providers whose numbers were greater than or equal to 2 before your addition:

    security.provider.2=com.cryptox.provider.CryptoX
Note: Providers may also be registered dynamically. To do so, a program 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 your code that dynamically registers this provider is in the MyApp.jar file in the /localWork directory, then here is a sample policy file grant statement granting that permission:
grant codeBase "file:/localWork/MyApp.jar" {
  permission java.security.SecurityPermission
      "insertProvider.MyJCE";
};

Setting Provider Permissions

Whenever JCE providers are not installed extensions, permissions must be granted for when applets or applications using JCE 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.

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 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";
};

JCE Keystore

The "SunJCE" provider supplies its own implementation of the java.security.KeyStore class in the Java 2 SDK, v 1.4. Its implementation employs a much stronger protection of private keys (using password-based encryption with Triple DES) than the keystore implementation supplied by the "SUN" provider in the Java 2 SDK, v 1.4. (Note that because the Java 2 SDK, v 1.4 is distributed world-wide in binary and source format, it cannot employ any strong encryption mechanisms.)

In order to take advantage of the keystore implementation of the "SunJCE" provider, you specify "JCEKS" as the keystore type.

You may upgrade your keystore of type "JKS" - this is the name of the keystore type implemented by the "SUN" provider in the Java 2 SDK - to a JCE keystore of type "JCEKS" by changing the password of a private-key entry in your keystore.

To apply the cryptographically strong(er) key protection supplied by "SunJCE" 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

You may want to change the password back to its old value, using the same command.

See Security Tools for more information about keytool and about keystores and how they are managed.

Code Examples

This section is a short tutorial on how to use some of the major features of the JCE APIs in the Java 2 SDK, v 1.4. Complete sample programs that exercise the APIs can be found in Appendix F of this document.

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 Data Encryption Standard (DES).

Generating a Key

To create a DES key, we have to instantiate a KeyGenerator for DES. We do not specify a provider, because we do not care about a particular DES key generation implementation. Since we do not initialize the KeyGenerator, a system-provided source of randomness will be used to create the DES key:

    KeyGenerator keygen = KeyGenerator.getInstance("DES");
    SecretKey desKey = 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 a DES (Data Encryption Standard) cipher in Electronic Codebook mode, with PKCS #5-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 DES is "DES", the standard name for the Electronic Codebook mode is "ECB", and the standard name for PKCS #5-style padding is "PKCS5Padding":

    Cipher desCipher;

    // Create the cipher
    desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");

We use the generated desKey from above to initialize the Cipher object for encryption:

    // Initialize the cipher for encryption
    desCipher.init(Cipher.ENCRYPT_MODE, desKey);

    // Our cleartext
    byte[] cleartext = "This is just an example".getBytes();

    // Encrypt the cleartext
    byte[] ciphertext = desCipher.doFinal(cleartext);

    // Initialize the same cipher for decryption
    desCipher.init(Cipher.DECRYPT_MODE, desKey);

    // Decrypt the ciphertext
    byte[] cleartext1 = desCipher.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.

The following method is an example of how to collect a user password as a char array:

    /**
     * Reads user password from given input stream.
     */
    public char[] readPasswd(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;
    }

In order to use Password-Based Encryption (PBE) as defined in PKCS #5, 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
    // "readPasswd" 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(readPasswd(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 F for sample programs exercising the Diffie-Hellman key exchange between 2 and 3 parties, respectively.

Appendix A: Standard Names

The JCE API requires and utilizes a set of standard names for algorithms, algorithm modes, and padding schemes. This specification establishes the following names as standard names. It supplements the list of standard names defined in Appendix A in the JavaTM Cryptography Architecture API Specification & Reference. Note that algorithm names are treated case-insensitively.

In some cases naming conventions are suggested for forming names that are not explicitly listed, to facilitate name consistency across provider implementations. Such suggestions use items in angle brackets (such as <digest> and <encryption>) as placeholders to be replaced by specific message digest, encryption algorithm, and other names.

Cipher

Algorithm

The following names can be specified as the algorithm component in a transformation when requesting an instance of Cipher:

  • AES: Advanced Encryption Standard as specified by NIST in a draft FIPS. Based on the Rijndael algorithm by Joan Daemen and Vincent Rijmen, AES is a 128-bit block cipher supporting keys of 128, 192, and 256 bits.

  • Blowfish: The block cipher designed by Bruce Schneier.

  • DES: The Digital Encryption Standard as described in FIPS PUB 46-2.

  • DESede: Triple DES Encryption (DES-EDE).

  • PBEWith<digest>And<encryption> or PBEWith<prf>And<encryption>: The password-based encryption algorithm (PKCS #5), 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, RC4, and 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.

Mode

The following names can be specified as the mode component in a transformation when requesting an instance of Cipher:

  • NONE: No mode.

  • CBC: Cipher Block Chaining Mode, as defined in FIPS PUB 81.

  • CFB: Cipher Feedback Mode, as defined in FIPS PUB 81.

  • ECB: Electronic Codebook Mode, as defined in: The National Institute of Standards and Technology (NIST) Federal Information Processing Standard (FIPS) PUB 81, "DES Modes of Operation," U.S. Department of Commerce, Dec 1980.

  • OFB: Output Feedback Mode, as defined in FIPS PUB 81.

  • PCBC: Propagating Cipher Block Chaining, as defined by Kerberos V4.

Padding

The following names can be specified as the padding component in a transformation when requesting an instance of Cipher:

  • NoPadding: No padding.

  • OAEPWith<digest>And<mgf>Padding: Optimal Asymmetric Encryption Padding scheme defined in PKCS #1, where <digest> should be replaced by the message digest and <mgf> by the mask generation function. Example: OAEPWithMD5AndMGF1Padding.

  • 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 make 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.

    Note that this padding mechanism is not supported by the "SunJCE" provider.

KeyAgreement

The following algorithm names can be specified when requesting an instance of KeyAgreement:

  • DiffieHellman: Diffie-Hellman Key Agreement as defined in PKCS #3: Diffie-Hellman Key-Agreement Standard, RSA Laboratories, version 1.4, November 1993.

KeyGenerator

The following algorithm names can be specified when requesting an instance of KeyGenerator:

  • AES

  • Blowfish

  • DES

  • DESede

  • HmacMD5

  • HmacSHA1

KeyPairGenerator

The following algorithm names can be specified when requesting an instance of KeyPairGenerator:

  • DiffieHellman

SecretKeyFactory

The following algorithm names can be specified when requesting an instance of SecretKeyFactory:

  • AES

  • DES

  • DESede

  • PBEWith<digest>And<encryption> or PBEWith<prf>And<encryption>: Secret-key factory for use with PKCS #5 password-based encryption, where <digest> is a message digest, <prf> is a pseudo-random function, and <encryption> is an encryption algorithm. Examples: PBEWithMD5AndDES (PKCS #5, v 1.5) and PBEWithHmacSHA1AndDESede (PKCS #5, v 2.0). Note: These both use only the low order 8 bits of each password character.

KeyFactory

The following algorithm names can be specified when requesting an instance of KeyFactory:

  • DiffieHellman

AlgorithmParameterGenerator

The following algorithm names can be specified when requesting an instance of AlgorithmParameterGenerator:

  • DiffieHellman

AlgorithmParameters

The following algorithm names can be specified when requesting an instance of AlgorithmParameters:

  • Blowfish

  • DES

  • DESede

  • DiffieHellman

  • PBE

MAC

The following algorithm names can be specified when requesting an instance of Mac:

  • HmacMD5: The HMAC-MD5 keyed-hashing algorithm as defined in RFC 2104: "HMAC: Keyed-Hashing for Message Authentication" (February 1997).

  • HmacSHA1: The HMAC-SHA1 keyed-hashing algorithm as defined in RFC 2104: "HMAC: Keyed-Hashing for Message Authentication" (February 1997).

  • PBEWith<mac>: MAC for use with PKCS #5 v 2.0 password-based message authentication standard, where <mac> is a Message Authentication Code algorithm name. Example: PBEWithHmacSHA1.

Keystore Types

The following types can be specified when requesting an instance of KeyStore:

  • JCEKS: The proprietary keystore type implemented by the "SunJCE" provider.

Exemption Mechanisms

The following exemption mechanism names can be specified in the permission policy file that accompanies an application considered "exempt" from cryptographic restrictions:

  • 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.

Appendix B: SunJCE Default Keysizes

The SunJCE provider uses the following default keysizes:

  • KeyGenerator

    • DES: 56 bits

    • Triple DES: 112 bits

    • Blowfish: 56 bits

    • HmacMD5: 64 bytes

    • HmacSHA1: 64 bytes

  • KeyPairGenerator

    • Diffie-Hellman: 1024 bits

  • AlgorithmParameterGenerator

    • Diffie-Hellman: 1024 bits

Appendix C: SunJCE Keysize Restrictions

The SunJCE provider enforces the following restrictions on the keysize passed to the initialization methods of the following classes:

  • KeyGenerator

    Restrictions (by algorithm):

    • DES: keysize must be equal to 56

    • Triple DES: keysize must be equal to 112 or 168

      Note: 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.

    • Blowfish: keysize must be a multiple of 8, and can only range from 32 to 448, inclusive

  • KeyPairGenerator

    Restrictions (by algorithm):

    • Diffie-Hellman: keysize must be a multiple of 64, and can only range from 512 to 1024, inclusive

  • AlgorithmParameterGenerator

    Restrictions (by algorithm):

    • Diffie-Hellman: keysize must be a multiple of 64, and can only range from 512 to 1024, inclusive

Appendix D: Jurisdiction Policy File Format

JCE represents its jurisdiction policy files as J2SE-style policy files with corresponding permission statements. As described in Default Policy Implementation and Policy File Syntax, a J2SE 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 JCE, 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 E: Maximum Key Sizes Allowed by "Strong" Jurisdiction Policy Files

Due to import control restrictions, the jurisdiction policy files shipped with the Java 2 SDK, v 1.4 allow "strong" but limited cryptography to be used. Here are the maximum key sizes allowed by this "strong" version of the jurisdiction policy files:

Algorithm

Maximum Key Size

DES

64

DESede

*

RC2

128

RC4

128

RC5

128

RSA

2048

* (all others)

128

Appendix F: Sample Programs

  • Diffie-Hellman Key Exchange between 2 Parties

    /*
 * Copyright 1997-2001 by Sun Microsystems, Inc.,
 * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
 * 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.
 */

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 instanticate 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 1997-2001 by Sun Microsystems, Inc.,
 * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
 * 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.
 */

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 Example

    /*
 * Copyright 1997-2001 by Sun Microsystems, Inc.,
 * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
 * 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.
 */

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 1997-2001 by Sun Microsystems, Inc.,
 * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
 * 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.
 */

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());
    }
}

Copyright © 1996-2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-security@java.sun.com. 		Sun
Java Software
Last modified: 10 Jan 2002


Security

Java

Java GSS

 Security Contents
New Features in JavaTM GSS for Java TM 2 SDK, Standard Edition, v 1.4.2 include the following:
  • 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 J2SE, 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.

    The current draft which updates RFC 1510, is available online: http://www.ietf.org/internet-drafts/draft-ietf-krb-wg-kerberos-clarifications-04.txt.

  • 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 © 1995-2003 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-security@sun.com. This is not a subscription list. 		Sun
Java Software


Single Sign-on Using Kerberos in Java

Mayank Upadhyay
Ram Marti

Sun Microsystems, Inc.

{mayank.upadhyay, ram.marti} @sun.com

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 JavaTM 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.

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 J2SE, 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 J2SE 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 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 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 J2SE, 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. JavaTM 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.
      Feedback
      Last modified: Wed May 2 12:54:31 PDT 2001


All Classes (Java GSS-API Utilities )

 All Classes
GSSUtil


API Help (Java GSS-API Utilities )

Overview Package Class Use Tree Index Help
Java GSS-API Utilities
PREV NEXT FRAMES NO FRAMES

How This API Document Is Organized

This API (Application Programming Interface) document has pages corresponding to the items in the navigation bar, described as follows.

Overview

The Overview page is the front page of this API document and provides a list of all packages with a summary for each. This page can also contain an overall description of the set of packages.

Package

Each package has a page that contains a list of its classes and interfaces, with a summary for each. This page can contain four categories:

  • Interfaces (italic)
  • Classes
  • Exceptions
  • Errors

Class/Interface

Each class, interface, nested class and nested interface has its own separate page. Each of these pages has three sections consisting of a class/interface description, summary tables, and detailed member descriptions:

  • Class inheritance diagram
  • Direct Subclasses
  • All Known Subinterfaces
  • All Known Implementing Classes
  • Class/interface declaration
  • Class/interface description

  • Nested Class Summary
  • Field Summary
  • Constructor Summary
  • Method Summary

  • Field Detail
  • Constructor Detail
  • Method Detail
Each summary entry contains the first sentence from the detailed description for that item. The summary entries are alphabetical, while the detailed descriptions are in the order they appear in the source code. This preserves the logical groupings established by the programmer.

Use

Each documented package, class and interface has its own Use page. This page describes what packages, classes, methods, constructors and fields use any part of the given class 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.

Tree (Class Hierarchy)

There is a Class Hierarchy page for all packages, plus a hierarchy for each package. Each hierarchy page contains a list of classes and a list of interfaces. The classes are organized by inheritance structure starting with java.lang.Object. The interfaces do not inherit from java.lang.Object.
  • When viewing the Overview page, clicking on "Tree" displays the hierarchy for all packages.
  • When viewing a particular package, class or interface page, clicking "Tree" displays the hierarchy for only that package.

Index

The Index contains an alphabetic list of all classes, interfaces, constructors, methods, and fields.

Prev/Next

These links take you to the next or previous class, interface, package, or related page.

Frames/No Frames

These links show and hide the HTML frames. All pages are available with or without frames.

Serialized Form

Each serializable or externalizable 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 description.

This help file applies to API documentation generated using the standard doclet.

Overview Package Class Use Tree Index Help
Java GSS-API Utilities
PREV NEXT FRAMES NO FRAMES


Java GSS-API Utilities

Frame Alert

This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client.
Link toNon-frame version.


Index (Java GSS-API Utilities )

Overview Package Class Use Tree Index Help
Java GSS-API Utilities
PREV NEXT FRAMES NO FRAMES
C G

C

com.sun.security.jgss - package com.sun.security.jgss
createSubject(GSSName, GSSCredential) - Static method in class com.sun.security.jgss.GSSUtil
Use this method to convert a GSSName and GSSCredential into a Subject.

G

GSSUtil - class com.sun.security.jgss.GSSUtil.
GSS-API Utilities for using in conjunction with Sun Microsystem's implementation of Java GSS-API.
GSSUtil() - Constructor for class com.sun.security.jgss.GSSUtil
C G
Overview Package Class Use Tree Index Help
Java GSS-API Utilities
PREV NEXT FRAMES NO FRAMES


Overview (Java GSS-API Utilities )

Overview Package Class Use Tree Index Help
Java GSS-API Utilities
PREV NEXT FRAMES NO FRAMES

JavaTM GSS-API Utilities

This package contains GSS-API utilities for using in conjunction with Sun Microsystem's implementation of Java GSS-API.

See:
Description

Packages
com.sun.security.jgss

This package contains GSS-API utilities for using in conjunction with Sun Microsystem's implementation of Java GSS-API.

Overview Package Class Use Tree Index Help
Java GSS-API Utilities
PREV NEXT FRAMES NO FRAMES


Class Hierarchy (Java GSS-API Utilities )

Overview Package Class Use Tree Index Help
Java GSS-API Utilities
PREV NEXT FRAMES NO FRAMES

Hierarchy For All Packages

Package Hierarchies:
com.sun.security.jgss

Class Hierarchy

  • class java.lang.Object
    • class com.sun.security.jgss.GSSUtil
Overview Package Class Use Tree Index Help
Java GSS-API Utilities
PREV NEXT FRAMES NO FRAMES


GSSUtil (Java GSS-API Utilities )

Overview Package Class Use Tree Index Help
Java GSS-API Utilities
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

com.sun.security.jgss
Class GSSUtil

java.lang.Object
    extended by com.sun.security.jgss.GSSUtil
public class GSSUtil
extends Object

GSS-API Utilities for using in conjunction with Sun Microsystem's implementation of Java GSS-API.

Constructor Summary
GSSUtil()
Method Summary
static Subject createSubject(GSSName principals, GSSCredential credentials)
Use this method to convert a GSSName and GSSCredential into a Subject.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

GSSUtil

public GSSUtil()
Method Detail

createSubject

public static Subject createSubject(GSSName principals,
                                    GSSCredential credentials)
Use this method to convert a GSSName and GSSCredential into a Subject. Typically this would be done by a server that wants to impersonate a client thread at the Java level by setting a client Subject in the current access control context. If the server is merely interested in using a principal based policy in its local JVM, then it only needs to provide the GSSName of the client. The elements from the GSSName are placed in the principals set of this Subject and those from the GSSCredential are placed in the private credentials set of the Subject. Any Kerberos specific elements that are added to the subject will be instances of the standard Kerberos implementation classes defined in javax.security.auth.kerberos.

Parameters:
principals - a GSSName containing one or more mechanism specific representations of the same entity. These mechanism specific representations will be populated in the returned Subject's principal set.
credentials - a GSSCredential containing one or more mechanism specific credentials for the same entity. These mechanism specific credentials will be populated in the returned Subject's private credential set. Passing in a value of null will imply that the private credential set should be left empty.
Returns:
a Subject with the entries that contain elements from the given GSSName and GSSCredential.
Overview Package Class Use Tree Index Help
Java GSS-API Utilities
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD


com.sun.security.jgss (Java GSS-API Utilities )

Overview Package Class Use Tree Index Help
Java GSS-API Utilities
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package com.sun.security.jgss

Class Summary
GSSUtil GSS-API Utilities for using in conjunction with Sun Microsystem's implementation of Java GSS-API.

Overview Package Class Use Tree Index Help
Java GSS-API Utilities
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES


com.sun.security.jgss Class Hierarchy (Java GSS-API Utilities )

Overview Package Class Use Tree Index Help
Java GSS-API Utilities
PREV NEXT FRAMES NO FRAMES

Hierarchy For Package com.sun.security.jgss

Class Hierarchy

  • class java.lang.Object
    • class com.sun.security.jgss.GSSUtil
Overview Package Class Use Tree Index Help
Java GSS-API Utilities
PREV NEXT FRAMES NO FRAMES


Uses of Package com.sun.security.jgss (Java GSS-API Utilities )

Overview Package Class Use Tree Index Help
Java GSS-API Utilities
PREV NEXT FRAMES NO FRAMES

Uses of Package
com.sun.security.jgss

No usage of com.sun.security.jgss

Overview Package Class Use Tree Index Help
Java GSS-API Utilities
PREV NEXT FRAMES NO FRAMES


Uses of Class com.sun.security.jgss.GSSUtil (Java GSS-API Utilities )

Overview Package Class Use Tree Index Help
Java GSS-API Utilities
PREV NEXT FRAMES NO FRAMES

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
PREV NEXT FRAMES NO FRAMES


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.


JAAS Authentication

The JavaTM Authentication and Authorization Service (JAAS) was introduced as an optional package to the JavaTM 2 SDK, Standard Edition (J2SDK), v 1.3. JAAS has now been integrated into the J2SDK, v 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.


Use of JavaTM 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. 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.


Use of JAAS Login Utility and JavaTM 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 JavaTM GSS-API for Secure Message Exchanges Without JAAS Programming tutorial. In that tutorial, JAAS (JavaTM 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 JavaTM 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.


Feedback

Please e-mail Java GSS-API and JAAS tutorial comments to:

java-security@sun.com

Please specify which tutorial(s) you are referring to in your message.

Though we value your input, before sending problem reports please search the Java Security Q&A Archives:

http://archives.java.sun.com/archives/java-security.html

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 2 Standard Edition security team.

Please note that due to the volume of messages we receive, we may not be able to respond to every individual message.


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 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 J2SE API. Any class, therefore, can represent a credential.


Introduction to JAAS and Java GSS-API Tutorials

This page links to a series of tutorials demonstrating various aspects of the use of JAAS (JavaTM Authentication and Authorization Service) and JavaTM GSS-API.

JAAS can be used for two purposes:

  • for authentication of users, to reliably and securely determine who is currently executing Java code, and

  • for authorization of users to ensure they have the access control rights (permissions) required to do security-sensitive operations.

Java GSS-API is used for securely exchanging messages between communicating applications. The Java GSS-API contains the Java bindings for the Generic Security Services Application Program Interface (GSS-API) defined in RFC 2853. GSS-API offers application programmers uniform access to security services atop a variety of underlying security mechanisms, including Kerberos.

Note: JSSE is another API that can be used for secure communication. For the differences between the two, see When to use Java GSS-API vs. JSSE.

The reason both JAAS and Java GSS-API tutorials are presented together is because JAAS authentication is typically performed prior to secure communication using Java GSS-API. Thus JAAS and Java GSS-API are related and often used together. However, it is possible for applications to use JAAS without Java GSS-API, and it is also possible to use Java GSS-API without JAAS. Furthermore, JAAS itself can be used simply for authentication or for both authentication and authorization.

The following tutorials provide working examples for all of the scenarios described above.

  1. Use of JavaTM GSS-API for Secure Message Exchanges Without JAAS Programming

    Demonstrates the use of the Java GSS-API for secure message exchanges between a client application and a server application.

  2. JAAS Authentication

    Explains how an application can authenticate users using JAAS.

  3. JAAS Authorization

    Explains how to enforce user-based access controls using JAAS.

  4. Use of JAAS Login Utility

    Describes a utility program that authenticates a user using JAAS and executes any application as that user. The appropriate user-based access controls are enforced while the application executes. This utility, as a convenience, essentially performs the operations described in the JAAS Authentication and JAAS Authorization tutorials on your behalf. Therefore it is possible to skip directly to this tutorial if you do not need to know how to perform JAAS authentication and authorization directly.

  5. Use of JAAS Login Utility and Java GSS-API for Secure Message Exchanges

    The most comprehensive tutorial. The Login utility is used to authenticate a service user and to start up a server application as that user. The Login utility is also used to authenticate a client user and to start up a client application as that user. Finally the client and server applications, on behalf of their authenticated client and service users, exchange secure messages using the Java GSS-API.

  6. More Things You Can Do With Java GSS-API and JAAS

    Shows additional operations the server application in the previous tutorial can perform once communication has been established with the client application.

All applications in all tutorials in this series utilize Kerberos Version 5 as the underlying technology for authentication and secure communication. See Kerberos Requirements. The term "Kerberos" used throughout the tutorials is meant to refer to Kerberos Version 5.

Related Documentation

API Specifications

  • com.sun.security.jgss Package
  • com.sun.security.auth Package
  • com.sun.security.auth.callback Package
  • com.sun.security.auth.login Package
  • com.sun.security.auth.module Package

User Guides

  • JavaTM Authentication and Authorization Service (JAAS) Reference Guide.

Papers

  • Single Sign-on Using Kerberos in Java

  • JAAS white paper

Tutorials

  • Java 2 Security Tutorial

Other Java Security Documentation

  • Default Policy Implementation and Policy File Syntax

  • Permissions in the JavaTM 2 SDK

  • Java 2 Security Architecture

Reference Document

  • Generic Security Service API Version 2: Java Bindings presented and requested comments on the Java bindings for GSS-API that are incorporated into Java GSS-API.

Copyright © 2001-2002 Sun Microsystems, Inc. All Rights Reserved.

Next Tutorial Feedback


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.


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 JREs from all vendors. (Actually, 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 (J2RE v 1.4).

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, not a part of the J2RE, v 1.4.

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 J2SDK v 1.4 installed on Solaris in a directory named /jdk1.4, the directory in which the configuration file is looked for is:
    /jdk1.4/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.


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 J2RE.

    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.)


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.


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\"";


Troubleshooting

Below are listed some problems that may occur when attempting a login, and suggestions for solving them.

  • java.lang.SecurityException at javax.security.auth.login.Configuration.getConfiguration

    Cause: There was a problem processing the JAAS login configuration file, possibly due to a syntax error in the file.

    Solution: Check the configuration file carefully for errors. See JAAS Login Configuration File for information about the syntax required in the login configuration file.

  • javax.security.auth.login.LoginException: KrbException:: Pre-authentication information was invalid (24) - Preauthentication failed

    Cause 1: The password entered is incorrect.

    Solution 1: Verify the password.

    Cause 2: If you are using the keytab to get the key (e.g., by setting the useKeyTab option to true in the Krb5LoginModule entry in the JAAS login configuration file), then the key might have changed since you updated the keytab.

    Solution 2: Consult your Kerberos documentation to generate a new keytab and use that keytab.

    Cause 3: Clock skew - If the time on the KDC and on the client differ significanlty (typically 5 minutes), this error can be returned.

    Solution 3: Synchronize the clocks (or have a system administrator do so).

  • GSSException: No valid credentials provided (Mechanism level: Attempt to obtain new INITIATE credentials failed! (null)) . . . Caused by: javax.security.auth.login.LoginException: Clock skew too great

    Cause: Kerberos requires the time on the KDC and on the client to be loosely synchronized. (The default is within 5 minutes.) If that's not the case, you will get this error.

    Solution: Synchronize the clocks (or have a system administrator do so).

  • javax.security.auth.login.LoginException: KrbException: Null realm name (601) - default realm not specified

    Cause: The default realm is not specified in the Kerberos configuration file krb5.conf (if used), provided as a part of the user name, or specified via the java.security.krb5.realm system property.

    Solution: Verify that your Kerberos configuration file (if used) contains an entry specifying the default realm, or directly specify it by setting the value of the java.security.krb5.realm system property and/or including it in your user name when authenticating using Kerberos.

  • javax.security.auth.login.LoginException: java.net.SocketTimeoutException: Receive timed out

    Solution: Verify that the Kerberos KDC is up and running.

  • GSSException: No valid credentials provided (Mechanism level: Failed to find any Kerberos Ticket)

    Cause: This may occur if no valid Kerberos credentials are obtained. In particular, this occurs if you want the underlying mechanism to obtain credentials but you forgot to indicate this by setting the useSubjectCredsOnly system property value to false (for example via -DuseSubjectCredsOnly=false in your execution command).

    Solution: Be sure to set the useSubjectCredsOnly system property value to false if you want the underlying mechanism to obtain credentials, rather than your application or a wrapper program (such as the Login utility used by some of the tutorials) performing authentication using JAAS.

  • javax.security.auth.login.LoginException: Could not load configuration file <krb5.conf> (No such file or directory)

    Cause: The tutorials' sample execution commands specify the default Kerberos realm and KDC by setting values for the java.security.krb5.realm and java.security.krb5.kdc system properties. If you like, you can instead have a krb5.conf Kerberos configuration file used. Such a file includes information about what the default realm and KDC are. To use a krb5.conf file, you either set the system property java.security.krb5.conf (instead of the realm and kdc properties) to specify the location of the file or you don't set any of these properties and therefore an attempt is made to locate the krb5.conf file in a default location. You will get the error "Could not load configuration file <krb5.conf> (No such file or directory)" if the file could not be found.

    Solution: Verify that the Kerberos configuration file krb5.conf is available and readable. Check Kerberos Requirements for information about how to specify the location of the krb5.conf file and where such a file is searched for by default if you don't explicitly indicate the location.

  • javax.security.auth.login.LoginException: KrbException: KDC has no support for encryption type (14) - KDC has no support for encryption type

    Cause: Your KDC does not support the encryption type requested. (Typically, the encryption type is specified in the krb5.conf Kerberos configuration file.)

    Solution: Please choose an encryption type that is supported by the KDC you are using. The encryption types supported by the Kerberos implementation from Sun Microsystems are DES_CBC_MD5,DES_CBC_CRC,and DES_CBC_MD4.

  • KDC reply did not match expectations

    Cause: The KDC sent a response that cannot be understood by the client.

    Solution: Verify that you have set correctly all the krb5.conf file configuration parameters and consult your KDC vendor's guide.

Note: A debugging mode can be enabled by setting the system property sun.security.krb5.debug to "true". This will allow you to follow the program's execution of the Kerberos V5 protocol. If you are sending feedback regarding a problem you are facing, we would appreciate your including the complete debugging output.


JSSE Reference Guide for the J2SDK, v 1.4.2

JavaTM Secure Socket Extension (JSSE)

Reference Guide

for the JavaTM 2 SDK, Standard Edition, v 1.4.2

Introduction
Features and Benefits
JSSE Standard API
SunJSSE Provider
What's New
What's New in JSSE in the Java 2 SDK, v 1.4.2
What's New in JSSE in the Java 2 SDK, v 1.4
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
SSLSocket and SSLServerSocket Classes
SSLSocketFactory and SSLServerSocketFactory Classes
SSLSession Interface
HttpsURLConnection Class
Support Classes and Interfaces
SSLContext Class
TrustManager Class
TrustManagerFactory Class
X509TrustManager Interface
KeyManager Class
KeyManagerFactory Class
X509KeyManager Interface
Relationships between TrustManagers and KeyManagers
Secondary Support Classes and Interfaces
SSLSessionContext Interface
SSLSessionBindingListener Interface
SSLSessionBindingEvent Class
HandShakeCompletedListener Interface
HandShakeCompletedEvent Class
HostnameVerifier Interface
X509Certificate Class
Previous (JSSE 1.0.x) Implementation Classes and Interfaces

Customizing JSSE
The Installation Directory <java-home>
Customization

Additional Keystore Formats

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

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 (standard extension) to the JavaTM 2 SDK, Standard Edition (J2SDK) versions 1.2 and 1.3. JSSE has now been integrated into the J2SDK, v 1.4.

JSSE provides both an application programming interface (API) framework and an implementation of that API. The JSSE API supplements the "core" cryptographic services defined in the Java 2 SDK, v 1.4 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. (It also provides a limited public key certificate API that is compatible with Java Development Kit (JDK) 1.1-based platforms. However, please note that this limited javax.security.cert certificate API is provided only for backward compatibility with JSSE 1.0.x and should not be used. Instead, use the standard java.security.cert certificate API.)

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 in the J2SDK, v 1.4 implements 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 2 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 2 platform include the Java Cryptography Extension (JCE), 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.

Note: While the JSSE APIs allow the replacement of the underlying implementations (also known as "pluggability"), due to U.S. export restrictions this release does not permit you to replace the SSL/TLS algorithms. The TrustManagerFactory and KeyManagerFactory are still fully pluggable.

Features and Benefits

JSSE includes the following important features:

  • Implemented in 100% Pure Java

  • Can be exported to most countries

  • Provides API support for SSL versions 2.0 and 3.0, and implementation of SSL version 3.0

  • Provides API support and an implementation for TLS version 1.0

  • Includes classes that can be instantiated to create secure channels (SSLSocket and SSLServerSocket)

  • 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

  • Includes code licensed from RSA Data Security Inc. such as RSA and RC4

  • Provides support for several cryptographic algorithms commonly used in cipher suites, including those listed in the following table:

Cryptographic Functionality Available With JSSE

Cryptographic Algorithm *

Cryptographic Process

Key Lengths (Bits)

RSA

Authentication and key exchange

2048 (authentication)
2048 (key exchange)
512 (key exchange)

RC4

Bulk encryption

128
128 (40 effective)

DES

Bulk encryption

64 (56 effective)
64 (40 effective)

Triple DES

Bulk encryption

192 (112 effective)

Diffie-Hellman

Key agreement

1024
512

DSA

Authentication

1024

* Note: The cryptographic algorithms shipped in the SunJSSE provider are not registered with the Java Cryptography Architecture (JCA) provider framework, and are not available for use by other applications.

** Note: The SunJSSE implementation uses the JavaTM Cryptography Extension (JCE) AES cipher for AES-based ciphersuites.

JSSE Standard API

The JSSE standard API, available in the javax.net, javax.net.ssl and javax.security.cert packages, covers:

  • Secure (SSL) sockets and server sockets.

  • 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.

  • Key and trust manager interfaces (including X.509-specific key and trust managers), and factories for creating them.

  • A class for secure HTTP URL connections.

  • A public key certificate API compatible with JDK 1.1-based platforms.

SunJSSE Provider

The J2SDK, v 1.4 release comes with a JSSE provider named "SunJSSE", which comes pre-installed and pre-registered with the JCA. This provider supplies the following cryptographic services:

  • RSA support for the signature-related JCA features of the Java 2 platform.

  • 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.

  • A read-only implementation of PKCS12 as JCA keystore type "pkcs12".
The following table lists the cipher suites that SunJSSE supports and those that are enabled by default.

Supported Cipher Suites in Default Preference Order
Name Enabled by Default New in
J2SE 1.4.2
SSL_RSA_WITH_RC4_128_MD5 | X
SSL_RSA_WITH_RC4_128_SHA | X
TLS_RSA_WITH_AES_128_CBC_SHA | X | X
TLS_DHE_RSA_WITH_AES_128_CBC_SHA | X | X
TLS_DHE_DSS_WITH_AES_128_CBC_SHA | X | X
SSL_RSA_WITH_3DES_EDE_CBC_SHA | X
SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA | X | X
SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA | X
SSL_RSA_WITH_DES_CBC_SHA | X
SSL_DHE_RSA_WITH_DES_CBC_SHA | X | X
SSL_DHE_DSS_WITH_DES_CBC_SHA | X
SSL_RSA_EXPORT_WITH_RC4_40_MD5 | X
SSL_RSA_EXPORT_WITH_DES40_CBC_SHA | X | X
SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA | X | X
SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA | X
TLS_RSA_WITH_AES_256_CBC_SHA * | X
TLS_DHE_RSA_WITH_AES_256_CBC_SHA * | X
TLS_DHE_DSS_WITH_AES_256_CBC_SHA * | X
SSL_RSA_WITH_NULL_MD5
SSL_RSA_WITH_NULL_SHA
SSL_DH_anon_WITH_RC4_128_MD5
TLS_DH_anon_WITH_AES_128_CBC_SHA | X
TLS_DH_anon_WITH_AES_256_CBC_SHA * | X
SSL_DH_anon_WITH_3DES_EDE_CBC_SHA
SSL_DH_anon_WITH_DES_CBC_SHA
SSL_DH_anon_EXPORT_WITH_RC4_40_MD5
SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA

* Requires installation of the JCE Unlimited Strength Jurisdiction Policy Files. See http://java.sun.com/j2se/1.4.2/download.html

What's New

This section highlights the differences between the JSSE in releases 1.4.2 and 1.4 of the Java 2 Platform and earlier releases.

What's New in JSSE in the J2SDK, v 1.4.2

The following changes were introduced in the JSSE in version 1.4.2 of the Java 2 platform:
  • The SunJSSE implementation now supports a number of additional ciphersuites. They include ciphersuites using AES as a symmetric cipher and ephemeral Diffie-Hellman with RSA authentication (DHE_RSA). For more information, see the table of "Supported Cipher Suites" in the section SunJSSE Provider.

  • In addition to the simple X.509 based trustmanager previously available in the SunJSSE provider, it now supports a second, PKIX-compliant trust manager. It is implemented using the default CertPath PKIX implementation. For more information, see the section TrustManagerFactory Class.

What's New in JSSE in the J2SDK, v 1.4

Here are the differences between JSSE 1.0.2 and the JSSE in the J2SDK, v 1.4:

  • JSSE Is Now in J2SDK

  • javax.security.cert Should Not Be Used

  • SunJSSE Provider Can Use JCE Providers for Encryption

  • Classes Formerly in com.sun.net.ssl Are Now in javax.net.ssl

  • New Methods and Interface

  • Changed Classes and Methods

  • Documentation Improvements

JSSE Is Now in J2SDK

JSSE was previously an optional package (extension) to the JavaTM 2 SDK, Standard Edition (J2SDK), versions 1.2 and 1.3. JSSE has now been integrated into the J2SDK, v 1.4. The SunJSSE provider is also included and is pre-registered in the java.security security properties file included with the J2SDK, v 1.4.

javax.security.cert Should Not Be Used

JSSE was developed before the java.security.cert package was widely available, so a supplemental certificate package was introduced in earlier versions of JSSE called javax.security.cert. JSSE is now bundled into the J2SDK itself and takes advantage of the more complete certificate API available in the java.security.cert package. All new applications should use java.security.cert. The javax.security.cert package exists only for backward compatibility with previous JSSE releases, and should no longer be used.

SunJSSE Provider Can Use JCE Providers for Encryption

The SunJSSE provider can now make use of JCE providers for encryption algorithms. Previously, SunJSSE always made use of internal implementations for encryption algorithms. Now implementations from providers with a higher preference order than SunJSSE are used if available. See Customizing the Encryption Algorithm Providers for more information.

Classes Formerly in com.sun.net.ssl Are Now in javax.net.ssl

All of the classes and interfaces formerly (in JSSE 1.0.x) in the com.sun.net.ssl package have been promoted to the javax.net.ssl package. The old com.sun.net.ssl classes and interfaces still exist and are unchanged, but are included in the SunJSSE provider only for backward compatibility. What is provided is actually "wrappers" that reference the new javax.net.ssl classes/interfaces.

The implementation now uses javax.net.ssl.SSLPermissions rather than com.sun.net.ssl.SSLPermission, so any policy files that used to mention com.sun.net.ssl.SSLPermission should now use javax.net.ssl.SSLPermissions instead.

New Methods and Interfaces

New methods setWantClientAuth and getWantClientAuth were added to SSLSocket and SSLServerSocket (in javax.net.ssl) to enable optional client authentication.

The method SSLContext.getInstance(protocol) returns socket factories which support at least the specified protocol. New methods setEnabledProtocols and getEnabledProtocols were added to SSLSocket and SSLServerSocket to further refine which protocols are enabled for use on this connection. Another new method getSupportedProtocols was added to SSLSocket and SSLServerSocket; getSupportedProtocols can be used to obtain the protocol versions that can be enabled for use on an SSL connection. The new method getProtocol was added to SSLSession for retrieving the standard name of the protocol used in the session.

SocketFactory and ServerSocketFactory have new methods createSocket and createServerSocket, respectively, for creating unconnected sockets.

New methods getServerSessionContext and getClientSessionContext were added to SSLContext. They allow the developer to obtain the set of SSL client or server sessions available for reuse during handshaking.

New methods setSessionTimeout and getSessionTimeout were added to SSLSessionContext. They allow the developer to control when sessions timeout and become invalid. New methods setSessionCacheSize and getSessionCacheSize were also added to control how many sessions should be cached for reuse by future connections.

New methods were added to HttpsURLConnection, SSLSession, and HandshakeCompletedEvent (all in javax.net.ssl) that allow you to get generic Java 2 java.security.cert.Certificate certificates in addition to the javax.security.cert.X509Certificate certificates returned by previously-existing methods. The new methods are

SSLSession.getPeerCertificates
HandshakeCompletedEvent.getPeerCertificates
HttpsURLConnection.getServerCertificates

A getLocalCertificates method was added to SSLSession, HandshakeCompletedEvent, and HttpsURLConnection. This method returns the certificate(s) that were sent to the peer during handshaking. This provides a way to determine what certificate chain was actually used to authenticate the local side of a given SSL session.

A new interface ManagerFactoryParameters was added as a base interface that providers can extend if they need KeyManagerFactory and/or TrustManagerFactory initialization parameters other than the ones that can be passed to the KeyStore-based init methods of those classes. The KeyManagerFactory and TrustManagerFactory classes each have a new init method that takes a ManagerFactoryParameters argument. Users of a particular provider are expected to pass an implementation of the appropriate ManagerFactoryParameters as defined by the provider.

Changed Classes and Methods

When the com.sun APIs were prepared for inclusion in the javax namespace, some API limitations were corrected in the javax version. The old com.sun.* APIs found in the previous JSSE optional packages are still the same and have not changed. The changes described in the paragraphs below only apply to the new javax.* classes of the same name.

The HttpsURLConnection constructor has been changed to be protected. This was done for consistency with other similar classes such as URLConnection, JarURLConnection, and HttpURLConnection, all in the java.net package. Another change to the HttpsURLConnection class is that the method that returned javax.security.cert certificates was removed.

Hostname verification has been redone to be more generic. The negotiated SSLSession is now passed to the verifier's verify method instead of the hostname contained in the received certificates. The SSLSession can then be queried for the negotiated ciphersuite, the exchanged certificates, and so on.

The X509TrustManager isClientTrusted and isServerTrusted methods were renamed checkClientTrusted and checkServerTrusted, respectively. If the certificate chain is not trusted by this TrustManager, the checkClientTrusted and checkServerTrusted methods throw an exception rather than return a boolean (like the former methods did). This allows implementations to ascertain the underlying cause for failure of the trust decision. The checks done by checkClientTrusted and checkServerTrusted include verifying that the certificate is used for an operation that complies with the certificate's key usage extension. To properly perform this check, it is necessary to pass the authentication type to these methods, and so a String authType argument has been added.

One parameter has been added and one changed for the X509KeyManager chooseClientAlias and chooseServerAlias methods. A Socket socket parameter was added to both methods for specifying the socket to be used for the connection. The keytype parameter for the chooseClientAlias method was changed from a single String to an array of Strings specifying the key algorithm type name(s), ordered with the most-preferred type first. For example, the chooseClientAlias method signature used to be

  chooseClientAlias(String keyType, Principal[] issuers)
and now it is
  chooseClientAlias(String[] keyType, Principal[] issuers,
                    Socket socket)
The parameters help decide which certificate(s) to use when connecting to a remote host.

The default key manager factory algorithm name has been changed from sun.ssl.keymanager.type to ssl.KeyManagerFactory.algorithm. Similarly, the default trust manager factory algorithm name has been changed from sun.ssl.trustmanager.type to ssl.TrustManagerFactory.algorithm.

Documentation Improvements

This JSSE Reference Guide was updated and expanded.

There were a number of minor clarifications made to the JSSE javadocs, primarily when discussing illegal arguments and implied behavior.

Related Documentation

Java Secure Socket Extension Documentation

  • The JSSE home page, with links to JavaOneSM conference slides, the JSSE FAQ, legal issues, etc.:
    http://java.sun.com/products/jsse/

  • 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 2 Standard Edition security team.

  • JSSE API documentation:
    • javax.net package
    • javax.net.ssl package
    • javax.security.cert package

Java 2 Platform Security Documentation

  • Java 2 security homepage:
    http://java.sun.com/security/

  • The JavaTM Certification Path API Programmer's Guide:
    http://java.sun.com/j2se/1.4.2/docs/guide/security/certpath/CertPathProgGuide.html

  • Links to more Java 2 platform security documents:
    http://java.sun.com/j2se/1.4.2/docs/guide/security/

  • Tutorial for Java 2 platform security:
    http://java.sun.com/docs/books/tutorial/security1.2/

  • Book on Java 2 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.doc.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:

  • Documentation from Netscape about SSL:
    http://developer.netscape.com/docs/manuals/security.html#SSL

  • Introduction to SSL from Sun™ ONE Software (formerly known as iPlanet):
    http://www.iplanet.com/developer/docs/articles/security/
    ssl.html

  • The SSL Protocol version 3.0 Internet Draft:
    http://home.netscape.com/eng/ssl3/ssl-toc.html

  • The TLS Protocol version 1.0 Internet Draft:
    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 protocol by which 2 or more parties can establish the same cryptographic keys, without having to exchange any secret information in the clear. Examples include RSA and Diffie-Hellman.

Key Managers and Trust Managers

Key managers (see KeyManagerFactory) and trust managers (see TrustManagerFactory) 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 Sun'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 J2SDK 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 "TCP/IP Protocol Stack With SSL" figure below, 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.

Let's 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 since 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 since 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 US 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 available public key exchange algorithms, secret key encryption 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 since 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 below shows the sequence of messages that are exchanged in the SSL handshake. Messages that are only sent 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 3) above is not sufficient for key exchange.

  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.

  9. Certificate verify - In internet applications, this message is rarely sent. 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.

If the parameters generated during an SSL session are saved, these parameters can sometimes be re-used for future SSL sessions. Saving SSL session parameters allows encrypted communication to begin much more quickly.

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 class of the connection is the SSLSocket. In the diagram below, the major classes used to create SSLSockets are laid out in a logical ordering.

diagram of classes used to create SSLSockets

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.

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. (SunJSSE currently only uses this variant of init.) 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.

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.

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 Sun 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.

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.

SSLSession Interface

A javax.net.ssl.SSLSession represents a security context negotiated between the two peers of an SSLSocket connection. Once a session has been arranged, it can be shared by future SSLSockets connected between the same two peers. The session 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. The value of this master secret is known only to the underlying secure socket implementation and is not exposed through the SSLSession API.

HttpsURLConnection Class

The https protocol is similar to http, but https first establishes a secure channel via SSL/TLS sockets 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, and java.net.HttpURLConnection classes for more information about how http 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 hostname of the URL does not match the hostname in the credentials received as part of the SSL/TLS handshake, it's possible that URL spoofing has occured. If the implementation cannot determine a hostname match with reasonable certainty, the SSL implementation will perform a callback to the instance's assigned HostnameVerifier for futher checking. The hostname verifier can perform whatever steps are necessary to make the determination, such as performing alternate hostname pattern matching or perhaps popping up an interactive dialog box. An unsuccessful verification will close the connection. (See RFC 2818 for more information regarding hostname 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 and SSLServerSocketFactory 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 JavaTM Cryptography Architecture API Specification & Reference.

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        Algorithm or
Implemented           Protocol

KeyFactory            "RSA"

KeyPairGenerator      "RSA"

KeyStore              "PKCS12"

Signature             "MD2withRSA"
Signature             "MD5withRSA"
Signature             "SHA1withRSA"

KeyManagerFactory     "SunX509"
TrustManagerFactory   "SunX509", "SunPKIX"

SSLContext            "SSL"
SSLContext            "SSLv3"
SSLContext            "TLS"
SSLContext            "TLSv1"

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. An SSLContext holds all of the state information shared across all sockets 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("SSLv3") may return a instance which implements SSLv3 and TLSv1. The getSupportedProtocols method returns a list of supported protocols when an SSLSocket or SSLServerSocket is created from a socket factory obtained from this context. You can control which protocols are actually enabled for an SSL connection by using the method setEnabledProtocols(String[] protocols). (Refer to the API documention for this method in the SSLSocket and the SSLServerSocket classes for more information.)

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 in the internals of JSSE), a default KeyManager and a TrustManager are created. The default SecureRandom implementation is also chosen.

TrustManager Class

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. Some secure socket implementations may also support authentication based on shared secret keys, Kerberos, or other mechanisms.

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. The SunJSSE provider implements a factory which can return a basic X.509 trust manager. 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.

In the 1.4.2 release of the Java 2 platform, a CertPath-based X.509 trust manager called "SunPKIX" TrustManagerFactory class was added. SunPKIX is available in addition to the previously available simple X.509 trust manager. For compatibility, it is not active by default. It can be enabled by changing the ssl.TrustManagerFactory.algorithm property in the java.security file from "SunX509" to "SunPKIX". Alternatively, it can be accessed programmatically by calling TrustManagerFactory.getInstance("SunPKIX"). The same "SunX509" TrustManagerFactory algorithm for cacerts (javax.net.ssl.trustStore/jssecacerts/cacerts) also initializes the SunPKIX algorithm.

Note: The algorithm name "SunPKIX" is preliminary and may change after standardization in a future release.
The PKIX trust manager uses the CertPath PKIX implementation from an installed security provider. In the currect release, you cannot specify the PKIXParameters to be used for validation; a suitable API will be added in a future release. Currently, the 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. For details see the JavaTM Certification Path API Programmer's Guide.

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:

"SunX509"

A sample call is the following:

TrustManagerFactory tmf =
    TrustManagerFactory.getInstance("SunX509", "SunJSSE");

The above call will create an instance of the SunJSSE provider's default trust manager factory. This factory can then be used to create trust managers which provide basic X.509-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 JavaTM 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 default "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.

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 default "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 default 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 {

    X509TrustManager sunX509TrustManager;

    MyX509TrustManager() {
        // create sunX509TrustManager
        //
        // for example:
        //     Create/load a keystore
        //     Get instance of a "SunX509" TrustManagerFactory "tmf"
        //     init the TrustManagerFactory with the keystore

        sunX509TrustManager = tmf.getTrustManagers()[0]
    }

    ... // checkClientTrusted method omitted

    public void checkServerTrusted(X509Certificate[] chain,
                                   String authType)
                                   throws CertificateException) {
        try {
            sunX509TrustManager.checkServerTrusted(chain, authType);
        } catch (CertificateException excep) {
            // do any special handling, such as popping up
            // dialog boxes, prompting the user, etc.
        }
    }

    public X509Certificate[] getAcceptedIssuers() {
        return sunJSSETrustManager.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[] myTM = new TrustManager [] {
                             new MyX509TrustManager() };
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, myTM, 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 sunX509TrustManager 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 called to make the trust decisions.

KeyManager Class

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 secure socket 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, 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.

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 that 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.

Note: If no KeyStore parameter is passed to the SunJSSE default "SunX509" KeyManagerFactory, the factory tries to find key material by consulting the system properties

javax.net.ssl.keyStore
javax.net.ssl.keyStorePassword
If these properties specify a file with an appropriate password, the factory uses this file for the KeyStore. If that file does not exist, then a default KeyManager using an empty keystore is created.

Generally, the process 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 process 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.

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.

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.

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.

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.

Now JSSE has been integrated into the J2SDK, v 1.4. 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, v 1.4 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, v 1.4 (ones using the javax API). However, applications written using the JSSE API in the J2SDK, v 1.4 can only utilize JSSE providers written for the J2SDK, v 1.4. This new release contains some new functionality and attempting to access such functionality on a provider that doesn't supply it wouldn't work. SunJSSE, provided with the J2SDK from Sun Microsystems, 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 2 Runtime Environment (JRE) is installed. It is determined based on whether you are running JSSE on a JRE with or without the JavaTM 2 SDK installed. Java 2 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 2 SDK is installed in /home/user1/j2sdk1.4.0, then <java-home> is
    /home/user1/j2sdk1.4.0/jre

  • On Solaris, if JRE is installed in /home/user1/j2re1.4.0 and the Java 2 SDK is not installed, then <java-home> is
    /home/user1/j2re1.4.0

  • On Microsoft Windows platforms, if the Java 2 SDK is installed in C:\j2sdk1.4.0, then <java-home> is
    C:\j2sdk1.4.0\jre

  • On Microsoft Windows platforms, if the JRE is installed in C:\j2re1.4.0 and the Java 2 SDK is not installed, then <java-home> is
    C:\j2re1.4.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, etc. The table below 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 Sun Microsystems

cert.provider.x509v1 security property

HTTPS protocol implementation

Implementation from Sun Microsystems

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

None.

* javax.net.ssl.keyStore system property

default keystore type

KeyStore.getDefaultType()

* javax.net.ssl.keyStoreType system property

default keystore password

None.

* javax.net.ssl.keyStorePassword system property

default truststore

jssecacerts, if it exists. Otherwise, cacerts

* javax.net.ssl.trustStore system property

default truststore type

KeyStore.getDefaultType()

* javax.net.ssl.trustStoreType system property

default truststore password

None.

* javax.net.ssl.trustStorePassword system property

default key manager factory algorithm name

"SunX509"

ssl.KeyManagerFactory.algorithm security property
default trust manager factory algorithm name

"SunX509"

ssl.TrustManagerFactory.algorithm security property
default proxy host

None.

* https.proxyHost system property
default proxy port

80

* https.proxyPort system property
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.
encryption algorithms used by SunJSSE provider

internal SunJSSE implementations

Give JCE algorithm provider(s) a higher preference order than the SunJSSE provider

* 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.

** Due to U.S. export restrictions, the JSSE implementation in Sun Microsystems' Java 2 SDK, v 1.4 does not allow replacement of the default SSLSocketFactory or SSLServerSocketFactory implementations. Please see the note on pluggability in the Introduction. If you are using a different JSSE implementation that allows alternate SSL/TLS implementation, you do so by setting the specified security properties.

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. You can set a system property either statically or dynamically:

  • 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");

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 J2SDK 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 J2SDK 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, v 1.4 release comes 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 JavaTM Cryptography Architecture API Specification & Reference.

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 2 platform are automatically registered for you; the following lines appear in the java.security security properties file to register the standard security provider with preference order 1 and the SunJSSE provider with preference order 2:

security.provider.1=sun.security.provider.Sun
security.provider.2=com.sun.net.ssl.internal.ssl.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, 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.

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 J2SDK 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 "SunX509" is used to perform the search. Note: A TrustManagerFactory implementation for the "SunX509" 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.

Customizing the Encryption Algorithm Providers

The SunJSSE provider can make use of JCE providers for the encryption algorithms it uses (RSA, RC4, DES, and Triple DES). Previously, SunJSSE always made use of internal implementations for encryption algorithms.

Now implementations from providers with a higher preference order than SunJSSE are used if available. Providers with a lower preference order are ignored in favor of the SunJSSE internal implementations. 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.) For example, a statement like
Security.insertProviderAt(new MyProvider(), 2);
ensures that MyProvider is searched for relevant encryption algorithms prior to SunJSSE, assuming that the SunJSSE provider was initially configured as the second provider. Note that this is the case in the default configuration, and in that configuration Sun is specified as the first provider. It is strongly recommended that you leave the Sun provider at position 1.

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 JCE Reference Guide.

Additional Keystore Formats

The JSSE SunJSSE provider supplies an implementation of the PKCS12 java.security.KeyStore format. This format is also supported by other toolkits and applications for importing and exporting keys and certificates. For example, Netscape 4.x (versions 4.04 and later) can export client certificates and keys into a file using the ".p12" filename extension in PKCS12 format.

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 using the keytool command with the -storetype option set to pkcs12. (See Security Tools for information about keytool.)

JSSE in the J2SDK, v 1.4 has limitations on its implementation but it can read and use PKCS12 keystore files exported by Netscape Navigator. Future releases will also support and be tested with Internet Explorer and other applications. See the README file for the release you are using for information as to its PKCS12-handling capabilities.

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 Class
  • KeyManager Class

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.

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 J2SDK 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 -genkey -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);

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 2 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) send SSLv3/TLS ClientHellos encapsulated in a SSLv2 ClientHello packet. Some servers do not accept this format, in these cases use setEnabledProtocols to disable the sending of encapsulated SSLv2 ClientHellos.

Debugging Utilities

JSSE provides dynamic debug tracing support. This is similar to the support used for debugging access control failures in the Java 2 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

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.

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

  • 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 2 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

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.

Where to Find the Sample Code

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 "duke" 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 "duke" in the truststore it consults, an authentication error will occur. Be sure to use the samplecacerts truststore (which contains "duke"s public key), 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 J2SDK (in the cacerts file), plus a certificate for "duke" needed by the client to authenticate "duke" when communicating with the sample server ClassFileServer. (ClassFileServer uses a keystore containing the private key for "duke" 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.

Note: The "duke" certificate in the samples directory is different from the "duke" certificate available from the security example provided on http://java.sun.com/security/signExample12/. If you have both "duke" certificates installed, the sample code will not work properly. To view the certificates available in your certificate file, use the keytool command.

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 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 in the J2SDK, v 1.4 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 Sun Microsystems.

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.

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: 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 -genkey -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]:  Sun Microsystems, 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="Sun Microsystems, 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="Sun Microsystems, Inc.",
L=Palo Alto, ST=CA, C=US
Issuer: CN=Duke, OU=Java Software, O="Sun Microsystems, 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="Sun Microsystems, Inc.", L=Palo Alto, ST=CA, C=US
Issuer: CN=Duke, OU=Java Software, O="Sun Microsystems, 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="Sun Microsystems, Inc.", L=Palo Alto, ST=CA, C=US
Issuer: CN=Duke, OU=Java Software, O="Sun Microsystems, 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 protocol name parameter passed to the getInstance method of SSLContext supports a named secure socket protocol and optionally a named purpose separated from the protocol name by a '/' character. The table below lists some common standard protocol names.
Protocol | Comment
SSL | Supports some version of SSL; may support other versions
SSLv2 | Supports SSL version 2 or higher
SSLv3 | Supports SSL version 3; may support other versions
TLS | Supports some version of TLS; may support other versions
TLSv1 | Supports TLS version 1; may support other versions

The keyType parameter passed to the chooseClientAlias, chooseServerAlias, getClientAliases, and getServerAliases methods of X509KeyManager specify the public key type(s). Each row of the table below lists the standard name that should be used for keyType, given the specified certificate type.

Name | Certificate Type | Corresponds to (RFC 2246)
RSA | RSA | rsa_sign(1)
DSA | DSA | dss_sign(2)
DH_RSA | Diffie-Hellman with RSA signature | rsa_fixed_dh(3)
DH_DSA | Diffie-Hellman with DSA signature | dss_fixed_dh(4)

The protocols parameter passed to the setEnabledProtocols method of SSLSocket specifies the protocol versions to be enabled for use on the connection. The table below 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 protocol (defined in RFC 2246)
SSLv2Hello | Enables the sending of SSLv2 hellos. For compatibility reasons, some protocols such as SSLv3 and TLSv1 allow sending SSLv3/TLSv1 hellos encapsulated in an SSLv2 format hello.

The authType parameter passed to the checkClientTrusted and checkServerTrusted methods of X509TrustManager indicates the authentication type. The table below 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 run time 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".

Copyright © 1998-2003, Sun Microsystems, Inc. 4150 Network Circle Santa Clara, California 95054 All Rights Reserved.

Please send comments to: java-security@sun.com. This is not a subscription list.


JSSE Samples

This samples directory contains subdirectories with JSSE sample files.

If you are viewing this page on the web, the best way to obtain all the samples files, including the binary keystore files, is to download the following zip file:

jssesamples.zip

Below are lists of the directories and links to all the text files within the directories.

samples
README.txt
samplecacerts (binary)

rmi
Hello.java
HelloClient.java
HelloImpl.java
RMISSLClientSocketFactory.java
RMISSLServerSocketFactory.java
policy
readme.txt
testkeys (binary)
sockets
client
SSLSocketClient.java
SSLSocketClientWithClientAuth.java
SSLSocketClientWithTunneling.java
testkeys (binary)
server

ClassFileServer.java
ClassServer.java
testkeys (binary)
urls


                Java(tm) Secure Socket Extension
          for the JavaTM 2 SDK, Standard Edition, v 1.4

                          Sample Code

                            README

----------------------------------------------------------------------
CONTENTS
----------------------------------------------------------------------
    - Introduction
    - Sample KeyStores
    - Code Examples
    - Troubleshooting

----------------------------------------------------------------------
Introduction
----------------------------------------------------------------------
This JSSE sample code bundle provides some rudimentary examples of how
the JSSE can be used to secure communications in the Java(tm) network
environment.

The samples do require some familiarity with Java and the JSSE API, so
please consult the appropriate documentation for more information.

J2SDK:  http://java.sun.com/doc/

JSSE:	Documentation for the JSSE API can be found in Sun's
    J2SDK implementation or documentation bundles, or at
    http://java.sun.com/j2se/1.4/docs/guide/security/jsse/JSSERefGuide.html

    If you use a JSSE implementation from a vendor other than Sun,
    also consult that JSSE implementation's documentation.  Follow any
    instructions given by the vendor as to how to configure the
    security provider, set the classpaths (if necessary), enable the
    https protocol handler, define HTTPS proxy servers, and so on.

----------------------------------------------------------------------
Sample KeyStores
----------------------------------------------------------------------
This bundle includes two sample keystore files that can be used with
the sample code.  They are both stored in the "JKS" KeyStore format,
which is the default format used by Sun's J2SDK implementation.  (If
another KeyStore format is desired, the J2SDK will need to be configured
to recognize the new default format.)  The remainder of this document
assumes the Sun implementations of J2SDK and JSSE are being used.

JSSE uses the certificate KeyStore files to authenticate the clients
and servers.

samplecacerts	This file is very similar to the stock J2SDK cacerts
        file, in that it contains trust certificates from
        several vendors.  It also contains a trust certificate
        from Duke, the Java mascot (see */testkeys below).

        This file can be installed as:
            <java-home>/lib/security/jssecacerts
        or:
            <java-home>/lib/security/cacerts

        (Be sure to replace this file with a production cacerts
        file before deploying the application.)

        The password for this keystore is the same as the
        J2SDK cacert's initial password:  changeit

*/testkeys	This file is used by the code samples as the source
        of public/private key and certificate material.  It
        contains the keystore certificate entry for Duke (as
        above in samplecacerts).

        These files are duplicated in each sample directory, as
        the sample code expects the testkeys file to be in the
        current working directory.

        The password for this keystore is:  passphrase

The Sun J2SDK utility "keytool" can be used to generate certificates and
keystore files.

If you are using the Sun implementations of the J2SDK and JSSE, you will
configure the system to use the proper trustStore.  Please see the J2SDK
and JSSE documentation for more information about how to specify
trustStores.

IMPORTANT NOTE:  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.

NOTE:  If you use a browser such as Microsoft's Internet Explorer or
Netscape's Navigator to access the example ssl server (e.g.
socket/server/ClassFileServer), you will see a dialog popup with the
message that the application doesn't recognize the "duke" certificate.
This is normal because the self-signed certificate being presented to
the browser is not initially trusted.

----------------------------------------------------------------------
Code Examples
----------------------------------------------------------------------
The sample code bundle is broken into several directories, based on
the style of SSL connections.

urls

    URLReader.java

    This example illustrates using a URL to access resources on a
    secure site.  By default, this example connects to
    www.verisign.com, but it can be adapted to connect to the
    ClassFileServer above.  The URL request must be slightly
    modified, and you must create a host certificate for the https
    host being used, otherwise there will be a "HTTPS hostname
    wrong" error.  (Note:  This behaviour can be overriden by using
    the HostNameVerifier in the HttpsURLConnection class.)

    Also, if you are behind a firewall, you will need to set
    "https.proxyHost" and "https.proxyPort".

    USAGE:
        java URLReader

    URLReaderWithOptions.java

    This example is very similar to URLReader above, but
    allows you to set the system properties via arguments to the
    main method, rather than as -D options to the java runtime
    environment.

    USAGE:
        java URLReaderWithOptions [-h proxyhost] [-p proxyport] \
            [-k protocolhandlerpkgs] [-c ciphersarray]

        proxyHost = secure proxy server hostname (https.proxyHost)
        proxyPort = secure proxy server port (https.proxyPort)
        protocolhandlerpkgs = a "|" separated list of protocol handlers
            (java.protocol.handler.pkgs)
        ciphersarray = enabled cipher suites as a comma separated list
            (https.cipherSuites)

sockets

    server

    ClassServer.java
    ClassFileServer.java

        This sample demonstrates the implementation of a
        mini-webserver, which can service simple HTTP or HTTPS
        requests (only the GET method is supported).

        By default, the server does not use SSL/TLS.  However,
        a command line option enables SSL/TLS.

        Requests must be of the form:

        GET /<filename>

        USAGE:
        java ClassFileServer port docroot [TLS [true]]

            port = the port on which the server resides
            docroot = the root of the local directory hierarchy
            TLS = an optional flag which enables SSL/TLS
            services
            true = an optional flag which requires that clients
            authenticate themselves.  This option requires
            that SSL/TLS support be enabled.

        NOTE:  If you are connecting via a web brower to a
        TLS socket, specify that the https protocol be used:

        e.g.  https://localhost:2001/dir1/file1

        Otherwise, you may see unrecognized SSL handshake errors.

    client

    SSLSocketClient.java

        This example demonstrates how to use a SSLSocket as a client to
        send a HTTP request and get a response from an HTTPS server.
        By default, this example connects to www.verisign.com, but
        it can easily be adapted to connect to the ClassFileServer
        above.  (Note:  The GET request must be slightly modified.
        See above for more information.)

        This application assumes the client is not behind a firewall.

        USAGE:
        java SSLSocketClient

    SSLSocketClientWithClientAuth.java

        This example is similar to SSLSocketClient above, but
        this shows how to set up a key manager to do client
        authentication if required by server.

        This application also assumes the client is not behind a
        firewall.

        USAGE:
        java SSLSocketClientWithClientAuth host port requestedfilepath

    SSLSocketClientWithTunneling.java

        This example illustrates how to do proxy Tunneling to access a
        secure web server from behind a firewall.

        The System properties "https.proxyHost" and "https.proxyPort"
        are used to make a socket connection to the proxy host, and
        then the SSLSocket is layered on top of that Socket.

        USAGE:
        java SSLSocketClientWithTunneling

rmi

     Hello.java
     HelloImpl.java
     RMISSLClientSocketFactory.java
     RMISSLServerSocketFactory.java
     HelloClient.java

    This example illustrates how to use RMI over an SSL transport
    layer, using the JSSE.  The server will run HelloImpl, and the
    client will run HelloClient.

    The compilation is a little tricky, here are the necessary
    steps:

        % javac *.java
        % rmic HelloImpl
        % rmiregistry
        % java \
        -Djava.rmi.server.codebase="file:/current_working_dir/" \
        HelloImpl   (run in another window)
        % java HelloClient (run in another window)

    Note the final trailing slash on the "java.rmi.server.codebase"
    parameter.  If the codebase is not specified properly, you may
    get an java.lang.ClassNotFoundException exception.

    Also note that the RMI security manager may be installed,
    and therefore, you will need to give it the appropriate
    network privilege:

        permission java.net.SocketPermission "localhost:1099", "connect";

----------------------------------------------------------------------
Troubleshooting
----------------------------------------------------------------------
One of the most common problems people have in using JSSE is when the
JSSE receives a certificate that is unknown to the mechanism that makes
trust decisions.  If an unknown certificate is received, the trust
mechanism will throw an exception saying that the certificate is
untrusted.  Make sure that the correct trust KeyStore is being used,
and that the JSSE is installed and configured correctly.

In the Sun Reference Implementation, the exception error returned will
be:

    javax.net.ssl.SSLException: Couldn't find trusted certificate

The SSL debug mechanism can be used to investigate such trust
problems.  See the implementation documentation for more information
about this subject.


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/products/jdk/1.2/docs/guide/rmi/
    http://java.sun.com/docs/books/tutorial/rmi/index.html


Java Security Architecture: Contents

CONTENTS | PREV | NEXT

JavaTM 2 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 2 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.


Java Security Architecture: -

CONTENTS | PREV | NEXT Java Security Architecture

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 2 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.


Java Security Architecture: -

CONTENTS | PREV | NEXT Java Security Architecture

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.


Java Security Architecture: -

CONTENTS | PREV | NEXT Java Security Architecture

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.


Java Security Architecture: -

CONTENTS | PREV | NEXT Java Security Architecture

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 pages of the More Features of the Java Language trail of the Java Tutorial, including http://java.sun.com/docs/books/tutorial/java/more/nested.html and http://java.sun.com/docs/books/tutorial/java/more/innerclasses.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.


Java Security Architecture: -

CONTENTS | PREV | NEXT Java Security Architecture

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.


Java Security Architecture: -

CONTENTS | PREV | NEXT Java Security Architecture

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/tooldocs/solaris
and

/docs/tooldocs/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/tooldocs/solaris/
or

/docs/tooldocs/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.


Java Security Architecture: -

CONTENTS | PREV | NEXT Java Security Architecture

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.


Java Security Architecture: -

CONTENTS | PREV | NEXT Java Security Architecture

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.


Java Security Architecture: -

CONTENTS | PREV | NEXT Java Security Architecture

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 2 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.


Java Security Architecture: -

CONTENTS | PREV | NEXT Java Security Architecture

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.


Java Security Architecture: -

CONTENTS | PREV | NEXT Java Security Architecture

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.


Java Security Architecture: -

CONTENTS | PREV | NEXT Java Security Architecture

12 Revision History

Various drafts on Java 2 Security Architecture, under different disguises, existed since August of 1996.

Java 2 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.


Java Security Architecture: -

CONTENTS | PREV | NEXT Java Security Architecture

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.


Object Serialization

 Documentation Contents
Object Serialization extends the core Java Input/Output classes with support for objects. Object Serialization supports the encoding of objects, and the objects reachable from them, into a stream of bytes; and it supports the complementary reconstruction of the object graph from the stream. Serialization is used for lightweight persistence and for communication via sockets or Remote Method Invocation (RMI). The default encoding of objects protects private and transient data, and supports the evolution of the classes. A class may implement its own external encoding and is then solely responsible for the external format.

Serialization now includes an API that allows the serialized data of an object to be specified independently of the fields of the class and allows those serialized data fields to be written to and read from the stream using the existing protocol to ensure compatiblity with the default writing and reading mechanisms.

Enhancements
  • Enhancements in J2SETM 1.4 - Describes enhancements and improvements to Object Serialization in J2SE 1.4.
  • Previous Enhancements - Describes enhancements to Object Serialization made in previous releases of the Java 2 Platform.
Specification
  • Specification - Describes the architecture of the Object Serialization system and the APIs. The specification is also available in PS and PDF formats.
API Specification
(javadoc)
  • java.io Package - Documents all of the interfaces and classes.
Examples
  • Examples- Demonstrate different aspects of and uses for Object Serialization.
FAQ
  • FAQ- Answers the most frequently asked questions about Object Serialization.
Tools
  • serialver - Explains the serialver command, which returns the serialVersionUID for a class.

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-io@java.sun.com

Sun
Java Software


Serialization Enhancements in Previous Releases

Java

Object Serialization Enhancements
in Previous Releases

 Documentation Contents
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 © 1999 Sun Microsystems, Inc. All Rights Reserved.
Please send comments to: rmi-comments@java.sun.com 		Sun


Serialization Release Notes

Java

Serialization Changes and Enhancements
in J2SETM 1.4

 Documentation Contents
The following are enhancements to serialization in version 1.4 of the Java 2 Platform. For a summary of enhancements in previous releases, see Enhancements in Previous Releases.
Support for deserialization of unshared objects
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)

Previously, security-conscious programmers had to clone private internal objects after deserializing them to guard against the possibility that outside parties with access to the serialization stream could append spurious back handles to the sensitive objects, resulting in extra references to them during deserialization. However, this solution slows performance and wastes memory -- two objects must be created and a copy operation invoked in order to ensure a unique reference to a single usable object. The new API additions provide a more efficient solution by allowing receivers to invalidate "unshared" objects as they are read in, making it impossible for third parties to dereference back-handles to those objects occurring later in the stream.

Security permissions now required to override putFields, readFields
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
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
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
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
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
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.
Copyright © 2001 Sun Microsystems, Inc. All Rights Reserved.
Please send comments to: rmi-comments@java.sun.com 		Sun


Object Serialization Examples

The following examples demonstrate different aspects of and uses for Object Serialization:

  • Using Serialization with Sockets
  • Using Serialization with a Custom Data Format
  • Using Serialization with SuperClasses:
    • Serialization with a NonSerializable Superclass
    • Externalization with an Externalizable Superclass
    • Externalization with a NonExternalizable Superclass
  • Using Serialization with Evolution:
    • Serialization and Evolution
    • Externalization and Evolution
    • Serialization, Evolution, and the addition of a new SuperClass
    • Serialization, Evolution, and the Serializable Fields API
  • Using Substitution by Serializable Class


Using Serialization and the Serializable Fields API

Abstract

This example shows how to use the Serializable Fields API with Serialization, demonstrating that the class can define fields other than those already in the class to be serializable. This differs from just rewriting the writeObject method to customize the data format (see the Custom Data Format example) because, in this example, versioning support still holds.

Using the Serializable Fields API, this example specifically changes the internal representation of a rectangle from x1,y1,x2,y2 implementation (see OriginalClass.java) to Point(x1,y1), Point(x2,y2) (see EvolvedClass.java) while the external representation still remains x1, y1, x2, y2. This ensures bidirectional compatibility between the original and evolved representations.

As with all examples dealing with evolution, here the evolved class (ARectangle) must define a serialVersionUID field that is obtained using the command serialver on the original class (ARectangle).

Additional Information

Source Files
Running the Example
List of Examples


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


Using Serialization and the Serializable Fields API

Using Serialization and the Serializable Fields API blue bar

Source Files

The following source files are provided:

OriginalClass.java, the Original Class
EvolvedClass.java, the Evolved Class

Additional Information

Running the Example
Abstract
List of Examples


Using Serialization and the Serializable Fields API

Running the Example

Complete the following procedure to compile and run this example:

  1. From yourbasedir/objectserializationexamples/AlternatePersistentFieldAPI, compile the Original Class using JDKTM 1.2 or higher:
      javac OriginalClass.java
  2. Run the Original Class with the serialization flag:
      java OriginalClass -s
  3. Compile the Evolved Class:
      javac EvolvedClass.java
  4. Run the Evolved Class with the deserialization flag:
      java EvolvedClass -d

This procedure tests compatibility in one direction only. To test bidirectional compatibility, perform the same procedure in the other direction (in steps 1-4, replace the original class name with the evolved class name, and vice versa).

Additional Information

Abstract
Sources
List of Examples


Using Serialization with a Custom Data Format

Abstract

Demonstrates how to use the writeObject and readObject methods to encode a custom data format. When there is a large amount of persistent data, that data should be stored in a convenient, condensed format, such as the one used in this example.

This example uses a triangular array, a symmetrical, 2-dimensional array. During serialization only half of the array is saved. This example serializes half of the array in writeObject, then restores the whole array in readObject by deserializing half of the array and copying to restore the other half of the array.

This example differs from the Using Serialization and the Serializable Fields API Example in that this example does not support versioning. In addition, because this example does not use an Externalizable interface, superclasses are not a consideration.

Additional Information

Source Files
Running the Example
List of Examples


Using Serialization with a Custom Data Format

Source Files

The following source file is provided:

CustomDataExample.java

Additional Information:

Running the Example
Abstract
List of Examples


Using Serialization with a Custom Data Format

Serialization and Custom Data Format

Running the Example

Complete the following procedure to compile and run the example:

  1. From yourbasedir/objectserializationexamples/CustomDataFormat, compile the file CustomDataExample.java using JDK TM 1.1 or higher:
      javac CustomDataExample.java
  2. Run the file you just compiled:
      java CustomDataExample

Two arrays are printed:

  • The first array shows the array before serialization.
  • The second array shows the array after deserialization.

Additional Information:

Abstract
Sources
List of Examples


Serialization, Evolution, and the Addition of a New SuperClass

Abstract

Shows how to use versioning in serialization to evolve the class to have a new superclass. For example, if the initial class structure was as follows:

  class A {...};
  class C extends A {...};

and the evolved class structure is as follows:

  class A {...};
  class B extends A {...};
  class C extends B {...};

then the new version of subclass C should be able to read the old version of subclass C, and vice versa. The example demonstrates this principle.

The evolved classses (ASuperClass and ASubClass) must define a serialVersionUID field that is obtained using the command serialver on the original classes (ASuperClass and ASubClass).

Note that in this example, the superclasses (A and B) implement the Serializable interface. If they did not, subclass C would be responsible for saving and restoring the fields of A and B. See Serialization with a NonSerializable Superclass for additional information about this topic.

Additional Information:

Source Files
Running the Example
List of Examples


Serialization, Evolution, and the Addition of a New SuperClass

Source Files

The following source files are provided:

OriginalClass.java
EvolvedClass.java

Additional Information

Running the Example
Abstract
List of Examples


Serialization, Evolution, and the Addition of a New SuperClass

Running the Example

Complete the following procedure to compile and run this example:

  1. From yourbasedir/objectserializationexamples/AddingNewSuperClassAndEvolution, compile the Original Class using JDKTM 1.2 or higher:
      javac OriginalClass.java
  2. Run the Original Class with the serialization flag:
      java OriginalClass -s
  3. Compile the Evolved Class:
      javac EvolvedClass.java
  4. Run the Evolved Class with the deserialization flag:
      java EvolvedClass -d

This procedure tests compatibility in one direction only. To test bidirectional compatibility, perform the same procedure in the other direction (in steps 1-4, replace the original class name with the evolved class name, and vice versa).

For more information:

Abstract
Sources
List of Examples


Using Serialization with Evolution

Abstract

Under certain circumstances, when Java objects use serialization to store objects, the version of the class reading the data could be different from the version of class that wrote that data.

This example demonstrates some of the compatible changes that Serialization handles without using class-specific methods.

As with all examples that deal with evolution, the evolved class (AClass) must define a serialVersionUID field that is obtained using the command serialver on the original class (AClass).

Additional Information

Source Files
Running the Example
List of Examples


Using Serialization with Evolution

Source Files

The following source files are provided:

EvolutionExampleOriginalClass.java, the Original Class
EvolutionExampleEvolvedClass.java, the Evolved Class

Additional Information

Running the Example
Abstract
List of Examples


Using Serialization with Evolution

Running the Example

Complete the following procedure to compile and run this example:

  1. From yourbasedir/objectserializationexamples/SerializationAndEvolution, compile the Original Class using JDKTM 1.2 or higher:
      javac EvolutionExampleOriginalClass.java
  2. Run the Original Class with the serialization flag:
      java EvolutionExampleOriginalClass -s
  3. Compile the Evolved Class:
      javac EvolutionExampleEvolvedClass.java
  4. Run the Evolved Class with the deserialization flag:
    java EvolutionExampleEvolvedClass -d

This procedure tests compatibility in one direction only. To test bidirectional compatibility, perform the same procedure in the other direction (in steps 1-4, replace the original class name with the evolved class name, and vice versa).

Additional Information

Abstract
Sources
List of Examples


Using Externalization and Evolution

Abstract

This example shows how to evolve a persistent format using the Externalizable interface. A class that uses the Externalizable interface is responsible for saving its own state, for saving the state of its supertype, and for versioning (including skipping over data).

This example specifically deals with versioning. For information about saving the state of the supertype, which may or may not be Externalizable, see the following examples:

  • Using Serialization with a NonSerializable Superclass
  • Using Externalization with an Externalizable Superclass
  • Using Externalization with a NonExternalizable Superclass

Additional Information

Running the Example
Sources
List of Examples


Using Externalization and Evolution

Source Files

The following source files are provided:

ExternExampleOriginalClass.java, the Original Class
ExternExampleEvolvedClass.java, the Evolved Class

Additional Information

Running the Example
Abstract
List of Examples


Using Externalization and Evolution

Running the Example

Complete the following procedure to compile and run this example:

  1. From yourbasedir/objectserializationexamples/ExternalizationandEvolution, compile the Original Class using JDKTM 1.2 or higher:
      javac ExternExampleOriginalClass.java
  2. Run the Original Class with the serialization flag:
      java ExternExampleOriginalClass -s
  3. Compile the Evolved Class:
      javac ExternExampleEvolvedClass.java
  4. Run the Evolved Class with the deserialization flag:
      java ExternExampleEvolvedClass -d

This procedure tests compatibility in one direction only. To test bidirectional compatibility, perform the same procedure in the other direction (in steps 1-4, replace the original class name with the evolved class name, and vice versa).

Additional Information

Abstract
Sources
List of Examples


Externalization with an Externalizable SuperClass

Abstract

When using the Externalizable interface, an externalizable object must implement a writeExternal method to save the state of the object and a readExternal method to restore the state of the object. The externalizable object must also coordinate with its supertype to save and restore its state.

This example demonstrates how an object saves and restores the state of its externalizable supertype. When the supertype of an externalizable object is also externalizable, the subclass object calls the writeExternal and readExternal methods of its superclass in its own writeExternal and readExternal methods.

Additional Information:

Source Files
Running the Example
List of Examples


Externalization with an Externalizable SuperClass

Source Files

The following source files are provided:

Savesuper.java
Book.java, tThe subclass book
ReadingMaterial.java, the superclass ReadingMaterial

Additional Information

Running the Example
Abstract
List of Examples


Externalization with an Externalizable SuperClass

Running the Example

Complete the following procedure to compile and run this example:

  1. From yourbasedir/objectserializationexamples/ExternalizableSuperclass, compile the Savesuper.java file using JDKTM 1.1 or higher:
      javac Savesuper.java
  2. Run the file you just compiled: java Savesuper

The original book object is printed (showing the object before serialization) and then the new book object is printed (showing the object after serialization).

Additional Information

Abstract
Sources
List of Examples

< blue bar


Externalization with an NonExternalizable SuperClass

Exernalization with an NonExternalizable SuperClass

Abstract

When using the Externalizable interface, an externalizable object must implement a writeExternal method to save the state of the object and a readExternal method to restore the state of the object. The externalizable object must also coordinate with its supertype to save and restore its state.

This example demonstrates how an object saves and restores the state of its nonexternalizable supertype. When the supertype of an externalizable object is not externalizable, the subclass object must explicitly save and restore the state of the fields of the superclass in its own writeExternal and readExternal methods.

Additional Information:

Source Files
Running the Example
List of Examples


Externalization with an NonExternalizable SuperClass

Exernalization with an NonExternalizable SuperClass

Source Files

The following source files are provided:

Nonexternsuper.java
Book.java, the subclass book
ReadingMaterial.java, the superclass ReadingMaterial

Additional Information:

Running the Example
Abstract
List of Examples


Externalization with an NonExternalizable SuperClass

Exernalization with an NonExternalizable SuperClass

Running the Example

Complete the following procedure to compile and run the example:

  1. From yourbasedir/objectserializationexamples/NonExternalizableSuperclass, compile the file Nonexternsuper.java using JDKTM 1.1 or higher:
      javac Nonexternsuper.java
  2. Run the compiled file:
      java Nonexternsuper

The book object prints out before and after serialization.

Additional Information

Abstract
Sources
List of Examples


Using Serialization with a NonSerializable Superclass

Abstract

Shows how to serialize a subclass which has a superclass that is not serializable.

When a superclass of a particular subclass is not serializable, the subclass must save and restore the state of the superclass.

Additional Information

Source Files
Running the Example
List of Examples


Using Serialization with a NonSerializable Superclass

Source Files

The following source files are provided:

NonSerialSuperExample.java
Book.java, the subclass Book
ReadingMaterial.java, the superclass ReadingMaterial

Additional Information:

Running the Example
Abstract
List of Examples


Using Serialization with a NonSerializable Superclass

Running the Example

Complete the following procedure to compile and run the two examples:

  1. From yourbasedir/objectserializationexamples/NonSerializableSuperClass, compile the files using JDKTM 1.1 or higher:
      javac NonSerialSuperExample.java
  javac Book.java
  javac ReadingMaterial.java
  2. Run the compiled file:
      java NonSerialSuperExample

The book object prints out before and after serialization.

Additional Information:

Abstract
Sources
List of Examples


Using Serialization with Sockets

Abstract

Shows how to use sockets and serialization for sending and receiving objects.

In this example, the current date is sent from the client to the server. The file Client.java provides the code for sending the date and the file Server.java provides the code for receiving the date. The Server is the local host machine.

Additional Information:

Source Files
Running the Example
List of Examples


Using Serialization with Sockets

Source Files

The following source files are provided:

  • Server.java
  • Client.java

Additional Information:

Running the Example
Abstract
List of Examples


Using Serialization with Sockets

Running the Example:

Complete the following procedure to compile and run the two examples:

  1. From yourbasedir/objectserializationexamples/UsingSockets, compile the files Server.java and Client.java using JDKTM1.1 or higher:
      javac Server.java
  javac Client.java
  2. Run the Server:
      java Server
  3. Suspend the Server, using Ctrl/Z on UNIX systems.
  4. Put the Server in the background, using the following command on UNIX systems:
      bg
  5. Run the Client:
      java Client

Using sockets and serialization, the current date is sent from the client to the server, which then prints out the date.

Additional Information:

Abstract
Sources
List of Examples


Substitution by Serializable Classes

Serialization and the writeReplace/readResolve Methods

Abstract

This example demonstrates how to use the writeReplace/readResolve methods. The readResolve method resolves the object read from the stream before it is returned to the caller. The writeReplace method allows a Serializable class of an object to nominate its own replacement in the stream before the object is written.

This example creates a symbol class for which only one instance of each each symbol binding exists. The Symbol class defines the readResolve method. A symbol is created from outside using the symbollookup method. The symbollookup method finds and returns a symbol if one already and, if one does not already exist, creates one. This assures uniqueness within one VM. Then, when the readResolve method is called as the symbol is being read, a preexisting equivalent Symbol object is substituted from the hashtable to maintain the unique identity constraint, if such a symbol exists. If the symbol does not exist, the new symbol is added to the hashtable and returned. This assures uniqueness when dealing with more than one VM.

Additional Information

Source Files
Running the Example
List of Examples


Substitution by Serializable Classes

Serialization and the writeReplace/readResolve Methods blue bar

Source Files

The following source file is provided:

Substitute.java

Additional Information

Running the Example
Abstract
List of Examples


Substitution by Serializable Classes

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 JDKTM 1.2 or higher:
      javac Substitute.java
  2. Run the compiled file:
      java Substitute

Additional Information

Abstract
Sources
List of Examples


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 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 getName method returns the fully-qualified name of the class. The class name is saved in the stream and is used when the class must be loaded.

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 serializable nor the externalizable flag bits are set.
  • For serializable classes, the 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 externalizable 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 1.1 and 1.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.

User interface described in the previous context

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, methoit is strongly recommended thatds, 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. Serializable classes do not need to anticipate versioning; however, Externalizable classes do.

Note – It is strongly recommended that serializable classes that are inner classes or which contain inner classes declare the serialVersionUID data member. This is because different implementations of compilers could use different names for synthetic members that are generated for the implementation of inner classes, and these names are used in the current computation of SUIDs.

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.

The sequence of items in the stream is as follows:

  1. The class name written using UTF encoding.
  2. The class modifiers written as a 32-bit integer.
  3. The name of each interface sorted by name written using UTF encoding.
  4. For each field of the class sorted by field name (except private static and private transient fields):
    1. The name of the field in UTF encoding.
    2. The modifiers of the field written as a 32-bit integer.
    3. The descriptor of the field in UTF encoding
  5. If a class initializer exists, write out the following:
    1. The name of the method, <clinit>, in UTF encoding.
    2. The modifier of the method, java.lang.reflect.Modifier.STATIC, written as a 32-bit integer.
    3. The descriptor of the method, ()V, in UTF encoding.
  6. For each non-private constructor sorted by method name and signature:
    1. The name of the method, <init>, in UTF encoding.
    2. The modifiers of the method written as a 32-bit integer.
    3. The descriptor of the method in UTF encoding.
  7. For each non-private method sorted by method name and signature:
    1. The name of the method in UTF encoding.
    2. The modifiers of the method written as a 32-bit integer.
    3. The descriptor of the method in UTF encoding.
  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;

    10. Contents | Previous | Next JavaTM Object Serialization Specification

    Copyright © 2003 Sun Microsystems, Inc. All rights reserved.


Example of Serializable Fields

Appendix C

Topics:

  • Example Alternate Implementation of java.io.File

C.1 Example Alternate Implementation of java.io.File

This appendix provides a brief example of how an existing class could be specified and implemented to interoperate with the existing implementation but without requiring the same assumptions about the representation of the file name as a String.

The system class java.io.File represents a filename and has methods for parsing, manipulating files and directories by name. It has a single private field that contains the current file name. The semantics of the methods that parse paths depend on the current path separator which is held in a static field. This path separator is part of the serialized state of a file so that file name can be adjusted when read.

The serialized state of a File object is defined as the serializable fields and the sequence of data values for the file. In this case, there is one of each.

Serializable Fields:
    String path;     // path name with embedded separators
Serializable Data:
    char            // path name separator for path name
An alternate implementation might be defined as follows:
class File implements java.io.Serializable {
    ...
    private String[] pathcomponents;
    // Define serializable fields with the ObjectStreamClass

    /**
    * @serialField path String
    *              Path components separated by separator.
    */
    private static final ObjectStreamField[] serialPersistentFields
    =   }
        new ObjectStreamField(“path”, String.class)
     };
    ...
    /**
    * @serialData  Default fields followed by separator character.
    */
    private void writeObject(ObjectOutputStream s)
        throws IOException
    {
        ObjectOutputStream.PutField fields = s.putFields();
        StringBuffer str = new StringBuffer();
        for(int i = 0; i < pathcomponents; i++) {
            str.append(separator);
            str.append(pathcomponents[i]);
        }
        fields.put(“path”, str.toString());
        s.writeFields();
        s.writeChar(separatorChar); // Add the separator character
    }
    ...
    private void readObject(ObjectInputStream s)
        throws IOException
    {
        ObjectInputStream.GetField fields = s.readFields();
        String path = (String)fields.get(“path”, null);
        ...
        char sep = s.readChar(); // read the previous separator char
        // parse path into components using the separator
        // and store into pathcomponents array.
    }
}

Contents | Previous | Next JavaTM Object Serialization Specification

Copyright © 2003 Sun Microsystems, Inc. All rights reserved.


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 | Previous | Next JavaTM Object Serialization Specification

Copyright © 2003 Sun Microsystems, Inc. All rights reserved.


Object Input Classes

Chapter 1

Topics:

  • The ObjectInputStream Class
  • The ObjectInputStream.GetField Class
  • The ObjectInputValidation Interface
  • The readObject Method
  • The readExternal Method
  • The readResolve Method

1.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 its name, serialVersionUID, and fields. Add it and its handle to the set of known objects. Call the resolveClass method on the stream to get the local class for this descriptor, and throw an exception if the class cannot be found. Return the ObjectStreamClass object.
  7. If the object in the stream is a String, read its UTF encoding, add it and its handle to the set of known objects, and proceed to Step 11.
  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 11.
  9. 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.
  10. An instance of the class is allocated. The instance and its handle are added to the set of known objects. The contents restored appropriately:
    1. 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.
    2. 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.
  11. Process potential substitutions by the class of the object and/or by a subclass of ObjectInputStream:
    1. If the class of the object defines the appropriate readResolve method, the method is called to allow the object to replace itself.
    2. 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 obtainable elsewhere in the stream or through external means. However, for objects which are not instances of java.lang.Class and do not define readResolve methods, readUnshared guarantees that the returned object reference is unique and cannot be obtained a second time from the ObjectInputStream that created it, even if the underlying data stream has been manipulated. This guarantee applies only to the base-level object returned by readUnshared, and not to any transitively referenced sub-objects in the returned object graph.

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.

1.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.

1.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;
}

1.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 1.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.

1.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 section 4.5.5 of The Java™ Language Specification, Second Edition); 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.

1.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.”

1.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 | Previous | Next JavaTM Object Serialization Specification

Copyright © 2003 Sun Microsystems, Inc. All rights reserved.


Object Output Classes

Chapter 1

Topics:

  • The ObjectOutputStream Class
  • The ObjectOutputStream.PutField Class
  • The writeObject Method
  • The writeExternal Method
  • The writeReplace Method
  • The useProtocolVersion Method

1.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 descriptor for the class is written to the stream including its name, serialVersionUID, and the list of fields by name and type. A handle is assigned for the descriptor. The annotateClass subclass method is called before writeObject returns.
  8. Process potential substitutions by the class of the object and/or by a subclass of ObjectInputStream.
    1. If the class of an object defines the appropriate writeReplace method, the method is called. Optionally, it can return a substitute object to be serialized.
    2. 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.

      3. 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 in Universal Transfer Format (UTF) format, or a variant of UTF for long strings (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. 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 this object. Starting in Java™ 2 SDK, Standard Edition, v1.3, writeObject calls writeClassDescriptor to output the ObjectStreamClass object.
  12. The contents of the object are written to the stream.
    1. 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.
    2. If the object is externalizable, the writeExternal method of the object is called.
    3. 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 1.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.

1.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. I/O exceptions will be thrown if the underlying stream throws an exception. An IllegalArgumentException is thrown if the name does not match the name of a field declared for this object’s ObjectStreamClass or if the type of the value does not match the declared type of the serializable field.

1.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.

1.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 1.6 "The readExternal Method.” Compatibility issues caused by this change are discussed in Section 1.6 "The useProtocolVersion Method.”

1.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.

1.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 | Previous | Next JavaTM Object Serialization Specification

Copyright © 2003 Sun Microsystems, Inc. All rights reserved.


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 flag indicating if the class defined a writeObject method
  • The number of serializable fields
  • The array of fields of the class that are serialized by the default mechanism
    For 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 section 4.3.2 of The Java™ Virtual Machine Specification, Second Edition.
  • 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 depends on the length of the UTF encoded string. If the UTF encoding of the given String is less than 65536 bytes in length, the String is written in the standard Java UTF-8 format. Starting with the Java™ 2 SDK, Standard Edition, v1.3, strings for which the UTF encoding length is greater than or equal to 65536 bytes are written in a variant “long” UTF format. The “long” UTF format is identical to the standard Java UTF-8 format, except that it uses 8 bytes to write the length of the UTF string, instead of 2 bytes. 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.

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 (long-utf) is used to designate a string written in “long” UTF format. 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
  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)

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  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;

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.

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 | Previous | Next JavaTM Object Serialization Specification

Copyright © 2003 Sun Microsystems, Inc. All rights reserved.


Security in Object Serialization

Appendix A

Topics:

  • Overview
  • Design Goals
  • Security Issues
  • Preventing Serialization of Sensitive Data
  • Writing Class-Specific Serializing Methods
  • Guarding Unshared Deserialized Objects
  • Preventing Overwriting of Externalizable Objects
  • Encrypting a Bytestream

A.1 Overview

The object serialization system allows a bytestream to be produced from a graph of objects, sent out of the Java™ environment (either saved to disk or transmitted over the network) and then used to recreate an equivalent set of new objects with the same state.

What happens to the state of the objects outside of the environment is outside of the control of the Java™ system (by definition), and therefore is outside the control of the security provided by the system. The question then arises: once an object has been serialized, can the resulting byte array be examined and changed in a way that compromises the security of the Java program that deserializes it? The intent of this section is to address these security concerns.

A.2 Design Goals

The goal for object serialization is to be as simple as possible and yet still be consistent with known security restrictions; the simpler the system is, the more likely it is to be secure. The following points summarize the security measures present in object serialization:

  • Only objects implementing the java.io.Serializable or java.io.Externalizable interfaces can be serialized. Mechanisms are provided which can be used to prevent the serialization of specific fields (typically, those containing sensitive or unneeded data).
  • The serialization package cannot be used to recreate or reinitialize objects. Deserializing a byte stream may result in the creation of new objects, but will not overwrite or modify the contents of existing objects.
  • Although deserializing an object may trigger downloading of code from a remote source, the downloaded code is restricted by all of the usual Java™ code verification and security mechanisms. Classes loaded as a side-effect of deserialization are no more or less secure than those loaded in any other fashion.

A.3 Security Issues

Naive use of object serialization may allow a malicious party with access to the serialization byte stream to read private data, create objects with illegal or dangerous state, or obtain references to the private fields of deserialized objects. Implementors concerned with security should be aware of the following implications of serialization:

  • Default serialization of an object writes the values of all fields of that object to the serialization stream, regardless of whether or not they are public. Malicious code can effectively read the values of private fields of a serializable object by serializing the object and then examining the resulting byte stream. Methods for avoiding this problem are described in Section A.4 "Preventing Serialization of Sensitive Data”.
  • During deserialization, objects are created and initialized using data from the incoming serialization stream. If the stream was corrupted or tampered with prior to deserialization, the deserialized objects may have unexpected or illegal state. Methods for avoiding this problem are described in Section A.5 "Writing Class-Specific Serializing Methods”.
  • By inserting extra wire handle references into a serialization byte stream, it is possible during deserialization to forge extra references to objects occurring earlier in the stream. Therefore, it is unsafe for developers to assume that references to private objects obtained via deserialization are unique. Techniques for dealing with this problem are discussed in section Section A.6 "Guarding Unshared Deserialized Objects”.
  • Objects implementing the Externalizable interface are susceptible to overwriting, since the readExternal method is public. A caller can invoke the readExternal method at any time, passing it an arbitrary stream to read values from, causing the target object to be reinitialized. A means of preventing this is outlined in Section A.7 "Preventing Overwriting of Externalizable Objects”.

A.4 Preventing Serialization of Sensitive Data

Fields containing sensitive data should not be serialized; doing so exposes their values to any party with access to the serialization stream. There are several methods for preventing a field from being serialized:

  • Declare the field as private transient.
  • Define the serialPersistentFields field of the class in question, and omit the field from the list of field descriptors.
  • Write a class-specific serialization method (i.e., writeObject or writeExternal) which does not write the field to the serialization stream (i.e., by not calling ObjectOutputStream.defaultWriteObject).

A.5 Writing Class-Specific Serializing Methods

To guarantee that a deserialized object does not have state which violates some set of invariants that need to be guaranteed, a class can define its own serializing and deserializing methods. If there is some set of invariants that need to be maintained between the data members of a class, only the class can know about these invariants, and it is up to the class author to provide a deserialization method that checks these invariants.

Security-conscious implementors should keep in mind that a serializable class’ readObject method is effectively a public constructor, and should be treated as such. This is true whether the readObject method is implicit or explicit. It is not safe to assume that the byte stream that is provided to the readObject method was generated by serializing a properly constructed object of the correct type. It is good defensive programming to assume that the byte stream is provided by an adversary whose goal is to compromise the object under construction.

This is important even if you are not worried about security; it is possible that disk files can be corrupted and serialized data be invalid. So checking such invariants is more than just a security measure; it is a validity measure. However, the only place it can be done is in the code for the particular class, since there is no way the serialization package can determine what invariants should be maintained or checked.

In version 1.4 of the Java™ 2 SDK, Standard Edition, support was added for class-defined readObjectNoData methods (see Section 1.5 "The readObjectNoData Method”). Non-final serializable classes which initialize fields to non-default values should define a readObjectNoData method to ensure consistent state 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

A.6 Guarding Unshared Deserialized Objects

If a class has any private or package private object reference fields, and the class depends on the fact that these object references are not available outside the class (or package), then either the referenced objects must be defensively copied as part of the deserialization process, or else the ObjectOutputStream.writeUnshared and ObjectInputStream.readUnshared methods (introduced in version 1.4 of the Java™ 2 SDK, Standard Edition) should be used to ensure unique references to the internal objects.

In the copying approach, the sub-objects deserialized from the stream should be treated as "untrusted input": newly created objects, initialized to have the same value as the deserialized sub-objects, should be substituted for the sub-objects by the readObject method. For example, suppose an object has a private byte array field, b, that must remain private:

    private void readObject(ObjectInputStream s)
        throws IOException, ClassNotFoundException
    {
        s.defaultReadObject();
        b = (byte[])b.clone();
        if (<invariants are not satisfied>)
            throw new java.io.StreamCorruptedException();
    }

This issue is particularly important when considering serialization of immutable objects containing internal (necessarily private) references to mutable sub-objects. If no special measures are taken to copy the sub-objects during deserialization of the container object, then a malicious party with write access to the serialization stream may violate the container object’s immutability by forging references to its mutable sub-objects, and using these references to change the internal state of the container object. Thus, in this case it is imperative that the immutable container class provide a class-specific deserialization method which makes private copies of each mutable component object it deserializes. Note that for the purpose of maintaining immutability, it is unnecessary to copy immutable component objects.

It is also important to note that calling clone may not always be the right way to defensively copy a sub-object. If the clone method cannot be counted on to produce an independent copy (and not to "steal" a reference to the copy), an alternative means should be used to produce the copy. An alternative means of copying should always be used if the class of the sub-object is not final, since the clone method or helper methods that it calls may be overridden by subclasses.

Starting in version 1.4 of the Java™ 2 SDK, Standard Edition, unique references to deserialized objects can also be ensured by using the ObjectOutputStream.writeUnshared and ObjectInputStream.readUnshared methods, thus avoiding the complication, performance costs and memory overhead of defensive copying. The readUnshared and writeUnshared methods are further described in Section 1.1 "The ObjectInputStream Class” and Section 1.1 "The ObjectOutputStream Class”.

A.7 Preventing Overwriting of Externalizable Objects

Objects which implement the Externalizable interface must provide a public readExternal method. Since this method is public, it can be called at arbitrary times by anyone with access to the object. To prevent overwriting of the object’s internal state by multiple (illegal) calls to readExternal, implementors may choose to add checks to insure that internal values are only set when appropriate:

    public synchronized void readExternal(ObjectInput in)
        throws IOException, ClassNotFoundException
    {
        if (! initialized) {
            initialized = true;

            // read in and set field values ...
        } else {
            throw new IllegalStateException();
        }
    }

A.8 Encrypting a Bytestream

Another way of protecting a bytestream outside the virtual machine is to encrypt the stream produced by the serialization package. Encrypting the bytestream prevents the decoding and the reading of a serialized object’s private state, and can help safeguard against tampering with stream contents.

Object serialization allows encryption, both by allowing classes to define their own methods for serialization and deserialization (inside which encryption can be used), and by adhering to the composable stream abstraction (allowing the output of a serialization stream to be channelled into another filter stream which encrypts the data).

Contents | Previous | Next JavaTM Object Serialization Specification

Copyright © 2003 Sun Microsystems, Inc. All rights reserved.


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
  • Protecting Sensitive Information

1.1 Overview

The ability to store and retrieve Java™ 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 Java™ objects, the serialized form must be able to identify and verify the Java™ 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 Java™ objects are to:

  • Have a simple yet extensible mechanism.
  • Maintain the Java™ 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 Java™ 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 1.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 objects of type Class, ObjectStreamClass, String, and arrays. 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.

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 1.2 "The ObjectOutputStream.PutField Class” and Section 1.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 Java™ 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 1.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 1.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 Java™ 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 Java™ 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 1.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 1.7 "The readResolve Method” for additional information.)

1.12 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 | Previous | Next JavaTM Object Serialization Specification

Copyright © 2003 Sun Microsystems, Inc. All rights reserved.


JavaTM Object Serialization Specification
Contents | Previous | Next

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 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 Java™ Type Evolution

5.6 Type Changes Affecting Serialization

6 Object Serialization Stream Protocol

6.1 Overview

6.2 Stream Elements

6.3 Stream Protocol Versions

6.4 Grammar for the Stream Format

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 | Previous | Next

Copyright © 2003 Sun Microsystems, Inc. All rights reserved.


Versioning of Serializable Objects

Chapter 5

Topics:

  • Overview
  • Goals
  • Assumptions
  • Who’s Responsible for Versioning of Streams
  • Compatible Java™ Type Evolution
  • Type Changes Affecting Serialization

5.1 Overview

When Java™ objects use serialization to save state in files, or as blobs in databases, the potential arises that the version of a class reading the data is different than the version that wrote the data.

Versioning raises some fundamental questions about the identity of a class, including what constitutes a compatible change. A compatible change is a change that does not affect the contract between the class and its callers.

This section describes the goals, assumptions, and a solution that attempts to address this problem by restricting the kinds of changes allowed and by carefully choosing the mechanisms.

The proposed solution provides a mechanism for “automatic” handling of classes that evolve by adding fields and adding classes. Serialization will handle versioning without class-specific methods to be implemented for each version. The stream format can be traversed without invoking class-specific methods.

5.2 Goals

The goals are to:

  • Support bidirectional communication between different versions of a class operating in different virtual machines by:
  • Defining a mechanism that allows Java™ classes to read streams written by older versions of the same class.
  • Defining a mechanism that allows Java™ classes to write streams intended to be read by older versions of the same class.
  • Provide default serialization for persistence and for RMI.
  • Perform well and produce compact streams in simple cases, so that RMI can use serialization.
  • Be able to identify and load classes that match the exact class used to write the stream.
  • Keep the overhead low for nonversioned classes.
  • Use a stream format that allows the traversal of the stream without having to invoke methods specific to the objects saved in the stream.

5.3 Assumptions

The assumptions are that:

  • Versioning will only apply to serializable classes since it must control the stream format to achieve it goals. Externalizable classes will be responsible for their own versioning which is tied to the external format.
  • All data and objects must be read from, or skipped in, the stream in the same order as they were written.
  • Classes evolve individually as well as in concert with supertypes and subtypes.
  • Classes are identified by name. Two classes with the same name may be different versions or completely different classes that can be distinguished only by comparing their interfaces or by comparing hashes of the interfaces.
  • Default serialization will not perform any type conversions.
  • The stream format only needs to support a linear sequence of type changes, not arbitrary branching of a type.

5.4 Who’s Responsible for Versioning of Streams

In the evolution of classes, it is the responsibility of the evolved (later version) class to maintain the contract established by the nonevolved class. This takes two forms. First, the evolved class must not break the existing assumptions about the interface provided by the original version, so that the evolved class can be used in place of the original. Secondly, when communicating with the original (or previous) versions, the evolved class must provide sufficient and equivalent information to allow the earlier version to continue to satisfy the nonevolved contract.

Graphical illustration of the contract described in the previous context

For the purposes of the discussion here, each class implements and extends the interface or contract defined by its supertype. New versions of a class, for example foo’, must continue to satisfy the contract for foo and may extend the interface or modify its implementation.

Communication between objects via serialization is not part of the contract defined by these interfaces. Serialization is a private protocol between the implementations. It is the responsibility of the implementations to communicate sufficiently to allow each implementation to continue to satisfy the contract expected by its clients.

5.5 Compatible Java™ Type Evolution

In the Java™ Language Specification, Chapter 13 discusses binary compatibility of Java™ classes as those classes evolve. Most of the flexibility of binary compatibility comes from the use of late binding of symbolic references for the names of classes, interfaces, fields, methods, and so on.

The following are the principle aspects of the design for versioning of serialized object streams.

  • The default serialization mechanism will use a symbolic model for binding the fields in the stream to the fields in the corresponding class in the virtual machine.
  • Each class referenced in the stream will uniquely identify itself, its supertype, and the types and names of each serializable field written to the stream. The fields are ordered with the primitive types first sorted by field name, followed by the object fields sorted by field name.
  • Two types of data may occur in the stream for each class: required data (corresponding directly to the serializable fields of the object); and optional data (consisting of an arbitrary sequence of primitives and objects). The stream format defines how the required and optional data occur in the stream so that the whole class, the required, or the optional parts can be skipped if necessary.
  • The required data consists of the fields of the object in the order defined by the class descriptor.
  • The optional data is written to the stream and does not correspond directly to fields of the class. The class itself is responsible for the length, types, and versioning of this optional information.
  • If defined for a class, the writeObject/readObject methods supersede the default mechanism to write/read the state of the class. These methods write and read the optional data for a class. The required data is written by calling defaultWriteObject and read by calling defaultReadObject.
  • The stream format of each class is identified by the use of a Stream Unique Identifier (SUID). By default, this is the hash of the class. All later versions of the class must declare the Stream Unique Identifier (SUID) that they are compatible with. This guards against classes with the same name that might inadvertently be identified as being versions of a single class.
  • Subtypes of ObjectOutputStream and ObjectInputStream may include their own information identifying the class using the annotateClass method; for example, MarshalOutputStream embeds the URL of the class.

5.6 Type Changes Affecting Serialization

With these concepts, we can now describe how the design will cope with the different cases of an evolving class. The cases are described in terms of a stream written by some version of a class. When the stream is read back by the same version of the class, there is no loss of information or functionality. The stream is the only source of information about the original class. Its class descriptions, while a subset of the original class description, are sufficient to match up the data in the stream with the version of the class being reconstituted.

The descriptions are from the perspective of the stream being read in order to reconstitute either an earlier or later version of the class. In the parlance of RPC systems, this is a “receiver makes right” system. The writer writes its data in the most suitable form and the receiver must interpret that information to extract the parts it needs and to fill in the parts that are not available.

5.6.1 Incompatible Changes

Incompatible changes to classes are those changes for which the guarantee of interoperability cannot be maintained. The incompatible changes that may occur while evolving a class are:

  • Deleting fields - If a field is deleted in a class, the stream written will not contain its value. When the stream is read by an earlier class, the value of the field will be set to the default value because no value is available in the stream. However, this default value may adversely impair the ability of the earlier version to fulfill its contract.
  • Moving classes up or down the hierarchy - This cannot be allowed since the data in the stream appears in the wrong sequence.
  • Changing a nonstatic field to static or a nontransient field to transient - When relying on default serialization, this change is equivalent to deleting a field from the class. This version of the class will not write that data to the stream, so it will not be available to be read by earlier versions of the class. As when deleting a field, the field of the earlier version will be initialized to the default value, which can cause the class to fail in unexpected ways.
  • Changing the declared type of a primitive field - Each version of the class writes the data with its declared type. Earlier versions of the class attempting to read the field will fail because the type of the data in the stream does not match the type of the field.
  • Changing the writeObject or readObject method so that it no longer writes or reads the default field data or changing it so that it attempts to write it or read it when the previous version did not. The default field data must consistently either appear or not appear in the stream.
  • Changing a class from Serializable to Externalizable or visa-versa is an incompatible change since the stream will contain data that is incompatible with the implementation in the available class.
  • Removing either Serializable or Externalizable is an incompatible change since when written it will no longer supply the fields needed by older versions of the class.
  • Adding the writeReplace or readResolve method to a class is incompatible if the behavior would produce an object that is incompatible with any older version of the class.

5.6.2 Compatible Changes

The compatible changes to a class are handled as follows:

  • Adding fields - When the class being reconstituted has a field that does not occur in the stream, that field in the object will be initialized to the default value for its type. If class-specific initialization is needed, the class may provide a readObject method that can initialize the field to nondefault values.
  • Adding classes - The stream will contain the type hierarchy of each object in the stream. Comparing this hierarchy in the stream with the current class can detect additional classes. Since there is no information in the stream from which to initialize the object, the class’s fields will be initialized to the default values.
  • Removing classes - Comparing the class hierarchy in the stream with that of the current class can detect that a class has been deleted. In this case, the fields and objects corresponding to that class are read from the stream. Primitive fields are discarded, but the objects referenced by the deleted class are created, since they may be referred to later in the stream. They will be garbage-collected when the stream is garbage-collected or reset.
  • Adding writeObject/readObject methods - If the version reading the stream has these methods then readObject is expected, as usual, to read the required data written to the stream by the default serialization. It should call defaultReadObject first before reading any optional data. The writeObject method is expected as usual to call defaultWriteObject to write the required data and then may write optional data.
  • Removing writeObject/readObject methods - If the class reading the stream does not have these methods, the required data will be read by default serialization, and the optional data will be discarded.
  • Adding java.io.Serializable - This is equivalent to adding types. There will be no values in the stream for this class so its fields will be initialized to default values. The support for subclassing nonserializable classes requires that the class’s supertype have a no-arg constructor and the class itself will be initialized to default values. If the no-arg constructor is not available, the InvalidClassException is thrown.
  • Changing the access to a field - The access modifiers public, package, protected, and private have no effect on the ability of serialization to assign values to the fields.
  • Changing a field from static to nonstatic or transient to nontransient - When relying on default serialization to compute the serializable fields, this change is equivalent to adding a field to the class. The new field will be written to the stream but earlier classes will ignore the value since serialization will not assign values to static or transient fields.

Contents | Previous | Next JavaTM Object Serialization Specification

Copyright © 2003 Sun Microsystems, Inc. All rights reserved.


Sound

 Documentation Contents
The JavaTM 2 Platform includes a powerful API for capturing, processing, and playing back audio and MIDI (Musical Intstrument Digital Interface) data. This API is supported by an efficient sound engine which guarantees high-quality audio mixing and MIDI synthesis capabilities for the platform.

The provided reference implementation of this API supports the following features:

  • Audio file formats: AIFF, AU and WAV
  • Music file formats: MIDI Type 0, MIDI Type 1, and Rich Music Format (RMF)
  • Sound formats: 8- and 16-bit audio data, in mono and stereo, with sample rates from 8 kHz to 48 kHz
  • Linear, a-law, and mu-law encoded data in any of the supported audio file formats
  • MIDI wavetable synthesis and sequencing in software, and access to hardware MIDI devices
  • An all-software mixer that can mix and render up to 64 total channels of digital audio and synthesized MIDI music

The above list describes the reference implementation, not the API itself. The API permits flexible configuration of the audio and MIDI system, including ways for applications to ask the system exactly what resources are installed and available.

Additional information on the reference implementation is available from the Java Sound Home Page. This site also provides links to a selection of MIDI sound banks that may be used to enhance the sound quality of the MIDI synthesizer.

Java Sound Guide
  • API Programmer's Guide - also available in PDF
Java Sound API Reference
(javadoc)
  • javax.sound.sampled Package
  • javax.sound.midi Package
  • javax.sound.sampled.spi Package
  • javax.sound.midi.spi Package
For More Information

Located on the Java Software website:
  • The Java Sound Home Page

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: javasound-comments@sun.com 		Sun
Java Software


Code Overview: AudioSystem.java

Appendix 1: Code Overview: AudioSystem.java

For the benefit of service providers and API implementers, a brief overview of the JavaSound 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 onto 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:

The following context described this graphic.

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().


Chapter 1: Introduction to the Java Sound API

Design Goals

The JavaTM 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.


Chapter 2: Overview of the Sampled Package

This chapter provides an introduction to the JavaTM 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.)

a 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:

The following context describes this graphic

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:

The following context describes this graphic

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.

The following context describes this graphic

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.


Chapter 3: Accessing Audio System Resources

Notes:

  1. For Linux, Port is currently not implemented in the Sun reference implementation of JavaSound. (See http://developer.java.sun.com/developer/bugParade/bugs/4384401.html.)
  2. Looping a portion of a Clip from a start point to an end point doesn't work. (See http://developer.java.sun.com/developer/bugParade/bugs/4386052.html.)

The JavaTM 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.


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 JavaTM 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."


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 JavaTM 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."


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 JavaTM 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.")


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 JavaTM 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:

  1. Get an AudioInputStream object from the file.
  2. Create a byte array in which you'll store successive chunks of data from the file.
  3. 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.


Chapter 8: Overview of the MIDI Package

Chapter 1,"Introduction to Java Sound," gave a glimpse into the MIDI capabilities of the JavaTM 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.


Chapter 9: Accessing MIDI System Resources

The JavaTM 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.


Chapter 10: Transmitting and Receiving MIDI Messages

Understanding Devices, Transmitters, and Receivers

The JavaTM 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.


Chapter 11: Playing, Recording and Editing MIDI Sequences

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 JavaTM 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:

  1. Use MidiSystem.getSequencer to get a new sequencer to use for recording, as above.

  2. 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.

  3. 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.

  4. Create an empty Track in the Sequence, with Sequence.createTrack. This step is unnecessary if the Sequence was created with initial Tracks.

  5. 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.

  6. 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.

  7. Invoke startRecording on the Sequencer.

  8. When done recording, invoke Sequencer.stop or Sequencer.stopRecording.

  9. 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.


Chapter 12: Synthesizing Sound

Most programs that avail themselves of the JavaTM 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."


Chapter 13: Introduction to the Service Provider Interfaces

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 JavaTM 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.


Chapter 14: Providing Sampled-Audio Services

As discussed in Chapter 13, "Introduction to the Service Provider Interfaces," the JavaTM 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.


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 JavaTM 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.


Java Plug-in 1.4 Developer Guide Contents

Java logo
Java Sound Programmer Guide

Note: There are two ways to navigate this guide:

  • Search the guide
  • Select from the contents below:

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

Last updated January 11, 2002


Preface

For Whom This Guide Is Intended

This guide is intended for three groups of readers:

  • Application developers: software programmers who want to write JavaTM applications or applets using audio or MIDI. Most readers will fall into this category.
  • Service providers: developers of software modules that extend the capabilities of an implementation of the Java Sound application programming interface (API). For example, a vendor might provide a new audio mixer or MIDI synthesizer, or the ability to read and write a new file format. The Java Sound API is designed to let programs automatically access all such "plug-in" modules available on a particular system.
  • API implementors: developers creating new implementations of the Java Sound API.

It is assumed that the reader has a basic knowledge of programming in the Java language. Familiarity with audio and MIDI is helpful but not assumed.

What This Guide Describes

This is a largely conceptual description of the Java Sound API, with some code snippets as programming examples. The Java Sound API specifies a software layer that allows application programs to communicate with an audio and MIDI engine. The Java Sound API is part of the JavaTM 2 Platform, Standard Edition (J2SE), version 1.3, which is the version described by this guide. The sound API is included in both the Java 2 Software Development Kit (SDK), Standard Edition, and the Java 2 Runtime Environment, Standard Edition. Earlier implementations of the Java Sound API were supplied as a separate products and their programming interfacea differ from the one described here.

Note:

This guide is not a description of any particular implementation of the Java Sound API. In particular, it does not specifically describe the reference implementation of the Java Sound API created by Sun Microsystems, Inc. For example, you will not find here a list of exactly which sound file formats are supported in the reference implementation. (Because the Java Sound API makes "plug-in" services possible, API implementors and/or third parties can add support for new formats, ports with special features, etc.) In general, this guide ignores unique features, extensions, limitations, or bugs of a particular implementation.

As a convenience for developers, it does make note of some current limitations of Sun's reference implemenation. If you are having problems, it is highly recommended that you consult:

  • Sun's Bug Database in the Java Developer Connection
  • Java Sound Home Page
  • Java Sound Reference Implementation Notes

For More Information

See the links to the Java Sound API reference documentation at http://java.sun.com/products/jdk/1.4/docs/guide/sound/. This Web site also includes a brief description of the reference implementation, as well as links to other resources about the Java Sound API, such as demo programs, mailing lists, and Frequently Answered Questions (FAQs). Also see the Java Sound Home Page mentioned above.

Copyright © 2000, Sun Microsystems Inc. All rights reserved.


Deva Search

Java Sound Search Page
Tips


Endorsed Standards Override Mechanism

 Documentation Contents

Introduction

An endorsed standard is a JavaTM API defined through a standards process other than the Java Community Process SM (JCPSM). Because endorsed standards are defined outside the JCP, it is anticipated that such standards may be revised between releases of the Java 2 Platform. In order to take advantage of new revisions to endorsed standards, developers and software vendors may use the Endorsed Standards Override Mechanism to provide newer versions of an endorsed standard than those included in the Java 2 Platform as released by Sun Microsystems.

Endorsed Standards Classes Deployment

Classes implementing newer versions of endorsed standards should be placed in JAR files. The system property java.endorsed.dirs specifies one or more directories that the Java runtime environment will search for such JAR files. If more than one directory path is specified by java.endorsed.dirs, they must be separated by File.pathSeparatorChar. If no value is set for java.endorsed.dirs, then Sun Microsystem's implementation of the Java 2 Platform looks for JAR files in a default standard location:
<java-home>\lib\endorsed          [Microsoft Windows]
<java-home>/lib/endorsed          [Solaris or Linux]
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 or the jre directory in the Java 2 SDK).

The Java runtime environment will use classes in such JAR files to override the corresponding classes provided in the Java 2 Platform as shipped by Sun.

Endorsed Standards APIs

The endorsed standards for J2SETM 1.4 constitute all classes and interfaces that are defined in the packages listed below. Classes and interfaces defined in sub-packages of listed packages are not endorsed standards unless those sub-packages are themselves listed. The Endorsed Standards Override Mechanism may be used to override the J2SE platform packages in the list below, and these packages may be overriden only by versions of the endorsed standard that are newer than that provided by the Java 2 Platform as released by Sun. No other packages from the J2SE platform API specification may be overridden.
javax.rmi.CORBA
org.omg.CORBA
org.omg.CORBA.DynAnyPackage
org.omg.CORBA.ORBPackage
org.omg.CORBA.portable
org.omg.CORBA.TypeCodePackage
org.omg.CORBA_2_3
org.omg.CORBA_2_3.portable
org.omg.CosNaming
org.omg.CosNaming.NamingContextExtPackage
org.omg.CosNaming.NamingContextPackage
org.omg.Dynamic
org.omg.DynamicAny
org.omg.DynamicAny.DynAnyFactoryPackage
org.omg.DynamicAny.DynAnyPackage
org.omg.IOP
org.omg.IOP.CodecFactoryPackage
org.omg.IOP.CodecPackage
org.omg.Messaging
org.omg.PortableInterceptor
org.omg.PortableInterceptor.ORBInitInfoPackage
org.omg.PortableServer
org.omg.PortableServer.CurrentPackage
org.omg.PortableServer.POAManagerPackage
org.omg.PortableServer.POAPackage
org.omg.PortableServer.portable
org.omg.PortableServer.ServantLocatorPackage
org.omg.SendingContext
org.omg.stub.java.rmi
org.w3c.dom
org.xml.sax
org.xml.sax.ext
org.xml.sax.helpers
In addition to the packages listed above, which are part of the J2SE specification, users of Sun's J2SE Reference Implementation may be allowed to use the Endorsed Standards Override Mechanism to override implementation-specific classes such as the org.w3c.dom sub-packages delivered in Sun's Reference Implementation. See the corresponding license for details.

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: j2se-comments@sun.com 		Sun Microsystems, Inc
Java Software


Project Swing (Java(TM) Foundation Classes) Software

Java

Project Swing (JavaTM Foundation Classes) Software

 Documentation Contents
Project Swing is the part of the JavaTM Foundation Classes (JFC) software that implements a set of GUI components with a pluggable look and feel. Project Swing is implemented entirely in the Java programming language, and is based on the JDKTM 1.1 Lightweight UI Framework. The pluggable look and feel lets you design a single set of GUI components that can automatically have the look and feel of any OS platform (Microsoft Windows, SolarisTM, Macintosh). Project Swing components include both 100% Pure JavaTM certified versions of the existing AWT component set (Button, Scrollbar, Label, etc.), plus a rich set of higher-level components (such as tree view, list box, and tabbed panes).

Enhancements

  • Swing Enhancements in the Java 2 SDK, v1.4.1 and v1.4.2
  • Swing Enhancements in the Java 2 SDK, v1.4
  • Swing Enhancements in the Java 2 SDK, v1.3

API Specification
(javadoc)

  • javax.swing
  • javax.swing.border
  • javax.swing.colorchooser
  • javax.swing.event
  • javax.swing.filechooser
  • javax.swing.plaf
  • javax.swing.plaf.basic
  • javax.swing.plaf.metal
  • javax.swing.plaf.multi
  • javax.swing.table
  • javax.swing.text
  • javax.swing.text.html
  • javax.swing.text.html.parser
  • javax.swing.text.rtf
  • javax.swing.tree
  • javax.swing.undo

Additional Specification

  • Focus Model Specification

For More Information

Located on the Java Software website:
  • The Swing Connection
  • The Java Tutorial: Creating a GUI with JFC/Swing
  • The JFC Home Page

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: swing-feedback@java.sun.com 		Sun Microsystems, Inc
Java Software


Swing Changes and New Features

Java

Swing Changes and New Features for JavaTM 2 SDK, Standard Edition, v 1.4

 Project Swing

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 Java Developer Connection (JDC) Bug Parade , 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 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

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 © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: swing-feedback@java.sun.com. This is not a subscription list. 		Sun
Java Software


Actions

 Other Swing Changes

API for Adding Actions to ActionEvent Sources

Background

Swing provides an implementation of the Command pattern which helps application developer centralize functionality which can be accessed from multiple places in the GUI. The Action interface is used to provide a stateful ActionListener which can provide the implementation of functionality accessed for example from the toolbar, a menu item, and a keyboard binding. As the state of the Action changes, for instance when it becomes disabled, the associated controls change their state accordingly (they also become disabled).

The Problem

For Actions to work as intended, the following connections need to be made (assume the Action has already been created):
  1. The control needs to be created
  2. The Action is added as an ActionListener on the control
  3. A PropertyChangeListener is created which describes how the control should be updated in response to PropertyChangeEvents on the Action
  4. The PropertyChangeListener is added as a listener on the Action.
  5. Information about the linkage may need to be retained so it can be undone to allow garbage collection (in 1.2 this can be automatically handled with WeakRefs).
Since a typical application may have between 5 and 25 Actions, and 2-3 controls per Action, the steps above need to be done up to 75 times!

In order to relieve the developer of much of this burden, we have provided a way to have this done automatically, through helper methods on potential Containers of Actions. The three places where this is surfaced in Swing at present are:

JToolBar.java | public JButton add(Action a)
JMenu.java | public JMenuItem add(Action a)
JPopupMenu.java | public JMenuItem add(Action a)

The problems with this approach are several:

  1. It is highly problematic for Builders, since it overloads Container.add() to allow a non-Component parameter which is not itself the thing that ends up being added.
  2. Developers cannot participate in the configuration of the controls created without subclassing the container classes
  3. Even if they do subclass, the granularity of the configuration ends up being per-Container instead of per-control added.
  4. It limits developers to the expected control for each Container rather than allowing the full range of ActionEvent sources which Action permits.

Solution

Many developers have commented that they would prefer to create their own controls which are ActionEvent sources and then have a method which connects them to a particular Action. The solution is along these lines, and addresses the deficiencies listed above.

The added API is initially added to AbstractButton, which defines the abstract superclass of JButton, JMenuItem, JMenu, JCheckBox, etc.

The new public methods are as follows:

  • public void setAction(Action a)
  • public Action getAction()
  • protected void configurePropertiesFromAction(Action a)
  • protected PropertyChangeListener createActionPropertyChangeListener()
In addition, constructors have been added to the ActionEvent sources which will allow for creating a control directly with the supplied Action.

In JButton:

  • public JButton(Action a)
Equivalent constructors have been added to:
  • JCheckBox
  • JRadioButton
  • JToggleButton
  • JMenuItem
  • JMenu
  • JCheckBoxMenuItem
  • JRadioButtonMenuItem
Notes:
  • setAction is merely a helper method which performs the linkage steps described above as a convenience to the developer.
  • It is not expected that developers will often switch the Action for a control on the fly. However, it is possible for them to do so, using setAction since it replaces the previously set action and fires a PropertyChangeEvent.
  • This does not replace the standard method of adding ActionListeners, note that it uses addActionListener() as stated above
  • The current Container apis listed above will be reimplemented in terms of setAction, so that they give the same behavior as they did previously. This solution will make that code much easier to maintain!
  • The methods configurePropertiesFromAction and createActionPropertyChangeListener will be overridden in subclasses to provide the expected default behavior.

createAction Factory Methods for JToolBar, JPopupMenu, JMenu

New factory methods allow one to control what toolbars and menus create when an action is added directly, i.e. with the add method.

Addition to JToolBar:

  • protected JButton createActionComponent(Action a)
Addition to JPopupMenu:
  • protected JMenuItem createActionComponent(Action a)
Addition to JMenu:
  • protected JMenuItem createActionComponent(Action a)

New Action Constants

See:
  • public static final String ACCELERATOR_KEY
  • public static final String MNEMONIC_KEY

Add AbstractAction getKeys Method

This new method is needed for serialization of Abstract Actions, and gives the developer a way to find out which keys have been set for the AbstractAction.

See:

  • public Object[] getKeys()

Copyright © 1999 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: swing-feedback@java.sun.com. This is not a subscription list. 		Sun
Java Software


Borders

 Other Swing Changes

New BorderFactory Methods

BorderFactory previously did not provide methods to create a raised etched border. It only provided a method to create a lowered border. To be consistent with the rest of the class the following methods have been added to BorderFactory:

See:

  • public static Border createEtchedBorder(int type)
  • public static Border createEtchedBorder(int type, Color highlight, Color shadow)

New LineBorder Constructor

LineBorder allows for rounded corners. Unfortunately this property previously could not be set in anyway, short of subclassing. To allow developers to create LineBorders with rounded corners, a new constructor has been added.

See:

  • public LineBorder(Color color, int thickness, boolean roundedCorners)

Move MetalUtils.TableHeaderBorder into MetalBorders

This border was inconsistently placed in the package private class plaf.metal.MetalUtils. Since it now needs to be public for access from the Proxy, it has been moved to javax.swing.plaf.metal.MetalBorders and made public:

See:

  • TableHeaderBorder

Copyright © 1999 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: swing-feedback@java.sun.com. This is not a subscription list. 		Sun
Java Software


I18N - New GlyphView.GlyphPainter Method getNextVisualPositionFrom

 Other Swing Changes

I18N - New GlyphView.GlyphPainter Method getNextVisualPositionFrom

Provides a way to determine the next visually represented model location that one might place a caret. Some views may not be visible, they might not be in the same order found in the model, or they just might not allow access to some of the locations in the model.

See:

  • public int getNextVisualPositionFrom( GlyphView v, int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet) throws BadLocationException

Copyright © 1999 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: swing-feedback@java.sun.com. This is not a subscription list. 		Sun
Java Software


Input Verification

 Other Swing Changes

New class InputVerifier

The purpose of this class is to help clients support smooth focus navigation through GUIs with text fields. Such GUIs often need to ensure that the text entered by the user is valid (for example, that it's in the proper format) before allowing the user to navigate out of the text field. To do this, clients create a subclass of InputVerifier and, using JComponent's setInputVerifier method, attach an instance of their subclass to the JComponent whose input they want to validate. Before focus is transfered to another Swing component that requests it, the input verifier's shouldYieldFocus method is called. Focus is transfered only if that method returns true.

Sometimes a component, such as a Cancel button or a scroll bar, should receive the focus even if input is invalid. To enable this, invoke setVerifyInputWhenFocusTarget(false) on the component.

The API change consists of a new abstract class, InputVerifier, and four new methods added to JComponent.

See:

  • javax.swing.InputVerifier

New methods in JComponent:

  • public void setInputVerifier(InputVerifier inputVerifier)
  • public InputVerifier getInputVerifier()
  • public void setVerifyInputWhenFocusTarget(boolean flag)
  • public boolean getVerifyInputWhenFocusTarget()

Copyright © 1999 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: swing-feedback@java.sun.com. This is not a subscription list. 		Sun
Java Software


JFileChooser

 Other Swing Changes

New JFileChooser isAcceptAllFileFilterUsed Property

This property allows control of the AcceptAll (*.*) file filter, which is added to the choosable file filters combo box by default.

See:

  • public static final String ACCEPT_ALL_FILE_FILTER_USED_CHANGED_PROPERTY
  • public void setAcceptAllFileFilterUsed(boolean b)
  • public boolean isAcceptAllFileFilterUsed()

Support for removing the OK and Cancel Buttons

The normal way to bring a JFileChooser is with the dialog creation utilities. However, since a JFileChooser is a JComponent, it can just as easily be embedded in a container. When this is done, it will oftentimes be the case that the developer will want control of any control buttons (ok, cancel, other) and not want the default Accept and Cancel buttons to appear. The following property will allow the developer to specify if the control buttons should be shown or not by the file chooser.

See:

  • public boolean getControlButtonsAreShown()
  • public void setControlButtonsAreShown(boolean b)

Copyright © 1999 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: swing-feedback@java.sun.com. This is not a subscription list. 		Sun
Java Software


JFrame

 Other Swing Changes

Add EXIT_ON_CLOSE defaultCloseOperation Constant

JFrame provides the setDefaultCloseOperation method which can be used to configure the default action when a JFrame is closed. For single framed applications it often the case that closing the frame will exit the application. Previously, developers had to add a WindowListener and do this themselves. To make this common case easier for developers to accomplish, a constant has been added to JFrame that specifies when the frame closes the application should exit: See:
  • public static final int EXIT_ON_CLOSE

Copyright © 1999 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: swing-feedback@java.sun.com. This is not a subscription list. 		Sun
Java Software


JButton, JCheckBox, JRadioButton

Other Swing Changes

New JCheckBox borderPaintedFlat Property

JCheckBox is often used as a cell renderer in tables and lists. The specifications for the Java Look and Feel (codenamed Metal) and the Windows Look and Feel specify that the check box be rendered with a 2D flat border rather than a 3D border when used as a cell renderer. The borderPaintedFlat property has been added to enable this behavior.

See:

  • public static final String BORDER_PAINTED_FLAT_CHANGED_PROPERTY
  • public void setBorderPaintedFlat(boolean b)
  • public boolean isBorderPaintedFlat()

Add DefaultButtonModel getGroup Method

This was an oversite of the original implementation. Unfortunately, since ButtonModel is an interface, this property cannot be added to it. It has instead been added to DefaultButtonModel, which should help most developers who want this.

See:

  • public ButtonGroup getGroup()

Copyright © 1999 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: swing-feedback@java.sun.com. This is not a subscription list. 		Sun
Java Software


Menus

Java

JMenu, JMenuBar and related classes

 Other Swing Changes

JMenu getPopupMenuOrigin method now protected

  • protected Point getPopupMenuOrigin()

BasicMenuItemUI installComponents, uninstallComponents methods now protected

  • protected void installComponents(JMenuItem menuItem)
  • protected void uninstallComponents(JMenuItem menuItem)

Added isPopupTrigger Method to JPopupMenu

  • public boolean isPopupTrigger(MouseEvent e)

And similarly to javax.swing.plaf.PopupMenuUI:

  • public boolean isPopupTrigger(MouseEvent e)

Copyright © 1999 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: swing-feedback@java.sun.com. This is not a subscription list. 		Sun
Java Software


JSplitPane

 Other Swing Changes

New JSplitPane resizeWeight Property

When the size of a JSplitPane changes, the extra space is added to the right/bottom component. This gives the effect of the left/top component being fixed.

The methods get/setResizeWeight(double) have been added. The resizeWeight property indicates how to distribute extra space. The left/top component will get resizeWeight * delta extra space, with the right/bottom component getting (1 - resizeWeight) * delta extra space.

See:

  • public final static String RESIZE_WEIGHT_PROPERTY
  • public void setResizeWeight(double value)
  • public double getResizeWeight()

JSplitPane dividerLocation Property Now Bound

The dividerLocation property is bound in JSplitPane.

See:

  • public static final String DIVIDER_LOCATION_PROPERTY

BasicSplitPaneDivider Border

JSplitPane has a unique border. That is, the border is drawn around both the components, and then drawn around the divider. Previously, one Border was responsible for all this. The problem with this approach is that there is no way to specify the border size drawn around the divider. It also made laying the components out rather tricky.

There is now a Border on the Divider (BasicSplitPaneDivider). As a result, setDividerSize now needs to take into account the border size, which is usually an extra 2 pixels, that is developers used to do setDividerSize(5), but now it will need to be setDividerSize(7) (unless a developer installs a new UI with a different border size).

The javadoc for JSplitPane also mentioned if the size of one the components was changed, an attempt would be made to position the divider correctly. This lead to all sorts of problems, and is no longer supported. Instead, setDividerLocation should be used.

See:

In BasicSplitPaneUI

  • protected int getDividerBorderSize() //deprecated

In BasicSplitPaneDivider

  • public void setBorder(Border border)
  • public Border getBorder()

Copyright © 1999 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: swing-feedback@java.sun.com. This is not a subscription list. 		Sun
Java Software


JTabbedPane

 Other Swing Changes

Added JTabbedPane toolTipTextAt Indexed Property

This property makes it possible to associate a tooltip with a tab, after the tab has been added.

See:

  • public void setToolTipTextAt(int index, String toolTipText)
  • public String getToolTipTextAt(int index)

Copyright © 1999 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: swing-feedback@java.sun.com. This is not a subscription list. 		Sun
Java Software


JTable

 Other Swing Changes
As a result of JTable changes, code written for v 1.2 or for JFC/Swing 1.1 might have the following problems when run in v 1.3:
  • Since the TableColumn getHeaderRenderer method now returns null by default, you can't use that method to get the default header renderer. Instead, change your code to use the JTableHeader getDefaultRenderer method. See How to Use Tables in The Java Tutorial for an example.
  • Because JTable's default text editor is now smarter about data types, it now gives setValueAt objects of the appropriate type, instead of always specifying strings. For example, if setValueAt is invoked for an Integer cell, then the value is specified as an Integer instead of a String. If you implemented a table model, then you might have to change its setValueAt method to take the new data type into account. If you implemented a class used as a data type for cells, make sure that your class has a constructor that takes a single String argument.

Column and Row Layout Improvements

We made the following changes:

  • Improved performance in tables with large numbers of columns
    Moving the header renderers from the columns themselves to the table header represents the most significant change to performance and footprint by sharing similar header renderers on a per-table basis.
  • Dynamic changing of individual row height
    The rendering machinery in the JTable has been substantially overhauled in this release to enable this much sought after feature in the JTable.
  • Simplified creation of non-standard editor components
    The AbstractCellEditor class has been included in response to continued feedback on the difficulty of creating non-standard editor components.
  • Better handling of inter-cell spacing
    Previously JTable did not correctly implement its specification for inter-cell spacing. Changes in the inter-cell spacing affected a number of other properties including the overall height of the table. In v 1.3, the inter-cell spacing has only one effect: to provide an inset for the cells, where the inset is the amount that renderers and editors are shrunk to accommodate the spacing between the cells.

For more information, see the API documentation for the following methods and fields. Note that "obsolete" means that you should avoid using the obsolete API, but that using the API isn't dangerous enough to warrant a compile-time warning. "Deprecated" API, on the other hand, is not only obsolete but also results in a compile-time warning.

In JTable

  • public void removeNotify()
  • protected void unconfigureEnclosingScrollPane()
  • public void changeSelection(int rowIndex, int columnIndex, boolean toggle, boolean extend)
  • protected boolean cellSelectionEnabled // obsolete
  • public void setRowHeight(int row, int height)
  • public int getRowHeight(int row)

In JTableHeader

  • protected boolean updateTableInRealTime // obsolete
  • public boolean getUpdateTableInRealTime() // obsolete
  • public void setUpdateTableInRealTime(boolean flag) // obsolete
  • public void setDefaultRenderer(TableCellRenderer defaultRenderer)
  • public TableCellRenderer getDefaultRenderer()
  • protected TableCellRenderer createDefaultRenderer()

In TableColumn

  • public final static String COLUMN_WIDTH_PROPERTY; // obsolete
  • public final static String HEADER_VALUE_PROPERTY; // obsolete
  • public final static String HEADER_RENDERER_PROPERTY // obsolete
  • public final static String CELL_RENDERER_PROPERTY // obsolete
  • protected TableCellRenderer createDefaultHeaderRenderer()
  • transient protected int resizedPostingDisableCount // deprecated
  • public void disableResizedPosting() // deprecated
  • public void enableResizedPosting() //deprecated

New Class: javax.swing.AbstractCellEditor

Existing Class DefaultCellEditor now extends AbstractCellEditor

New SizeSequence Utility Class

Before this release the height of rows in a JTable was always fixed. Introducing variable height rows whilst retaining the scalability requirements of the JTable (no O(N) behavior on rows) has required this new class and we have made it public as we think it may be generally useful. Indeed, table columns and the variable height rows of a JList might both use this class in the future to improve performance.

See: javax.swing.SizeSequence

Copyright © 1995-98 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: swing-feedback@java.sun.com. This is not a subscription list. 		Sun
Java Software


JToolBar

 Other Swing Changes

Support for Specifying the Title of an Undocked ToolBar

See:

  • public JToolBar(String name)
  • public JToolBar(String name , int orientation)

Copyright © 1999 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: swing-feedback@java.sun.com. This is not a subscription list. 		Sun
Java Software


JTree

 Other Swing Changes

New JTree toggleClickCount Property

JTree now provides a property for configuring how many mouse clicks are needed to expand/collapse a node. See:

  • public final static String TOGGLE_CLICK_COUNT_PROPERTY
  • protected int toggleClickCount
  • public void setToggleClickCount(int clickCount)
  • public int getToggleClickCount()

New JTree Properties: Anchor, LeadSelectionPath

The TreeSelectionModel maintains a set of selected paths. Most UIs also provide the notion of the lead path and the anchor path. The anchor path is used for gestures that extend the selection, and the lead is usually the path that was last added to the selection. The lead may also be manipulated independently such that it isn't always selected. Motif does this, as do the control modifiers with the Java Look and Feel (aka Metal). Support for this was previously added in a private manner such that developers were not able to determine what the anchor/lead were. The new API will expose this to developers so that they can get the lead/anchor as well as programmatically modify it. Exposing methods will also make it so that developers are free to override the behavior in any way they see fit.

See:

  • public final static String LEAD_SELECTION_PATH_PROPERTY
  • public final static String ANCHOR_SELECTION_PATH_PROPERTY
  • public void setLeadSelectionPath(TreePath newPath)
  • public void setAnchorSelectionPath(TreePath newPath)
  • public TreePath getLeadSelectionPath()
  • public TreePath getAnchorSelectionPath()

Exposed DefaultTreeCellRenderer.hasFocus as a Protected Field

DefaultTreeCellRenderer exposes almost all of the arguments passed in via the getTreeCellRendererComponent method as protected instance variables. This makes it easy for a subclass that wishes to only change painting, as the subclass only has to override paint, and not getTreeCellRendererComponent to track all the arguments themselves. The hasFocus argument (last argument) was private. The hasFocus instance variable is now protected vs private.

In javax.swing.tree.DefaultTreeCellRenderer see:

  • protected boolean hasFocus

Added TreeSelectionEvent.isAddedPath()

TreeSelectionEvent encapsulates the delta of how the TreeSelectionModel changed. That is, it will contain any paths that have been added to the selection, as well as paths that have been removed. To determine if a particular path is new to the selection model the isAddedPath(TreePath) method is provided. The valueChanged(TreeSelectionEvent) listener method usually takes the form of:

TreePath[] paths = event.getPaths();
for (int counter = paths.length - 1; counter >= 0; counter--) {
    if (event.isAddedPath(paths[counter])) ...
}

TreeSelectionEvent.isAddedPath(TreePath) has to iterate through the TreePaths to determine the index of the TreePath in its internal TreePath array, and then map that to a boolean to determine if it is a new path. To avoid the step of isAddedPath(TreePath) iterating through its TreePath array, isAddedPath(int) has been added.

In javax.swing.event.TreeSelectionEvent see:

  • public boolean isAddedPath(int index)

New JTree expandsSelectedPaths Property and removeDescendantSelectedPaths Method

When the selection is programatically changed in a JTree, the selected items are made visible (visible meaning all the parent items are expanded). For certain applications this behavior is not desirable, eg say all nodes of a certain type should be selected regardless of their visibility. This behavior is implemented across JTree and BasicTreeUI, making it tricky to override this behavior. The public methods get/setExpandsSelectedPaths have been added to JTree. If set to false, when the selection changes the nodes are not made visible, the default is true.

The protected method removeDescendantSelectedPaths has also been added. This method is called whenever a node is removed/collapsed to remove any descendant selected paths. This provides a simple place for subclassers to override should they not want the selection to change when a node is removed/collapsed.

See:

  • public final static String EXPANDS_SELECTED_PATHS_PROPERTY
  • public void setExpandsSelectedPaths(boolean newValue)
  • public boolean getExpandsSelectedPaths()
  • protected void removeDescendantSelectedPaths(TreePath path, boolean includePath)

DefaultTreeSelectionModel.insureUniqueness now Obsolete

DefaultTreeSelectionModel has the protected method insureUniqueness. It would go through an array of TreePaths making sure there were no duplicates. The implementation has changed such that a Hashtable is used and this method is no longer needed, it has marked obsolete. The implementation is now empty, but still invoked as before.

Here's the API and spec for the changes to javax.swing.tree.DefaultTreeSelectionModel

    /**
     * This method is obsolete and its implementation is now a noop. It's
     * still called by setSelectionPaths and addSelectionPaths, but only
     * for backwards compatibility.
     */
    protected void insureUniqueness()

Copyright © 1995-98 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: swing-feedback@java.sun.com. This is not a subscription list. 		Sun
Java Software


Keyboard Binding

 Other Swing Changes

New Keyboard Binding Infrastructure

The new keyboard binding infrastructure unifies and replaces the two previously existing schemes for binding user input (for example, Control-S) to program actions (for example, saving a file). The Swing Connection article Keyboard Bindings in Swing has details about the old and new keyboard binding schemes, including example code.

The API changes for the new infrastructure center around two new classes -- ActionMap and InputMap. Other changes include new methods in JComponent, LookAndFeel, and SwingUtilities, as well as a few new special-purpose classes that descend from ActionMap and InputMap.

See:

  • javax.swing.ActionMap
  • javax.swing.InputMap
  • javax.swing.ComponentInputMap
  • javax.swing.plaf.ActionMapUIResource
  • javax.swing.plaf.InputMapUIResource
  • javax.swing.plaf.ComponentInputMapUIResource

New methods in JComponent:

  • public ActionMap getActionMap()
  • public InputMap getInputMap()
  • public InputMap getInputMap(int condition)
  • public void setActionMap(ActionMap map)
  • public void setInputMap(int condition, InputMap map)

New methods in LookAndFeel:

  • public static void loadKeyBindings(InputMap retMap, Object[] keys)
  • public static ComponentInputMap makeComponentInputMap(JComponent c, Object[] keys)
  • public static InputMap makeInputMap(Object[] keys)

New methods in SwingUtilities:

  • public static InputMap getUIInputMap(JComponent component, int condition)
  • public static void replaceUIInputMap(JComponent component, int condition, InputMap map)
  • public static ActionMap getUIActionMap(JComponent component)
  • public static void replaceUIActionMap(JComponent component, ActionMap map)

Copyright © 2000 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: swing-feedback@java.sun.com. This is not a subscription list. 		Sun
Java Software


Listener Lists

 Other Swing Changes

Expose Listener Lists: Add getListeners Method

A getListeners() method has been added to the following classes.

  • javax.swing.Timer
  • javax.swing.AbstractListModel
  • javax.swing.DefaultBoundedRangeModel
  • javax.swing.DefaultButtonModel
  • javax.swing.DefaultListSelectionModel
  • javax.swing.DefaultSingleSelectionModel DefaultSingleSelectionModel
  • javax.swing.table.AbstractTableModel
  • javax.swing.table.DefaultTableColumnModel
  • javax.swing.tree.DefaultTreeModel
  • javax.swing.tree.DefaultTreeSelectionModel
  • javax.swing.text.AbstractDocument
  • javax.swing.text.DefaultCaret
  • javax.swing.event.EventListenerList

Copyright © 1999 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: swing-feedback@java.sun.com. This is not a subscription list. 		Sun
Java Software


Internal Frames

Java

Internal Frames:
JInternalFrame, JDesktopPane, and Related Classes

 Other Swing Changes

Internal Frames Invisible By Default

In v 1.2 internal frames were visible by default; now they start out invisible. To make a JInternalFrame appear onscreen, use this code:
      anInternalFrame.setVisible(true);

Why the change? The rule for default visibility in Swing is that only top-level components, such as JFrame and JDialog, have default visibility false; the remaining components have default visibility true. This is so that once a JFrame is constructed, one call to setVisible(true) on the JFrame will show it and all of its contents.

Although JInternalFrame is not really a top-level component, it needs to behave like a JFrame in many ways. In particular, it needs to fire JInternalFrame events corresponding to Window events on JFrames. One such event, INTERNAL_FRAME_OPENED, is fired in response to the initial visibility change from false to true; with no such change prior to version 1.3, the event wasn't being fired.

To fix this bug, and to make JInternalFrame more compatible with its heavyweight cousin JFrame, the default visibility of JInternalFrame changed to false beginning with version 1.3 of the Java 2 Platform. Therefore, to show an internal frame, just call setVisible(true) after adding the frame to its parent.

Added JInternalFrame setLayer(int layer) Method

JInternalFrame's setLayer() method takes an int, so that the beans introspector recognizes this as a property.

See:

  • public void setLayer(int layer)

Added protected BasicInternalFrameUI.uninstallListeners() Method

Previously BasicInternalFrameTitlePane did not remove its listeners when no longer needed (thus becoming a memory leak). This behavior is now provided.

See:

  • protected void uninstallListeners()
  • protected void installListeners()

JInternalFrame "closed" Property

  1. The default setting for defaultCloseOperation has been changed from HIDE_ON_CLOSE to DISPOSE_ON_CLOSE. This change is provided so that clients who want to use only the vetoable property mechanism (which is the simplest, and which we encourage) can just do so, without having to set defaultCloseOperation.
  2. JInternalFrame's doDefaultCloseAction method has been changed from private to public. This is because the UI has to be able to invoke it. In the past, the UI just invoked JInternalFrame's public setClosed method, which called doDefaultCloseAction. But setClosed is used for programmatically closing frames, and thus should not call doDefaultCloseAction, because defaultCloseOperation is defined only for user-initiated close operations.

See:

  • public void doDefaultCloseAction()

JInternalFrame Normal Bounds

Getting the normal dimensions of an internal frame is now possible through a new method to JInternalFrame: getNormalBounds()

See:

  • public Rectangle getNormalBounds()
  • public void setNormalBounds(Rectangle r)

Added getFocusOwner Method to JInternalFrame

New method for JInternalFrame:
  • public Component getFocusOwner()

Added getInternalFrame method to InternalFrameEvent

New method to InternalFrameEvent:
  • public JInternalFrame getInternalFrame()

MetalInternalFrameTitlePane Class is now public

See:

  • MetalInternalFrameTitlePane

Added restoreSubcomponentFocus Method to JInternalFrame

New method to JInternalFrame:
  • public void restoreSubcomponentFocus()

Added setDragMode Method to JDesktopPane

New method to JDesktopPane:
  • public void setDragMode(int dragMode)

Copyright © 1999 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: swing-feedback@java.sun.com. This is not a subscription list. 		Sun
Java Software


Performance

 Other Swing Changes

New Class: UIDefaults.UIDefaultProxy, Related Performance Changes

One of the main reasons that Swing's startup performance was slower than desired was that as soon as any component requires a UI delegate, the UIManager loads a look and feel, which results in loading a defaults table which includes defaults for UIs for all component classes.

In previous releases, we mistakenly believed that instance creation should be avoided, and so we delayed instance creation by creating anonymous implementations of LazyValue, an interface which acts as a lightweight proxy that only creates its instance the first time it is retrieved from the defaults table.

Performance analysis for Kestrel indicates that we were wrong in believing that instance creation was the determining factor. In fact, the overwhelming factor contributing to delay and increased footprint in this area was classloading, which was ironically not helped by our creation of lots of anonymous interface implementations!

The general approach taken to fix this was to define a concrete LazyValue implementation in UIDefaults.java which uses reflection to create its proxied instance when asked to do so. This class is called UIDefaultProxy. As a result only one class is loaded, and about 90 other classloads could be avoided in a Hello World example.

See: UIDefaults.UIDefaultProxy

In the course of replacing the existing anonymous LazyValue implementations and identifying other classloads that could be avoided, we came across several classes and accessor methods which were incorrectly package private. Since the UIDefaultProxy is in the javax.swing package, and most of the uses are in javax.swing.plaf.* packages, these signatures needed to be changed so that they could be used by the proxy.

The following is a list of these:

javax.swing.plaf.basic.BasicBorders

  • public static Border getSplitPaneDividerBorder()
javax.swing.plaf.metal.MetalBorders
  • public static class PaletteBorder
  • public static Border getButtonBorder()
  • public static Border getTextBorder()
  • public static Border getTextFieldBorder()
  • static class ToggleButtonBorder extends ButtonBorder
  • public static Border getToggleButtonBorder()
  • public static Border getDesktopIconBorder()
javax.swing.plaf.metal.MetalIconFactory
  • public static Icon getCheckBoxIcon()
  • public static class PaletteCloseIcon implements Icon, UIResource, Serializable

Copyright © 1999 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: swing-feedback@java.sun.com. This is not a subscription list. 		Sun
Java Software


Printing

 Other Swing Changes

New JComponent methods: printBorder, printComponent, printChildren

JComponent previously did not override print. This meant that printing was no different than painting, resulting in the double buffer being used. This is not the desired behavior. It also makes it harder for developers to add customized printing logic. In most cases the developer would resort to completely replacing print, rewriting all the code to notify the children. This is not desirable. To be consistant with the painting methods, methods printBorder, printChildren and printComponent have been added, all of which are protected.

See:

  • protected void printComponent(Graphics g)
  • protected void printChildren(Graphics g)
  • protected void printBorder(Graphics g)

Copyright © 1999 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: swing-feedback@java.sun.com. This is not a subscription list. 		Sun
Java Software


Scrolling

Java

Scrolling: JViewport, JScrollPane, and Related Classes

 Other Swing Changes

New JViewport scrollMode Property

Interactive scrolling speed has proven to be perhaps the most important factor in users perception of overall swing performance. 1.3 adds a new optimization, called "BLIT_SCROLL_MODE" (now the default) that copies unobscured areas of the components heavy weight ancestor to effect a scroll. Previously we had offered a related optimzation that managed a per viewport backing store image. Although still supported, the backingStoreEnabled property has been deprecated.

See:

  • public static final int BLIT_SCROLL_MODE
  • public static final int BACKINGSTORE_SCROLL_MODE
  • public static final int SIMPLE_SCROLL_MODE
  • public void setScrollMode(int mode)
  • public int getScrollMode()
  • protected boolean backingStore // Deprecated
  • public boolean isBackingStoreEnabled() // Deprecated
  • public void setBackingStoreEnabled(boolean enabled) // Deprecated

Copyright © 1999 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: swing-feedback@java.sun.com. This is not a subscription list. 		Sun
Java Software


Swing Changes and New Features

Java

Swing Changes and New Features for JavaTM 2 SDK, Standard Edition, v 1.3

 Project Swing
  • JTree
  • JTable
  • JSplitPane
  • JFileChooser
  • JButton, JCheckBox, JRadioButton
  • Internal Frames: JInternalFrame, JDesktopPane, and related classes
  • JTabbedPane
  • Text
  • Scrolling: JViewport, JScrollPane, and related classes
  • Printing
  • Input Verification
  • Keyboard Binding
  • I18N- New GlyphView.GlyphPainter Method getNextVisualPositionFrom
  • Borders
  • Actions
  • JToolBar
  • Menus: JMenu, JMenuBar, and related classes
  • JFrame
  • Listener Lists
  • Performance

Copyright © 1999 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: swing-feedback@java.sun.com. This is not a subscription list. 		Sun
Java Software


Text

 Other Swing Changes

Default HTML Font Is Now Serif

HTML text -- including HTML text used in labels, buttons, and so on -- used to be in SansSerif font by default. As of v 1.3, the default font is Serif.

HTMLEditorKit insertAtBoundry => insertAtBoundary

A method in HTMLEditorKit.InsertHTMLTextAction, insertAtBoundry, was misspelled. It's been deprecated and insertAtBoundary has been added.

Automatic Handling of DocumentEvents

The default functionality of managing the DocumentEvent has been moved (from CompositeView) and raised from package private to public. Subclassing has been made much easier as the management of the DocumentEvent is now distributed to the protected methods:

  • updateChildren
  • forwardUpdate
  • forwardUpdateToView
  • updateLayout

To accomplish its behavior, the methods managing the children of the view also needed to be moved from CompositeView to View.

  • removeAll
  • remove
  • append
  • replace

The following methods were added to the javax.swing.text.View:

  • protected boolean updateChildren(DocumentEvent.ElementChange ec, DocumentEvent e, ViewFactory f)
  • protected void forwardUpdate(DocumentEvent.ElementChange ec, DocumentEvent e, Shape a, ViewFactory f)
  • protected void forwardUpdateToView(View v, DocumentEvent e, Shape a, ViewFactory f)
  • protected void updateLayout(DocumentEvent.ElementChange ec, DocumentEvent e, Shape a)
  • public void removeAll()
  • public void remove(int i)
  • public void insert(int offs, View v)
  • public void append(View v)
  • public void replace(int offset, int length, View[] views)

BoxView: Add axis property, layoutChanged Method

BoxView has an axis argument which subclasses previously could not get at. A subclass that sets it's axis based upon i18n considerations needs this as a property. The layout of the box should also be treated seperate from the requested size as in some cases (such as a table) the layout may become invalid independant of the children's preferences.

The following methods have been added to javax.swing.text.BoxView:

  • public int getAxis()
  • public void setAxis(int axis)
  • public void layoutChanged(int axis)

ParagraphView now extends FlowView

The View protocol supports building flows, but the only previous implementation had been ParagraphView which creates relatively simple paragraph flows. The functionality can be generalized substantially to do things like shaped flows, page breaking, etc. Generalizing the functionality will make the creation of alternative flows much easier.

A new class called FlowView takes a strategy to translate the logical structure to a physical structure. The strategy is defined by a nested static class called FlowStrategy. ParagraphView extends FlowView adding just that behavior which is paragraph-specific (i.e line spacing, first line indent, alignment, etc). This change adds the following method to the javax.swing.text.View class:

  • public int getViewIndex(int pos, Position.Bias b)

FormView Localization; SUBMIT, RESET deprecated

Class javax.swing.text.html.FormView was not previously localizable. There are two public static final Strings, SUBMIT and RESET, that are used to determine the text for <form> elements in an HTML document. As they are public static final they can not be localized. SUBMIT and RESET have been deprecated, the values are now obtained from the UIManager properties: FormView.submitButtonText and FormView.resetButtonText.

Serialization

Here's a summary of the serialization related changes in the swing.text package:
  • javax.swing.text.html.parser.ParserDelegator now implements Serializable.
  • Added a nullary constructor to the public static innner class HTML.Tag to allow serialization of subclasses to work.

HTML Package: Expose More of AbstractWriter

AbstractWriter is used as a base class for developers wishing to provide custom writing out of a text Document. For example, HTMLWriter extends AbstractWriter, and is used in the html package to output html. The problem with AbstractWriter was that most of the methods and ivars it provided were private. Subclasses had to resort to copying numerous methods and ivars to be useful. HTMLWriter extends AbstractWriter, but ended up copying all the ivars, and overriding almost all the methods. The following changes open up the API in AbstractWriter, making it more useful by itself. This makes HTMLWriter much simpler, and it won't have to copy as much from AbstractWriter.

See:

  • public int getStartOffset()
  • public int getEndOffset()
  • protected Writer getWriter()
  • protected int getLineLength()
  • protected void setCurrentLineLength(int length)
  • protected int getCurrentLineLength()
  • protected boolean isLineEmpty()
  • protected void setCanWrapLines(boolean newValue)
  • protected boolean getCanWrapLines()
  • public void setLineSeparator(String value)
  • public String getLineSeparator()
  • protected int getIndentLevel()
  • protected void writeLineSeparator() throws IOException
  • protected void write(char[] chars, int startIndex, int length) throws IOException
  • protected void output(char[] content, int start, int length) throws IOException

HTML Package: Expose More CSS1 Support

The html package supports CSS 1. One of the abilities of CSS is to support cascading of style sheets (as the name implies), that is more than one style sheet can influence the presentation simultaneously. For example a browser usually has a style sheet that defines the default styles, a particular page might also have a style sheet that overrides those provided by the browser. The following methods expose this to developers, allowing them to link style sheets:

  • public synchronized void addStyleSheet(StyleSheet ss)
  • public synchronized void removeStyleSheet(StyleSheet ss)
  • public StyleSheet[] getStyleSheets()

Simplify HTML Insertions

Previously it was not very easy for developers to insert arbitrary html into an existing html document. To accomplish this, the developer needed to have an intimate knowledge of the swing text package, as well as the html package. Many developers have used dynamic html, which provides a handful of methods that make it trivial to insert html into an existing page. To accomodate these users we now expose methods that closely mirror those provided by dynamic html:
  • public void setInnerHTML(Element elem, String htmlText) throws BadLocationException, IOException
  • public void setOuterHTML(Element elem, String htmlText) throws BadLocationException, IOException
  • public void insertAfterStart(Element elem, String htmlText) throws BadLocationException, IOException
  • public void insertBeforeEnd(Element elem, String htmlText) throws BadLocationException, IOException
  • public void insertBeforeStart(Element elem, String htmlText) throws BadLocationException, IOException
  • public void insertAfterEnd(Element elem, String htmlText) throws BadLocationException, IOException
  • public Element getElement(String id)
  • public Element getElement(Element e, Object attribute, Object value)

And this is constant has been added to class HTMLEditorKit.ParserCallback:

  • public static final Object IMPLIED

New text Package ZoneView class

Problem:
The swing text package uses View objects to represent a presentation of the document model for the sake of layout and rendering. If the model is large, the number of view objects that get created is large, in spite of only being able to view a small number of them. A View implementation is needed that defers creation of the objects until they are actually needed for display. This can be done by building zones with an estimated size that get replaced with the actual View objects when they are needed. This can substantially reduce the amount of memory used for large documents.

Solution:
The following class called ZoneView supports zones that don't consume much memory until actively viewed or edited. WrappedPlainView which will become more heavyweight with its support of bidi for i18n will benefit substantially from this class by changing it's superclass from BoxView to ZoneView (which is a BoxView).

See:

  • javax.swing.text.ZoneView

New text Package AsyncBoxView class

Problem:
The swing text package uses View objects to represent a view of the document model to handle layout and rendering. Layout is done on the event handling thread like most other things. Layout is sometimes quite expensive in terms of cpu time, and causes the user interface to freeze while performing layout. The text package has some support of concurrency however, so this should be extended to include performing layout asynchronous to the gui event handling thread. A View implementation is needed that performs layout asynchronously.

Solution:
To address this need, the following classes are being added to the text package. For more information visit The Swing Connection.

  • javax.swing.text.AsyncBoxView
  • javax.swing.text.LayoutQueue

Add getGraphics Method to text View Class

A method is included on the javax.swing.text.View class to fetch the Graphics object that will be used to render.

See:

  • public Graphics getGraphics()

Copyright © 1999 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: swing-feedback@java.sun.com. This is not a subscription list. 		Sun
Java Software


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 |
JFormattedTextField | X | X
JLabel | see here | see here
JList | X |
JPasswordField |  | X
JTable | X |
JTextArea | X | X
JTextField | X | X
JTextPane | X | X
JTree | 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 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.


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.insertString(fb, offset, 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.


Windows Look and Feel Keyboard Navigation Hiding

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()


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:


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);


Swing Changes Since Java 2 SDK, v1.4

Java

Swing Changes Since JavaTM 2 SDK, Standard Edition, v 1.4

 Project Swing

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 1.5 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 © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: swing-feedback@java.sun.com. This is not a subscription list. 		Sun
Java Software


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:> </td> <td align=center><img src= | 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


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.


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.


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);


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.


Java TM Logging APIs

Java

JavaTM Logging APIs

 Documentation Contents
The JavaTM Logging APIs, introduced in package java.util.logging, facilitate software servicing and maintenance at customer sites by producing log reports suitable for analysis by end users, system administrators, field service engineers, and software development teams. The Logging APIs capture information such as security failures, configuration errors, performance bottlenecks, and/or bugs in the application or platform. The core package includes support for delivering plain text or XML-formatted log records to memory, output streams, consoles, files, and sockets. In addition, the logging APIs are capable of interacting with logging services that already exist on the host operating system.
Documentation
  • Logging Overview
  • API Specification: java.util.logging

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: j2se-comments@java.sun.com 		Sun
Java Software


Java TM Logging Overview

Java

JavaTM Logging Overview

Last update Nov 26 2001
Documentation Contents

1.0 Java Logging Overview
1.1 Overview of Control Flow
1.2 Log Levels
1.3 Loggers
1.4 Logging Methods
1.5 Handlers
1.6 Formatters
1.7 The LogManager
1.8 Configuration File
1.9 Default Configuration
1.10 Dynamic Configuration Updates
1.11 Native Methods
1.12 XML DTD
1.13 Unique Message IDs
1.14 Security
1.15 Configuration Management
1.16 Packaging
1.17 Localization
1.18 Remote Access and Serialization
2.0 Examples
2.1 Simple Use
2.2 Changing the Configuration
2.3 Simple Use, Ignoring Global Configuration
2.4 Sample XML Output
3.0 Appendix A: DTD for XMLFormatter Output

1.0 JavaTM Logging Overview

The logging APIs are described in detail in the J2SE API Specification. The goal of this document is to provide an overview of key elements.

1.1 Overview of Control Flow

Applications make logging calls on Logger objects. Loggers are organized in a hierarchical namespace and child Loggers may inherit some logging properties from their parents in the namespace.

Applications make logging calls on Logger objects. These Logger objects allocate LogRecord objects which are passed to Handler objects for publication. Both Loggers and Handlers may use logging Levels and (optionally) Filters to decide if they are interested in a particular LogRecord. When it is necessary to publish a LogRecord externally, a Handler can (optionally) use a Formatter to localize and format the message before publishing it to an I/O stream.

The previous context describes this graphic

Each Logger keeps track of a set of output Handlers. By default all Loggers also send their output to their parent Logger. But Loggers may also be configured to ignore Handlers higher up the tree.

Some Handlers may direct output to other Handlers. For example, the MemoryHandler maintains an internal ring buffer of LogRecords and on trigger events it publishes its LogRecords through a target Handler. In such cases, any formatting is done by the last Handler in the chain.

The previous context describes this graphic

The APIs are structured so that calls on the Logger APIs can be cheap when logging is disabled. If logging is disabled for a given log level, then the Logger can make a cheap comparison test and return. If logging is enabled for a given log level, the Logger is still careful to minimize costs before passing the LogRecord into the Handlers. In particular, localization and formatting (which are relatively expensive) are deferred until the Handler requests them. For example, a MemoryHandler can maintain a circular buffer of LogRecords without having to pay formatting costs.

1.2 Log Levels

Each log message has an associated log Level. The Level gives a rough guide to the importance and urgency of a log message. Log level objects encapsulate an integer value, with higher values indicating higher priorities.

The Level class defines seven standard log levels, ranging from FINEST (the lowest priority, with the lowest value) to SEVERE (the highest priority, with the highest value).

1.3 Loggers

As stated earlier, client code sends log requests to Logger objects. Each logger keeps track of a log level that it is interested in, and discards log requests that are below this level.

Loggers are normally named entities, using dot-separated names such as "java.awt". The namespace is hierarchical and is managed by the LogManager. The namespace should typically be aligned with the Java packaging namespace, but is not required to follow it slavishly. For example, a Logger called "java.awt" might handle logging requests for classes in the java.awt package, but it might also handle logging for classes in sun.awt that support the client-visible abstractions defined in the java.awt package.

In addition to named Loggers, it is also possible to create anonymous Loggers that don't appear in the shared namespace. See section 1.14.

Loggers keep track of their parent loggers in the logging namespace. A logger's parent is its nearest extant ancestor in the logging namespace. The root Logger (named "") has no parent. Anonymous loggers are all given the root logger as their parent. Loggers may inherit various attributes from their parents in the logger namespace. In particular, a logger may inherit:

  • Logging level. If a Logger's level is set to be null then the Logger will use an effective Level that will be obtained by walking up the parent tree and using the first non-null Level.
  • Handlers. By default a Logger will log any output messages to its parent's handlers, and so on recursively up the tree.
  • Resource bundle names. If a logger has a null resource bundle name, then it will inherit any resource bundle name defined for its parent, and so on recursively up the tree.

1.4 Logging Methods

The Logger class provides a large set of convenience methods for generating log messages. For convenience, there are methods for each logging level, named after the logging level name. Thus rather than calling "logger.log(Constants.WARNING,..." a developer can simply call the convenience method "logger.warning(..."

There are two different styles of logging methods, to meet the needs of different communities of users.

First, there are methods that take an explicit source class name and source method name. These methods are intended for developers who want to be able to quickly locate the source of any given logging message. An example of this style is:

void warning(String sourceClass, String sourceMethod, String msg);

Second, there are a set of methods that do not take explicit source class or source method names. These are intended for developers who want easy-to-use logging and do not require detailed source information.

void warning(String msg);

For this second set of methods, the Logging framework will make a "best effort" to determine which class and method called into the logging framework and will add this information into the LogRecord. However, it is important to realize that this automatically inferred information may only be approximate. The latest generation of virtual machines perform extensive optimizations when JITing and may entirely remove stack frames, making it impossible to reliably locate the calling class and method.

1.5 Handlers

J2SE provides the following Handlers:

  • StreamHandler: A simple handler for writing formatted records to an OutputStream.
  • ConsoleHandler: A simple handler for writing formatted records to System.err
  • FileHandler: A handler that writes formatted log records either to a single file, or to a set of rotating log files.
  • SocketHandler: A handler that writes formatted log records to remote TCP ports.
  • MemoryHandler: A handler that buffers log records in memory.

It is fairly straightforward to develop new Handlers. Developers requiring specific functionality can either develop a Handler from scratch or subclass one of the provided Handlers.

1.6 Formatters

J2SE also includes two standard Formatters:
  • SimpleFormatter: Writes brief "human-readable" summaries of log records.
  • XMLFormatter: Writes detailed XML-structured information.

As with Handlers, it is fairly straightforward to develop new Formatters.

1.7 The LogManager

There is a global LogManager object that keeps track of global logging information. This includes:
  • A hierarchical namespace of named Loggers.
  • A set of logging control properties read from the configuration file. See section 1.8.

There is a single LogManager object that can be retrieved using the static LogManager.getLogManager method. This is created during LogManager initialization, based on a system property. This property allows container applications (such as EJB containers) to substitute their own subclass of LogManager in place of the default class.

1.8 Configuration File

The logging configuration can be initialized using a logging configuration file that will be read at startup. This logging configuration file is in standard java.util.Properties format.

Alternatively, the logging configuration can be initialized by specifying a class that can be used for reading initialization properties. This mechanism allows configuration data to be read from arbitrary sources, such as LDAP. JDBC, etc. See the LogManager API Specification for details.

There is a small set of global configuration information. This is specified in the description of the LogManager class and includes a list of root-level Handlers to install during startup.

The initial configuration may specify levels for particular loggers. These levels are applied to the named logger and any loggers below it in the naming hierarchy. The levels are applied in the order they are defined in the configuration file.

The initial configuration may contain arbitrary properties for use by Handlers or by subsystems doing logging. By convention these properties should use names starting with the name of the handler class or the name of the main Logger for the subsystem.

For example, the MemoryHandler uses a property "java.util.logging.MemoryHandler.size" to determine the default size for its ring buffer.

1.9 Default Configuration

The default logging configuration that ships with the JRE is only a default, and can be overridden by ISVs, system admins, and end users.

The default configuration makes only limited use of disk space. It doesn't flood the user with information, but does make sure to always capture key failure information.

The default configuration establishes a single handler on the rootr logger for sending output to the console.

1.10 Dynamic Configuration Updates

Programmers can update the logging configuration at run time in a variety of ways:
  • FileHandlers,MemoryHandlers, and PrintHandlers can all be created with various attributes.
  • New Handlers can be added and old ones removed.
  • New Loggers can be created and can be supplied with specific Handlers.
  • Levels can be set on target Handlers.

1.11 Native Methods

There are no native APIs for logging.

Native code that wishes to use the Java Logging mechanisms should make normal JNI calls into the Java Logging APIs.

1.12 XML DTD

The XML DTD used by the XMLFormatter in specified in Appendix A.

The DTD is designed with a "<log>" element as the top-level document. Individual log records are then written as "<record>" elements.

Note that in the event of JVM crashes it may not be possible to cleanly terminate an XMLFormatter stream with the appropriate closing </log>. Therefore tools that are analyzing log records should be prepared to cope with un-terminated streams.

1.13 Unique Message IDs

The Java Logging APIs do not provide any direct support for unique message IDs. Those applications or subsystems requiring unique message IDs should define their own conventions and include the unique IDs in the message strings as appropriate.

1.14 Security

The principal security requirement is that untrusted code should not be able to change the logging configuration. Specifically, if the logging configuration has been set up to log a particular category of information to a particular Handler, then untrusted code should not be able to prevent or disrupt that logging.

A new security permission LoggingPermission is defined to control updates to the logging configuration.

Trusted applications are given the appropriate LoggingPermission so they can call any of the logging configuration APIs. Untrusted applets are a different story. Untrusted applets can create and use named Loggers in the normal way, but they are not allowed to change logging control settings, such as adding or removing handlers, or changing log levels. However, untrusted applets are able to create and use their own "anonymous" loggers, using Logger.getAnonymousLogger. These anonymous Loggers are not registered in the global namespace and their methods are not access-checked, allowing even untrusted code to change their logging control settings.

The logging framework does not attempt to prevent spoofing. The sources of logging calls cannot be determined reliably, so when a LogRecord is published that claims to be from a particular source class and source method, it may be a fabrication. Similarly, formatters such as the XMLFormatter do not attempt to protect themselves against nested log messages inside message strings. This, a spoof LogRecord might contain a spoof set of XML inside its message string to make it look as if there was an additional XML record in the output.

In addition, the logging framework does not attempt to protect itself against denial of service attacks. Any given logging client can flood the logging framework with meaningless messages in an attempt to conceal some important log message.

1.15 Configuration Management

The APIs are structured so that an initial set of configuration information is read as properties from a configuration file. The configuration information may then be changed programatically by calls on the various logging classes and objects.

In addition, there are methods on LogManager that allow the configuration file to be re-read. When this happens, the configuration file values will override any changes that have been made programatically.

1.16 Packaging

All of the logging class are in the java.* part of the namespace, in the java.util.logging package.

1.17 Localization

Log messages may need to be localized.

Each Logger may have a Resource Bundle name associated with it. The corresponding Resource Bundle can be used to map between raw message strings and localized message strings.

Normally localization will be performed by Formatters. As a convenience, the formatter class provides a formatMessage method that provides some basic localization and formatting support.

1.18 Remote Access and Serialization

As with most Java platform APIs, the logging APIs are designed for use inside a single address space. All calls are intended to be local. However, it is expected that some Handlers will want to forward their output to other systems. There are a variety of ways of doing this:

Some Handlers (such as the SocketHandler) may write data to other systems using the XMLFormatter. This provides a simple, standard, inter-change format that can be parsed and processed on a variety of systems.

Some Handlers may wish to pass LogRecord objects over RMI. The LogRecord class is therefore serializable. However there is a problem in how to deal with the LogRecord parameters. Some parameters may not be serializable and other parameters may have been designed to serialize much more state than is required for logging. To avoid these problems the LogRecord class has a custom writeObject method that converts the parameters to strings (using Object.toString()) before writing them out. See the LogRecord API Specification for details.

Most of the logging classes are not intended to be serializable. Both Loggers and Handlers are stateful classes that are tied into a specific virtual machine. In this respect they are analogous to the java.io classes, which are also not serializable.

2.0 Examples

2.1 Simple Use

The following is a small program that performs logging using the default configuration.

This program relies on the root handlers that were established by the LogManager based on the configuration file. It creates its own Logger object and then makes calls to that Logger object to report various events.

package com.wombat;

public class Nose{
    // Obtain a suitable logger.
    private static Logger logger = Logger.getLogger("com.wombat.nose");
    public static void main(String argv[]){
        // Log a FINE tracing message
        logger.fine("doing stuff");
        try{
            Wombat.sneeze();
        } catch (Error ex){
            // Log the error
            logger.log(Level.WARNING,"trouble sneezing",ex);
        }
        logger.fine("done");
    }
}

2.2 Changing the Configuration

Here's a small program that dynamically adjusts the logging configuration to send output to a specific file and to get lots of information on wombats:

public static void main(String[] args){
    Handler fh = new FileHandler("%t/wombat.log");
    Logger.getLogger("").addHandler(fh);
    Logger.getLogger("com.wombat").setLevel("com.wombat",Level.FINEST);
    ...
}

2.3 Simple Use, Ignoring Global Configuration

Here's a small program that sets up it own logging Handler and ignores the global configuration.

package com.wombat;

import java.util.logging.*;

public class Nose {
    private static Logger logger = Logger.getLogger("com.wombat.nose");
    private static FileHandler fh = new FileHandler("mylog.txt");
    public static void main(String argv[]) {
        // Send logger output to our FileHandler.
        logger.addHandler(fh);
        // Request that every detail gets logged.
        logger.setLevel(Level.ALL);
        // Log a simple INFO message.
        logger.info("doing stuff");
        try {
            Wombat.sneeze();
        } catch (Error ex) {
            logger.log(Level.WARNING, "trouble sneezing", ex);
        }
        logger.fine("done");
    }
}

2.4 Sample XML Output

Here's a small sample of what some XMLFormatter XML output looks like:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE log SYSTEM "logger.dtd">
<log>
<record>
  <date>2000-08-23 19:21:05</date>
  <millis>967083665789</millis>
  <sequence>1256</sequence>
  <logger>kgh.test.fred</logger>
  <level>INFO</level>
  <class>kgh.test.XMLTest</class>
  <method>writeLog</method>
  <thread>10</thread>
  <message>Hello world!</message>
</record>
</log>

3.0 Appendix A: DTD for XMLFormatter Output

<!-- DTD used by the java.util.logging.XMLFormatter -->
<!-- This provides an XML formatted log message. -->

<!-- The document type is "log" which consists of a sequence
of record elements -->
<!ELEMENT log (record*)>

<!-- Each logging call is described by a record element. -->
<!ELEMENT record (date, millis, sequence, logger?, level,
class?, method?, thread?, message, key?, catalog?, param*, exception?)>

<!-- Date and time when LogRecord was created in ISO 8601 format -->
<!ELEMENT date (#PCDATA)>

<!-- Time when LogRecord was created in milliseconds since
midnight January 1st, 1970, UTC. -->
<!ELEMENT millis (#PCDATA)>

<!-- Unique sequence number within source VM. -->
<!ELEMENT sequence (#PCDATA)>

<!-- Name of source Logger object. -->
<!ELEMENT logger (#PCDATA)>

<!-- Logging level, may be either one of the constant
names from java.util.logging.Constants (such as "SEVERE"
or "WARNING") or an integer value such as "20". -->
<!ELEMENT level (#PCDATA)>

<!-- Fully qualified name of class that issued
logging call, e.g. "javax.marsupial.Wombat". -->
<!ELEMENT class (#PCDATA)>

<!-- Name of method that issued logging call.
It may be either an unqualified method name such as
"fred" or it may include argument type information
in parenthesis, for example "fred(int,String)". -->
<!ELEMENT method (#PCDATA)>

<!-- Integer thread ID. -->
<!ELEMENT thread (#PCDATA)>

<!-- The message element contains the text string of a log message. -->
<!ELEMENT message (#PCDATA)>

<!-- If the message string was localized, the key element provides
the original localization message key. -->
<!ELEMENT key (#PCDATA)>

<!-- If the message string was localized, the catalog element provides
the logger's localization resource bundle name. -->
<!ELEMENT catalog (#PCDATA)>

<!-- If the message string was localized, each of the param elements
provides the String value (obtained using Object.toString())
of the corresponding LogRecord parameter. -->
<!ELEMENT param (#PCDATA)>

<!-- An exception consists of an optional message string followed
by a series of StackFrames. Exception elements are used
for Java exceptions and other java Throwables. -->
<!ELEMENT exception (message?, frame+)>

<!-- A frame describes one line in a Throwable backtrace. -->
<!ELEMENT frame (class, method, line?)>

<!-- an integer line number within a class's source file. -->
<!ELEMENT line (#PCDATA)>

Copyright ©2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: j2se-comments@java.sun.com 		Sun
Java Software


Package Version Identification

 Documentation Contents
The versioning feature enables package-level version control so that applications and applets can identify at runtime the version of a specific Java Runtime Environment, VM, and class package.
Package Versioning Specification
  • Versioning Specification (HTML, PDF)

Versioning API Reference
(javadoc)
  • java.lang.Class
  • java.lang.ClassLoader
  • java.lang.Package
  • java.lang.System

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: jre-comments@java.sun.com 		Sun
Java Software


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 JavaTM Product Versioning Specification

Copyright © 2003 Sun Microsystems, Inc. All rights reserved.


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, §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 JLS, 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 JavaTM Product Versioning Specification

Copyright © 2003 Sun Microsystems, Inc. All rights reserved.


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 © 2003 Sun Microsystems, Inc. All rights reserved.


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 SolarisTM 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 © 2002 Sun Microsystems, Inc. All Rights Reserved.

 Sun


Java(TM) Virtual Machines

Java

JavaTM Virtual Machines

 Documentation Contents
The Java 2 SDK, Standard Edition, contains two implementations of the Java virtual machine (VM).
Java HotSpot Client VM
The Java HotSpot Client VM is the default virtual machine of the Java 2 SDK and Java 2 Runtime Environment. As its name implies, it is tuned for best performance when running applications in a client environment by reducing application start-up time and memory footprint.

Java HotSpot Server VM
The Java HotSpot Server VM is designed for maximum program execution speed for applications running in a server environment. The Java HotSpot Server VM is invoked by using the -server command-line option when launching an application, as in
java -server MyApp

Some features of Java HotSpot technology, common to both VM implementations, are the following.

  • Adaptive compiler - Applications are launched using a standard interpreter, but the code is then analyzed as it runs to detect performance bottlenecks, or "hot spots". The Java HotSpot VMs compile those performance-critical portions of the code for a boost in performance, while avoiding unnecessary compilation of seldom-used code (most of the program). The Java HotSpot VMs also usesthe adaptive compiler to decide, on the fly, how best to optimize compiled code with techniques such as in-lining. The runtime analysis performed by the compiler allows it to eliminate guesswork in determining which optimizations will yield the largest performance benefit.

  • Rapid memory allocation and garbage collection - Java HotSpot technology provides for rapid memory allocation for objects, and it has a fast, efficient, state-of-the-art garbage collector.

  • Thread synchronization - The Java programming language allows for use of multiple, concurrent paths of program execution (called "threads"). Java HotSpot technology provides a thread-handling capability that is designed to scale readily for use in large, shared-memory multiprocessor servers.

New Features and Changes

The following are some of the recently added features in the Java HotSpot VMs.

Enhancements in J2SE 1.4.2:

  • Virtual Machine Enhancements in J2SE 1.4.2
Enhancements in J2SE 1.4.1:
  • J2SE 1.4.1 is available in versions that support the 64-bit Intel Itanium processor on Linux Red Hat 7.2 and Windows XP 64-bit edition. Look for the downloads for these versions on the J2SE 1.4.1 download page.

    In this release, these 64-bit versions have the following limitations.

    • Applications can be run only in interpreted mode. The platform will run in interpreted mode by default, with no need to supply the -Xint flag on the command line when launching an application. When using the 64-bit versions of the J2SE 1.4.1 platform, the command java MyApp will launch and execute MyApp by interpreting the bytecode. Java HotSpot-technology-based dynamic compilers for 64-bit support is planned for a future release of the J2SE platform.
    • The 64-bit versions of J2SE 1.4.1 do not include the Java Plug-in and Java Web Start products.
    • The 64-bit versions of J2SE 1.4.1 do not have an installer application. These versions are available only as a tar bundle.
    The 32-bit versions of the J2SE 1.4.1 will not work on Intel Itanium machines.

  • A deadlock detection utility has been added to the Java HotSpot VM. The utility is invoked by a Ctrl+\ on the command line while an application is running. The utility detects Java-platform-level deadlocks, including locking done from the Java Native Interface (JNI), the Java Virtual Machine Profiler Interface (JVMPI), and Java Virtual Machine Debug Interface (JVMDI).

    When invoked, the utility displays a thread dump to standard out and indicates any Java-platform-level deadlocks it detects. Refer to this sample output. If the application is deadlocked because two or more threads are involved in a cylce to acquire monitors, then the list of such threads and monitors involved in the deadlocks are displayed. Note, however, that this will not find deadlocks involving threads waiting on monitors on which no signal will be forthcoming.

Enhancements in J2SE 1.4.0:

  • Signal chaining

  • Error-reporting mechanism

  • The new -Xloggc:file option reports on each garbage-collection event, as with -verbose:gc, but logs this data to file. In addition to the information -verbose:gc provides, each reported event is preceeded by the time (in seconds) since the first garbage-collection event.

  • Beginning with J2SDK 1.4.0, the Classic Virtual Machine is no longer shipped as part of the Java 2 SDK. (On Solaris platforms, the Classic VM was removed in J2SDK 1.3.0.) If you have been running your applications on the Classic VM by using the -classic command-line option, you will need to use either the Java HotSpot Client VM (invoked by default or by using the -client option) or Java HotSpot Server VM (invoked with the -server option). Attempting to launch an application with the -classic option will result in this message: Error: Classic VM no longer supported.

  • The SolarisTM-SPARCTM platform edition of J2SDK 1.4.0 will support 64-bit operation on 64-bit Sparc-v9 platforms when using the Java HotSpot Server VM. With a 64-bit address space, more than four gigabytes of heap memory is available. The Java HotSpot Server VM includes support for both 32-bit and 64-bit operations, and users can select either 32-bit or 64-bit operation by using command-line flags -d32 or -d64, respectively.
    • Users of the Java Native Interface will need to recompile their code to be able to run it on the 64-bit VM.
    • There is no 64-bit support for the Java HotSpot Client VM. Only the Java HotSpot Server VM provides for optional 64-bit operation.
    • Users must install 64-bit Solaris support in order to run the virtual machine in 64-bit mode.
    • On older Sparcv9 systems, users must modify the file /platform/sun4u/boot.conf in order to enable 64-bit programs. See the text in the boot.conf file for more information.

  • The new -Xcheck:jni command-line option performs 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.

  • The J2SE 1.4.0 platform accepts class file versions in the range 45.3 to 48.0.

Command-Line Options

Some operating characteristics of the Java HotSpot VM can be controlled by the use of command-line flags. The command-line options supported by the Java HotSpot VMs are described on the reference pages for the Java application launcher (Microsoft Windows | Solaris Operating Environment | Linux). Non-standard options recognized by the current implementations of the VMs, but not necessarily by future or non-Sun implementations, are described on the Java HotSpot VM Options web page.

See Also

The following additional documentation is available on the Sun web site.
  • Performance Documentation
  • FAQ for Java HotSpot Technology
  • Java HotSpot VM Options
  • Java HotSpot Architecture white paper
  • The Java HotSpot Server VM: The Solution for Reliable, Secure Performance for the Enterprise

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: j2se-comments@eng.sun.com 		Sun


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  (a java.lang.Object)
        - locked  (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  (a java.lang.String)
        - locked  (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  (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  (a java.lang.String)
        - locked  (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  (a java.lang.Object)
        - locked  (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  (a java.lang.ref.ReferenceQueue$Lock)
        at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:111)
        - locked  (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  (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  (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  (a java.lang.Object)
        - locked  (a java.lang.String)
"Thread-6":
        at Locker.run(Deadlock.java:98)
        - waiting to lock  (a java.lang.String)
        - locked  (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  (a java.lang.Object)
        - locked  (a java.lang.Object)
"Thread-2":
        at Locker.run(Deadlock.java:98)
        - waiting to lock  (a java.lang.String)
        - locked  (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.


Signal Chaining
The JavaTM 2 SDK, Standard Edition, (J2SDK) 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:

A. Support for pre-installed signal handlers when the HotSpot VM is created.
B. 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 © 2002 Sun Microsystems, Inc. All Rights Reserved.

 Sun


XML in the Java(TM) 2 Platform

Java

XML in the JavaTM 2 Platform

 Documentation Contents

XML (Extensible Markup Language) is a flexible way to create common information formats and share both the format and the data on the World Wide Web, intranets, and elsewhere. XML can be used by any individual or group of individuals or companies that wants to share information in a consistent way. XML, a formal recommendation from the World Wide Web Consortium (W3C), is similar to the language of today's Web pages, the Hypertext Markup Language (HTML). Both XML and HTML contain markup symbols to describe the contents of a page or file. HTML, however, describes the content of a Web page (mainly text and graphic images) only in terms of how it is to be displayed and interacted with. For example, a <P> starts a new paragraph. XML describes the content in terms of what data is being described. For example, a <PHONENUM> could indicate that the data that followed it was a phone number. This means that an XML file can be processed purely as data by a program or it can be stored with similar data on another computer or, like an HTML file, that it can be displayed. For example, depending on how the application in the receiving computer wanted to handle the phone number, it could be stored, displayed, or dialed.

Java 2 Platform XML Features

  • The JavaTM API For XML Processing (JAXP)

Additional XML reference material

    Located on the Java Software website:

  • JavaTM Technology & XML Home Page
  • XML Tutorial
  • XML at Sun

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software


XML Processing

Documentation Contents

The JavaTM API for XML Processing (JAXP) includes the basic facilities for working with XML documents through the following standardized set of Java Platform APIs.

Document Object Model (DOM) Level 2

The Document Object Model (DOM) is a set of interfaces defined by the W3C DOM Working Group. It describes facilities for a programmatic representation of a parsed XML (or HTML) document. The DOM Level 2 specification defines these interfaces using Interface Definition Language (IDL) in a language independent fashion and also includes a Java Language binding.

The JavaTM API for XML processing specification includes by reference both the abstract semantics described for the DOM Level 2 Core Recommendation interfaces and the associated Java Language binding. It does not include the optional extensions defined by the DOM working group.

The API package included by the JavaTM API for XML processing specification is:

  • org.w3c.dom, which is a part of the Common DOM API.

Simple API For XML Parsing (SAX) 2.0

The Simple API for XML (SAX) is a public domain API developed cooperatively by the members of the XML-DEV mailing list. It provides an event-driven interface to the process of parsing an XML document.

An event driven interface provides a mechanism for "callback" notifications to application’s code as the underlying parser recognizes XML syntactic constructions in the document.

The JavaTM API for XML processing specification includes by reference the SAX 2.0 API and the SAX2 extensions in its entirety.

The API packages included by reference are:

  • org.xml.sax
  • org.xml.sax.helpers
  • org.xml.sax.ext

XSLT 1.0

The XSL Transformations (XSLT) describes a language for transforming XML documents into other XML documents or other text output. It was defined by the W3C XSL Working group.

The XSLT 1.0 Recommendation is located at:

http://www.w3.org/TR/1999/REC-xslt-19991116

The JavaTM API for XML processing specification includes by reference the XSLT 1.0 specification in its entirety.

The API packages included by reference are:

  • javax.xml.transform

Pluggability Layer

The endorsed APIs provide broad and useful functionality. However, the use of a SAX or a DOM parser typically requires knowledge of the specific implementation of the parser. Providing the functionality of the endorsed APIs in the Java Platform, while allowing choice of the implementation of the parser, requires a Pluggability layer.

The JavaTM API for XML processing specification defines a Pluggability mechanism to allow a compliant SAX or DOM parser to be used through the abstract javax.xml.parsers and javax.xml.transform API. Also, compliant Transformers are pluggable via the javax.xml.transform API.

For More Information

Located on the Java Software website:

  • JavaTM Technology & XML Home Page
Copyright © 2001 Sun Microsystems, Inc. All Rights Reserved.

Sun Microsystems, Inc
Java Software


Contacting Java Software

 Documentation Contents

The Java 2 SDK, Standard Edition is a product of Sun Microsystems, Inc. The Java 2 SDK is developed by Java Software, a part of Sun Microsystems.

Java Software welcomes your comments and suggestions. You can contact us through email, or you can file a bug report. But please remember that Java Software does not offer free technical support. If you need help, try the More Technical Resources page, where you'll find links to FAQs, online tutorials, and many other resources.

Send Us Email

Feel free to send email directly to Java Software engineering teams using:

Java Software email address list
If you're not sure which team to contact, browse the Guide to Features and look for a "Comments" email link at the bottom of the main page for each feature.

Please file documentation bugs as described below. For other general comments about the documentation not targeted to any particular engineering team, please contact the Documentation Team.

File a Bug Report

You can use our bug tracking system to report bugs or request new features. Use our Bug Report Form.

Download/Installation Problems?

If you're having problems downloading or installing the Java 2 SDK or Java 2 Runtime Environment, please see the Download and Installation FAQs.

Copyright © 2003 Sun Microsystems, Inc. All Rights Reserved.

Java Software


Java 2 SDK Demos

Java

Demonstration
Applets and Applications

 Documentation Contents
The JavaTM 2 SDK contains a demos directory that includes applets, applications, and sample code that demonstrate various features of the Java 2 Platform. The available demos are described in the following sections.

Applets

The applet demos are located in the Java 2 SDK's demo/applets directory. To run the applets, use the appletviewer or your web browser to open the file named example1.html in each of the applets' subdirectories. The demo applets are also available on the java.sun.com web site, and links to the online applets are provided below.

Applets can run in AppletViewer or in web browers when the JavaTM Plug-in product is installed. The AppletViewer is provided with the Java 2 SDK, Standard Edition, in the SDK's bin directory. For information about how to use the AppletViewer and other SDK tools, see Java 2 SDK Tools and Utilities.

  • Animator (1, 2, 3, 4)
  • ArcTest
  • BarChart
  • Blink
  • CardTest
  • Clock
  • DitherTest
  • DrawTest
  • Fractal
  • GraphLayout (1, 2, 3, 4)
  • GraphicsTest
  • ImageMap
  • JumpingBox
  • MoleculeViewer (1, 2, 3)
  • NervousText
  • SimpleGraph
  • SortDemo
  • SpreadSheet
  • TicTacToe
  • WireFrame (1, 2, 3, 4)

JFC Applications and Applets

These applications and applets, located in the Java 2 SDK's demo/jfc directory, demonstrate Swing and Java 2DTM technology.

Java Platform Debugger Architecture

The demo/jpda/examples.jar file in the SDK contains JPDA examples, including source code for the jdb Java Debugger and the prototype javadt GUI debugger.

The Poller Demo (SolarisTM Operating Environment only)

This demo, located in the Java 2 SDK's demo/jni/Poller directory, demonstrates access to the input/output multiplexing functionality from the Java programming language. See the Solaris poll man page.

Java Secure Socket Extension (JSSE) Demo

This demo, located in the Java 2 SDK's demo/jsse directory, contains sample code that illustrates the use of the Java 2 Platform's JSSE functionality can be used to secure communications in the Java network environment.

Additional Applications and Applets

Additional applets and applications may be found at:
  • Guide to Features - Examples are included in the documentation for particular features.
  • Applets Page - Located on Sun Java Software web site
  • The Java Tutorial - Located on Sun Java Software web site
    • First Cup of Java
    • "Hello World" Applet and Application
    • BINGO! Client/Server Application

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to jdk-comments@java.sun.com 		Sun

Java Software


Specifications and Developer Docs

Java

API Specifications vs.
API Developer Documentation

 Contents
A common question we get is: Why aren't the JavaTM 2 platform API specifications written as more complete developer documentation? Why don't they include full working code examples, definitions of common programming terms, conceptual overviews, metaphors, illustrations, descriptions of implementation bugs and workarounds? We have chosen to put this information in the books listed below, and restrict the specifications to "assertions" necessary for conforming implementations.

  • Developer documentation contained in the Java 2 SDK documentation:
    Java 2 SDK SE Documentation - This is the documentation for a particular release of the Java 2 SDK. It points to the Java 2 Platform, Standard Edition API Specification mentioned above.

Browsable online and downloadable (HTML).
  • Developer guides and tutorials:
    Java Tutorial Books - Developer documentation that covers much of the Java 2 Platform.

Browsable online, downloadable, and available as printed books.
  • Code Examples
    Java Developers Almanac - Searchable online code examples

Browsable online and available as printed book.
  • 1.2 API developer reference documentation:
    The Java Class Libraries, Second Edition - These books include more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terminology, workarounds for bugs, and working code examples for nearly all classes, interfaces and members in 15 basic packages in Java 2 SDK, Standard Edition, v 1.2.

Available in print only. Code samples are downloadable.
  • Other books in the Java Series "from the source", include Developers Almanac, Java Programming Language, Java Language Specification, Java FAQ, Security, JDBC, JVM, 3D, Enterprise JavaBeans, the Class Libraries Poster and others.
Some available online, all available in print as books.

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Java Software


New Features

Java

JavaTM 2 SDK, Standard Edition, version 1.4.2
Summary of New Features and Enhancements

 Contents

Version 1.4.0 of the Java 2 SDK, Standard Edition was a major feature release. The features listed below are those introduced in 1.4.0 (since 1.3). Version 1.4.2 is a maintenance release and introduces the minor enhancements and changes (since 1.4.1) listed at Enhancements and Changes in J2SE 1.4.2 on the web site.

The full list of features, including features brought forward from previous versions, is available at Guide to Features.

Java 2 Platform
  • XML Processing
  • New I/O APIs
  • Security
  • Java 2DTM technology
  • Image I/O Framework
  • Java Print Service
  • AWT
  • Swing
  • Drag and Drop
  • Logging API
  • JavaTM Web Start Product
  • Long-term Persistence of JavaBeansTM Components
  • JDBCTM 3.0 API
  • Assertion Facility
  • Preferences API
  • Chained Exception Facility
  • Endorsed Standards Override Mechanism
  • Java Virtual Machines
  • Performance
  • Networking Support, Including IPv6
  • RMI
  • Serialization
  • Java Naming and Directory InterfaceTM (JNDI)
  • CORBA, Java IDL, and RMI-IIOP
  • JavaTM Platform Debugger Architecture
  • Internationalization
  • JavaTM Plug-in Product
  • Collections Framework
  • Accessibility
  • Regular Expressions
  • Math
  • Reflection
  • Java Native Interface
Tools
  • Tools and Utilities

Java 2 Platform

  • XML Processing
    The JavaTM API for XML processing has been added to the Java 2 Platform. It provides basic support for processing XML documents through a standardized set of Java Platform APIs.

  • New I/O APIs
    The new I/O (NIO) APIs provide new features and improved performance in the areas of buffer management, character-set support, regular-expression matching, file I/O, and scalable network I/O.

  • Security
    • The JavaTM Cryptography Extension (JCE), JavaTM Secure Socket Extension (JSSE), and JavaTM Authentication and Authorization Service (JAAS) security features have now been integrated into the JavaTM 2 SDK, Standard Edition (Java 2 SDK), v 1.4 rather than being optional packages.
    • There are two new security features:
      • The JavaTM GSS-API can be used for securely exchanging messages between communicating applications using the Kerberos V5 mechanism.
      • The JavaTM Certification Path API includes new classes and methods in the java.security.cert package that allow you to build and validate certification paths (also known as "certificate chains").
    • Due to import control restrictions, the JCE jurisdiction policy files shipped with the Java 2 SDK, v 1.4 allow "strong" but limited cryptography to be used. An "unlimited" version of these files indicating no restrictions on cryptographic strengths is available.
    • The JSSE implementation provided in this release includes strong cipher suites. However, due to U.S. export control restrictions, this release does not allow alternate "pluggable" SSL/TLS implementations to be used. For more information, please see the JSSE Reference Guide.
    • With the integration of JAAS into the Java 2 SDK, the java.security.Policy API handles Principal-based queries, and the default policy implementation supports Principal-based grant entries. Thus, access control can now be based not just on what code is running, but also on who is running it.
    • Support for dynamic policies has been added. In Java 2 SDK releases prior to version 1.4, classes were statically bound with permissions by querying security policy during class loading. The lifetime of this binding was scoped by the lifetime of the class loader. In version 1.4 this binding is now deferred until needed by a security check. The lifetime of the binding is now scoped by the lifetime of the security policy.
    • The graphical Policy Tool utility has been enhanced to enable specifying a Principal field indicating what user is to be granted specified access control permissions.

  • Java 2DTM Technology
    Java 2D includes many new features including: performance improvements, support for hardware acceleration for offscreen images, a pluggable image I/O framework, a new print service API, and several new font features.

  • Image I/O Framework
    The Java Image I/O Framework 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 current APIs for loading and saving images.

  • Java Print Service API
    The JavaTM Print Service is a new Java Print API that enables client and server applications to:
    • Discover and select print services based on their capabilities
    • Specify the format of print data
    • Submit print jobs to services that support the document type to be printed.
  • AWT
    Changes to the AWT package center on improving the robustness, behavior, and performance of programs that present a graphical user interface. A new focus architecture replaces the previous implementation and addresses many focus-related bugs caused by platform inconsistencies, and incompatibilities between AWT and Swing components. 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; a benefit to applications like games, or other rendering-intensive applications. Headless support is now enabled by new graphics environment methods that indicate whether a display, keyboard, and mouse can be supported in a graphics environment. The ability to disable native frame decorations is now available for applications which need to take full control of specifying how a frame will look; when enabled this prevents the rendering of a native titlebar, system menu, border, or other native operating system dependent screen components. The oft-requested 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. Also, a new mouse wheel listener class allows customization of mouse wheel behavior. The AWT package has been modified to be fully 64-bit compliant and now runs on Solaris machines with 64-bit and 32-bit addresses.

  • Swing
    Many new features have been added to Swing. The new spinner component is a single line input field that allows the user to select a number or a value by cycling through a sequence of values using a tiny pair of up/down arrow buttons. The new formatted text field component allows formatting of dates, numbers, and strings, such as a text field that accepts only decimal money values. The Windows look and feel implementation is updated to track features available in the 2000/98 versions. A new drag and drop architecture provides seamless drag and drop support between components as well as an easy way to implement drag and drop in your customized Swing components - writing a couple of methods which describe the particulars of your data model is all that is required. Swing's progress bar component has been enhanced to support an indeterminate state; rather than showing the degree of completeness, the indeterminate progress bar uses constant animation to show that a time-consuming operation is occurring. Due to great customer demand, the tabbed pane component has been enhanced to support scrollable tabs. With this feature enabled, if all the tabs will not fit within a single tab run, the tabbed pane component will display a single, scrollable run of tabs, instead of wrapping the tabs onto multiple runs. The popup and popup factory classes, which were previously package private, have been exposed and made public so that programmers may customize or create their own popups. The new focus architecture is fully integrated into Swing.

  • Drag and Drop
    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 and clipboard transfer via cut/copy/paste. See Swing Data Transfer.

  • Logging API
    The Java Logging APIs facilitate software servicing and maintenance at customer sites by producing log reports suitable for analysis by end users, system administrators, field service engineers, and software development teams. The Logging APIs capture information such as security failures, configuration errors, performance bottlenecks, and/or bugs in the application or platform.

  • JavaTM Web Start Product
    The Java Web Start product is a new application-deployment technology that is bundled with J2SE 1.4.0. With Java Web Start, you launch applications simply by clicking on a Web page link. If the application is not present on your computer, Java Web Start automatically downloads all necessary files. It then caches the files on your computer so the application is always ready to be relaunched anytime you want -- either from an icon on your desktop or from the browser link. And no matter which method you use to launch the application, the most current version of the application is always presented to you.

  • Long-term Persistence of JavaBeans Components
    The new persistence model is designed to handle the process of converting a graph of beans to and from a persistent form. The new API is suitable for creating archives of graphs of JavaBeans components as textual representations of their properties. See API Enhancements to the JavaBeans Component API.

  • JDBC 3.0 API
    The JDBC 3.0 API, comprised of packages java.sql and javax.sql, provides universal data access from the Java programming language. Using the JDBC 3.0 API, you can access virtualy any data source, from relational databases to spreadsheets and flat files. JDBC technology also provides a common base on which tools and alternative interfaces can be built.

    New features include the ability to set savepoints in a transaction, to keep result sets open after a transaction is committed, to reuse prepared statements, to get metadata about the parameters to a prepared statement, to retrieve keys that are automatically generated, and to have multiple result sets open at one time. There are two new JDBC data types, BOOLEAN and DATALINK, with the DATALINK type making it possible to manage data outside of a data source. This release also establishes the relationship between the JDBC Service Provider Interface and the Connector architechture.

  • Assertion Facility
    An assertion facility has been added to the Java 2 Platform. Assertions are boolean expressions that the programmer believes to be true concerning the state of a computer program. For example, after sorting a list, the programmer might assert that the list is in ascending order. Evaluating assertions at runtime to confirm their validity is one of the most powerful tools for improving code quality, as it quickly uncovers the programmer's misconceptions concerning a program's behavior.

  • Preferences API
    This new feature is a simple API for managing user preference and configuration data. Applications require preference and configuration data to adapt to different users, environments and needs. Applications need a way to store, retrieve, and modify this data. This need is met by the Preferences API. The Preferences API is intended to replace most common uses of class java.util.Properties, rectifying many of its deficiencies, while retaining its light weight.

  • Endorsed Standards Override Mechanism
    An endorsed standard is a JavaTM API defined through a standards process other than the Java Community Process SM (JCPSM). Because endorsed standards are defined outside the JCP, it is anticipated that such standards may be revised between releases of the Java 2 Platform. In order to take advantage of new revisions to endorsed standards, developers and software vendors may use the Endorsed Standards Override Mechanism to provide newer versions of an endorsed standard than those included in the Java 2 Platform as released by Sun Microsystems.

  • Chained Exception Facility
    This new facility provides a common API to record the fact that one exception caused another, to access causative exceptions, and to acess the 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.

  • Java Virtual Machines
    The Java virtual machines in this release include several enhancements.
    • Signal-chaining facility.
    • 64-bit support on SolarisTM-SPARCTM platform edition.
    • Error-reporting mechanism.
    • New command-line option for performing additional Java Native Interface (JNI) checks.
    • New facility for logging garbage-collection events.
    The Classic virtual machine is no longer shipped as part of the Java 2 SDK.

  • Performance
    This release includes performance enhancements in many areas of the platform. See Performance Enhancements for a description of some of them.

  • Networking Support, Including IPv6
    New features include support for IPv6 in TCP- and UDP-based applications, and support for unconnected/unbound sockets, allowing more flexible socket creation, binding, and connection. A mechanism called Java Secure Socket Extension provides encryption for data sent via sockets, and a new class, URI, allows URI construction and parsing without the presence of a protocol handler. The FTP Protocol Handler has been overhauled for conformity to current standards. The default character set is now UTF8, and APIs have been added to enable other character schemes.

    A new class, NetworkInterface, allows enumeration of interfaces and addresses, and JNDI DNS SP Support in InetAddress enables applications to configure a pure Java name service provider. TCP out-of-band data provides support for legacy applications; a UDP Connection function registers destination address with the OS, enabling asynchronous errors to be returned on the UDP socket; and full SOCkS V5 and V4 TCP support includes auto-negotiation with the proxy for which version to use. In addition, there are improvements to streaming, request and response headers processing, and error handling.

  • RMI
    Server-side Stack Traces Now Retained in Remote Exceptions
    The RMI runtime implementation will now preserve the server-side stack trace information of an exception that is thrown from a remote call, in addition to filling in the client-side stack trace as it did previous releases. Therefore, when such an exception becomes accessible to client code, its stack trace will now contain all of its original server-side trace data followed by the client-side trace.

    Service Provider Interface for RMIClassLoader
    Certain static methods of java.rmi.server.RMIClassLoader now delegate their behavior to an instance of a new service provider interface, java.rmi.server.RMIClassLoaderSpi. This service provider object can be configured to augment RMI's dynamic class loading behavior for a given application. By default, the service provider implements the standard behavior of all of the static methods in RMIClassLoader. See the class documentation of RMIClassLoader and RMIClassLoaderSpi for more details.

    Dynamic Server Host Name
    The java.rmi.server.hostname property can now be dynamically updated to indicate that future exports should use a new host name. Therefore, the new host name value will be contained in the stub for an object that is exported after the property is updated.

  • Serialization
    This release has several changes and enhancements to the serialization API, including
    • Support for deserialization of objects that are known to be unshared in the data-serialization stream.
    • Support for a class-defined readObjectNoData method.
    • Important bug fixes.

  • Java Naming and Directory InterfaceTM (JNDI)
    • An Internet Domain Naming System (DNS) service provider is part of the Java 2 Platform, Standard Edition, v1.4. This component enables applications to read data stored in the DNS.
    • The JNDI Lightweight Directory Access Protocol (LDAP) service provider has security enhancements that enable applications to establish secure sessions over existing LDAP connections and to use different authentication protocols.
    • The JNDI CORBA Object Services (COS) naming service provider supports the Interoperable Naming Service (INS) specification (99-12-03).
    See JNDI Enhancements for details.

  • CORBA, Java IDL, and RMI-IIOP
    The ORB shipping as part of Java 2 Platform now includes a Portable Object Adapter (POA) functionality. An ORB makes it possible for client(s) to make method invocations on the objects being supported by server(s) executing on the same or different machine(s). ThePOA functionality allows programmers to construct object implementations that are portable between different ORB products, provide support for objects with persistent identities, and much more. Other new features include Portable Interceptors, Interoperable Naming Service, GIOP 1.2 support, Dynamic Management of Any values, and new tools that support a persistent naming service and other features. To learn more about the new features in Java IDL and RMI-IIOP between J2SE v.1.3 and J2SE v.1.4, link to Changes in CORBA Features Between J2SE 1.3 and 1.4.

  • JavaTM Platform Debugger Architecture
    Full Speed Debugging Support
    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.

    HotSwap
    This feature has been added to allow a class to be updated while under the control of a debugger.

    Instance Filters
    EventRequests now have the capability of specifying an instance filter, which restricts the events generated by the request to those in which the currently executing instance is the object specified.

    Support For Debugging Other Languages
    The Java Platform Debugger Architecture has been extended so that non-Java programming language source, which is translated to Java programming language source, can be debugged in the future.

    VMDeathRequests
    A request can now be made to control target VM termination notification, allowing clean shutdown synchronization

  • Internationalization
    Unicode 3.0 Support
    Character handling in J2SE 1.4 is based on version 3.0 of the Unicode standard. This affects the Character and String classes in the java.lang package as well as the collation and bidirectional text analysis functionality in the java.text package.

    Support for Thai and Hindi
    Thai and Hindi are now supported in all areas of functionality. See the Supported Locales document for complete information on supported locales and writing systems.

    Currency class
    The class java.util.Currency was introduced so that currencies can be referenced independent of locales. There are new methods on java.text.NumberFormat and related classes to specify the currency for formatting monetary values.

  • JavaTM Plug-in Product
    Java Plug-in 1.4 offers the following new features: support of HTTPS through Java Secure Socket Extension (JSSE) rather than the browser; enhanced applet caching so that other files, such as GIF, JPEG, AU, etc., can be cached as part of the download in addition to JAR and class files; applet persistence so that applets may persist across browser page changes; various applet-compatibility enhancements to allow most JDK 1.1 applets to run seemlessly in Java 2; and on Microsoft Windows platforms, support in Java Plug-in for launching applets using the <APPLET> tag.

    Version 1.4 also provides access to the DOM via standard, w3c-defined interfaces; assertion and logging support; applet usability enhancements, including a customizable progress bar for applet loading; and enhanced options in the Java Console to allow dynamic reconfiguration of proxy settings, the policy file, etc., while the applet is running.

  • Collections Framework
    The collections framework has several enhancements in Java 2 SDK 1.4, including a marker interface to advertise random access, an identity-based (rather than equality-based) Map, insertion-order-preserving Map and Set implementations, and several new algorithms for manipulating and returning values from lists. See Collections Framework Enhancements for details.

  • Accessibility
    New features include support for:
    • Mnemonic tab navigation on a JTabbedPane
    • Text editing by assistive technologies
    • Accessibility of HTML components
    • Accessibility of Swing Actions
    • List navigation using the first letter of list items
    • Component roles DATE_EDITOR, FONT_CHOOSER, GROUP_BOX, SPIN_BOX, STATUS_BAR
    • Properties to indicate the presence of a screen magnifier or screen reader, or to specify assistive technologies to load into the Java virtual machine

  • Regular Expressions
    New package java.util.regex contains classes for matching character sequences against patterns specified by regular expressions.

  • Math
    A new, efficient method for generating prime numbers with no need for the caller to specify a certainty has been added to class java.math.BigInteger.

  • Reflection
    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.

  • Java Native Interface
    A few changes have been made to JNI in v 1.4. First, the version number has been incremented and the specification of JNI_OnLoad updated accordingly. Second, JNI has been enhanced to reflect a new feature of the java.nio package: direct buffers. The contents of a direct buffer can, potentially, reside in native memory outside of the ordinary garbage-collected heap. Finally, the new Invocation Interface routine AttachCurrentTreadAsDaemon allows native code to attach a daemon thread to the virtual machine; this is useful when the VM should not wait for this thread to exit upon shutdown. See JNI Enhancements for more on these enhancements.

Tools and Utilities

See Tool Changes for details on the changes summarized here.
  • The java application launcher supports command-line options for support of the new Assertions Facility. On the SolarisTM Operating Environment (SPARCTM Platform Edition) new command-line options are available for specifying 64-bit or 32-bit operation. On all platforms, new option -Xloggc:file logs each garbage-collection event in the specified file. Also on all platforms, the new option -Xcheck:jni performs additional checks for Java Native Interface (JNI) functions at the cost of some performance degradation

  • The javadoc tool has several new tags, a dozen new options, smarter inheriting of doc comments, more control over HTML output, improvements to the Doclet API, better error messages, dozens of bug fixes, and is easier to run. For more details, see What's New in Javadoc 1.4. Downloaded separately from the SDK, the MIF doclet has had a major upgrade -- it generates API documentation in FrameMaker and PDF format.

  • The native2ascii tool contains bug fixes to now correctly process source files encoded with Unicode encoding.

  • The idlj tool now generates server-side bindings following the Portable Servant Inheritance Model. This change involves producing new POA bindings by default. A new command-line option is added to enable you to continue to generate backwards-compatible server-side bindings. To learn more about the Portable Servant Inheritance Model, follow the link.

  • The orbd tool, or Object Request Broker Daemon, is a new alternative tool for the Transient Naming Service, tnameserv. ORBD includes both a Transient Naming Service and a Persistent Naming Service. The orbd tool is used to enable clients to transparently locate and invoke persistent objects on servers in the CORBA environment. The orbd tool incorporates the functionality of a Server Manager, an Interoperable Naming Service, and a Bootstrap Name Server. When used in conjunction with the servertool, the Server Manager locates, registers, and activates a server when a client wants to access the server.

  • The servertool is new to this release. The servertool provides an ease-of-use interface for application programmers to register, unregister, startup, and shutdown a server.

  • The rmic compiler has a new option to enable Portable Object Adapter, or POA support for Remote Method Invocation. The POA enables portability among vendor ORBs, among other uses. To lea rn more about the POA, follow the link. To enable POA support with the rmic compiler, use the arguments rmic -iiop -poa.

  • The graphical Policy Tool utility has been enhanced to enable specifying a Principal field indicating what user is to be granted specified access control permissions.

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

 Sun Microsystems, Inc


JavaTM 2, Standard Edition (J2SETM) Specification ("Specification")
Version: 1.4.2
Status: FCS
Release: June 25, 2003

Copyright 2003 Sun Microsystems, Inc.

4150 Network Circle, Santa Clara, California 95054, U.S.A
All rights reserved.

NOTICE; LIMITED LICENSE GRANTS

Sun Microsystems, Inc. ("Sun") hereby grants you a fully-paid, non-exclusive, non-transferable, worldwide, limited license (without the right to sublicense), under the Sun's applicable intellectual property rights to view, download, use and reproduce the Specification only for the purpose of internal evaluation, which shall be understood to include developing applications intended to run on an implementation of the Specification provided that such applications do not themselves implement any portion(s) of the Specification.

Sun also grants you a perpetual, non-exclusive, worldwide, fully paid-up, royalty free, limited license (without the right to sublicense) under any applicable copyrights or patent rights it may have in the Specification to create and/or distribute an Independent Implementation of the Specification that: (i) fully implements the Spec(s) including all its required interfaces and functionality; (ii) does not modify, subset, superset or otherwise extend the Licensor Name Space, or include any public or protected packages, classes, Java interfaces, fields or methods within the Licensor Name Space other than those required/authorized by the Specification or Specifications being implemented; and (iii) passes the TCK (including satisfying the requirements of the applicable TCK Users Guide) for such Specification. The foregoing license is expressly conditioned on your not acting outside its scope. No license is granted hereunder for any other purpose.

You need not include limitations (i)-(iii) from the previous paragraph or any other particular "pass through" requirements in any license You grant concerning the use of your Independent Implementation or products derived from it. However, except with respect to implementations of the Specification (and products derived from them) that satisfy limitations (i)-(iii) from the previous paragraph, You may neither: (a) grant or otherwise pass through to your licensees any licenses under Sun's applicable intellectual property rights; nor (b) authorize your licensees to make any claims concerning their implementation's compliance with the Spec in question.

For the purposes of this Agreement: "Independent Implementation" shall mean an implementation of the Specification that neither derives from any of Sun's source code or binary code materials nor, except with an appropriate and separate license from Sun, includes any of Sun's source code or binary code materials; and "Licensor Name Space" shall mean the public class or interface declarations whose names begin with "java", "javax", "com.sun" or their equivalents in any subsequent naming convention adopted by Sun through the Java Community Process, or any recognized successors or replacements thereof.

This Agreement will terminate immediately without notice from Sun if you fail to comply with any material provision of or act outside the scope of the licenses granted above.

TRADEMARKS

No right, title, or interest in or to any trademarks, service marks, or trade names of Sun or Sun's licensors is granted hereunder. Sun, Sun Microsystems, the Sun logo, Java, J2SE, and the Java Coffee Cup Logo are trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S. and other countries.

DISCLAIMER OF WARRANTIES

THE SPECIFICATION IS PROVIDED "AS IS". SUN MAKES NO REPRESENTATIONS OR WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT, THAT THE CONTENTS OF THE SPECIFICATION ARE SUITABLE FOR ANY PURPOSE OR THAT ANY PRACTICE OR IMPLEMENTATION OF SUCH CONTENTS WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADE SECRETS OR OTHER RIGHTS. This document does not represent any commitment to release or implement any portion of the Specification in any product.

THE SPECIFICATION COULD INCLUDE TECHNICAL INACCURACIES OR TYPOGRAPHICAL ERRORS. CHANGES ARE PERIODICALLY ADDED TO THE INFORMATION THEREIN; THESE CHANGES WILL BE INCORPORATED INTO NEW VERSIONS OF THE SPECIFICATION, IF ANY. SUN MAY MAKE IMPROVEMENTS AND/OR CHANGES TO THE PRODUCT(S) AND/OR THE PROGRAM(S) DESCRIBED IN THE SPECIFICATION AT ANY TIME. Any use of such changes in the Specification will be governed by the then-current license for the applicable version of the Specification.

LIMITATION OF LIABILITY

TO THE EXTENT NOT PROHIBITED BY LAW, IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY DAMAGES, INCLUDING WITHOUT LIMITATION, LOST REVENUE, PROFITS OR DATA, OR FOR SPECIAL, INDIRECT, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF OR RELATED TO ANY FURNISHING, PRACTICING, MODIFYING OR ANY USE OF THE SPECIFICATION, EVEN IF SUN AND/OR ITS LICENSORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

You will indemnify, hold harmless, and defend Sun and its licensors from any claims arising or resulting from: (i) your use of the Specification; (ii) the use or distribution of your Java application, applet and/or clean room implementation; and/or (iii) any claims that later versions or releases of any Specification furnished to you are incompatible with the Specification provided to you under this license.

RESTRICTED RIGHTS LEGEND

U.S. Government: If this Specification is being acquired by or on behalf of the U.S. Government or by a U.S. Government prime contractor or subcontractor (at any tier), then the Government's rights in the Specification and accompanying documentation shall be only as set forth in this license; this is in accordance with 48 C.F.R. 227.7201 through 227.7202-4 (for Department of Defense (DoD) acquisitions) and with 48 C.F.R. 2.101 and 12.212 (for non-DoD acquisitions).

REPORT

You may wish to report any ambiguities, inconsistencies or inaccuracies you may find in connection with your use of the Specification ("Feedback"). To the extent that you provide Sun with any Feedback, you hereby: (i) agree that such Feedback is provided on a non-proprietary and non-confidential basis, and (ii) grant Sun a perpetual, non-exclusive, worldwide, fully paid-up, irrevocable license, with the right to sublicense through multiple levels of sublicensees, to incorporate, disclose, and use without limitation the Feedback for any purpose related to the Specification and future versions, implementations, and test suites thereof.

(LFI#132520/Form ID#011801)


Properietary Rights Notice

 Copyright © 2003 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, U.S.A. All rights reserved.

Sun Microsystems, Inc. has intellectual property rights relating to technology embodied in the product that is described in this document. In particular, and without limitation, these intellectual property rights may include one or more of the U.S. patents listed at http://www.sun.com/patents and one or more additional patents or pending patent applications in the U.S. and in other countries.

This document and the product to which it pertains are distributed under licenses restricting their use, copying, distribution, and decompilation. No part of the product or of this document may be reproduced in any form by any means without prior written authorization of Sun and its licensors, if any.

Third-party software, including font technology, is copyrighted and licensed from Sun suppliers. Portions Copyright Eastman Kodak Company 1992. This product includes code licensed from RSA Data Security. This product includes software developed by the Apache Software Foundation (http://www.apache.org). Portions licensed from Taligent, Inc. This software is based in part on the work of the Independent JPEG Group. The Graphics Interchange Format is the Copyright property of CompuServe Incorporated.

Sun, Sun Microsystems, the Sun logo, Java, Solaris, J2SE, the Duke logo, the Java Coffee Cup logo and the Solaris logo are trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S. and other countries.

All SPARC trademarks are used under license and are trademarks or registered trademarks of SPARC International, Inc. in the U.S. and other countries. Products bearing SPARC trademarks are based upon architecture developed by Sun Microsystems, Inc. UNIX is a registered trademark in the U.S. and other countries, exclusively licensed through X/Open Company, Ltd. Lucida is a registered trademark or trademark of Bigelow & Holmes in the U.S. And other countries. GIF(sm) is a Service Mark property of CompuServe Incorporated.

Federal Acquisitions: Commercial Software - Government Users Subject to Standard License Terms and Conditions.

DOCUMENTATION IS PROVIDED "AS IS" AND ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD TO BE LEGALLY INVALID.

Copyright © 2003 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, États-Unis. Tous droits réservés.

Sun Microsystems, Inc. détient les droits de propriété intellectuelle sur la technologie incluse dans le produit décrit dans ce document. En particulier, et de manière non-exclusive, ces droits de propriété intellectuelle peuvent inclure un ou plusieurs brevets U.S. énumérés à l'adresse suivante : http://www.sun.com/patents et un ou plusieurs brevets supplémentaires ou une ou plusieurs demandes de brevet pendantes aux États-Unis et dans d'autres pays.

Ce document et le produit auquel il se rapporte sont distribués en vertu de licences limitant leur utilisation, leur copie, leur diffusion et leur décompilation. Aucune partie de ce produit ou de ce document ne peut être reproduite, sous quelque forme et par quelque moyen que ce soit, sans l'autorisation écrite préalable de Sun et, le cas échéant, de ses concédants.

Tout logiciel de tiers, y compris toute technologie de police, est protégé par droit d'auteur et obtenu sous licence auprès de fournisseurs de Sun. Certaines parties sont protégées par droit d'auteur Eastman Kodak Company 1992. Ce produit inclut un code concédé sous licence par RSA Data Security. Ce produit inclut un logiciel développé par Apache Software Foundation (http://www.apache.org). Certaines parties sont obtenues sous licence de Taligent, Inc. Ce logiciel repose en partie sur le travail du JPEG Independant Group. Le Format Graphics Interchange est la propriété protégée par droit d'auteur de CompuServe Incorporated.

Sun, Sun Microsystems, le logo Sun, Java, Solaris, J2SE, le logo Duke, le logo Java Coffee Cup et le logo Solaris sont des marques ou des marques déposées de Sun Microsystems, Inc. aux États-Unis et dans d'autres pays.

Toutes les marques SPARC sont utilisées sous licence et sont des marques ou des marques déposées de SPARC International, Inc. aux États-Unis et dans d'autres pays. Les produits portant les marques SPARC reposent sur l'architecture développée par Sun Microsystems, Inc. UNIX est une marque déposée aux États-Unis et dans d'autres pays, concédée sous licence exclusivement par l'intermédiaire de X/Open Company, Ltd. Lucida est une marque déposée ou une marque de Bigelow & Holmes aux États-Unis et dans d'autres pays. GIF(sm) est une propriété de marque de service de CompuServe Incorporated.

LA DOCUMENTATION EST FOURNIE " TELLE QUELLE " ET TOUTES CONDITIONS, DÉCLARATIONS ET GARANTIES EXPRESSES OU TACITES, Y COMPRIS TOUTE GARANTIE TACITE DE QUALITÉ MARCHANDE, D'ADÉQUATION À UN USAGE PARTICULIER OU D'ABSENCE DE CONTREFAÇON DE DROITS DE TIERS, SONT REJETÉES, EXCEPTÉ DANS LE CAS OÙ L'EXCLUSION OU LA LIMITATION DE TELLES GARANTIES NE SERAIT PAS AUTORISÉE PAR LA LÉGISLATION EN VIGUEUR.


Legal Notices

 Documentation Contents

Proprietary Rights Notice

J2SETM Specification License

Documentation Redistribution Policy
(On java.sun.com web site)

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Sun


Sommaire

BONJOUR
Musique "Invention BWV988" J.S. BACH 1685-1750

Javadoc SDK

Java 2 SE v1.4.2


Javadoc Tool

Java

Javadoc 1.4.2
Tool

 Java 2 SDK v1.4 Contents
Javadoc is a tool that parses the declarations and documentation comments in a set of source files and produces a set of HTML pages describing the classes, inner classes, interfaces, constructors, methods, and fields.

You can use Javadoc doclets to customize Javadoc output. A doclet is a program written with the doclet API that specifies the content and format of the output to be generated by the javadoc tool. You can write a doclet to generate any kind of text-file output, such as HTML, SGML, XML, RTF, and MIF. SunTM provides a "standard" doclet for generating HTML-format API documentation and an experimental MIF doclet for generating MIF, PDF, PS, RTF, FrameMaker, and other formats. Doclets can also be used to perform special tasks not related to producing API documentation. For example, a diagnostic doclet could be created to check that all class members of the classes on which Javadoc operates have documentation comments.

Javadoc Enhancements
Describes the new features.
  • What's New in Javadoc 1.4.2
  • What's New in Javadoc 1.4.1
  • What's New in Javadoc 1.4.0
  • What's New in Javadoc 1.3
  • What's New in Javadoc 1.2.2
  • What's New in Javadoc 1.2

Javadoc Tool Reference Page

References pages listing all javadoc tags and command-line options. Shows how to run the Javadoc tool, with examples in Solaris and Microsoft Windows.
  • Javadoc 1.4.2 Tool Reference Page (Solaris)
  • Javadoc 1.4.2 Tool Reference Page (Microsoft Windows)

Doclet API

  • Doclet Overview - Provides an introduction to doclets with simple examples that illustrate the Doclet API.
  • Doclet API - Documentation for the com.sun.javadoc package, which comprises the Doclet API.

Taglet API

  • Taglet Overview - Provides an introduction to taglets with simple examples that illustrate the Taglet API.
  • Taglet API - Documentation for the com.sun.tools.doclets.Taglet class, which comprises the Taglet API.

Doclets

  • Standard Doclet - the doclet that produces the default HTML-formatted API documentation. Javadoc uses the standard doclet if no other doclet is specified with Javadoc's -doclet option.

  • MIF Doclet - Experimental - generates API documentation in MIF (Maker Interchange Format). These MIF files can then be opened in Adobe FrameMaker (or fmbatch) and optionally converted to PDF, PS, Microsoft RTF, Microsoft Word or WordPerfect. Not included in Java 2 SDK.

  • DocCheck Doclet - Experimental - reviews Javadoc comments in the source code, identifying gaps and irregularities, and producing an HTML report that displays serious and trivial problems and suggests changes.

  • Third Party Doclets - Developed outside of Sun.

Let Us Know about Your Doclets
We'd like to know about doclets that you create. If you would like us to consider adding a link from the doclets page to your doclet's output, send the URL to email address javadoctool at sun.com.

For More Information

Located on the Java Software website:
  • Javadoc FAQ - Important tips and workarounds for bugs.
  • Javadoc Forum - Enter into discussions with fellow developers. You must join the Java Developer Connection (free) to take part. Click on "Javadoc Tool" category. This forum is monitored only occasionally by the Javadoc team. If you want a prompt reply from the Javadoc team, use the email address below.
  • Submitting Bugs:
    1. What Bugs Are in Javadoc? - Please see if your bug or feature request is already in our database:
    2. How Do I Submit Bugs and Feature Requests? - Then submit your bugs and feature requests according to these instructions.
  • Javadoc announcements email group - A public one-way mailing list you can subscribe to for receiving major announcements about Javadoc tool, the standard doclet, the MIF doclet, the DocCheck doclet, the localization doclet, and others. Traffic should be light.
  • Email Address for the Javadoc Team - While we read all comments, and try to reply to every one, replies are not guaranteed.
  • Javadoc Tool Home Page - Covers all versions of the Javadoc tool.

Copyright © 1997-2002 Sun Microsystems, Inc. All Rights Reserved.
Please send comments to: javadoctool at sun.com 		Sun


Doclet Overview

Contents

  • The Basics
  • A Simple Example Doclet
  • Example - Subclassing the standard doclet
  • Example - Creating and handling custom tags
  • Example - Using custom command-line options

The Basics

Doclets are programs written in the JavaTM programming language that use the doclet API to specify the content and format of the output of the Javadoc tool. By default, the Javadoc tool uses the "standard" doclet provided by SunTM to generate API documentation in HTML form. However, you can supply your own doclets to customize the output of Javadoc as you like. You can write the doclets from scratch using the doclet API, or you can start with the standard doclet and modify it to suit your needs.

Here are the basic steps you need to follow to create and use your own doclet:

  1. Write the Java program that constitutes your doclet. Your program should import com.sun.javadoc.* in order to use the doclet API. The entry point of your program is a class with a public static boolean start method that takes a RootDoc as a parameter.
  2. Compile your doclet. You can use the compiler in the Java 2 SDK, javac.
  3. Run the javadoc tool using the -doclet startingclass option to produce the output specified by your doclet, where startingclass is the fully-qualified name of the starting class mentioned in step 1 above.
The doclet API class files are in the lib/tools.jar file in the SDK. When you compile a doclet, the tools.jar must be on the class path. You can use the -classpath option on javac for this purpose.

If you run javadoc without the -doclet command-line option, it will default to the standard doclet to produce HTML-format API documentation.

Package com.sun.javadoc consists of interfaces that define the doclet API. The lib/tools.jar file in the Java 2 SDK contains these interfaces and also a private package with classes that implement the interfaces. The tools.jar file also contains the classes implementing the standard doclet.

A Simple Example Doclet

You can get a feeling for the way doclets work by looking at this simple example doclet that consists of one short class:
import com.sun.javadoc.*;

public class ListClass {
    public static boolean start(RootDoc root) {
        ClassDoc[] classes = root.classes();
        for (int i = 0; i < classes.length; ++i) {
            System.out.println(classes[i]);
        }
        return true;
    }
}
As you might be able to guess by looking at the code, this doclet takes the classes upon which Javadoc is operating and prints their names to standard out.

This first thing to notice about the doclet is that it imports the com.sun.javadoc package in order to use the doclet APIs. As with all doclets, the entry point is the public static boolean start method. The start method takes a RootDoc as a parameter. This parameter carries information about any options specified on the command line when javadoc is run, and also about the classes and packages upon which javadoc is operating.

RootDoc defines a classes method that returns a ClassDoc array whose elements represent the classes that Javadoc parses. The for loop then prints out the names of each class in the array. (Passing a ClassDoc to println results in the printing of the name of the class that the ClassDoc represents.)

To run this doclet, you first have to compile it. You can compile it with the javac compiler. The doclet API classfiles are in the file lib/tools.jar in the Java 2 SDK which javac does not automatically load. You therefore need to include tools.jar on the compiler's classpath, as in this example:

javac -classpath C:\jdk1.3\lib\tools.jar ListClass.java
To run the ListClass doclet, you point to the compiled doclet with Javadoc's -doclet and -docletpath tags. For example, to run the doclet on a file called MyClass.java, you could use this command, assuming ListClass.class is in the current directory:
% javadoc -doclet ListClass -docletpath .  MyClass.java
The output will be the string "MyClass". Note that this command does not require tools.jar to be on the class path, as the Javdoc tool automatically loads it.

A note about command-line options: If you run javadoc -help, you'll see that the Javadoc tool has two sets of command-line options. One set is generic and will work with any doclet. The second set of options is special to the standard doclet. Options in this second set will not be available when using custom doclets. Your custom doclets can also define their own command-line options. See the example below.

To generate API documentation, a doclet will have to be considerably more complex than this simple example. If you want to customize the format of the API documentation generated by Javadoc, you may want to start with the default standard doclet and modify it as necessary rather than write your own doclet from scratch.

Example - Subclassing the Standard Doclet

To customize the output of the Javadoc tool, you need to write your own doclet that specifies the content and format of the output that you desire. If you want HTML output with roughly the same format as the default output, you can use the standard doclet as a starting point for creating your doclet. You can subclass appropriate classes in the standard doclet and then add or override methods as necessary to produce the output you want. Or you can copy the whole standard doclet and modify it. If you use a copy of the standard doclet as your starting point, you may want to remove the package statements at the beginning of each source file and replace them with the name of your own, new package.

For an example, see How can I modify the standard doclet to produce links to source code from the API documentation? Please send any corrections to javadoc-tool@sun.com.

Example - Creating and handling custom tags

Suppose, for example, that you want use a custom tag, say @mytag, in your documentation comments in addition to the standard tags like @param and @return. To make use of the information in your custom tags, you need to have your doclet use instances of Tag that represent your custom tags. One of the easiest ways to do that is to use the tags(String) method of Doc or one of Doc's subclasses. This method returns an array of Tag objects representing any tags whose name matches the string argument. For example, if method is an instance of MethodDoc, then
method.tags("mytag")
would return an array of Tag objects representing any @mytag tags in the method's documentation comment. You can then access the information in your @mytag tags with Tag's text method. That method returns a string representing the content of the tag which you can parse or use as needed. For example, if a documentation comment contained one of your custom tags like this:
@mytag Some dummy text.
then the text method would return the string "Some dummy text.".

Here's a standalone doclet (not a subclass of the standard doclet) that uses these ideas to print out the text associated with all instances of a specified tag that it finds in method comments. It could be extended to find all instances of that tag in all comments.

import com.sun.javadoc.*;

public class ListTags {
    public static boolean start(RootDoc root){
        String tagName = "mytag";
        writeContents(root.classes(), tagName);
        return true;
    }

    private static void writeContents(ClassDoc[] classes, String tagName) {
        for (int i=0; i < classes.length; i++) {
            boolean classNamePrinted = false;
            MethodDoc[] methods = classes[i].methods();
            for (int j=0; j < methods.length; j++) {
                Tag[] tags = methods[j].tags(tagName);
                if (tags.length > 0) {
                    if (!classNamePrinted) {
                        System.out.println("\n" + classes[i].name() + "\n");
                        classNamePrinted = true;
                    }
                    System.out.println(methods[j].name());
                    for (int k=0; k < tags.length; k++) {
                        System.out.println("   " + tags[k].name() + ": "
                            + tags[k].text());
                    }
                }
            }
        }
    }
}
The tag for which this doclet searches is specified by the variable tagName. The value of the tagName string can be any tag name, custom or standard. This doclet writes to standard out, but its output format could be modified, for example, to write HTML output to a file.

Example - Using custom command-line options

 You can write doclets that accept custom command-line options. To see how that works, let's augment the example doclet above so that it allows you to use a command-line option to specify the tag name to search for.

Any doclet that uses custom options must have a method called optionLength(String option) that returns an int. For each custom option that you want your doclet to recognize, optionLength must return the number of separate pieces or tokens in the option. For our example, we want to be able to use the custom option of the form -tag mytag. This option has two pieces, the -tag option itself and its value, so the optionLength method in our doclet must return 2 for the -tag option. The optionsLength method should return 0 for unrecognized options.

Here's the full, augmented doclet:

import com.sun.javadoc.*;

public class ListTags {
    public static boolean start(RootDoc root){
        String tagName = readOptions(root.options());
        writeContents(root.classes(), tagName);
        return true;
    }

    private static void writeContents(ClassDoc[] classes, String tagName) {
        for (int i=0; i < classes.length; i++) {
            boolean classNamePrinted = false;
            MethodDoc[] methods = classes[i].methods();
            for (int j=0; j < methods.length; j++) {
            Tag[] tags = methods[j].tags(tagName);
            if (tags.length > 0) {
                if (!classNamePrinted) {
                    System.out.println("\n" + classes[i].name() + "\n");
                    classNamePrinted = true;
                }
                System.out.println(methods[j].name());
                for (int k=0; k < tags.length; k++) {
                    System.out.println("   " + tags[k].name() + ": " + tags[k].text());
                }
            }
        }
        }
    }

    private static String readOptions(String[][] options) {
        String tagName = null;
        for (int i = 0; i < options.length; i++) {
            String[] opt = options[i];
        if (opt[0].equals("-tag")) {
            tagName = opt[1];
        }
        }
    return tagName;
    }

    public static int optionLength(String option) {
        if(option.equals("-tag")) {
        return 2;
        }
        return 0;
    }

    public static boolean validOptions(String options[][],
                       DocErrorReporter reporter) {
    boolean foundTagOption = false;
        for (int i = 0; i < options.length; i++) {
            String[] opt = options[i];
            if (opt[0].equals("-tag")) {
            if (foundTagOption) {
                reporter.printError("Only one -tag option allowed.");
            return false;
            } else {
            foundTagOption = true;
        }
        }
    }
    if (!foundTagOption) {
        reporter.printError("Usage: javadoc -tag mytag -doclet ListTags ...");
    }
    return foundTagOption;
    }
}
In this modified doclet, the variable tagName is set with the command-line option -tag. It has a optionLength method returns two for our custom option. Note that an explicit call to optionLength isn't required.

This doclet also adds the readOptions methods that actually parses the command-line options looking for the -tag option. It makes use of the fact that the Rootdoc.options method returns a two-dimensional String array containing option information. For example, given the command

javadoc -foo this that -bar other ...
the RootDoc.options method will return
options()[0][0] = "-foo"
options()[0][1] = "this"
options()[0][2] = "that"
options()[1][0] = "-bar"
options()[1][1] = "other"
The number of elements in the array's second index is determined by the optionLength method. In this example, optionLength returns 3 for option -foo and returns 2 for option -bar.

The validOptions method is an optional method that you can use to test the validity of the usage of command-line tags. If the validOptions method is present, it is automatically invoked; you don't have to explicitly call it. It should return true if the option usage is valid, and false otherwise. You can also print appropriate error messages from validOptions when improper usages of command-line options are found. The validOptions method in this example doclet checks that the -tag option is used once and only once.

Copyright © 1995-98 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: 		Sun


Doclet Overview

Java

The Standard Doclet

 Javadoc 1.4

Contents

  • What the Standard Doclet Is
  • Classes in the Standard Doclet
  • 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 SunTM that produces Javadoc's default HTML-formatted API output. The API documentation for the JavaTM platform in this SDK 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.

The classes listed below are part of the internal implementation of the standard doclet, subject to change without notice from version to version -- they are not an API. These classes are published here as a good example of the use of much of the doclet API. Also, by seeing how the standard doclet produces the default HTML output, it will be easier for you to modify the standard doclet to make your own doclet for generating custom API documentation.

The next version of the standard doclet will be written to a Doclet Toolkit API that we will support.

Classes in the Standard Doclet

The standard doclet is composed of the classes in the com.sun.tools.doclets, com.sun.tools.doclets.standard and com.sun.tools.doclets.standard.tags packages. Classes in the standard doclet that play key roles in generating the default HTML output are summarized here:

Important - These classes are part of the internal implementation of the standard doclet, and are subject to change without notice from version to version -- they are not an API. Use them at your own risk.
com.sun.tools.doclets
  • HtmlWriter - This class contains code for writing the various HTML tags needed for generating any output in HTML form.
  • HtmlDocWriter - This class extends HtmlWriter, and contains additional HTML-related code for producing the specialized hyperlinks used in the default HTML output, including links in the headers and footers of the HTML pages.
  • Taglet - An interface that represents a class used to format the ouput of a tag. You can develop a Taglet to format the output of your custom tags. For more information about Taglets, please see the taglet overview.
  • TagletManager - This class manages the Taglets being used by the doclet. It has methods for registering Taglets, retrieving Taglets and checking whether or not a tag is known by the TagletManager (used for error checking). The TagletManager also checks for tags that are used in the wrong places. For example, a warning message is printed if a @param tag is used in class documentation because that tag should only be used in constructor and method documentation.
com.sun.tools.doclets.standard
  • Standard - This class contains the start method and hence serves as the entry point for the standard doclet. It orchestrates the generation of the HTML API files for the packages and classes upon which javadoc is operating.
  • PackageIndexWriter - This class generates the overview-summary.html file that lists all packages specified on the javadoc command line. As an example, see the overview-summary.html file in the API documentation.
  • PackageIndexFrameWriter - This generates the overview-frame.html file used for displaying the list of package links in the upper-left frame in the frame-formatted default output. See the overview-frame.html file in the API documentation of this release of the J2SE documentation.
  • PackageFrameWriter - This generates the package-frame.html file that lists the interfaces and classes in a given package for displaying in the lower-left frame of the frame-formatted default output. As an example of this type of page, see the package-frame.html file for java.awt in the API documentation of this release of the platform API documentation.
  • FrameOutputWriter - This generates the index.html file used for presenting the frame-formated "cover page" of the API documentation. See the index.html file from the platform API documentation as an example.
  • PackageWriter - This generates the package-summary.html files that list the interfaces and classes for a given package. For an example of this type of page, see the package-summary.html page for java.lang in the API documentation of this release.
  • ClassWriter - This generates the HTML API documentation for each individual interface and class. For an example from the Java 2 Platform API documentation, see Font.html.
  • SingleIndexWriter - This generates the single index file of class members that the standard doclet produces when the -splitindex option is not used.
  • SplitIndexWriter - This generates the mutliple index files for the class members that is generated when the Javadoc runs the standard doclet with the -splitindex command-line option. The files are numbered such as index-1.html.
  • TreeWriter - This class generates the overview-tree.html file that lists the Class Hierarchy for the classes upon which the standard doclet operates. For an example from the Java 2 Platform API documentation, see overview-tree.html.
  • DeprecatedListWriter - This generates the file deprecatedlist.html which lists deprecated APIs. As an example, see the deprecated-list.html file from the API documentation in this release.
  • ClassUseMapper, ClassUseWriter, and PackageUseWriter - These classes generate the "Use" files for classes and packages. Click the "Use" link in the navigation bar to go to a class or package "use" page. Examples of such pages are those for class Character and package java.lang.
  • PackageListWriter - generates the package-list text file that gets placed in the top-level directory of the API documetation. This file is required for use with standard doclet's -link command-line option. Standard doclet class Extern also plays a role in making the -link option work. See the Javadoc reference pages ([Windows] [Solaris]) for details about this option.
  • Group - This class handles the grouping of packages in one or more tables on the overview-summary.html page. It supports the standard doclet's -group command-line option. See the Javadoc reference pages ([Windows] [Solaris]) for details about this option.
com.sun.tools.doclets.standard.tags
  • AbstractExecutableMemberTaglet - This is an abstract Taglet that formats the output for a tag used in documentation for executable members.
  • AbstractInlineTaglet - This is an abstract Taglet that formats the output for an inline tag. You should subclass this abstract class if you would like to create your own custom inline tag.
  • DocRootTaglet - A taglet that formats the output for {@docRoot}.
  • InheritDocTaglet - A taglet that formats the output for {@inheritDoc}.
  • ParamTaglet - A taglet that formats the output for @param.
  • ReturnTaglet - A taglet that formats the output for @return.
  • SeeTaglet - A taglet that formats the output for @see.
  • SimpleTaglet - A taglet that formats the output for single argument tags such as @author and @version.
  • ThrowsTaglet - A taglet that formats the output for @throws.
  • ValueTaglet - A taglet that formats the output for {@value}.
For more information about Taglets, please see the taglet overview.

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/j2sdk1.4.0/lib/tools.jar \
  -doclet com.sun.tools.doclets.standard.Standard \
  myPackage

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 2 SDK, 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 2 SDK at:
  • Java 2 SDK v1.4 Source Code Release
    (Note: There is a delay between when the J2SE SDK is available and the source code release is available.)
The source files are located in the directory src/share/classes/com/sun/tools/doclets.

Copyright © 1995-98 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: javadoc-tool@sun.com 		Sun


What's New in Javadoc 1.2

 Javadoc Enhancements

This document describes the changes made to Javadoc between versions 1.1 and 1.2. It is divided into sections for three types of users: (1) for writers of doc comments, (2) for developers wanting to write doclets (architecture and the Doclet API), and (3) for readers of the javadoc-generated HTML pages (content and format). Further details are given in the "Detailed Changes" section that follows.

SUMMARY OF CHANGES

This summary includes changes for writers of doc comments, changes to the Javadoc tool (the Doclet API) and changes to the content and format of the HTML output of Javadoc (as implemented in the Standard Doclet).

WRITING DOC COMMENTS

Changes for Writing Doc Comments

The following list summarizes in one place all features listed elsewhere that can have an impact on how you would write doc comments.
  • The first sentence of each class description should be a summary statement.
  • Package-level comments are now possible.
  • The first sentence of each package description should be a summary statement.
  • System-wide (overview) comments are now possible.
  • New Javadoc tags are available for use in doc comments.
  • Copies new "doc-files" directory for holding images and examples.
  • Hierarchical destination file structure
  • Possible incompatibilities between 1.1 and 1.2 doc comments

ARCHITECTURE

Doclet API

  • Javadoc now has a Doclet API to which you can write doclets.

CONTENT

New Tags

  • @throws is a synonym for @exception.
  • @see now accepts packages, HTML anchors and quoted strings. It can also take a label.
  • {@link apiname label} is a new tag for in-line links in text.

Provides more API information and links

  • Includes mechanisms for package-level and document-level information.
  • Incorporates one-line summaries for classes and packages like there have been for members.
  • Includes inherited API on class and interface pages.
  • Includes return types in method summaries, and field data types in field summaries.
  • Includes links to interfaces from members that implement that interface.
  • Includes list of subclasses for each class, and implementing classes for each interface.
  • Copies member descriptions from interfaces to implementing classes.
  • Includes a class hierarchy (tree) view for each package.
  • Introduces -link option for linking to external Javadoc-generated documents.
  • Includes list of deprecated API.
  • Omits the keywords native and synchronization (which are not part of the Java spec).
  • Copies new "doc-files" directory for holding images and examples.

Customizable title, header and footer

  • Introduces options for adding a unique title, header, footer, and bottom note. The bottom note is for information like a copyright notice and mailto link.

FORMAT

Image files

  • No longer relies on images for headings and bullets. Instead it uses table cells and horizontal rules to distinguish headings and API.

Style sheet

  • Add HTML style sheets for control of colors, fonts and positioning.

Improved navigation

  • Adds optional HTML frames for lists of packages and classes. You can show or hide these frames with a single click.
  • Navigation bar is now the same from screen-to-screen.
  • Renames "API Users Guide" to "Help".
  • Changes the term "index" to "summary" in headings of class pages for member summaries.
  • Better distinguishes the summary and detail sections from each other.

Index improvements

  • Option exists to break index up to one file per initial character.
  • Index is internationalized to handle Unicode characters.
  • Index now contains the classes and interfaces.

Hierarchical Destination File Structure

  • Change the destination directory from flat to hierarchical. (new in Beta4)

GENERAL

Incompatibilities

  • Describes possible incompatibilities when running Javadoc 1.2 on 1.1 comments

Other Doclets

  • Maintains the ability to generate Javadoc 1.1 HTML output, for those who want it.
  • [Future] Adds the ability to generate MIF output, for importing into FrameMaker.

Future Enhancements After 1.2

  • Allow for incremental builds contributing to a single Javadoc-generated document.

DETAILED CHANGES

These are the detailed changes made to Javadoc from 1.1 to 1.2. Features denoted as "Done" are implemented and tested in 1.2 Beta 4.

CHANGES FOR WRITING DOC COMMENTS

Javadoc 1.2 has the following new requirements and features you should be aware of when writing documentation comments:
The first sentence of each class description should be a summary statement.
Package-level comments are now possible.
The first sentence of each package description should be a summary statement.
System-wide comments are now possible.
New Javadoc tags are available for use in doc comments.
Copies new "doc-files" directory for holding images and examples.
Hierarchical destination file structure
Possible incompatibilities between 1.1 and 1.2 doc comments

ARCHITECTURE - DOCLET API

Javadoc now has a Doclet API to which you can write doclets. This is a major architectural change to Javadoc.
You can use Javadoc doclets to customize Javadoc output. Think of a doclet as a plug-in for text conversion. A doclet is written written to the doclet API to specifies the content and format of the output to be generated by the Javadoc tool. You can write a doclet to generate any kind of text-file output, such as HTML, SGML, XML, RTF, and MIF. Sun provides a "standard" doclet for generating HTML-format API documentation. Doclets can also be used to perform special tasks not related to producing API documentation. For example, a diagnostic doclet could be created to check that all members have documentation comments.

Motivation for New Architecture - The original Javadoc (in 1.0.x and 1.1.x) takes java source files as input and produces HTML as output. The format of the HTML output is hard coded in java. The disadvantage is that developers who want to customize the output are out of luck, unless they have a source license and want to hack some very arcane code. This means technical writers cannot make enhancements they might need, whether minor (such as capitalizing a word, changing color, adding bold, ...) or major (converting to a new format, such as MIF or RTF).

The requirements for the Javadoc re-architecting were:

  • Separate the mechanisms used to parse and process the input source from the specification of the output format.

  • Make the output format specification pluggable.

  • Make the output format specification as comprehensible as possible to tech writers.
New architecture: The javadoc front-end handles command line arguments and java parsing/processing, constructing a root data structure and passes this off to a java "doclet". The doclet would access this data via an API representing packages, classes, methods, fields, and comments, as well as enumerations of these objects. New doclets could be written to this API, or standard doclets could be subclassed to allow minor changes.

CONTENT - NEW TAGS

These tags are actually implemented in the javadoc API, not in the standard doclet.
New tag "@throws" is a synonym for "@exception". This is a convenience, since "throws" is a keyword in the Java language.

Existing tag "@see" now accepts packages, HTML anchors and quoted strings. It can also take a label. An @see tag can refer to a package just like it can refer to a class, method or other API. The HTML anchor is of the form <a href="xxx">XXX</a> and the quoted string is of the form "xxx". For examples, see Javadoc Reference Page. The label is optional and is of the form: "@see name label". If a label is included, it will be displayed instead of the name.

New tag "{@link apiname label}" is for in-line links in text. In previous versions of Javadoc, the only way to include links to API was to use the @see tag or to hard-code HTML. This new in-line tag uses the same algorithm that @see uses to generate the HTML link. The difference is that it places the link in-line rather than under a "See Also" heading.

CONTENT - PROVIDES MORE API INFORMATION AND LINKS

Add to source tree one file per package, named "package.html", dedicated to doc comments. The first sentence of each package description is the summary. Javadoc picks up everything between <body> and </body> and add it to the package summary page "package-summary.html" (which also contains a table of its classes and interfaces). Javadoc copies the first sentence of this to the overview page "overview.html". Therefore, you should not put a title or any other text between <body> and the first sentence.

Outline for package-level comments:

  • Introduction
  • Package Specification
  • Related Documentation

For more information, see Package Level Comments.

Old Behavior: Javadoc 1.1 has no mechanism for including comments specific to a particular package.
NOTE - The above feature requires writers to follow a new Javadoc rule: The first sentence of each package description should be a summary statement.

Add a single system-wide document "overview.html" for the set of packages. Include in it any comments that apply to the all the packages being documented. For example, you might document the following assumption on this page: "NullPointerException is thrown wherever null is passed in, except as noted."

This file belongs in your source tree and can be any filename you specify. By convention, we use the name "overview.html". Specify this filename with the -overview option on the command line when running Javadoc and the file's contents (between the <body> and </body> tags) is inserted into the initial page that appears in the right-hand frame, named overview-summary.html (which was called packages.html in Beta3 and earlier versions).

Old Behavior: Javadoc 1.1 has no mechanism for including comments that apply to all packages.

Javadoc picks up the first sentence one-line summary for each package from package.html and puts it in packages.html. This provides a brief summary of each packages in the list of all packages.
Old Behavior: Javadoc 1.1 has no such summary list.

Pick up the first sentence of each class description and include it in the class summary at package-<class>.html This provides a brief summary of all classes for a given package.
Old Behavior: Javadoc 1.1 has no such summary list.
NOTE - The above feature requires writers to follow a new Javadoc rule: The first sentence of each class description should be a summary statement.

Add inherited API to method and field summaries on class and interface pages.
Old Behavior: In Javadoc 1.1, the inherited members for a given class do not appear on the class page, necessitating following links to discover them.

Include return type and keywords "static", "protected" and "abstract" in the signature in the method summary, since they are needed by someone calling a method. Do not include public, transient, volatile, or final; those appear in the detail section further down the page. Include data type of fields.
Old Behavior: In Javadoc 1.1, method summaries don't indicate the return type. Field summaries don't indicate the field type.

Add "Specified by" for members that implement an interface.
Old Behavior: In Javadoc 1.1, members of a class that implement an interface make no such mention.

Add the list of subclasses at the top of the class page. Also add the subinterfaces and implementing classes at the top of the interface pages.
Old Behavior: Javadoc 1.1 does not list subclasses on a class page.

Copy the description automatically from the method in an interface to its implementing subclass only when the implementing method contains no text. Include a boilerplate statement that says that the text is copied from the interface. The reason for doing this, is that when implementing an interface, the method descriptions are often identical for both the interface and the class. Copying the descriptions manually seems like needless work that is difficult to maintain.
Old Behavior: Javadoc 1.1 does not copy method descriptions from an interface.

Add a tree view for each package. When you are viewing a package or class, the "Tree" link goes to that view, which then has a link to the tree for all packages.
Old Behavior: Javadoc 1.1 has no tree view (class hierarchy) of single packages. The only tree view is of all packages, which, for the JDK, is overwhelming.

Introduce -link option for linking to external Javadoc-generated documents. Default is to not link to external documentation. When someone generates docs, the -link option generates links to documentation for any API referenced by the API being documented. The links can be local or remote (on the Internet).
Old Behavior: Javadoc 1.1 makes no links to documentation outside what is being generated.

Submit bugs against default constructors that should not be documented by Javadoc. We should either deprecate them or remove them as bugs.
(Does not affect Javadoc)
Old Behavior: Javadoc includes all default constructors, whether or not an application developer would ever call them. When it documents default constructors, it leaves their descriptions blank.

Add a deprecated summary page listing all deprecated API. (Eventually we will add links to the replacement API.)
Old Behavior: Javadoc 1.1 does not generate a list of deprecated API.

Mark classes that are deprecated.
Old Behavior: In Javadoc 1.1, deprecated classes are not marked as such in the class list for a given package.

Remove "synchronized" and "native" from signatures. Javadoc generates an API specification. These two keywords do not belong in the signatures of a specification, because they are implementation-specific. The keyword "native" does not need to be documented. The keyword "synchronized" indicates thread-safe behavior that should instead be described in the method descriptions. A thread-safe method itself might not use the "synchronized" keyword but might call private methods that are.
Old Behavior: Javadoc 1.1 includes the keywords "synchronized" and "native".

Copy "doc-files" directory (one per package) for holding images and examples. Javadoc looks for a directory named "doc-files" in each package directory of the source tree and copies that directory and its contents to the destination. The files in "doc-files" are merely copied to the destination and not processed by Javadoc. This means these files cannot contain the standard navigation bar, header or footer, or be included in the index or tree. This directory can contain arbitrary files referenced by doc comments. Examples: images, HTML files, text files, example source code, HTML tables shared by more than one class.

Example: To include a reference to the image file "Button-1.gif" within the description for the java.awt.Button class:

  • In the source tree, create a directory named "doc-files" in the "java/awt/" directory.
  • Put the "Button-1.gif" file in the "doc-files" directory.
  • Add an <img> tag to your doc comment for the Button class:
       /**
    * <img src="doc-files/Button-1.gif">
    */
Java Software has adopted the naming convention starting with "-1" and incrementing for subsequent images. For more details, see Including Images.
Old Behavior: In Javadoc 1.1, running Javadoc generates files with broken links because images are not copied to the destination. (In the JDK, these images are currently mostly screen shots of AWT and Swing components.)

CONTENT - CUSTOMIZABLE TITLE/HEADER/FOOTER

Add the -title option to include a title to first page "packages.html". Example title: "Java Platform 1.2 Core API".
Old Behavior: Javadoc 1.1 has no formal way to add a title to the generated document.

Add -header, -footer, -bottom options for header/footer/bottom on every page. This enables you to put the version number of the API (such as "Java 1.2 Beta 4") on every page so that when you print out a page, you have a record of the version it came from. The "bottom" feature lets you add a copyright notice or feedback email link at the bottom of each page.
Old Behavior: In Javadoc 1.1, the version number by default does not appear on any page.

CONTENT - NO LINKS TO SOURCE FILES

For internal development, having direct links from each Javadoc-generated class page to its source code would be handy. However, we have decided not to include links in the Java API documentation to the Java source code when we generate and publish our API documentation. Hence it becamse a low priority to put that feature into the standard doclet. However, we have made available separately a doclet that generates links to the source code.

FORMAT - IMAGE FILES

Eliminate any required GIF images. Replace the GIF bullets with horizontal rules. Replace the graphic headings (e.g., "Methods", "Fields") with text inside colored table cells.
Old Behavior: Javadoc 1.1 requires GIF images for bullets and headers. These are not necessary, they slow down the display, and they need to be manually copied to the destination.

FORMAT - STYLE SHEET

Add HTML style sheets for control of colors, fonts and positioning. Style sheets are a standardized way of setting the colors, fonts and positioning of text on web pages at runtime. To modify the colors of the table cells or the font sizes in the left-hand frames, modify the file stylesheet.css that is generated by javadoc. There is also a -stylesheetfile option when running javadoc for specifying your own style sheet.

For example, you can change the background cell color of the headings from dark blue to white by editing the file stylesheet.css as follows.

From:

   #TableHeadingColor     { background: #CCCCFF } /* Dark mauve */
To:
   #TableHeadingColor     { background: #FFFFFF } /* Dark mauve */

For a formal description, see Cascading Style Sheets from W3C. For a more practical description, see CSS Reference Table from CNET. (For an introduction, click on "back to intro" from the CSS Reference Table.)

FORMAT - IMPROVED NAVIGATION

Add frames for package, class and member. (For no frames, start at "package-summary.html". For frames, start at "overview-summary.html")
Old Behavior: Javadoc 1.1 has no easy way to access any package, class or member. It requires users to backtrace.

Add "All classes" link to top of package list (upper left frame). When user clicks this, it should display list of all classes in alphabetic order in lower left-hand frame.
Old Behavior: Javadoc 1.1 has no easy way to access any class, regardless of the package it is in. It requires users to go to "Class Hierarchy". It would be nice to have a list of just classes and interfaces.

Develop a single navigation bar that works in all screens. Dim out the unused items.
Old Behavior: In Javadoc 1.1, the standard navigation bar along the top changes dramatically from page to page. There are three different navigation bars: all packages (2 items), a package (3 items), and a class (6 items).

Add another navigation bar to jump to each subsection.
Summary: Inner | Field | Constr | Method Detail: Field | Constr | Method
Old Behavior: Javadoc 1.1 requires you to scroll past the class description to get to the member summaries and detail.

Rename the "API Users Guide" link to "Help". Modify Javadoc to generate a default help file. Add an option -nohelp to omit the "Help" link from the navigation bar if desired. Add an option -helpfile to create a file
Old Behavior: Javadoc 1.1 has a link in packages.html called "API Users Guide". The file it points to is not automatically copied to the destination directory.

HTML frame for members in Javadoc 1.2. This is a feature we had considered adding to the standard doclet but decided not to. We plan to announce a third-party developer to eventually release this feature in a separate doclet.

FORMAT - WEB PAGES

Change the summaries to tables with borders and cell background color. This better distinguishes between summary and detail portions of class files.
Old Behavior: In Javadoc 1.1, both the summary and detail portions both look quite similar, it's not obvious when scrolling down the page which section you are in.

Keep "Index" as the name of the alphabetized list of API at the end of the document. Rename top portion of each package page from "Package Index" to "Package Summary", likewise for top portion of each class page rename "Method Index" to "Method Summary", "Constructor Index" to "Constructor Summary", and "Field Index" to "Field Summary".
Old Behavior: In Javadoc 1.1, the word "index" is used to identify both summaries at the top of class pages, and the alphabetic book-type list containing all the API. This is needlessly confusing.

FORMAT - INDEX IMPROVEMENTS

Add -breakindex option to break the index into a separate file for each letter of alphabet.
Old Behavior: In Javadoc 1.1, the index is a gigantic 1.4MB file for JDK; takes forever to load over Internet.

Add classes and interfaces to the index.
Old Behavior: In Javadoc 1.1, the index lists only constructors and members, not classes or interfaces.

Internationalize the index, to enable any Unicode characters.
Old Behavior: In Javadoc 1.1, the index handles only the alphabet A-Z. (Actually, only A-Y.)

FORMAT - HIERARCHICAL DESTINATION FILE STRUCTURE

Add hierarchical destination directories that replicates the source code tree of one directory per subpackage. Flat structure will no longer be supported. This has the effect of reducing the number of files in a directory by distributing them by package. A side effect is to reduce length of filenames, since package names will be directory names rather than part of the filename. This will make it easier for third parties to generate shorter names (for example, 31-character names for the Macintosh) that retain some meaning.

For example, java.awt.Button.html will now be \java\awt\Button.html Given all the 1.2 changes, the destination file structure for running Javadoc on the java.applet package would now look like file structure.

Old Behavior: Javadoc 1.1 uses a flat structure, where all HTML files sit in a single directory.

INCOMPATIBILITIES

Possible incompatibilities between 1.1 and 1.2 doc comments We have been careful to write Javadoc 1.2 to be compatible with documentation comments written for previous versions of Javadoc. However, there may be a few cases where old documentation comments may not "work" the same when compiled with Javadoc 1.2.

  • Many filenames have changed. The most important change is that the initial page of the generated documentation is now index.html (which sets up HTML frames) instead of packages.html. If you want to avoid frames, the initial page to load is overview-summary.html (which replaces packages.html in 1.1).

  • In the text of comments, writers might have hard-coded in-line links to API names. Because javadoc now generates hierarchical directories, those links would now be broken. The new {@link} tag enables proper in-line links.

OTHER DOCLETS

Maintain Javadoc 1.1 format with its own doclet. This keeps the old look and flat directory structure but with some of the new bug fixes. To access this, use the "-1.1" javadoc option
Old Behavior: - The Javadoc 1.1 format is important for those who has built parsers that operate on and rely on that HTML output.

[Future] Implement a MIF doclet. This will add the ability to generate MIF output, for importing into FrameMaker.
(Plan to do and release separately after 1.2.)
Old Behavior: Javadoc 1.1 has no MIF capability (Javadoc 1.0.2 does).

FUTURE ENHANCEMENTS - TO DO IN A RELEASE AFTER 1.2

Allow for incremental builds contributing to a single Javadoc-generated document. Would be useful to save the intermediate format from each Javadoc run and allow merging of those intermediate formats into a complete document, with fully correct index, tree, class hierarchy, subclasses list, etc.
(Not done - planned for a release after 1.2)
Old Behavior: Javadoc 1.1 does not allow incremental building of documentation.

Copyright © 2001 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software

Please send comments to: javadoc-tool@sun.com


What's New in Javadoc 1.3

 Javadoc Enhancements

This document describes the changes made to the Javadoc tool between versions 1.2.2 and 1.3.

New Features

Added {@docRoot} - This is a new Javadoc tag that represents the path from any class page up to the root directory of the generated documentation hierarchy. The purpose of this tag is to allow you to make a link to a single web page from all generated pages, such as to a copyright page or corporate logo from the footers of all generated pages. (This tag was broken in 1.3 Beta) (Request #4197510)

MIF doclet. This adds the ability to generate MIF output, for importing into FrameMaker and eventual conversion to PDF, PS, RTF, Word, or WordPerfect.
IMPORTANT - The MIF doclet is not included in the Java 2 SDK. You must obtain it separately from: MIF Doclet download page

Bug Fixes

4260169: Added <code> HTML tag to "Overrides", "Specified By" and "Tags copied from".

4276757: Fixed Javadoc to document inherited public members of package-private classes.

4214932: Fixed bug where private fields/methods were documented as inherited.

4216836: The "Specified by:" link has been added for a method in an interface implementing a method from a superinterface.

4227539: We now list interfaces found walking all the way up the hierarchy tree. For interfaces, added "All superinterfaces: A, B, C". For classes, added "All implemented interfaces: A, B, C".

4233601: In inner class summary, fixed bug where Exceptions were mistakenly listed as Interfaces.

4216434: Fixed Javadoc -help option which didn't print all the options (-helpfile, -stylesheetfile).

4235271: Fixed bug where overriding method in Interface is now shown as "Specified By".

4231274: Added a missing space ahead of parenthetical phrase "(also extends...)"

4285930: Changed second argument of -linkoffline so that if supplying a relative path, you should make it relative to the destination directory (supplied with -d) rather than relative to the current directory from where javadoc is run.

Future Enhancements

To possibly do in a release after 1.3
XML Doclet - for a standardized representation of static program information of a set of packages. This might possibly allow developers to incrementally build a single document from separate Javadoc runs. By saving the intermediate representation from each Javadoc run, it would allow merging of those into a complete document, with fully updated index, tree, class hierarchy, subclasses list, etc.

Copyright © 2001 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software

Please send comments to: javadoc-tool@sun.com


What's New in Javadoc 1.4

 Javadoc Tool

This document describes the changes made to the Javadoc tool between versions 1.3 and 1.4. You can also see a concise list of outstanding bugs listed at important new bugs and regressions, and can view listings from our database at Important Bug Fixes and Changes.

  • Summary of New Tags and Options
  • Possible Incompatibilities
  • Running Javadoc
  • Writing Doc Comments
  • Output Content
  • Doclet API
  • Standard Doclet Code Change
  • Javadoc Tool Front End

Summary of New Tags and Options

Here is a brief summary of the new tags and options.
New Tags
{@linkplain}, {@inheritDoc}, @serial, {@value}

New Options
-breakiterator, -docfilessubdirs -exclude, -excludedocfilessubdir -nocomment, -noqualifier, -quiet, -source, -linksource, -subpackages, -tag, -taglet

Possible Incompatibilities

The following changes can affect the way your existing doc comments are interpreted or displayed:
  • New sentence break for first sentence
  • Javadoc copies @throws comments more conservatively

Running Javadoc

Includes changes that affect command line options, errors and warnings.
Added -subpackages option to recursively traverse all subpackages by passing in a single package root. The -exclude option unconditionally exclude packages from the list of packages to document even if it would otherwise be included by some previous or later -subpackages command-line flag. For example, -subpackages java -exclude java.lang.ref would include java.io, java.util, and java.lang (among others), but not java.lang.ref. (4074234)

Added "-source 1.4" option for assertions - This option documents code that was compiled using "javac -source 1.4", necessary for code that contains assertions. (4400430)

Added public methods to invoke Javadoc tool from within Java - Added a programmatic interface to the Javadoc tool in com.sun.tools.javadoc.Main (consequently, the standard doclet was made re-entrant). For more details, see Standard Doclet. (4113483)

Warning and error messages now contain filename and line number. The line number is to the declaration line rather than to the particular line in the doc comment. Uses the SourcePosition class. (4396665)

Serialized form page enhancements - Javadoc now includes private classes in the serialized form page (without requiring the -private flag). This means the serialized form page can be properly generated in a normal Javadoc run. This was done by adding the method PackageDoc.allClasses(boolean filter) where private and package-private classes are included when filter is false. ( Information Specific to the Doclet API) The method writeReplace() is now included in the serialized form page. Javadoc also now looks at "@serial include" and "@serial exclude" tags and includes or excludes classes accordingly. For more information, see @serial tag. (4290079, 4180839, 4341304)

Documented @files to work with command line options as well as filenames This changes the documentation to conform to the implementation. The @files feature was originally documented in javadoc and javac to allow only filenames, not command line options. This expands the documentation to say that @files also allows command line options. (Also renamed @files to @argfile in the documentation to make it clear it's a file of arguments.) (4469119)

Added -quiet option to shut off non-error messages
Only the warnings and errors appear, making them easier to find. (4217345)

The standard doclet prints its version number in its output stream. Suppressed by -quiet option. (4114089)

Automatically create destination directory (-d). Since a primary function of javadoc is to create files and directories, it seems reasonable to create the root destination directory as well. (4464477)

Document only legal classes - When documenting a package, Javadoc no longer reads files whose names are not composed of legal class names. Example: When passing com.sun.foo into Javadoc, it used to parse every file in the directory com\sun\foo whose name ended with ".java", whether or not the filename, stripped of that suffix, was actually a legal class name. Now Javadoc will parse only files whose names are legal class names. This enables developers to include templates, test source files, or other .java files that will not be documented, by including, for example, a hyphen "-" in its filename. (4398440)

Fixed -linkoffline separator '/' - When running on Microsoft Windows, the -linkoffline option now properly inserts '/' instead of '\' in each link that points to an external class. This bug caused broken links to external classes when documentation that was created by Javadoc on Windows was then browsed on Unix. (4359874)

Removed transitional "-1.1" option - The "-1.1" option was introduced in version 1.2 as a doclet to provide a transition path from Javadoc 1.1 to 1.2. This transition is not necessary for moving to 1.3. The "1.1" doclet did not handle new features of the language (such as inner classes) and because of shared code with the standard doclet was an impediment to maintenance. (4312499)

Writing Doc Comments

Includes changes that affect how doc comments are written, such as new tags.
Added tag interface for custom tags
You can create and use your own custom tags -- both normal standalone tags, similar to @return, and inline tags, similar to {@link}.
  • Simple tags - These are tags with a single text argument. You choose a unique name for a tag and use the -tag option.
  • Complex tags - These are tags with more than one argument, or that need special output. This requires developing a "taglet" class that implements the tag behavior. Then specify the -taglet and -tagletclasspath options (don't use the -tag option).
In both cases, the order of the -tag and -taglet options determine the order they are output. You can mix these options with the standard tags "-tag return", "-tag param" to intersperse them.

For custom inline tags, you must create a taglet. (4282805)

Flag any unknown tags while printing custom tags. This is a part of the custom tag mechanism. When javadoc parses the doc comments, any tag encountered that is not either a standard tag or passed in with -tag or -taglet is considered unknown, and a warning is thrown. (4039014)

When omitting the leading asterisk (*), keep indentation within <PRE> tags. This enables you to paste code examples directly into a doc comment. Indentation is relative to the left margin (rather than the separator /**). (4232882)

Added -breakiterator for new way to determine end of first sentence. We plan to change the algorithm for determining the end of the first sentence in the next major feature release. The -breakiterator option gives you a preview of the new algorithm. In 1.2 and 1.3, the java.text.BreakIterator class was used to determine the end of sentence for all languages but English (4165985). English had its own algorithm, which looked for a period followed by a space. When -breakiterator is omitted, the end of the first sentence is unchanged from 1.2 and 1.3, but warnings are emitted displaying where there would be a difference. Using -breakiterator uses the new algorithm. Differences in the algorithms show up in English as follows: (4165985)

  • Old algorithm - Stops at a period followed by a space or a paragraph-level HTML tag, such as <P>.
  • New algorithm - 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 "Serial no. is valid", but won't handle "Mr. Smith"). Won't stop at HTML tags or sentences that begin with numbers or symbols.

Fixed Javadoc to no longer require method bodies. - You can now run javadoc on .java source files that are pure stub files with no method bodies. This means you can write documentation comments and run Javadoc in the earliest stages of design while creating the API, before writing the implementation. Previously, javadoc complained if you tried to do this, insisting that you add "abstract" to the methods and the classes.

Added {@linkplain}, a plain text version of {@link}. The link's label is displayed in plain text rather than code font. Useful when the label is plain text. (4429628)
Example:

        Refer to {@linkplain add() the overridden method}.

Added {@inheritDoc} tag for inheriting documentation. This tag copies the doc comment from a superclass into the current doc comment. This allows developers to write around the copied text rather than have the inherited text be the only text. Previously, text was copied only if the comment was missing. (4186639)

Javadoc tags @return, @param, and @throws are now individually inherited. In 1.3, they would be inherited only if the entire doc comment was empty. The @see tag is also inherited, but only if there are no @see tags in the overriding element. (4496270)

The @throws documentation is copied from an overridden method to a subclass only when the exception is explicitly declared in the overridden method. In 1.3, the @throws text would be copied to an overriding method, whether or not that method actually could throw that execption. This new behavior may remove some documentation that @throws was properly inheriting. You can use {@inheritDoc} to cause @throws to inherit documentation. (4317583)

Output Content

Includes output text, images, layout, formatting and links.
Includes values of static field constants - Javadoc now documents the values of constant fields. Those values appear on a separate Constant Values page, reachable from "See also: Constant Values" links by each static field. The new inline tag {@value}, when used in a static field comment, returns its value. This tag is useful for inserting the value into a doc comment. (4422788)

This change required adding to the Doclet API the methods FieldDoc.constantValue() and FieldDoc.constantValueExpression() in package com.sun.javadoc. ( Information Specific to the Doclet API) (4320557)

Added -noqualifier option to omit qualifying package name from ahead of class names in output
The previous behavior was as follows: On the page for class p.C, add the package name only to classes not belonging to package p. 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 (such as "java.lang:java.awt:javax.*"). (4359889)

Add links to source code, using -linksource option
Creates an HTML version of each source file and adds links to them from the normal documentation. (Named -src in Beta 2. Will rename it to -linksource in the final version, to better differentiate it from -source.) (1242492)

Put current class or package name first in window title.
This enables the name to appear in the Windows task bar when a window is minimized. (Also works in Internet Explorer when frames are turned on.) (4232597)

Generate package page when passing in source filenames (*.java). The docs that are generated should not be any different when passing in package names than when passing in the source filenames for classes in those packages. (4359386)

Put exception class link in throws section in two cases:
(1) there a @throws tag but no text accompanies the tag
(2) if an exception is declared but there is no tag (4074202)

Added -nocomment to suppress description and tags, generating only declarations. Enables re-using source files originally intended for a different purpose. (4464558)

Error exit status - Fixed javadoc to use the exit status of the doclet. (4136558)

Use the -encoding option when reading package.html. (4463408)

Added "All Classes" to navigation bar for improved accessibility (4140824)

Directory doc-files is now copied when passing in .java files - When passing in source files (*.java) to Javadoc, it now copies the "doc-files" directories to the destination. (Formerly, the "doc-files" directories were not copied.) This behavior is now identical to that when passing in package names. (4340814)

Fixed doc-files directory at doc root to be copied to destination.
This enables the inclusion of overview-level documentation to be included. (4256505)

Added -docfilessubdirs to enable deep copy of doc-files - Subdirectories of the "doc-files" directory are now recursively copied to the destination when -docfilessubdirs is used. For example, doc-files/example/images and all its contents would now be copied.If you need it, this option is also available: -excludedocfilessubdir name1>:<name2>... to exclude any doc-files subdirectories with the given names. This prevents the copying of SCCS and other source-code-control subdirectories. Previously, only files directly in "doc-files" were copied. (4385048)

Fixed {@docroot} in HTML frame - The {@docroot} tag is now properly resolved when it appears in the upper left HTML frame (overview-frame.html). (4365290)

Fixed {@docroot} in @see - The {@docroot} tag is now properly resolved when it appears in the text of an @see tag. (4416364)

Fixed {@link} with {@docRoot} - The {@docRoot} tag no longer disables any {@link} tag that follows it in the same comment. (4369014)

"Implements" heading - A doc comment inherited from an abstract method now uses the proper subheading "implements" rather than "overrides". (4318787)

Fixed "Implementing Class" on interface page - Fixed bug on interface page where some classes were not showing up as "implementing class". (4378491)

Fixed display of static initializers - The initializer static {...} caused the "Methods Inherited From" table to start with a comma (,). The underlying bug was that javadoc considered static {} to be an anonymous method. It will no longer appear as a method entry in the generated docs. (4136861)

Properly document fields and methods for private inner classes. (445611)

Corrected "nested classes" terminology - Javadoc now uses the term "nested classes" rather than "inner classes" throughout its headings and subheadings. The definitions are: "A nested class is any class whose declaration occurs within the body of another class or interface." while "An inner class is a nested class that is not static." Therefore, "nested" is the more general term. (4307151)

Doclet API

Information Specific to the Doclet API Doclet API is no longer serializable. - The classes no longer extend serializable. (It would have been impossible, in general, to properly serialize them.) (4125581)

Information Specific to the Doclet API Expose filename and line number of declarations. A new class SourcePosition has been added to the Doclet API, as well as a new method position() in Doc and Tag (see 4192783). These enable the complete decomposing and recomposing of source files. (4192783, 4208989)

Information Specific to the Doclet API Added MethodDoc.overriddenMethod() for returning the list of methods that are overridden.

Information Specific to the Doclet API Improved documentation of the Doclet API.

Information Specific to the Doclet API Potential incompatibility - The Tag interface now has a position() method. Doclets that implement the 1.3 Tag interface (such as MIF Doclet 1.2 Beta 1) will not work with Javadoc 1.4.

Standard Doclet Code Change

Standard doclet code change - In the standard doclet source code, added a configuration argument to the MessageRetriever constructor signature. This may affect code that subclasses the standard doclet. New constructor is now MessageRetriever(Configuration configuration, String resourcelocation) (No bug number)

Javadoc Tool Front End

There are many changes to the Javadoc tool described in the other sections; the most notable one is mentioned here.

Complete reimplementation of the Javadoc tool and API (4400430): - Javadoc now uses the new javac compiler instead of the old.

A few changes in behavior are known. These are not bugs and will probably never be "fixed" in javadoc:

  • Private inner classes are now marked as private. The old javadoc incorrectly marked them as having package protection.
  • static class initialization blocks were reported by the old javadoc as if they were a function named <clinit>. The new javadoc correctly omits them.
  • The old javadoc incorrectly inserted a this$0 parameter to constructors for nested classes. While this agrees with the reflective view of these constructors, it is not correct from the source or the language viewpoint. The new javadoc reports the signature as it appears in the source.
  • The old javadoc sometimes reported the compiler-generated field this$0 as a serializable field. The new javadoc correctly omits mention of this$0 and other synthetic members. See java.util.logging.LogManager.LogProperties for an example.
  • The old javadoc occasionally omitted wildcard import declararations that appeared in the source. For example, in the translation unit for java.io.PipedOutputStream there is a (useless and redundant) "import java.io.*;". The new javadoc correctly includes this in the list of imports.
  • The old javadoc incorrectly reported that a private method overrides a private method with the same signature in the superclass. The new javadoc correctly reports that a private method is never overridden.
  • Some bugs remaining in the new java.io implementation prevent the correct processing of Unicode characters on output. While this is not a javadoc bug per se, it will affect any comparison of the old javadoc output with the new. For an example of the differences, see java.util.regex.Pattern.Caret. The workaround is to use a locale that supports a wider set of Unicode.

Some further known examples of incorrect behavior of the old javadoc are intentionally reproduced in the new javadoc implementation for compatibility. For example, if a class a.A has inner classes and you import them using:

        import a.A.*;
Old Javadoc would incorrectly report (through the Doclet API) an import of:
        import a.*;
There is no way of correctly expressing this import declaration with the current javadoc API.

ClassDoc instances are no longer unique - Prior to 1.4.0, every class being documented was represented by a single ClassDoc instance -- this was an undocumented implementation detail. With 1.4.0, this is no longer true -- the Javadoc tool is capable of creating two different ClassDoc instances that represent the same class. This would break any doclets that mistakenly relied on this fact. One such bug was 4496290: The -use option is severely broken.

Copyright © 2001 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software

Please send comments to: javadoc-tool@sun.com


What's New in Javadoc 1.4.1

 Javadoc Tool
This document describes the changes made to the Javadoc tool between versions 1.4.0 and 1.4.1. You can also see a concise list of outstanding bugs listed at important new bugs and regressions, and can view listings from our database at Important Bug Fixes and Changes.

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 worked in 1.3.x, broke in 1.4.0, and have been fixed in 1.4.1.

  • New Features
  • Bug Fixes
    • Running Javadoc
    • Error/Warning Messages
    • Command Line Options
    • Tags
    • Miscellaneous

New Features

Added package and class names as keywords in <META> tags. This should improve search results for search engines that look at <META> tags. (4034096, stddoclet)

Bug Fixes:

Running Javadoc:

Regression: Fixed bug where it mistakenly documented .class files found on classpath (if they belong to packages passed in on the command line). (4548768, tool)

Regression: Fixed to handle packages named *.java. (4507380, tool)

Added better checking to accept only valid source file and package names. (4434834, tool)

Error/Warning Messages

Fixed com.sun.tools.javadoc.Main.execute to not ignore PrintWriters. (4587487, tool)

Added quotes around package name in error message when "\ " (backslash, space) passed in. (4370719, tool)

Command Line Options:

Regression: Fixed -use option, which was severely broken. (4496290, stddoclet)

Regression: Fixed -encoding option for reading source files. (4661481, stddoclet)

Regression: Fixed -link option to handle absolute paths. (4640745, stddoclet)

Fixed hang when -subpackages is passed in topmost package name. (4628237, tool)

Changed diagnostic of -help to 'Display command line options and exit'. (4501697, tool)

Tags:

Regression: Fixed to properly insert </DD> when using multiple @author tags. (4651598, stddoclet)

Regression: Fixed {@docRoot} which had been inserting an extra slash "/". (4524350, stddoclet)

Regression: Fixed @throws in implementing class to override @throws in interface. (4633969, stddoclet)

Regression: Fixed to enable @throws tags to have duplicate error class names. (4525364, stddoclet)

Regression: Fixed {@inheritDoc}, which did not work. (4618686, stddoclet)

Added warning when lowercase {@docroot} is used instead of {@docRoot}. (4662945, stddoclet)

Miscellaneous

Added interface constants to the Constant Field Values list. (4526070, stddoclet)

Corrected boolean constant fields to use true/false rather than 0/1. (4587494, tool)

Removed extra space of indentation for comments that omit leading asterisk. (4587562, tool)

Regression: Fixed StringIndexOutOfBoundsException caused by multiple <a href> tags. (4638015, stddoclet)

Changed so nothing is serializable when Serializable is not on -bootclasspath. (4644960, tool)

Removed "()" from window title when frames are off. (4530730, stddoclet)

Notes for doclet programmers:

The -use option was broken because Doc objects are no longer unique in 1.4.0. To keep track of class and package usage, the standard doclet creates Doc/List hash tables where the key is a ClassDoc or PackageDoc and the List is a list of Doc objects that use the key. This way of determining class and package usage worked fine with previous versions of the Javadoc tool, but it does not seem to work with 1.4.x. A Doc object should not be used as a key in the hash table. They are not unique -- that is, the Javadoc tool seems to be capable of creating two different ClassDoc objects that represent the same class. To fix this bug, we used the qualified name as the key in the hash table. We plan to make Doc objects unique again at some point.

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: 		Sun
Java Software


What's New in Javadoc 1.4.2

 Javadoc Tool

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)

    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 include 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 include 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 © 2003 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: 		Sun
Java Software


All Classes (Doclet API)

 All Classes
ClassDoc
ConstructorDoc
Doc
DocErrorReporter
Doclet
ExecutableMemberDoc
FieldDoc
MemberDoc
MethodDoc
PackageDoc
ParamTag
Parameter
ProgramElementDoc
RootDoc
SeeTag
SerialFieldTag
SourcePosition
Tag
ThrowsTag
Type


Deprecated List (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES

Deprecated API

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


API Help (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES

How This API Document Is Organized

This API (Application Programming Interface) document has pages corresponding to the items in the navigation bar, described as follows.

Package

Each package has a page that contains a list of its classes and interfaces, with a summary for each. This page can contain four categories:

  • Interfaces (italic)
  • Classes
  • Exceptions
  • Errors

Class/Interface

Each class, interface, nested class and nested interface has its own separate page. Each of these pages has three sections consisting of a class/interface description, summary tables, and detailed member descriptions:

  • Class inheritance diagram
  • Direct Subclasses
  • All Known Subinterfaces
  • All Known Implementing Classes
  • Class/interface declaration
  • Class/interface description

  • Nested Class Summary
  • Field Summary
  • Constructor Summary
  • Method Summary

  • Field Detail
  • Constructor Detail
  • Method Detail
Each summary entry contains the first sentence from the detailed description for that item. The summary entries are alphabetical, while the detailed descriptions are in the order they appear in the source code. This preserves the logical groupings established by the programmer.

Use

Each documented package, class and interface has its own Use page. This page describes what packages, classes, methods, constructors and fields use any part of the given class 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.

Tree (Class Hierarchy)

There is a Class Hierarchy page for all packages, plus a hierarchy for each package. Each hierarchy page contains a list of classes and a list of interfaces. The classes are organized by inheritance structure starting with java.lang.Object. The interfaces do not inherit from java.lang.Object.
  • When viewing the Overview page, clicking on "Tree" displays the hierarchy for all packages.
  • When viewing a particular package, class or interface page, clicking "Tree" displays the hierarchy for only that package.

Deprecated API

The Deprecated API page lists all of the API that have been deprecated. A deprecated API is not recommended for use, generally due to improvements, and a replacement API is usually given. Deprecated APIs may be removed in future implementations.

Index

The Index contains an alphabetic list of all classes, interfaces, constructors, methods, and fields.

Prev/Next

These links take you to the next or previous class, interface, package, or related page.

Frames/No Frames

These links show and hide the HTML frames. All pages are available with or without frames.

Serialized Form

Each serializable or externalizable 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 description.

This help file applies to API documentation generated using the standard doclet.

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Doclet API

Frame Alert

This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client.
Link toNon-frame version.


Index (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES
A C D E F G H I K L M N O P Q R S T V

A

allClasses(boolean) - Method in interface com.sun.javadoc.PackageDoc
Get all classes and interfaces in the package, filtered to the specified access modifier option.
allClasses() - Method in interface com.sun.javadoc.PackageDoc
Get all included classes and interfaces in the package.
asClassDoc() - Method in interface com.sun.javadoc.Type
Return this type as a class doc if this type is a class or interface.

C

ClassDoc - interface com.sun.javadoc.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.
ConstructorDoc - interface com.sun.javadoc.ConstructorDoc.
Represents a constructor of a java class.
classNamed(String) - Method in interface com.sun.javadoc.RootDoc
Return a ClassDoc for the specified class or interface name.
classes() - Method in interface com.sun.javadoc.RootDoc
Return the included classes and interfaces in all packages.
column() - Method in interface com.sun.javadoc.SourcePosition
The column in the source file.
com.sun.javadoc - package com.sun.javadoc
The Doclet API (also called the Javadoc API) provides a mechanism for clients to inspect the source-level structure of programs and libraries, including javadoc comments embedded in the source.
commentText() - Method in interface com.sun.javadoc.Doc
Return the text of the comment for this doc item.
compareTo(Object) - Method in interface com.sun.javadoc.Doc
Compares this doc object with the specified object for order.
compareTo(Object) - Method in interface com.sun.javadoc.SerialFieldTag
Compares this Object with the specified Object for order.
constantValue() - Method in interface com.sun.javadoc.FieldDoc
Get the value of a constant field.
constantValueExpression() - Method in interface com.sun.javadoc.FieldDoc
Get the value of a constant field.
constructors() - Method in interface com.sun.javadoc.ClassDoc
Return included constructors in this class.
constructors(boolean) - Method in interface com.sun.javadoc.ClassDoc
Return constructors in this class, filtered to the specified access modifier option.
containingClass() - Method in interface com.sun.javadoc.ProgramElementDoc
Get the containing class or interface of this program element.
containingPackage() - Method in interface com.sun.javadoc.ProgramElementDoc
Get the package that this program element is contained in.

D

Doc - interface com.sun.javadoc.Doc.
Represents Java language constructs (package, class, constructor, method, field) which have comments and have been processed by this run of javadoc.
DocErrorReporter - interface com.sun.javadoc.DocErrorReporter.
This interface provides error, warning and notice printing.
Doclet - class com.sun.javadoc.Doclet.
This is an example of a starting class for a doclet, showing the entry-point methods.
Doclet() - Constructor for class com.sun.javadoc.Doclet
definesSerializableFields() - Method in interface com.sun.javadoc.ClassDoc
Return true if Serializable fields are explicitly defined with the special class member serialPersistentFields.
description() - Method in interface com.sun.javadoc.SerialFieldTag
Return the field comment.
dimension() - Method in interface com.sun.javadoc.Type
Return the type's dimension information, as a string.

E

ExecutableMemberDoc - interface com.sun.javadoc.ExecutableMemberDoc.
Represents a method or constructor of a java class.
errors() - Method in interface com.sun.javadoc.PackageDoc
Get included Error classes in this package.
exception() - Method in interface com.sun.javadoc.ThrowsTag
Return a ClassDoc which represents the exception.
exceptionComment() - Method in interface com.sun.javadoc.ThrowsTag
Return the exception comment associated with this ThrowsTag.
exceptionName() - Method in interface com.sun.javadoc.ThrowsTag
Return the name of the exception associated with this ThrowsTag.
exceptions() - Method in interface com.sun.javadoc.PackageDoc
Get included Exception classes in this package.

F

FieldDoc - interface com.sun.javadoc.FieldDoc.
Represents a field in a java class.
fieldName() - Method in interface com.sun.javadoc.SerialFieldTag
Return the serialziable field name.
fieldType() - Method in interface com.sun.javadoc.SerialFieldTag
Return the field type string.
fieldTypeDoc() - Method in interface com.sun.javadoc.SerialFieldTag
Return the ClassDoc for field type.
fields() - Method in interface com.sun.javadoc.ClassDoc
Return included fields in this class or interface.
fields(boolean) - Method in interface com.sun.javadoc.ClassDoc
Return fields in this class or interface, filtered to the specified access modifier option
file() - Method in interface com.sun.javadoc.SourcePosition
The source file.
findClass(String) - Method in interface com.sun.javadoc.ClassDoc
Find the specified class or interface within the context of this class doc.
findClass(String) - Method in interface com.sun.javadoc.PackageDoc
Lookup a class or interface within this package.
firstSentenceTags() - Method in interface com.sun.javadoc.Doc
Return the first sentence of the comment as an array of tags.
firstSentenceTags() - Method in interface com.sun.javadoc.Tag
Return the first sentence of the comment as an array of tags.
flatSignature() - Method in interface com.sun.javadoc.ExecutableMemberDoc
get flat signature.

G

getRawCommentText() - Method in interface com.sun.javadoc.Doc
Return the full unprocessed text of the comment.

H

holder() - Method in interface com.sun.javadoc.Tag
Return the containing Doc of this Tag element.

I

importedClasses() - Method in interface com.sun.javadoc.ClassDoc
Get the list of classes and interfaces declared as imported.
importedPackages() - Method in interface com.sun.javadoc.ClassDoc
Get the list of packages declared as imported.
inlineTags() - Method in interface com.sun.javadoc.Doc
Return comment as an array of tags.
inlineTags() - Method in interface com.sun.javadoc.Tag
For a documentation comment with embedded {@link} tags, return an array of Tag objects.
innerClasses() - Method in interface com.sun.javadoc.ClassDoc
Return included nested classes and interfaces within this class or interface.
innerClasses(boolean) - Method in interface com.sun.javadoc.ClassDoc
Return nested classes and interfaces within this class or interface filtered to the specified access modifier option.
interfaces() - Method in interface com.sun.javadoc.ClassDoc
Return interfaces implemented by this class or interfaces extended by this interface.
interfaces() - Method in interface com.sun.javadoc.PackageDoc
Get included Interfaces in this package.
isAbstract() - Method in interface com.sun.javadoc.ClassDoc
Return true if this class is abstract.
isAbstract() - Method in interface com.sun.javadoc.MethodDoc
Return true if this method is abstract
isClass() - Method in interface com.sun.javadoc.Doc
Is this Doc item a class (not an interface)? This includes ordinary classes, errors and exceptions.
isConstructor() - Method in interface com.sun.javadoc.Doc
Is this Doc item a constructor?
isError() - Method in interface com.sun.javadoc.Doc
Is this Doc item an error class?
isException() - Method in interface com.sun.javadoc.Doc
Is this Doc item an exception class?
isExternalizable() - Method in interface com.sun.javadoc.ClassDoc
Return true if this class implements or interface extends java.io.Externalizable.
isField() - Method in interface com.sun.javadoc.Doc
Is this Doc item a field?
isFinal() - Method in interface com.sun.javadoc.ProgramElementDoc
Return true if this program element is final.
isIncluded() - Method in interface com.sun.javadoc.Doc
Return true if this Doc item is included in the result set.
isInterface() - Method in interface com.sun.javadoc.Doc
Is this Doc item an interface?
isMethod() - Method in interface com.sun.javadoc.Doc
Is this Doc item a method (i.e.
isNative() - Method in interface com.sun.javadoc.ExecutableMemberDoc
Return true if this method is native
isOrdinaryClass() - Method in interface com.sun.javadoc.Doc
Is this Doc item an ordinary class? (i.e.
isPackagePrivate() - Method in interface com.sun.javadoc.ProgramElementDoc
Return true if this program element is package private.
isPrivate() - Method in interface com.sun.javadoc.ProgramElementDoc
Return true if this program element is private.
isProtected() - Method in interface com.sun.javadoc.ProgramElementDoc
Return true if this program element is protected.
isPublic() - Method in interface com.sun.javadoc.ProgramElementDoc
Return true if this program element is public.
isSerializable() - Method in interface com.sun.javadoc.ClassDoc
Return true if this class implements or interface extends java.io.Serializable.
isStatic() - Method in interface com.sun.javadoc.ProgramElementDoc
Return true if this program element is static.
isSynchronized() - Method in interface com.sun.javadoc.ExecutableMemberDoc
Return true if this method is synchronized
isSynthetic() - Method in interface com.sun.javadoc.MemberDoc
Returns true if this member was synthesized by the compiler.
isTransient() - Method in interface com.sun.javadoc.FieldDoc
Return true if this field is transient
isVolatile() - Method in interface com.sun.javadoc.FieldDoc
Return true if this field is volatile

K

kind() - Method in interface com.sun.javadoc.Tag
Return the kind of this tag.

L

label() - Method in interface com.sun.javadoc.SeeTag
Get the label of the @see tag.
line() - Method in interface com.sun.javadoc.SourcePosition
The line in the source file.

M

MemberDoc - interface com.sun.javadoc.MemberDoc.
Represents a member of a java class: field, constructor, or method.
MethodDoc - interface com.sun.javadoc.MethodDoc.
Represents a method of a java class.
methods() - Method in interface com.sun.javadoc.ClassDoc
Return included methods in this class or interface.
methods(boolean) - Method in interface com.sun.javadoc.ClassDoc
Return methods in this class or interface, filtered to the specified access modifier option.
modifierSpecifier() - Method in interface com.sun.javadoc.ProgramElementDoc
Get the modifier specifier integer.
modifiers() - Method in interface com.sun.javadoc.ProgramElementDoc
Get modifiers string.

N

name() - Method in interface com.sun.javadoc.Doc
Returns the non-qualified name of this Doc item.
name() - Method in interface com.sun.javadoc.Parameter
Get local name of this parameter.
name() - Method in interface com.sun.javadoc.Tag
Return the name of this tag.

O

optionLength(String) - Static method in class com.sun.javadoc.Doclet
Check for doclet-added options.
options() - Method in interface com.sun.javadoc.RootDoc
Command line options.
ordinaryClasses() - Method in interface com.sun.javadoc.PackageDoc
Get included ordinary classes (that is, exclude exceptions, errors and interfaces) in this package.
overriddenClass() - Method in interface com.sun.javadoc.MethodDoc
Return the class containing the method that this method overrides.
overriddenMethod() - Method in interface com.sun.javadoc.MethodDoc
Return the method that this method overrides.

P

PackageDoc - interface com.sun.javadoc.PackageDoc.
Represents a java package.
ParamTag - interface com.sun.javadoc.ParamTag.
Represents an @param documentation tag.
Parameter - interface com.sun.javadoc.Parameter.
Parameter information.
ProgramElementDoc - interface com.sun.javadoc.ProgramElementDoc.
Represents a java program element: class, interface, field, constructor, or method.
packageNamed(String) - Method in interface com.sun.javadoc.RootDoc
Return a PackageDoc for the specified package name.
paramTags() - Method in interface com.sun.javadoc.ExecutableMemberDoc
Return the param tags in this method.
parameterComment() - Method in interface com.sun.javadoc.ParamTag
Return the parameter comment associated with this ParamTag.
parameterName() - Method in interface com.sun.javadoc.ParamTag
Return the name of the parameter associated with this ParamTag.
parameters() - Method in interface com.sun.javadoc.ExecutableMemberDoc
Get argument information.
position() - Method in interface com.sun.javadoc.Doc
Return the source position of the first line of the corresponding declaration, or null if no position is available.
position() - Method in interface com.sun.javadoc.Tag
Return the source position of this tag.
printError(String) - Method in interface com.sun.javadoc.DocErrorReporter
Print error message and increment error count.
printError(SourcePosition, String) - Method in interface com.sun.javadoc.DocErrorReporter
Print an error message and increment error count.
printNotice(String) - Method in interface com.sun.javadoc.DocErrorReporter
Print a message.
printNotice(SourcePosition, String) - Method in interface com.sun.javadoc.DocErrorReporter
Print a message.
printWarning(String) - Method in interface com.sun.javadoc.DocErrorReporter
Print warning message and increment warning count.
printWarning(SourcePosition, String) - Method in interface com.sun.javadoc.DocErrorReporter
Print warning message and increment warning count.

Q

qualifiedName() - Method in interface com.sun.javadoc.ConstructorDoc
Get the name.
qualifiedName() - Method in interface com.sun.javadoc.ProgramElementDoc
Get the fully qualified name of this program element.
qualifiedTypeName() - Method in interface com.sun.javadoc.Type
Return qualified name of type excluding any dimension information.

R

RootDoc - interface com.sun.javadoc.RootDoc.
Represents the root of the program structure information for one run of javadoc.
referencedClass() - Method in interface com.sun.javadoc.SeeTag
Get the class doc referenced by the class name part of @see.
referencedClassName() - Method in interface com.sun.javadoc.SeeTag
Get the class or interface name of the @see reference.
referencedMember() - Method in interface com.sun.javadoc.SeeTag
Get the member doc for the field, constructor or method referenced by @see.
referencedMemberName() - Method in interface com.sun.javadoc.SeeTag
Get the field, constructor or method substring of the @see reference.
referencedPackage() - Method in interface com.sun.javadoc.SeeTag
Get the package doc when @see references only a package.
returnType() - Method in interface com.sun.javadoc.MethodDoc
Get return type.

S

SeeTag - interface com.sun.javadoc.SeeTag.
Represents a user-defined cross-reference to related documentation.
SerialFieldTag - interface com.sun.javadoc.SerialFieldTag.
Documents a Serializable field defined by an ObjectStreamField.
SourcePosition - interface com.sun.javadoc.SourcePosition.
This interface describes a source position: filename, line number, and column number.
seeTags() - Method in interface com.sun.javadoc.Doc
Return the see also tags in this Doc item.
serialFieldTags() - Method in interface com.sun.javadoc.FieldDoc
Return the serialField tags in this FieldDoc item.
serializableFields() - Method in interface com.sun.javadoc.ClassDoc
Return the Serializable fields of this class or interface.
serializationMethods() - Method in interface com.sun.javadoc.ClassDoc
Return the serialization methods for this class or interface.
setRawCommentText(String) - Method in interface com.sun.javadoc.Doc
Set the full unprocessed text of the comment.
signature() - Method in interface com.sun.javadoc.ExecutableMemberDoc
Get the signature.
specifiedClasses() - Method in interface com.sun.javadoc.RootDoc
Return the classes and interfaces specified as source file names on the command line.
specifiedPackages() - Method in interface com.sun.javadoc.RootDoc
Return the packages specified on the command line.
start(RootDoc) - Static method in class com.sun.javadoc.Doclet
Generate documentation here.
subclassOf(ClassDoc) - Method in interface com.sun.javadoc.ClassDoc
Test whether this class is a subclass of the specified class.
superclass() - Method in interface com.sun.javadoc.ClassDoc
Return the superclass of this class.

T

Tag - interface com.sun.javadoc.Tag.
Represents a simple documentation tag, such as @since, @author, @version.
ThrowsTag - interface com.sun.javadoc.ThrowsTag.
Represents a @throws or @exception documentation tag.
Type - interface com.sun.javadoc.Type.
Represents a java type.
tags() - Method in interface com.sun.javadoc.Doc
Return all tags in this Doc item.
tags(String) - Method in interface com.sun.javadoc.Doc
Return tags of the specified kind in this Doc item.
text() - Method in interface com.sun.javadoc.Tag
Return the text of this tag, that is, portion beyond tag name.
thrownExceptions() - Method in interface com.sun.javadoc.ExecutableMemberDoc
Return exceptions this method or constructor throws.
throwsTags() - Method in interface com.sun.javadoc.ExecutableMemberDoc
Return the throws tags in this method.
toString() - Method in interface com.sun.javadoc.Parameter
Returns a string representation of the class.
toString() - Method in interface com.sun.javadoc.SourcePosition
Convert the source position to the form "Filename:line".
toString() - Method in interface com.sun.javadoc.Tag
Convert this object to a string.
toString() - Method in interface com.sun.javadoc.Type
Returns a string representation of the type.
type() - Method in interface com.sun.javadoc.FieldDoc
Get type of this field.
type() - Method in interface com.sun.javadoc.Parameter
Get the type of this parameter.
typeName() - Method in interface com.sun.javadoc.Parameter
Get type name of this parameter.
typeName() - Method in interface com.sun.javadoc.Type
Return unqualified name of type excluding any dimension information.

V

validOptions(String[][], DocErrorReporter) - Static method in class com.sun.javadoc.Doclet
Check that options have the correct arguments.
A C D E F G H I K L M N O P Q R S T V
Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Class Hierarchy (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES

Hierarchy For All Packages

Package Hierarchies:
com.sun.javadoc

Class Hierarchy

  • class java.lang.Object
    • class com.sun.javadoc.Doclet

Interface Hierarchy

  • interface java.lang.Comparable
    • interface com.sun.javadoc.ClassDoc (also extends com.sun.javadoc.ProgramElementDoc, com.sun.javadoc.Type)
    • interface com.sun.javadoc.ConstructorDoc
    • interface com.sun.javadoc.Doc
      • interface com.sun.javadoc.ClassDoc (also extends com.sun.javadoc.ProgramElementDoc, com.sun.javadoc.Type)
      • interface com.sun.javadoc.ConstructorDoc
      • interface com.sun.javadoc.ExecutableMemberDoc
        • interface com.sun.javadoc.ConstructorDoc
        • interface com.sun.javadoc.MethodDoc
      • interface com.sun.javadoc.FieldDoc
      • interface com.sun.javadoc.MemberDoc
        • interface com.sun.javadoc.ConstructorDoc
        • interface com.sun.javadoc.ExecutableMemberDoc
          • interface com.sun.javadoc.ConstructorDoc
          • interface com.sun.javadoc.MethodDoc
        • interface com.sun.javadoc.FieldDoc
        • interface com.sun.javadoc.MethodDoc
      • interface com.sun.javadoc.MethodDoc
      • interface com.sun.javadoc.PackageDoc
      • interface com.sun.javadoc.ProgramElementDoc
        • interface com.sun.javadoc.ClassDoc (also extends com.sun.javadoc.Type)
        • interface com.sun.javadoc.ConstructorDoc
        • interface com.sun.javadoc.ExecutableMemberDoc
          • interface com.sun.javadoc.ConstructorDoc
          • interface com.sun.javadoc.MethodDoc
        • interface com.sun.javadoc.FieldDoc
        • interface com.sun.javadoc.MemberDoc
          • interface com.sun.javadoc.ConstructorDoc
          • interface com.sun.javadoc.ExecutableMemberDoc
            • interface com.sun.javadoc.ConstructorDoc
            • interface com.sun.javadoc.MethodDoc
          • interface com.sun.javadoc.FieldDoc
          • interface com.sun.javadoc.MethodDoc
        • interface com.sun.javadoc.MethodDoc
      • interface com.sun.javadoc.RootDoc (also extends com.sun.javadoc.DocErrorReporter)
    • interface com.sun.javadoc.ExecutableMemberDoc
      • interface com.sun.javadoc.ConstructorDoc
      • interface com.sun.javadoc.MethodDoc
    • interface com.sun.javadoc.FieldDoc
    • interface com.sun.javadoc.MemberDoc
      • interface com.sun.javadoc.ConstructorDoc
      • interface com.sun.javadoc.ExecutableMemberDoc
        • interface com.sun.javadoc.ConstructorDoc
        • interface com.sun.javadoc.MethodDoc
      • interface com.sun.javadoc.FieldDoc
      • interface com.sun.javadoc.MethodDoc
    • interface com.sun.javadoc.MethodDoc
    • interface com.sun.javadoc.PackageDoc
    • interface com.sun.javadoc.ProgramElementDoc
      • interface com.sun.javadoc.ClassDoc (also extends com.sun.javadoc.Type)
      • interface com.sun.javadoc.ConstructorDoc
      • interface com.sun.javadoc.ExecutableMemberDoc
        • interface com.sun.javadoc.ConstructorDoc
        • interface com.sun.javadoc.MethodDoc
      • interface com.sun.javadoc.FieldDoc
      • interface com.sun.javadoc.MemberDoc
        • interface com.sun.javadoc.ConstructorDoc
        • interface com.sun.javadoc.ExecutableMemberDoc
          • interface com.sun.javadoc.ConstructorDoc
          • interface com.sun.javadoc.MethodDoc
        • interface com.sun.javadoc.FieldDoc
        • interface com.sun.javadoc.MethodDoc
      • interface com.sun.javadoc.MethodDoc
    • interface com.sun.javadoc.RootDoc (also extends com.sun.javadoc.Doc, com.sun.javadoc.DocErrorReporter)
    • interface com.sun.javadoc.SerialFieldTag (also extends com.sun.javadoc.Tag)
  • interface com.sun.javadoc.DocErrorReporter
    • interface com.sun.javadoc.RootDoc (also extends com.sun.javadoc.Doc)
  • interface com.sun.javadoc.Parameter
  • interface com.sun.javadoc.SourcePosition
  • interface com.sun.javadoc.Tag
    • interface com.sun.javadoc.ParamTag
    • interface com.sun.javadoc.SeeTag
    • interface com.sun.javadoc.SerialFieldTag (also extends java.lang.Comparable)
    • interface com.sun.javadoc.ThrowsTag
  • interface com.sun.javadoc.Type
    • interface com.sun.javadoc.ClassDoc (also extends com.sun.javadoc.ProgramElementDoc)
Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


ClassDoc (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

com.sun.javadoc
Interface ClassDoc

All Superinterfaces:
Comparable, Doc, ProgramElementDoc, Type
public interface ClassDoc
extends ProgramElementDoc, Type

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. A ClassDoc only exists if it was processed in this run of javadoc. References to classes which may or may not have been processed in this run are referred to using Type (which can be converted to ClassDoc, if possible).

Since:
JDK1.2
See Also:
Type

Method Summary
ConstructorDoc[] | constructors() Return included constructors in this class.
ConstructorDoc[] | constructors(boolean filter) Return constructors in this class, filtered to the specified access modifier option.
boolean | definesSerializableFields() Return true if Serializable fields are explicitly defined with the special class member serialPersistentFields.
FieldDoc[] | fields() Return included fields in this class or interface.
FieldDoc[] | fields(boolean filter) Return fields in this class or interface, filtered to the specified access modifier option
ClassDoc | findClass(String className) Find the specified class or interface within the context of this class doc.
ClassDoc[] | importedClasses() Get the list of classes and interfaces declared as imported.
PackageDoc[] | importedPackages() Get the list of packages declared as imported.
ClassDoc[] | innerClasses() Return included nested classes and interfaces within this class or interface.
ClassDoc[] | innerClasses(boolean filter) Return nested classes and interfaces within this class or interface filtered to the specified access modifier option.
ClassDoc[] | interfaces() Return interfaces implemented by this class or interfaces extended by this interface.
boolean | isAbstract() Return true if this class is abstract.
boolean | isExternalizable() Return true if this class implements or interface extends java.io.Externalizable.
boolean | isSerializable() Return true if this class implements or interface extends java.io.Serializable.
MethodDoc[] | methods() Return included methods in this class or interface.
MethodDoc[] | methods(boolean filter) Return methods in this class or interface, filtered to the specified access modifier option.
FieldDoc[] | serializableFields() Return the Serializable fields of this class or interface.
MethodDoc[] | serializationMethods() Return the serialization methods for this class or interface.
boolean | subclassOf(ClassDoc cd) Test whether this class is a subclass of the specified class.
ClassDoc | superclass() Return the superclass of this class.
Methods inherited from interface com.sun.javadoc.ProgramElementDoc
containingClass, containingPackage, isFinal, isPackagePrivate, isPrivate, isProtected, isPublic, isStatic, modifiers, modifierSpecifier, qualifiedName
Methods inherited from interface com.sun.javadoc.Doc
commentText, compareTo, firstSentenceTags, getRawCommentText, inlineTags, isClass, isConstructor, isError, isException, isField, isIncluded, isInterface, isMethod, isOrdinaryClass, name, position, seeTags, setRawCommentText, tags, tags
Methods inherited from interface com.sun.javadoc.Type
asClassDoc, dimension, qualifiedTypeName, toString, typeName

Method Detail

isAbstract

public boolean isAbstract()
Return true if this class is abstract. Return true for all interfaces.

isSerializable

public boolean isSerializable()
Return true if this class implements or interface extends java.io.Serializable. Since java.io.Externalizable extends java.io.Serializable, Externalizable objects are also Serializable.

isExternalizable

public boolean isExternalizable()
Return true if this class implements or interface extends java.io.Externalizable.

serializationMethods

public MethodDoc[] serializationMethods()
Return the serialization methods for this class or interface.

Returns:
an array of MethodDoc objects that represents the serialization methods for this class or interface.

serializableFields

public FieldDoc[] serializableFields()
Return the Serializable fields of this class or interface.

Return either a list of default fields documented by serial tag
or return a single FieldDoc for serialPersistentField member. There should be a serialField tag for each Serializable field defined by an ObjectStreamField array component of serialPersistentField.

Returns:
an array of FieldDoc objects for the Serializable fields of this class or interface.
See Also:
definesSerializableFields(), SerialFieldTag

definesSerializableFields

public boolean definesSerializableFields()
Return true if Serializable fields are explicitly defined with the special class member serialPersistentFields.

See Also:
serializableFields(), SerialFieldTag

superclass

public ClassDoc superclass()
Return the superclass of this class. Return null is this is an interface.

Returns:
the ClassDoc for the superclass of this class, null if there is no superclass.

subclassOf

public boolean subclassOf(ClassDoc cd)
Test whether this class is a subclass of the specified class. If this is an interface, return false for all classes except java.lang.Object (we must keep this unexpected behavior for compatibility reasons).

Parameters:
cd - the candidate superclass.
Returns:
true if cd is a superclass of this class.

interfaces

public ClassDoc[] interfaces()
Return interfaces implemented by this class or interfaces extended by this interface. Includes only directly-declared interfaces, not inherited interfaces. Return an empty array if there are no interfaces.

Returns:
An array of ClassDoc objects representing the interfaces.

fields

public FieldDoc[] fields()
Return included fields in this class or interface.

Returns:
an array of FieldDoc objects representing the included fields in this class or interface.

fields

public FieldDoc[] fields(boolean filter)
Return fields in this class or interface, filtered to the specified access modifier option

Parameters:
filter - Specify true to filter according to the specified access modifier option. Specify false to include all fields regardless of access modifier option.
Returns:
an array of FieldDoc objects representing the included fields in this class or interface.

methods

public MethodDoc[] methods()
Return included methods in this class or interface. Same as methods(true).

Returns:
an array of MethodDoc objects representing the included methods in this class or interface. Does not include constructors.

methods

public MethodDoc[] methods(boolean filter)
Return methods in this class or interface, filtered to the specified access modifier option. Does not include constructors.

Parameters:
filter - Specify true to filter according to the specified access modifier option. Specify false to include all methods regardless of access modifier option.
Returns:
an array of MethodDoc objects representing the included methods in this class or interface.

constructors

public ConstructorDoc[] constructors()
Return included constructors in this class. An array containing the default no-arg constructor is returned if no other constructors exist. Return empty array if this is an interface.

Returns:
an array of ConstructorDoc objects representing the included constructors in this class.

constructors

public ConstructorDoc[] constructors(boolean filter)
Return constructors in this class, filtered to the specified access modifier option. Return an array containing the default no-arg constructor if no other constructors exist.

Parameters:
filter - Specify true to filter according to the specified access modifier option. Specify false to include all constructors regardless of access modifier option.
Returns:
an array of ConstructorDoc objects representing the included constructors in this class.

innerClasses

public ClassDoc[] innerClasses()
Return included nested classes and interfaces within this class or interface. This includes both static and non-static nested classes. (This method should have been named nestedClasses(), as inner classes are technically non-static.) Anonymous and local classes or interfaces are not included.

Returns:
an array of ClassDoc objects representing the included classes and interfaces defined in this class or interface.

innerClasses

public ClassDoc[] innerClasses(boolean filter)
Return nested classes and interfaces within this class or interface filtered to the specified access modifier option. This includes both static and non-static nested classes. Anonymous and local classes are not included.

Parameters:
filter - Specify true to filter according to the specified access modifier option. Specify false to include all nested classes regardless of access modifier option.
Returns:
a filtered array of ClassDoc objects representing the included classes and interfaces defined in this class or interface.

findClass

public ClassDoc findClass(String className)
Find the specified class or interface within the context of this class doc. Search order: 1) qualified name, 2) nested in this class or interface, 3) in this package, 4) in the class imports, 5) in the package imports. Return the ClassDoc if found, null if not found.

importedClasses

public ClassDoc[] importedClasses()
Get the list of classes and interfaces declared as imported. These are called "single-type-import declarations" in the Java Language Specification.

Returns:
an array of ClassDoc representing the imported classes.

importedPackages

public PackageDoc[] importedPackages()
Get the list of packages declared as imported. These are called "type-import-on-demand declarations" in the Java Language Specification.

Returns:
an array of PackageDoc representing the imported packages.
Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


ConstructorDoc (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.javadoc
Interface ConstructorDoc

All Superinterfaces:
Comparable, Doc, ExecutableMemberDoc, MemberDoc, ProgramElementDoc
public interface ConstructorDoc
extends ExecutableMemberDoc

Represents a constructor of a java class.

Since:
JDK1.2

Method Summary
 String qualifiedName()
Get the name.
Methods inherited from interface com.sun.javadoc.ExecutableMemberDoc
flatSignature, isNative, isSynchronized, parameters, paramTags, signature, thrownExceptions, throwsTags
Methods inherited from interface com.sun.javadoc.MemberDoc
isSynthetic
Methods inherited from interface com.sun.javadoc.ProgramElementDoc
containingClass, containingPackage, isFinal, isPackagePrivate, isPrivate, isProtected, isPublic, isStatic, modifiers, modifierSpecifier
Methods inherited from interface com.sun.javadoc.Doc
commentText, compareTo, firstSentenceTags, getRawCommentText, inlineTags, isClass, isConstructor, isError, isException, isField, isIncluded, isInterface, isMethod, isOrdinaryClass, name, position, seeTags, setRawCommentText, tags, tags

Method Detail

qualifiedName

public String qualifiedName()
Get the name.

Specified by:
qualifiedName in interface ProgramElementDoc
Returns:
the qualified name of the member.
Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Doc (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.javadoc
Interface Doc

All Superinterfaces:
Comparable
All Known Subinterfaces:
ClassDoc, ConstructorDoc, ExecutableMemberDoc, FieldDoc, MemberDoc, MethodDoc, PackageDoc, ProgramElementDoc, RootDoc
public interface Doc
extends Comparable

Represents Java language constructs (package, class, constructor, method, field) which have comments and have been processed by this run of javadoc. All Doc objects are unique, that is, they are == comparable.

Since:
JDK1.2

Method Summary
String | commentText() Return the text of the comment for this doc item.
int | compareTo(Object obj) Compares this doc object with the specified object for order.
Tag[] | firstSentenceTags() Return the first sentence of the comment as an array of tags.
String | getRawCommentText() Return the full unprocessed text of the comment.
Tag[] | inlineTags() Return comment as an array of tags.
boolean | isClass() Is this Doc item a class (not an interface)? This includes ordinary classes, errors and exceptions.
boolean | isConstructor() Is this Doc item a constructor?
boolean | isError() Is this Doc item an error class?
boolean | isException() Is this Doc item an exception class?
boolean | isField() Is this Doc item a field?
boolean | isIncluded() Return true if this Doc item is included in the result set.
boolean | isInterface() Is this Doc item an interface?
boolean | isMethod() Is this Doc item a method (i.e.
boolean | isOrdinaryClass() Is this Doc item an ordinary class? (i.e.
String | name() Returns the non-qualified name of this Doc item.
SourcePosition | position() Return the source position of the first line of the corresponding declaration, or null if no position is available.
SeeTag[] | seeTags() Return the see also tags in this Doc item.
void | setRawCommentText(String rawDocumentation) Set the full unprocessed text of the comment.
Tag[] | tags() Return all tags in this Doc item.
Tag[] | tags(String tagname) Return tags of the specified kind in this Doc item.

Method Detail

commentText

public String commentText()
Return the text of the comment for this doc item. Tags have been removed.

tags

public Tag[] tags()
Return all tags in this Doc item.

Returns:
an array of Tag objects containing all tags on this Doc item.

tags

public Tag[] tags(String tagname)
Return tags of the specified kind in this Doc item. For example, if 'tagname' has value "@serial", all tags in this Doc item of kind "@serial" will be returned.

Parameters:
tagname - name of the tag kind to search for.
Returns:
an array of Tag containing all tags whose 'kind()' matches 'tagname'.

seeTags

public SeeTag[] seeTags()
Return the see also tags in this Doc item.

Returns:
an array of SeeTag containing all @see tags.

inlineTags

public Tag[] inlineTags()
Return comment as an array of tags. Includes inline tags (i.e. {@link reference} tags) but not block tags. Each section of plain text is represented as a Tag of kind "Text". Inline tags are represented as a SeeTag of kind "@see" and name "@link".

Returns:
an array of Tags representing the comment

firstSentenceTags

public Tag[] firstSentenceTags()
Return the first sentence of the comment as an array of tags. Includes inline tags (i.e. {@link reference} tags) but not block tags. Each section of plain text is represented as a Tag of kind "Text". Inline tags are represented as a SeeTag of kind "@see" and name "@link".

If the locale is English language, the first sentence is determined by the rules described in the Java Language Specification (first version): "This sentence ends at the first period that is followed by a blank, tab, or line terminator or at the first tagline.", in addition a line will be terminated by block HTML tags: <p> </p> <h1> <h2> <h3> <h4> <h5> <h6> <hr> <pre> or </pre>. If the locale is not English, the sentence end will be determined by java.text.BreakIterator.getSentenceInstance(Locale).

Returns:
an array of Tags representing the first sentence of the comment

getRawCommentText

public String getRawCommentText()
Return the full unprocessed text of the comment. Tags are included as text. Used mainly for store and retrieve operations like internalization.

setRawCommentText

public void setRawCommentText(String rawDocumentation)
Set the full unprocessed text of the comment. Tags are included as text. Used mainly for store and retrieve operations like internalization.

name

public String name()
Returns the non-qualified name of this Doc item.

Returns:
the name

compareTo

public int compareTo(Object obj)
Compares this doc object with the specified object for order. Returns a negative integer, zero, or a positive integer as this doc object is less than, equal to, or greater than the given object.

This method satisfies the Comparable interface.

Specified by:
compareTo in interface Comparable
Parameters:
obj - the Object to be compared.
Returns:
a negative integer, zero, or a positive integer as this Object is less than, equal to, or greater than the given Object.
Throws:
ClassCastException - the specified Object's type prevents it from being compared to this Object.

isField

public boolean isField()
Is this Doc item a field?

Returns:
true if it represents a field

isMethod

public boolean isMethod()
Is this Doc item a method (i.e. not a constructor)? False until overridden.

Returns:
true if it represents a method, false if it is anything else, including constructor, field, class, ...

isConstructor

public boolean isConstructor()
Is this Doc item a constructor?

Returns:
true if it represents a constructor

isInterface

public boolean isInterface()
Is this Doc item an interface?

Returns:
true if it represents an interface

isException

public boolean isException()
Is this Doc item an exception class?

Returns:
true if it represents an exception

isError

public boolean isError()
Is this Doc item an error class?

Returns:
true if it represents a error

isOrdinaryClass

public boolean isOrdinaryClass()
Is this Doc item an ordinary class? (i.e. not an interface, exception, or error)?

Returns:
true if it represents an ordinary class

isClass

public boolean isClass()
Is this Doc item a class (not an interface)? This includes ordinary classes, errors and exceptions.

Returns:
true if it represents a class (not an interface)

isIncluded

public boolean isIncluded()
Return true if this Doc item is included in the result set.

position

public SourcePosition position()
Return the source position of the first line of the corresponding declaration, or null if no position is available. A default constructor returns null because it has no location in the source file.

Since:
1.4
Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


DocErrorReporter (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.javadoc
Interface DocErrorReporter

All Known Subinterfaces:
RootDoc
public interface DocErrorReporter

This interface provides error, warning and notice printing.

Since:
JDK1.2

Method Summary
void | printError(SourcePosition pos, String msg) Print an error message and increment error count.
void | printError(String msg) Print error message and increment error count.
void | printNotice(SourcePosition pos, String msg) Print a message.
void | printNotice(String msg) Print a message.
void | printWarning(SourcePosition pos, String msg) Print warning message and increment warning count.
void | printWarning(String msg) Print warning message and increment warning count.

Method Detail

printError

public void printError(String msg)
Print error message and increment error count.

Parameters:
msg - message to print

printError

public void printError(SourcePosition pos,
                       String msg)
Print an error message and increment error count.

Parameters:
pos - the position item where the error occurs
msg - message to print
Since:
1.4

printWarning

public void printWarning(String msg)
Print warning message and increment warning count.

Parameters:
msg - message to print

printWarning

public void printWarning(SourcePosition pos,
                         String msg)
Print warning message and increment warning count.

Parameters:
pos - the position item where the warning occurs
msg - message to print
Since:
1.4

printNotice

public void printNotice(String msg)
Print a message.

Parameters:
msg - message to print

printNotice

public void printNotice(SourcePosition pos,
                        String msg)
Print a message.

Parameters:
pos - the position item where the message occurs
msg - message to print
Since:
1.4
Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Doclet (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

com.sun.javadoc
Class Doclet

java.lang.Object
    extended by com.sun.javadoc.Doclet
public abstract class Doclet
extends Object

This is an example of a starting class for a doclet, showing the entry-point methods. A starting class must import com.sun.javadoc.* and implement the start(RootDoc) method, as described in the package description. If the doclet takes command line options, it must also implement optionLength and validOptions. To start the doclet, you pass -doclet followed by the fully-qualified name of the starting class on the javadoc tool command line.

Constructor Summary
Doclet()
Method Summary
static int | optionLength(String option) Check for doclet-added options.
static boolean | start(RootDoc root) Generate documentation here.
static boolean | validOptions(String[][] options, DocErrorReporter reporter) Check that options have the correct arguments.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

Doclet

public Doclet()
Method Detail

start

public static boolean start(RootDoc root)
Generate documentation here. This method is required for all doclets.

Returns:
true on success.

optionLength

public static int optionLength(String option)
Check for doclet-added options. Returns the number of arguments you must specify on the command line for the given option. For example, "-d docs" would return 2.

This method is required if the doclet contains any options. If this method is missing, Javadoc will print an invalid flag error for every option.

Returns:
number of arguments on the command line for an option including the option name itself. Zero return means option not known. Negative value means error occurred.

validOptions

public static boolean validOptions(String[][] options,
                                   DocErrorReporter reporter)
Check that options have the correct arguments.

This method is not required, but is recommended, as every option will be considered valid if this method is not present. It will default gracefully (to true) if absent.

Printing option related error messages (using the provided DocErrorReporter) is the responsibility of this method.

Returns:
true if the options are valid.
Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


ExecutableMemberDoc (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.javadoc
Interface ExecutableMemberDoc

All Superinterfaces:
Comparable, Doc, MemberDoc, ProgramElementDoc
All Known Subinterfaces:
ConstructorDoc, MethodDoc
public interface ExecutableMemberDoc
extends MemberDoc

Represents a method or constructor of a java class.

Since:
JDK1.2

Method Summary
String | flatSignature() get flat signature.
boolean | isNative() Return true if this method is native
boolean | isSynchronized() Return true if this method is synchronized
Parameter[] | parameters() Get argument information.
ParamTag[] | paramTags() Return the param tags in this method.
String | signature() Get the signature.
ClassDoc[] | thrownExceptions() Return exceptions this method or constructor throws.
ThrowsTag[] | throwsTags() Return the throws tags in this method.
Methods inherited from interface com.sun.javadoc.MemberDoc
isSynthetic
Methods inherited from interface com.sun.javadoc.ProgramElementDoc
containingClass, containingPackage, isFinal, isPackagePrivate, isPrivate, isProtected, isPublic, isStatic, modifiers, modifierSpecifier, qualifiedName
Methods inherited from interface com.sun.javadoc.Doc
commentText, compareTo, firstSentenceTags, getRawCommentText, inlineTags, isClass, isConstructor, isError, isException, isField, isIncluded, isInterface, isMethod, isOrdinaryClass, name, position, seeTags, setRawCommentText, tags, tags

Method Detail

thrownExceptions

public ClassDoc[] thrownExceptions()
Return exceptions this method or constructor throws.

Returns:
an array of Type[] representing the exceptions thrown by this method.

isNative

public boolean isNative()
Return true if this method is native

isSynchronized

public boolean isSynchronized()
Return true if this method is synchronized

parameters

public Parameter[] parameters()
Get argument information.

Returns:
an array of Parameter, one element per argument in the order the arguments are present.
See Also:
Parameter

throwsTags

public ThrowsTag[] throwsTags()
Return the throws tags in this method.

Returns:
an array of ThrowTag containing all @exception and @throws tags.

paramTags

public ParamTag[] paramTags()
Return the param tags in this method.

Returns:
an array of ParamTag containing all @param tags.

signature

public String signature()
Get the signature. It is the parameter list, type is qualified. For instance, for a method mymethod(String x, int y), it will return (java.lang.String,int).

flatSignature

public String flatSignature()
get flat signature. all types are not qualified. return a String, which is the flat signiture of this member. It is the parameter list, type is not qualified. For instance, for a method mymethod(String x, int y), it will return (String, int).

Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


FieldDoc (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.javadoc
Interface FieldDoc

All Superinterfaces:
Comparable, Doc, MemberDoc, ProgramElementDoc
public interface FieldDoc
extends MemberDoc

Represents a field in a java class.

Since:
JDK1.2
See Also:
MemberDoc

Method Summary
Object | constantValue() Get the value of a constant field.
String | constantValueExpression() Get the value of a constant field.
boolean | isTransient() Return true if this field is transient
boolean | isVolatile() Return true if this field is volatile
SerialFieldTag[] | serialFieldTags() Return the serialField tags in this FieldDoc item.
Type | type() Get type of this field.
Methods inherited from interface com.sun.javadoc.MemberDoc
isSynthetic
Methods inherited from interface com.sun.javadoc.ProgramElementDoc
containingClass, containingPackage, isFinal, isPackagePrivate, isPrivate, isProtected, isPublic, isStatic, modifiers, modifierSpecifier, qualifiedName
Methods inherited from interface com.sun.javadoc.Doc
commentText, compareTo, firstSentenceTags, getRawCommentText, inlineTags, isClass, isConstructor, isError, isException, isField, isIncluded, isInterface, isMethod, isOrdinaryClass, name, position, seeTags, setRawCommentText, tags, tags

Method Detail

type

public Type type()
Get type of this field.

isTransient

public boolean isTransient()
Return true if this field is transient

isVolatile

public boolean isVolatile()
Return true if this field is volatile

serialFieldTags

public SerialFieldTag[] serialFieldTags()
Return the serialField tags in this FieldDoc item.

Returns:
an array of SerialFieldTag objects containing all @serialField tags.

constantValue

public Object constantValue()
Get the value of a constant field.

Returns:
the value of a constant field. The value is automatically wrapped in an object if it has a primitive type. If the field is not constant, returns null.

constantValueExpression

public String constantValueExpression()
Get the value of a constant field.

Returns:
the text of a Java language expression whose value is the value of the constant. The expression uses no identifiers other than primitive literals. If the field is not constant, returns null.
Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


MemberDoc (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.javadoc
Interface MemberDoc

All Superinterfaces:
Comparable, Doc, ProgramElementDoc
All Known Subinterfaces:
ConstructorDoc, ExecutableMemberDoc, FieldDoc, MethodDoc
public interface MemberDoc
extends ProgramElementDoc

Represents a member of a java class: field, constructor, or method. This is an abstract class dealing with information common to method, constructor and field members. Class members of a class (innerclasses) are represented instead by ClassDoc.

See Also:
MethodDoc, FieldDoc, ClassDoc

Method Summary
 boolean isSynthetic()
Returns true if this member was synthesized by the compiler.
Methods inherited from interface com.sun.javadoc.ProgramElementDoc
containingClass, containingPackage, isFinal, isPackagePrivate, isPrivate, isProtected, isPublic, isStatic, modifiers, modifierSpecifier, qualifiedName
Methods inherited from interface com.sun.javadoc.Doc
commentText, compareTo, firstSentenceTags, getRawCommentText, inlineTags, isClass, isConstructor, isError, isException, isField, isIncluded, isInterface, isMethod, isOrdinaryClass, name, position, seeTags, setRawCommentText, tags, tags

Method Detail

isSynthetic

public boolean isSynthetic()
Returns true if this member was synthesized by the compiler.

Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


MethodDoc (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.javadoc
Interface MethodDoc

All Superinterfaces:
Comparable, Doc, ExecutableMemberDoc, MemberDoc, ProgramElementDoc
public interface MethodDoc
extends ExecutableMemberDoc

Represents a method of a java class.

Since:
JDK1.2

Method Summary
boolean | isAbstract() Return true if this method is abstract
ClassDoc | overriddenClass() Return the class containing the method that this method overrides.
MethodDoc | overriddenMethod() Return the method that this method overrides.
Type | returnType() Get return type.
Methods inherited from interface com.sun.javadoc.ExecutableMemberDoc
flatSignature, isNative, isSynchronized, parameters, paramTags, signature, thrownExceptions, throwsTags
Methods inherited from interface com.sun.javadoc.MemberDoc
isSynthetic
Methods inherited from interface com.sun.javadoc.ProgramElementDoc
containingClass, containingPackage, isFinal, isPackagePrivate, isPrivate, isProtected, isPublic, isStatic, modifiers, modifierSpecifier, qualifiedName
Methods inherited from interface com.sun.javadoc.Doc
commentText, compareTo, firstSentenceTags, getRawCommentText, inlineTags, isClass, isConstructor, isError, isException, isField, isIncluded, isInterface, isMethod, isOrdinaryClass, name, position, seeTags, setRawCommentText, tags, tags

Method Detail

isAbstract

public boolean isAbstract()
Return true if this method is abstract

returnType

public Type returnType()
Get return type.

Returns:
the return type of this method, null if it is a constructor.

overriddenClass

public ClassDoc overriddenClass()
Return the class containing the method that this method overrides.

Returns:
a ClassDoc representing the superclass defining a method that this method overrides, null if this method does not override.

overriddenMethod

public MethodDoc overriddenMethod()
Return the method that this method overrides.

Returns:
a MethodDoc representing a method definition in a superclass this method overrides, null if this method does not override.
Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


com.sun.javadoc (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES

Package com.sun.javadoc

The Doclet API (also called the Javadoc API) provides a mechanism for clients to inspect the source-level structure of programs and libraries, including javadoc comments embedded in the source.

See:
Description

Interface Summary
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.
ConstructorDoc | Represents a constructor of a java class.
Doc | Represents Java language constructs (package, class, constructor, method, field) which have comments and have been processed by this run of javadoc.
DocErrorReporter | This interface provides error, warning and notice printing.
ExecutableMemberDoc | Represents a method or constructor of a java class.
FieldDoc | Represents a field in a java class.
MemberDoc | Represents a member of a java class: field, constructor, or method.
MethodDoc | Represents a method of a java class.
PackageDoc | Represents a java package.
Parameter | Parameter information.
ParamTag | Represents an @param documentation tag.
ProgramElementDoc | Represents a java program element: class, interface, field, constructor, or method.
RootDoc | Represents the root of the program structure information for one run of javadoc.
SeeTag | Represents a user-defined cross-reference to related documentation.
SerialFieldTag | Documents a Serializable field defined by an ObjectStreamField.
SourcePosition | This interface describes a source position: filename, line number, and column number.
Tag | Represents a simple documentation tag, such as @since, @author, @version.
ThrowsTag | Represents a @throws or @exception documentation tag.
Type | Represents a java type.

Class Summary
Doclet This is an example of a starting class for a doclet, showing the entry-point methods.

Package com.sun.javadoc Description

The Doclet API (also called the Javadoc API) provides a mechanism for clients to inspect the source-level structure of programs and libraries, including javadoc comments embedded in the source. This is useful for documentation, program checking, automatic code generation and many other tools.

Doclets are invoked by javadoc and use this API to write out program information to files. For example, the standard doclet is called by default and writes out documentation to HTML files.

The invocation is defined by the abstract Doclet class -- the entry point is the start method:

    public static boolean start(RootDoc root)
The RootDoc instance holds the root of the program structure information. From this root all other program structure information can be extracted.

Terminology

When calling javadoc, you pass in package names and source file names -- these are called the specified packages and classes. You also pass in Javadoc options; the access control Javadoc options (-public, -protected, -package, and -private) filter program elements, producing a result set, called the included set, or "documented" set. (The unfiltered set is also available through allClasses(false).)

Throughout this API, the term class is normally a shorthand for "class or interface", as in: ClassDoc, allClasses(), and findClass(String). In only a couple of other places, it means "class, as opposed to interface", as in: isClass(). In the second sense, this API calls out three kinds of classes: ordinary classes, errors and exceptions). Throughout the API, the detailed description of each program element describes explicitly which meaning is being used.

A qualified class or interface name is one that has its package name prepended to it, such as java.lang.String. A non-qualified name has no package name, such as String.

Example

The following is an example doclet that displays information in the @param tags of the processed classes:
import com.sun.javadoc.*;

public class ListParams extends Doclet {

    public static boolean start(RootDoc root) {
        ClassDoc[] classes = root.classes();
        for (int i = 0; i < classes.length; ++i) {
            ClassDoc cd = classes[i];
            printMembers(cd.constructors());
            printMembers(cd.methods());
        }
        return true;
    }

    static void printMembers(ExecutableMemberDoc[] mems) {
        for (int i = 0; i < mems.length; ++i) {
            ParamTag[] params = mems[i].paramTags();
            System.out.println(mems[i].qualifiedName());
            for (int j = 0; j < params.length; ++j) {
                System.out.println("   " + params[j].parameterName()
                    + " - " + params[j].parameterComment());
            }
        }
    }
}
Interfaces and methods from the Javadoc API are marked in red. Doclet is an abstract class that specifies the invocation interface for doclets, Doclet holds class or interface information, ExecutableMemberDoc is a superinterface of MethodDoc and ConstructorDoc, and ParamTag holds information from "@param" tags.

This doclet when invoked with a command line like:

    javadoc -doclet ListParams -sourcepath <source-location> java.util
producing output like:
    ...
    java.util.ArrayList.add
       index - index at which the specified element is to be inserted.
       element - element to be inserted.
    java.util.ArrayList.remove
       index - the index of the element to removed.
    ...

See Also:
Doclet, RootDoc
Package Class Use Tree Deprecated Index Help
Doclet API
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


com.sun.javadoc Class Hierarchy (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES

Hierarchy For Package com.sun.javadoc

Class Hierarchy

  • class java.lang.Object
    • class com.sun.javadoc.Doclet

Interface Hierarchy

  • interface java.lang.Comparable
    • interface com.sun.javadoc.Doc
      • interface com.sun.javadoc.PackageDoc
      • interface com.sun.javadoc.ProgramElementDoc
        • interface com.sun.javadoc.ClassDoc (also extends com.sun.javadoc.Type)
        • interface com.sun.javadoc.MemberDoc
          • interface com.sun.javadoc.ExecutableMemberDoc
            • interface com.sun.javadoc.ConstructorDoc
            • interface com.sun.javadoc.MethodDoc
          • interface com.sun.javadoc.FieldDoc
      • interface com.sun.javadoc.RootDoc (also extends com.sun.javadoc.DocErrorReporter)
    • interface com.sun.javadoc.SerialFieldTag (also extends com.sun.javadoc.Tag)
  • interface com.sun.javadoc.DocErrorReporter
    • interface com.sun.javadoc.RootDoc (also extends com.sun.javadoc.Doc)
  • interface com.sun.javadoc.Parameter
  • interface com.sun.javadoc.SourcePosition
  • interface com.sun.javadoc.Tag
    • interface com.sun.javadoc.ParamTag
    • interface com.sun.javadoc.SeeTag
    • interface com.sun.javadoc.SerialFieldTag (also extends java.lang.Comparable)
    • interface com.sun.javadoc.ThrowsTag
  • interface com.sun.javadoc.Type
    • interface com.sun.javadoc.ClassDoc (also extends com.sun.javadoc.ProgramElementDoc)
Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Package com.sun.javadoc (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES

Uses of Package
com.sun.javadoc

Classes in com.sun.javadoc used by com.sun.javadoc
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.
ConstructorDoc
Represents a constructor of a java class.
Doc
Represents Java language constructs (package, class, constructor, method, field) which have comments and have been processed by this run of javadoc.
DocErrorReporter
This interface provides error, warning and notice printing.
ExecutableMemberDoc
Represents a method or constructor of a java class.
FieldDoc
Represents a field in a java class.
MemberDoc
Represents a member of a java class: field, constructor, or method.
MethodDoc
Represents a method of a java class.
PackageDoc
Represents a java package.
Parameter
Parameter information.
ParamTag
Represents an @param documentation tag.
ProgramElementDoc
Represents a java program element: class, interface, field, constructor, or method.
RootDoc
Represents the root of the program structure information for one run of javadoc.
SeeTag
Represents a user-defined cross-reference to related documentation.
SerialFieldTag
Documents a Serializable field defined by an ObjectStreamField.
SourcePosition
This interface describes a source position: filename, line number, and column number.
Tag
Represents a simple documentation tag, such as @since, @author, @version.
ThrowsTag
Represents a @throws or @exception documentation tag.
Type
Represents a java type.

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


PackageDoc (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.javadoc
Interface PackageDoc

All Superinterfaces:
Comparable, Doc
public interface PackageDoc
extends Doc

Represents a java package. Provides access to information about the package, the package's comment and tags, and the classes in the package.

Since:
JDK1.2

Method Summary
ClassDoc[] | allClasses() Get all included classes and interfaces in the package.
ClassDoc[] | allClasses(boolean filter) Get all classes and interfaces in the package, filtered to the specified access modifier option.
ClassDoc[] | errors() Get included Error classes in this package.
ClassDoc[] | exceptions() Get included Exception classes in this package.
ClassDoc | findClass(String className) Lookup a class or interface within this package.
ClassDoc[] | interfaces() Get included Interfaces in this package.
ClassDoc[] | ordinaryClasses() Get included ordinary classes (that is, exclude exceptions, errors and interfaces) in this package.
Methods inherited from interface com.sun.javadoc.Doc
commentText, compareTo, firstSentenceTags, getRawCommentText, inlineTags, isClass, isConstructor, isError, isException, isField, isIncluded, isInterface, isMethod, isOrdinaryClass, name, position, seeTags, setRawCommentText, tags, tags

Method Detail

allClasses

public ClassDoc[] allClasses(boolean filter)
Get all classes and interfaces in the package, filtered to the specified access modifier option.

Parameters:
filter - Specifying true filters according to the specified access modifier option. Specifying false includes all classes and interfaces regardless of access modifier option.
Returns:
filtered classes and interfaces in this package
Since:
1.4

allClasses

public ClassDoc[] allClasses()
Get all included classes and interfaces in the package. Same as allClasses(true).

Returns:
all included classes and interfaces in this package.

ordinaryClasses

public ClassDoc[] ordinaryClasses()
Get included ordinary classes (that is, exclude exceptions, errors and interfaces) in this package.

Returns:
included ordinary classes in this package.

exceptions

public ClassDoc[] exceptions()
Get included Exception classes in this package.

Returns:
included Exceptions in this package.

errors

public ClassDoc[] errors()
Get included Error classes in this package.

Returns:
included Errors in this package.

interfaces

public ClassDoc[] interfaces()
Get included Interfaces in this package.

Returns:
included Interfaces in this package.

findClass

public ClassDoc findClass(String className)
Lookup a class or interface within this package.

Returns:
ClassDoc of found class or interface, or null if not found.
Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Parameter (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.javadoc
Interface Parameter

public interface Parameter

Parameter information. This includes a parameter type and parameter name.

Method Summary
String | name() Get local name of this parameter.
String | toString() Returns a string representation of the class.
Type | type() Get the type of this parameter.
String | typeName() Get type name of this parameter.

Method Detail

type

public Type type()
Get the type of this parameter.

name

public String name()
Get local name of this parameter. For example if parameter is the short 'index', returns "index".

typeName

public String typeName()
Get type name of this parameter. For example if parameter is the short 'index', returns "short".

toString

public String toString()
Returns a string representation of the class.

For example if parameter is the short 'index', returns "short index".

Returns:
type name and parameter name of this parameter.
Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


ParamTag (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.javadoc
Interface ParamTag

All Superinterfaces:
Tag
public interface ParamTag
extends Tag

Represents an @param documentation tag. Parses and stores the name and comment parts of the method/constructor parameter tag.

Method Summary
String | parameterComment() Return the parameter comment associated with this ParamTag.
String | parameterName() Return the name of the parameter associated with this ParamTag.
Methods inherited from interface com.sun.javadoc.Tag
firstSentenceTags, holder, inlineTags, kind, name, position, text, toString

Method Detail

parameterName

public String parameterName()
Return the name of the parameter associated with this ParamTag.

Returns:
the parameter name.

parameterComment

public String parameterComment()
Return the parameter comment associated with this ParamTag.

Returns:
the parameter comment.
Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


ProgramElementDoc (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.javadoc
Interface ProgramElementDoc

All Superinterfaces:
Comparable, Doc
All Known Subinterfaces:
ClassDoc, ConstructorDoc, ExecutableMemberDoc, FieldDoc, MemberDoc, MethodDoc
public interface ProgramElementDoc
extends Doc

Represents a java program element: class, interface, field, constructor, or method. This is an abstract class dealing with information common to these elements.

See Also:
MemberDoc, ClassDoc

Method Summary
ClassDoc | containingClass() Get the containing class or interface of this program element.
PackageDoc | containingPackage() Get the package that this program element is contained in.
boolean | isFinal() Return true if this program element is final.
boolean | isPackagePrivate() Return true if this program element is package private.
boolean | isPrivate() Return true if this program element is private.
boolean | isProtected() Return true if this program element is protected.
boolean | isPublic() Return true if this program element is public.
boolean | isStatic() Return true if this program element is static.
String | modifiers() Get modifiers string.
int | modifierSpecifier() Get the modifier specifier integer.
String | qualifiedName() Get the fully qualified name of this program element.
Methods inherited from interface com.sun.javadoc.Doc
commentText, compareTo, firstSentenceTags, getRawCommentText, inlineTags, isClass, isConstructor, isError, isException, isField, isIncluded, isInterface, isMethod, isOrdinaryClass, name, position, seeTags, setRawCommentText, tags, tags

Method Detail

containingClass

public ClassDoc containingClass()
Get the containing class or interface of this program element.

Returns:
a ClassDoc for this element's containing class or interface. If this is a top-level class or interface, return null.

containingPackage

public PackageDoc containingPackage()
Get the package that this program element is contained in.

Returns:
a PackageDoc for this element containing package. If in the unnamed package, this PackageDoc will have the name "".

qualifiedName

public String qualifiedName()
Get the fully qualified name of this program element. For example, for the class java.util.Hashtable, return "java.util.Hashtable".

For the method bar() in class Foo in the unnamed package, return "Foo.bar".

Returns:
the qualified name of the program element as a String.

modifierSpecifier

public int modifierSpecifier()
Get the modifier specifier integer.

See Also:
Modifier

modifiers

public String modifiers()
Get modifiers string. For example, for:
   public abstract int foo() { ... }
return "public abstract".

isPublic

public boolean isPublic()
Return true if this program element is public.

isProtected

public boolean isProtected()
Return true if this program element is protected.

isPrivate

public boolean isPrivate()
Return true if this program element is private.

isPackagePrivate

public boolean isPackagePrivate()
Return true if this program element is package private.

isStatic

public boolean isStatic()
Return true if this program element is static.

isFinal

public boolean isFinal()
Return true if this program element is final.

Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


RootDoc (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.javadoc
Interface RootDoc

All Superinterfaces:
Comparable, Doc, DocErrorReporter
public interface RootDoc
extends Doc, DocErrorReporter

Represents the root of the program structure information for one run of javadoc. From this root all other program structure information can be extracted. Also represents the command line information -- the packages, classes and options specified by the user.

Since:
JDK1.2

Method Summary
ClassDoc[] | classes() Return the included classes and interfaces in all packages.
ClassDoc | classNamed(String qualifiedName) Return a ClassDoc for the specified class or interface name.
String[][] | options() Command line options.
PackageDoc | packageNamed(String name) Return a PackageDoc for the specified package name.
ClassDoc[] | specifiedClasses() Return the classes and interfaces specified as source file names on the command line.
PackageDoc[] | specifiedPackages() Return the packages specified on the command line.
Methods inherited from interface com.sun.javadoc.Doc
commentText, compareTo, firstSentenceTags, getRawCommentText, inlineTags, isClass, isConstructor, isError, isException, isField, isIncluded, isInterface, isMethod, isOrdinaryClass, name, position, seeTags, setRawCommentText, tags, tags
Methods inherited from interface com.sun.javadoc.DocErrorReporter
printError, printError, printNotice, printNotice, printWarning, printWarning

Method Detail

options

public String[][] options()
Command line options.

For example, given:

     javadoc -foo this that -bar other ...
this method will return:
      options()[0][0] = "-foo"
      options()[0][1] = "this"
      options()[0][2] = "that"
      options()[1][0] = "-bar"
      options()[1][1] = "other"

Returns:
an array of arrays of String.

specifiedPackages

public PackageDoc[] specifiedPackages()
Return the packages specified on the command line. If -subpackages and -exclude options are used, return all the non-excluded packages.

Returns:
packages specified on the command line.

specifiedClasses

public ClassDoc[] specifiedClasses()
Return the classes and interfaces specified as source file names on the command line.

Returns:
classes and interfaces specified on the command line.

classes

public ClassDoc[] classes()
Return the included classes and interfaces in all packages.

Returns:
included classes and interfaces in all packages.

packageNamed

public PackageDoc packageNamed(String name)
Return a PackageDoc for the specified package name.

Parameters:
name - package name
Returns:
a PackageDoc holding the specified package, null if this package is not referenced.

classNamed

public ClassDoc classNamed(String qualifiedName)
Return a ClassDoc for the specified class or interface name.

Parameters:
qualifiedName - qualified class or package name
Returns:
a ClassDoc holding the specified class, null if this class is not referenced.
Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


SeeTag (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.javadoc
Interface SeeTag

All Superinterfaces:
Tag
public interface SeeTag
extends Tag

Represents a user-defined cross-reference to related documentation. The tag can reference a package, class or member, or can hold plain text. (The plain text might be a reference to something not online, such as a printed book, or be a hard-coded HTML link.) The reference can either be inline with the comment, using {@link}, or a separate block comment, using @see. Method name() returns "@link" (no curly braces) or "@see", depending on the tag. Method kind() returns "@see" for both tags.

Method Summary
String | label() Get the label of the @see tag.
ClassDoc | referencedClass() Get the class doc referenced by the class name part of @see.
String | referencedClassName() Get the class or interface name of the @see reference.
MemberDoc | referencedMember() Get the member doc for the field, constructor or method referenced by @see.
String | referencedMemberName() Get the field, constructor or method substring of the @see reference.
PackageDoc | referencedPackage() Get the package doc when @see references only a package.
Methods inherited from interface com.sun.javadoc.Tag
firstSentenceTags, holder, inlineTags, kind, name, position, text, toString

Method Detail

label

public String label()
Get the label of the @see tag. Return null if no label is present. For example, for:

@see String#trim() the trim method

return "the trim method".

referencedPackage

public PackageDoc referencedPackage()
Get the package doc when @see references only a package. Return null if the package cannot be found, or if @see references any other element (class, interface, field, constructor, method) or non-element. For example, for:

@see java.lang

return the PackageDoc for java.lang.

referencedClassName

public String referencedClassName()
Get the class or interface name of the @see reference. The name is fully qualified if the name specified in the original @see tag was fully qualified, or if the class or interface can be found; otherwise it is unqualified. If @see references only a package name, then return the package name instead. For example, for:

@see String#valueOf(java.lang.Object)

return "java.lang.String". For "@see java.lang", return "java.lang". Return null if @see references a non-element, such as @see <a href="java.sun.com">.

referencedClass

public ClassDoc referencedClass()
Get the class doc referenced by the class name part of @see. Return null if the class cannot be found. For example, for:

@see String#valueOf(java.lang.Object)

return the ClassDoc for java.lang.String.

referencedMemberName

public String referencedMemberName()
Get the field, constructor or method substring of the @see reference. Return null if the reference is to any other element or to any non-element. References to member classes (nested classes) return null. For example, for:

@see String#startsWith(String)

return "startsWith(String)".

referencedMember

public MemberDoc referencedMember()
Get the member doc for the field, constructor or method referenced by @see. Return null if the member cannot be found or if the reference is to any other element or to any non-element. References to member classes (nested classes) return null. For example, for:

@see String#startsWith(java.lang.String)

return the MethodDoc for startsWith.

Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


SerialFieldTag (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.javadoc
Interface SerialFieldTag

All Superinterfaces:
Comparable, Tag
public interface SerialFieldTag
extends Tag, Comparable

Documents a Serializable field defined by an ObjectStreamField.

 The class parses and stores the three serialField tag parameters:

 - field name
 - field type name
      (fully-qualified or visible from the current import context)
 - description of the valid values for the field
This tag is only allowed in the javadoc for the special member serialPersistentFields.

See Also:
ObjectStreamField

Method Summary
int | compareTo(Object obj) Compares this Object with the specified Object for order.
String | description() Return the field comment.
String | fieldName() Return the serialziable field name.
String | fieldType() Return the field type string.
ClassDoc | fieldTypeDoc() Return the ClassDoc for field type.
Methods inherited from interface com.sun.javadoc.Tag
firstSentenceTags, holder, inlineTags, kind, name, position, text, toString

Method Detail

fieldName

public String fieldName()
Return the serialziable field name.

fieldType

public String fieldType()
Return the field type string.

fieldTypeDoc

public ClassDoc fieldTypeDoc()
Return the ClassDoc for field type.

Returns:
null if no ClassDoc for field type is visible from containingClass context.

description

public String description()
Return the field comment. If there is no serialField comment, return javadoc comment of corresponding FieldDoc.

compareTo

public int compareTo(Object obj)
Compares this Object with the specified Object for order. Returns a negative integer, zero, or a positive integer as this Object is less than, equal to, or greater than the given Object.

Included to make SerialFieldTag items java.lang.Comparable.

Specified by:
compareTo in interface Comparable
Parameters:
obj - the Object to be compared.
Returns:
a negative integer, zero, or a positive integer as this Object is less than, equal to, or greater than the given Object.
Throws:
ClassCastException - the specified Object's type prevents it from being compared to this Object.
Since:
JDK1.2
Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


SourcePosition (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.javadoc
Interface SourcePosition

public interface SourcePosition

This interface describes a source position: filename, line number, and column number.

Since:
1.4

Method Summary
int | column() The column in the source file.
File | file() The source file.
int | line() The line in the source file.
String | toString() Convert the source position to the form "Filename:line".

Method Detail

file

public File file()
The source file. Returns null if no file information is available.

line

public int line()
The line in the source file. The first line is numbered 1; 0 means no line number information is available.

column

public int column()
The column in the source file. The first column is numbered 1; 0 means no column information is available. Columns count characters in the input stream; a tab advances the column number to the next 8-column tab stop.

toString

public String toString()
Convert the source position to the form "Filename:line".

Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Tag (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.javadoc
Interface Tag

All Known Subinterfaces:
ParamTag, SeeTag, SerialFieldTag, ThrowsTag
public interface Tag

Represents a simple documentation tag, such as @since, @author, @version. Given a tag (e.g. "@since 1.2"), holds tag name (e.g. "@since") and tag text (e.g. "1.2"). Tags with structure or which require special processing are handled by subclasses such as ParamTag (for @param), SeeTag (for @see and {@link}), and ThrowsTag (for @throws).

See Also:
SeeTag, ParamTag, ThrowsTag, SerialFieldTag, Doc.tags()

Method Summary
Tag[] | firstSentenceTags() Return the first sentence of the comment as an array of tags.
Doc | holder() Return the containing Doc of this Tag element.
Tag[] | inlineTags() For a documentation comment with embedded {@link} tags, return an array of Tag objects.
String | kind() Return the kind of this tag.
String | name() Return the name of this tag.
SourcePosition | position() Return the source position of this tag.
String | text() Return the text of this tag, that is, portion beyond tag name.
String | toString() Convert this object to a string.

Method Detail

name

public String name()
Return the name of this tag. The name is the string starting with "@" that is used in a doc comment, such as @return. For inline tags, such as {@link}, the curly brackets are not part of the name, so in this example the name would be simply @link.

holder

public Doc holder()
Return the containing Doc of this Tag element.

kind

public String kind()
Return the kind of this tag. similar or synonymous tags. For most tags, kind() == name(); the following table lists those cases where there is more than one tag of a given kind:

kind() | name()
@throws | @throws
@throws | @exception
@see | @see
@see | @link
@see | @linkplain
@serial | @serial
@serial | @serialData

text

public String text()
Return the text of this tag, that is, portion beyond tag name.

toString

public String toString()
Convert this object to a string.

inlineTags

public Tag[] inlineTags()
For a documentation comment with embedded {@link} tags, return an array of Tag objects. The entire doc comment is broken down into strings separated by {@link} tags, where each successive element of the array represents either a string or {@link} tag, in order, from start to end. Each string is represented by a Tag object of name "Text", where text() returns the string. Each {@link} tag is represented by a SeeTag of name "@link" and kind "@see". For example, given the following comment tag:

This is a {@link Doc commentlabel} example.

return an array of Tag objects:

  • tags[0] is a Tag with name "Text" and text consisting of "This is a "
  • tags[1] is a SeeTag with name "@link", referenced class Doc and label "commentlabel"
  • tags[2] is a Tag with name "Text" and text consisting of " example."

Returns:
Tag[] array of tags
See Also:
ParamTag, ThrowsTag

firstSentenceTags

public Tag[] firstSentenceTags()
Return the first sentence of the comment as an array of tags. Includes inline tags (i.e. {@link reference} tags) but not block tags. Each section of plain text is represented as a Tag of kind "Text". Inline tags are represented as a SeeTag of kind "@link". If the locale is English language, the first sentence is determined by the rules described in the Java Language Specification (first version): "This sentence ends at the first period that is followed by a blank, tab, or line terminator or at the first tagline.", in addition a line will be terminated by paragraph and section terminating HTML tags: <p> </p> <h1> <h2> <h3> <h4> <h5> <h6> <hr> <pre> or </pre>. If the locale is not English, the sentence end will be determined by java.text.BreakIterator.getSentenceInstance(Locale).

Returns:
an array of Tag objects representing the first sentence of the comment

position

public SourcePosition position()
Return the source position of this tag.

Returns:
the source position of this tag.
Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


ThrowsTag (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

com.sun.javadoc
Interface ThrowsTag

All Superinterfaces:
Tag
public interface ThrowsTag
extends Tag

Represents a @throws or @exception documentation tag. Parses and holds the exception name and exception comment. Note: @exception is a backwards compatible synonymy for @throws.

See Also:
ExecutableMemberDoc.throwsTags()

Method Summary
ClassDoc | exception() Return a ClassDoc which represents the exception.
String | exceptionComment() Return the exception comment associated with this ThrowsTag.
String | exceptionName() Return the name of the exception associated with this ThrowsTag.
Methods inherited from interface com.sun.javadoc.Tag
firstSentenceTags, holder, inlineTags, kind, name, position, text, toString

Method Detail

exceptionName

public String exceptionName()
Return the name of the exception associated with this ThrowsTag.

Returns:
name of the exception.

exceptionComment

public String exceptionComment()
Return the exception comment associated with this ThrowsTag.

Returns:
exception comment.

exception

public ClassDoc exception()
Return a ClassDoc which represents the exception.

Returns:
ClassDoc which represents the exception.
Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Type (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

com.sun.javadoc
Interface Type

All Known Subinterfaces:
ClassDoc
public interface Type

Represents a java type. Type can be a class, interface or primitive data type, like int or char.

Since:
JDK1.2

Method Summary
ClassDoc | asClassDoc() Return this type as a class doc if this type is a class or interface.
String | dimension() Return the type's dimension information, as a string.
String | qualifiedTypeName() Return qualified name of type excluding any dimension information.
String | toString() Returns a string representation of the type.
String | typeName() Return unqualified name of type excluding any dimension information.

Method Detail

typeName

public String typeName()
Return unqualified name of type excluding any dimension information.

For example, a two dimensional array of String returns 'String'.

qualifiedTypeName

public String qualifiedTypeName()
Return qualified name of type excluding any dimension information.

For example, a two dimensional array of String returns 'java.lang.String'.

dimension

public String dimension()
Return the type's dimension information, as a string.

For example, a two dimensional array of String returns '[][]'.

toString

public String toString()
Returns a string representation of the type. Return name of type including any dimension information.

For example, a two dimensional array of String returns String[][].

Returns:
name of type including any dimension information.

asClassDoc

public ClassDoc asClassDoc()
Return this type as a class doc if this type is a class or interface. Array dimensions are ignored.

Returns:
a ClassDoc if the type is a class or interface. Return null if it is a primitive type..
Package Class Use Tree Deprecated Index Help
Doclet API
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface com.sun.javadoc.ClassDoc (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.javadoc.ClassDoc

Uses of ClassDoc in com.sun.javadoc

Methods in com.sun.javadoc that return ClassDoc
ClassDoc[] | RootDoc.specifiedClasses() Return the classes and interfaces specified as source file names on the command line.
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 | ThrowsTag.exception() Return a ClassDoc which represents the exception.
ClassDoc | SerialFieldTag.fieldTypeDoc() Return the ClassDoc for field type.
ClassDoc | SeeTag.referencedClass() Get the class doc referenced by the class name part of @see.
ClassDoc[] | ExecutableMemberDoc.thrownExceptions() Return exceptions this method or constructor throws.
ClassDoc | MethodDoc.overriddenClass() Return the class containing the method that this method overrides.
ClassDoc[] | PackageDoc.allClasses(boolean filter) Get all classes and interfaces in the package, filtered to the specified access modifier option.
ClassDoc[] | PackageDoc.allClasses() Get all included classes and interfaces in the package.
ClassDoc[] | PackageDoc.ordinaryClasses() Get included ordinary classes (that is, exclude exceptions, errors and interfaces) in this package.
ClassDoc[] | PackageDoc.exceptions() Get included Exception classes in this package.
ClassDoc[] | PackageDoc.errors() Get included Error classes in this package.
ClassDoc[] | PackageDoc.interfaces() Get included Interfaces in this package.
ClassDoc | PackageDoc.findClass(String className) Lookup a class or interface within this package.
ClassDoc | Type.asClassDoc() Return this type as a class doc if this type is a class or interface.
ClassDoc | ClassDoc.superclass() Return the superclass of this class.
ClassDoc[] | ClassDoc.interfaces() Return interfaces implemented by this class or interfaces extended by this interface.
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 | ClassDoc.findClass(String className) Find the specified class or interface within the context of this class doc.
ClassDoc[] | ClassDoc.importedClasses() Get the list of classes and interfaces declared as imported.
ClassDoc | ProgramElementDoc.containingClass() Get the containing class or interface of this program element.

Methods in com.sun.javadoc with parameters of type ClassDoc
 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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface com.sun.javadoc.ConstructorDoc (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.javadoc.ConstructorDoc

Uses of ConstructorDoc in com.sun.javadoc

Methods in com.sun.javadoc that return ConstructorDoc
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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface com.sun.javadoc.Doc (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.javadoc.Doc

Uses of Doc in com.sun.javadoc

Subinterfaces of Doc in com.sun.javadoc
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
 Doc Tag.holder()
Return the containing Doc of this Tag element.

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface com.sun.javadoc.DocErrorReporter (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.javadoc.DocErrorReporter

Uses of DocErrorReporter in com.sun.javadoc

Subinterfaces of DocErrorReporter in com.sun.javadoc
 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
static boolean Doclet.validOptions(String[][] options, DocErrorReporter reporter)
Check that options have the correct arguments.

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Class com.sun.javadoc.Doclet (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES

Uses of Class
com.sun.javadoc.Doclet

No usage of com.sun.javadoc.Doclet

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface com.sun.javadoc.ExecutableMemberDoc (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.javadoc.ExecutableMemberDoc

Uses of ExecutableMemberDoc in com.sun.javadoc

Subinterfaces of ExecutableMemberDoc in com.sun.javadoc
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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface com.sun.javadoc.FieldDoc (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.javadoc.FieldDoc

Uses of FieldDoc in com.sun.javadoc

Methods in com.sun.javadoc that return FieldDoc
FieldDoc[] | ClassDoc.serializableFields() Return the Serializable fields of this class or interface.
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

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface com.sun.javadoc.MemberDoc (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.javadoc.MemberDoc

Uses of MemberDoc in com.sun.javadoc

Subinterfaces of MemberDoc in com.sun.javadoc
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
 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
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface com.sun.javadoc.MethodDoc (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.javadoc.MethodDoc

Uses of MethodDoc in com.sun.javadoc

Methods in com.sun.javadoc that return MethodDoc
MethodDoc | MethodDoc.overriddenMethod() Return the method that this method overrides.
MethodDoc[] | ClassDoc.serializationMethods() Return the serialization methods for this class or interface.
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.

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface com.sun.javadoc.PackageDoc (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.javadoc.PackageDoc

Uses of PackageDoc in com.sun.javadoc

Methods in com.sun.javadoc that return PackageDoc
PackageDoc[] | RootDoc.specifiedPackages() Return the packages specified on the command line.
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[] | ClassDoc.importedPackages() Get the list of packages declared as imported.
PackageDoc | ProgramElementDoc.containingPackage() Get the package that this program element is contained in.

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface com.sun.javadoc.Parameter (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.javadoc.Parameter

Uses of Parameter in com.sun.javadoc

Methods in com.sun.javadoc that return Parameter
 Parameter[] ExecutableMemberDoc.parameters()
Get argument information.

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface com.sun.javadoc.ParamTag (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.javadoc.ParamTag

Uses of ParamTag in com.sun.javadoc

Methods in com.sun.javadoc that return ParamTag
 ParamTag[] ExecutableMemberDoc.paramTags()
Return the param tags in this method.

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface com.sun.javadoc.ProgramElementDoc (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.javadoc.ProgramElementDoc

Uses of ProgramElementDoc in com.sun.javadoc

Subinterfaces of ProgramElementDoc in com.sun.javadoc
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.

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface com.sun.javadoc.RootDoc (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.javadoc.RootDoc

Uses of RootDoc in com.sun.javadoc

Methods in com.sun.javadoc with parameters of type RootDoc
static boolean Doclet.start(RootDoc root)
Generate documentation here.

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface com.sun.javadoc.SeeTag (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.javadoc.SeeTag

Uses of SeeTag in com.sun.javadoc

Methods in com.sun.javadoc that return SeeTag
 SeeTag[] Doc.seeTags()
Return the see also tags in this Doc item.

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface com.sun.javadoc.SerialFieldTag (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.javadoc.SerialFieldTag

Uses of SerialFieldTag in com.sun.javadoc

Methods in com.sun.javadoc that return SerialFieldTag
 SerialFieldTag[] FieldDoc.serialFieldTags()
Return the serialField tags in this FieldDoc item.

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface com.sun.javadoc.SourcePosition (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.javadoc.SourcePosition

Uses of SourcePosition in com.sun.javadoc

Methods in com.sun.javadoc that return SourcePosition
SourcePosition | Tag.position() Return the source position of this tag.
SourcePosition | Doc.position() Return the source position of the first line of the corresponding declaration, or null if no position is available.

Methods in com.sun.javadoc with parameters of type SourcePosition
void | DocErrorReporter.printError(SourcePosition pos, String msg) Print an error message and increment error count.
void | DocErrorReporter.printWarning(SourcePosition pos, String msg) Print warning message and increment warning count.
void | DocErrorReporter.printNotice(SourcePosition pos, String msg) Print a message.

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface com.sun.javadoc.Tag (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.javadoc.Tag

Uses of Tag in com.sun.javadoc

Subinterfaces of Tag in com.sun.javadoc
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
Tag[] | Tag.inlineTags() For a documentation comment with embedded {@link} tags, return an array of Tag objects.
Tag[] | Tag.firstSentenceTags() Return the first sentence of the 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.
Tag[] | Doc.inlineTags() Return comment as an array of tags.
Tag[] | Doc.firstSentenceTags() Return the first sentence of the comment as an array of tags.

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface com.sun.javadoc.ThrowsTag (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.javadoc.ThrowsTag

Uses of ThrowsTag in com.sun.javadoc

Methods in com.sun.javadoc that return ThrowsTag
 ThrowsTag[] ExecutableMemberDoc.throwsTags()
Return the throws tags in this method.

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Uses of Interface com.sun.javadoc.Type (Doclet API)

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES

Uses of Interface
com.sun.javadoc.Type

Uses of Type in com.sun.javadoc

Subinterfaces of Type in com.sun.javadoc
 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.

Methods in com.sun.javadoc that return Type
Type | Parameter.type() Get the type of this parameter.
Type | MethodDoc.returnType() Get return type.
Type | FieldDoc.type() Get type of this field.

Package Class Use Tree Deprecated Index Help
Doclet API
PREV NEXT FRAMES NO FRAMES
Submit a bug or feature
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-2003 Sun Microsystems, Inc. 4150 Network Circle
Santa Clara, California, 95054, U.S.A. All Rights Reserved.


Taglet Overview

Contents

  • Taglet API
  • Writing a Taglet
  • Example - A Standalone Taglet
  • Example - An Inline Taglet
  • Handling Errors and Warnings

Taglet API

Taglets are programs written in the JavaTM programming language that implement the Taglet API. Taglets can be written as either standalone tags, such as @todo, or inline tags, such as {@underline}. Standalone taglets do not currently support inline tags in their text. (See standalone and inline tags.) The Taglet API consists of one interface:
  • Taglet interface
A taglet can modify and format the text argument of a custom tag, and do other things, such as redirect the text to a file or other stream. A taglet can override a standard tag.

Taglets are the foundation beneath the -tag option. When you use the -tag option, it uses a built-in taglet to generate default HTML formatting that is similar to that generated for @return.

Writing a Taglet

Here are the basic steps you need to follow to create and use your own taglet:

  1. Write the Java program that constitutes your taglet. Your program should import the following:
       import com.sun.tools.doclets.Taglet;    // Taglet API
   import com.sun.javadoc.*;               // Doclet API
   import java.util.Map;                   // Used in register(Map)
    The com.sun.javadoc classes must be imported for the Tag interface used in toString(Tag).

  2. Your class must implement the requirements of the interface it extends. The toString method is where all of the custom work is implemented to modify, format or redirect the text argument passed in to to your custom tag.
        public String toString(Tag tag)
  3. In addition to the requirements of the interface you are implementing, your program must implement the following static method. Then enables the taglet to be loaded at runtime. See the source code in the example below.
        public static void register(Map tagletMap)

  4. Compile your doclet. Use javac compiler version 1.4.0 (or later) in the Java 2 SDK. The required class files are in the lib\tools.jar file in the SDK. For the first example below, assuming the SDK is installed at C:\Program Files\j2sdk1.4.1.
       javac -classpath "C:\Program Files\j2sdk1.4.1\lib\tools.jar"  ToDoTaglet.java

  5. Run the javadoc tool using the -taglet and -tagletpath options. For example, if your taglet class file is defined to be in package com.sun and is stored in C:\taglets\com\sun\Taglet.class, then you should set tagletpath to C:\taglets. This example calls javadoc on package com.package1, including ToDoTaglet tags:
       javadoc -taglet ToDoTaglet -tagletpath C:\taglets com.package1

The following examples are of standalone and inline taglets.

Example - A Standalone Taglet

The source code for an example of a standalone taglet implementing @todo is included at:
  • ToDoTaglet.java
The corresponding class file ToDoTaglet.class is already compiled and saved in the same directory as this source file.

This taglet formats the output for the @todo tag. A doc comment containing the following tag:

    /**
     * @todo Fix this!
     */
then the ToDo taglet formats the HTML output as follows:
To Do:
Fix this!

Implementation Description

Let's look at the source code. To name the tag and define the header text, define two private fields:
    private static final String NAME = "todo";
    private static final String HEADER = "To Do:";
To make this a standalone tag rather than an inline tag, you set isInlineTag to return false:
    public boolean isInlineTag() {
        return false;
    }
There are other methods inField, inMethod, inType, inPackage and inOverview that you specify true or false to indicate in which doc comments in the source code this tag can be used.

The toString(Tag) method determines how the text is inserted into the output when a single {@todo} tag is encountered. This code creates a bold heading followed by a table with a yellow background that contains the text (specified by tag.text()).

    public String toString(Tag tag) {`
        return "<DT><B>" + HEADER + "</B><DD>"
               + "<table cellpadding=2 cellspacing=0><tr><td bgcolor=\"yellow\">"
               + tag.text()
               + "</td></tr></table></DD>\n";
    }
Similarly, the toString(Tag[]) method (which takes an array of tags) determines how the text is inserted into the output when multiple {@todo} tags are encountered.

The register method

    /**
     * Register this Taglet.
     * @param tagletMap  the map to register this tag to.
     */
    public static void register(Map tagletMap) {
       ToDoTaglet tag = new ToDoTaglet();
       Taglet t = (Taglet) tagletMap.get(tag.getName());
       if (t != null) {
           tagletMap.remove(tag.getName());
       }
       tagletMap.put(tag.getName(), tag);
    }

Example - An Inline Taglet

Unline standalone tags, a custom inline tag can only be implemented using a taglet (rather than using the -tag option). This is because there is no default behavior for inline tags.

The source code for an example of an inline taglet implementing {@underline} is included at:

  • UnderlineTaglet.java
The corresponding class file UnderlineTaglet.class is already compiled and saved in the same directory as this source file.

This taglet formats the output for the {@underline} tag. A doc comment containing the following tag:

    /**
     * Be sure to insert the value at the {@underline start} of the array.
     */
would be output in HTML as follows:
Be sure to insert the value at the start of the array.

Implementation Description

Let's look at how this source code differs from the previous example. Of course the tag name is different (and inline tags have no heading, so none is defined):
    private String NAME = "underline";
To define this as an inline tag rather than a standalone tag, you set isInlineTag to return true:
    public boolean isInlineTag() {
        return true;
    }

The methods inField, inMethod, inConstructor, inType, inPackage and inOverview apply only to standalone tags and must all be set to false for inline tags.

The toString(Tag) method determines how the text is inserted into the output when an {@underline} tag is encountered. This code creates surrounds the text with the HTML underline tags <ul> and </ul>.

    public String toString(Tag tag) {
        return "<u>" + tag.text() + "</u>";
    }
It is not possible to have an array of inline tags to process, like it is with standalone tags. Therefore, the toString(Tag[]) method (which takes an array of tags) is ignored for inline tags.

Handling Errors and Warnings

Errors - A taglet can report an error and stop the Javadoc tool by simply printing the error message and then calling System.exit().

Warnings - A taglet can report a warning using a MessageRetriever given to it by the Doclet instance. The MessageRetriever is obtained from the Configuration object. The Configuration object is obtained from the doclet. For example, if the Taglet is designed to be used with the Standard doclet, the Configuration can be retrieved using Standard.configuration(), a static method. As an example, this is how the SimpleTaglet prints warnings, which is the default taglet for the -tag option.

Copyright © 2001-2002 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: 		Sun


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
java.lang.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.
java.lang.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.
java.lang.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

public 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

public 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

public 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

public 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

public 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

public 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

public 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

public java.lang.String getName()
Return the name of this custom tag.

Returns:
the name of this custom tag.

toString

public java.lang.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

public java.lang.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.


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, must not return any value, and 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 options that are subject to change in future releases.

Standard Options
-hotspot
Select the Java HotSpot Client VM. This is the default.

-server
Select the Java HotSpot Server VM.

-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 (.).

For more information on class paths, see Setting the Class Path.

-D property=value
Set a system property value.

-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 s 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 ; ]
-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 rent 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 lt;Main Class>

The -disableassertions and -da switches apply to all ss 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.

On Solaris 8, 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".

-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.

-showversion
Display version information and continue.

-?
-help
Display usage information and exit.

-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.

-Xdebug
Start with the debugger enabled. Refer to jdb description for more details and an example.

-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 2 SDK. 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 2 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 2 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 Java 2 SDK'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.

-Xincgc
Enable the incremental garbage collector. The incremental garbage collector, which is off by default, will eliminate occasional garbage-collection pauses during program execution. However, it can lead to a roughly 10% decrease in overall GC performance.

-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 2MB. 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 64MB. Examples:
       -Xmx83886080
       -Xmx81920k
       -Xmx80m

-Xss n
Set thread stack size.

-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 be used in production systems.

-Xrunhprof[:help][:<suboption>=<value>,...]
Enables cpu, heap, or monitor profiling. This option is typically followed by a list of comma-separated "<suboption>=<value>" pairs . Run the command java -Xrunhprof:help to obtain a list of suboptions and their default values.

-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.

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.

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software


Java 2 SDK File Structure

Java 2 SDK and Runtime Environment File Structure

 SDK Tools

This document gives an overview of the Java 2 SDK directories and the files they contain. This page may also be used as a reference for the file structure of the Java 2 Runtime Environment. To see the file structure of the Runtime Environment, just look at the description of the contents of the SDK's jre directory on this page. The file structure of the Java 2 Runtime Environment is identical to that of the SDK's jre directory.

Development Files and Directories

This section describes the files and directories that are required to develop apps for the Java platform. (The directories that are not required include demos, Java source code, and C header files. They are discussed in the following section, Additional Files and Directories.) The following chart shows the most important directories:

              j2sdk1.4.2
   ___________|_________________
  |           |                 |
 bin         lib               jre
  |           |         ________|__________
java*     tools.jar    |                   |
javac*    dt.jar      bin                 lib
javap*                 |       ________ ___|___ _________ ________ _______
javah*               java*    |        |       |         |        |       |
javadoc*                    rt.jar    ext   security   i386    applet  fonts
                        charsets.jar   |              /    \
                                  localedata.jar  server  client

Assuming the SDK software is installed at /j2sdk1.4.2, here are some of the most important directories:

/j2sdk1.4.2
The root directory of the SDK software installation. Contains copyright, license, and README files. Also contains src.jar, the archive of source code for the Java 2 platform.

/j2sdk1.4.2/bin
The executables for all the development tools contained in the Java 2 SDK. The PATH environment variable should contain an entry for this directory. For more information on the tools, see the SDK Tools.

/j2sdk1.4.2/lib
Files used by the development tools. Includes tools.jar, which contains non-core classes for support of the tools and utilities in the SDK. 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 the application.

/j2sdk1.4.2/jre
The root directory of the Java runtime environment used by the SDK development tools. The runtime environment is an implementation of the Java 2 platform. This is the directory referred to by the java.home system property.

/j2sdk1.4.2/jre/bin
Executable files for tools and libraries used by the Java platform. The executable files are identical to files in /j2sdk1.4.2/bin. The java launcher tool serves as an application launcher, in place of the old jre tool that shipped with 1.1 versions of the SDK software. This directory does not need to be in the PATH environment variable.

/j2sdk1.4.2/jre/lib
Code libraries, property settings, and resource files used by the Java runtime environment. Includes:
  • 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.

/j2sdk1.4.2/jre/lib/ext
Default installation directory for Extensions to the Java platform. This is where the JavaHelp jar file goes when it is installed, for example.
  • localedata.jar -- locale data for java.text and java.util.
/j2sdk1.4.2/jre/lib/security
Contains files used for security management. These include the security policy (java.policy) and security properties (java.security) files.

/j2sdk1.4.2/jre/lib/i386/client
Contains the .so file used by the Java HotSpot Client Virtual Machine, which is implemented with Java HotSpotTM technology. This is the default VM.

/j2sdk1.4.2/jre/lib/i386/server
Contains the .so file used by the Java HotSpot Server Virtual Machine.

/j2sdk1.4.2/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 teh local file system by the applet class loader, providing the same protections as if they had been downloaded over the net.

/j2sdk1.4.2/jre/lib/fonts
Font files for use by platform.

Additional Files and Directories

This section describes the directory structure for the demos, Java source code, and C header files. Here is the directory structure:

                            j2sdk1.4.2
                 ___________|__________ _________
                |           |          |         |
              demo       include    src.jar     man
             ___|___ _________ __________ ________
            |       |         |          |        |
          applets  jfc       jpda     plugin     jni

The additional files and directories shown above are:

/j2sdk1.4.2/src.jar
Archive containing source code for the Java 2 platform.

/j2sdk1.4.2/demo
Examples, with source code, that show you how to program for the Java platform.

/j2sdk1.4.2/demo/applets
Applets that can be used on a Web page.

/j2sdk1.4.2/demo/jfc
Examples that use Java 2DTM and JFC/Swing components.

/j2sdk1.4.2/demo/jpda
Examples of using the Java Platform Debugging Architecture. Includes source code for the javadt and jdb utilities.

/j2sdk1.4.2/demo/plugin
Demos for use with Java Plug-in product.

/j2sdk1.4.2/demo/jni
Example classes and C code that demonstrate access to poll(2) functionality from the Java 2 Platform.

/j2sdk1.4.2/include
C-language header files that support native-code programming using the Java Native Interface and the Java Virtual Machine Debugger Interface.

/j2sdk1.4.2/man
Contains troff-formatted man pages for the Java 2 SDK tools.

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software


kinit - Kerberos tool

kinit

kinit is used to obtain and cache Kerberos ticket-granting tickets. This tool is similar in functionality to the kinit tools 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>

DESCRIPTION

By default, for all Unix platforms a cache file named/tmp/krb5cc_<uid> will be generated. <uid> is the user identification number of the user logged into the system. For all other platforms, a cache file named <USER_HOME>/krb5cc_<USER_NAME> would be generated.

<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 Solaris, it could be /home/duke/krb5cc_duke, in which duke is the <USER_NAME> and /home/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
-f | Issue a forwardable ticket.
-p | Issue a proxiable ticket.
-c <cache_name> | The cache name (i.e., FILE:/temp/mykrb5cc).
-k | Use keytab
-t <keytab_filename> | The keytab name (i.e, /home/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 | Display instructions.

EXAMPLES

Requesting credentials valid for authentication from the current client host, for the default services, storing the credentials cache in the default location (/home/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:/home/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:/home/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 running the Unix ps command, for example.


klist - Kerberos tool

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 [-fe]] [-k [-tK]] [<name>] [-help]

Command Option | Description
-c | Specifes 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):
-f | Shows credentials flags.
-e | Shows the encryption type.

If the -k option is specified (options available for keytabs):
-t | Shows keytab entry timestamps.
-K | Shows keytab entry DES keys.

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


appletviewer - The Java Applet Viewer

The appletviewer command allows you to run applets outside of the context of a World-Wide 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.

OPTIONS

-debug
Starts the applet viewer in the Java debugger, jdb, thus allowing you to debug the applets in the document.

-encoding encoding name
Specify 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 © 2002 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software


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 an SDK 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.

% sdkTool -classpath classpath1:classpath2...

-or-

% setenv CLASSPATH classpath1:classpath2...

where:

sdkTool
A command-line tool, such as java, javac, or javadoc. For a listing, see SDK 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 colons.

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) are ignored.

Description

The class path tells the SDK tools and applications where to find third-party and user-defined classes -- that is, classes that are not 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.

Java 2 SDK, the JVM and other SDK 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 SDK software, 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 SDK tools' -classpath option when you invoke the JVM or other SDK 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 SDK software included a <jdk-dir>/classes entry in the default class path. That directory exists for use by the SDK software, and should not be used for application classes. Application classes should be placed in a directory outside of the SDK direcotry hierarchy. That way, installing a new development environment 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 SDK tools' -classpath option

The Java 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

In csh, the CLASSPATH environment variable is modified with the setenv command. The format is:

setenv CLASSPATH path1:path2

In sh, the CLASSPATH environment variable can be modified with these commands:

CLASSPATH = path1:path2:...
export CLASSPATH

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 in csh by using:

unsetenv CLASSPATH

In sh, you would use:

unset CLASSPATH

These commands unset CLASSPATH for the current shell 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 the shell you are running:

Shell | Startup Script
csh, tcsh | Examine your .cshrc file for the setenv command.
sh, ksh | Examine your .profile file for the export command.

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 /java/MyClasses/utility/myapp, you would set the class path so that it contains /java/MyClasses.

To run that app, you could use the following JVM command:

% java -classpath /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 /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 /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, /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:

% java -classpath /java/MyClasses/myclasses.jar utility.myapp.Cool

Multiple specifications

To find class files in the directory /java/MyClasses as well as classes in /java/OtherClasses, you would set the class path to:

% java -classpath /java/MyClasses:/java/OtherClasses ...

Note that the two paths are separated by a colon.

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 /java/MyClasses. Only if it doesn't find a class with the proper name in that directory will the interpreter look in the /java/OtherClasses directory.

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software


extcheck - Jar conflict detection utility

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 2 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 the 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 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 © 2002 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software


jar-The Java Archive Tool

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[v0M]f jarfile [-C dir] inputfiles [-J option]
jar c[v0]mf manifest jarfile [-C dir] inputfiles [-J option]
jar c[v0M] [-C dir] inputfiles [-J option]
jar c[v0]m manifest [-C dir] inputfiles [-J option]

Update jar file
jar u[v0M]f jarfile [-C dir] inputfiles [-J option]
jar u[v0]mf manifest jarfile [-C dir] inputfiles [-J option]
jar u[v0M] [-C dir] inputfiles [-J option]
jar u[v0]m manifest [-C dir] inputfiles [-J option]

Extract jar file
jar x[v]f jarfile [inputfiles] [-J option]
jar x[v] [inputfiles] [-J option]

List table of contents of jar file
jar t[v]f jarfile [inputfiles] [-J option]
jar t[v] [inputfiles] [-J option]

Add index to jar file
jar i jarfile [-J option]

where:

cuxtiv0Mmf
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 O (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 manifesfile are a pair -- if either is present, they must both appear. The letters m and f must appear in the same order that manifest and jarfile 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 to facilitate the packaging of java applets or applications into a single archive. When the components of an applet or application (.class files, images and sounds) are combined into a single archive, they may 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 use as a class path entry, whether it is compressed or not.

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". A manifest file entry named META-INF/MANIFEST.MF is automatically generated by the jar tool and is always the first entry in the jar file. The manifest file is the place where any meta-information about the archive is stored as name: value pairs. Refer to the JAR file specification for details about how meta-information is stored in the manifest file.

If you have a pre-existing manifest file whose name: value pairs you want the jar tool to include for the new jar archive, you can specify it using the m option:

% jar cmf myManifestFile myFile.jar *.class
Be sure that any pre-existing manifest file that you use ends with a new line. The last line of a manifest file will not be parsed if it doesn't end with a new line character. Note that when you specify "cfm" instead of "cmf" (i.e., you invert the order of the "m" and "f" options), you need to 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, as in:

% jar xf myFile.jar

To extract only certain files from a jar file, supply their filenames:

% jar xf myFile.jar foo bar

Beginning with version 1.3 of the Java 2 SDK, 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 i option. 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 will use the information stored in this file for efficient class loading. Refer to the JarIndex specification for details about how location information is stored in the index file.

A standard way to copy directories is to first compress files in dir1 to standard out, then extract from standard in to dir2 (omitting f from both jar commands):

% (cd dir1; jar c .) | (cd dir2; jar x)

Examples of using the jar tool to operate on jar files and jar file manifests are provided below and in the Jar trail of the Java Tutorial.

OPTIONS

c
Creates a new archive to 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.
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" from standard input (for x and t) or sends the "jar file" to standard output (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. A name: value pair is added unless one already exists with the same name, in which case its value is updated.

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. Examples of such attributes would be those for vendor information, version information, package sealing, and to make JAR-bundled applications executable. See the JAR Files trail in the Java Tutorial and the Notes for Developers page for examples of using the m option.
-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:
jar uf foo.jar -C classes bar.class
would change to the classes directory and add the bar.class from that directory to foo.jar. The following command,
jar uf foo.jar -C classes . -C bin xyz.class
would change to the classes directory and add to foo.jar all files within the classes directory (without creating a classes directory in the jar file), then change back to the original directory before changing to the bin directory to add xyz.class to foo.jar. If classes holds files bar1 and bar2, then here's what the jar file would contain using jar tf foo.jar:
META-INF/
META-INF/MANIFEST.MF
bar1
bar2
xyz.class

-J option
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 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.

For example, you could use a single argument file named "classes.list" to hold the names of the files:

% find . -name '*.class' -print > classes.list

Then execute the jar command passing in the argfile:

% jar cf my.jar @classes.list
An argument file can be passed in with a path, but any filenames inside the argument file that have relative paths are relative to the current working directory, not the path passed in. Here's such 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.

Let's say 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 your application's class loading time:
% jar i main.jar
An INDEX.LIST file is inserted to the META-INF directory which will enable 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
Java Tutorial on the Java Software web site.

Copyright © 2003 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software


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

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).

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.

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.

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.

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 keytore 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

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: case doesn't matter in keystore type designations. For example, "JKS" would be considered the same as "jks".

Supported Algorithms

At this time, jarsigner can sign a JAR file using either

  • DSA (Digital Signature Algorithm) with the SHA-1 digest algorithm, or

  • the RSA algorithm with the MD5 digest 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 "MD5withRSA" algorithm. This is only possible if there is a statically installed provider supplying an implementation for the "MD5withRSA" algorithm. (There is always a "SHA1withDSA" algorithm available, from the default "SUN" provider.)

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 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 (.DSA) File

The .SF file is signed and the signature is placed in the .DSA file. The .DSA 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.

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 , 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

-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.

-storepass password
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.

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. Also, when typing in a password at the password prompt, the password is echoed (displayed exactly as typed), so be careful not to type it in front of anyone.

-keypass password
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.

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. Also, when typing in a password at the password prompt, the password is echoed (displayed exactly as typed), so be careful not to type it in front of anyone.

-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.

-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.

-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.

-provider 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.

-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.

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 (iff 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.

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 © 2002 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software


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 declaration must look like the following:
    public static void main(String args[])
The method must be declared public and static, it must not return any value, and it must accept a String array as a parameter. 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 options that are subject to change in future releases.

Standard Options
-client
Select the Java HotSpot Client VM. This is the default.

-server
Select the Java HotSpot Server VM.

-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 (.).

For more information on class paths, see Setting the Class Path.

-D property=value
Set a system property value.

-d32
-d64
Specifies whether the program is to be run in a 32-bit or 64-bit environment. On Solaris these correspond to the ILP32 and LP64 data models, respectively. The -d64 option may only be used on 64-bit Solaris systems.

Currently only the Java HotSpot Server VM supports 64-bit operation, and the "-server" option is implicit 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. 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.

On Solaris 8, 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".

-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.

-showversion
Display version information and continue.

-?
-help
Display usage information and exit.

-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.

-Xdebug
Start with the debugger enabled. Refer to jdb description for more details and an example.

-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 2 SDK. 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 2 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 2 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 Java 2 SDK'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.

-Xincgc
Enable the incremental garbage collector. The incremental garbage collector, which is off by default, will eliminate occasional garbage-collection pauses during program execution. However, it can lead to a roughly 10% decrease in overall GC performance.

-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 2MB. 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 64MB. The upper limit for this value will be approximately 4000m on Solaris 7 and Solaris 8 SPARC platforms and 2000m on Solaris 2.6 and x86 platforms, minus overhead amounts. Examples:
       -Xmx83886080
       -Xmx81920k
       -Xmx80m

-Xss n
Set thread stack size.

-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 be used in production systems.

-Xrunhprof[:help][:<suboption>=<value>,...]
Enables cpu, heap, or monitor profiling. This option is typically followed by a list of comma-separated "<suboption>=<value>" pairs . Run the command java -Xrunhprof:help to obtain a list of suboptions and their default values.

-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.

-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.

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.

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software


javac - Java programming language compiler

  • Synopsis
  • Description
  • Searching for Types
  • Options
  • Command Line Argument Files
  • Examples
  • See Also

SYNOPSIS

javac [ options ] [ sourcefiles ] [ @argfiles ]
Arguments may be in any order.
options
Command-line options.
sourcefiles
One or more source files to be compiled (such as MyClass.java).
@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.

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 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 /workspace, the source code for com.mysoft.mypack.MyClass should be in /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).

SEARCHING FOR TYPES
When compiling a source file, the compiler often needs information about a type it does not yet recognize. 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.awt.Object.

When the compiler needs type information, it looks for a source file or class file which defines the type. The compiler searches first in the bootstrap and extension classes, then in the user class path. 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 use the -sourcepath option, the compiler searches the indicated path for source files; otherwise the compiler searches the user class path both for 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. Here is how javac handles each situation:

  • Search produces a class file but no source file: javac uses the class file.

  • Search produces a source file but no class file: javac compiles the source file and uses the resulting class file.

  • Search produces both a source file and a class file: javac determines whether the class file is out of date. If the class file is out of date, javac recompiles the source file and uses the updated class file. Otherwise, javac just uses the class file.

    javac considers a class file out of date only if it is older than the source file.

Note that javac can silently compile source files not mentioned on the command line. Use the -verbose option to trace automatic compilation.

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
-classpath classpath
Set the user class path, overriding the user class path in the CLASSPATH environment variable. If neither CLASSPATH or -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 searched for source files as well as class files.

-d directory
Set the destination directory for class files. The destination directory must already exist; javac will not create the destination directory. 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 /home/myclasses and the class is called com.mypackage.MyClass, then the class file is called /home/myclasses/com/mypackage/MyClass.class.

If -d is not specified, javac puts the class file in the same directory as the source file.

Note that 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 the names of source files that use or override deprecated members or classes.

-encoding encoding
Set the source file encoding name, such as EUCJIS/SJIS. If -encoding is not specified, the platform default converter is used.

-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.

-nowarn
Disable warning messages.

-source release
Enables support for compiling source code containing assertions.

When release is set to 1.4, the compiler accepts code containing assertions. Assertions were introduced in J2SE 1.4.

When release is set to 1.3, the compiler does not support assertions. The compiler defaults to the 1.3 behavior if the -source flag is not used.

-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 colons (:) 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 that classes found through the classpath are subject to automatic recompilation if their sources are found.

-verbose
Verbose output. This includes information about each class loaded and each source file compiled.

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 will work on VMs with the specified version. The default is to generate class files to be compatible with the 1.2 VM in the Java 2 SDK, with one exception. When the -source 1.4 option is used, the default target is 1.4. The versions supported by javac are:

1.1
Ensure that generated class files will be compatible with 1.1 and VMs in the Java 2 SDK.
1.2
Generate class files that will run on VMs in the Java 2 SDK, v 1.2 and later, but will not run on 1.1 VMs. This is the default.
1.3
Generate class files that will run on VMs in the Java 2 SDK, v 1.3 and later, but will not run on 1.1 or 1.2 VMs.
1.4
Generate class files that are compatible only with 1.4 VMs.

-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.

-extdirs directories
Cross-compile against the specified extension directories. Directories is a colon-separated list of directories. Each JAR archive in the specified directories is searched for class files.

Non-Standard Options

-X
Display information about non-standard options and exit.

-Xstdout filename
Send compiler messages to the named file. By default, compiler messages go to System.err.

-Xswitchcheck
Checks switch blocks for fall-through cases and provides 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 contain a break statement:
switch (x) {
case 1:
       System.out.println("1");
       //  No  break;  statement here.
case 2:
       System.out.println("2");
}
If the -Xswtichcheck 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.

The -J option
-J option
Pass option to the java launcher called by javac. For example, -J-Xms48m sets the startup memory to 48 megabytes. Although it does not begin with -X, it is not a `standard option' of javac. It is a common convention for -J to pass options to the underlying VM executing applications written in Java.

Note that 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.

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. 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 \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

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.
% ls
greetings/
% ls greetings
Hello.java
% 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]);
        }
    }
}
% javac greetings/Hello.java
% ls greetings
Hello.class   Hello.java
% 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.
% ls
greetings/
% ls greetings
Aloha.java         GutenTag.java      Hello.java         Hi.java
% javac greetings/*.java
% ls 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:
% pwd
/examples
% 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.
% 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.
% 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.
% 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.

% ls
classes/  lib/      src/
% ls src
farewells/
% ls src/farewells
Base.java      GoodBye.java
% ls lib
Banners.jar
% ls classes
% javac -sourcepath src -classpath classes:lib/Banners.jar \
  src/farewells/GoodBye.java -d classes
% ls classes
farewells/
% ls classes/farewells
Base.class      GoodBye.class
Note that 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 the Java 2 SDK javac to compile code that will run on a 1.1 VM.
% javac -target 1.1 -bootclasspath jdk1.1.7/lib/classes.zip \
             -extdirs "" OldCode.java
The -target 1.1 option ensures that the generated class files will be compatible with 1.1 VMs. In the Java 2 SDK javac compiles for 1.2 by default.

The Java 2 SDK's javac would also by default compile against its own bootstrap classes, so we need to tell javac to compile against JDK 1.1 bootstrap classes instead. We do this with -bootclasspath and -extdirs. Failing to do this might allow compilation against a Java 2 Platform API that would not be present on a 1.1 VM and fail at runtime.

SEE ALSO
  • 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 © 2002 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software


javadoc - The Java API Documentation Generator

Generates HTML pages of API documentation from Java source files. This document contains JavadocTM examples for Sun Solaris.

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 Identifiers). 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 JavadocTM 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 Identifiers 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 (section 8.6.7 of 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 1.4.
  • 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 2 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 must name it package.html and place it in the package directory in the source tree along with the .java files. The Javadoc tool will automatically look for this filename in this location. Notice that the filename is identical for all packages. For explicit details, see the example of package.html.

The content of the package comment file is one big documentation comment, 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 tags except {@link} must appear after the main description. If you add a @see tag in a package comment file, it must have a fully-qualified name.

When the Javadoc tool runs, it will automatically look for this file; if found, the Javadoc tool does the following:

  • Copies all content between <body> and </body> tags for processing.
  • 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. 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, if the source files for the java.applet package are contained in /home/user/src/java/applet directory, you could create an overview comment file at /home/user/src/overview.html.

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), as defined by the package statement. In this scenario where source files are not explicitly specified, this 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 directory:

    com/package1/test-files/
The test files will be ignored by the Javadoc tool (though this warning might appear: "No source files for package com.package1.test-files").

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 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 Identifiers).

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 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.

              ------------                  ------------
              |C| Detail |                  |P| Detail |
              | |        |                  | |        |
              | |        |                  |-|        |
              | |        |                  |C|        |
              | |        |                  | |        |
              | |        |                  | |        |
              ------------                  ------------
             javadoc *.java           javadoc java.lang java.awt
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. See -breakiterator for a description of how we are planning in a future release to change the way the sentence break is determined.

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
{@docRoot} | 1.3
@deprecated | 1.0
@exception | 1.0
{@inheritDoc} | 1.4
{@link} | 1.2
{@linkplain} | 1.4
@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
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.

{@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}
Note: This feature is broken in 1.4.0, but fixed in 1.4.1
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.
@param parameter-name description
Adds a parameter to the "Parameters" section. The description may be continued on the next line. This tag is valid only in a doc comment for a method or constructor.

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 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 Chapter 6, "Names" of the Java Language Specification, Second Edition. 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). 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, and readExternal 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.4
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}
When used in the doc comment of a static field, displays the value of the constant. These are the values displayed on the Constant Field Values page. This tag is valid only in doc comments for fields.

@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). 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 %I%, %G%
 * @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
-link
-linkoffline
-linksource
-locale
-nocomment
-nodeprecated
-nodeprecatedlist
-nohelp
-noindex
-nonavbar
-noqualifier
-nosince
-notree
-overview
-package
 -private
-protected
-public
-quiet
-serialwarn
-source
-sourcepath
-splitindex
-stylesheetfile
-subpackages
-tag
-taglet
-tagletpath
-title
-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 -sourcepath.

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 /src/classes/java/lang/, then you could place the overview file at /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

-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 /home/user/mifdoclet/lib/mifdoclet.jar
Example of path to starting doclet class file. Notice the class filename is omitted.
   -docletpath /home/user/mifdoclet/classes/com/sun/tools/doclets/mif/
-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 1.4
Necessary to enable javadoc to handle assertions present in J2SE v 1.4 source code. This option documents code that compiles using "javac -source 1.4",

-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 colon (:). 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:

  /home/user/src/com/mypackage/*.java
In this case you would specify the sourcepath to /home/user/src, the directory that contains com/mypackage, and then supply the package name com.mypackage:
  % javadoc -sourcepath /home/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 slash "/", you end up with the full path to the package: /home/user/src/com/mypackage.

To point to two source paths:

  % javadoc -sourcepath /home/user1/src:/home/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 colon (:). 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 /home/user/src/com/mypackage, and if this package relies on a library in /home/user/lib, you would specify:

  % javadoc -classpath /home/user/lib -sourcepath /home/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.

-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 colons (:).

-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 colons (:).

-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.

-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):
   % javadoc -J-Xmx32m -J-Xms32m com.mypackage
To tell what version of javadoc you are using, call the "-version" option of java:

   % 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 /home/user/doc/ directory:

  % javadoc -d /home/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.

  % javadoc -windowtitle "Java 2 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.

  % javadoc -doctitle "Java<sup><font size=\"-2\">TM</font></sup>" 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.

  % 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.

-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's say you want to link to the java.lang, java.io and other Java 2 Platform packages at http://java.sun.com/j2se/1.4.2/docs/api, The following command generates documentation for the package com.mypackage with links to the Java 2 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.)

  % javadoc -link http://java.sun.com/j2se/1.4.2/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:
  % 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 2 Platform v1.4 API is located at http://java.sun.com/j2se/1.4.2/docs/api/package-list. and starts out 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:

% 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's say you want to link to the java.lang, java.io and other Java 2 Platform packages at http://java.sun.com/j2se/1.4.2/docs/api, but your shell does not have web access. You could open the package-list file in a browser at http://java.sun.com/j2se/1.4.2/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 2 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.)

% javadoc -linkoffline http://java.sun.com/j2se/1.4.2/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):

% 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:

  % 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.

  % 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:
  % javadoc -helpfile /home/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:
  % javadoc -stylesheetfile /home/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:
  % 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.

-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 (:) can be replaced with a dash (-), which frees up the colon character to appear in the tagname. See the colon example.

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 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 as Separator - The colon separator can be replaced by the dash, making the following two equivalent:
    -tag todo:a:"To Do:"
    -tag todo-a-"To Do:"
This frees up the colon to be used in the tagname:
    -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.

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.

-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:

  % javadoc -d docs -sourcepath /home/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:
  % javadoc -sourcepath /home/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).

-breakiterator
Uses the sentence break iterator to determine the end of the first sentence. We plan to change the algorithm for determining the end of the first sentence in the next major feature release -- the -breakiterator option uses this new algorithm. We recommend you use this option whenever running version 1.4 so that your transition to the next major release will be seamless.

In 1.2 and 1.3, the java.text.BreakIterator class was used to determine the end of sentence for all languages but English. Therefore, the -breakiterator option has an effect only for English. English had its own algorithm, which looked for a period followed by a space. When -breakiterator is omitted, the end of the first sentence is unchanged from 1.2 and 1.3, and warnings are emitted displaying where there would be a difference.

Differences in the algorithms show up in English as follows:

  • Old algorithm - Stops at a period followed by a space or a paragraph-level HTML tag, such as <P>.
  • New 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 "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".

-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.

-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.

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, source filenames and package names in any combination, or just arguments to Javadoc options. The arguments within a file can be space-separated or newline-separated. 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:
  % 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 2 Platform v1.3 API Specification'
     -doctitle 'Java<sup><font size="-2">TM</font></sup> 2 Platform v1.4 API Specification'
     -header '<b>Java 2 Platform </b><br><font size="-1">v1.4</font>'
     -bottom 'Copyright 1993-2000 Sun Microsystems, Inc. All Rights Reserved.'
     -group "Core Packages" "java.*"
     -overview /java/pubs/ws/1.3/src/share/classes/overview-core.html
     -sourcepath /java/pubs/ws/1.3/src/share/classes

Create a file named "packages" containing:

     com.mypackage1
     com.mypackage2
     com.mypackage3
You would then run javadoc with:
  % 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):
  % 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://java.sun.com/cgi-bin/bugreport.cgi">Submit a
bug or feature</a><br><br>Java is a trademark or registered trademark of
Sun Microsystems, Inc. in the US and other countries.<br>Copyright 1993-2000 Sun
Microsystems, Inc. 901 San Antonio Road,<br>Palo Alto, California, 94303, U.S.A.
All Rights Reserved.</font>'
Then run the Javadoc tool with:
  % javadoc -bottom @bottom @packages
Or you could include the -bottom option at the start of the argument file, and then just run it as:
  % 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.

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 /home/src/java/awt/*.java. The destination directory is /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:
      % cd /home/src/
  % javadoc -d /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:
      % javadoc -d /home/html -sourcepath /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.
      % javadoc -d /home/html -sourcepath /home/src1:/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 (/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.
      % cd /home/src/java/awt
  % javadoc -d /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.
      % cd /home/src/
  % 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.
      % javadoc -d /home/html /home/src/java/awt/Button.java /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.
  % javadoc -d /home/html -sourcepath /home/src java.awt /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 2 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

This command line example is over 900 characters, which is 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.
% javadoc -sourcepath /java/jdk/src/share/classes            \
    -overview /java/jdk/src/share/classes/overview.html      \
    -d /java/jdk/build/api                                   \
    -use                                                     \
    -splitIndex                                              \
    -windowtitle 'Java 2 Platform v1.2 API Specification'    \
    -doctitle 'Java<sup><font size="-2">TM</font></sup> 2 Platform v1.2 API Specification' \
    -header '<b>Java 2 Platform </b><br><font size="-1">v1.2</font>' \
    -bottom '<font size="-1"><a href="http://java.sun.com/cgi-bin/bugreport.cgi">Submit
a bug or feature</a><br><br>Java is a trademark or registered trademark of Sun Microsystems,
Inc. in the US and other countries.<br>Copyright 1993-1999 Sun Microsystems, Inc.
901 San Antonio Road,<br>Palo Alto, California, 94303, U.S.A. All Rights Reserved.</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 2 Platform v1.2 API Specification'
DOCTITLE = 'Java<sup><font size="-2">TM</font></sup> 2 Platform v1.2 API Specification'
HEADER = '<b>Java 2 Platform </b><br><font size="-1">v1.2</font>'
BOTTOM = '<font size="-1"><a href="http://java.sun.com/cgi-bin/bugreport.cgi">Submit
    a bug or feature</a><br><br>Java is a trademark or registered trademark
    of Sun Microsystems, Inc. in the US and other countries.<br>Copyright 1993-1999
    Sun Microsystems, Inc. 901 San Antonio Road,<br>Palo Alto, California, 94303, U.S.A.
    All Rights Reserved.</font>'
GROUPCORE = '"Core Packages" "java.*:com.sun.java.*:org.omg.*"'
GROUPEXT  = '"Extension Packages" "javax.*"'
SRCDIR = '/java/jdk/1.2/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 colon, for example:
.:/home/classes:/usr/local/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)
Please send comments to email address: javadoctool at sun.com.

JavadocTM is a trademark of Sun Microsystems, Inc. (The javadoc command itself does not require the trademark symbol.)

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software


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. . .
javah_g [ 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.

javah_g is a non-optimized version of javah suitable for use with debuggers like jdb.

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 colons. Thus the general format for path is:
   .:<your_path>
For example:
   .:/home/avh/classes:/usr/local/java/classes
-bootclasspath path
Specifies path from which to load bootstrap classes. By default, the bootstrap classes are the classes implementing the core Java 2 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 colons, for example,
.:/home/avh/classes:/usr/local/java/classes

SEE ALSO

javac, java, jdb, javap, javadoc

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software


javap - The Java Class File Disassembler

Disassembles class files.

SYNOPSIS

javap [ options ] class. . .

DESCRIPTION

The javap command disassembles a class file. 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. 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 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 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);
}

Method DocFooter()
   0 aload_0
   1 invokespecial #1
   4 return

Method void init()
   0 aload_0
   1 sipush 500
   4 bipush 100
   6 invokevirtual #2
   9 aload_0
  10 aload_0
  11 ldc #3
  13 invokevirtual #4
  16 putfield #5
  19 aload_0
  20 aload_0
  21 ldc #6
  23 invokevirtual #4
  26 putfield #7
  29 return

Method void paint(java.awt.Graphics)
   0 aload_1
   1 new #8
   4 dup
   5 invokespecial #9
   8 aload_0
   9 getfield #5
  12 invokevirtual #10
  15 ldc #11
  17 invokevirtual #10
  20 invokevirtual #12
  23 bipush 100
  25 bipush 15
  27 invokevirtual #13
  30 aload_1
  31 aload_0
  32 getfield #7
  35 sipush 290
  38 bipush 15
  40 invokevirtual #13
  43 return

OPTIONS
-help
Prints out help message for javap.

-l
Prints out line and local variable tables.

-b
Ensures backward compatibility with javap in JDK 1.1.

-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
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.

-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. Directories are separated by colons. Thus the general format for path is:

   .:<your_path>
For example:
.:/home/avh/classes:/usr/local/java/classes
-bootclasspath path
Specifies path from which to load bootstrap classes. By default, the bootstrap classes are the classes implementing the core Java 2platform 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 jre/lib/ext.

ENVIRONMENT VARIABLES

CLASSPATH
Used to provide the system a path to user-defined classes. Directories are separated by colons, for example, For example:
.:/home/avh/classes:/usr/local/java/classes

SEE ALSO

javac, java, jdb, javah, javadoc

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software


jdb - The Java Debugger

jdb helps you find and fix bugs in Java language programs.

SYNOPSIS

jdb [ options ] [ class ] [ arguments ]
options
Command-line options, as specified below.
class
Name of the class to begin debugging.
arguments
Arguments passed to the main() method of class.

DESCRIPTION

The Java Debugger, jdb, is a simple command-line debugger for Java classes. It is a demonstration of the Java Platform Debugger Architecture that provides inspection and debugging of a local or remote Java Virtual Machine.

Starting a jdb Session

There are many ways to start a jdb session. The most frequently used way is to have jdb launch a new Java Virtual Machine (VM) with the main class of the application to be debugged. This is done by substituting the command jdb for java in the command line. For example, if your application's main class is MyClass, you use the following command to debug it under JDB:
 % jdb MyClass
When started this way, jdb invokes a second Java VM with any specified parameters, loads the specified class, and stops the VM before executing that class's first instruction.

Another way to use jdb is by attaching it to a Java VM that is already running. A VM that is to be debugged with jdb must be started with the following options:

Option | Purpose
-Xdebug | Enables debugging support in the VM
-Xrunjdwp:transport=dt_socket,server=y,suspend=n | Loads in-process debugging libraries and specifies the kind of connection to be made.

For example, the following command will run the MyClass application, and allow jdb to connect to it at a later time.

 % java -Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n MyClass
You can then attach jdb to the VM with the following commmand:
 % jdb -attach 8000
Note that "MyClass" is not specified in the jdb command line in this case because jdb is connecting to an existing VM instead of launching a new one.

There are many other ways to connect the debugger to a VM, and all of them are supported by jdb. The Java Platform Debugger Architecture has additional documentation on these connection options.

Basic jdb Commands

The following is a list of the basic jdb commands. The Java debugger supports other commands which you can list using jdb's help command.

help, or ?
The most important jdb command, help displays the list of recognized commands with a brief description.
run
After starting jdb, and setting any necessary breakpoints, you can use this command to start the execution the debugged application. This command is available only when jdb launches the debugged application (as opposed to attaching to an existing VM).
cont
Continues execution of the debugged application after a breakpoint, exception, or step.
print
Displays Java objects and primitive values. For variables or fields of primitive types, the actual value is printed. For objects, a short description is printed. See the dump command below for getting more information about an object.

NOTE: To display local variables, the containing class must have been compiled with the javac -g option.

print supports many simple Java expressions including those with method invocations, for example:

  • print MyClass.myStaticField
  • print myObj.myInstanceField
  • print i + j + k (i, j, k are primities and either fields or local variables)
  • print myObj.myMethod() (if myMethod returns a non-null)
  • print new java.lang.String("Hello").length()
dump
For primitive values, this command is identical to print. For objects, it prints the current value of each field defined in the object. Static and instance fields are included.

The dump command supports the same set of expressions as the print command.

threads
List the threads that are currently running. For each thread, its name and current status are printed, as well as an index that can be used for other commands, for example:
4. (java.lang.Thread)0x1 main      running
In this example, the thread index is 4, the thread is an instance of java.lang.Thread, the thread name is "main", and it is currently running,
thread
Select a thread to be the current thread. Many jdb commands are based on the setting of the current thread. The thread is specified with the thread index described in the threads command above.
where
where with no arguments dumps the stack of the current thread. where all dumps the stack of all threads in the current thread group. where threadindex dumps the stack of the specified thread.

If the current thread is suspended (either through an event such as a breakpoint or through the suspend command), local variables and fields can be displayed with the print and dump commands. The up and down commands select which stack frame is current.

Breakpoints

Breakpoints can be set in jdb at line numbers or at the first instruction of a method, for example:
  • stop at MyClass:22 (sets a breakpoint at the first instruction for line 22 of the source file containing MyClass)
  • stop in java.lang.String.length (sets a breakpoint at the beginnig of the method java.lang.String.length)
  • stop in MyClass.<init> (<init> identifies the MyClass constructor)
  • stop in MyClass.<clinit> (<clinit> identifies the static initialization code for MyClass)

If a method is overloaded, you must also specify its argument types so that the proper method can be selected for a breakpoint. For example, "MyClass.myMethod(int,java.lang.String)", or "MyClass.myMethod()".

The clear command removes breakpoints using a syntax as in "clear MyClass:45". Using the clear or command with no argument displays a list of all breakpoints currently set. The cont command continues execution.

Stepping

The step commands advances execution to the next line whether it is in the current stack frame or a called method. The next command advances execution to the next line in the current stack frame.

Exceptions

When an exception occurs for which there isn't a catch statement anywhere in the throwing thread's call stack, the VM normally prints an exception trace and exits. When running under jdb, however, control returns to jdb at the offending throw. You can then use jdb to diagnose the cause of the exception.

Use the catch command to cause the debugged application to stop at other thrown exceptions, for example: "catch java.io.FileNotFoundException" or "catch mypackage.BigTroubleException. Any exception which is an instance of the specifield class (or of a subclass) will stop the application at the point where it is thrown.

The ignore command negates the effect of a previous catch command.

NOTE: The ignore command does not cause the debugged VM to ignore specific exceptions, only the debugger.

Command Line Options
When you use jdb in place of the Java application launcher on the command line, jdb accepts many of the same options as the java command, including -D, -classpath, and -X<option>.

The following additional options are accepted by jdb:

-help
Displays a help message.
-sourcepath <dir1:dir2:...>
Uses the given path in searching for source files in the specified path. If this option is not specified, the default path of "." is used.
-attach <address>
Attaches the debugger to previously running VM using the default connection mechanism.
-listen <address>
Waits for a running VM to connect at the specified address using standard connector.
-listenany
Waits for a running VM to connect at any available address using standard connector.
-launch
Launches the debugged application immediately upon startup of jdb. This option removes the need for using the run command. The debuged application is launched and then stopped just before the initial application class is loaded. At that point you can set any necessary breakpoints and use the cont to continue execution.
-connect <connector-name>:<name1>=<value1>,...
Connects to target VM using named connector with listed argument values.
-dbgtrace [flags]
Prints info for debugging jdb.
-tclient
Runs the application in the Java HotSpot(tm) VM (Client).
-tserver
Runs the application in the Java HotSpot(tm) VM (Server).
-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.

Other options are supported for alternate mechanisms for connecting the debugger and the VM it is to debug. The Java Platform Debugger Architecture has additional documentation on these connection alternatives.

Options Forwarded to Debuggee Process

-v -verbose[:class|gc|jni]
Turns on verbose mode.
-D<name>=<value>
Sets a system property.
-classpath <directories separated by ":">
Lists directories in which to look for classes.
-X<option>
Non-standard target VM option

SEE ALSO

javac, java, javah, javap, javadoc.

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software


Java 2 SDK File Structure

Java 2 SDK and Runtime Environment File Structure

 SDK Tools

This document gives an overview of the Java 2 SDK directories and the files they contain. This page may also be used as a reference for the file structure of the Java 2 Runtime Environment. To see the file structure of the Runtime Environment, just look at the description of the contents of the SDK's jre directory on this page. The file structure of the Java 2 Runtime Environment is identical to that of the SDK's jre directory.

Development Files and Directories

This section describes the files and directories that are required to develop apps for the Java platform. (The directories that are not required include demos, Java source code, and C header files. They are discussed in the following section, Additional Files and Directories.) The following chart shows the most important directories:

              j2sdk1.4.2
   ___________|_________________
  |           |                 |
 bin         lib               jre
  |           |         ________|__________
java*     tools.jar    |                   |
javac*    dt.jar      bin                 lib
javap*                 |       ________ ___|___ _________ ________ _______
javah*               java*    |        |       |         |        |       |
javadoc*                    rt.jar    ext   security   sparc    applet  fonts
                        charsets.jar   |              /     \
                                  localedata.jar  server  client

Assuming the SDK software is installed at /j2sdk1.4.2, here are some of the most important directories:

/j2sdk1.4.2
The root directory of the SDK software installation. Contains copyright, license, and README files. Also contains src.zip, the archive of source code for the Java 2 platform.

/j2sdk1.4.2/bin
The executables for all the development tools contained in the Java 2 SDK. The PATH environment variable should contain an entry for this directory. For more information on the tools, see the SDK Tools.

/j2sdk1.4.2/lib
Files used by the development tools. Includes tools.jar, which contains non-core classes for support of the tools and utilities in the SDK. 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 the application.

/j2sdk1.4.2/jre
The root directory of the Java runtime environment used by the SDK development tools. The runtime environment is an implementation of the Java 2 platform. This is the directory referred to by the java.home system property.

/j2sdk1.4.2/jre/bin
Executable files for tools and libraries used by the Java platform. The executable files are identical to files in /j2sdk1.4.2/bin. The java launcher tool serves as an application launcher, in place of the old jre tool that shipped with 1.1 versions of the SDK software. This directory does not need to be in the PATH environment variable.

/j2sdk1.4.2/jre/lib
Code libraries, property settings, and resource files used by the Java runtime environment. Includes:
  • 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.

/j2sdk1.4.2/jre/lib/ext
Default installation directory for Extensions to the Java platform. This is where the JavaHelp jar file goes when it is installed, for example.
  • localedata.jar -- locale data for java.text and java.util.
/j2sdk1.4.2/jre/lib/security
Contains files used for security management. These include the security policy (java.policy) and security properties (java.security) files.

/j2sdk1.4.2/jre/lib/sparc
Contains the .so (shared object) files used by the Solaris version of the Java platform.

/j2sdk1.4.2/jre/lib/sparc/client
Contains the .so file used by the Java HotSpot Client Virtual Machine, which is implemented with Java HotSpotTM technology. This is the default VM.

/j2sdk1.4.2/jre/lib/sparc/server
Contains the .so file used by the Java HotSpot Server Virtual Machine.

/j2sdk1.4.2/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 teh local file system by the applet class loader, providing the same protections as if they had been downloaded over the net.

/j2sdk1.4.2/jre/lib/fonts
Font files for use by platform.

Additional Files and Directories

This section describes the directory structure for the demos, Java source code, and C header files. Here is the directory structure:

                            j2sdk1.4.2
                 ___________|__________ _________
                |           |          |         |
              demo       include    src.zip     man
             ___|___ _________ __________ ________
            |       |         |          |        |
          applets  jfc       jpda     plugin     jni

The additional files and directories shown above are:

/j2sdk1.4.2/src.zip
Archive containing source code for the Java 2 platform.

/j2sdk1.4.2/demo
Examples, with source code, that show you how to program for the Java platform.

/j2sdk1.4.2/demo/applets
Applets that can be used on a Web page.

/j2sdk1.4.2/demo/jfc
Examples that use Java 2DTM and JFC/Swing components.

/j2sdk1.4.2/demo/jpda
Examples of using the Java Platform Debugging Architecture. Includes source code for the javadt and jdb utilities.

/j2sdk1.4.2/demo/plugin
Demos for use with Java Plug-in product.

/j2sdk1.4.2/demo/jni
Example classes and C code that demonstrate access to poll(2) functionality from the Java 2 Platform.

/j2sdk1.4.2/include
C-language header files that support native-code programming using the Java Native Interface and the Java Virtual Machine Debugger Interface.

/j2sdk1.4.2/man
Contains troff-formatted man pages for the Java 2 SDK tools.

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software


keytool - Key and Certificate Management Tool

Manages a keystore (database) of private keys and their associated X.509 certificate chains authenticating the corresponding public keys. Also manages certificates from trusted entities.

SYNOPSIS

keytool [ commands ]

DESCRIPTION

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. 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 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 jarsigner tool uses information from a keystore to generate or verify digital signatures for Java ARchive (JAR) files. (A JAR file packages class files, images, sounds, and/or other digital data in a single file). jarsigner verifies the digital signature of a JAR file, using the certificate that comes with it (it is included in the signature block file of the JAR file), and then checks whether or not the public key of that certificate is "trusted", i.e., is contained in the specified keystore.

Please note: 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. It is possible to import the information from an identity database into a keystore, via the -identitydb keytool command.

Keystore Entries

There are two different types of entries in a keystore:
  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 and jarsigner tools 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. Aliases are case-insensitive; the aliases Hugo and hugo would refer to the same keystore entry.

An alias is specified when you add an entity to the keystore using the -genkey command to generate a key pair (public and private key) or the -import 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 -genkey -alias duke -keypass dukekeypasswd
This specifies an inital password of "dukekeypasswd" required by subsequent commands to access the private key assocated 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. When typing in a password at the password prompt, the password is currently echoed (displayed exactly as typed), so be careful not to type it in front of anyone.

Keystore Location

Each keytool command has a -keystore option for specifying the name and location of the persistent keystore file for the keystore managed by keytool. 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.

Keystore Creation

A keystore is created whenever you use a -genkey, -import, or -identitydb command to add data to a keystore that doesn't yet exist.

More specifically, if you specify, in the -keystore option, a keystore that doesn't yet exist, that keystore will be created.

If you don't specify a -keystore option, the default keystore is a file named .keystore in your home directory. If that file does not yet exist, it will be created.

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 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 keytore 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 "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 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

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".

Supported Algorithms and Key Sizes

keytool allows users to specify any key pair generation and signature algorithm supplied by any of the registered cryptographic service providers. That is, the keyalg and sigalg options for various commands must be supported by a provider implementation. The default key pair generation algorithm is "DSA". The signature algorithm is derived from the algorithm of the underlying private key: If the underlying private key is of type "DSA", the default signature algorithm is "SHA1withDSA", and if the underlying private key is of type "RSA", the default signature algorithm is "MD5withRSA".

When generating a DSA key pair, the key size must be in the range from 512 to 1024 bits, and must be a multiple of 64. The default key size for any algorithm is 1024 bits.

Certificates

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.

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 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 the Netscape/Microsoft Certificate Servers 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 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 v1 certificates.
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=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.

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 -genkey or -selfcert commands, 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=JavaSoft, O=Sun, L=Cupertino, S=California, C=US
and a sample command using such a string is
keytool -genkey -dname "CN=Mark Smith, OU=JavaSoft, O=Sun, 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=SunSoft, O=Sun, 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, o=Sun Microsystems\, Inc., o=sun, 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 "\".

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 -import and -printcert commands can be in either this format or binary encoded.

The -export 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 MD5 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-----

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 -genkey 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 -genkey 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 -import), 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 webpage, etc.).

Importing Certificates

To import a certificate from a file, use the -import command, as in

    keytool -import -alias joe -file jcertfile.cer

This sample command imports the certificate(s) in the file jcertfile.cer and stores it in the keystore entry identified by the alias joe.

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:

  • If the alias points to a key entry, then keytool assumes you are importing a certificate reply. keytool checks whether the public key in the certificate reply matches the public key stored with the alias, and exits if they are different.

  • 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. If the alias does not exist in the keystore, keytool creates a trusted certificate entry with the specified alias and associates it with the imported certificate.

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 -import 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 /tmp/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 /tmp/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
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 -import 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 -import command without the -noprompt option. If the -noprompt option is given, there is no interaction with the user.

Exporting Certificates

To export a certificate to a file, use the -export command, as in

    keytool -export -alias jane -file janecertfile.cer
This sample command exports jane's certificate to the file janecertfile.cer. That is, if jane is the alias for a key entry, the command exports the certificate at the bottom of the certificate chain in that keystore entry. This is the certificate that authenticates jane's public key.

If, instead, jane is the alias for a trusted certificate entry, then that trusted certificate is exported.

Displaying Certificates

To print out the contents of a keystore entry, use the -list command, as in

    keytool -list -alias joe
If you don't specify an alias, as in
    keytool -list
the contents of the entire keystore are printed.

To display the contents of a certificate stored in a file, use the -printcert command, as in

    keytool -printcert -file certfile.cer

This displays information about the certificate stored in the file certfile.cer.

Note: This works independently of a keystore, i.e., you do not need a keystore in order to display a certificate that's stored in a file.

Generating 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 -genkey command is called to generate a new public/private key pair, it also wraps the public key into a self-signed certificate.

You may occasionally wish to generate a new self-signed certificate. For example, you may want to use the same key pair under a different identity (distinguished name). For example, suppose you change departments. You can then:

  1. copy (clone) the original key entry. See -keyclone.

  2. generate a new self-signed certificate for the cloned entry, using your new distinguished name. See below.

  3. generate a Certificate Signing Requests for the cloned entry, and import the reply certificate or certificate chain. See the -certreq and -import commands.

  4. delete the original (now obsolete) entry. See -delete.

To generate a self-signed certificate, use the -selfcert command, as in
    keytool -selfcert -alias dukeNew -keypass b92kqmp
      -dname "cn=Duke Smith, ou=Purchasing, o=BlueSoft, c=US"
The generated certificate is stored as a single-element certificate chain in the keystore entry identified by the specified alias (in this case "dukeNew"), where it replaces the existing certificate chain.

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 key, and if this fails, will then prompt you for the private 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"

-keysize 1024

-validity 90

-keystore the file named .keystore in the user's home directory

-file stdin if reading, stdout if writing
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", and if the underlying private key is of type "RSA", -sigalg defaults to "MD5withRSA".

Options that Appear for Most Commands

The -v option can appear for all commands except -help. If it appears, it signifies "verbose" mode; detailed certificate information will be 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. (keytool 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.

These options may appear for all commands operating on a keystore:

-storetype storetype
This qualifier 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.

-keystore keystore
The keystore (database file) location. Defaults to the file .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.

-storepass storepass
The password which is used to protect the integrity of the keystore.

storepass must be at least 6 characters long. It 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.

Be careful with passwords - see Warning Regarding Passwords.

-provider 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.

Warning Regarding Passwords

Most commands operating on a keystore require the store password. Some commands require a private 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. When typing in a password at the password prompt, the password is currently echoed (displayed exactly as typed), so be careful not to type it in front of anyone.

COMMANDS

See also the Command and Option Notes.

Adding Data to the Keystore

-genkey {-alias alias} {-keyalg keyalg} {-keysize keysize} {-sigalg sigalg} [-dname dname] [-keypass keypass] {-validity valDays} {-storetype storetype} {-keystore keystore} [-storepass storepass] [-provider provider_class_name] {-v} {-Jjavaoption}

Generates a key pair (a public key and associated private key). Wraps the public key into an X.509 v1 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. See Supported Algorithms and Key Sizes.

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. Be careful with passwords - see Warning Regarding Passwords.

valDays tells the number of days for which the certificate should be considered valid.

-import {-alias alias} {-file cert_file} [-keypass keypass] {-noprompt} {-trustcacerts} {-storetype storetype} {-keystore keystore} [-storepass storepass] [-provider provider_class_name] {-v} {-Jjavaoption}

Reads the certificate or certificate chain (where the latter is supplied in a PKCS#7 formatted reply) from the file cert_file, and stores it in the keystore entry identified by alias. If no file is given, the certificate or PKCS#7 reply 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.

Importing a New Trusted Certificate

When importing a new trusted certificate, alias must not yet exist in the keystore. 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, the chain is first ordered (with the user certificate first and the self-signed root CA certificate last), before keytool attempts to match the root CA certificate provided in the reply with any of the trusted certificates in the keystore or the "cacerts" keystore file (if the -trustcacerts option was specified). If no match can be found, the information of the root CA certificate 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 root CA itself. 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.

The new certificate chain of alias replaces the old certificate chain associated with this entry. 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. Be careful with passwords - see Warning Regarding Passwords.

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 several root CA certificates with the following aliases and X.500 owner distinguished names:

  • Alias: thawtepersonalfreemailca
    Owner DN: EmailAddress=personal-freemail@thawte.com,
    CN=Thawte Personal Freemail CA,
    OU=Certification Services Division,
    O=Thawte Consulting, L=Cape Town, ST=Western Cape, C=ZA

  • Alias: thawtepersonalbasicca
    Owner DN: EmailAddress=personal-basic@thawte.com,
    CN=Thawte Personal Basic CA,
    OU=Certification Services Division,
    O=Thawte Consulting, L=Cape Town, ST=Western Cape, C=ZA

  • Alias: thawtepersonalpremiumca
    Owner DN: EmailAddress=personal-premium@thawte.com,
    CN=Thawte Personal Premium CA,
    OU=Certification Services Division,
    O=Thawte Consulting, L=Cape Town, ST=Western Cape, C=ZA

  • Alias: thawteserverca
    Owner DN: 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

  • Alias: thawtepremiumserverca
    Owner DN: EmailAddress=premium-server@thawte.com,
    CN=Thawte Premium Server CA,
    OU=Certification Services Division,
    O=Thawte Consulting cc, L=Cape Town, ST=Western Cape, C=ZA

  • Alias: verisignclass1ca
    Owner DN: OU=Class 1 Public Primary Certification Authority,
    O="VeriSign, Inc.", C=US

  • Alias: verisignclass2ca
    Owner DN: OU=Class 2 Public Primary Certification Authority,
    O="VeriSign, Inc.", C=US

  • Alias: verisignclass3ca
    Owner DN: OU=Class 3 Public Primary Certification Authority,
    O="VeriSign, Inc.", C=US

  • Alias: verisignclass4ca
    Owner DN: OU=Class 4 Public Primary Certification Authority,
    O="VeriSign, Inc.", C=US

  • Alias: verisignserverca
    Owner DN: OU=Secure Server Certification Authority,
    O="RSA Data Security, Inc.", C=US

  • Alias: baltimorecodesigningca
    Owner DN: CN=Baltimore CyberTrust Code Signing Root,
    OU=CyberTrust, O=Baltimore, C=IE

  • Alias: gtecybertrustglobalca
    Owner DN: CN=GTE CyberTrust Global Root,
    OU="GTE CyberTrust Solutions, Inc.", O=GTE Corporation, C=US

  • Alias: baltimorecybertrustca
    Owner DN: CN=Baltimore CyberTrust Root,
    OU=CyberTrust, O=Baltimore, C=IE

  • Alias: gtecybertrustca
    Owner DN: CN=GTE CyberTrust Root,
    O=GTE Corporation, C=US

  • Alias: gtecybertrust5ca
    Owner DN: CN=GTE CyberTrust Root 5,
    OU="GTE CyberTrust Solutions, Inc.", O=GTE Corporation, C=US

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.

-selfcert {-alias alias} {-sigalg sigalg} {-dname dname} {-validity valDays} [-keypass keypass] {-storetype storetype} {-keystore keystore} [-storepass storepass] [-provider provider_class_name] {-v} {-Jjavaoption}

Generates an X.509 v1 self-signed certificate, using keystore information including the private key and public key associated with alias. If dname is supplied at the command line, it is used as the X.500 Distinguished Name for both the issuer and subject of the certificate. Otherwise, the X.500 Distinguished Name associated with alias (at the bottom of its existing certificate chain) is used.

The generated certificate is stored as a single-element certificate chain in the keystore entry identified by alias, where it replaces the existing certificate chain.

sigalg specifies the algorithm that should be used to sign the certificate. See Supported Algorithms and Key Sizes.

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. Be careful with passwords - see Warning Regarding Passwords.

valDays tells the number of days for which the certificate should be considered valid.

-identitydb {-file idb_file} {-storetype storetype} {-keystore keystore} [-storepass storepass] [-provider provider_class_name] {-v} {-Jjavaoption}

Reads the JDK 1.1.x-style identity database from the file idb_file, and adds its entries to the keystore. If no file is given, the identity database is read from stdin. If a keystore does not exist, it is created.

Only identity database entries ("identities") that were marked as trusted will be imported in the keystore. All other identities will be ignored. For each trusted identity, a keystore entry will be created. The identity's name is used as the "alias" for the keystore entry.

The private keys from trusted identities will all be encrypted under the same password, storepass. This is the same password that is used to protect the keystore's integrity. Users can later assign individual passwords to those private keys by using the "-keypasswd" keytool command option.

An identity in an identity database may hold more than one certificate, each certifying the same public key. But a keystore key entry for a private key has that private key and a single "certificate chain" (initially just a single certificate), where the first certificate in the chain contains the public key corresponding to the private key. When importing the information from an identity, only the first certificate of the identity is stored in the keystore. This is because an identity's name in an identity database is used as the alias for its corresponding keystore entry, and alias names are unique within a keystore,

Exporting Data

-certreq {-alias alias}
  {-sigalg sigalg} {-file certreq_file}
  [-keypass keypass]
  {-storetype storetype}
  {-keystore keystore} [-storepass storepass]
  [-provider provider_class_name]
  {-v} {-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 and X.500 Distinguished Name associated with alias are 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.

Be careful with passwords - see Warning Regarding Passwords.

sigalg specifies the algorithm that should be used to sign the CSR. See Supported Algorithms and Key Sizes.

The CSR is stored in the file certreq_file. If no file is given, the CSR is output to stdout.

Use the import command to import the response from the CA.

-export
  {-alias alias}
  {-file cert_file}
  {-storetype storetype}
  {-keystore keystore} [-storepass storepass]
  [-provider provider_class_name]
  {-rfc} {-v} {-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.

Displaying Data

-list {-alias alias} {-storetype storetype} {-keystore keystore} [-storepass storepass] [-provider provider_class_name] {-v | -rfc} {-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 MD5 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, and serial number. 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} {-v} {-Jjavaoption}

Reads the certificate from the file cert_file, and prints its contents in a human-readable format. If no file is given, the certificate is read from stdin.

The certificate may be either binary encoded or in printable encoding format, as defined by the Internet RFC 1421 standard.

Note: This option can be used independently of a keystore.

Managing the Keystore

-keyclone {-alias alias} [-dest dest_alias] [-keypass keypass] [-new new_keypass] {-storetype storetype} {-keystore keystore} [-storepass storepass] [-provider provider_class_name] {-v} {-Jjavaoption}

Creates a new keystore entry, which has the same private key and certificate chain as the original entry.

The original entry is identified by alias (which defaults to "mykey" if not provided). The new (destination) entry is identified by dest_alias. If no destination alias is supplied at the command line, the user is prompted for it.

If the private key password is different from the keystore password, then the entry will only be cloned if a valid keypass is supplied. This is the password used to protect the private key associated with alias. If no key password is supplied at the command line, and the private key password is different from the keystore password, the user is prompted for it. The private key in the cloned entry may be protected with a different password, if desired. If no -new option is supplied at the command line, the user is prompted for the new entry's password (and may choose to let it be the same as for the cloned entry's private key).

Be careful with passwords - see Warning Regarding Passwords.

This command can be used to establish multiple certificate chains corresponding to a given key pair, or for backup purposes.

-storepasswd [-new new_storepass] {-storetype storetype} {-keystore keystore} [-storepass storepass] [-provider provider_class_name] {-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.

Be careful with passwords - see Warning Regarding Passwords.

-keypasswd {-alias alias} [-keypass old_keypass] [-new new_keypass] {-storetype storetype} {-keystore keystore} [-storepass storepass] [-provider provider_class_name] {-v} {-Jjavaoption}

Changes the password under which the private key identified by alias is protected, from old_keypass to new_keypass.

If the -keypass option is not provided at the command line, and the private 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.

Be careful with passwords - see Warning Regarding Passwords.

-delete [-alias alias] {-storetype storetype} {-keystore keystore} [-storepass storepass] [-provider provider_class_name] {-v} {-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.

Getting Help

-help

Lists all the commands and their options.

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 -genkey -dname "cn=Mark Jones, ou=JavaSoft, o=Sun, c=US"
      -alias business -keypass kpi135 -keystore /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 "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 "JavaSoft", organization of "Sun" 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 -genkey
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 -genkey command without options specified, and that you responded to the prompts with values equal to those given in the first -genkey 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 import 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 five 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 -import 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 -import -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 -import -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 -export -alias mykey -file MJ.cer
Given that certificate, and the signed JAR file, a client can use the jarsigner tool to authenticate your signature.

Changing Your Distinguished Name but Keeping your Key Pair

Suppose your distinguished name changes, for example because you have changed departments or moved to a different city. If desired, you may still use the public/private key pair you've previously used, and yet update your distinguished name. For example, suppose your name is Susan Miller, and you created your initial key entry with the alias sMiller and the distinguished name
  "cn=Susan Miller, ou=Finance Department, o=BlueSoft, c=us"
Suppose you change from the Finance Department to the Accounting Department. You can still use the previously-generated public/private key pair and yet update your distinguished name by doing the following. First, copy (clone) your key entry:
    keytool -keyclone -alias sMiller -dest sMillerNew
(This prompts for the store password and for the initial and destination private key passwords, since they aren't provided at the command line.) Now you need to change the certificate chain associated with the copy, so that the first certificate in the chain uses your different distinguished name. Start by generating a self-signed certificate with the appropriate name:
    keytool -selfcert -alias sMillerNew
      -dname "cn=Susan Miller, ou=Accounting Department, o=BlueSoft, c=us"

Then generate a Certificate Signing Request based on the information in this new certificate:

    keytool -certreq -alias sMillerNew
When you get the CA certificate reply, import it:
    keytool -import -alias sMillerNew -file VSSMillerNew.cer
After importing the certificate reply, you may want to remove the initial key entry that used your old distinguished name:
    keytool -delete -alias sMiller

SEE ALSO

  • jar tool documentation

  • jarsigner tool documentation

  • the Security trail of the Java Tutorial for examples of the use of keytool

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software


Policy Tool - Policy File Creation and Management Tool

Policy Tool -

Policy File Creation and Management Tool

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 Change Keystore command in the Edit 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 Edit 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 Change Keystore command in the Edit 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 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 2 Platform

  • Default Policy Information and Policy File Syntax

  • keytool tool documentation

  • Security Architecture Specification

  • The Security trail of the Java Tutorial for examples of the use of the security tools including Policy Tool

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software


rmic - The Java RMI Compiler

rmic generates stubs, skeletons, ties 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 the compiled Java programming language classes that contain remote object implementations. A remote object is one that implements the interface java.rmi.Remote. The classes named in the rmic command must be 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_Skel.class and HelloImpl_Stub.class files in the hello subdirectory (named for the class's package).

A skeleton for a remote object is a JRMP protocol server-side entity that contains a method which 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 proxy for a remote object which is responsible for forwarding 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. JRMP protocol stubs are generated by default. Use the -iiop option to generate stubs for the IIOP protocol.

The stub implements only the remote interfaces, not any local interfaces that the remote object also implements. Because a JRMP stub implements exactly 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
Override 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 colons. Thus the general format for path is:
.:<your_path>
For example:
.:/usr/local/java/classes
-d directory
Specifies the destination root directory for the generated class hierarchy. You can use this option to specify a destination directory for the stub, tie, and skeleton files. For example, the command

Windows:

% rmic -d C:\java\classes foo.MyClass

Solaris:

% rmic -d /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 previous versions of rmic, if -d was not specified the package hierarchy was not created, and the output files were placed directly in the current directory.
-depend
Makes the compiler consider recompiling classes which are referenced from other classes. Normally, it only recompiles missing or out-of-date classes that are referred to from source code.

-extdirs path
Override location of installed extensions

-g
Enables generation of debugging tables. Debugging tables contain information about line numbers and local variables - information used by Java debugging tools. By default, only line numbers are 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.

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 stubs and skeletons and writes them to the same directory as the .class file.

-nowarn
Turns off warnings. If used the compiler does not print out any warnings.

-vcompat
(default) Creates stubs and skeletons compatible with both 1.1 and 1.2 JRMP stub protocol versions.

-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
Create stubs and skeletons for 1.1 JRMP stub protocol version.

-v1.2
Create stubs for the 1.2 JRMP stub protocol version only.

ENVIRONMENT VARIABLES

CLASSPATH
Used to provide the system a path to user-defined classes. Directories are separated by colons. For example,
.:/usr/local/java/classes

SEE ALSO

java, javac, CLASSPATH

Copyright © 2003 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software


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
    "/files/apps/java/jdk1.2.2/solaris/bin/java";

    permission com.sun.rmi.rmid.ExecPermission
    "/files/apps/java/jdk1.2.2/solaris/bin/java_g";

    permission com.sun.rmi.rmid.ExecPermission
    "/files/apps/rmidcmds/*";

    permission com.sun.rmi.rmid.ExecOptionPermission
    "-Djava.security.policy=/files/policies/group.policy";

    permission com.sun.rmi.rmid.ExecOptionPermission
    "-Djava.security.debug=*";

    permission com.sun.rmi.rmid.ExecOptionPermission
    "-Dsun.rmi.*";
};
    The first two permissions granted allow rmid to execute the 1.2.2 version of the java and java_g commands, specified by their explicit path names. 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 third permission allows rmid to execute any command in the directory /files/apps/rmidcmds.

    The fourth permission granted, an ExecOptionPermission, allows rmid to launch an activation group that defines the security policy file to be /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. For example:
        .:/usr/local/java/classes

    SEE ALSO

    rmic, CLASSPATH, java

    Copyright © 2003 Sun Microsystems, Inc. All Rights Reserved.

             Sun
    Java Software


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:

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, java.rmi.registry.LocateRegistry and java.rmi.Naming

Copyright © 2003 Sun Microsystems, Inc. All Rights Reserved.

 Sun
Java Software